Review the prerequisites
Suitable for: Readers who can follow a request and its resulting state.
- 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.
Foundation · Understand the concepts
Why valid arguments can still produce an invalid action
Objectives of this level: Construct one request that passes shape checks yet must fail each later gate.
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.
A model can propose order-b and amount_minor=300 in perfectly formed JSON. Shape validation knows that an order ID is a string; it does not know that order-b belongs to tenant-b. A tenant-a session therefore cannot authorize this request. Supplying tenant_id=tenant-b inside the arguments only adds another untrusted assertion.
Separate five questions. Is the request complete and typed? Are units and cross-field business rules valid? May this authenticated actor act on this resource? Is the current resource version and remaining amount compatible with the proposal? Did the authority actually commit an effect and record a receipt? Passing an earlier gate cannot answer a later question.
Use integer minor units with an explicit currency in this lab. 300 USD minor units means 3 USD; a bare 3 has no safe default unit. The Python check rejects bool as well as float because isinstance(True, int) would otherwise accept it. JSON Schema's required/closed-property rules describe structure; object ownership remains an application decision. Object constraints.
The runtime's call ID identifies a model-turn exchange. A durable operation ID identifies the business action across recovery. Two legitimate partial refunds need two operation IDs; two deliveries of one refund need the same ID. Neither an operation ID nor a tool description grants permission.
Fixed inputs for the gate table
The trusted caller is tenant-a/user-a with refund:write. Initially order-a belongs to tenant-a, has remaining_minor=1000, resource version 1 and currency USD; order-b belongs to tenant-b. The complete normal request is:
{"schema_version":2,"operation_id":"refund-1","order_id":"order-a","amount_minor":300,"currency":"USD","expected_version":1}
Use a fresh authority for cases 1–3. Cases 4–5 first commit that normal request, leaving remaining_minor=700 and version 2.
- Add tenant_id=tenant-b: the exact field set fails shape_fields. No effect or resource lookup is needed.
- Set amount_minor=true: the integer check fails shape_integer. A Boolean is not money.
- Set order_id=order-b: shape passes but authorization fails. The public denial does not return the other tenant's balance.
- Submit operation_id=refund-2 with expected_version=1: authorization passes, but a new action's state precondition fails resource_version.
- Deliver refund-1 once, then lose its response: no business gate necessarily failed. The caller's observation is unknown. Reconcile the unchanged operation and receive replayed with its original receipt; do not create refund-2 to solve a missing acknowledgment.
Here “business authority” means the service owning the order state and committing its effect; a gate is a required check, not a prompt preference.
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 second valid action is not a retry
Two separately requested refunds of 300 each need distinct operation IDs and state versions 1 then 2. With both authorized and enough balance, they legitimately leave two receipts and remaining_minor=400. A global rule that permits only one refund per order would incorrectly reject this second action; uniqueness is scoped to the business intent.
Acceptance task for this level
Using the five fixed inputs in this body, produce a gate table with trusted inputs, earliest rejection or uncertainty boundary, observed state, and allowed next action. For acknowledgment loss explicitly allow no rejected business gate.
Reading this browser’s record…
Hide the answer and check your understanding
A model request has a valid operation ID and schema, but names another tenant's order. Which additional value would make it executable?
Expand reference derivation
No model-supplied value can grant access. The executor must obtain authenticated identity and a current object-specific authorization decision from trusted state. If that decision is absent, deny; do not keep guessing IDs.
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