Skip to content
Agent Field Notes
Course contentsExpand a topic to choose a lesson.

SYSTEMATIC LEARNING / FOUR-LEVEL COURSE

Approval binding: unchanged intent, current authority and one operation

Review a frozen refund intent, then test changed arguments, permission revocation, expiry, resource changes and duplicate workers.

Learning objectives: Bind approval to exact action semantics and demonstrate why current authorization and duplicate-effect control remain separate execution obligations.

Content checked: 2026-10-11 · Each level has independent explanations, tasks and inspections

Choose a starting point based on your familiarity with this topic. Current level: Debugging · Diagnose failures. After completing the task, continue to the next level. Reading and self-checks alone do not establish mastery.

On this level

Review the prerequisites

Suitable for: Developers who can compare a request, a trace and an authoritative result.

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?

Approval: intent identity and current authority at the effect boundary
  1. 1
    Requester

    Propose typed arguments under authenticated context.

  2. 2
    Intent store

    Freeze normalized semantics and a durable operation ID.

  3. 3
    Reviewer

    Approve the exact digest with current review authority.

  4. 4
    Executor

    Check digest, permission/epoch, expiry and resource preconditions.

  5. 5
    Business 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
  1. Freeze

    Normalize units, targets and resource preconditions before review.

  2. Approve

    A separately authorized reviewer acknowledges that digest before expiry.

  3. Recheck

    Compare submitted semantics, current permissions, epoch and resource version.

  4. Commit or reconcile

    Write one local effect and receipt, or preserve unknown for external reconciliation.

Debugging · Diagnose failures

Reproduce argument mutation, revocation and duplicate delivery

Objectives of this level: Diagnose each rejected branch from its proposal, permission generation and local effect ledger.

Visual guide · Approval binds a fixed intent

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.

The demo creates separate local authorities so faults cannot contaminate each other. changed_amount sends 800 after reviewing 300 and returns proposal_changed. revoked_after_approval disables the requester and returns permission_revoked. expired executes exactly at expires=200 and returns approval_expired. resource_changed increments the resource version and returns resource_changed. Each of these retains 1000 remaining and zero effects.

For mutation, inspect the stored normalized envelope beside the submitted arguments. The root cause is borrowing approval for new semantics. Repair by creating a new intent and review; changing the stored envelope in place erases what was approved. For revocation, read current enabled/epoch values, not the role cached at prepare time. Revocation followed by regrant still changes epoch and requires a fresh proposal. For duplicate delivery, keep operation identity and compare the done receipt before considering another dispatch.

Run python3 -B -m unittest -v test_deep_dive.ApprovalTests. The tests include reviewer revocation, argument key order, expiry boundary, stale resource, duplicate approval and two connections. They also verify that revoke-after-commit leaves the effect history intact. This matters when incident triage is tempted to mark a timeout or cancellation as if the remote action never occurred.

The current lab rejects by a structured reason and has no automatic model retry loop. A production runtime can retry transport uncertainty with the same identity, but must stop on authorization denial or changed semantics. Its logs should retain operation/digest/version correlations without publishing credentials or private payloads.

A complete worked run

from approval_deep_dive import approved_service, ARGS
s = approved_service()
bad = s.execute('tenant-a', 'user-a', 'refund-1', dict(ARGS, amount_minor=800))
assert bad['reason'] == 'proposal_changed'
assert s.state()['effect_count'] == 0
fixed = s.execute('tenant-a', 'user-a', 'refund-1', ARGS)
assert fixed['status'] == 'committed'
assert s.execute('tenant-a', 'user-a', 'refund-1', ARGS)['status'] == 'replayed'
print(bad['reason'], s.state()['effect_count'])
s.close()

Actual output: proposal_changed 1. The repaired rerun submits the originally reviewed action. A genuinely new amount would instead require a new reviewed proposal.

Exact mutation repair and reviewer-generation case

The worked script starts with a fresh already-approved service; it rejects 800 before executing the original reviewed 300. That repaired rerun restores the original action. A genuine user request for 800 must have a new operation and a new review; changing the old envelope is not a repair.

For an independent fault exercise, copy approval_deep_dive.py to approval_learner.py. In this copy disable only the comparison of digest(submitted) to the saved digest. Submit 800 to the reviewed-300 proposal and record the incorrectly committed effect. Restore the digest comparison and rerun from a fresh service: proposal_changed and zero effects. Then run the unchanged reference ApprovalTests.

Add a separate reviewer schedule: prepare/approve, revoke reviewer-a's approve authority, then enable it again in the authored permission table without resetting its incremented epoch. Executing the old approval must return approver_permission_epoch_changed and zero effects. A new current approval is a new reviewed decision; do not auto-renew it merely because a role became enabled.

For the injected-fault script import from the learner copy explicitly: from approval_learner import approved_service, ARGS. The worked reference script above imports the original module and remains unchanged. Use a fresh instance for both before/after runs so an earlier effect cannot contaminate the comparison.

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

  1. Run the isolated mutation, revocation, expiry and resource-version schedules.
  2. Compare stored proposal identity and actual local effect counts.
  3. Run ApprovalTests for replay and duplicate connections.
Download the complete application experiment package (including data and dependent scripts) ↓
python3 -B approval_deep_dive.py
View 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.
View the running environment, output and verification records →

code example

Key order versus changed business value

Reverse the ARGS key order and compare the digest: canonical sorted keys preserve it. Change amount_minor or expected_version instead and the digest differs. Do not diagnose both as formatting errors; only the latter changes the reviewed action.

Acceptance task for this level

Diagnose changed_amount, revoked_after_approval and duplicate_dispatch from fresh independent services. Inject and repair the missing digest guard in approval_learner.py, retaining source and before/after outputs. Add revoke/regrant of the reviewer and stale resource cases, then run reference ApprovalTests.

Acceptance self-checks

Reading this browser’s record…

Hide the answer and check your understanding

A cached authorization allowed dispatch, but the permission service revoked access just before the payment service received it. Would one extra preflight check close the race?

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.