AI Hero Club

AI Agent Engineering · Lesson 2

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.
AI Agent Engineering / Learning Plan ↗

LESSON 02 / 8Suggested study 120 minutes

State, Events and Recoverable Execution

After an interruption leaves only a conversation log, how can we decide whether to continue, retry or refuse recovery?

3 Questions for This Lesson
  • Define a state sufficient to restore rather than just save dialogue text
  • Consistency check between the indexing of event chains and snapshots
  • Actual disruption and reinstatement of same task and inventory books
Course Project ZIP ↓

Why a Conversation Log Is Not Execution State

Chapter I establishes tools input and authorization, which in turn transforms the execution history into a recyclable object. Chat text may write “Saved”, with no response; or the tool is completed and the model cannot be exported. To restore the system, it is necessary to identify the identity of the mission, the cause of the current termination, the observed results, the actions yet to be performed, cumulative attempts, strategic decision counts and outcomes. These fields together constitute the status s. The natural language interpretation in the log can be readable, but it must not serve as the only basis for determining whether the inventory has changed. The project is saved by structured JSON status and SQLite, rather than from the chat text guessing phase.

The task id is a restored identity, not a display of title. The same id must be re-started with the same field as the original task; if the number or permission changes, a new identity should be used, otherwise recovery will mix two different business intentions into one thing. Project start first reads the original snapshot, compares the task, and then resets the event chain. New tasks are created when there is no status. The end state re-runs only back to existing status and does not redo tools; this is different from blindly starting again, which may repeat the reservation.

The Smallest Unit of a State Transition

The active state includes at least task, status, observations, pending, caps, decisions, attachments, result. Observations save confirmed results by toolbar name;pending saves the full pending action and cannot save only the tool name, otherwise the parameters or buttons of restoration may be regenerated. Calls is the total number of actual tool attempts and failures are counted; Attemps are the current attempts at sending; decisions are the number of tool actions that are prepared for local JSON strategy to locate the next action. Three counts answer different questions and cannot replace each other.

A normal tool action starts with three sustainable boundaries: prepared, attached_started, and observed. Prepared first saves the policy selection and complete parameters; attempt_started increases the number of attempts to be counted and saved before calling; observed adds observations and emptys the feeding after the result returns. This allows the middle state of “Attempts recorded but not yet effected” and the middle state of “Effect has been submitted but observation not saved”. The latter requires a Chapter 4 account to be processed in such a way that this chapter does not pretend to save a state only to guarantee long-range side effects just once.

st+1=δ(st,et),terminal(st)⇒δ(st,e)=sts_{t+1}=\delta(s_t,e_t),\qquad \mathrm{terminal}(s_t)\Rightarrow\delta(s_t,e)=s_t
s as a state, e as an event, t as a transfer serial number, delta as a transfer function; termination drives again without adding effects.

The Roles of Event Chains and Snapshots

Quick images allow recovery to quickly achieve the latest state, and the event chain allows readers to verify how it reaches. Each time the project saves an event and updates the snapshot in the same SQLite service, the event contains a type and the complete state. The task-based maintenance numbering starts from zero, records a summary of the previous event, and calculates SHA256 for numbers, presumes and loads. Preservation of the full state takes more space than a mere memory increment, but it facilitates resetting; real systems can use a tighter snapshot of events and cycles, provided that the reconstruction results are still validated to match the current snapshot.

Hi=SHA256⁡(canon⁡(i,Hi−1,Ei)),H−1=064H_i=\operatorname{SHA256}(\operatorname{canon}(i,H_{i-1},E_i)),\qquad H_{-1}=0^{64}
E is the event load, i is the event serial number; Canon is a sequence of fixed keys, UTF- 8 and fixed JSON separation. The summary detects changes in content and does not provide an identity signature.

Standardization avoids that the same dictionary produces different summaries simply by type of key order. Items are sorted, separated closely and created by keeping Chinese code. Re-selling item reconciliation numbers is continuous, previous, summaries are identical, and final comparison of final event status with a states watch snapshot. This check may detect deletions of intermediate events or changes only snapshots. It is not a cryptographic audit system that is tampered with by the administrator: a person who can rewrite all events and summaries at the same time can still forge a new chain, and if the threat is resisted, an external anchor or signature must be added.

Worked Example 1: Stopping the Process After Two Tools

In the case of reserve-camera, the initial status calls zero and observational empty. After executing the search calls hold only hits; after executing document calls holds both text and content summaries. At this point, stop_after=2 returns ranning, the database has two steps of observation. Closes the connection and re-opens the same database and loads the same task. The policy reads that there is already a search and document, only stock, then reserve, and finally ends. The full state of restoration is the same as uninterrupted operation, including call times four and final inventory two; it does not compare only “Success” text.

Run in the Project DirectoryProject directory running: genuinely closed and database reopened, continuing from intermediate observations.
import pathlib,tempfile,json
from agent import Store,Runner
from run import ROOT
row=json.loads((ROOT/'data/tasks.jsonl').read_text().splitlines()[1])
with tempfile.TemporaryDirectory() as td:
    path=pathlib.Path(td)/'state.sqlite'
    store=Store(path,ROOT/'data');store.import_documents()
    partial=Runner(store).run(row['task'],stop_after=2)
    assert partial['calls']==2 and partial['status']=='running'
    store.db.close()
    store=Store(path,ROOT/'data')
    final=Runner(store).run(row['task'])
    assert final['status']=='reserved' and final['calls']==4
    assert store.replay(row['task']['id'])==final
    store.db.close()
print('resume PASS')

Worked Example 2: What Snapshot-Only Storage Misses

Assuming that normal events are zero, then there is prepared and observed. Some simply modify the status forms to reservated, but no reserve observes or echoes. If you restore a snapshot, the fictional results will be completed. The project replay will find the last event not equal to the snapshot. Conversely, modifying the event payload without updating the summary will fail in the event. Tests the actual implementation of SQL rewrite loads and requires to drop the broken event log instead of checking the log with the naked eye.

There is also a more common error: duplicate numbers or jump numbers. The main key of the project prevents the insertion of the same task number twice, and reloading the list again equals the actual order starting from zero. Each task has its own numbering chain and should not require a strict staggering of the entire database event. Since only single-work processes are supported at this time, multiple process grabs and leases have not been achieved; the contest driven simultaneously by two workers is out of the receiving and inspection range. Database services provide a partial atomic character but cannot automatically supplement and grant ownership over any arbitrary application of the protocol.

A Successful Save Does Not Confirm the Side Effect

If the process is interrupted after attachment_started and before it is actually called, it is reasonable to see the pending again; if it is interrupted after tool matter has been submitted and before observed, the same pending will also be retested. The client end state alone cannot determine whether the same status is valid from both appearances. The project thus perpetuates the tool 's endpoint etc. and resumes reading the results when retrying with the same key. This is at the core of cross-border uncertainty, and “Every step of the way.” should not be misspelled as automatically avoiding all duplications. Chapter IV will be deduced from time to time.

Scope: Current information version freeze policy

The state should also bind the information version. The first time a project imports the body of the saved document and SHA256, and the following key_documents find that the contents of the same identity document have changed and request a new database. This is a conservative freezing policy: restoration will not be quietly replaced with a new version of the information, and the original reference is still based on the same content. If the actual online system supports the update, it requires a visible version selection, revocation and migration, and the course does not claim that the current database supports such dynamic knowledge maintenance; the engineering course in the context will be studied separately and withdrawn.

The first category consists of path equivalents: stop at multiple cut points of zero to four steps and recover against completeness, stock and compliance. The second category consists of damage detection: change of mission content, change of event load, change of snapshot, or change of source version cannot continue silently. The former proves that the usual legal interruptions can be restored, while the latter test system does not treat inconsistent objects as a normal history. “File Exists After Memory” The dictum does not cover these semantics. The current test is performed on a real SQLite file, without a fake memory dictionary simulation.

Scope: Application interruption and hardware failure

There is also a clear boundary of failure for sustainability: SQLite submission was successfully created under the assumption of official services and documentation systems, and the course does not directly test real power outages, board damage or malware managers. We actually injected the application process boundaries with interruptions and re-opening document validations. The database file exists without indicating that the last save has been submitted; recovery should only be done by reading the snapshots and checking events, rather than by printing the inferences from the controller. The course does not exaggerate application-level breakdowns to full hardware failure guarantees.

Extension: storage costs of event snapshots

Complete state preservation also costs. Each event carries a snapshot, and if the document is long, the logs repeat a large amount of content. Here, small frozen information is selected to maintain readability and to make re-release mechanisms easy to verify. The extension allows for a summary of non-changeable text, with the event merely citing identity, and regular compression; but the compressed rule must be retained to rebuild the source and verify. This course does not treat the unrealized event as having the capacity or extrapolating the size of the production storage from the volume of the current documents.

Standalone ProgramThe Standard Library is independently inspected and does not rely on the project catalogue.
import hashlib,json
def hashed(obj):
    raw=json.dumps(obj,sort_keys=True,separators=(',',':')).encode()
    return hashlib.sha256(raw).hexdigest()
previous='0'*64
first={'seq':0,'previous':previous,'payload':{'status':'running'}}
h0=hashed(first)
second={'seq':1,'previous':h0,'payload':{'status':'info'}}
assert second['previous']==hashed(first)
changed={**first,'payload':{'status':'reserved'}}
assert second['previous']!=hashed(changed)
print('chain and mutation PASS')

Exercises and Project Contributions

TRY IT YOURSELF

Foundation: what is the planning need?

Why is saving the pending = "reserve" not enough to restore? Lists at least four parameters that must be saved.

Hint 1
Restores the complete action to be replayed, not just the name of the action.
Hint 2
The four categories of information, namely, target, quantity, version and identity, are checked, and in particular the operational identity cannot be re-created at the time of retesting.
Compare with the Solution
It is also necessary to regenerate these parameters at the time of recovery. The target, number, version or identity may be altered; especially the new key will transform the same business intent into a new effect. The project preserves the full action object and makes the original task a fixed premise.

TRY IT YOURSELF

Step forward: a secure boundary for the Hash chain

The attackers can rewrite the entire database table and recalculate each summary.

Hint 1
The abstract chain detects partial inconsistencies, but is there an independent and credible anchor at the end of the chain?
Hint 2
Assuming that the attackers, together, change the payload to the full subsequent summary, the judgement will only be whether the consistency within the chain can still be distinguished from the falsification of history.
Compare with the Solution
No. Hash chains detect damage and local tampering that are not synchronized. They do not amount to an external signature or non-fixable log. Those who can rewrite the entire chain can construct a new history that is consistent. External credible anchors, access isolations, or signatures are required to deal with stronger threats; this course only states local integrity checks.

TRY IT YOURSELF

Challenge: Two identical plans

The client keeps the samepending after pre-call crash and post-tool submission. Why can't a client just check the client decide whether to withhold the inventory again?

Hint 1
Two time series that were interrupted before submission and not observed after submission may appear to be the same on the client side.
Hint 2
Ask who can reliably know whether the effects are in storage; peer-to-peer feedback should be saved with the effects, and not depend on client guessing whether to do it again.
Compare with the Solution
The client does not have the confirmation information to distinguish between the two. If a direct redecoration is repeated, it is possible to skip the button if it is repeated directly. The same business is intended to remain the same key, so that the tool saves the message in the same matter as the effect, then tries again to check the key before deciding to execute it; the client records the observation afterwards. This depends on the tool end protocol and cannot be guaranteed unilaterally by the status of the dialogue.

This chapter is delivered by Store.save, snapshot, replay and breakpoint Runner. The next chapter considers the strategy as a replacement unlettered action proposer, specifying when to continue and when to stop; status and log are traceable, so replacing the decision source will still use the same tools and recovery checks.

BUILD THE MECHANISM

Construct a permanent state of binding task

Creates, saves and restores the status of the task in the real LearnerRunner.start. Downloads this full course, running in the project root directory; edits only learner/starter.py, which already provides a tectonic framework.

Input and Output The same complete request must be tied with task id; new status calls=0, pending=None.
Saved snapshots are the same as events; reset silently creating a second task.

Run in the Project DirectoryStudy tasks to be completed
# LearnerRunner.start(替换已提供类的此方法)
def start(self,task):
        raise NotImplementedError('state')
Hint 1

The distinction between new tasks and existing snapshots cannot be made to cover the old state.

Hint 2

The task has been completed with the id task before checking replay.

Hint 3

Changing the level of equality but retaining the id should be rejected rather than withheld.

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

Migration test Adds a read-only task to save and restart with SQLite; checks the status identity and count, and does not perform any real external borrowing.

Reference Implementation and Explanation
Run in the Project DirectoryReference achieved
# LearnerRunner.start(替换已提供类的此方法)
def start(self,task):
        validate_task(task);old=self.store.snapshot(task['id'])
        if old:
            if old['task']!=task:raise ContractError('task ID reused with different request')
            self.store.replay(task['id']);return old
        state={'task':task,'status':'running','observations':{},'pending':None,'calls':0,'decisions':0,'attempts':0,'result':None}
        self.store.save(state,'created');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. How should events and snapshots be updated?

Show ExplanationFailure to do so may leave the two at odds.
2. Same task id but quantity change?

Show ExplanationMission status must be complete with operational intent.
3. Hashi chain major check?

Show ExplanationIt does not automatically provide assurances of authenticity or non-frozen external assurances.
4. Save client status only to remove post-submission disconnection?

Show ExplanationThe client cannot distinguish between pre-calling and after-effects unrecognised, requiring a service-end effects return.

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