# Shared runtime in the after-sales Agent / 售后 Agent 的共享运行时

## English

### What you will build and measure

This specialty connects the existing fictional after-sales Agent to a file-backed admission/settlement runtime and an independent local merchant HTTP process. Multiple worker processes share global/tenant capacity and synthetic work-unit budgets. A lost write response and a crashed worker are recovered under the original business key. The merchant checks the current runtime claim at the actual return-write boundary.

The [earlier career programming exercise](https://ai.lwkjob.com/lab/career-levels/README.md) deliberately uses one process, in-memory SQLite and logical time without completion settlement. This package adds real local process/file/HTTP behavior; it is a separate bounded specialty, not a completed production system or the whole senior path. The model remains the offline deterministic teaching adapter. Review uses seeded fictional reviewer calls, not observed real human approval. The business effect is a fictional create_return record, not an actual refund or payment.

### Start from a clean source package

Download [agent-senior-runtime-v1.zip](https://ai.lwkjob.com/downloads/agent-senior-runtime-v1.zip), extract it and enter agent-senior-runtime-v1. Use Python 3.10+ and the standard library; no Java/JDK, provider key or third-party installation is required. Keep the package manifest and original source digests. The package contains no pre-generated work database or successful learner submission.

project/SOURCE_PROVENANCE.json binds eight byte-identical copies from the original capstone. The new runtime and client/server wrappers are separate. Read project/agent.py for proposal/approval/execute, runtime_worker.py for the actual worker call, merchant_runtime.py for the HTTP transaction guard, runtime.py for admission/settlement and runtime.sql for persistent state. Trace those calls rather than treating a JSON output named passed as a completed business task.

Run these commands from the package root. Each --work directory must be new or empty; use a different directory to preserve each run. Reports default to that directory's report.json; --out can choose a separate report path.

```sh
python3 -B senior_lab.py demo --work work/demo --out work/demo/report.json
python3 -B senior_lab.py load --work work/load --tasks 12 --workers 4 --out work/load/report.json
python3 -B -m unittest -v test_runtime.py
python3 -B -m json.tool work/demo/report.json
python3 -B -m json.tool work/load/report.json
```

demo and load return 0 when their asserted experiment completes. The [unimplemented learner task](https://ai.lwkjob.com/lab/senior-runtime/LEARNER_TASK.md) must fail before implementation; a CLI/setup failure is not that contract failure. The programs start only localhost services and stop their child service processes. These experiments import local Python source; use source you trust.

### Calculate first, then inspect actual records

Before running, write available budget = total - reserved - spent. A reservation estimates synthetic work units. A verified merchant record supplies actual synthetic units for settlement; neither value is model token usage, currency or an end-to-end service cost. Count a held reservation as occupied capacity even when its effect is unknown. On confirmed completion within the reservation, remove the whole original reservation, add the verified actual charge to spent and release its slot. On safe confirmed absence, release without inventing an effect. Unknown keeps its hold.

The worked policy rejects actual units above the reservation with settlement_policy_change_required and leaves the reservation in place. The changed learner requirement adds overrun: record actual units, keep the reservation/slot and freeze tenant admission. After that policy is implemented at the real hook, budget snapshots expose pending_observed_actual_units and pending_uncovered_units. Its observed charge is pending, not yet in spent; a still-zero spent must not hide that debt. The normal guided demo/load use reservation 5 and actual 3, so they do not implement or prove the changed overrun policy.

In demo/competition, the configured global cap is 2 and per-tenant cap is 1. Each normal task reserves 5 and the merchant records synthetic actual usage 3. Two real worker PIDs pause after admission, one for each tenant. A same-tenant admission is rejected first, then another attempt is rejected by the global cap while both slots are held. Read evidence.competition.simultaneous_reservations and barrier_workers, then completed_workers, final and merchant_ledger. Verify the two simultaneous holds, the current per-tenant budgets and the actual business receipts. A later task can start after completion releases capacity.

In demo/crash, the merchant commits a return and deliberately drops the TCP response; the first worker exits 75. The persisted reservation remains. After the short lease expires, another actual process recovers the same reservation and original operation key with a new epoch. Read before_restart, recover_worker, final and merchant_ledger together. There must be one return/receipt, released reservation, synthetic spent 3 and a completed runtime state. A new operation key would break this reconciliation evidence.

In demo/guards, compare stale_http and stale_local. They test refusal at different boundaries: an old claim cannot write the merchant and cannot settle the runtime. Inspect reservation_binding, forged_receipt, revoked_http, revoked_completion and revoked_conserves. The lab controller explicitly restores the fictional authority for the no-effect release; it is not a model-granted permission. post_release_http must reject a late write after the reservation is released.

### Why the fence protects this local effect

Runtime admission/recovery increments a task epoch and binds tenant, owner, worker and reservation. The local HTTP merchant verifies those bindings, current enabled authority, held state and expiry inside the same SQLite write transaction as the business operation. Its original route still checks proposal/approval/current business policy and the original-key receipt. Admission and settlement also check the current merchant user/tenant/role, separately from the runtime ACL. The runtime then compares completion evidence against the merchant ledger; a worker-supplied receipt JSON alone cannot settle. The HTTP server writes fixed synthetic cost 3 into rt_costs with the business transaction; a missing usage record or a worker value that is None, bool, float or a mismatching integer is rejected.

This works because the runtime and merchant share one authoritative file on one host. The HTTP service is a separate process/connection, not a remote production merchant. A separate external service that does not enforce the fence cannot be protected by a local epoch check. Safe absence here also relies on the current fenced claim and same transaction; a point-in-time empty lookup from an unfenced remote service would not establish terminal no-effect. Killing a process or releasing a slot does not cancel an unknown write.

Leases use the host wall clock; the local design assumes its consistency and does not establish a cross-host clock protocol. Lease, epoch and permission checks occur after BEGIN, before the business write, in the same SQLite transaction; once admitted, that atomic transaction may complete even if the lease expires before commit. There is no second expiry check at commit, and a lease is not an end-to-end deadline. Current authorization at a transaction does not grant permanent permission. Do not weaken current checks to make a historical approval or recovered worker pass.

### Read the load denominator and timing scope

The bounded load command accepts 2..30 tasks and 2..8 worker processes. It prepares actual Agent model/tool/RAG/proposal turns and seeded review first, then measures the worker execution window. The default has 12 prepared tasks and 4 real worker processes. Small authored inputs and the explicit 25ms overlap pause are teaching conditions, not natural production traffic.

Read evidence.accounting: submitted, admitted_unique_tasks, not_admitted_tasks, terminal, successful, worker_errors, all states and rejected_admission_attempts. Distinguish unique tasks from retry/admission attempts. Unknown/overrun/queued work belongs in the denominator even if a success-only latency statistic excludes it. Check sum_states and inspect the individual worker results, final state and merchant_ledger. Use peaks to verify shared global/tenant holds and reserved-plus-spent accounting rather than inferring isolation from a final zero counter.

measured_throughput divides successful tasks by the recorded worker-window seconds. Initial setup and Agent preparation are excluded. latency_ms reports successful-task admission-to-terminal and submitted-to-terminal values with their sample sizes; the latter includes queue time after each task's preparation. The percentile algorithm is nearest rank. For 12 successes, p95 is the largest observed value in that small sample. The window uses perf_counter_ns; persisted task timestamps use the host wall clock. Inspect both clock scopes before interpreting a difference.

You may report the observed local sample under its exact configuration. It does not measure live-model latency/tokens/cost, cloud networking, multi-host coordination, production capacity, tail reliability or a customer SLA. A normal load run also does not replace the crash/revocation counterexamples. Do not convert fixed teaching labels into a model-quality percentage.

### From worked example to independent responsibility

Implement the separate [receipt-aware settlement task](https://ai.lwkjob.com/lab/senior-runtime/LEARNER_TASK.md): preserve a red baseline, add the new overrun behavior in personal source, prove real completion/recovery hook behavior, break one invariant in a separate copy, restore it and regress the runtime. The learner template and the public old policy do not implement the changed overrun decision; forwarding to that policy must fail the new checks. Disclose source/AI assistance. Public fixed checks remain practice rather than proof of independent authorship; a reviewer still needs to supply a complete fresh changed requirement and observe your personal modification.

Complete the [decision/migration/incident/handoff guide](https://ai.lwkjob.com/lab/senior-runtime/ADR_GUIDE.md). Kill switches, rolling migration, rollback, multi-host deployment and manual overrun adjustment remain design/rehearsal tasks unless you implement and verify them in your own copy. A written plan does not establish an executed migration. Use the [pilot protocol](https://ai.lwkjob.com/lab/senior-runtime/PILOT_GUIDE.md) for real learner observation and scoring calibration; no actual participant or employer calibration is claimed by this package.

Return the evidence to the [career responsibility paths](https://ai.lwkjob.com/lab/capstone/CAREER_PATHS.md) and [assessment worksheet](https://ai.lwkjob.com/lab/capstone/ASSESSMENT_TEMPLATE.json). Keep unobserved real-provider, fresh-requirement, production and collaboration gates pending. This specialty does not change the scoring rules or pass the full main project/senior rank.

### Reproducible packaging and evidence

PACKAGE_MANIFEST.json binds the allowlisted public source/document bytes. A runtime report binds engineering source digests, Python version, process identities and actual state/ledger records; teaching documents and generated work reports are excluded from its engineering digest list. The learner report separately binds the submitted module. Keep the exact source copy and report together; later source edits require a rerun. package.py builds only allowlisted sources and manifest metadata, excluding work databases, reports, caches and private reference implementations.

```sh
python3 -B package.py --out agent-senior-runtime-v1.zip
```

## 中文

### 要实现和测量什么

本专题把已有虚构售后 Agent 接入文件准入/结算运行时与独立本机商家 HTTP 进程。多个 worker 共享全局/租户容量和合成工作单位预算；沿原业务键恢复丢失写返回与崩溃 worker，商家在实际退货写入边界检查当前运行时 claim。

[旧 career 编程练习](https://ai.lwkjob.com/lab/career-levels/README.md)有意使用单进程、内存 SQLite、逻辑钟且无完成结算。本包补真实本机进程/文件/HTTP 行为，是独立有界专题，不是已完成生产系统或整个资深路径。模型仍为离线确定性教学生成器；审核采用种子虚构 reviewer 调用，不是观察到真实人工批准。业务效果是虚构 create_return 记录，不是真退款或支付。

### 从干净源码包开始

下载 [agent-senior-runtime-v1.zip](https://ai.lwkjob.com/downloads/agent-senior-runtime-v1.zip)，解压进入 agent-senior-runtime-v1。使用 Python 3.10+ 和标准库，无需 Java/JDK、提供方 key 或第三方安装。保留 manifest 与原源码摘要；包内没有预生成工作数据库或已通过的学员答案。

project/SOURCE_PROVENANCE.json 绑定八份与原 capstone 字节一致的副本；新运行时与客户/服务端 wrapper 分开实现。看 project/agent.py 的提案/批准/执行、runtime_worker.py 的实际 worker 调用、merchant_runtime.py 的 HTTP 事务守卫、runtime.py 的准入/结算、runtime.sql 的持久状态。沿调用追踪，不把名为 passed 的 JSON 当业务任务完成。

从包根目录运行以下命令。每个 --work 目录必须新建或为空，另选目录保留每次运行；报告默认在目录的 report.json，--out 可指定另一路径。

```sh
python3 -B senior_lab.py demo --work work/demo --out work/demo/report.json
python3 -B senior_lab.py load --work work/load --tasks 12 --workers 4 --out work/load/report.json
python3 -B -m unittest -v test_runtime.py
python3 -B -m json.tool work/demo/report.json
python3 -B -m json.tool work/load/report.json
```

demo/load 在断言实验完成时退出 0。[未实现学员任务](https://ai.lwkjob.com/lab/senior-runtime/LEARNER_TASK.md)编码前须失败，CLI/环境错误不算合同失败。程序仅启动 localhost 服务并收回子服务进程；实验导入本地 Python 源码，只使用信任源码。

### 先手算，再看真实记录

运行前写 available=total-reserved-spent。预留估算合成工作单位，商家核验记录提供实际合成单位结算，两者都不是模型 Token、货币或端到端服务成本。效果未知仍把预留计为占用容量。预留内确认完成时去掉整个原预留、将核验实际扣费加进 spent、释放槽；安全确认无效果只释放，不造效果；未知保持 hold。

旧引导政策在 actual 超出预留时拒绝 settlement_policy_change_required，保留原预留。学员变化需求增加 overrun：记录实际单位、保留预留/槽、冻结租户准入。本人政策接入真实 hook 后，快照暴露 pending_observed_actual_units、pending_uncovered_units；观测扣费待处理，尚未入 spent，不能因 spent 零掩盖债务。正常引导 demo/load 用预留 5、实际 3，不实现或证明新超额政策。

demo/competition 配置全局上限 2、每租户 1；正常任务各预留 5，商家记录实际合成用量 3。两个真实 worker PID 各在一租户准入后暂停：先拒绝同租户新准入，再在两槽被占时拒绝全局超限。看 evidence.competition.simultaneous_reservations、barrier_workers，再看 completed_workers、final、merchant_ledger；核对两个同时 hold、当前租户预算与实际业务回执。完成释放后，后续任务才能启动。

demo/crash 中商家提交退货后故意丢 TCP 返回，首个 worker 退出 75，持久预留还在。短 lease 过期后，另一个真实进程用新 epoch 恢复同一预留与原业务键。一起看 before_restart、recover_worker、final、merchant_ledger；须只有一份退货/回执、预留释放、合成 spent=3、运行时完成。换新操作键会破坏这份对账证据。

demo/guards 中比较 stale_http 和 stale_local：分别拒绝旧 claim 写商家及结算本地。看 reservation_binding、forged_receipt、revoked_http、revoked_completion、revoked_conserves。实验控制器明确恢复虚构当前权限后演练无效果释放，不是模型授予权限；post_release_http 须在预留释放后拒绝迟到写入。

### fence 为何能保护本机效果

准入/恢复递增任务 epoch，绑定租户、owner、worker、reservation。本机 HTTP 商家在业务操作同一 SQLite 写事务内核验这些绑定、当前启用权限、hold 状态和 expiry；原业务 route 仍检查提案/批准/当前政策与原键回执。准入和结算还独立于 runtime ACL 核验当前商家 user/tenant/role。完成时运行时再对照商家账本，worker 自带回执 JSON 不足以结算。HTTP 服务在业务事务内向 rt_costs 写固定合成成本 3；usage 记录缺失，或 worker 值为 None、bool、浮点或不匹配整数，均拒绝。

成立前提是运行时和商家在单机共享同一权威文件。HTTP 服务是独立进程/连接，不是远端生产商家；其他外部服务若不执行 fence，仅查本地 epoch 无法保护它。安全确认无效果也依赖当前 fenced claim 与同事务；未 fence 远端服务在某时查空，不能证明终态无效果。杀进程或释放槽不能取消未知写。

lease 使用本机壁钟，设计假设其一致性，没有建立跨主机时钟协议。租约、epoch 和权限在 BEGIN 后、业务写入前于同一 SQLite 事务内检查；通过后该原子事务可以完成，即使提交前租约到期。没有实施提交瞬间的第二次 expiry 检查，租约也不是端到端截止时间。事务时当前授权不授予永久权限；不能为让历史批准或恢复 worker 通过而弱化当前检查。

### 看清负载分母与计时范围

有界负载接受 2..30 任务与 2..8 worker 进程。先完成实际 Agent 模型/工具/RAG/提案轮次及种子审核，再测 worker 执行窗口；默认 12 任务、4 个真实进程。少量作者构造输入与明确的 25ms 重叠暂停是教学条件，不是自然生产流量。

看 evidence.accounting 的 submitted、admitted_unique_tasks、not_admitted_tasks、terminal、successful、worker_errors、全部状态、rejected_admission_attempts，区分独立任务与重试/准入次数。即使仅成功延迟统计排除未知/超额/排队，它们仍属于任务分母；核对 sum_states、各 worker 结果、最终状态和商家账本。用 peaks 看共享全局/租户 hold 与 reserved+spent，不凭最终零计数推断隔离。

measured_throughput 用成功任务除以记录的 worker 窗口秒数，排除初始化与 Agent 准备。latency_ms 给成功任务的准入到终态、提交到终态及样本量，后者含各任务准备后的排队。百分位采用 nearest rank，12 成功时 p95 就是该小样本最大值。窗口用 perf_counter_ns，持久任务时间用本机壁钟，解释差异前查看两个时钟范围。

可以在精确配置下报告本机样本；它不测真实模型延迟/Token/成本、云网络、多机协调、生产容量、尾部可靠性或客户 SLA。正常负载也不替代崩溃/撤权反例，固定教学标签不能变成模型质量百分比。

### 从示范到本人职责

做独立[回执结算任务](https://ai.lwkjob.com/lab/senior-runtime/LEARNER_TASK.md)：保留红基线、在本人源码增新超额行为、证明真实完成/恢复 hook、另副本破坏不变量、恢复并回归。模板与公开旧政策均未实现新 overrun 决定，仅转发旧政策须在新检查失败；注明源码/AI 协助。固定检查仍是练习，不能证明独立作者身份，评审还须给完整变化新需求并观察本人修改。

做[决策/迁移/事故/交接指南](https://ai.lwkjob.com/lab/senior-runtime/ADR_GUIDE.md)。kill switch、滚动迁移、回滚、多机部署、超额人工调整仍为设计/演练任务，除非本人副本实现并验证。书面计划不证明已执行迁移。[试教协议](https://ai.lwkjob.com/lab/senior-runtime/PILOT_GUIDE.md)用于真实学员观察与评分校准，本包没有真实参与者或企业校准主张。

将证据回填[职责路径](https://ai.lwkjob.com/lab/capstone/CAREER_PATHS.md)和[评审记录](https://ai.lwkjob.com/lab/capstone/ASSESSMENT_TEMPLATE.json)，未观察真实提供方、新需求、生产、协作门保持 pending。本专题不改评分规则，也不通过整个主项目/资深职级。

### 可复现打包与证据

PACKAGE_MANIFEST.json 绑定白名单公开源码/文档字节。运行时报告绑定工程源码摘要、Python 版本、进程身份及实际状态/账本；教案和生成的 work 报告不进入工程摘要列表。学员报告另外绑定提交模块。保留精确源码和报告，后续源码变化须重跑；package.py 只打白名单源码和 manifest 元数据，不含 work 数据库、报告、缓存或私有参考答案。

```sh
python3 -B package.py --out agent-senior-runtime-v1.zip
```
