76 / 90

第76日: エージェント実行状態、チェックポイントと冪等副作用

境界付きエージェントの実行ライフサイクルをモデル化し、トレースを永続化・リプレイして、ツール副作用を再試行安全にする。

エージェント 480 アクティブ分(8 時間)
01 120 分

エージェント実行状態マシンとアクション/観測トレース

Agent支援エンジニアリングチェック

前提条件

第73〜75日のエージェントループとツールプロトコル学習、およびTicket 22の境界付きエージェントプロジェクト(projects/agent_learning)。

学習目標

境界付きエージェントが保持する完全な実行状態(アクション/観測トレース、ステップカウンタ、リトライカウンタ)を特定し、3つの合法終了状態(goal_reached, tool_failure, step_budget)を列挙する。

手順

1. projects/agent_learning/agent.py を開き run_task を読みます。
- 実行ごとの可変状態: trace({action, observation} ペアの追記専用リスト)、retries(ok=false の観測回数)、暗黙のステップカウンタ len(trace)。
- 終了遷移: write_report が ok=true を返す -> status=completed, termination=goal_reached。retries が max_retries(=2) を超過 -> status=failed, termination=tool_failure。どちらでもなくループ終了 -> status=budget_exhausted, termination=step_budget。
2. 意図的に存在しないものを確認します: 思考連鎖フィールドも隠れたスクラッチパッドもなく、トレースが永続化される全状態です(project.json の evidence.forbidden_fields が thought と chain_of_thought を列挙)。
3. 本番のチェックポイント機構と比較します: LangGraph のチェックポインタは各スーパーステップでグラフ状態を永続化し、Temporal はイベント履歴のリプレイで状態を再構築します。本トレースは同じ思想の最小イベントログです。
4. python -m projects.agent_learning.cli evaluate --fixture summarize-notes --output /tmp/agent-run.json を実行し、result.status と result.termination を確認します。

演習と予測記録

実行前に通常実行の4ステップトレースを予測し、CLIを実行して各ステップの遷移(アクション提案 -> 観測記録 -> カウンタ更新)を記録してください。steps=4, retries=0, termination=goal_reached で終了することを確認します。

独立習得基準

コードを実行せずに、失敗した観測で増加するカウンタ(retries)、健全な実行を終了させる上限(max_steps=6)、成功時に早期終了させる唯一のアクション(write_report)を答えられる。

公式ソースリソースと権利証跡

linking MIT (LangGraph project) / documentation site terms

LangGraph Persistence: Checkpoints, Threads, and State Snapshots

著者・提供機関: LangChain / LangGraph Documentation Team | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Persistence: Checkpointer vs. store (checkpoints keyed by thread_id); the page now redirects to docs.langchain.com

検証バージョンと日付: LangGraph documentation (Verified: 2026-10-30)

選定理由:

Primary reference for agent-run checkpointing: LangGraph checkpointers persist graph state at every super-step so interrupted runs resume from the last committed snapshot, the production analogue of this project's action/observation trace.

ソース前提知識:

Agent loop fundamentals, tool calling, and JSON state serialization.

安全フォールバック(オフライン回復性):

The checkpoint/replay exercise is implemented directly against the projects/agent_learning trace JSON; no framework installation is required.

比較対象候補リソースと選定評価 (2)
Temporal Durable Execution documentation ↗ compared_alternative [MIT / documentation terms]

Temporal persists event histories for replay-based recovery of arbitrary workflows; LangGraph targets agent graphs specifically and stays closer to the learner's tool-loop mental model.

OpenAI Agents SDK session/state documentation ↗ compared_alternative [MIT / documentation terms]

Provider-scoped SDK sessions; LangGraph's explicit checkpoint model exposes the underlying state-transition semantics more transparently.

linking Temporal Technologies copyright (documentation; Temporal server code is MIT) / documentation site terms

Temporal Documentation: Durable Execution and Event History Replay

著者・提供機関: Temporal Technologies Documentation Team | オリジナル出所URL ↗

該当セクション・タイムスタンプ: What is Temporal?: Durable Execution

検証バージョンと日付: Temporal documentation (Verified: 2026-10-30)

選定理由:

Standard industrial reference for durable execution: workflow state is rebuilt by replaying a persisted event history through deterministic code, exactly the checkpoint/replay mechanism learners reproduce against the agent trace.

ソース前提知識:

State machines, event logs, and deterministic replay concepts.

安全フォールバック(オフライン回復性):

Replay semantics are exercised offline against the deterministic adapter; Temporal itself is never installed.

比較対象候補リソースと選定評価 (2)
LangGraph Persistence documentation ↗ compared_alternative [MIT / documentation terms]

Agent-specific checkpointing; Temporal supplies the general event-sourced replay model that motivates the exercise.

Cadence workflow documentation ↗ compared_alternative [MIT / documentation terms]

Temporal's predecessor with equivalent replay semantics; Temporal's docs are more actively maintained.

02 120 分

チェックポイントとリプレイ: 永続化トレースから実行状態を再構築

独立習得チェック(AI 支援なし)

前提条件

第76日アクティビティ1の実行状態モデル。JSONシリアライズ。

学習目標

実行トレースをJSONチェックポイントとして永続化し、決定的リプレイを証明する: 記録された各プレフィックスを adapter.next_action に与えると記録されたアクションを正確に再現する。

手順

1. チェックポイント書式を設計します: {'task_id': 'summarize-notes', 'steps': 4, 'retries': 0, 'trace': [...]} を run_checkpoint.json に書き込みます。
2. replay(trace_prefix, adapter) を実装します: adapter.next_action(list(trace_prefix)) を返します。DeterministicModelAdapter は履歴のみから次アクションを選ぶため、プレフィックス k のリプレイは必ず trace[k].action を生成します。
3. 0..steps-1 の全 k で検証します。これはイベントソーシング型回復の縮小版です: state = fold(history)、Temporal が durable execution として文書化する回復形態と同じです。
4. 正直な限界を記録します: リプレイはアダプタの意思決定状態を再構築しますが、外部副作用は巻き戻しません。report.txt はトレースの外に存在するため書き込まれたままです。

演習と予測記録

save_checkpoint(result, path) と replay(trace_prefix, adapter) を実装してください。通常実行の全 k で replay(trace[:k]) == trace[k]['action'] をアサートし、続けて invalid_arguments 障害実行(5ステップ)でも確認します。

独立習得基準

チェックポイント化したプレフィックスから全アクションを一致リプレイできることを実演し、現実の限界を1つ述べられる: トレース外の副作用は巻き戻されない。

公式ソースリソースと権利証跡

linking Temporal Technologies copyright (documentation; Temporal server code is MIT) / documentation site terms

Temporal Documentation: Durable Execution and Event History Replay

著者・提供機関: Temporal Technologies Documentation Team | オリジナル出所URL ↗

該当セクション・タイムスタンプ: What is Temporal?: Durable Execution

検証バージョンと日付: Temporal documentation (Verified: 2026-10-30)

選定理由:

Standard industrial reference for durable execution: workflow state is rebuilt by replaying a persisted event history through deterministic code, exactly the checkpoint/replay mechanism learners reproduce against the agent trace.

ソース前提知識:

State machines, event logs, and deterministic replay concepts.

安全フォールバック(オフライン回復性):

Replay semantics are exercised offline against the deterministic adapter; Temporal itself is never installed.

比較対象候補リソースと選定評価 (2)
LangGraph Persistence documentation ↗ compared_alternative [MIT / documentation terms]

Agent-specific checkpointing; Temporal supplies the general event-sourced replay model that motivates the exercise.

Cadence workflow documentation ↗ compared_alternative [MIT / documentation terms]

Temporal's predecessor with equivalent replay semantics; Temporal's docs are more actively maintained.

linking MIT (LangGraph project) / documentation site terms

LangGraph Persistence: Checkpoints, Threads, and State Snapshots

著者・提供機関: LangChain / LangGraph Documentation Team | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Persistence: Checkpointer vs. store (checkpoints keyed by thread_id); the page now redirects to docs.langchain.com

検証バージョンと日付: LangGraph documentation (Verified: 2026-10-30)

選定理由:

Primary reference for agent-run checkpointing: LangGraph checkpointers persist graph state at every super-step so interrupted runs resume from the last committed snapshot, the production analogue of this project's action/observation trace.

ソース前提知識:

Agent loop fundamentals, tool calling, and JSON state serialization.

安全フォールバック(オフライン回復性):

The checkpoint/replay exercise is implemented directly against the projects/agent_learning trace JSON; no framework installation is required.

比較対象候補リソースと選定評価 (2)
Temporal Durable Execution documentation ↗ compared_alternative [MIT / documentation terms]

Temporal persists event histories for replay-based recovery of arbitrary workflows; LangGraph targets agent graphs specifically and stays closer to the learner's tool-loop mental model.

OpenAI Agents SDK session/state documentation ↗ compared_alternative [MIT / documentation terms]

Provider-scoped SDK sessions; LangGraph's explicit checkpoint model exposes the underlying state-transition semantics more transparently.

03 120 分

冪等なツール副作用と「ちょうど一度」の錯覚

Agent支援エンジニアリングチェック

前提条件

第76日アクティビティ1〜2。write_report ペイロード契約。

学習目標

write_report の再発行が安全な理由(副作用が冪等であること)を説明し、デュープキーや一意制約を必要とする非冪等な副作用(追記、課金)と対比する。

手順

1. 冪等副作用: 同一内容の write_report を2回適用しても report.txt は同じ状態のままです。各呼び出し後にファイルをハッシュして検証します。
2. 非冪等の反例: append_note ツールはリトライで行を重複させ、charge_card 副作用は二重課金します。Stripe が冪等キーで解決する障害モードです。
3. 予算の視点: at-least-once 配信(リトライ)+ 冪等副作用 = effectively-once の結果。ただしリトライは劣化した系への負荷を増幅するため(SRE の連鎖障害モデル)、安全なリトライでも予算は有限に保ちます。
4. 各プロジェクトツールを分類します: list_notes(読み取り専用・冪等)、read_note(読み取り専用・冪等)、write_report(上書き・内容一致により冪等)。

演習と予測記録

冪等性を実測してください: _tool_call の write_report を同一内容で2回呼び、各回後に report.txt をハッシュします。次に非冪等な append_note ツールと、安全性を回復するデュープキー(filename+content の sha256)を設計してください。

独立習得基準

副作用を冪等/非冪等に分類し、それぞれをリトライ下で安全にする仕組み(デュープキー、一意制約、上書きセマンティクス)を挙げられる。

公式ソースリソースと権利証跡

linking Stripe site content / linked reference noncommercial

Stripe API Documentation: Idempotent Requests

著者・提供機関: Stripe, Inc. | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Idempotent requests (Idempotency-Key header; keys can be removed after at least 24 hours)

検証バージョンと日付: Stripe API documentation (Verified: 2026-10-30)

選定理由:

Standard production definition of idempotency keys: Stripe guarantees safe client retries by deduplicating POST requests on a caller-supplied key, the exact mechanism that turns at-least-once retries into effectively-once effects.

ソース前提知識:

HTTP APIs, retries, and side-effect semantics.

安全フォールバック(オフライン回復性):

Idempotency semantics are demonstrated locally with repeated write_report calls and a sha256 dedupe key, no Stripe account needed.

比較対象候補リソースと選定評価 (2)
IETF draft: The Idempotency-Key HTTP Header Field ↗ compared_alternative [IETF Trust / open access]

Standardization-track header specification; Stripe's live documentation is the more concrete deployed example.

AWS Builder's Library: Making retries safe with idempotent APIs ↗ compared_alternative [Amazon site content]

Deep design treatment of idempotent server design; Stripe provides the tighter client-visible contract cited in the exercise.

linking CC BY-NC-ND 4.0 noncommercial no-derivatives

Site Reliability Engineering, Chapter 22: Addressing Cascading Failures

著者・提供機関: Mike Ulrich, in Site Reliability Engineering (eds. Betsy Beyer, Chris Jones, Jennifer Petoff, Niall Richard Murphy; Google) | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Preventing Server Overload: Retries

検証バージョンと日付: O'Reilly 2016 free online edition (Verified: 2026-10-30)

選定理由:

Primary analysis of how unbounded retries amplify partial outages into cascading failures, motivating hard retry budgets and deadlines in agent runtimes.

ソース前提知識:

Retries, queueing, and load-shedding basics.

安全フォールバック(オフライン回復性):

The retry-amplification scenario and budget arithmetic are fully reproduced in the lesson's worked example.

比較対象候補リソースと選定評価 (2)
Release It! (Michael Nygard) - Stability patterns ↗ compared_alternative [Commercial book]

Broader stability-pattern catalog (circuit breakers, bulkheads); the SRE chapter is free and directly quantifies retry amplification.

Strong companion article; the SRE chapter frames the failure mode (cascading overload) that the retry budget defends against.

04 120 分

評価: 実行状態遷移監査と台帳検証

独立習得チェック(AI 支援なし)

前提条件

第76日アクティビティ1〜3。

学習目標

記録された実行の終了状態をトレースから再導出し、不正遷移にフラグを立てる監査関数を構築し、観測された4つの実行すべてに対して証明する。

手順

1. audit_run(result) -> {'steps': int, 'retries': int, 'status': str, 'termination': str, 'violations': []}。
2. 規則: steps <= max_steps(6)。retries <= max_retries+1(3) で、retries>2 は status='failed'/termination='tool_failure' と対になること。status='completed' は最終アクションが write_report かつ観測が ok であること。status='budget_exhausted' は steps==6 かつ終端成功なしであること。
3. 通常実行と3つの障害トレースを入力し、期待される (status, termination) ペアをアサートします。
4. 1つのトレースを故意に破損させ(例: write_report 観測の ok フラグを消す)、監査が宣言された status を信用せず不一致にフラグを立てることを示します。

演習と予測記録

audit_run を実装し、記録済み各実行についてJSON台帳行を1行ずつ出力してください。台帳が completed/goal_reached(4ステップ)、completed/goal_reached(5ステップ・1リトライ)、failed/tool_failure(3ステップ・3リトライ)、budget_exhausted/step_budget(6ステップ・0リトライ)を再現することを確認します。

独立習得基準

導出した判定が全記録実行と一致し、意図的に破損させたトレースで違反フラグが発火する遷移監査を提出できる。

公式ソースリソースと権利証跡

linking MIT (LangGraph project) / documentation site terms

LangGraph Persistence: Checkpoints, Threads, and State Snapshots

著者・提供機関: LangChain / LangGraph Documentation Team | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Persistence: Checkpointer vs. store (checkpoints keyed by thread_id); the page now redirects to docs.langchain.com

検証バージョンと日付: LangGraph documentation (Verified: 2026-10-30)

選定理由:

Primary reference for agent-run checkpointing: LangGraph checkpointers persist graph state at every super-step so interrupted runs resume from the last committed snapshot, the production analogue of this project's action/observation trace.

ソース前提知識:

Agent loop fundamentals, tool calling, and JSON state serialization.

安全フォールバック(オフライン回復性):

The checkpoint/replay exercise is implemented directly against the projects/agent_learning trace JSON; no framework installation is required.

比較対象候補リソースと選定評価 (2)
Temporal Durable Execution documentation ↗ compared_alternative [MIT / documentation terms]

Temporal persists event histories for replay-based recovery of arbitrary workflows; LangGraph targets agent graphs specifically and stays closer to the learner's tool-loop mental model.

OpenAI Agents SDK session/state documentation ↗ compared_alternative [MIT / documentation terms]

Provider-scoped SDK sessions; LangGraph's explicit checkpoint model exposes the underlying state-transition semantics more transparently.

linking Stripe site content / linked reference noncommercial

Stripe API Documentation: Idempotent Requests

著者・提供機関: Stripe, Inc. | オリジナル出所URL ↗

該当セクション・タイムスタンプ: Idempotent requests (Idempotency-Key header; keys can be removed after at least 24 hours)

検証バージョンと日付: Stripe API documentation (Verified: 2026-10-30)

選定理由:

Standard production definition of idempotency keys: Stripe guarantees safe client retries by deduplicating POST requests on a caller-supplied key, the exact mechanism that turns at-least-once retries into effectively-once effects.

ソース前提知識:

HTTP APIs, retries, and side-effect semantics.

安全フォールバック(オフライン回復性):

Idempotency semantics are demonstrated locally with repeated write_report calls and a sha256 dedupe key, no Stripe account needed.

比較対象候補リソースと選定評価 (2)
IETF draft: The Idempotency-Key HTTP Header Field ↗ compared_alternative [IETF Trust / open access]

Standardization-track header specification; Stripe's live documentation is the more concrete deployed example.

AWS Builder's Library: Making retries safe with idempotent APIs ↗ compared_alternative [Amazon site content]

Deep design treatment of idempotent server design; Stripe provides the tighter client-visible contract cited in the exercise.