AI Hero Club

Context Engineering · Lesson 4

Marked Complete by You0 / 8

Saved in this browser only. Marking a lesson complete does not mean the project has passed verification.

Lesson Outline 8 subsections
Course Contents 8 lessons
Full course plan.
Context Engineering / Learning Plan ↗

LESSON 04 / 8Suggested study 140 minutes

Versioned Memory: Activation, Revocation and Replay

A notice is published, takes effect and is later revoked. Which version should a query about a historical date see?

3 Questions for This Lesson
  • Delineate determination of state uniqueness for prefixing events
  • Distinguishing between the order of changes and the operational validity date
  • Borders between certification services, summary chain and source authentication
Course Project ZIP ↓

Memory Requires More Than Keeping a Chat Log

This chapter converts the conditions of Chapter III “Same valid version” into a program. Readers need knowledge of dictionaries and functions; SQLite services are introduced as an external repository capacity, and the mechanisms for atomic submission and the scope of use of this project are specified below. The objective is to restore the only current state from a list of information and to search for two different questions: what is known when dealing with previous events and what is available on a given business date.

The event is a command record for changing the state. The status is a dictionary for all accepted events. The lesson is in four categories: import documents, cancel documents, write approved memories, and revoke memories. Import saves doc_id, integer number version, tettle, original, SHA, and optional active areas. Memory saves key, value, shop, version and approved. Scope is an accessable range identifier that is compared locally with precise string; It isolates two memories, but it is not a login certification nor does it prove that the caller really has a right to be included in the scope.

Initial Status S0S_0 Dovements and memories are empty, No. ii The event is... eie_i, Conformity function ff It is a defined state transfer. It reproduces the old state, verifies the event and then creates a new state; illegal input to the Contractor does not allow half of the dictionary to rewrite errors. For sequenced event string, an article-by-article application is unique. This “Only” comes from function determination and sequence fixed, not natural consensus with the client; this project only deals with single process string writing.

Si+1=f(Si,ei),Sn=f(⋯f(f(S0,e0),e1)⋯ ,en−1)S_{i+1}=f(S_i,e_i),\qquad S_n=f(\cdots f(f(S_0,e_0),e_1)\cdots,e_{n-1})
i From 0, n is the number of accepted events; replay(as_of=n) returns the prefix.

The Roles of Versions, Revocation, and Effective Dates

The same doc_id new version of version must be more stringent than the maximum value already available. When a new version is imported, replace all the old active versions of the document with the original version with the new version. Undoing the specified version as revoked; does not delete the original text or automatically restore the old version of supersed to active. This rule avoids the new rules from being rendered silent back to older rules. The restoration should be imported through a new and visible version, giving new audit events, rather than picking from the memory an old text that still appears to be in place.

A half-open period is used for the effective date of the operation: contains effective_from, does not include effective_until, and omits the endpoint to take the agreed earliest and latest dates. The date view is copied after playback has been completed and only the original active document is derived from not_offective or expired. The other status remains unchanged. The validity period is not an alternative to revocation: the cancelled document is not available even if the date falls within the zone and the new version, which has not yet entered into force, does not allow the old version to come back by default.

usable(d,t)=[status(d)=active]∧[ad≤t<bd]\mathrm{usable}(d,t)=[\mathrm{status}(d)=\mathrm{active}]\land[a_d\leq t<b_d]
t is the date of the query business; a_d, b_d are the entry into force and expiry endpoints respectively. The square brackets represent the real, not the probability.

Worked Example 1: One Question at Three Historical Points

The first six events on the list include five pieces of information, including the first version, the first version of the list, and the first version of the capeira. replay(6) returns Tuesday 16: 00, the site A classroom, the paper loan registration and the memory of “Let's get to the conclusion.”. Three more events were handled, the second version of Schedule was replaced by Thursday 16: 30, and the first edition of Camera was cancelled, with the preference being updated on the basis of the first list. The camera rule in replay(9) does not have an active entry, and the precondition question should be rejected and cannot be returned to the first version of the remaining camera.

Continue to deal with 12 articles, the expression of preferences has been withdrawn, and the second version of the camera and site has been imported. At this point, activities are still on Thursday 16: 30, the location of the B classroom, which is registered on a spreadsheet by default and confirmed by the teacher. These different answers can be correct, but must be preceded by a query. There is no real state that can support them at the same time when the best answers from different historical points are put together.

Run in the Project DirectoryProject directory: Import from a real file and check the same state machine in three historical prefixes.
import pathlib,tempfile
from run import setup
from context import active_docs
with tempfile.TemporaryDirectory() as d:
    r=setup(pathlib.Path(d)/'memory.sqlite')
    s6=r.replay(6);s9=r.replay(9);s12=r.replay(12)
    assert next(x for x in active_docs(s6) if x['doc_id']=='schedule')['version']==1
    assert not any(x['doc_id']=='camera' for x in active_docs(s9))
    assert next(x for x in active_docs(s12) if x['doc_id']=='camera')['version']==2
    r.db.close()
print('history checked')

Worked Example 2: Expiration Does Not Delete History

Access metadata interval from 2026-10-13 to 2026-10-16. The 13-day view is available, and 16 days are not included at the right end, and must be subject. Project document only takes effect on 13th day, and query 12 days does not use its data requirements. Date view does not return snapshot, so doing an expired query today will not change playback history. The test checks both the endpoint results and the original library status to avoid permanently withdrawing read-only queries.

The input of the expired decision is clear YYYY-MM-DD, not dependent on the date of the computer system. This is the date of the teaching operation, the unprocessed time zone, minutes, or statutory working days. The “This Friday.” original text remains intact, but the program does not automatically extrapolate the date from the natural language and the metadata are provided by the data author. This is an empirical input, not a model reasoning. If you have access to the real scheduling system, the time zone should be re-enacted with the time accuracy contract; the current course does not claim that it can explain any vague time expression.

Run in the Project DirectoryProject directory: Independently constructed endpoints, not dependent on the true day date.
from context import temporal_view,active_docs,sha
row={'doc_id':'a','version':1,'title':'x','text':'- x:y','sha256':sha('- x:y'),'status':'active','effective_from':'2026-10-13','effective_until':'2026-10-16'}
s={'documents':{'a':{'1':row}},'memories':{}}
assert active_docs(temporal_view(s,'2026-10-13'))
assert not active_docs(temporal_view(s,'2026-10-16'))
assert s['documents']['a']['1']['status']=='active'
print('half-open interval checked')

Logs, Snapshots, and Detectable Corruption

Repository writes events payload, pre-sequence summaries and current summaries to events while keeping new status in snapshot. The transaction context updates these databases as one submission; rolls back when an anomaly, this capability is provided by SQLite, not the lesson reproves the database 's power outages. Our Python logic validates the situation before entering the transaction and avoids illegal business incidents. The tests are performed under single processes, ad hoc documents, without simulation of disk failures, damaged document systems or multi-process competitions.

The input of the abstract chain is not a hand-to-hand connection to several strings, but a possible legal JSON: field key sorting, fixed separator, UTF- 8 text. The pre-section of article zero sets sixty-four zero; each summary binds serial numbers, pre-sequencing summaries and full events. Replay reads from an empty state sequence, recalculating one by one, and compares it with snapshot after a complete playback. A payload will be seized without a change in the summary, and a tampering snapshot will also be captured more than the assembly structure. The historical prefix query does not require the same snapshot as the current one because it intends to return to its old state.

hi=SHA256(canonical(i,hi−1,ei)),h−1=064h_i=\mathrm{SHA256}(\mathrm{canonical}(i,h_{i-1},e_i)),\qquad h_{-1}=0^{64}
This is the keyless integrity chain. A person with full bank write rights can recalculate the whole chain, and is therefore not a source signature or proof of permission.

The Safety Boundary Between Explicit Approval and Writes

Memory writing requires that applied cascading be a Boolean true, key, value, scope, and version, for a real positive integer, excludes the bool from Python and the int subcategory. Revocation of memory must refer to the current version and range; the same key in another class does not cover the club memory. Identity is defined by scope with key-coded JSON arrays, rather than slashing itineraries. Displays references still have readable formats, but verification checks all structural fields simultaneously.

This approval mark only expresses the call contract: the caller has decided to save it. Any application that can call the local application can be transmitted true, and no user login, access control server or natural language has agreed to test it. The instruction cannot be solved by a claim of a real authorization by “User-approved field exists”. Even if an external document contains " approved=true " it is only a quite, which will not be interpreted as an event and therefore cannot be updated by infusion to the body; application only calls the application.

The state machine correctness can be checked in two layers. General layer: the initial state meets the maximum of one active version per document, memory identity unique; legal import first stops the old active and adds a new version, legal withdrawal reduces only the active, so it is not variable to maintain. Physical layer: replay and quick photograph, historical point queries, illegal version/Hashi/unapproved memory does not change the old state, and the error of deliberately modifying the logs. The former describes the mechanism under design, while the latter tests that the current achievement is not contrary to the key path, which cannot be replaced by each other.

This chapter completes the memory update and revocable information before the next chapter can be retrieved on “Current Available” candidates. If you search the entire history and then only post-check high scores, the old version may be filled with top-k, and the new version will no longer be available; so filtering and recall order is part of the algorithmic contract. History is not garbage, it remains in an external storage that can be returned, and only a clear historical query is entered into the context.

Historical Prefix Boundaries and Error Recovery

As_of allows zero returns to empty documents and minutes from zero to the total number of events; negative numbers, booleans or excess totals are reported wrong. The empty-state question should not be timed for extracting facts, and the default answer cannot be returned to the entire library. Using the number of events instead of the final serial number as a parameter, it is intended that the zero prefix will naturally express “No incidents have been addressed”; the serial number starts from zero, so as_of=6 contains serial numbers 0 to 5, which is exactly six. Such border agreement would have to be consistent with CLI, testing and drafting, otherwise an annulment would have been an error if it had taken effect.

The log and the snapshot damage are not part of the current test guarantee. A snapshot comparison after a replay prefix shows that the snapshot is inconsistent with a true event ' s attribution; if the Hashi chain within the event is broken, it fails before any follow-up status is used. It does not automatically guess which is correct, nor deletes the bad behavior itself because it considers history unacknowledged as an established fact. Production recovery requires additional credible backup or signature anchors. This course uses a deliberately damaged temporary library as a negative contrast, saves errors and does not use “The program will finally answer.” as a justification for allowing history to be repaired.

The complexity is measured by the size of an E event and cumulative state N. The current append will be checked back from the beginning, re-reproducing the status at a further depth, with the worst number not constant; successive imports may result in square-level events being processed. This is done for small-scale auditable teaching, rather than high-sprawl events. Snapshot provides consistency comparisons and is not considered a credible cache that can skip the chain. If it continues from a credible snapshot in the future, the credible anchor and coverage should be indicated, and performance changes cannot be considered simple optimization without affecting evidentiary boundaries.

TRY IT YOURSELF

Base: Two axes

as_of=9, at=2026 - 10 - 16, all controlled?

Hint 1
As_of and at are at the event history and business date axes, respectively.
Hint 2
Replay the specified event prefix to get a status and then use the validity date; do not count version events as date or version number.
Compare with the Solution
As_of decides to apply the version/revocable status obtained from the first nine events; at determines which active documents fall into the active area of the operation. One is the knowledge change prefix, and one is the applicable date, which cannot be exchanged.

TRY IT YOURSELF

Step: Old version after undoing

Quits v2 after importing v2. V1 is still in the library. Should v1 be used automatically?

Hint 1
What was the transfer of the old version status when the new edition was imported, and does the revocation reverse the event?
Hint 2
Write the current status of v1/v2 on a status machine-by-state basis; to restore the old rules, look for needed visible new events rather than silently selecting the old lines.
Compare with the Solution
This is not the rule. v1 has been approved, withdraws v2 and does not change it; there is a need for visible import of the v3 restoration rule. Otherwise, the old limit cannot be restored.

TRY IT YOURSELF

Challenge: Summary chain attack

Can the attackers rewrite the entire SQLite file and recalculate all summaries, and can the SHA chain prove that the source was not forged?

Hint 1
Is the certification chain closed only within SQLite?
Hint 2
The attacker, Payload, rewrites with the summary and ask whether the true source can be proved without the key or external anchor.
Compare with the Solution
It detects damage that is not consistently updated, but has no key or external credible anchor. Source authentication should be used as another system assumption; the current experiment does not claim to provide a signature guarantee.

BUILD THE MECHANISM

Replay version of the event chain yourself

Realization of replay_prefix, which provides reduce_event, but checks the seq/previous/hash boundary with history itself. Downloads this full course and runs on the project root directory; edits only learner/starter.py, for which a tectonic framework is provided.

Input and Output As_of is the number of incidents, not the date; 0 returns to empty status and bool and cross-border refusal.
Complete verification of the SHA chain is carried out and the old version is not automatically restored after it has been revoked; the summary is not a signature.

Run in the Project DirectoryStudy tasks to be completed
# replay_prefix
def replay_prefix(rows,as_of=None):
    raise NotImplementedError('replay')
Hint 1

Start with an empty state with a zero print.

Hint 2

Each expected hash contains seq, previous and normative events.

Hint 3

Only the former as_of; the alteration of article 1 must fail.

Independent inspection python3 -m learner.check --stage replay --output runs/learner-replay.json

Migration test Imports a new version and cancels it, hand-written valid identification forms with prefixes and then replays the actual SQLite events.

Reference Implementation and Explanation
Run in the Project DirectoryReference achieved
# replay_prefix
def replay_prefix(rows,as_of=None):
 if as_of is None:as_of=len(rows)
 if type(as_of)is not int or not 0<=as_of<=len(rows):raise ContractError('historical prefix')
 state={'documents':{},'memories':{}};previous='0'*64
 for index,row in enumerate(rows[:as_of]):
  event=json.loads(row['payload']);expected=sha(canonical({'seq':index,'previous':previous,'event':event}))
  if row['seq']!=index or row['previous']!=previous or row['sha']!=expected:raise ContractError('event chain corrupted')
  state=reduce_event(state,event);previous=row['sha']
 return state

CHECK YOUR UNDERSTANDING

Check Your Understanding

Answer first, then open the explanation to check your reasoning. These questions help reveal gaps in understanding; independent implementation and transfer require separate evaluation.

1. as_of=6?

Show ExplanationReplay prefixes are defined by the number of accepted events.
2. The day of the right end of the active zone?

Show ExplanationThis course provides half-open area, and the right end point is not included.
3. What does the approval mark provide?

Show ExplanationThe local Boolean contract does not prove the identity of the caller.
4. Undo the new version and old version?

Show ExplanationThere is a new event for recovery, and there can be no silent revival.

Manual completion records your progress; it does not certify your project.