Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Memory writes: source authority, valid time, stale jobs and revocation

Admit scoped reusable facts, order corrections by source events and revisions, then prove old asynchronous jobs cannot revive a revoked preference.

Learning objectives: Implement and test memory admission, effective intervals, conditional correction and revocation fences without treating extraction completion time as fact authority.

Content checked: 2026-10-11 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Implementation · Build it. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Developers comfortable with Python dictionaries and local SQL transactions.

Admission
A policy decision about attributable, purposeful and reusable data before durable storage.
Source sequence
A trusted event-log order for statements and corrections; the extractor cannot invent it.
Valid time
The interval in which a fact applies to the business question, distinct from ingestion time.
Revision fence
An expected generation checked before accepting a background write.
Revocation tombstone
Minimal non-payload control state that blocks stale sources and reads after revocation.

How does the mechanism work?

Memory write and read fences across source, valid time and revocation
  1. 1
    Candidate

    Attribute subject, assertion, purpose and source event.

  2. 2
    Trusted control

    Compare source sequence, expected revision and revocation generation.

  3. 3
    Ledger

    Commit payload/provenance with valid interval and advance revision.

  4. 4
    Correction/revocation

    End the prior valid interval or delete payload and fence old sources.

  5. 5
    Protected read

    Require current consent/control, matching purpose and applicable valid time.

stored_at measures ingestion; it does not grant source precedence. Distributed purge and old-backup reconciliation are design obligations, not tested local results.

Step-by-step explanation
  1. Attribute and admit

    Check subject, source kind, scope, purpose and explicit reuse policy.

  2. Compare before write

    Require current revision and a newer authoritative source event.

  3. Apply valid interval

    End the previous fact at the new fact's effective time, not job completion.

  4. Revoke and fence

    Delete local payload, advance source/revision control and require fresh explicit reconsent.

  5. Read within purpose

    Check current revocation and valid time before reusing a fact.

Implementation · Build it

Write an admission and temporal correction ledger

Objectives of this level: Run scoped candidate admission and compare-and-write corrections with explicit valid intervals.

Visual guide · Admission before persistence

Admission before persistence

The lab admits explicit self-attributed meal-planning preferences only. This is a bounded policy, not a universal rule for retaining third-party facts. Select the figure to open it at full size.

Download the core experiment bundle on a computer and extract the agent-core-deep-dive-v1 folder. Install Python 3.9+ with its standard library, open a terminal in that folder and run:

python3 -B memory_write_deep_dive.py > memory_write_deep_dive.results.json
python3 -B -m unittest discover -v

Open the saved JSON and compare its statuses/counts with the worked example in this body. The implementation and debugging snippets run from the same extracted folder; the bundle includes every imported module. Save the body’s Python snippet as a .py file in that folder and run python3 -B your_file.py; its printed output is stated beside it. The source can also be downloaded at https://ai.lwkjob.com/lab/deep-dive/memory_write_deep_dive.py. The engineering route continues the same complete after-sales Agent project; full stages are in that package's README.

Run python3 -B memory_write_deep_dive.py. Candidate carries tenant, subject, slot, value, source_id/source_seq, base_revision, assertion kind, reuse purpose, valid interval, stored_at and reconsent. The extractor supplies candidate meaning; a trusted event log and authenticated context supply identity/order. Do not let model JSON self-assign source_seq or reconsent authority in a real integration.

The control table is keyed by tenant/subject/slot and stores revision, last_seq and revoked. The facts table stores payload with provenance and effective interval. In BEGIN IMMEDIATE, admit checks expected revision, newer source sequence and revocation state. An accepted correction increments revision and ends the previous interval at the new valid_from. It routes an earlier-than-current effective start to review rather than guessing how to rewrite historical intervals.

The demo stores vegetarian at event-10/revision1, then vegan at event-20/revision2 effective from 200. Reading at 150 still returns vegetarian; reading at 250 returns vegan. The event-11 job finishing at stored_at=900 is rejected as stale_revision. Even rebasing that old source to the current revision fails stale_source_event.

Read checks the purpose, current revocation control and [valid_from,valid_to) interval. It returns source and interval metadata beside the value so reuse can be audited. This is a local ordered-fact ledger, not an extraction-accuracy benchmark or a full bitemporal database. A production API must authenticate read/write identities and retain appropriate purpose boundaries.

A complete worked run

from memory_write_deep_dive import Memory, Candidate
m = Memory()
assert m.admit(Candidate())['revision'] == 1
new = Candidate(value='vegan', source_id='event-20', source_seq=20, base_revision=1, valid_from=200, stored_at=150)
assert m.admit(new)['revision'] == 2
assert m.read(199)['value'] == 'vegetarian'
assert m.read(200)['value'] == 'vegan'
print(m.read(199)['value'], m.read(200)['value'])
m.close()

Actual output: vegetarian vegan. stored_at=150 does not make a preference valid before 200.

State lifetime and trusted flags

The complete script prints vegetarian vegan. Memory() without a path creates a fresh in-memory ledger and m.close() ends that instance. Keep m alive for the task's additional queries: read199 is vegetarian, read200 is vegan and read1000 is None because both intervals end exclusively at1000. Running the module first does not create a durable state for another new Memory instance.

Capture event-11 before committing event-20. Reusing its original base_revision1 returns stale_revision; using base_revision2 with the same source11 returns stale_source_event. Copying source11 into a new event ID to bypass that check would invent a new assertion.

Both reusable and reconsent must be real Python Booleans. reconsent='False' is a nonempty string, not false; the module returns candidate_shape before admitting it. A real system obtains reconsent authority from a trusted newer event, never from a model-created Boolean alone.

Independently implement make_job_candidate(trusted_event) in your own file, preserving tenant/subject, source_id/source_seq, captured base revision, purpose and valid interval. Use fixed trusted fixture events here; do not claim login or extraction validation. Test that a later completion changes stored_at only and cannot promote source11 to source21 or set reconsent. Pass the captured candidate to the ledger and retain its rejection.

Run experiments and observe counterexamples

Authored source events, identities and integer times; actual local admission/validity/CAS/revocation checks. No extraction model, vector/cache purge, old-backup restore or physical erasure.

Python 3.10+ · Runs by default using only the standard library · Runs on your computer

  1. Compare quote rejection, initial fact and future correction.
  2. Reproduce old async completion and rebased old source.
  3. Revoke and test read/write fences, then fresh explicit reconsent.
Download the complete application experiment package (including data and dependent scripts) ↓
python3 -B memory_write_deep_dive.py
View the entry-point script
"""Memory admission, valid time and revocation in a local SQLite ledger.

Source sequences and revisions come from a trusted event log, not the model.
Times are integer teaching fixtures. No extraction model or backup service.
"""
import json
import sqlite3
from dataclasses import dataclass


@dataclass(frozen=True)
class Candidate:
    tenant: str = 'tenant-a'
    subject: str = 'user-a'
    slot: str = 'diet'
    value: str = 'vegetarian'
    source_id: str = 'event-10'
    source_seq: int = 10
    base_revision: int = 0
    subject_kind: str = 'self'
    assertion: str = 'explicit'
    reusable: bool = True
    purpose: str = 'meal-planning'
    valid_from: int = 100
    valid_to: int = 1000
    stored_at: int = 110
    reconsent: bool = False


class Memory:
    def __init__(self, path=':memory:'):
        self.db = sqlite3.connect(path, timeout=5, isolation_level=None)
        self.db.executescript('''
          CREATE TABLE IF NOT EXISTS control(tenant TEXT, subject TEXT, slot TEXT, revision INTEGER, last_seq INTEGER, revoked INTEGER,
            PRIMARY KEY(tenant,subject,slot));
          CREATE TABLE IF NOT EXISTS facts(tenant TEXT, subject TEXT, slot TEXT, value TEXT, source_id TEXT, source_seq INTEGER,
            revision INTEGER, purpose TEXT, valid_from INTEGER, valid_to INTEGER, stored_at INTEGER);
        ''')

    def close(self):
        self.db.close()

    def control(self, tenant='tenant-a', subject='user-a', slot='diet'):
        row = self.db.execute('SELECT revision,last_seq,revoked FROM control WHERE tenant=? AND subject=? AND slot=?',
                              (tenant, subject, slot)).fetchone()
        return row if row else (0, -1, 0)

    def admit(self, candidate, authenticated_tenant='tenant-a', authenticated_subject='user-a'):
        c = candidate
        if (c.tenant, c.subject) != (authenticated_tenant, authenticated_subject):
            return {'status': 'rejected', 'reason': 'scope'}
        if type(c.reusable) is not bool or type(c.reconsent) is not bool:
            return {'status': 'rejected', 'reason': 'candidate_shape'}
        if c.subject_kind != 'self' or c.assertion != 'explicit' or not c.reusable or c.purpose != 'meal-planning':
            return {'status': 'rejected', 'reason': 'admission_policy'}
        if any(type(v) is not int for v in (c.source_seq, c.base_revision, c.valid_from, c.valid_to, c.stored_at)) or c.valid_from >= c.valid_to:
            return {'status': 'rejected', 'reason': 'validity_interval'}
        if any(type(v) is not str or not v for v in (c.slot, c.value, c.source_id)):
            return {'status': 'rejected', 'reason': 'candidate_shape'}
        with self.db:
            self.db.execute('BEGIN IMMEDIATE')
            revision, last_seq, revoked = self.control(c.tenant, c.subject, c.slot)
            if c.base_revision != revision:
                return {'status': 'rejected', 'reason': 'stale_revision', 'current_revision': revision}
            if c.source_seq <= last_seq:
                return {'status': 'rejected', 'reason': 'stale_source_event'}
            if revoked and not c.reconsent:
                return {'status': 'rejected', 'reason': 'revoked_requires_reconsent'}
            latest = self.db.execute('SELECT MAX(valid_from) FROM facts WHERE tenant=? AND subject=? AND slot=?',
                                     (c.tenant, c.subject, c.slot)).fetchone()[0]
            if latest is not None and c.valid_from < latest:
                return {'status': 'rejected', 'reason': 'retroactive_requires_review'}
            next_revision = revision + 1
            # A future correction ends the old interval at its effective time,
            # not when the background extraction job happens to finish.
            self.db.execute('UPDATE facts SET valid_to=MIN(valid_to,?) WHERE tenant=? AND subject=? AND slot=? AND valid_to>?',
                            (c.valid_from, c.tenant, c.subject, c.slot, c.valid_from))
            self.db.execute('INSERT INTO facts VALUES(?,?,?,?,?,?,?,?,?,?,?)',
                            (c.tenant, c.subject, c.slot, c.value, c.source_id, c.source_seq, next_revision, c.purpose, c.valid_from, c.valid_to, c.stored_at))
            self.db.execute('INSERT OR REPLACE INTO control VALUES(?,?,?,?,?,0)',
                            (c.tenant, c.subject, c.slot, next_revision, c.source_seq))
            return {'status': 'stored', 'revision': next_revision, 'source_id': c.source_id}

    def revoke(self, source_seq, tenant='tenant-a', subject='user-a', slot='diet'):
        with self.db:
            self.db.execute('BEGIN IMMEDIATE')
            revision, last_seq, _ = self.control(tenant, subject, slot)
            if type(source_seq) is not int or source_seq <= last_seq:
                raise ValueError('stale_revocation_event')
            self.db.execute('DELETE FROM facts WHERE tenant=? AND subject=? AND slot=?', (tenant, subject, slot))
            self.db.execute('INSERT OR REPLACE INTO control VALUES(?,?,?,?,?,1)', (tenant, subject, slot, revision + 1, source_seq))
            return {'status': 'revoked', 'revision': revision + 1, 'payload_rows': 0}

    def read(self, at, tenant='tenant-a', subject='user-a', slot='diet', purpose='meal-planning'):
        if self.control(tenant, subject, slot)[2]:
            return None
        row = self.db.execute('''SELECT value,source_id,revision,valid_from,valid_to,stored_at FROM facts
          WHERE tenant=? AND subject=? AND slot=? AND purpose=? AND valid_from<=? AND ?<valid_to
          ORDER BY revision DESC LIMIT 1''', (tenant, subject, slot, purpose, at, at)).fetchone()
        return dict(zip(('value','source_id','revision','valid_from','valid_to','stored_at'), row)) if row else None


def demo():
    from dataclasses import replace
    memory = Memory()
    quote = memory.admit(Candidate(subject_kind='third_party_quote'))
    initial = memory.admit(Candidate())
    old_async = Candidate(value='vegetarian', source_id='event-11', source_seq=11, base_revision=1, stored_at=900)
    correction = memory.admit(Candidate(value='vegan', source_id='event-20', source_seq=20, base_revision=1,
                                        valid_from=200, stored_at=210))
    stale = memory.admit(old_async)
    before = memory.read(150)
    after = memory.read(250)
    revoke = memory.revoke(30)
    delayed_after_revoke = memory.admit(replace(old_async, base_revision=3))
    fresh_without_consent = memory.admit(Candidate(value='vegan', source_id='event-40', source_seq=40, base_revision=3,
                                                   valid_from=400, stored_at=410))
    revoked_read = memory.read(250)
    reconsent = memory.admit(Candidate(value='vegetarian', source_id='event-41', source_seq=41, base_revision=3,
                                        valid_from=400, stored_at=420, reconsent=True))
    result = {'origin': 'authored_source_events_local_sqlite', 'quote': quote, 'initial': initial, 'correction': correction,
              'old_async_completion': stale, 'read_at_150': before, 'read_at_250': after, 'revocation': revoke,
              'old_source_rebased_after_revocation': delayed_after_revoke, 'fresh_without_reconsent': fresh_without_consent,
              'read_after_revocation': revoked_read, 'explicit_reconsent': reconsent, 'read_at_450': memory.read(450),
              'boundary': 'No extraction accuracy, vector-index purge, cache purge or physical backup erasure is tested.'}
    memory.close()
    return result


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, sort_keys=True))

Expected output when running locally

{
  "boundary": "No extraction accuracy, vector-index purge, cache purge or physical backup erasure is tested.",
  "correction": {
    "revision": 2,
    "source_id": "event-20",
    "status": "stored"
  },
  "explicit_reconsent": {
    "revision": 4,
    "source_id": "event-41",
    "status": "stored"
  },
  "fresh_without_reconsent": {
    "reason": "revoked_requires_reconsent",
    "status": "rejected"
  },
  "initial": {
    "revision": 1,
    "source_id": "event-10",
    "status": "stored"
  },
  "old_async_completion": {
    "current_revision": 2,
    "reason": "stale_revision",
    "status": "rejected"
  },
  "old_source_rebased_after_revocation": {
    "reason": "stale_source_event",
    "status": "rejected"
  },
  "origin": "authored_source_events_local_sqlite",
  "quote": {
    "reason": "admission_policy",
    "status": "rejected"
  },
  "read_after_revocation": null,
  "read_at_150": {
    "revision": 1,
    "source_id": "event-10",
    "stored_at": 110,
    "valid_from": 100,
    "valid_to": 200,
    "value": "vegetarian"
  },
  "read_at_250": {
    "revision": 2,
    "source_id": "event-20",
    "stored_at": 210,
    "valid_from": 200,
    "valid_to": 1000,
    "value": "vegan"
  },
  "read_at_450": {
    "revision": 4,
    "source_id": "event-41",
    "stored_at": 420,
    "valid_from": 400,
    "valid_to": 1000,
    "value": "vegetarian"
  },
  "revocation": {
    "payload_rows": 0,
    "revision": 3,
    "status": "revoked"
  }
}
  • event-11 cannot replace event-20 even if stored_at=900.
  • Time150 returns vegetarian and time250 returns vegan before revocation.
  • Revocation removes local payload and rejects old events; fresh explicit reconsent creates revision4.
View the running environment, output and verification records →

code example

Retroactive correction needs another policy

After a fact starts at200, a later trusted correction asks to start at150. The bounded module returns retroactive_requires_review rather than reconstructing every historical interval. Source order is necessary, but it does not solve arbitrary temporal reconciliation.

Acceptance task for this level

Keep one Memory instance for source10→20, query199/200/1000 and submit source11 with original/current revision. Independently implement make_job_candidate from the fixed trusted fixture events; prove completion changes no source identity or consent. Test string reconsent rejection.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Why is checking only base_revision insufficient when a failed background writer rereads current state and retries?

Further explanations and practice

When encountering unfamiliar principles, first read the implementation, continuous questioning and migration cases, and then independently explain the premise and boundaries. Answers and notes are saved to the original account record.

All linked explanations and exercises (1 )

Sources and verification scope

The principles are based on public information; the numbers, cases and tasks are the teaching design of this website. Offline experiments verify the range noted on this page, and the learning effect still needs to be judged through independent tasks and feedback.