跳到正文
Agent Field Notes
课程目录展开方向,选择要学习的课程。

SYSTEMATIC LEARNING / 分层专题

工具契约:从合法请求到有权执行的业务事实

实现退款边界,注入格式合法却越权的请求与过期状态,再改变契约版本和业务权威边界。

学习目标:解释并实现结构、业务、权限、状态与回执检查;判断哪些保证能跨越重试和独立服务边界。

内容核对2026-11-03 · 每层有独立讲解、任务与检查

按这个知识点的熟悉程度选择起点。当前层:入门 · 理解原理。完成任务后可以继续下一层;阅读与自检不自动代表掌握。

本层学习目录

先补齐必要概念

适合:能跟踪请求与结果状态的读者。

Schema
描述字段形状、类型和约束的契约;字段合法不证明调用者拥有操作权限。
可信上下文
服务端认证后得到的身份与租户,不能直接相信模型填写的身份。
副作用
对外部世界的写入,例如付款、发布或删除。
状态版本
资源当前状态的版本,用于发现检查之后发生的变化。

原理怎样一步步成立?

工具调用:建议到回执的信任边界
  1. 1
    模型

    提出工具名、参数与 call_id;这些都是候选输入。

  2. 2
    运行时

    先查白名单、完整性与共享预算,再校验参数;未通过就停止该动作。

  3. 3
    业务服务

    从可信会话读取身份,核对资源归属与当前权限,在提交边界检查状态。

  4. 4
    工具适配器

    按 call_id 关联成功、失败或未知回执,保留已发生事实。

  5. 5
    验收

    回执进入下一轮输入;最终答案与事实核对,通过后才报告业务完成。

结构正确不授予权限;call_id 只关联本轮调用,不能代替跨恢复的业务操作键。

逐步解释原理
  1. 候选参数

    模型提出动作与参数。

  2. 结构与语义

    检查字段、类型、单位和关联约束。

  3. 身份与状态

    核对真实权限与当前业务状态。

  4. 执行与回执

    有条件地执行,并校验结果及业务证据。

入门 · 理解原理

为什么参数合法,动作仍可能不合法

本层目标:为每个后续关卡构造一个通过结构检查却必须失败的请求。

图解 · 新效果逐道通过独立关卡

新效果逐道通过独立关卡

图示为新动作路径。获准的旧回执重放先于新资源前置条件检查;本地事务不能把远端付款纳入原子提交。 点图可打开原图放大查看。

模型可以用格式完全正确的 JSON 提出 order-b 和 amount_minor=300。结构检查知道订单 ID 是字符串,却不知道 order-b 属于 tenant-b。因此 tenant-a 的会话不能授权它。把 tenant_id=tenant-b 放进参数,只增加了一个来自不可信来源的断言。

分开回答五个问题:请求是否完整且类型正确?单位与字段间业务规则是否成立?已认证的主体是否能对这个资源执行动作?当前资源版本和剩余额度是否满足提议?业务权威是否真的提交了副作用并留下回执?通过前一道关卡不能代替后一道关卡的证据。

本实验使用整数最小货币单位并显式声明币种。300 USD minor units 是 3 美元,单独一个 3 不能安全地猜默认单位。Python 检查拒绝 bool 和 float,因为 isinstance(True, int) 原本会接纳布尔值。JSON Schema 的必填与封闭属性规则描述结构;对象归属仍由应用判断。对象约束。

运行时 call ID 标识一次模型回合中的调用;持久化 operation ID 标识跨恢复的业务动作。两次合法的部分退款需要两个 operation ID,同一退款的两次投递需要同一个 ID。operation ID 和工具描述都不授予权限。

关卡表的固定输入

可信调用者是 tenant-a/user-a,拥有 refund:write。初始 order-a 属于 tenant-a,remaining_minor=1000、资源版本为 1、币种为 USD;order-b 属于 tenant-b。正常请求完整如下:

{"schema_version":2,"operation_id":"refund-1","order_id":"order-a","amount_minor":300,"currency":"USD","expected_version":1}

第 1–3 例各用全新业务状态;第 4–5 例先提交正常请求,让余额成为 700、资源版本成为 2。

  1. 增加 tenant_id=tenant-b:严格字段集合检查返回 shape_fields,尚不需要查资源或写副作用。
  2. 把 amount_minor 改为 true:整数检查返回 shape_integer,布尔值不能当金额。
  3. 把 order_id 改为 order-b:结构通过,授权返回 authorization;公开错误不带其他租户余额。
  4. 新建 refund-2 却保留 expected_version=1:授权通过,新动作的状态前置条件返回 resource_version。
  5. refund-1 已提交但响应丢失:业务关卡可能全部通过,只是调用者不知道结果。原参数核对同一操作,得到 replayed 和原回执;不能为缺确认而新建 refund-2。

这里的“业务权威”是拥有订单状态、实际提交副作用的服务;“关卡”是必须成立的检查条件,不是提示词偏好。

运行实验,观察反例

编写的请求;实际本地 SQLite 结构/权限/状态/回执检查。没有模型或外部支付执行。

Python 3.10+ · 默认运行只使用标准库 · 在你的电脑运行

  1. 运行模块,识别 events 的各个关卡。
  2. 运行 ToolContractTests,包含重新打开与重复连接。
  3. 比较业务状态和已存回执,说明远端服务边界。
下载完整应用实验包(含数据与依赖脚本) ↓
python3 -B tool_contract_deep_dive.py
查看本入口脚本
"""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))

本地运行的预期输出

{
  "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 通过结构检查并在授权失败。
  • valid 提交 300;retry 回放;changed_retry 被拒绝。
  • 最终 remaining_minor=700、effect_count=1。
查看运行环境、输出和校验记录 →

代码示例

第二个合法动作不是重复投递

用户分别要求两次各 300 的退款,需要不同操作 ID,资源版本依次为 1、2。权限和余额满足时,两张回执及 remaining_minor=400 是合法结果。“每订单最多退款一次”的全局去重会错拒第二个动作,唯一性应限定一项业务意图。

本层验收任务

使用本层正文的五个固定输入制作关卡表,写可信输入、最早拒绝或不确定边界、实际状态与下一步。确认丢失一行允许写“没有业务关卡失败”。

逐条验收自评

正在读取此浏览器记录…

收起答案,检查理解

模型请求的 operation ID 与 schema 都合法,但指向另一个租户的订单。再增加什么参数能让它执行?

延伸原理与知识练习

遇到不熟悉的原理,先阅读实现、连续追问和迁移案例,再独立说明前提与边界。作答与笔记保存到原有账号记录。

本专题的全部关联解析与练习(3 道)

依据与验证范围

原理依据来自公开资料;数字、案例和任务是本站教学设计。离线实验验证本页注明的范围,学习效果仍需通过独立任务与反馈判断。