Review the prerequisites
Suitable for: Readers who can follow a request and its resulting state.
- 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?
- 1Candidate
Attribute subject, assertion, purpose and source event.
- 2Trusted control
Compare source sequence, expected revision and revocation generation.
- 3Ledger
Commit payload/provenance with valid interval and advance revision.
- 4Correction/revocation
End the prior valid interval or delete payload and fence old sources.
- 5Protected 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
- Attribute and admit
Check subject, source kind, scope, purpose and explicit reuse policy.
- Compare before write
Require current revision and a newer authoritative source event.
- Apply valid interval
End the previous fact at the new fact's effective time, not job completion.
- Revoke and fence
Delete local payload, advance source/revision control and require fresh explicit reconsent.
- Read within purpose
Check current revocation and valid time before reusing a fact.
Foundation · Understand the concepts
Why saving a sentence changes its authority and lifespan
Objectives of this level: Classify attributable reusable facts and distinguish source, effective time and storage time.
Visual guide · 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.
'My colleague is vegetarian' is not the user's diet. 'Write this one email more firmly' is a temporary instruction, not a reusable tone preference. An extractor that writes either sentence into the user's persistent profile changes the subject or intended lifespan and contaminates future decisions.
Admission must ask who asserted the fact, about whom, under what purpose, with what evidence and retention expectation. In this bounded lab only explicit self-attributed meal-planning preferences are reusable. Third-party quotations, model inferences and one-task instructions fail admission. Other applications may legitimately retain verified third-party facts, but need an appropriate subject/scope/source policy; this toy policy is not universal.
Distinguish three clocks. source_seq orders authoritative events. valid_from/valid_to say when a preference applies. stored_at says when the extraction/storage job completed. A background job finishing at 900 with an event from sequence 11 cannot outrank a correction from sequence 20 simply because its storage timestamp is later.
Correction and revocation require different behavior. A correction may preserve a historical interval for an as-of question. Revocation blocks reuse and removes local payload in this lab, including historical reads. Minimal control state is retained to reject delayed writes. Fresh explicit reconsent can create a new fact; merely replaying an old conversation cannot. Background versus hot-path memory motivates the timing problem, while the revision/source protocol here is an application design.
Five fixed inputs with separate clocks
Use tenant-a/user-a and purpose meal-planning for durable preferences. Times are authored integers, not production clock measurements. A source sequence is trusted statement order; valid time selects applicability; stored_at is job completion.
- event-10/source_seq10: “I am vegetarian; use it for meal planning.” Explicit self statement, reusable=True, interval[100,1000), stored_at110, base_revision0. Admit as revision1.
- event-12/source_seq12: “My colleague is vegetarian.” Third-party quotation about the colleague, not user-a; reject under this self-preference policy regardless of similar words.
- event-13/source_seq13: “Make only this email firmer.” A current-email instruction, reusable=False and purpose current-email. Keep temporary; do not write a meal preference.
- event-20/source_seq20: “From time200 I am vegan for meal planning.” Explicit reusable self correction, interval[200,1000), stored_at150, base_revision1. Admit as revision2; at199 the previous preference still applies.
- event-11/source_seq11: a vegetarian self statement captured from revision1, stored_at900 after case4 committed. Keep its original source and base_revision1. Reject stale_revision; rebasing only the revision to2 still rejects stale_source_event.
The quote/email cases do not advance the accepted diet slot. Source11 finishes later but remains earlier than source20. A revocation is a separate event30 that blocks current and historical reuse, not a correction merely ending an effective interval.
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
- Compare quote rejection, initial fact and future correction.
- Reproduce old async completion and rebased old source.
- Revoke and test read/write fences, then fresh explicit reconsent.
python3 -B memory_write_deep_dive.pyView 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.
code example
A verified status is not a permanent preference
An order-status tool's receipt may be authoritative for that order at its observation time. Retain object scope/version and reread for a mutable action precondition. Storing the snapshot as a permanent user preference changes its subject and lifespan.
Acceptance task for this level
Classify the five numbered fixed inputs in this body by subject, assertion, purpose, reusable lifespan, source sequence, effective interval and storage time. Explain why source11 stays stale even after completion900 and how revoke30 differs from a correction.
Reading this browser’s record…
Hide the answer and check your understanding
A background job completed today from a statement made before yesterday's correction. Which timestamp decides whether it may replace the current fact?
Expand reference derivation
Neither completion time alone nor a model confidence score. Compare the trusted source event sequence and expected revision against current control state; apply the fact's valid interval separately. An old source remains old even if it is imported today.
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.