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: Debugging · Diagnose failures. 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 who can compare a request, a trace and an authoritative result.

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.

Debugging · Diagnose failures

Block stale async writes and revoked-data resurrection

Objectives of this level: Reproduce delayed completion and revocation races, then prove the local read/write fences after reopening.

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.

The failure schedule starts an event-11 extraction from revision1, commits event-20's correction as revision2, then completes the old job at stored_at=900. A last-write-by-storage-time strategy would select the stale value. The implemented ledger returns stale_revision and preserves vegan at time250. If the worker silently rebases, stale_source_event still rejects event-11.

Next revoke with source_seq=30. The ledger deletes fact payload rows and advances control to revision3, last_seq30, revoked1. Reads return None. The old source rebased to revision3 remains rejected. A new event40 without explicit reconsent also fails. A fresh explicit reconsent at event41/revision3 creates revision4 with its own effective interval.

Diagnose by recording source_id/seq, base/current revision, valid interval, stored_at and revocation generation. The root cause of resurrection is treating stale extraction or restored payload as current authority. Repair both conditional writes and protected reads; merely deleting the current value leaves a delayed writer free to recreate it.

Run MemoryTests. The reopen test closes and opens the same local database after revocation and verifies the tombstone persists. This is not a restore of an old backup. A genuinely old snapshot can also contain old control state, so production restore must consult current revocation authority before exposing its payload. The lab does not purge a vector index, cache, derived export or backup service; those require separate propagation evidence.

A complete worked run

Visual guide · A late job cannot resurrect a fact

A late job cannot resurrect a fact

stored_at does not order assertions. The local ledger rejects stale revisions and source events; revocation retains control state without the fact payload. Select the figure to open it at full size.

from dataclasses import replace
from memory_write_deep_dive import Memory, Candidate
m = Memory()
m.admit(Candidate())
old = Candidate(source_id='event-11', source_seq=11, base_revision=1, stored_at=900)
m.admit(Candidate(value='vegan', source_id='event-20', source_seq=20, base_revision=1, valid_from=200))
assert m.admit(old)['reason'] == 'stale_revision'
assert m.admit(replace(old, base_revision=2))['reason'] == 'stale_source_event'
assert m.read(250)['value'] == 'vegan'
m.revoke(30)
assert m.read(250) is None
assert m.admit(replace(old, base_revision=3, reconsent=True))['reason'] == 'stale_source_event'
print(m.control(), m.db.execute('SELECT COUNT(*) FROM facts').fetchone()[0])
m.close()

Actual output: (3, 30, 1) 0. Local payload deletion and current control are both observable; physical backup erasure is outside this result.

Exact late-job repair schedule

The code above creates one fresh m: source10/revision1, captured source11, correction20/revision2, then old completion900. It proves stale revision, stale source after rebasing, a vegan read at250, and local deletion/control after revoke30. Actual output is(3,30,1) 0. Each fault comparison uses the original source identity; the printed source/control facts are more decisive than an extractor confidence score.

For a source repair exercise copy memory_write_deep_dive.py to memory_write_learner.py. Disable the source-sequence guard only in that copy. For this isolating variation, event11 also proposed vegetarian effective from200; its old captured source is unchanged when the worker rebases to revision2. Submit Candidate(value='vegetarian', source_id='event-11', source_seq=11, base_revision=2, valid_from=200, stored_at=900) after source20. The equal effective start keeps the separate retroactive guard from masking the missing source-order check. It can now wrongly write over vegan; restore the source guard and repeat the same fresh source10→20 schedule/input to get stale_source_event and unchanged vegan. Separately verify event40 without consent remains rejected after revoke30 and reconsent='False' returns candidate_shape. Reference MemoryTests run against the completed reference, not your renamed copy.

Fresh event41 with base_revision3, explicit reconsent=True and a new interval may create revision4. That is new consent under the fixture policy, not a replay of the deleted event11. Local reopen retains current control; old-backup restoration remains a separate design task.

For the injected-fault script import from the learner copy explicitly: from memory_write_learner import Memory, Candidate. The worked reference script above imports the original module and remains unchanged. Use a fresh instance for both before/after runs so an earlier effect cannot contaminate the comparison.

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

Reconsent representation cannot create authority

Use a fresh post-revocation source with reconsent='False'. It must fail candidate_shape, not be accepted because Python treats a nonempty string as truthy. A real True still requires the fixture's current revision/newer source; production requires trusted consent evidence.

Acceptance task for this level

Record source10/20/11/revoke30 with revisions, reads and payload count. In memory_write_learner.py inject and repair the missing source-order guard and retain source/before-after evidence. Test fresh-without-consent, string flag and trusted source41 separately; run reference MemoryTests including reopen.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Deleting the fact row returned success, but a background job later recreates it. Which missing state explains this?

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.