Review the prerequisites
Suitable for: Developers comfortable with Python dictionaries and local SQL transactions.
- Proposal envelope
- Trusted tenant/actor, operation identity, tool version and normalized action arguments captured for review.
- Approval digest
- A hash identifying exactly which proposal was reviewed; integrity comparison alone does not authenticate an approver.
- Permission epoch
- A trusted authorization generation that changes when a permission is revoked or regranted.
- Receipt replay
- An authorized lookup of an already committed operation result; it does not dispatch a second effect.
How does the mechanism work?
- 1Requester
Propose typed arguments under authenticated context.
- 2Intent store
Freeze normalized semantics and a durable operation ID.
- 3Reviewer
Approve the exact digest with current review authority.
- 4Executor
Check digest, permission/epoch, expiry and resource preconditions.
- 5Business authority
Commit one effect and receipt, or reconcile an existing receipt.
Digest identity, authorization and deduplication are separate predicates. The lab shares one SQLite authority; the design layer changes this constraint.
Step-by-step explanation
- Freeze
Normalize units, targets and resource preconditions before review.
- Approve
A separately authorized reviewer acknowledges that digest before expiry.
- Recheck
Compare submitted semantics, current permissions, epoch and resource version.
- Commit or reconcile
Write one local effect and receipt, or preserve unknown for external reconciliation.
Implementation · Build it
Freeze and execute an immutable proposal
Objectives of this level: Run the complete prepare/approve/execute flow with normalized arguments and an atomic local receipt.
Visual guide · Approval binds a fixed intent
A digest identifies reviewed semantics, not an approver credential. The local transaction covers authority checks and effect commit, not a remote service. 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 approval_deep_dive.py > approval_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/approval_deep_dive.py. The engineering route continues the same complete after-sales Agent project; full stages are in that package's README.
Run python3 -B approval_deep_dive.py from the bundle. prepare accepts identity from a trusted caller, validates integer amount and explicit currency, snapshots the permission epoch and saves a canonical envelope. It does not execute a refund. approve checks a reviewer role and matches the digest stored for that tenant/operation.
The canonical profile allows strings and integers with sorted keys and fixed separators. It intentionally rejects floats and unknown fields; this is not a general cross-language JSON canonicalization standard. A production cross-language signer should specify one canonical format and business normalization profile, including defaults, arrays, Unicode and amount units.
execute starts a local write transaction. It checks the current requester permission, epoch, stored envelope, submitted digest, approval state, reviewer status, expiry and resource version. A done operation may replay its receipt after expiry if current access and unchanged identity still hold; no new effect is dispatched. A new execution debits the resource, inserts a unique effect and marks the proposal done in one transaction.
The caller must never trust model-supplied actor, approved, permissions or destination routing. The lab uses authored trusted identities to expose the boundary; it does not implement login, an approval UI or cryptographic approver authentication. The example's authority tables share SQLite, so a revocation committed before execution begins is observed by that execution.
Prepare, review and dispatch in one instance
Visual guide · Who proposes, reviews and commits
Prepare and approve create no business effect. A repeated done operation returns its bound receipt after current access checks; it does not debit again. Select the figure to open it at full size.
from approval_deep_dive import ApprovalService, ARGS
s = ApprovalService()
checksum = s.prepare('tenant-a', 'user-a', 'refund-1', ARGS)
s.approve('tenant-a', 'refund-1', 'reviewer-a', checksum)
assert s.state()['effect_count'] == 0
print(s.db.execute("SELECT envelope FROM proposals WHERE operation_id='refund-1'").fetchone()[0])
first = s.execute('tenant-a', 'user-a', 'refund-1', ARGS)
again = s.execute('tenant-a', 'user-a', 'refund-1', ARGS)
assert first['status'] == 'committed'
assert again['receipt'] == first['receipt']
assert s.state() == {'effect_count': 1, 'remaining_minor': 700}
print(again['status'], s.state()['effect_count'])
s.close()
Run this single script from a fresh process in the extracted folder. It prints the stored normalized envelope, then replayed 1. Preparation/approval have no effect; both dispatches share one authority instance. Every new ApprovalService() without a path starts a separate in-memory database.
Reviewer revocation has its own generation
The requester permission_epoch and the reviewer's approver_epoch are separate. The approval record captures the reviewer's current epoch; execute checks that it still matches. Revoking and regranting approve authority increments that epoch. The old approval then returns approver_permission_epoch_changed instead of silently becoming valid again. Renew review through an explicitly authorized new proposal/operation; do not overwrite the old review record in place.
Implement recovery_decision(result) independently in your own file: committed/replayed means verify the same receipt; permission_revoked, permission_epoch_changed, approver_permission_epoch_changed or proposal_changed means stop automatic dispatch and obtain the appropriate current decision; a hypothetical remote unknown means reconcile the original operation. This helper is a recovery policy, not a permission issuer.
Run experiments and observe counterexamples
Authored approval schedules and real local SQLite state transitions; no login, signed capability, network or external refund provider.
Python 3.10+ · Runs by default using only the standard library · Runs on your computer
- Run the isolated mutation, revocation, expiry and resource-version schedules.
- Compare stored proposal identity and actual local effect counts.
- Run ApprovalTests for replay and duplicate connections.
python3 -B approval_deep_dive.pyView the entry-point script
"""Immutable approval and local atomic execution; offline teaching fixture.
Permission epoch, resource version, digest, expiry and duplicate dispatch are
checked against a single SQLite authority. No remote service is exercised.
"""
import hashlib
import json
import sqlite3
def normalize(args):
required = {'order_id', 'amount_minor', 'currency', 'expected_version'}
if type(args) is not dict or set(args) != required:
raise ValueError('shape_fields')
if type(args['amount_minor']) is not int or not 0 < args['amount_minor'] <= 1000:
raise ValueError('amount_minor')
if type(args['expected_version']) is not int or args['expected_version'] < 1:
raise ValueError('expected_version')
if args['currency'] != 'USD' or type(args['order_id']) is not str or not args['order_id']:
raise ValueError('business_parameters')
return dict(args)
def digest(envelope):
# This profile permits only strings and integers. It is not general RFC 8785.
return hashlib.sha256(json.dumps(envelope, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()
class ApprovalService:
def __init__(self, path=':memory:'):
self.db = sqlite3.connect(path, timeout=5, isolation_level=None)
self.db.executescript('''
CREATE TABLE IF NOT EXISTS permissions(tenant TEXT, actor TEXT, role TEXT, enabled INTEGER, epoch INTEGER,
PRIMARY KEY(tenant,actor,role));
CREATE TABLE IF NOT EXISTS resources(id TEXT PRIMARY KEY, tenant TEXT, remaining INTEGER, version INTEGER);
CREATE TABLE IF NOT EXISTS proposals(tenant TEXT, operation_id TEXT, actor TEXT, envelope TEXT, digest TEXT,
expires INTEGER, state TEXT, approver TEXT, result TEXT, approver_epoch INTEGER,
PRIMARY KEY(tenant,operation_id));
CREATE TABLE IF NOT EXISTS effects(tenant TEXT, operation_id TEXT, amount INTEGER, PRIMARY KEY(tenant,operation_id));
INSERT OR IGNORE INTO permissions VALUES('tenant-a','user-a','execute',1,1);
INSERT OR IGNORE INTO permissions VALUES('tenant-a','reviewer-a','approve',1,1);
INSERT OR IGNORE INTO resources VALUES('order-a','tenant-a',1000,1);
''')
# Existing local lab databases retain their receipts. An old pending
# approval with no recorded reviewer epoch cannot authorize a new effect.
if 'approver_epoch' not in {row[1] for row in self.db.execute('PRAGMA table_info(proposals)')}:
self.db.execute('ALTER TABLE proposals ADD COLUMN approver_epoch INTEGER')
def close(self):
self.db.close()
def permission(self, tenant, actor, role):
return self.db.execute('SELECT enabled,epoch FROM permissions WHERE tenant=? AND actor=? AND role=?',
(tenant, actor, role)).fetchone()
def prepare(self, tenant, actor, operation_id, args, now=100, expires=200):
# tenant and actor are provided by server authentication, never model text.
normalized = normalize(args)
if type(operation_id) is not str or not 1 <= len(operation_id) <= 80 or expires <= now:
raise ValueError('proposal_parameters')
permission = self.permission(tenant, actor, 'execute')
resource = self.db.execute('SELECT tenant,version FROM resources WHERE id=?', (normalized['order_id'],)).fetchone()
if not permission or not permission[0] or not resource or resource[0] != tenant:
raise ValueError('authorization')
envelope = {'domain': 'refund-approved/v2', 'tenant': tenant, 'actor': actor, 'operation_id': operation_id,
'permission_epoch': permission[1], 'args': normalized}
checksum = digest(envelope)
prior = self.db.execute('SELECT digest FROM proposals WHERE tenant=? AND operation_id=?', (tenant, operation_id)).fetchone()
if prior:
if prior[0] != checksum:
raise ValueError('operation_identity_conflict')
return checksum
self.db.execute('''INSERT INTO proposals
(tenant,operation_id,actor,envelope,digest,expires,state,approver,result)
VALUES(?,?,?,?,?,?,?,?,?)''',
(tenant, operation_id, actor, json.dumps(envelope, sort_keys=True), checksum, expires, 'pending', None, None))
return checksum
def approve(self, tenant, operation_id, approver, approved_digest, now=110):
with self.db:
self.db.execute('BEGIN IMMEDIATE')
permission = self.permission(tenant, approver, 'approve')
if not permission or not permission[0]:
raise ValueError('approver_denied')
row = self.db.execute('SELECT actor,digest,expires,state,approver,approver_epoch FROM proposals WHERE tenant=? AND operation_id=?',
(tenant, operation_id)).fetchone()
if not row or row[1] != approved_digest or now >= row[2] or row[0] == approver:
raise ValueError('approval_invalid')
if row[3] == 'pending':
self.db.execute("UPDATE proposals SET state='approved',approver=?,approver_epoch=? WHERE tenant=? AND operation_id=? AND state='pending'",
(approver, permission[1], tenant, operation_id))
elif row[3] not in ('approved', 'done') or row[4] != approver or row[5] != permission[1]:
raise ValueError('approval_state')
def revoke(self, tenant, actor, role='execute'):
self.db.execute('UPDATE permissions SET enabled=0,epoch=epoch+1 WHERE tenant=? AND actor=? AND role=?', (tenant, actor, role))
def execute(self, tenant, actor, operation_id, proposed_args, now=120):
try:
args = normalize(proposed_args)
except ValueError as error:
return {'status': 'denied', 'reason': str(error)}
with self.db:
self.db.execute('BEGIN IMMEDIATE')
row = self.db.execute('SELECT actor,envelope,digest,expires,state,approver,result,approver_epoch FROM proposals WHERE tenant=? AND operation_id=?',
(tenant, operation_id)).fetchone()
permission = self.permission(tenant, actor, 'execute')
if not permission or not permission[0]:
return {'status': 'denied', 'reason': 'permission_revoked'}
if not row or row[0] != actor:
return {'status': 'denied', 'reason': 'proposal_missing'}
original = json.loads(row[1])
if permission[1] != original['permission_epoch']:
return {'status': 'denied', 'reason': 'permission_epoch_changed'}
submitted = dict(original, args=args)
if digest(submitted) != row[2]:
return {'status': 'denied', 'reason': 'proposal_changed'}
if row[4] == 'done':
return {'status': 'replayed', 'receipt': json.loads(row[6])}
reviewer = self.permission(tenant, row[5], 'approve')
if row[4] != 'approved' or not reviewer or not reviewer[0]:
return {'status': 'denied', 'reason': 'approval_inactive'}
if reviewer[1] != row[7]:
return {'status': 'denied', 'reason': 'approver_permission_epoch_changed'}
if now >= row[3]:
return {'status': 'denied', 'reason': 'approval_expired'}
resource = self.db.execute('SELECT tenant,remaining,version FROM resources WHERE id=?', (args['order_id'],)).fetchone()
if not resource or resource[0] != tenant:
return {'status': 'denied', 'reason': 'resource_denied'}
if resource[2] != args['expected_version']:
return {'status': 'denied', 'reason': 'resource_changed'}
if resource[1] < args['amount_minor']:
return {'status': 'denied', 'reason': 'insufficient_remaining'}
self.db.execute('UPDATE resources SET remaining=remaining-?,version=version+1 WHERE id=? AND version=?',
(args['amount_minor'], args['order_id'], args['expected_version']))
self.db.execute('INSERT INTO effects VALUES(?,?,?)', (tenant, operation_id, args['amount_minor']))
receipt = {'operation_id': operation_id, 'amount_minor': args['amount_minor'], 'resource_version': resource[2] + 1}
self.db.execute("UPDATE proposals SET state='done',result=? WHERE tenant=? AND operation_id=? AND state='approved'",
(json.dumps(receipt, sort_keys=True), tenant, operation_id))
return {'status': 'committed', 'receipt': receipt}
def state(self):
return {'effect_count': self.db.execute('SELECT COUNT(*) FROM effects').fetchone()[0],
'remaining_minor': self.db.execute("SELECT remaining FROM resources WHERE id='order-a'").fetchone()[0]}
ARGS = {'order_id': 'order-a', 'amount_minor': 300, 'currency': 'USD', 'expected_version': 1}
def approved_service(path=':memory:'):
service = ApprovalService(path)
checksum = service.prepare('tenant-a', 'user-a', 'refund-1', ARGS)
service.approve('tenant-a', 'refund-1', 'reviewer-a', checksum)
return service
def demo():
changed = approved_service()
revoked = approved_service()
duplicate = approved_service()
expired = approved_service()
stale = approved_service()
revoked.revoke('tenant-a', 'user-a')
stale.db.execute("UPDATE resources SET version=2 WHERE id='order-a'")
scenarios = [
{'case': 'changed_amount', 'result': changed.execute('tenant-a', 'user-a', 'refund-1', dict(ARGS, amount_minor=800)), 'state': changed.state()},
{'case': 'revoked_after_approval', 'result': revoked.execute('tenant-a', 'user-a', 'refund-1', ARGS), 'state': revoked.state()},
{'case': 'expired', 'result': expired.execute('tenant-a', 'user-a', 'refund-1', ARGS, now=200), 'state': expired.state()},
{'case': 'resource_changed', 'result': stale.execute('tenant-a', 'user-a', 'refund-1', ARGS), 'state': stale.state()},
{'case': 'first_dispatch', 'result': duplicate.execute('tenant-a', 'user-a', 'refund-1', ARGS)},
{'case': 'duplicate_dispatch', 'result': duplicate.execute('tenant-a', 'user-a', 'refund-1', ARGS), 'state': duplicate.state()},
]
for service in (changed, revoked, duplicate, expired, stale):
service.close()
return {'origin': 'authored_approval_schedule_local_sqlite', 'scenarios': scenarios,
'boundary': 'Permission check and effect share one authority. Independent remote authorization needs an execution-side capability/version check.'}
if __name__ == '__main__':
print(json.dumps(demo(), indent=2, sort_keys=True))
Expected output when running locally
{
"boundary": "Permission check and effect share one authority. Independent remote authorization needs an execution-side capability/version check.",
"origin": "authored_approval_schedule_local_sqlite",
"scenarios": [
{
"case": "changed_amount",
"result": {
"reason": "proposal_changed",
"status": "denied"
},
"state": {
"effect_count": 0,
"remaining_minor": 1000
}
},
{
"case": "revoked_after_approval",
"result": {
"reason": "permission_revoked",
"status": "denied"
},
"state": {
"effect_count": 0,
"remaining_minor": 1000
}
},
{
"case": "expired",
"result": {
"reason": "approval_expired",
"status": "denied"
},
"state": {
"effect_count": 0,
"remaining_minor": 1000
}
},
{
"case": "resource_changed",
"result": {
"reason": "resource_changed",
"status": "denied"
},
"state": {
"effect_count": 0,
"remaining_minor": 1000
}
},
{
"case": "first_dispatch",
"result": {
"receipt": {
"amount_minor": 300,
"operation_id": "refund-1",
"resource_version": 2
},
"status": "committed"
}
},
{
"case": "duplicate_dispatch",
"result": {
"receipt": {
"amount_minor": 300,
"operation_id": "refund-1",
"resource_version": 2
},
"status": "replayed"
},
"state": {
"effect_count": 1,
"remaining_minor": 700
}
}
]
}- Changed amount and revoked permission produce zero effects.
- Expiry at 200 and stale resource version block new execution.
- First/duplicate dispatch leave effect_count=1 and remaining_minor=700.
code example
Regrant does not renew an old review
After revoke/regrant of reviewer-a, enabled=True is insufficient: the saved approver_epoch differs from the current epoch. Record approver_permission_epoch_changed. A new authorized proposal/review can proceed under the new epoch, while the old approval remains historical.
Acceptance task for this level
Run the full prepare/approve/execute script above in one service instance and print its frozen envelope/receipt. Before dispatch verify zero effects; after two identical dispatches verify one. Prepare changed amount under refund-1 and record conflict. Independently implement/test recovery_decision for the stated reason/status cases.
Reading this browser’s record…
Hide the answer and check your understanding
Does computing SHA-256 of the model's JSON authenticate the approval?
Expand reference derivation
No. It identifies bytes under a specified normalization profile. Approval authority comes from a trusted reviewer identity and protected approval state or a verifiable credential. Hashing an untrusted approved=true field cannot create either.
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.
All linked explanations and exercises (1 )
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.