# Walkthrough: preserve one return while its worker changes

[README](README.md) · [中文走读](WALKTHROUGH.zh.md) · [Fault exercises](EXERCISES.md)

Use the directory containing `journey.py`. Every fresh run uses task `journey-return` and business key `return:journey-return:v1` in its own separate ledgers. Repeated fixture IDs in separate work directories are not repeated business actions in one merchant database. All model decisions are authored offline. This walkthrough explains the executable contract; the [frozen evidence index](https://ai.lwkjob.com/research-evidence/harness-journey/README.md) holds exact executed outputs and source hashes.

## Predict the interrupted result

Before running anything, write down your predictions: Does a missing HTTP response prove failure? Does an accepted proposal prove a merchant return exists? Can a new worker spend another reservation? Can an old event or old worker change current state? Which database could answer each question?

```sh
python3 -B journey.py scenario --name lost_response --work /tmp/journey-stop --stop-after-unknown
python3 -B journey.py inspect --work /tmp/journey-stop --task-id journey-return
python3 -B journey.py verify --work /tmp/journey-stop
```

The scenario command reaches the deliberate checkpoint and exits 0. The verifier exits 1 while the work remains unresolved. Preserve both outputs. A verifier failure at this checkpoint is evidence of incomplete recovery, not proof that the committed merchant write failed. Read the actual failed assertion names; do not substitute a copied green report.

<a id="model-and-proposal"></a>

## Model, evidence and proposal

The execution-stage queue does not reserve the entire model/retrieval phase in this lab. The authored model path and approved proposal are prepared before the execution claim. This scopes the synthetic units to the local execution stage, not all work done by an Agent.

`fallback.py` records one authored primary `429:rate_limited`, a simulated `wait:1:simulated`, and the selected backup's bounded normal Agent turns. A single fallback decision does not mean a single total model turn. `journey_model_attempts.source` is `offline_fixture`; request/response digests bind the local adapter inputs/outputs. No provider requests or provider timing are measured. The normal Agent turn/tool limits still apply. Read the `request_digest` alongside the saved Agent transcript to follow the actual prior tool facts into the backup.

The ordinary return needs selected `d-general` and `d-proof`, a current authorized order, valid quantity/reason and a saved `propose_return` result matching `proposal_hash`. A retrieved candidate outside selected context cannot be cited. `proposal_json` is a proposed action; the local proposal-tool receipt means accepted for approval. `approval_json` names the fixture reviewer approval. None of these alone proves a merchant effect.

Read `tasks/journey-return.sqlite` fields `tasks.retrieval_json`, `proposal_json`, `proposal_hash`, `approval_json`, `transcript_json` and `tool_receipts.result_json`. Then compare the merchant `approvals` row. Approval binds the task/proposal version/hash; the model does not author it.

<a id="queue-and-events"></a>

## Queue admission and durable events

`Workflow.acquire_next()` chooses tenant FIFO heads using a persisted tenant cursor, then reserves under `BEGIN IMMEDIATE`. The transaction rechecks current ACL, global/tenant held slots and remaining synthetic units before advancing `journey_scheduler.cursor`. A held unknown counts as occupied capacity. Recovery is different from new admission: it retains the reservation ID and amount.

The workflow event stream uses `{event_id, seq, status, source}` with trusted source `executor`. `Workflow.apply()` checks tenant before replay, then checks an existing identity's digest before applying new sequence/transition rules. An identical old event returns its saved receipt; it must not reset the present snapshot. Same ID/different body is `event_conflict`; a new event using an already consumed sequence is `sequence_conflict`; a skipped sequence is `sequence_gap`. Snapshot, cursor and event/receipt rows commit together. These local transactions cannot undo the merchant HTTP effect.

Read `journey_workflows.snapshot_json`, `cursor` and `journey_transition_events.event_json`, `digest`, `receipt_json`. Runtime audit events live separately in `rt_events`; they are observations, not executor transition sequence numbers.

## Commit, lose the response, preserve unknown

The worker calls the actual loopback merchant through `RuntimeClient`. The fresh return write includes the runtime epoch, worker and reservation; the merchant checks those in the same SQLite transaction as its return/receipt insert. Agent execution also checks a receipt under the original operation key before attempting a new write.

The deliberate failure occurs after merchant commit. The response disappears and the child exits 75. The controller records unknown while preserving its reservation and synthetic units. At this moment, inspect both sides: merchant `returns` and `receipts` can already prove the effect, while Agent/runtime state has not yet reached completed. A crash exit is not a second return and is not proof of no effect.

[![Recover the original committed effect](figures/recovery-sequence-en.svg)](figures/recovery-sequence-en.svg)

*Authored sequence diagram. [Open full size](figures/recovery-sequence-en.svg). Read the databases and executed evidence separately.*

<a id="migration-and-recovery"></a>

## Upgrade, fence, reconcile and settle

```sh
python3 -B journey.py resume --work /tmp/journey-stop
python3 -B journey.py inspect --work /tmp/journey-stop --task-id journey-return
python3 -B journey.py verify --work /tmp/journey-stop
```

Use exactly the same `verify --work /tmp/journey-stop` before and after repair. Resume preserves the original task/key and waits for an expired claim before migration. A live old executor is refused with `migration_live_worker`. The v1→v2 envelope maps `unknown` to `reconcile_required`; it preserves `operation_key`, approval fields, `budget_used` and extensions while incrementing the worker epoch. `budget_used` is a preserved legacy envelope field (0 in this fixture), not current execution spend; use `rt_budget.spent` and `rt_costs` for that accounting. This is semantic workflow migration, distinct from Agent SQL `PRAGMA user_version` and source fingerprints.

The new worker recovers the existing reservation, queries the original merchant receipt and saves the bound receipt in the Agent checkpoint. `Runtime.settle()` compares that receipt against the merchant `receipts` row and actual synthetic usage against `rt_costs` before invoking `decide_settlement(payload)`. The learner policy cannot make an invented receipt authoritative.

The ordinary completed path has reserved units 5 and confirmed synthetic usage 3: the contract charges 3 and releases 2. Those are declared fixture units. They are not model billing or a refund. The final verifier independently checks completed layers, one effect/receipt/usage row, receipt equality/bindings, one admission and settlement, unknown hold, migration/recovered audit, contiguous executor history, budget conservation and source fingerprints. The detailed checks are in [acceptance.py](acceptance.py).

<a id="storage-map"></a>

## Storage map

| File/table | Exact fields to inspect | Evidence boundary |
| --- | --- | --- |
| `shared.sqlite` / `rt_tasks` | `id`, `tenant`, `owner`, `operation_key`, `state`, `epoch`, `worker`, `expires`, `reservation_id`, `reserved_units`, `actual_units`, `receipt_json` | Current execution claim and reservation; a state label alone is insufficient |
| `rt_budget` | `tenant`, `total`, `reserved`, `spent`, `frozen` | Synthetic unit conservation and overrun freeze |
| `rt_acl` / `users` | `active`, owner/tenant binding | Current runtime and merchant authority |
| `journey_scheduler` | `id`, `cursor` | Persisted round-robin position |
| `journey_workflows` | `task_id`, `workflow_schema`, `snapshot_json`, `worker_epoch`, `cursor` | Semantic workflow state; not Agent SQL version |
| `journey_transition_events` | `task_id`, `event_id`, `seq`, `digest`, `event_json`, `receipt_json` | Durable executor delivery identity and receipt |
| `journey_model_attempts` | `task_id`, `model_label`, `source`, `status`, `request_digest`, `response_digest` | Authored routing/adapter audit, not provider quality |
| `returns`, `receipts`, `approvals` | Task/order/tenant/owner, proposal binding; `receipts.operation_key`, `result_json` | Merchant authority for business effect and approval |
| `rt_costs` | `operation_key`, `synthetic_units` | Authoritative local fixture usage |
| `rt_events` | `task_id`, `event`, `value_json`, `at` | Admission, hold, migration, recovery and settlement audit |
| `tasks/journey-return.sqlite` / `tasks` | `status`, `proposal_json`, `proposal_hash`, `approval_json`, `operation_key`, `receipt_json`, `fence` | Agent checkpoint, distinct from merchant history |
| Agent `tool_receipts` | `task_id`, `call_id`, `name`, `args_hash`, `result_json` | Tool delivery identity; not business operation identity |
| `run.json` / `report.json` | Source fingerprints / observed assertions | Run binding / navigation; neither replaces storage verification |

Use the Python standard library to inspect key rows without requiring the optional `sqlite3` shell. This opens files read-only and does not repair them:

```sh
python3 - /tmp/journey-stop <<'PY'
import json, sqlite3, sys
from pathlib import Path
work = Path(sys.argv[1]).resolve()
for file, sql in [
    ('shared.sqlite', 'SELECT id,state,operation_key,epoch,reservation_id,reserved_units,actual_units FROM rt_tasks'),
    ('shared.sqlite', 'SELECT task_id,workflow_schema,snapshot_json,worker_epoch,cursor FROM journey_workflows'),
    ('shared.sqlite', 'SELECT task_id,event_id,seq,digest,receipt_json FROM journey_transition_events ORDER BY seq'),
    ('shared.sqlite', 'SELECT operation_key,result_json FROM receipts'),
    ('tasks/journey-return.sqlite', 'SELECT id,status,operation_key,proposal_hash,approval_json,receipt_json FROM tasks')]:
    db = sqlite3.connect((work / file).as_uri() + '?mode=ro', uri=True)
    db.row_factory = sqlite3.Row
    print(file, sql)
    print(json.dumps([dict(r) for r in db.execute(sql)], ensure_ascii=False, indent=2))
    db.close()
PY
```

## Diagnose the earliest failed boundary

| Symptom | First comparison | Do not infer |
| --- | --- | --- |
| Queue looks alternating but a held tenant enters again | Cursor, actual `rt_tasks` reservation holds, global/tenant limits | Printed schedule is atomic admission |
| Replay moves the state backward | Original identity/digest and current cursor | Every old transition is a new instruction |
| v2 is readable but retry uses a new key | Before/after envelope, approval binding and epoch | Deserialization proves business compatibility |
| Backup produces a draft but no approved proposal | Selected evidence, saved proposal-tool receipt and approval | Valid JSON or fallback success proves completion |
| Child crashes after return write | Independent receipt under original operation key | Missing response means no write occurred |
| Receipt-shaped JSON cannot settle | Merchant row equality and `rt_costs` | Worker-supplied receipt is authoritative |
| Green saved report but verifier fails | Read-only storage assertions and source fingerprints | Report status overrides corrupted/missing rows |

The [exercises](EXERCISES.md) turn these comparisons into repeatable fault probes and a red→repair→same-check path. Preserve outputs from before a change. Do not alter the grader, add `passed: true`, delete business history or silently weaken a denial to obtain green.
