Review the prerequisites
Suitable for: Developers comfortable with Python dictionaries and local SQL transactions.
- Schema
- A contract describing field shapes, types, and constraints. Valid fields do not establish that the caller is authorized to perform the action.
- Trusted context
- Identity and tenant information obtained through server-side authentication. Do not directly trust identity values supplied by the model.
- Side effect
- A write to the external world, such as a payment, publication, or deletion.
- State version
- The version of a resource's current state, used to detect changes since the check.
How does the mechanism work?
- 1Model
Proposes a tool name, arguments, and call_id. All are candidate inputs.
- 2Runtime
Checks the allowlist, completeness, shared budget, and arguments. A failed check stops the action.
- 3Business service
Reads identity from a trusted session; checks resource ownership and current permissions, then state at the commit boundary.
- 4Tool adapter
Correlates success, failure, or unknown receipts by call_id and preserves facts that already occurred.
- 5Acceptance
Adds the receipt to the next input; checks the final answer against facts before reporting business completion.
Valid structure grants no permission. call_id correlates a call in this turn; it cannot replace a business operation key across recovery.
Step-by-step explanation
- Candidate parameters
The model proposes actions and parameters.
- Structure and semantics
Check fields, types, units, and constraints relating them.
- Identity and state
Check actual permissions and the current business state.
- Execution and receipt
Execute conditionally and verify the results and business evidence.
Implementation · Build it
Implement a local authority with effect and receipt in one transaction
Objectives of this level: Run the typed dispatcher and reconcile a repeated operation against its stored payload and receipt.
Visual guide · Fresh effects pass separate gates
This is the fresh-action path. Authorized receipt replay is checked before new resource preconditions; the local transaction does not include remote payments. Select the figure to open it at full size.
Download the core experiment bundle on a computer and extract the agent-core-deep-dive-v1 folder. Install Python 3.9+ with its standard library, open a terminal in that folder and run:
python3 -B tool_contract_deep_dive.py > tool_contract_deep_dive.results.json
python3 -B -m unittest discover -v
Open the saved JSON and compare its statuses/counts with the worked example in this body. The implementation and debugging snippets run from the same extracted folder; the bundle includes every imported module. Save the body’s Python snippet as a .py file in that folder and run python3 -B your_file.py; its printed output is stated beside it. The source can also be downloaded at https://ai.lwkjob.com/lab/deep-dive/tool_contract_deep_dive.py. The engineering route continues the same complete after-sales Agent project; full stages are in that package's README.
Download the lab bundle, extract it, and run python3 -B tool_contract_deep_dive.py. It needs Python 3.9+ and the standard library. The downloaded tool_contract_deep_dive.py contains a SQLite authority with orders and an effects table whose primary key is (tenant, operation_id).
The executor first validates an exact field set, integer types, contract version, currency and limits. Its Context is created by the trusted caller. It starts BEGIN IMMEDIATE, reads the tenant-owned order and checks scope, then looks up an earlier receipt. Matching payload and actor return that receipt; reuse of the key for a different amount returns idempotency_conflict. A new intent must match the resource version and remaining amount. The conditional update and receipt insert commit together.
The digest includes a fixed domain, tenant, actor and the complete v2 request. It compares identity; it is not a signature or a secret capability. Permission is checked before replay so a receipt lookup does not bypass access checks. Retries keep the original expected_version because the stored receipt is checked before evaluating a new state transition.
This placement is a local guarantee: both the remaining balance and receipt live in the same SQLite transaction. BEGIN IMMEDIATE can encounter a busy writer; a real adapter needs bounded handling of that condition. It cannot make an HTTP payment join this transaction. SQLite transaction semantics.
A complete worked run
Visual guide · Replay a matching receipt
Current access is checked before replay. Matching retries keep the original expected version; changed payloads conflict instead of executing again. Select the figure to open it at full size.
Run from the extracted bundle:
from tool_contract_deep_dive import Executor, Context, request
e = Executor()
ctx = Context('tenant-a', 'user-a')
first = e.execute(ctx, request())
retry = e.execute(ctx, request())
assert first['status'] == 'committed'
assert retry['receipt'] == first['receipt']
assert e.state() == {'remaining_minor': 700, 'effect_count': 1}
print(retry['status'], e.state()['effect_count'])
e.close()
Actual output: replayed 1. The balance row and effect count, not the text of a success message, establish the local result.
State lifetime and an independent extension
Executor() uses a new in-memory database. The standalone module closes that database when it finishes. Its saved JSON is evidence, not a persistent service checkpoint. Start the worked script above from a fresh folder process; keep the same e instance open for your task. After its first/refund-1 replay, add the changed amount and second-refund calls before e.close(). Creating a new Executor for only refund-2 would start at version 1 and correctly reject expected_version=2.
Then implement normalize_v1 in your own file. Its only accepted old shape is schema_version=1, operation_id, order_id, integer amount_cents and expected_version; this pinned v1 contract means USD. Produce a v2 request with the same operation ID/resource/precondition, amount_minor=amount_cents and currency=USD. Reject true, 3.5, extra fields and unknown versions instead of guessing units. This adapter practice does not authorize an action or change an existing approval.
One failed proposal through six concrete gates
Visual guide · Why o-100 never acquired a proposal receipt
Historical task live-20261030-ordinary: a valid call reached evidence validation, then stopped before saving a proposal or its receipt. Read receipts do not prove a business effect. Select the figure to open it at full size.
Follow the actual live-20261030-ordinary task rather than replacing it with a success example. The final provider object calls propose_return with order_id="o-100", quantity=1, reason="It does not fit", policy_ids=["d-general"] and call_id="call_ccAgBPjXEzAOTe3IbQ6UO2Iy". The exact keys and types pass shape validation. The call ID identifies delivery of this tool call; it is not merchant authority or a completed-return identity.
The task is bound to authenticated tenant="acme", owner="alice". Its authorized order is ordinary, 8 days old, with purchased quantity 2; order_id matches the task. The recorded memory version and policy version are both 1. Read the actual retrieve_policy result: context_ids=["d-general","d-battery","d-proof"]. Thus proof was delivered; this failure did not originate in retrieval coverage.
The proposal cites only general. validate_evidence(..., for_proposal=True) requires general+proof and raises missing_policy_evidence before constructing or saving a proposal. The observed end state is failed, proposal=null, approval=null, receipt=null, with two saved read-tool receipts (get_order, retrieve_policy) and no propose_return receipt. Those read receipts prove retrieved observations, not a return application. Quantity 1 is within the purchased quantity, but execution stopped at evidence coverage before the later quantity/reason guard: do not describe every later check as executed.
In the repaired runtime, eligible also needs a saved propose_return result whose proposal and proposal_hash match current state. Even that only reaches awaiting_approval; an independent merchant approval and execution receipt are later boundaries. Keep candidate validation, local proposal receipt and merchant effect receipt distinct.
Evidence: original task trace, original run ledger, and runtime gate implementation. The replay ledger binds old/new source hashes; its unchanged ordinary output still fails, so exposing the contract does not retroactively fix a model's missing citation.
Continue in one runnable project: evidence, approval and receipt are separate
Follow Harness Journey through model/proposal and recovery. This connected project creates a fictional return request, not a refund. Selected d-general and d-proof support an ordinary proposal; finding a document among retrieval candidates alone does not make it citable. A saved local proposal-tool receipt means the proposal was accepted for approval. Only a bound, authoritative merchant receipt establishes the business effect.
Run python3 -B journey.py scenario --name evidence_missing --work /tmp/journey-evidence, then forged_receipt in another fresh directory. Both continue through the same approved return path after the negative probe. The source ZIP includes the actual merchant HTTP boundary and independent persisted-state verifier.
Continue the connected project article and inspect the executable entrypoint.
Tool evidence needs separate fact and derivation contracts
Continue section11. Direct facts cite tool-returned records; business eligibility follows current registered rules and validated facts. A real record ID cannot prove an arbitrary conclusion. Separate atomic_claims/derived_claims and check trust/scope/freshness, rule versions and exact premises. A proof pass still requires separate merchant proposal, approval and effect/receipt boundaries.
See project section11, walkthrough and single contract definition.
Review action wording against authoritative effect evidence
Section12 separates eligibility, proposal, approval and completed effect. Review claims such as “refunded,” “approved” or “receipt issued” against authoritative facts. A structured contract pass is not a merchant effect. Record quoted wording, actual stage, actor scope and evidence location; merchant boundaries still decide authority.
See section12, review form and workflow.
Retain original action facts while revising prose
The same LAB-001 task revises authored “refund completed” prose back to eligibility while structured facts/proof stay unchanged. It establishes no executed merchant effect. Snapshots run the original review.py without disabling checker/source validation. The correction is authored, not a new provider response.
See section 13 and the walkthrough.
Keep proposed prose separate from original tool facts
Learners submit proposed prose and assessment outside the source package. Original responses, structured facts and tool evidence stay unchanged. Mechanical checks concern the original packet and do not freshly prove a revised decision. Changing prose cannot restore denied access or refresh historical MCP authority.
See section 14 and the learner instructions.
Run experiments and observe counterexamples
Authored requests; actual local SQLite shape/authority/state/receipt checks. No model or external payment execution.
Python 3.10+ · Runs by default using only the standard library · Runs on your computer
- Run the module and identify each gate in events.
- Run ToolContractTests, including reopen and duplicate connections.
- Compare business state and stored receipts, then state the remote-service boundary.
python3 -B tool_contract_deep_dive.pyView the entry-point script
"""Offline tool-boundary experiment. SQLite is the local business authority.
No model, payment API, network, or distributed exactly-once claim. Python 3.9+.
"""
import hashlib
import json
import sqlite3
from dataclasses import dataclass
@dataclass(frozen=True)
class Context:
tenant: str
actor: str
scopes: tuple = ('refund:write',)
FIELDS = {'schema_version', 'operation_id', 'order_id', 'amount_minor', 'currency', 'expected_version'}
def validate_shape(request):
if type(request) is not dict or set(request) != FIELDS:
return 'shape_fields'
if any(type(request[k]) is not int for k in ('schema_version', 'amount_minor', 'expected_version')):
return 'shape_integer' # bool is not an amount, even though isinstance(True, int).
if any(type(request[k]) is not str or not 1 <= len(request[k]) <= 80 for k in ('operation_id', 'order_id', 'currency')):
return 'shape_string'
if request['schema_version'] != 2:
return 'contract_version'
return None
def fingerprint(context, request):
envelope = {'domain': 'refund/v2', 'tenant': context.tenant, 'actor': context.actor, 'request': request}
return hashlib.sha256(json.dumps(envelope, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()
class Executor:
def __init__(self, path=':memory:'):
self.db = sqlite3.connect(path, timeout=5, isolation_level=None)
self.db.executescript('''
CREATE TABLE IF NOT EXISTS orders(id TEXT PRIMARY KEY, tenant TEXT, remaining INTEGER, version INTEGER, currency TEXT);
CREATE TABLE IF NOT EXISTS effects(tenant TEXT, operation_id TEXT, digest TEXT, result TEXT,
PRIMARY KEY(tenant, operation_id));
INSERT OR IGNORE INTO orders VALUES('order-a','tenant-a',1000,1,'USD');
INSERT OR IGNORE INTO orders VALUES('order-b','tenant-b',1000,1,'USD');
''')
def close(self):
self.db.close()
def execute(self, context, request):
error = validate_shape(request)
if error:
return {'status': 'denied', 'gate': error}
if not 0 < request['amount_minor'] <= 1000 or request['currency'] != 'USD' or request['expected_version'] < 1:
return {'status': 'denied', 'gate': 'business_parameters'}
digest = fingerprint(context, request)
# __exit__ receives this block's outcome, not an exception currently
# handled by the caller (e.g. a recovery inside except TimeoutError).
with self.db:
self.db.execute('BEGIN IMMEDIATE')
row = self.db.execute('SELECT tenant,remaining,version,currency FROM orders WHERE id=?', (request['order_id'],)).fetchone()
# Do not distinguish guessed foreign IDs from missing resources in the public error.
if 'refund:write' not in context.scopes or not row or row[0] != context.tenant:
return {'status': 'denied', 'gate': 'authorization'}
prior = self.db.execute('SELECT digest,result FROM effects WHERE tenant=? AND operation_id=?',
(context.tenant, request['operation_id'])).fetchone()
if prior:
if prior[0] != digest:
return {'status': 'denied', 'gate': 'idempotency_conflict'}
return {'status': 'replayed', 'receipt': json.loads(prior[1])}
if row[2] != request['expected_version']:
return {'status': 'denied', 'gate': 'resource_version'}
if row[1] < request['amount_minor'] or row[3] != request['currency']:
return {'status': 'denied', 'gate': 'business_state'}
cursor = self.db.execute('UPDATE orders SET remaining=remaining-?,version=version+1 WHERE id=? AND version=?',
(request['amount_minor'], request['order_id'], request['expected_version']))
if cursor.rowcount != 1:
raise RuntimeError('state compare-and-swap failed')
receipt = {'operation_id': request['operation_id'], 'amount_minor': request['amount_minor'],
'currency': request['currency'], 'resource_version': row[2] + 1}
self.db.execute('INSERT INTO effects VALUES(?,?,?,?)',
(context.tenant, request['operation_id'], digest, json.dumps(receipt, sort_keys=True)))
return {'status': 'committed', 'receipt': receipt}
# The connection context commits effect and receipt on normal exits,
# including return; exceptions from this transaction roll it back.
def state(self):
return {'remaining_minor': self.db.execute("SELECT remaining FROM orders WHERE id='order-a'").fetchone()[0],
'effect_count': self.db.execute('SELECT COUNT(*) FROM effects').fetchone()[0]}
def request(**changes):
return dict({'schema_version': 2, 'operation_id': 'refund-1', 'order_id': 'order-a',
'amount_minor': 300, 'currency': 'USD', 'expected_version': 1}, **changes)
def demo():
executor, context = Executor(), Context('tenant-a', 'user-a')
foreign = request(order_id='order-b')
events = [
{'case': 'foreign_order', 'shape_valid': validate_shape(foreign) is None, 'result': executor.execute(context, foreign)},
{'case': 'model_tenant', 'result': executor.execute(context, dict(request(), tenant_id='tenant-b'))},
{'case': 'bool_amount', 'result': executor.execute(context, request(amount_minor=True))},
{'case': 'too_large', 'result': executor.execute(context, request(amount_minor=1001))},
{'case': 'invalid_version', 'result': executor.execute(context, request(expected_version=0))},
{'case': 'valid', 'result': executor.execute(context, request())},
{'case': 'retry', 'result': executor.execute(context, request())},
{'case': 'changed_retry', 'result': executor.execute(context, request(amount_minor=301))},
{'case': 'new_operation_old_version', 'result': executor.execute(context, request(operation_id='refund-2'))},
]
result = {'origin': 'authored_requests_local_sqlite', 'events': events, 'final': executor.state(),
'boundary': 'One local SQLite authority; a remote side effect needs its own idempotency and reconciliation protocol.'}
executor.close()
return result
if __name__ == '__main__':
print(json.dumps(demo(), indent=2, sort_keys=True))
Expected output when running locally
{
"boundary": "One local SQLite authority; a remote side effect needs its own idempotency and reconciliation protocol.",
"events": [
{
"case": "foreign_order",
"result": {
"gate": "authorization",
"status": "denied"
},
"shape_valid": true
},
{
"case": "model_tenant",
"result": {
"gate": "shape_fields",
"status": "denied"
}
},
{
"case": "bool_amount",
"result": {
"gate": "shape_integer",
"status": "denied"
}
},
{
"case": "too_large",
"result": {
"gate": "business_parameters",
"status": "denied"
}
},
{
"case": "invalid_version",
"result": {
"gate": "business_parameters",
"status": "denied"
}
},
{
"case": "valid",
"result": {
"receipt": {
"amount_minor": 300,
"currency": "USD",
"operation_id": "refund-1",
"resource_version": 2
},
"status": "committed"
}
},
{
"case": "retry",
"result": {
"receipt": {
"amount_minor": 300,
"currency": "USD",
"operation_id": "refund-1",
"resource_version": 2
},
"status": "replayed"
}
},
{
"case": "changed_retry",
"result": {
"gate": "idempotency_conflict",
"status": "denied"
}
},
{
"case": "new_operation_old_version",
"result": {
"gate": "resource_version",
"status": "denied"
}
}
],
"final": {
"effect_count": 1,
"remaining_minor": 700
},
"origin": "authored_requests_local_sqlite"
}- foreign_order passes shape and fails authorization.
- valid commits 300; retry replays; changed_retry is denied.
- Final remaining_minor=700 and effect_count=1.
code example
A representation change can change intent identity
Try refund-1 with only expected_version changed to 2 after it committed. It returns idempotency_conflict, not a new successful refund. The version is part of the normalized request fingerprint; reading current state is appropriate for a new action, not for rewriting the payload of an old retry.
Acceptance task for this level
In one fresh script and one Executor instance, commit/replay refund-1, try its changed amount 301, then submit refund-2 with expected_version=2 and amount_minor=400. Independently implement normalize_v1 for the exact pinned USD-cents input above and save accepted/rejected conversion fixtures. Continue evidence-v2 practice; preserve the original failure, your own repair and unchanged-checker results. Complete semantic-review practice, separating teaching references, declaration completeness and actual human signoff. Replay the same-task review cycle, preserving initial reviews, stale-binding rejection and fresh records. Complete three source review exercises, preserving submissions, revisions and manual comparisons.
Reading this browser’s record…
Hide the answer and check your understanding
Why does retrying the original request still work after the first refund increments the order version?
Expand reference derivation
It is a receipt reconciliation for the same intent. After current authorization, the executor finds the matching stored payload before testing the precondition for a new effect. A different operation has no receipt and must use current state.
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.
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.
- JSON Schema: object properties and required fields
- OWASP: object-specific authorization
- SQLite: transactions
- Local tool experiment and actual results
- Core experiments: download and run on a computer
- Complete after-sales Agent project: run on a computer
- Decision-specific evidence contract repair
- Harness Journey: one connected practical project
- Bilingual project guide and fault exercises
- Harness Journey source ZIP
- Atomic facts and rule derivations
- Versioned evidence contracts and preserved raw records
- Human semantic review practice
- Zero-request rubric, forms and trace-grounded cases
- Same-task review and repair cycle
- Zero-request cycle execution evidence
- Source-based review practice
- Learner exercise execution evidence