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: Design · Explain the trade-offs. 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: Engineers choosing guarantees across services, time and failure boundaries.

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.

Design · Explain the trade-offs

Preserve revocation across replicas, caches and historical imports

Objectives of this level: Design admission/correction/revocation when source order and read replicas no longer share one transaction.

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.

Change the architecture to multiple regional writers, a vector index, cached profiles and an old backup import. Last stored_at ordering fails because clock order says when a replica wrote, not which assertion applies. A model-assigned confidence or timestamp cannot establish authority either.

Choose a conflict policy per slot: an authoritative event sequence, an explicit source precedence, or a conflict set requiring review. Single sequencing gives clear correction semantics but adds coordination latency and availability dependence. A conflict set preserves concurrent evidence but increases read/review complexity. Valid time remains separate; retroactive imports may require interval reconciliation instead of replacing the current preference.

Keep revocation generations in a current control plane that restored snapshots cannot roll back. Purge payload and derived indexes/caches by event/generation, record acknowledgments, and fence reads while propagation is incomplete according to the chosen policy. If every replica must observe revocation before answering, availability may drop during partitions. If bounded propagation is accepted, state the maximum stale-read window and avoid claiming immediate revocation. Minimal tombstones need their own justified retention and access policy; they should not retain the revoked sensitive payload.

For backup restore, load into a quarantined namespace, reconcile each subject/slot against current revocation and source authority, then rebuild derived material. Re-extracting an old conversation is an import of an old source, not fresh consent. Fresh reconsent must have trusted subject attribution, purpose, a newer event and its own effective interval.

Evaluate memory by task benefit and contamination, not just hit rate: scope violations, stale-source accepts, unjustified inference writes, revocation lag and purpose misuse deserve separate slices. Read memory conflict/time and revocation for the adjacent mechanisms; those stable IDs and existing experiments are retained.

A concrete regional import decision

Assume region A has current control revision3/source30/revoked=True, while region B restores a snapshot from revision1/source10 containing vegetarian. A vector cache also still contains that old payload. Restoring the old control table together with the payload would roll back the revocation fence.

Load the snapshot into quarantine, compare each subject/slot with current independent revocation authority, and exclude the revoked fact before serving or rebuilding vectors. Record acknowledgments from the profile store, vector index, cache and exports. If B cannot reach current control, choose either no protected answer until reconciliation or a declared bounded stale-read policy; document the availability/privacy tradeoff. A new explicit event41 may create a fresh fact, but importing event10 today cannot. This is a design proposal; the local module tests neither regional restore nor derived-service purge.

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

A cache acknowledgment is not the whole purge

Deleting a profile and receiving its acknowledgment does not show a vector index/export has removed the same generation. Track each derived store, fence its reads until the selected propagation contract is met, and report unacknowledged stores explicitly.

Acceptance task for this level

Design a regional memory system with an asynchronous extractor, a vector cache and old-backup import. Compare single sequencing with conflict-set review, define effective-time reconciliation and specify revocation/reconsent gates and propagation evidence.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

Can restoring the whole database, including its old tombstone table, guarantee revoked memory stays hidden?

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.