Skip to content

feat(runtime): add original CSI application retirement - #14698

Merged
doudouOUC merged 7 commits into
mainfrom
codex/csi-application-retirement
Oct 19, 2026
Merged

doudouOUC merged 7 commits into
mainfrom
codex/csi-application-retirement

Conversation

@doudouOUC

@doudouOUC doudouOUC commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

What this PR does

Extracts the original-owner application retirement slice from #13526, frozen at 1a6529b73c007044d9d04e0614fbc30ebe13c0ac, directly onto main 11a6346aa92b5e2f473464174e6043d053bf8010. It is independent of the cold-recovery split #14695: only a settled, still-live original runtime generation 1, writer generation 1 and activation epoch 1 can complete this path.

The existing Hosted owner closes admission and joins its actual work and renewals, then prepares one exact terminal suffix. Durable SETTLING → FROZEN → CUT → DRAINED progress binds a complete SQL image to the original worker's file, history, execution and descriptor observations. Completion seals the native journal and releases the one logical Runtime Session; the original binding and holder remain DRAINING and the runtime slot remains occupied. Exact retries consume the saved cut and receipt without acquiring another writer or worker.

The typed inventory covers 32 tables and 736 columns, including retained snapshot/page/body graphs and agent resources. It preserves main's real Hosted context-usage projection and precisely validates its latest committed output association instead of suppressing that producer. V12 adds eleven progress/unique-target fields to the existing retirement operation and preserves the published V11 wake migration and its producer behavior. The finalizer uses an explicit boot6/resource-handle4 contract; boot4/5 construction and ordinary execution remain compatible but do not gain finalization authority.

The complete design and remaining qualification requirements are synchronized in English and 简体中文.

Why it's needed

Finishing a file turn or observing an empty local task set does not establish an application cut shared by SQL admission, native history and the original worker's open descriptors. Generic CSI activation and Runtime Session release intentionally refuse this gap. This slice supplies an explicit durable completion protocol while retaining unknown-state refusal and the original execution and storage identities.

Reviewer Test Plan

How to verify

For a newly constructed boot6 original owner, finish supported Read/Write/Edit work, begin retirement and invoke the existing-owner retire route. Verify monotonic progress to DRAINED version 4, a sealed head, closed original descriptors, unchanged file/history/execution identities, a released logical Runtime Session, DRAINING binding/holder and an occupied slot. New attach, input, execution, writer acquisition and ordinary final-boundary operations must refuse once their relevant admission closes.

Retry the same operation before and after a lost reply and confirm exact saved bytes and stable progress. Cross a tenant, workspace, binding, retirement, writer generation, activation epoch, deadline, resource, receipt or retained snapshot association and confirm refusal without an undeclared durable change. A recovered owner must not gain original-owner retirement authority.

The original owner retains parent-first same-Connection locking. OTHER-owner validation still takes late foreign-parent locks after bounded whole-table child scans; concurrent ordinary writers can cause deadlock/timeout and rollback. Cross-tenant race acceptance is pending and this lock-order question requires maintainer review. Do not interpret the focused checks as production qualification of that path.

Evidence (Before & After)

Before: a fresh global qwen 0.25.2 baseline returned 404 for attach/text/retire. This establishes unavailable capability only, not an SQL protocol reproduction.

After: root build, typecheck and bundle passed on the unchanged rebased TypeScript sources. Focused Core tests passed 233/233; focused CLI tests passed 575 with 33 platform skips, followed by a 43/43 strict finalizer/worker subset. Production-equivalent candidate 0a039626d3dcef22e93e3540f56184fd1fa00915 passed 178 focused Java checks without skips, both Checkstyle configurations, SpotBugs with zero findings and packaging. Current head bbea488786f00b8d0f54f8b4a6658cbc3b017b2e changes only two metadata lookup keys in the MySQL test fixture; production source is identical and test compilation passed. This selection covers retirement 17, history 3, inventory 63, native activation 20, retained graphs 31 and lock-order 44.

An earlier complete clean unit phase reported 4,930 cases with zero failures/errors and 18 skips, then stopped at one formatting violation. The complete suite was not rerun after the later minimal qualification and fixture corrections. Fresh SQL exposed handle-key-order comparisons in both inventory qualification and retained status reading, plus test dialect and mount-fixture issues. The corrections preserve stored bytes/digests, strict schema checks, all other identity fields and actual native descriptor closure. The separate E2E report retains every failed attempt and its exact candidate.

At 0a039626d3dcef22e93e3540f56184fd1fa00915, actual initial Hosted attach → one settled text turn → retire reached DRAINED v4 with writer generation 1 / epoch 1, conserved execution/file/backup identities, all four original native descriptors closed and binding/holder still DRAINING. Independent persisted-status GET and a brand-new production Core client retry both passed; complete 33-table images were unchanged by both retries and no writer was reacquired. All four standard MySQL cases also passed. The inventory run passed 62/63 and exposed the fixture metadata-key defect corrected in the current test-only commit. On current head bbea488, the corrected BOOLEAN case passed independently, then all 63 inventory and 31 retained MySQL cases passed without skips. Ordinary Hosted 2/2 and ordinary process-fault 2/2 also passed; the process profile covers six ordinary fault cuts plus coordinator restart. Two selected ordinary Workspace cases FAILED at tool-session acquisition before their fault cuts. Fresh read-only checks passed both Session authorizations and found no required physical storage registration; the fixture registers those roots only on Linux, and this run used macOS. A complete main E2E baseline and supported Linux rerun were not performed, so these remain failures rather than a claim of no regression. Exact scopes and limitations are in the separate report.

Cross-tenant races, the private CSI process-death/fault matrix and Linux filesystem acceptance remain unverified. H2 and labelled mock seams are not substitutes for those gates. Historical source-branch results are not used as evidence. The native foreground /review workflow tool is unavailable on this host; this PR does not claim formal review approval.

Tested on

OS Status
🍏 macOS ⚠️ build/typecheck/bundle, earlier full Java unit phase, current-production focused module/static and reported SQL/Hosted checks passed; two ordinary Workspace checks failed
🪟 Windows ⚠️ Not tested
🐧 Linux ⚠️ Not tested; 33 platform-specific focused checks skipped locally

Environment (optional)

Local macOS, Node.js 22.14.0, JDK 21 and Maven 3.9.16. Disposable MySQL 8.4 was used for the reported SQL and actual Hosted retirement checks; private CSI process-death acceptance remains pending. Mocked worker mount/readback seams are explicitly labelled by the tests.

Risk & Scope

  • Main risk or tradeoff: this feature crosses core, Hosted and native SQL contracts and requires maintainer architecture review. The large, explicit typed inventory is necessary to refuse hidden or unsupported carriers. Late foreign-parent locking can conflict with another owner's ordinary writes; rollback/retry behavior and cross-tenant races remain a maintainer review and qualification requirement.
  • Not validated / out of scope: new cold recovery, recovery→retirement qualification, node evidence, installed-byte policy, physical stop, CSI unpublish, binding/holder RELEASED, reuse and public CSI selectors. Two ordinary Workspace checks remain failed; private CSI process-death and Linux acceptance are pending.
  • Breaking changes / migration notes: additive V12 leaves V11 untouched. Do not mix pre-V12 schema readers/writers with the upgraded catalog or substitute old worker boot4/5 for boot6 finalization. Existing old-contract execution compatibility does not certify an application cut or physical release.

Linked Issues

Part of #13526; this extraction does not close the cumulative PR or a separate issue.

中文说明

本 PR 的变更

从 #13526 的冻结版本 1a6529b73c007044d9d04e0614fbc30ebe13c0ac 提取原始 owner 的应用退役部分,直接基于 main 11a6346aa92b5e2f473464174e6043d053bf8010。它独立于冷恢复拆分 #14695:只有已经 settled、仍存活且 runtime generation 1、writer generation 1、activation epoch 1 的原 owner 能完成此路径。

现有 Hosted owner 关闭接纳并等待真实工作和续租,然后准备唯一的精确终止后缀。持久 SETTLING → FROZEN → CUT → DRAINED 进度把完整 SQL 镜像与原 worker 的文件、历史、执行和描述符观察绑定。完成时 seal native journal 并释放唯一逻辑 Runtime Session;原 binding 和 holder 保持 DRAINING,runtime slot 继续被占用。精确重试消费保存的 cut 和 receipt,不会获取另一个 writer 或 worker。

typed 库存覆盖 32 表、736 列,包括保留的 snapshot/page/body 图及 agent 资源。保留 main 真实 Hosted 上下文用量投影,精确校验其最新已提交输出关联,不抑制既有 producer。V12 在现有 retirement operation 上增加十一项进度/唯一 target 字段,保留已发布的 V11 wake migration 及其 producer 行为。finalizer 使用显式 boot6/resource-handle4 协议;boot4/5 的构造和普通执行继续兼容,但不会获得 finalization authority。

完整设计和剩余资格验收要求已同步维护在 English 与 简体中文。

为什么需要

文件 turn 完成或本地任务集合为空,并不能建立 SQL 接纳、native history 与原 worker 打开描述符共同认可的应用切点。通用 CSI activation 和 Runtime Session release 明确拒绝这一缺口。本部分提供显式持久完成协议,同时保留未知状态拒绝,以及原 execution 和 storage 身份。

评审者测试计划

如何验证

对新构造的 boot6 原始 owner,完成支持的 Read/Write/Edit 工作,开始退役,再调用现有 owner 的 retire 路由。确认进度单调到达 DRAINED version 4、head 已 seal、原描述符已关闭、file/history/execution 身份不变、逻辑 Runtime Session 已释放、binding/holder 保持 DRAINING 且 slot 仍被占用。新的 attach、input、execution、writer acquisition 和普通 final-boundary 操作在相应接纳关闭后必须拒绝。

在丢失响应前后重试相同操作,确认保存字节精确一致且进度稳定。交叉 tenant、workspace、binding、retirement、writer generation、activation epoch、deadline、resource、receipt 或 retained snapshot 关联,确认拒绝且没有未声明的持久修改。恢复 owner 不能取得原 owner 的退役 authority。

原始 owner 保持 parent-first 的同 Connection 锁顺序。OTHER owner 的验证仍在有界全表子行扫描后取得 foreign parent 锁;与普通 writer 并发时可能 deadlock/timeout 并回滚。跨 tenant race 验收尚未完成,该锁顺序问题需要维护者评审。不能将 focused 检查理解为此路径已获得生产资格。

证据(前后对比)

变更前:新跑的全局 qwen 0.25.2 基线中 attach/text/retire 返回 404。这只证明能力不可达,不是 SQL 协议复现。

变更后:未再改动的 rebase 后 TypeScript 源已通过 root build、typecheck 和 bundle。Core focused 233/233;CLI focused 575 通过、33 项平台限定跳过,随后 strict finalizer/worker 子集 43/43 通过。生产代码等价的候选 0a039626d3dcef22e93e3540f56184fd1fa00915 已通过 178 项 Java focused、无跳过,两套 Checkstyle、零发现的 SpotBugs 和打包。当前 head bbea488786f00b8d0f54f8b4a6658cbc3b017b2e 仅修改 MySQL 测试夹具两处元数据取值键,生产源码不变,测试编译通过。本次选择为 retirement 17、history 3、库存 63、native activation 20、保留图 31、锁序 44。

此前完整 clean 单测阶段报告 4,930 项,0 失败、0 error、18 跳过,随后被一项格式违规挡住;之后的最小资格/夹具修正没有再跑整套。真实 SQL 揭示库存资格与保留状态读取中的 handle 键顺序比较,以及测试方言和 mount 夹具问题。修正保持存储字节/摘要、严格 schema、其他身份字段校验和真实原生描述符关闭。独立 E2E 报告 保留全部失败尝试及准确候选。

在 0a039626d3dcef22e93e3540f56184fd1fa00915 上,实际首次 Hosted attach → 一个 settled 文本 turn → retire 已达到 DRAINED v4,writer generation 1 / epoch 1、execution/file/backup 身份保持,四个原始原生描述符均关闭,binding/holder 仍 DRAINING。独立持久状态 GET 和新建生产 Core 客户端重试均通过;两次重试前后的完整 33 表原像相同,没有重新获取 writer。四项标准 MySQL 场景全部通过。库存 62/63 通过,唯一失败揭示当前纯测试提交修正的元数据键错误。在当前 bbea488 上,BOOLEAN 单例独立通过,随后 63 项库存和 31 项保留历史 MySQL 检查全部通过、无跳过。普通 Hosted 2/2、普通进程故障 2/2 也通过,后者覆盖六个普通故障切点和 coordinator 重启。选中的两项普通 Workspace 场景在工具会话获取阶段失败,未进入故障切点。新只读检查证明两个 Session 授权均通过,但缺少必需的物理存储登记;fixture 仅在 Linux 注册相应根目录,本轮运行于 macOS。未执行完整 main E2E 对照或受支持 Linux 复验,因此两项保留为失败,不能声称全面无回归。准确范围和限制见独立报告。

跨 tenant race、私有 CSI 进程死亡/故障矩阵和 Linux 文件系统验收仍未验证。H2 和已标注 mock seam 不能替代这些门禁。不使用 source 分支历史结果作为证据。宿主缺少原生前台 /review workflow 工具,本 PR 不声称正式 review 已通过。

测试平台

OS 状态
🍏 macOS ⚠️ build/typecheck/bundle、早先完整 Java 单测阶段、当前生产 focused 模块/静态及所报告 SQL/Hosted 检查通过;两项普通 Workspace 检查失败
🪟 Windows ⚠️ 未测试
🐧 Linux ⚠️ 未测试;本机 focused 检查跳过 33 项平台限定用例

环境(可选)

本地 macOS、Node.js 22.14.0、JDK 21、Maven 3.9.16。所报告的 SQL 与实际 Hosted 退役检查使用一次性 MySQL 8.4;私有 CSI 进程死亡验收仍待完成。worker mount/readback 的 mocked seam 已由测试明确标注。

风险与范围

  • 主要风险或取舍:本功能跨 core、Hosted 与 native SQL 契约,需要维护者架构评审。显式且规模较大的 typed inventory 用于拒绝隐藏或不支持的载体。late foreign-parent 锁可能与其他 owner 的普通写入冲突;回滚/重试及跨 tenant race 仍需维护者评审和资格验收。
  • 未验证或范围外:新增冷恢复、恢复后退役资格、节点证据、安装字节策略、物理停止、CSI unpublish、binding/holder RELEASED、复用和公开 CSI selector。两项普通 Workspace 检查仍失败;私有 CSI 进程死亡及 Linux 验收待完成。
  • 破坏性变更或迁移说明:V12 为增量迁移,V11 保持不变。升级 catalog 后不能混用 pre-V12 的 schema reader/writer,也不能用旧 boot4/5 worker 替代 boot6 finalization。旧协议普通执行兼容并不证明应用切点或物理释放。

关联问题

属于 #13526 的拆分;不关闭累计 PR 或其他 issue。

@doudouOUC

doudouOUC commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

E2E and verification report — original CSI application retirement

Current candidate: bbea488786f00b8d0f54f8b4a6658cbc3b017b2e; frozen main base 11a6346aa92b5e2f473464174e6043d053bf8010; cumulative source 1a6529b73c007044d9d04e0614fbc30ebe13c0ac. The 90-file source manifest is .qwen/e2e-tests/application-candidate-metadata-key-sha256.json, SHA-256 72ddccd73acdddb43233d88037a65197be8cf1b8750d251dde10c3b4e61eea62. Main has advanced since this frozen base; it was not manually rebased during acceptance.

Current results are below. The only change from 0a03962 to bbea488 is two metadata lookup keys in a MySQL test fixture. Independent comparison of all 17,697 product pins found exactly one changed test class; every production product is identical. The 0a results retain their exact source attribution.

Check Candidate / result
Actual original Hosted owner, starting at first attach 0a03962: PASS, exit 0; one settled file turn → DRAINED v4
Fresh original-token SQL status and a new independent HTTP store client 0a03962: GET 200 and exact completed result; each preserves the complete 33-table raw image (32 managed inventory tables plus Flyway history)
Standard real MySQL/SQL/worker cases 0a03962: 4/4 PASS, 0 failures/errors/skips, including two-turn retirement with fresh complete retry and existing recovery regressions
Real MySQL BOOLEAN regression bbea488: 1/1 PASS, 0 failures/errors/skips, 5.493 seconds
Full real MySQL inventory profile bbea488: 63/63 PASS, 0 failures/errors/skips, 94.978 seconds
Final retained-graph MySQL profile bbea488: 31/31 PASS, 0 failures/errors/skips, 53.244 seconds
Matching ordinary Hosted regression bbea488: 2/2 PASS, 0 failures/errors/skips, 14.950 seconds
Matching ordinary Workspace/tool-fault regressions bbea488: 2/2 FAIL, 0 errors/skips, 13.469 seconds; initial acquire refused before fault cuts; missing physical-storage registration observed
Matching ordinary process regressions bbea488: 2/2 PASS, 0 failures/errors/skips, 129.896 seconds; six ordinary process fault cuts and coordinator restart
Affected Java consumers plus complete static/packaging stages 0a03962: 178/178 PASS, 0 failures/errors/skips; both Checkstyle configurations 0, SpotBugs 0 bug instances/0 errors, packaging successful; exit 0 in 1:26
TypeScript build and focused checks Root build/typecheck/bundle PASS; Core 233/233; CLI 575 passed/33 platform skips; strict finalizer/worker subset 43/43. No later TypeScript production change.

The final 178-case Java selection is retirement 17 + history 3 + inventory 63 + native activation 20 + retained graphs 31 + lock-order 44. It differs from the earlier historical 178-case selection. The full 4930-case unit phase was reported on earlier 7bc-equivalent bytes with 0 failures/errors and 18 skips; its verify then failed one format gate. It was not rerun on the current head. Historical source-branch passes do not qualify this extraction.

What the actual original-owner run proves

The owner was attached through the existing Hosted routes, kept runtime generation 1 / writer generation 1 / activation epoch 1, executed one settled file turn (2 model requests, 1 retained main usage projection), and retired through freeze → cut → original-worker finalize → DRAINED version 4. Writer acquire stayed 1 → 1, and no additional execution prepare/start or model request occurred. Completed cached retry, a direct fresh status GET, and a new independent HTTP store client's complete returned the same saved result. The latter two complete 33-table image files were independently compared with the DRAINED image: objects and raw file bytes were identical. Later attach/text returned the closed-admission refusal.

Original execution and usage rows, working bytes/device/inode, and retained backup pins stayed exact. Only the logical Runtime Session became RELEASED; binding and holder remained DRAINING and the slot remained occupied. The original native inspector's root FD 19 was associated with its real FileHandle; after finalization it returned EBADF and disappeared from the owned FD map. All 4 captured worker/backend native handles returned EBADF, with zero owned handles left. The separate fixture observation handle remained open until its own cleanup and was not counted as worker-owned.

Evidence: final-0a039626d/actual-owner-1turn-193955-ce5d5650/ (actual-owner-report.json, completed-status-diagnostic.json, independent-complete-retry.json, native-descriptor-evidence.json, and exact phase/full-table images). Standard SQL evidence: final-0a039626d/mysql-194017-0d8cd2f1/. Final BOOLEAN/full inventory: final-bbea48878/mysql-194815-d3f8cf58/ and mysql-194831-07e1bf94/. These paths are under the owned k2-application-retirement-evidence-20261019/ evidence directory.

The two ordinary Workspace methods failed before the intended tool-fault boundaries, at tool-sessions:acquire with 409 workspace_unavailable. The fault driver recorded faults=0; those tool fault cuts are not qualified. This run's read-only diagnostic established both session-authorization calls passed, but both sessions had zero storage aliases/owners and the physical-storage-key guard refused at LocalStorageOwners.key:76. The local macOS fixture had not registered that physical root. The relevant local-storage guard and Workspace authority/test sources match the frozen base; ManagedAgentStore itself is changed by this PR, so an all-source equivalence claim is not made. A complete base E2E/Linux control was not run. These remain two failures; no previous PR's attribution or private CSI qualification is substituted. Evidence: final-bbea48878/regression-workspace-195156-7bb44c51/. Retained and ordinary Hosted passes are separate results (mysql-195033-9a36752c/, regression-hosted-195132-f2506d53/). The ordinary process run (regression-process-195222-e2209083/) had no selected-case flag; its log records all six harness/Spring/worker kill/stop cuts, plus the coordinator-restart method passed. Those remain ordinary Hosted evidence.

Scope and remaining acceptance limits

The supported private path is a settled, live original runtime generation 1 / writer generation 1 / activation epoch 1. DRAINED grants no node evidence, physical stop, CSI unpublish, binding/holder RELEASED, reuse, recovered-owner retirement or public selector authority. The actual owner run uses declared local mount/proc-FD/placement facades over real files and handles; it does not establish native CSI deployment, packaged Main, OS-process death or Linux physical behavior. Ordinary Hosted/Workspace/process regression results do not grant private CSI death or cold-owner qualification. Unit promise/mount/HTTP mocks are only unit evidence; the actual Hosted route qualification above is reported separately.

The original owner preserves parent-first same-Connection ordering. OTHER association validation retains late foreign-parent locks after bounded whole-table child scans; competing ordinary writers may deadlock/time out, roll back and require retry. Maintainer review and actual cross-tenant writer-race acceptance remain required. The repository formal review workflow was unavailable in this session; maintainer review is still pending. Local checks used macOS, Node 22.14.0, JDK 21 and Maven 3.9.16; Windows/Linux were not tested locally, and 33 CLI platform cases were skipped.

Final handoff: all 90 source hashes and 17,697 product pins matched the frozen candidate; MJS and V12 source/target checksums matched. No owned candidate processes remained. The owned MySQL server exited, its four remaining databases were dropped, and its data/socket/credential directory was removed. Evidence is in final-bbea48878/final-products-unchanged.json and cleanup.json. No further candidate execution or product edits followed.

Self-review records separate the two complete reads of the earlier 89-file extraction from later corrective-commit diff/consumer reads and the small fixture follow-ups. They do not claim two new complete 90-file PR reads or formal approval. Final source/product pin checks accompany the owned acceptance results.

Preserved failures and convergence history
  • Fresh global qwen 0.25.2 attach/text/retire returned 404: unavailable capability only, not an SQL reproduction. Earlier missing JS build prerequisites and the old SETTLING expectation remain in their logs; root build and later focused checks superseded them.
  • First clean Maven run: 4922 cases, 3 failures, 1 error, 18 skips. The corrected roots were an obsolete schema11 assertion, the old intentional boot6 rejection, the precise refusal for an unactivated sealed reader, and the lock-order parser's inability to resolve exact same-file final receiver types. Refusal before fetch/receipt/lease and unknown-receiver failure were retained; five positive/negative parser meta cases protect the narrow resolution. A separate projection builder omission of declared NULL cells was fixed without relaxing identity comparisons.
  • First real MySQL attempt on 55fc: 4 SQL = 3 passed/1 failed; inventory 62 = 59 passed/2 failed/1 errored; retained graphs 31/31 passed. Initial retirement status refused because persisted and snapshot handles had different object-key order. Strict parsed qualification fixed that one association; frozen raw bytes and whole-image equality stayed exact. The CHECK constraint really rejected with MySQL HY000/3819 but a different Spring wrapper; its assertion now verifies the exact named underlying constraint/code. An escaped oversized setup statement exceeded the disposable 64 MiB packet limit; increasing only that owned server to 128 MiB made the unchanged case pass. Production limits were not raised.
  • The first BOOLEAN ALTER fixture lost NOT NULL/default. Its preservation helper later still looked up uppercase keys while the actual managed row mapper returns lowercase keys. The exact 0a diagnostic recorded archived BOOLEAN NULL, NO/default0 → YES/null and the strict schema validator's nullability refusal. bbea changes only the two Map lookup strings; neither production schema nor rejection assertions were weakened. The 0a 63-case result remains 62 passed/1 failed; the bbea 63-case pass is a separate run.
  • 7bc-equivalent full unit phase: 4930 reported, 0 failures/errors, 18 skips. Overall verify failed one runtime-broker Checkstyle blank line; SpotBugs was not reached. 883 removed only that line and passed affected 158 plus both Checkstyle configurations/SpotBugs/packaging. This is not a full-suite rerun on a later commit.
  • The old mount fixture bypassed native withVerifiedRoot, leaving the private root directory uninitialized. A transparent first-call wrapper confirmed this original freeze failure. c90 maps only provenance/root paths and retains native observe/withVerifiedRoot/isAvailable/close/inspection, with real EBADF closure checks. No inspection or close flags were stubbed.
  • c90 then completed retirement but its fresh historical status failed. Its completed-owner cached retry did not qualify a fresh DB read. Actual comparison of all 14 retirement components found only handle JSON text unequal; the other 13 and strict parsed JSON were equal. A focused ordered-begin/unordered-history regression first failed at the exact helper, then passed after the minimum qualifier repair. The record-equality fast path preserves existing both-null identities; the fallback strictly parses only non-null handle objects and retains exact comparison of the other 13 components. Changed content, duplicate keys, trailing objects, arrays and four foreign identity fields still refuse. Snapshot bytes, digests and global mappers were not changed. The final 0a actual fresh GET/new-client and 4-SQL positives supersede that failure.

Owned local logs include application-main11a-build-typecheck-bundle.log, application-core-focused.log, application-cli-focused.log, application-finalizer-strict-focused.log, application-java-clean-verify.log, application-java-convergence-focused-final.log, application-java-mysql-convergence-focused.log, application-java-clean-verify-final.log, application-java-final-scoped-verify.log, application-java-retained-identity-before-fix.log, application-java-retained-identity-after-fix.log, application-java-retained-identity-final-verify.log and application-java-metadata-key-test-compile.log.


E2E 与验证报告——原始 CSI 应用退役

当前候选:bbea488786f00b8d0f54f8b4a6658cbc3b017b2e;冻结main基线:11a6346aa92b5e2f473464174e6043d053bf8010;累计source:1a6529b73c007044d9d04e0614fbc30ebe13c0ac。90文件source清单为 .qwen/e2e-tests/application-candidate-metadata-key-sha256.json,SHA-256为 72ddccd73acdddb43233d88037a65197be8cf1b8750d251dde10c3b4e61eea62。main在冻结基线之后已前进,验收期间没有手工rebase。

当前结果如下。0a03962→bbea488只修改MySQL测试fixture的两个元数据lookup键;独立比较全部17,697项产品pin,只有对应测试class不同,全部生产产品字节相同。0a通过结果继续保留其精确source归属。

检查 候选 / 结果
从最初attach开始的实际原始Hosted owner 0a03962:PASS,exit0;一个settled文件turn→DRAINED v4
原token fresh SQL status及新建独立HTTP store client 0a03962:GET200、返回精确完成结果;各自保持完整33表原像不变(32张managed库存表+Flyway history)
标准真实MySQL/SQL/worker用例 0a03962:4/4通过,0失败/error/跳过,包含两turn退役的fresh complete重试及原恢复回归
真实MySQL BOOLEAN回归 bbea488:1/1通过,0失败/error/跳过,5.493秒
完整真实MySQL库存profile bbea488:63/63通过,0失败/error/跳过,94.978秒
最终MySQL保留图profile bbea488:31/31通过,0失败/error/跳过,53.244秒
匹配的普通Hosted回归 bbea488:2/2通过,0失败/error/跳过,14.950秒
匹配的普通Workspace/tool-fault回归 bbea488:2/2失败,0 error/跳过,13.469秒;初始acquire在fault cuts前拒绝;实证缺少物理storage注册
匹配的普通process回归 bbea488:2/2通过,0失败/error/跳过,129.896秒;含6个普通process fault cuts及coordinator重启
相关Java消费者及完整static/packaging阶段 0a03962:178/178通过,0失败/error/跳过;两套Checkstyle0,SpotBugs 0 bug instance/0 error,packaging通过;exit0、1:26
TypeScript构建与focused检查 root build/typecheck/bundle通过;Core233/233;CLI575通过/33项平台跳过;strict finalizer/worker子集43/43。此后无TypeScript生产变更。

最终Java178项是退役17+history3+库存63+native activation20+保留图31+锁序44,与更早历史178项选择不同。更早7bc等价源码的完整单测阶段报告4930项、0失败/error、18跳过,但其verify随后因一项格式门禁失败;没有在当前head重跑整套。source分支历史通过不能证明本提取合格。

实际原owner运行证明了什么

通过既有Hosted路由完成最初attach,保持runtime generation1 / writer generation1 / activation epoch1,运行一个settled文件turn(2次模型请求、保留1行main真实用量投影),经freeze→cut→原worker finalize→DRAINED版本4。writer acquire保持1→1,无新增execution prepare/start或模型请求。完成owner的缓存重试、直接fresh status GET、新建独立HTTP store client的complete均返回相同已存结果。后两次完整33表镜像已独立与DRAINED原像比较,JSON对象和原文件字节全部相同。后续attach/text返回关闭接纳的拒绝。

原execution和usage行、工作文件字节/device/inode、保留backup pins精确不变。只释放逻辑Runtime Session;binding/holder保持DRAINING,slot继续占用。原native inspector的root FD19与真实FileHandle关联,finalize后stat为EBADF并从owned FD map消失。捕获的全部4个worker/backend native handle均为EBADF,owned handle剩余0。fixture独立观察句柄保持打开至自己的cleanup,不计作worker-owned。

证据:final-0a039626d/actual-owner-1turn-193955-ce5d5650/(actual-owner-report.json、completed-status-diagnostic.json、independent-complete-retry.json、native-descriptor-evidence.json及精确阶段/全表原像)。标准SQL:final-0a039626d/mysql-194017-0d8cd2f1/;最终BOOLEAN/完整库存:final-bbea48878/mysql-194815-d3f8cf58/与mysql-194831-07e1bf94/。均位于本轮owned k2-application-retirement-evidence-20261019/证据目录。

两个普通Workspace方法均在预期tool-fault边界之前失败,初始tool-sessions:acquire返回409 workspace_unavailable,fault driver记录faults=0,不能算相应tool fault cuts通过。本轮只读诊断确认两次session authorization均通过,但两个session的storage alias/owner均为0,LocalStorageOwners.key:76物理storage key门禁拒绝,本地macOS fixture没有注册该物理root。相关local-storage guard、Workspace authority/测试源码与冻结基线相同,但本PR修改了ManagedAgentStore,不声称全部前置source等价。未运行完整base E2E/Linux对照,这两项仍保留失败,不用其它PR归因或私有CSI资格替代。证据:final-bbea48878/regression-workspace-195156-7bb44c51/;保留图及普通Hosted通过分别记录于mysql-195033-9a36752c/、regression-hosted-195132-f2506d53/。普通process运行regression-process-195222-e2209083/无selected-case过滤,日志记录全部6个harness/Spring/worker kill/stop cuts,coordinator-restart方法也通过;这些仍只算普通Hosted证据。

范围与剩余验收边界

支持的是已settled、仍存活的原始runtime generation1 / writer generation1 / activation epoch1私有路径。DRAINED不授予node evidence、物理stop、CSI unpublish、binding/holder RELEASED、复用、恢复owner退役或公开selector authority。实际owner运行使用已声明的本地mount/proc-FD/placement映射及真实文件/句柄,不证明native CSI部署、packaged Main、OS进程死亡或Linux物理行为。普通Hosted/Workspace/process回归结果不赋予私有CSI死亡/冷owner资格。单元Promise/mount/HTTP mock只证明单元行为,与上述实际Hosted路由验收分别报告。

原owner保留parent-first同Connection锁序。OTHER归属验证仍在有界全表子行扫描后取得foreign-parent锁;与普通writer竞争可能deadlock/timeout、回滚并需要重试。仍需维护者评审及实际跨tenant writer-race验收。本会话无法运行仓库正式review工作流,维护者评审仍待完成。本地使用macOS、Node22.14.0、JDK21、Maven3.9.16;未本地测试Windows/Linux,CLI有33项平台限定跳过。

最终交接:90项source hash与17,697项product pin均与冻结候选精确相同,MJS/V12 source-target校验和相同,无owned候选进程残留。owned MySQL已退出、剩余4个数据库已drop,data/socket/credential目录已删除。证据为final-bbea48878/final-products-unchanged.json和cleanup.json,之后没有候选执行或产品编辑。

自审记录区分更早89文件提取的两遍完整阅读、之后修正提交的完整diff/实际消费者阅读及小fixture后续,不声称两遍新的完整90文件PR阅读或正式approval。最终source/product pin核对随owned验收结果保留。

保留的失败及收敛历史
  • 新跑全局qwen0.25.2的attach/text/retire返回404,只证明能力不可达,不是SQL复现。更早JS构建依赖缺失及旧SETTLING预期失败日志保留,由root build和后续focused结果替代。
  • 首轮clean Maven报告4922项、3失败、1 error、18跳过。修正根因是旧schema11断言、原故意拒绝boot6断言、未安装activation的sealed reader精确拒绝码、锁序parser不能解析同文件精确final receiver类型。保留fetch/receipt/lease前拒绝及未知receiver拒绝;5个正反parser meta用例保护收窄规则。另一项投影builder遗漏显式NULL列的失败修正后未放宽身份比较。
  • 55fc首轮真实MySQL:4SQL为3通过/1失败,库存62为59通过/2失败/1 error,保留图31/31通过。初始status因持久handle与snapshot对象键顺序不同拒绝;仅该资格关联改为严格解析值相等,冻结原字节及全镜像精确比较保留。CHECK实际以MySQL HY000/3819拒绝,但Spring异常包装不同,现核验精确底层具名约束/代码。oversized setup转义SQL超过一次性数据库64MiB packet;仅将owned数据库调至128MiB即原case通过,没有提高生产限制。
  • 原BOOLEAN ALTER fixture丢失NOT NULL/default。其保留helper之后仍用uppercase key读取,而实际managed row mapper返回lowercase;0a精确诊断记录archived BOOLEAN NULL、NO/default0→YES/null及严格schema validator的nullability拒绝。bbea只改两个Map lookup字符串,没有放宽生产schema或拒绝断言。0a的63项结果仍保留为62通过/1失败,bbea63项通过是另一轮结果。
  • 7bc等价完整单测阶段报告4930项、0失败/error、18跳过;verify因runtime-broker Checkstyle一项空行失败,未到SpotBugs。883只删空行,相关158项及两套Checkstyle/SpotBugs/packaging通过,不称后续提交完整套件重跑。
  • 旧mount fixture绕过native withVerifiedRoot,私有root directory未初始化。透明首调用wrapper确认原始freeze失败;c90仅映射provenance/root路径,保留native observe/withVerifiedRoot/isAvailable/close/inspection及真实EBADF关闭检查,没有stub检查结果或关闭标志。
  • c90随后完成退役,但fresh历史status仍失败;完成owner的缓存重试不证明fresh DB读取。实际14项退役组件比较只有handle JSON文本不同,其余13项和严格解析值均相等。ordered-begin/unordered-history focused先在精确helper复现失败,最小资格修正后通过。整record相等快速路径保留既有both-null身份;fallback仅严格解析双非空handle object,其余13项精确比较。内容变更、重复键、尾随对象、数组和4个foreign身份字段继续拒绝,没有修改snapshot字节、摘要、全局mapper。最终0a的实际fresh GET/新client与4SQL正例取代该失败状态。

本轮本地日志包括 application-main11a-build-typecheck-bundle.log、application-core-focused.log、application-cli-focused.log、application-finalizer-strict-focused.log、application-java-clean-verify.log、application-java-convergence-focused-final.log、application-java-mysql-convergence-focused.log、application-java-clean-verify-final.log、application-java-final-scoped-verify.log、application-java-retained-identity-before-fix.log、application-java-retained-identity-after-fix.log、application-java-retained-identity-final-verify.log与application-java-metadata-key-test-compile.log。

@qwen-code-review-bot

qwen-code-review-bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Qwen Triage finished — view run. See the stage comments in this thread for the result.

✅ Qwen Triage 已完成 —— 查看运行。结果见本线程中的各阶段评论。

@qwen-code-review-bot

Copy link
Copy Markdown
Collaborator

Thanks for splitting this out of #13526 — extracting a settleable slice instead of landing the cumulative branch is the right call, and the design doc pair is genuinely readable.

Template — complete ✓. All required sections present, both languages, Tested-on filled in honestly rather than optimistically.

Problem — real, and not theoretical. I checked the premise rather than taking it on faith: on main, generic activation release and Runtime Session release do refuse the CSI lane, so there is no durable cut that SQL admission, native history and the worker's open descriptors all agree on. That is an observable gap in existing code, not a hypothesised one. The qwen 0.25.2 404 baseline is correctly labelled as proving unavailable capability only — appreciated, since that is exactly the kind of claim that usually gets overread.

Direction — aligned with the managed-agent control plane, and the "original owner only, generation 1 / epoch 1, everything else refuses" framing is a disciplined way to bound a first slice. But this crosses three surfaces that are not ours to wave through: core session authority, the internal session-store contract, and the SQL schema. Escalating for maintainer architecture review, which the PR itself asks for.

Size — core paths are touched (packages/core/src/managed-runtime/**, plus a cross-package change spanning cli / core / managed-agent-server), so the two-tier gate applies. Breakdown at the reviewed head:

Category Files Lines
Production logic 55 8,918
Tests (TS + Java) 30 5,420
Test fixtures 2 316
Docs 2 146
Schema (V12 migration) 1 12

The author has admin on this repo, so the Tier 1 large-refactor hard block does not apply, and the title is feat rather than refactor — so nothing here is blocked on size. But 8,918 production lines is well past both the 500-line maintainer-awareness threshold and the 1,000-line large-PR advisory, and Tier 2 asks for 100% confidence on a core change with every downstream consumer named. I cannot honestly claim that for a durable retirement protocol spanning two languages and a schema migration, so this escalates rather than auto-approves. Informational, not a block: if any part of this can be sequenced separately, the review would land faster.

Approach — the two extractions are exactly what I would have done: encodeTransaction and commitBody let retirement reuse the ordinary commit-body builder instead of duplicating it, and I verified both are behaviour-preserving rather than assuming it. The scope question I would put to you is the inventory. WorkspaceCsiApplicationInventory.java is 3,439 lines — 39% of all production code in the PR — and most of it is a hand-maintained declaration of 32 tables and 736 columns that already exist in the Flyway baseline. I looked for the mitigation and it is there: the schema(ResultSetMetaData, Declaration) check compares live column count and names against the declaration, so drift refuses instead of silently passing, and the new ManagedSchema.validate(Connection) overload delegates to the existing ManagedSchemaCatalog.validate rather than adding a parallel validator. So this is a standing maintenance tax (every future migration touches the SQL, the projection, and the catalogue), not a correctness hole. Worth a deliberate decision that the explicit catalogue is the shape you want to carry forward, since it is the single largest thing in the diff and the hardest to undo later.

Risk — no match against the revert-history high-risk paths. The elevated risk here is the one you flagged yourself: the foreign-parent lock ordering taken after bounded whole-table child scans, and the unverified cross-tenant races. That is a maintainer architecture question, not something a static pass can settle.

Moving on to code review. 🔍

中文说明

感谢把这部分从 #13526 拆出来——提取一个可独立结算的切片,而不是直接合并累计分支,这个方向是对的,双语文档也确实可读。

模板 — 完整 ✓。必需章节齐全,中英双语,Tested-on 如实填写。

问题 — 真实存在,不是理论性加固。我核实了前提而没有直接采信:在 main 上,通用 activation 释放与 Runtime Session 释放确实拒绝 CSI 通道,因此 SQL 接纳、native history 与 worker 打开的描述符之间没有共同认可的持久切点。这是现有代码中可观测的缺口,不是假设。qwen 0.25.2 的 404 基线被正确标注为"仅证明能力不可达"——这一点很好,因为这类结论通常会被过度解读。

方向 — 与 managed-agent 控制面一致,"仅原 owner、generation 1 / epoch 1、其余一律拒绝"的界定方式很有纪律。但本变更跨越三个不能由 gate 单独放行的面:core session authority、internal session-store 契约、SQL schema。现转交维护者做架构评审,这也是 PR 自身提出的请求。

规模 — 触及核心路径(packages/core/src/managed-runtime/**,以及跨 cli / core / managed-agent-server 的跨包变更),因此适用两级门禁。评审 head 的构成如下:

类别 文件数 行数
生产逻辑 55 8,918
测试(TS + Java) 30 5,420
测试夹具 2 316
文档 2 146
Schema(V12 迁移) 1 12

作者在本仓库具有 admin 权限,因此 Tier 1 大型 refactor 硬阻断不适用;标题为 feat 而非 refactor,也不会因规模被阻断。但 8,918 行生产代码远超 500 行的维护者关注阈值与 1,000 行的大 PR 建议阈值,而 Tier 2 对核心变更要求 100% 确信并能点名每一个下游消费者。对一个跨两种语言与一次 schema 迁移的持久退役协议,我无法诚实地声称达到该标准,因此走升级流程而非自动批准。仅供参考、不构成阻断:如果有部分能单独排期,评审会更快落地。

方案 — 两处提取正是我会采用的做法:encodeTransaction 与 commitBody 让退役路径复用普通 commit-body 构建器而不是重复实现,并且我核实了两者行为等价,而非默认如此。我想提请你考虑的范围问题是 inventory:WorkspaceCsiApplicationInventory.java 有 3,439 行,占全部生产代码的 39%,其中大部分是对 Flyway 基线中已存在的 32 表、736 列的手工声明。我确认了缓解措施确实存在:schema(ResultSetMetaData, Declaration) 会把实际列数与列名和声明逐一比对,因此 schema 漂移会拒绝而不是静默通过;新增的 ManagedSchema.validate(Connection) 重载委托给既有的 ManagedSchemaCatalog.validate,没有引入平行校验器。所以这是一笔长期维护成本(今后每次迁移都要同时改 SQL、projection 与 catalogue),不是正确性漏洞。但它是 diff 中最大的单体,也是最难回退的部分,值得明确决定是否要长期保留这种显式 catalogue 形态。

风险 — 未命中回滚历史中的高风险路径。此处真正的风险是你自己指出的那一项:有界全表子行扫描之后取得 foreign parent 锁的锁顺序,以及尚未验证的跨 tenant 竞争。这属于维护者的架构问题,静态评审无法定论。

进入代码审查 🔍

— Qwen Code · qwen3.8-max-2026-09-02

Reviewed at bbea488786f00b8d0f54f8b4a6658cbc3b017b2e · re-run with @qwen-code /triage

@qwen-code-review-bot

qwen-code-review-bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

Code review

I read the production diff against main and verified the things that are cheap to get wrong rather than assuming them. What holds up:

  • V12 migration is safe to land. Main tops out at V11, so there is no version collision — worth stating explicitly, because two files named V12__*.sql merge cleanly in git and only fail at runtime. The generated column csi_retirement_target_key CHAR(64) exactly matches ma_operation.target_key CHAR(64) NOT NULL in the V1 baseline, and relying on MySQL's NULL-distinct unique semantics to scope uq_ma_csi_retirement_target to CSI_RETIREMENT rows only is the correct way to express that. ManagedSchema.EXTENSIONS and ManagedSchemaProjection.OPERATION are both updated consistently with all eleven new columns plus the generated one.
  • The new controller mounts cleanly. It shares @RequestMapping with ManagedSessionStoreController but the method paths are disjoint, so there is no ambiguous mapping. Its dual @ConditionalOnProperty on session-store.enabled + runtime-broker.enabled is identical to the condition on its own bean in RuntimeBrokerConfiguration, so the controller can never mount without its dependency. The /internal/** boundary is preserved — BrokerSecurity still requires a configured writer binding key before that surface may leave loopback.
  • Route auth is not a regression. retire binds tenantId, workspaceId and bindingId from the body to the existing owner before doing anything, which is strictly more than the sibling /internal-csi/text route checks. I went looking for a missing fingerprint check and the honest answer is that the existing internal-csi routes do not re-verify it either, so this is consistent with the surface's trust model rather than a new hole.
  • Both extractions are behaviour-preserving. In encodeTransaction the record construction now happens before the assertReaderFacingBody loop, which would matter if either had side effects — createRecord only generates a UUID and builds an object, and the assert only reads, so a throw leaves state untouched either way. The commitBody extraction is line-for-line identical to the inline code it replaced. Every helper the new core code calls (corrupt, nullableDigest, safeCounter, asRecord, assertManagedSessionStableId) already exists on main.
  • completeOriginalCsiRetirement is well-formed. Exact closed key set on the status object, stage ↔ progressVersion ↔ digest-presence invariants pinned together, and monotonicity enforced against the previously observed status so a saved cut or receipt cannot silently change between retries.
  • CsiOwnershipRevision narrows rather than widens. Replacing the raw SQL csi_revision = csi_revision + 1 with an explicit next() that only permits 0→1 and 1→2 is an improvement, and reserved(revision) == (revision == 1) is semantically identical to the hardcoded check it replaced. decodeRetirement is also substantially stronger than what it replaced — it now derives and cross-checks roughly twenty invariants (operation key, scope hash, target kind/id/key, request digest, payload version, exact envelope and data shape) instead of trusting identity_json.
  • The mapper-agnostic handle comparison fixes a real defect class. Byte-exact comparison of resourceHandleJson is not stable across Jackson key-ordering configurations, so a legitimate retirement could be refused on a semantically identical handle. Falling back to a canonical parse and then re-checking every other field for exact equality is the right shape, and the new test pins both the acceptance and the refusals (mutated value, duplicate keys, trailing garbage, array, and foreign resourceHandleKind / runtimeInstanceId / leaseId / leaseDigest).

What I would want answered before merge — these are questions, not blockers, and in each case the fail-closed reading may well be the intended one:

  1. owner.failures is append-only and permanently blocks retirement. track() now records every rejected background task, and the renewal timer pushes on every falsy or rejected renewActivation. Nothing ever clears the array, and the retire path refuses with csi_retirement_task_failed whenever it is non-empty. So one transient renewal blip — or one text turn that failed an hour ago and was already reported to its caller — makes that owner unretireable until the process restarts. The design doc does say failures stay recorded, so this may be deliberate, but the consequence is that a healthy live session becomes permanently un-drainable, and that deserves an explicit decision rather than falling out of the bookkeeping.
  2. joinOriginalCsiWriter() stops renewal before it checks whether it may proceed. this.stopRenewal() runs ahead of the acquirePromise || pendingAppend guard, so on the refused path renewal is already stopped and retirementJoin is never set — later renewWriter() calls still reject on renewalStopped, and the lease expires. Everywhere else this PR refuses without mutating, so this asymmetry stands out. It is harmless if SQL beginRetirement always seals the binding before the worker is asked to join; please confirm that ordering is guaranteed and not merely how the current caller happens to sequence it.
  3. prepareOriginalCsiRelease() caches a rejected promise forever. Because retirementPreparation is never cleared, one transient failure inside preparation leaves runSerial rejecting every subsequent operation and close() throwing permanently. Same fail-closed question as (1), and the two compound: a session that fails preparation can neither proceed nor shut down cleanly.
  4. Minor: Math.addExact(revision, 1) in CsiOwnershipRevision.next() is unreachable overflow protection, since the guard above it already rejects anything greater than 1.

The foreign-parent lock ordering you flagged is the one thing I would not attempt to settle from a static read. I confirmed the intended parent-first order is actually wired (lockBindingControl then JdbcCsiApplicationProgress.lock before lockActiveForRetirement), and that lockRetirementBinding now unwraps to the target connection and asserts it is transactional — which is a genuine fix, since taking a row lock on a wrapper connection would not hold it for the transaction. Whether the late foreign-parent acquisition is acceptable under concurrent ordinary writers for another owner is an architecture call for a maintainer.

sequenceDiagram
    participant P1 as Hosted owner retire route
    participant P2 as Local session authority
    participant P3 as HTTP store client
    participant P4 as Application store
    participant P5 as SQL ma_operation
    participant P6 as Original worker
    P1->>P1: latch admission, stop renewal, join admitted tasks
    P1->>P2: prepareOriginalCsiRelease
    P2-->>P1: staged release records, not appended locally
    P1->>P3: joinWriter then prepare(records)
    P3-->>P1: commit body bytes and prepared digest
    P1->>P4: complete(retirementId)
    P4->>P5: status read, stage SETTLING version 1
    P4->>P5: freeze, stage FROZEN version 2
    P4->>P5: cut, stage CUT version 3, seal head
    P4->>P6: finalize RPC outside the SQL transaction
    P6-->>P4: exact cleanup facts, descriptors closed
    P4->>P5: stage DRAINED version 4, release logical Runtime Session
    P4-->>P1: status DRAINED
Loading
Files changed (20 of 90 shown)
File What changed
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/managedagent/store/WorkspaceCsiApplicationInventory.java New 3,439-line typed catalogue of all 32 tables and 736 columns, with bounded discovery, fixed-point reference expansion, and a live ResultSetMetaData drift check
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/managedagent/store/WorkspaceCsiApplicationStore.java New store driving status / freeze / cut / finalize behind the operator-authenticated prefix
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/managedagent/store/WorkspaceCsiApplicationHistory.java New native history and retained-projection validation chain
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/runtimebroker/JdbcCsiActivationAdmission.java Largest Java edit; admission now consumes same-Connection retirement progress so ordinary mutation refuses once FROZEN
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/managedagent/store/WorkspaceCsiReservationStore.java Begin persists SETTLING plus an overflow-checked settlement deadline; revision moves to the explicit CsiOwnershipRevision machine; decodeRetirement and retained-identity checks substantially strengthened
packages/core/src/managed-runtime/http-managed-session-store.ts New csiRetirement surface (joinWriter / prepare / complete), commit-body extraction, and admission closed to seal / ensureWriter / renewWriter once retirement owns the boundary
packages/core/src/managed-runtime/managed-session-authority.ts New prepareOriginalCsiRelease staging one exact terminal suffix; encodeTransaction extraction; runSerial and close refuse once preparation is latched
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/runtimebroker/JdbcCsiExecutionAdmission.java Execution admission reads same-Connection progress
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/managedagent/store/WorkspaceCsiApplicationWorkerMatch.java New worker-match validation for finalization authority
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/runtimebroker/JdbcCsiRetirementSeal.java New head sealing at CUT
packages/cli/src/serve/managed-csi-file-worker.ts Worker finalization: compares executions, grants, receipts, history and files both directions, closes admission and descriptors
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/runtimebroker/JdbcCsiApplicationRetirement.java New retirement admission queries
packages/cli/src/serve/managed-csi-file-finalize-protocol.ts New explicit boot6 / resource-handle4 finalizer contract
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/managedagent/store/ManagedSessionStore.java Native store extended for the new progress fields
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/runtimebroker/CsiNativeActivationProof.java Activation proof extended for the retained terminal suffix
packages/cli/src/serve/managed-runtime-tool-executor.ts Executor refuses once retirement admission closes
packages/cli/src/serve/hosted-csi-session.ts New authenticated retire route, admission latch, renewal join, failure retention
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/runtimebroker/JdbcRuntimeSessionRepository.java Logical Runtime Session release at DRAINED
packages/managed-agent-server/src/main/java/com/alibaba/qwen/code/managedagent/api/WorkspaceCsiApplicationController.java New internal controller exposing status and the three commands
packages/managed-agent-server/src/main/resources/db/managed-schema/V12__csi_application_retirement.sql Additive V12: eleven ma_operation progress / unique-target fields, V11 untouched
…and 70 more files 30 test files (5,420 lines), 2 contract fixtures (316), 2 design docs (146), and the remaining smaller production edits

Testing

There is no test verdict for the code under review. Stating that plainly, because it is the most decision-relevant fact in this pass:

  • At the reviewed head bbea4887, all five PR-CI workflow runs are still queued or pending. Nothing has reported.
  • At the previous head c90f6f66, CI was cancelled by concurrency supersession before any test job produced a result. The check annotation reads: Canceling since a higher priority waiting request for Qwen Code CI-pull_request-QwenLM/qwen-code-codex/csi-application-retirement exists. Cancelled, not failed: Test (ubuntu-latest, Node 22.x), Lint & Static (ubuntu-latest, Node 22.x), Integration Tests (no-AK, No Sandbox), web-shell E2E Smoke, Serve A/B, SDK Java (fast) / ubuntu-latest / Java 21, SDK Java (fast) / Flyway migration version uniqueness, and SDK Java (fast) / Real daemon E2E / Java 11 all report cancelled. Only tui-parity and the orchestration jobs (Classify PR, Select the Managed Agent tier, OpenTUI no-flicker gate, TUI parity snapshots, Remind on force-push) completed green — none of which compile, lint or test this change.
  • Two commits landed after the evidence in the PR description was written. Comparing 883efe2b — the commit the description says passed the full Java unit phase, both Checkstyle gates and SpotBugs — against the current head, production code changed in exactly one file: WorkspaceCsiReservationStore.java, +20/−3 (commit 0a039626, the mapper-agnostic handle fix). The description's statement that the candidate carries "identical Java/TypeScript production bytes" was true of c90f6f66 and is no longer true of the head.

So no automated result and no author-reported result currently covers the head's production bytes. Everything in the PR description's Evidence section is the author's own local macOS claim about earlier commits — I am attributing it as that, not adopting it as verification, and per the module's rules H2 and labelled mock seams do not establish MySQL or process-recovery behaviour in any case.

Also load-bearing and to the author's credit for stating it: the description reports that the happy path reached DRAINED v4, but "the separate fresh persisted-status SQL retry currently refuses and is being diagnosed". Exact retry after a lost reply is one of the acceptance criteria in the design doc, so a required item is currently failing by the author's own account.

Not verified, and why: build / typecheck / lint / unit tests (CI cancelled then superseded on the head); Windows and Linux (author states untested, 33 platform-specific checks skipped locally); cross-tenant races and the full process/fault profiles (author states pending); MySQL acceptance on the head (the described run predates 0a039626).

CI results for bbea488 — this table auto-updates as CI workflows complete:

Check Conclusion
SDK Java (fast) / ubuntu-latest / Java 21 ⏳ running
Test (ubuntu-latest, Node 22.x) ⏳ running
Build and verify reference distribution ✅ success
Classify PR ✅ success
Integration Tests (no-AK, No Sandbox) ✅ success
Lint & Static (ubuntu-latest, Node 22.x) ✅ success
OpenTUI no-flicker gate ✅ success
SDK Java (fast) / Flyway migration version uniqueness ✅ success
SDK Java (fast) / Real daemon E2E / Java 11 ✅ success
Select the Managed Agent tier ✅ success
Serve A/B (ubuntu-latest, Node 22.x) ✅ success
TUI parity snapshots (ink vs opentui) ✅ success

One row per check name (latest run); skipped checks omitted; failures sort first. / 每个检查名一行(取最新一次运行),省略 skipped,失败项排在最前。

Sandboxed verification would settle this: @qwen-code /verify — that the protocol actually drives SETTLING → FROZEN → CUT → DRAINED to version 4 on real SQL, that an exact retry after a lost reply returns identical saved bytes without acquiring another writer or worker, and that a foreign tenant / binding / writer-generation / epoch crossing refuses without an undeclared durable change. None of that is observable from the diff, the PR's own CI has produced no verdict on this head, and the description already reports the persisted-status retry refusing. The author has write access, so this can be triggered directly rather than sponsored.

中文说明

代码审查

我对照 main 阅读了生产代码 diff,并对容易出错的地方做了核实而不是默认采信。站得住的部分:

  • V12 迁移可以安全落地。 main 目前最高为 V11,不存在版本冲突——这一点值得明确说明,因为两个同名 V12__*.sql 在 git 层面能干净合并,只会在运行时失败。生成列 csi_retirement_target_key CHAR(64) 与 V1 基线中的 ma_operation.target_key CHAR(64) NOT NULL 完全一致;依赖 MySQL 唯一索引对 NULL 的互异语义,把 uq_ma_csi_retirement_target 限定在 CSI_RETIREMENT 行上,是正确的表达方式。ManagedSchema.EXTENSIONS 与 ManagedSchemaProjection.OPERATION 均已同步更新,涵盖十一个新列及生成列。
  • 新 controller 可以正常挂载。 它与 ManagedSessionStoreController 共用 @RequestMapping,但方法级路径互不重叠,不存在歧义映射。其 session-store.enabled + runtime-broker.enabled 双重 @ConditionalOnProperty 与 RuntimeBrokerConfiguration 中对应 bean 的条件完全一致,因此不会出现 controller 挂载而依赖缺失的情况。/internal/** 边界保持不变——BrokerSecurity 仍要求在离开 loopback 前配置 writer binding key。
  • 路由鉴权没有退化。 retire 在执行任何操作前会把 body 中的 tenantId、workspaceId、bindingId 与既有 owner 绑定校验,这比同级的 /internal-csi/text 检查得更严格。我专门找过是否缺少 fingerprint 校验,诚实的结论是:现有 internal-csi 路由同样不会二次校验它,因此这与该面既有的信任模型一致,不是新引入的缺口。
  • 两处提取均保持行为等价。 encodeTransaction 中 record 的构造现在发生在 assertReaderFacingBody 循环之前——如果二者有副作用这就会有问题,但 createRecord 只生成 UUID 并构造对象,assert 只做读取,因此抛错路径下两种方式都不会留下状态变更。commitBody 的提取与被替换的内联代码逐行一致。新核心代码调用的所有辅助函数(corrupt、nullableDigest、safeCounter、asRecord、assertManagedSessionStableId)在 main 上均已存在。
  • completeOriginalCsiRetirement 结构严谨。 status 对象采用精确封闭键集合,stage ↔ progressVersion ↔ digest 存在性三者互相钉住,并对此前观测到的 status 强制单调性,使得已保存的 cut 或 receipt 不会在重试之间被悄悄改变。
  • CsiOwnershipRevision 是收紧而非放宽。 用只允许 0→1 与 1→2 的显式 next() 替换裸 SQL csi_revision = csi_revision + 1 是改进;reserved(revision) == (revision == 1) 与其替换掉的硬编码判断语义完全相同。decodeRetirement 也比被替换的版本强得多——现在会推导并交叉校验约二十项不变量(operation key、scope hash、target kind/id/key、request digest、payload version、精确的 envelope 与 data 形状),而不再信任 identity_json。
  • 跨 mapper 的 handle 比较修复了一类真实缺陷。 对 resourceHandleJson 做字节级精确比较在 Jackson 键排序配置不同时并不稳定,因此语义完全相同的 handle 也可能导致合法退役被拒绝。回退到规范化解析、再对其余每个字段做精确相等校验,是正确的形态;新增测试同时钉住了接受路径与拒绝路径(取值被改、重复键、尾部垃圾、数组,以及外来的 resourceHandleKind / runtimeInstanceId / leaseId / leaseDigest)。

合并前我希望得到回答的问题——这些是提问而非阻断项,且每一项按 fail-closed 理解都可能正是设计意图:

  1. owner.failures 只增不减,会永久阻断退役。 track() 现在记录每一个被拒绝的后台任务,续租定时器也会在每次 renewActivation 返回假值或被拒绝时写入。该数组永不清空,而 retire 路径只要它非空就以 csi_retirement_task_failed 拒绝。因此一次瞬时的续租抖动——或一小时前已经向调用方报告过的失败 turn——会让该 owner 在进程重启前无法退役。设计文档确实写明失败要被保留,所以这可能是有意为之,但其后果是一个健康的存活会话永久无法 drain,值得明确决策,而不应由记账逻辑顺带决定。
  2. joinOriginalCsiWriter() 在判断是否允许之前就停止了续租。 this.stopRenewal() 位于 acquirePromise || pendingAppend 判断之前,因此在被拒绝的路径上续租已经停止,而 retirementJoin 从未被设置——后续 renewWriter() 仍会因 renewalStopped 被拒绝,租约随即到期。本 PR 其他所有位置都是"拒绝且不产生变更",这处不对称因此显眼。如果 SQL beginRetirement 总是在请求 worker join 之前先 seal binding,它就是无害的;请确认该顺序是被保证的,而不只是当前调用方恰好如此编排。
  3. prepareOriginalCsiRelease() 会永久缓存一个已拒绝的 promise。 由于 retirementPreparation 从不清除,preparation 内部一次瞬时失败就会让 runSerial 拒绝之后所有操作、close() 永久抛错。与第 1 点是同一个 fail-closed 问题,且二者会叠加:preparation 失败的会话既无法继续,也无法干净关闭。
  4. 次要:CsiOwnershipRevision.next() 中的 Math.addExact(revision, 1) 是不可达的溢出保护,因为其上方判断已拒绝大于 1 的取值。

你自己指出的 foreign parent 锁顺序,是我不会尝试用静态阅读下结论的一项。我确认了预期的 parent-first 顺序确实已接线(lockBindingControl,再 JdbcCsiApplicationProgress.lock,最后 lockActiveForRetirement),也确认 lockRetirementBinding 现在会解包到 target connection 并断言其处于事务中——这是实实在在的修复,因为在包装 connection 上取行锁不会为事务持有该锁。但在另一 owner 的普通写入并发下,延后取得 foreign parent 锁是否可接受,属于维护者的架构判断。

测试

本次评审的代码没有任何测试结论。 直说这一点,因为它是本轮最具决策相关性的事实:

  • 在评审 head bbea4887 上,五个 PR-CI workflow run 全部处于 queued 或 pending,没有任何结果。
  • 在上一个 head c90f6f66 上,CI 在任何测试 job 产出结果之前就被并发机制取消。check annotation 原文为:Canceling since a higher priority waiting request for Qwen Code CI-pull_request-QwenLM/qwen-code-codex/csi-application-retirement exists。是取消而非失败:Test (ubuntu-latest, Node 22.x)、Lint & Static (ubuntu-latest, Node 22.x)、Integration Tests (no-AK, No Sandbox)、web-shell E2E Smoke、Serve A/B、SDK Java (fast) / ubuntu-latest / Java 21、SDK Java (fast) / Flyway migration version uniqueness、SDK Java (fast) / Real daemon E2E / Java 11 全部为 cancelled。只有 tui-parity 与编排类 job(Classify PR、Select the Managed Agent tier、OpenTUI no-flicker gate、TUI parity snapshots、Remind on force-push)为绿色——它们都不会编译、lint 或测试本变更。
  • 在 PR 描述写下证据之后又落了两个 commit。将描述中称已通过完整 Java 单测阶段、两套 Checkstyle 与 SpotBugs 的 883efe2b 与当前 head 对比,生产代码只有一个文件发生变化:WorkspaceCsiReservationStore.java,+20/−3(commit 0a039626,即跨 mapper 的 handle 修复)。描述中"Java/TypeScript 生产字节完全相同"的说法对 c90f6f66 成立,对当前 head 已不成立。

因此,目前没有任何自动化结果或作者报告的结果覆盖 head 的生产字节。PR 描述 Evidence 一节的全部内容都是作者本人在 macOS 上对更早 commit 的声明——我按此归属,不将其当作验证采信;并且按照本模块的规则,H2 与已标注的 mock seam 本来也不能证明 MySQL 或进程恢复行为。

同样关键、也应归功于作者如实写明:描述称happy path 已到达 DRAINED v4,但"独立重新读取持久状态的 SQL 重试目前仍拒绝,正在定位"。丢失响应后的精确重试是设计文档中的验收标准之一,因此按作者自己的说明,一项必需验收项目前是失败的。

未验证项及原因:build / typecheck / lint / 单测(head 上 CI 先被取消后被取代);Windows 与 Linux(作者说明未测试,本机跳过 33 项平台限定用例);跨 tenant 竞争与完整 process/fault profile(作者说明待完成);head 上的 MySQL 验收(所述运行早于 0a039626)。

沙箱验证可以定论这一点:@qwen-code /verify——即该协议是否真的在真实 SQL 上驱动 SETTLING → FROZEN → CUT → DRAINED 至 version 4;丢失响应后的精确重试是否返回完全相同的保存字节、且不获取另一个 writer 或 worker;跨 tenant / binding / writer generation / epoch 时是否在无未声明持久变更的前提下拒绝。这些都无法从 diff 观测,本 PR 自己的 CI 在该 head 上没有产出任何结论,而描述本身已报告持久状态重试被拒绝。作者具有 write 权限,因此可以直接触发,无需 sponsored run。

— Qwen Code · qwen3.8-max-2026-09-02

Reviewed at bbea488786f00b8d0f54f8b4a6658cbc3b017b2e · re-run with @qwen-code /triage

@qwen-code-review-bot

Copy link
Copy Markdown
Collaborator

Confidence: 3/5 — the parts I could verify are disciplined and several are better than what they replace, but a core change of this size escalates to a maintainer by policy, and right now no evidence of any kind covers the head's production code.

Stepping back from the stage-by-stage detail: this does not read like volume for its own sake. My independent proposal before opening the diff was that retirement would need to reuse the ordinary commit-body builder rather than grow a second encoder, and that the holder-revision arithmetic should become a named state machine instead of csi_revision + 1 in a SQL string. The PR does both — encodeTransaction and commitBody are exactly the reuse I would have asked for, and CsiOwnershipRevision is stricter than the code it replaces. decodeRetirement going from "trust identity_json" to twenty cross-checked invariants is the same direction. If I inherited this in six months I would not curse the author for the parts I read closely.

Where I would have gone differently is the inventory. I would have tried to derive the 32-table / 736-column catalogue from the schema baseline rather than maintain it by hand beside it, because the failure mode of a hand-maintained parallel declaration is that it is correct on the day it is written and slowly stops being correct. Having read the drift check, I no longer think this is a correctness risk — schema(ResultSetMetaData, Declaration) compares live column count and names, so a migration that forgets the catalogue refuses loudly instead of passing quietly, and that is the property that actually matters. It remains 39% of the production diff and a permanent three-place edit for every future migration, so it is worth a maintainer deciding that this is the shape we want, not just that it happens to work.

What stops me approving is not a code defect. It is that I cannot currently point at any evidence for the commit under review:

  • CI on the head is entirely queued. CI on the previous head was cancelled by concurrency supersession before a single build, lint, typecheck or test job reported — so the cancelled checks are not a red signal about the code, they are an absent one, and the distinction matters.
  • Two commits landed after the PR description's evidence was written, and one of them changes production Java. The description's "identical Java/TypeScript production bytes" was accurate for c90f6f66 and is no longer accurate for the head. Nothing — CI or author — has exercised WorkspaceCsiReservationStore.java as it now stands.
  • The description itself reports that the fresh persisted-status SQL retry "currently refuses and is being diagnosed". Exact retry after a lost reply is a stated acceptance criterion in the design doc, so a required item is failing on the author's own account. Approving into that would be attesting to a result the author has told us does not exist yet.

The three fail-closed questions from Stage 2 (the append-only owner.failures array that can make a healthy session permanently un-drainable, stopRenewal() firing before the guard that may reject the join, and the permanently cached rejected preparation promise) are the kind of thing that is very plausibly intentional in a protocol whose whole philosophy is refuse-rather-than-guess. I am raising them because the consequences are asymmetric and permanent per process lifetime, not because I believe they are bugs. Someone who holds the architecture in their head can answer all three in a sentence each.

So: deferring rather than approving or rejecting. This is a Stage 0 escalation — 8,918 production lines across core session authority, the internal session-store contract and a schema migration, which is past the point where "the direction looks correct" is a sufficient standard, and the PR asks for maintainer architecture review in its own Risk & Scope section. The foreign-parent lock ordering and the unverified cross-tenant races need a human who owns that concurrency model, and the acceptance gap above needs to be closed on the actual head with CI green on it.

I could not resolve an accountable owner deterministically — $QWEN_MAINTAINER_HANDLE is unset, the PR carries no area label so the owner-map resolver matched no area, and there are no prior human reviews to fall back to — so I am not guessing a login. A maintainer watching this repo's managed-agent surface, please pick this up. Re-running @qwen-code /triage once CI has reported on the head and the retry diagnosis has landed will produce a fresh pass against that commit.

中文说明

Confidence: 3/5 — 我能核实的部分都很扎实,其中几处比被替换的代码更好;但这种规模的核心变更按策略必须升级给维护者,而且目前没有任何证据覆盖 head 的生产代码。

从逐阶段细节中抽身来看:这不是为了堆量而堆量。我在打开 diff 之前的独立判断是——退役路径需要复用普通的 commit-body 构建器,而不是再长出第二个编码器;holder revision 的运算应该成为一个具名状态机,而不是 SQL 字符串里的 csi_revision + 1。本 PR 两者都做到了:encodeTransaction 与 commitBody 正是我会要求的复用,CsiOwnershipRevision 比它替换掉的代码更严格。decodeRetirement 从"信任 identity_json"变为二十项交叉校验的不变量,方向一致。如果六个月后由我接手,对我细读过的这些部分,我不会埋怨作者。

我会采取不同做法的地方是 inventory。我会尝试从 schema 基线推导出 32 表 / 736 列的 catalogue,而不是在其旁边手工维护一份,因为手工维护的平行声明,其失效模式是:写下当天是正确的,然后慢慢变得不正确。读过漂移检查之后,我不再认为这是正确性风险——schema(ResultSetMetaData, Declaration) 会比对实际列数与列名,因此忘记同步 catalogue 的迁移会大声拒绝,而不是静默通过,而这才是真正关键的性质。它仍然占生产 diff 的 39%,并且让今后每次迁移都变成三处修改,所以值得由维护者决定这就是我们想要的形态,而不只是"它恰好能跑"。

阻止我批准的并不是代码缺陷,而是我目前无法为被评审的 commit 指出任何证据:

  • head 上的 CI 全部处于 queued。上一个 head 的 CI 在任何 build、lint、typecheck 或 test job 报告之前就被并发机制取消——因此那些被取消的 check 不是关于代码的红色信号,而是缺失的信号,这个区别很重要。
  • 在 PR 描述写下证据之后又落了两个 commit,其中一个改动了生产 Java 代码。描述中"Java/TypeScript 生产字节完全相同"对 c90f6f66 是准确的,对当前 head 已不准确。无论是 CI 还是作者,都没有运行过当前形态的 WorkspaceCsiReservationStore.java。
  • 描述本身报告:独立重新读取持久状态的 SQL 重试"目前仍拒绝,正在定位"。丢失响应后的精确重试是设计文档中写明的验收标准,因此按作者自己的说明,一项必需验收项正在失败。在这种情况下批准,等于为一个作者已告知尚不存在的结果作保。

Stage 2 中那三个 fail-closed 问题(只增不减、可能让健康会话永久无法 drain 的 owner.failures;在可能拒绝 join 的判断之前就执行的 stopRenewal();以及被永久缓存的已拒绝 preparation promise),在一个整体哲学就是"宁可拒绝也不猜测"的协议里,非常可能就是有意为之。我提出它们,是因为其后果不对称且在进程生命周期内是永久的,而不是因为我认为它们是 bug。脑中有整套架构的人,每个问题一句话就能回答。

因此:选择 defer,既不批准也不驳回。这是一次 Stage 0 升级——8,918 行生产代码跨越 core session authority、internal session-store 契约与一次 schema 迁移,已经超出"方向看起来正确"足以作为标准的范围,而且 PR 在自己的 Risk & Scope 一节中就请求维护者做架构评审。foreign parent 锁顺序与未验证的跨 tenant 竞争,需要由拥有该并发模型的人来判断;上述验收缺口需要在真正的 head 上、并且 CI 为绿的前提下补齐。

我无法确定性地解析出责任人——$QWEN_MAINTAINER_HANDLE 未设置,PR 没有 area label 因此 owner-map 解析器未匹配到任何 area,也没有既有的人工 review 可供回退——所以我不会猜一个 login。请关注本仓库 managed-agent 面的维护者接手。在 CI 对该 head 出结果、重试问题定位完成之后重新运行 @qwen-code /triage,会针对那个 commit 产生新的一轮评审。

— Qwen Code · qwen3.8-max-2026-09-02

Reviewed at bbea488786f00b8d0f54f8b4a6658cbc3b017b2e · re-run with @qwen-code /triage

yiliang114
yiliang114 previously approved these changes Oct 19, 2026

@yiliang114 yiliang114 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — original CSI application retirement @ bbea488

Reviewed the durable authority path rather than the whole 90-file surface: V12 + projections, the SETTLING→FROZEN→CUT→DRAINED transitions, the three new Session-Store endpoints, the host-side barrier/latch ordering, and the worker finalize protocol. No locally executed tests: at bbea488 the PR workflows are still queued (Serve A/B, Build and verify reference distribution, OpenTUI no-flicker gate), so this verdict rests on source only.

What I checked and found consistent:

  • Migration shape. V12 lands after main's published V11 and only adds the eleven ma_operation columns plus a generated CHAR(64) target key; the unique index is scoped by that generated column, so non-CSI_RETIREMENT rows keep multiple NULLs. ManagedSchemaProjection.OPERATION carries every new column, and the migration is registered as version 12 after 11.
  • Begin is atomic with the seal. WorkspaceCsiReservationStore.beginRetirement writes progress_format/version/stage and the checked startedAt + 300000 deadline in the same transaction as the binding seal and the RESERVED → DRAINING holder move, and the update is guarded on all four progress columns being NULL — a retry cannot reset the deadline.
  • Deadline authority. JdbcCsiApplicationProgress.requireCurrentTime / JdbcCsiApplicationRetirement.requireCurrentTime read database time under the already-held locks and use strict <, so equality with expiry is expired; the ceiling and the deadline are re-derived from the immutable operation identity rather than trusted from the row.
  • Credential boundaries. workerAuthority requires the presented bearer to equal both the provision-seed token and the lease token; with a seed present JdbcRuntimeBindingRepository.mapLease uses the seed token, so that conjunction is satisfiable only for the original owner. The writer-facing status/command paths go through requireCsiApplicationCredential, which re-validates tenant/workspace/session, the head lease-token hash and the original writer generation on the same connection. The new broker route also pins tenant, content type, no-store and a 16 KiB body bound before dispatch.
  • Transition integrity. Each stage update is a CAS on (stage, version, digest, NULL payload) and is followed by a full-image verification against baseline + terminal delta; cut inserts the terminal suffix before flipping ma_session_head to SEALED, and finalize persists the receipt before releasing the logical Runtime Session and flipping to DRAINED. A failed subsequent step rolls the whole transaction back, leaving a retryable stage rather than a half-applied one.
  • Barrier ordering on the host. The retire route latches before any await, stops the renewal timer, joins the admitted task set and the raw in-flight activation renewal, then joins the writer before touching stopLocal — which is the ordering the design requires for the in-flight grant to still validate.
  • Journal isolation. requireCsiJournalIsolation blocks private CREATE/request resolution and retirement when an event transport is installed, on both the store and the native-session side.

Non-blocking notes:

  • WorkspaceCsiApplicationStore.lock calls UUID.fromString(retirementId) directly, so a malformed id from status/command escapes as a bare IllegalArgumentException instead of the module's typed 4xx (csi_request_invalid). Cheap to route through the same validation used elsewhere.
  • The three new handlers take @RequestBody byte[], which Spring reads in full before WorkspaceCsiApplicationJson.object(...) applies the 192 KiB / 16 KiB bounds. Fine for an internal listener, but the bound is currently a post-read check rather than a transport guarantee.
  • status() runs the full typed inventory scan (up to 4096 rows / 32 MiB, with FOR UPDATE across the catalogue) on every poll, including read-only status reads.
  • RuntimeBrokerHttpServer.registerCsiApplicationAuthority adds one HttpServer context per session and the JDK server has no context-removal API. Harmless if the broker is per-session; a slow leak if one broker serves many sessions over its lifetime.

Approving on the code as reviewed. This is not a qualification of the paths the PR itself leaves open — the foreign-owner late-lock ordering, cross-tenant races, private process-death acceptance and the Linux run — and the two failing ordinary Workspace cases at bbea488 remain failures, not covered by this review.

@qqqys qqqys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

COMMENT — no blocking defect found, and no prior blocking finding exists to re-verify. This is not an approval: at +14,244/-568 over 90 files, with roughly 6,000 lines of production code and every code-executing CI lane still pending, the code-review gates for a change of this scope could not be completed inside this pass's budget. The unconfirmed gates are listed explicitly at the end so the next pass can start from them.

No historical blocking findings

This PR has one review, an approval at this head, and no automated review ledger, no inline review threads and no finding history. There is therefore nothing carried forward to re-verify, and the approval already on the PR is that reviewer's evidence rather than mine.

What I did verify at this head

I spent the budget on the surfaces where a defect would be irreversible or cross a trust boundary, rather than sampling broadly.

The new retirement endpoint authenticates every destructive action. WorkspaceCsiApplicationController is registered only under @ConditionalOnProperty for both session-store.enabled and runtime-broker.enabled, sits on the internal /internal/managed-session-store/v1/sessions/{sessionId} surface, and constrains the mutating action by path pattern to freeze|cut|finalize, so the action set is closed at the mapping rather than by a runtime string check. The controller forwards the writer-token header rather than trusting it, and WorkspaceCsiApplicationStore verifies it on every path: status, freeze, cut and finalizeApplication each call nativeStore.requireCsiApplicationCredential(target, locked.authority(), token) after taking the row lock and before acting, and each follows it with verifySaved(locked). The bearer route (workerAuthority) compares with MessageDigest.isEqual against both the provision-seed token and the lease token and answers 401 when neither matches, so the comparison is constant-time and the two-credential acceptance is explicit rather than incidental. Its Authorization header is shape-validated (length() <= 519, Bearer [A-Za-z0-9._~+/-]{1,512}=*) before substring(7). Mutating paths also re-verify the persisted image through WorkspaceCsiApplicationImage.verify(...) after writing, and the inventory lookup is tenant-scoped (operation_kind = 'CSI_RETIREMENT' AND tenant_id = ? AND operation_id = ?). Connection work is time-bounded through bounded(connection, started) / remaining(started).

The migration is additive, and its uniqueness gate is green against main. V12__csi_application_retirement.sql only adds ten nullable columns to ma_operation, one generated column and one unique constraint — no drop, no rewrite, no backfill, so it cannot destroy existing rows. The generated column is the right device for the constraint: csi_retirement_target_key is NULL unless operation_kind = 'CSI_RETIREMENT', and because a MySQL unique index permits multiple NULLs, uq_ma_csi_retirement_target (csi_retirement_target_key, target_revision) constrains only retirement operations. Flyway migration version uniqueness (latest main) passes, which is the check that matters for a version collision with another open PR; the fast-tier copy of that lane is still pending.

The seal fails closed on state and identity. JdbcCsiRetirementSeal uses locking reads throughout (SELECT ... FOR UPDATE, with setQueryTimeout(10) on requireOpen), always keyed by target_key, target_revision and tenant_id, and throws 409 csi_retirement_identity_unavailable when the retirement row is absent. lock binds the operation row to the binding state in both directions — no row requires state == READY && !draining(), a row requires state == DRAINING && draining() — and requires that there is no second row. readHistorical bounds the frozen payload to (0, 32 MiB], pins progress_format to qwen-csi-application-retirement/1 with progress_version == 4 and progress_stage == "DRAINED", and then requires the stored frozen bytes to be byte-equal to the caller's and their SHA-256 to equal the stored digest, plus a format/retirementId/bindingId/requestKey match on the frozen document. So a stale, substituted or partially written frozen request cannot be accepted.

Why this is not an approval

The instruction this pass operates under requires an approval to rest on completed code-review gates, and for a change of this size the gates are not completable in the budget. Two things are missing, and neither is a claim that something is wrong:

Coverage. I read the whole of WorkspaceCsiApplicationController.java, V12__csi_application_retirement.sql, JdbcCsiRetirementSeal.java's locking and identity predicates, and WorkspaceCsiApplicationStore.java's credential-verification structure. That is a small fraction of the production surface. Not read at all: WorkspaceCsiApplicationInventory.java (+3,439, the single largest new file), the JdbcCsiActivationAdmission.java rewrite (+309/-146, which changes an admission gate this PR's own recovery paths depend on), JdbcCsiExecutionAdmission.java (+170/-58), WorkspaceCsiReservationStore.java (+147/-39), JdbcCsiApplicationProgress.java and JdbcCsiApplicationRetirement.java (+154 and +183, new), CsiFileFinalizeProtocol.java and its TypeScript counterpart managed-csi-file-finalize-protocol.ts (+127 and +175, a new two-language wire protocol whose two sides I have not compared term by term), WorkspaceCsiApplicationHistory.java / ...Image.java / ...Json.java / ...WorkerMatch.java, CsiOwnershipRevision.java, CsiNativeActivationProof.java (+138/-3), CsiNativeToolReservation.java (+82/-11), ManagedSessionStore.java (+161/-10), and on the TypeScript side http-managed-session-store.ts (+307/-77) and managed-session-authority.ts (+129/-40) — both in packages/core, so both are shared by surfaces outside this feature — plus managed-csi-file-worker.ts (+210/-10), managed-runtime-tool-executor.ts (+145/-1), hosted-csi-session.ts (+127/-9) and the finalize/envelope/mount/root-directory modules. With that much unread, I cannot name the downstream consumers of the changed core store and authority APIs, which is the bar this repository's own review policy sets for core-module changes; a feat of this size is an escalation for maintainer awareness rather than something to wave through, and the 1,000-line advisory is exceeded by an order of magnitude.

Execution evidence. Eleven lanes are still pending, including Test (ubuntu-latest, Node 22.x), Lint & Static, Build and verify reference distribution, Serve A/B, Integration Tests (no-AK, No Sandbox) and SDK Java (fast) / ubuntu-latest / Java 21. Nothing has yet executed this diff's TypeScript or Java. There are no failures, and pending lanes are not treated as a gate — but there is also no green run to corroborate a 14k-line change, and the extensive MySQL integration coverage this PR adds (WorkspaceCsiApplicationInventoryMySqlIT, WorkspaceCsiRetainedArtifactsMySqlIT, the extended WorkspaceCsiSqlWorkerMySqlIT and SessionRowLockOrderTest at +292/-34) is not executed by the fast tier at all.

No Critical is asserted anywhere in this review. Everything I read was consistent and carefully fenced, and I found nothing I could prove defective at this head.

Suggested next step

The useful next gate is a pass over the two highest-leverage unread items rather than another broad sweep: the JdbcCsiActivationAdmission rewrite, because it changes an admission gate that the already-merged cold-recovery paths call into, and the finalize protocol's two language implementations side by side, because a divergence there would only surface at runtime on the retirement path. Landing this after the pending lanes report would also let a reviewer treat a green Test and SDK Java lane as corroboration rather than reading 6,000 lines cold.

中文说明

未发现阻塞性缺陷,也没有需要复核的历史阻塞问题:本 PR 只有一份针对当前提交的批准,没有自动评审记录、行内线程或历史问题。本轮不提交批准,原因不是发现了问题,而是门禁无法在预算内完成:改动为一万四千余行、九十个文件,生产代码约六千行,且所有会执行代码的检查通道仍在运行。

已核对的部分集中在不可逆或跨信任边界的位置。新的退役接口对每个破坏性动作都校验凭据:控制器仅在两个开关同时启用时注册,动作由路径模式限定为冻结、切断与终结三类,写入令牌由存储层在取得行锁后逐路径校验,持有者令牌路由使用恒定时间比较并在两种凭据都不匹配时返回 401,请求头在截取前先做形态校验,写入后还会重新校验持久化镜像,清单查询按租户限定,连接工作有时间预算。数据库迁移是纯增量的:只新增可空列、一个生成列和一个唯一约束,没有删除或改写;生成列在非退役操作时为 NULL,因此唯一约束只作用于退役行;针对最新主干的迁移版本唯一性检查已通过。封印逻辑在状态与身份上都失败即拒绝:全部使用带租户条件的加锁读,操作行与绑定状态双向绑定,历史读取要求格式、版本与阶段固定,并要求冻结字节与调用方逐字节相等且摘要匹配。

未覆盖的部分是本轮不能批准的主要原因:最大的新增清单类、准入逻辑的大幅重写、执行准入、预约存储、进度与退役两个新类、跨语言的新终结协议两侧、历史与镜像等辅助类,以及核心包中的会话存储与授权模块和多个前端服务文件均未阅读。核心包的两个文件被本功能之外的表面共用,在阅读量不足的情况下无法列全其下游调用方,而这是本仓库对核心模块改动设定的门槛;此规模的新增也远超一千行的提示阈值,属于需要维护者知悉的升级情形。此外十一项检查仍在运行,尚无任何执行过本改动的绿色结果,而本 PR 新增的大量 MySQL 集成测试并不由快速通道执行。

建议的下一步不是再做一次宽泛扫描,而是优先阅读两处影响最大的未读内容:准入逻辑的重写,因为它改动了已合并的冷恢复路径所依赖的准入关卡;以及终结协议的两种语言实现并排比对,因为该处的不一致只会在退役路径运行时暴露。若能在待运行通道出结果后再评审,也可以把绿色的单元测试与 Java 通道作为佐证,而不必冷读六千行。

chiga0
chiga0 previously approved these changes Oct 19, 2026

@chiga0 chiga0 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE — no blockers. All non-blocking notes below.


What was checked

V12 migration (V12__csi_application_retirement.sql): 11 additive ALTER TABLE columns on ma_operation, then one generated CHAR(64) column feeding a unique constraint scoped to CSI_RETIREMENT rows. Version ordering is correct (V11 precedes V12); generated column expression confines the unique index to retirement operations only, so existing non-retirement rows are unaffected.

State machine (SETTLING → FROZEN → CUT → DRAINED): JdbcCsiApplicationRetirement.Authority enforces stage-gated payload rules — frozen bytes required in FROZEN/CUT/DRAINED, cut bytes required in CUT/DRAINED, finalize bytes required in DRAINED, all absent otherwise. requireCurrentTime() reads DB wall-clock under the lock and throws if past deadline. CAS stage updates use WHERE progress_stage = <current> to guard concurrent transitions. The deadline derivation (startedAt + 300_000) matches the lock() expectation.

prepareOriginalCsiRelease() in managed-session-authority.ts: correctly gates runSerial() and close() once retirementPreparation is set. Validates epoch === 1, phase === 'active', compactedThrough === 0, createdBy === 'hosted-harness' before committing. Publishes managed-activation-boundary then constructs the activation.changed event with phase: 'released'.

Retire route in hosted-csi-session.ts: active(owner) is called before clearInterval(owner.timer), so the already-retired guard runs first. owner.failures fail-closed is consistent with the stated design intent ("reject unsupported or uncertain evidence before repair").

Worker finalize protocol (boot v6) in managed-csi-file-worker.ts: preCut/finalization latches on observe/cut respectively; retried requests with matching bodies reuse the cached value — idempotent. Descriptor closure is verified before building DRAINED bytes.

joinOriginalCsiWriter() in http-managed-session-store.ts: called only after await Promise.allSettled(admitted) in the retire route, so acquirePromise/pendingAppend should be clear at invocation time.


Non-blocking notes

NB-1 (http-managed-session-store.ts, joinOriginalCsiWriter()): this.stopRenewal() fires before the acquirePromise || pendingAppend guard. On the corrupt/rejected path retirementJoin is not set, so a subsequent call re-enters the function and calls stopRenewal() again — but renewal is already stopped and retirementJoin stays unset. If the caller retries after the guard fails, the session is racing lease expiry with no way to restart the renewal timer. In practice the caller awaits all admitted tasks before calling joinWriter(), so the guard should always pass; this is an integrity check for an impossible state. Moving the guard above stopRenewal() would be safer but is not a blocker.

NB-2 (managed-session-authority.ts, prepareOriginalCsiRelease()): retirementPreparation is assigned before the async work resolves. If the inner async block throws (e.g. network error publishing managed-activation-boundary), retirementPreparation stays set as a rejected-but-cached promise, permanently preventing runSerial() and close() from succeeding on this instance. The HTTP retry path works at the session level (retirementResult is cleared on rejection), but the authority object is bricked. Per the stated design intent this is intentional (retirement is a one-way door); calling it out for documentation.

NB-3 (echoing yiliang114): bare new IllegalArgumentException() without a message string on the malformed-retirement-ID path in JdbcCsiApplicationRetirement.lock() makes the log entry diagnosis-hostile.

NB-4 (echoing yiliang114): full WorkspaceCsiApplicationInventory scan on every status poll — cost scales with table/column count (currently 32 tables, 736 columns). Fine now; worth noting if the catalogue grows.

NB-5 (echoing yiliang114): HttpServer context created per session in hosted-csi-session.ts without an explicit stop() call on the retirement path. Verify teardown is covered by the outer container lifecycle.

@qwen-code-review-bot

qwen-code-review-bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator

🩺 serve daemon A/B

Built the PR base vs this PR head 749cfdf, drove a fixed endpoint set against each, and diffed the JSON responses. Only fields that changed are shown.

health-deep-with-session

field PR base (before) this PR (after)
activeWorkStaleMs 6 5

— Qwen Code · serve A/B

@doudouOUC
doudouOUC dismissed stale reviews from chiga0 and yiliang114 via 67c8b92 October 19, 2026 12:59
@doudouOUC
doudouOUC force-pushed the codex/csi-application-retirement branch from bbea488 to 67c8b92 Compare October 19, 2026 12:59
@doudouOUC

doudouOUC commented Oct 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

Rebased the original CSI application retirement branch from bbea488786f00b8d0f54f8b4a6658cbc3b017b2e onto main at 24ca86f622f6d2b29d94a67983e206818da7fcfc. The updated head is 67c8b92089e3a94ad80751b0b36ff58c115fec82. A merge-tree check against the later main head fdb51f8961792033254af91d753bdf62e228bd32 also has no conflicts.

Action Result
Reconcile retirement with the merged cold-recovery work Preserve the live recovery overload and its byte budget, the historical read mode, the cold-receipt return value used by final-output recovery, and both recovery and retirement fixture arguments.
Replay existing follow-up fixes Retain all functional follow-ups; the formatting-only commit becomes empty because main already supplies the required recovery-owner validation.
Existing writer-renewal suggestion Replied with the verified admission/join ordering and the reason that an integrity refusal keeps renewal stopped. The existing behavior is retained.
Existing preparation-caching suggestion Replied with the verified one-way authority fence and the bilingual design reference. The existing behavior is retained.
Review-thread handling Both non-blocking notes were individually answered and resolved; no additional source changes were needed.

Validation on the resulting source tree:

  • Root build and complete typecheck passed. Core targeted tests: 233 passed.
  • The six-file CLI run initially had 117 passed and one retirement-barrier timeout. The test engineer could not reproduce the timeout: the complete retirement file passed 7/7, and the affected case passed twice individually with coverage. The exact original timeout cause remains unknown; no source or timeout change was made for it.
  • Java full unit suite: 4,943 tests, 0 failures/errors, 18 environment skips. The earlier native-fixture run was repeated successfully after the prerequisite CLI build completed.
  • MySQL 8.4: 31 retained-artifact cases and 8 SQL-worker cases passed; inventory had 62 passed plus one setup error because client-prepared binary encoding exceeded the server's 64 MiB packet limit. The identical failing inventory method passed with useServerPrepStmts=true. A read-only driver probe verified this transport prerequisite. This is an initial full integration run plus a targeted rerun, rather than a claim that the initial mvn verify command exited successfully.
  • Checkstyle reported 0 violations; SpotBugs reported 0 bugs/errors. The conflict-resolution diff completed two clean self-audit passes.

Fresh CI evidence and review against the updated head are still needed. Hourly incremental babysitting remains active until the PR is merged or closed.

中文:已解决与主干冷恢复改动的冲突,保留恢复、退役和历史读取的各自约束。构建、类型检查、相关 TypeScript 测试、Java 单元测试和静态检查已有通过证据;MySQL 的 102 个场景通过初次运行及单项重跑得到验证。初次 CLI 并发测试的一次超时未能复现,原因仍未确认。新提交仍需 CI 和针对新 head 的评审,每小时检查继续运行。

yiliang114
yiliang114 previously approved these changes Oct 19, 2026

@yiliang114 yiliang114 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-review at 67c8b920 — delta from bbea488

My earlier approval (5571290094) was dismissed when the head moved, so this is a fresh verdict on the new head. I reviewed the delta rather than re-reading the whole 90-file surface.

The delta is a rebase onto fdb51f89 (which now carries #14695 cold recovery, #14691 held-Runtime inventory, #14634 credential bootstrap and #14292 artifacts) plus one branch fix, 67c8b920, restoring the cold-recovery complete(...) overload in CsiNativeToolReservation. A tree diff between bbea488 and 67c8b920 shows only 11 of the PR's 90 files changed; ten of those change only by main's code, and the retirement-specific blobs (V12, the reservation/inventory identity checks, the host retire route, registerCsiApplicationAuthority) are byte-identical to the head I approved.

What I re-verified at this head:

  • The rebase did not drop the branch side. hosted-csi-session.ts still has the retire route at line 602 with the latch → join → prepare/complete ordering; RuntimeBrokerHttpServer.registerCsiApplicationAuthority is still registered; JdbcCsiActivationAdmission keeps the application-retirement entry points next to main's new requireRecoveryTail / verifyColdFinalOutput.
  • The overload chain is unambiguous and keeps both semantics. (Map) → (Map, seq, rev) → (Map, recovery=false, seq, rev) → the private eight-argument form; (Map, recovery) → (Map, recovery, 0, 0); (Map, seq, rev, JournalRead) → recovery=false with that reader. Cold paths reach receiptMembers(..., true, 0, 0) and keep the 8 MiB byte budget; verifyHistoricalReceipts keeps its explicit JournalRead with recovery=false.
  • V12 is still the right slot. Base fdb51f89 carries V1–V11, and the migration adds V12 with the same eleven additive columns and generated-target unique key, so the version lane does not collide after the rebase.

Non-blocking:

  • The PR body still calls bbea488 the current head and its evidence section predates this rebase. The two production fixes now sit in the final commits and the cold-recovery overload restoration is not described, so worth refreshing to keep the reviewer test plan aligned with the bytes being merged.
  • chiga0's two NB threads (stopRenewal() before the integrity guard; cached rejected retirementPreparation) are answered with the retirement-fence rationale. I agree with declining both.
  • Every code-executing lane is queued at review time. Not a finding.

Approving on the code. This remains no qualification of the paths the PR itself leaves open: foreign-owner late-lock ordering, cross-tenant races, private process-death acceptance and the Linux run.

@qqqys qqqys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

COMMENT — re-reviewed at head 67c8b92089e3a94ad80751b0b36ff58c115fec82, which supersedes my review of bbea4887. No blocking defect found and no prior blocking finding exists, but this is not an approval: the head moved by a rebase plus five commits I have not read, every CI lane is pending so nothing has executed this diff, and the production surface remains far larger than a bounded pass can cover.

What changed since the last review

The branch diverged from bbea4887 (ahead 20 / behind 6) and was rebased onto a newer main that now includes the completed private CSI cold recovery this feature builds on, plus cc2de634 (bounding the held-Runtime inventory read). On top of the rebased feature commit there are five new commits whose content I did not read:

  • 043bacd6 fix(runtime): compare CSI retirement handle values
  • be64a644 fix(runtime): qualify retained CSI handle identities across mappers
  • 67c8b920 fix(runtime): retain cold recovery receipt overload
  • c5d45705 test(runtime): retain native mount lifecycle in CSI fixture
  • 7b326851 test(runtime): preserve MySQL inventory column constraints

Three of those are production fixes to identity comparison and overload retention, which is precisely the area a reviewer would want to read rather than infer. The measured diff at this head is 90 files, +14,202/-564: production Java is 39 files at +7,160/-324, test Java 22 files at +3,600/-64, and non-Java 29 files at +3,442/-176 (which includes the packages/core and packages/cli TypeScript). The totals moved only slightly from the previous head, so the scope conclusion is unchanged.

The four surfaces I verified before still hold at this head

I re-checked each rather than carrying the claims forward:

  • The retirement endpoint still authenticates every destructive path. WorkspaceCsiApplicationController keeps the action set closed at the mapping (freeze|cut|finalize), still takes identity from TenantContext and the writer token from the header, and still shape-validates the bearer route's Authorization value. WorkspaceCsiApplicationStore calls requireCsiApplicationCredential at all six sites and still compares both accepted credentials with MessageDigest.isEqual, so the comparison stays constant-time.
  • The migration is still purely additive. V12__csi_application_retirement.sql has 12 ADD COLUMN / ADD CONSTRAINT statements and zero occurrences of DROP, DELETE, TRUNCATE or MODIFY, so it cannot destroy existing rows; the generated column keeps uq_ma_csi_retirement_target scoped to CSI_RETIREMENT operations only.
  • The seal still uses locking reads. JdbcCsiRetirementSeal retains three FOR UPDATE reads, all keyed by target_key, target_revision and tenant_id.

One hazard this PR does not have, stated explicitly

Both this PR and the concurrent package reorganization touch runtimebroker, so it is worth recording the distinction rather than leaving it to inference. This PR does not move ManagedHoldFamily: at this head the class is still package com.alibaba.qwen.code.runtimebroker; with ofDispatchMode(Object) package-private at :44 and its only caller at :41 inside the same class. main's new call site in JdbcToolExecutionRepository:851 is also in runtimebroker, so it stays same-package and compiles. The cross-package visibility collision is a property of the reorganization PR, not of this one.

This PR's only change to that file is a one-line retyping inside a private record — JdbcCsiReadyAdmission.Admission progress becomes JdbcCsiApplicationProgress.Continuation progress — consistent with the JdbcCsiApplicationProgress class it adds. That is benign on its face, but whether the merged tree compiles is exactly what the pending Java lane will establish, and I have not established it.

Gates not completed

  • No execution evidence at all. Every lane is pending at this head — 0 pass, 0 fail, 11 pending — including Build and verify reference distribution and SDK Java (fast) / ubuntu-latest / Java 21, the two that would compile this diff. Pending lanes are not treated as a gate, but for a change of this size the absence of any green run means the verdict rests entirely on reading.
  • Coverage. Unread at this head: WorkspaceCsiApplicationInventory.java (+3,439, still the largest new file), the JdbcCsiActivationAdmission.java rewrite (+309/-146) that changes an admission gate the now-merged cold-recovery paths call into, JdbcCsiExecutionAdmission.java (+170/-58), JdbcCsiApplicationProgress.java and JdbcCsiApplicationRetirement.java (new), the two-language finalize protocol (CsiFileFinalizeProtocol.java + managed-csi-file-finalize-protocol.ts), WorkspaceCsiReservationStore.java, ManagedSessionStore.java (+161/-10), CsiNativeActivationProof.java (+130/-2), and on the TypeScript side http-managed-session-store.ts and managed-session-authority.ts — both in packages/core and both shared by surfaces outside this feature. I cannot name every downstream consumer of those two, which is the bar this repository's review policy sets for core-module changes; at this size the policy's escalation for maintainer awareness applies, and the earlier open question about whether the design wants maintainer sign-off before rather than after a rebase is still unresolved and is not mine to settle.
  • Spring wiring. I did not confirm that every stereotype-annotated class remains under the component-scan root, nor that runtimebroker stays Spring-free. A moved annotation fails at runtime, not at compile time, so no lane would catch it early.

No Critical is asserted anywhere in this review.

Suggested next step

The cheapest path to a reviewable state is to let the pending lanes finish — a green Build and verify reference distribution and SDK Java lane would establish that the rebased tree compiles against current main, which is the one fact this pass could not check — and then have the next pass read the five new commits and the two packages/core files rather than re-sweeping the whole feature.

中文说明

本轮针对新的提交重新评审,取代上一次结论。未发现阻塞性缺陷,也没有需要复核的历史阻塞问题,但仍不予批准,理由有三:本次 head 由变基加上五个我未阅读的新提交构成;所有检查通道都在运行中,尚无任何通道执行过这份改动;生产代码规模仍远超一次有预算限制的评审所能覆盖的范围。

与上一版相比,分支已变基到更新的主干——其中包含本功能所依赖的私有序列冷恢复,以及一处持有清单读取成本的收敛——并在特性提交之上新增五个提交,其中三个是对身份比较与重载保留的生产修复,恰好属于应当阅读而非推断的部分。按当前 head 实测:共 90 个文件、新增 14202 行删除 564 行,其中生产 Java 为 39 个文件新增 7160 行,测试 Java 为 22 个文件,非 Java 为 29 个文件(含核心包与 CLI 的 TypeScript 改动)。总量与上一版相差不大,规模结论不变。

上一轮核对过的四个面在本轮已逐项重新确认,而非沿用旧结论:退役接口仍在每个破坏性路径上校验凭据,动作集合仍由路由模式限定为三种,两个可用凭据仍使用恒定时间比较;数据库迁移仍是纯增量,十二条新增语句、零条删除或修改语句,生成列使唯一约束只作用于退役操作;封印逻辑仍保留三处带租户条件的加锁读。

有一点值得明确记录,因为同期另有一个包重组改动也涉及同一包:本 PR 并未移动 ManagedHoldFamily,该类在当前提交上仍属原包,其包内可见方法的唯一调用点也在同类之内;主干新增的调用方同样位于该包,因此仍是同包调用、可以编译。跨包可见性冲突属于那个重组改动,不属于本 PR。本 PR 对该文件的唯一改动是私有记录中一行的类型替换,表面上无害,但合并后能否编译正取决于仍在运行的 Java 通道,我尚未确认。

未完成的门禁:所有通道均在运行,没有任何绿色结果,因此结论完全依赖阅读;最大的新增清单类、准入逻辑的大幅重写、执行准入、两个新进度与退役类、跨语言终结协议、预约存储,以及核心包中被本功能之外表面共用的两个 TypeScript 文件均未阅读,因此无法列全其下游调用方,而这正是本仓库对核心模块改动设定的门槛,此规模也适用需要维护者知悉的升级情形;此外未确认带构造型注解的类在移动后是否仍位于组件扫描根内,此类问题在运行时才暴露。本轮未断言任何严重问题。

建议的下一步是先让仍在运行的通道跑完——构建与 Java 通道转绿即可确认变基后的代码树能与当前主干一起编译,这正是本轮唯一无法核对的事实——随后由下一轮优先阅读那五个新提交与核心包的两个文件,而不必重扫整个特性。

@github-actions

Copy link
Copy Markdown
Contributor

Please do not rebase or force-push to an active PR as it invalidates existing review comments. Note for future reference, the bots always squash all changes into a single commit automatically as part of the integration.

中文

请勿对活跃的 PR 执行 rebase 或 force-push,因为这会使已有的评审评论失效。另外,供日后参考:作为集成流程的一部分,机器人始终会自动将所有改动压缩(squash)为单个提交。

@chiga0 chiga0 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

COMMENT — no confirmed/supported blocker found in the surfaces I read. Approval withheld: WorkspaceCsiApplicationInventory.java (+3 439 lines, not read) and JdbcCsiActivationAdmission.java (+309/−146, not read) are material production files for a Deep-tier review and remain an open coverage gap. yiliang114 has already approved at this head after a focused delta review.


Scope — what I read in this pass

Read in full: V12__csi_application_retirement.sql · JdbcCsiApplicationProgress.java · JdbcCsiApplicationRetirement.java · JdbcCsiRetirementSeal.java · CsiFileFinalizeProtocol.java · WorkspaceCsiApplicationStore.java · WorkspaceCsiApplicationController.java · managed-csi-file-finalize-protocol.ts

Read via diff (all added hunks): http-managed-session-store.ts (+307/−77) · managed-session-authority.ts (+129/−40) · managed-csi-file-worker.ts (+210/−10) · hosted-csi-session.ts (+127/−9)

Scanned (grep/excerpt only): WorkspaceCsiApplicationInventory.java (INSERT pattern and stage constants) · WorkspaceCsiApplicationStore.java stage-transition UPDATEs

Not read: WorkspaceCsiApplicationInventory.java (+3 439) · JdbcCsiActivationAdmission.java (+309/−146) · JdbcCsiExecutionAdmission.java (+170/−58) · WorkspaceCsiReservationStore.java (+147/−39) · ManagedSessionStore.java (+161/−10) · CsiNativeActivationProof.java (+130/−2) · WorkspaceCsiApplicationHistory/Image/HistoryImage/Json/WorkerMatch.java · test files · design docs


Findings — no blockers

NB-1 (preserved from round 1, confirmed design intent)

joinOriginalCsiWriter() calls stopRenewal() before the acquirePromise || pendingAppend integrity guard. If the guard fires, retirementJoin is left unset while renewal is permanently stopped. Safe because the retire handler in hosted-csi-session.ts awaits Promise.allSettled(admitted) before calling joinWriter(), so both flags are clear at that point. yiliang114 confirmed this is the retirement-fence rationale.

NB-2 (preserved from round 1, confirmed design intent)

prepareOriginalCsiRelease() assigns retirementPreparation to the pending promise before the queue.then(async () => …) body runs, immediately closing runSerial() and close() to new work. Intentional one-way door. yiliang114 confirmed this is design intent.

NB-3 (new — inline thread)

workerAuthority() uses !seedMatches || !leaseMatches, which throws unless credential equals both the provision-seed token and the lease token. This works because for an original epoch-1 generation-1 DRAINING binding the seed and lease are identical (no renewal has ever rotated the lease independently of the epoch). The invariant is implicit and undocumented. qqqys's review described this as "answers 401 when neither matches" (OR-accept), which is the logical inverse of the actual check (AND-accept). Behavior is identical when seed==lease, which holds for this code path. Non-blocking; a comment would help.

NB-4 (new — body only)

finalizeApplication() uses two consecutive jdbc.update() calls inside one Spring TransactionTemplate lambda: first sets finalize_receipt_bytes / _sha256, then calls sessions.completeCsiApplication(...), then advances progress_stage to DRAINED. All three run atomically. The second UPDATE's WHERE clause includes AND finalize_receipt_sha256 = ? and sees the first UPDATE's write within the same transaction (InnoDB read-your-own-writes). On retry after rollback, the first UPDATE is idempotent (WHERE AND finalize_receipt_bytes IS NULL matches again). Correct; noted for auditor visibility.


Cross-check against prior reviews

yiliang114 (re-approved at 67c8b920): Confirmed NB-1 and NB-2 are design intent; verified rebase didn't drop the branch side; confirmed V12 is in the correct Flyway slot; confirmed the CsiNativeToolReservation overload chain is unambiguous. No findings beyond mine. ✓

qqqys (COMMENT at 67c8b92): Authentication gating, migration additive-only, seal locking reads — all consistent with my findings. One description discrepancy: qqqys described workerAuthority() as "answers 401 when neither matches" (OR-accept), but the code is AND-accept (!seedMatches || !leaseMatches). Behavior is identical for epoch-1 DRAINING apps where seed==lease. qqqys listed WorkspaceCsiApplicationInventory.java and JdbcCsiActivationAdmission.java as their top gaps — these are carried into approvalBlockers below.


Approval blockers (coverage gaps only — no asserted defect)

File Lines Why
WorkspaceCsiApplicationInventory.java +3 439 Largest new production file; core inventory & image verification for retirement — not read
JdbcCsiActivationAdmission.java +309/−146 Changes an admission gate the retirement and cold-recovery paths both call; not read

yiliang114's delta approval covers the retirement-specific blobs. It does not cover this file pair. No defect in either is asserted.


Reviewed with AI assistance.

byte[] credential = token == null ? new byte[0] : token.getBytes(StandardCharsets.UTF_8);
boolean seedMatches = MessageDigest.isEqual(credential, locked.binding().getProvisionSeed().getToken().getBytes(StandardCharsets.UTF_8));
boolean leaseMatches = MessageDigest.isEqual(credential, locked.binding().getLease().getToken().getBytes(StandardCharsets.UTF_8));
if (!seedMatches || !leaseMatches) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NB-3: workerAuthority() auth — !seedMatches || !leaseMatches requires credential to equal both the provision-seed token and the lease token simultaneously. This works because for an original epoch-1 generation-1 DRAINING binding the provision seed IS the active lease (no renewal has ever rotated the lease independently of the epoch). If that invariant broke — e.g. a future path that rotates the lease without incrementing the epoch — this check would permanently 401 the worker. A comment at this site documenting the invariant, or an assertion such as Objects.equals(getProvisionSeed().getToken(), getLease().getToken()) before the comparison, would make the assumption explicit rather than silent.

chiga0
chiga0 previously approved these changes Oct 19, 2026

@chiga0 chiga0 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE — round 3: coverage gaps closed, no blockers found.


Round ledger

Id Round 2 finding Status
R2-3 workerAuthority() requires !seedMatches || !leaseMatches (AND-accept); invariant seed==lease for epoch-1 DRAINING is implicit still present — non-blocking, no change
R2-4 Two-UPDATE CUT→DRAINED transition in one TransactionTemplate — correct, InnoDB read-your-own-writes still present — non-blocking, no change

Round 2 approval blockers (coverage gaps) — now resolved:

File Lines Outcome
WorkspaceCsiApplicationInventory.java +3 439 Read in full — no blockers (see below)
JdbcCsiActivationAdmission.java +309/−146 Read in full — no blockers (see below)

WorkspaceCsiApplicationInventory.java — what I checked

Overflow / bounds safety: MAX_ROWS = 4096, MAX_BYTES = 32 MiB. scan() adds a Blocker and returns immediately at both row_limit and byte_limit; the discover() fixed-point loop checks overflow first on every iteration. The loop terminates because the row set can only grow, bounded by those limits.

restoreCanonical() round-trip: Re-serialises the snapshot from bytes and asserts Arrays.equals(bytes, restored.bytes). Version header "qwen-csi-application-inventory/2" hard-coded at both sides — tamper-proof and version-gated.

validateHistoricalBaseline(): Precondition baseline.blockers().isEmpty() is required before validation begins. Calls restoreCanonical() first, so a corrupted persisted snapshot throws IllegalArgumentException before any SQL is run. Stage must be SETTLING, binding record_version >= intent.sealedBindingVersion() (relaxed >= is correct — version may have incremented since the seal), first_activation_journal_revision == 2L for epoch-1 original.

FOR UPDATE locking: inspect() requires !target.getAutoCommit(). Every scan() uses LIMIT (MAX_ROWS+1) FOR UPDATE with a 10-second setQueryTimeout.

No defect found.


JdbcCsiActivationAdmission.java — what I checked

terminalPreflight(): authority.requirePreCut() runs first, then full journal replay via history(), then require(writerExpiresAt > now && activationExpiresAt > now) using DB clock via authority.requireCurrentTime(connection) — no wall-clock drift. Resource non-existence guard runs before the final time fence, ensuring the boundary resource has not already been committed.

lockRetirementPredecessor(): Uses activeNativeHead() (no expiry check) — correct at SETTLING/FROZEN stage because the writer lease may have expired when retirement begins; no continuation work is attempted here.

JournalRead time budget: Historical reads require isReadOnly() + TRANSACTION_REPEATABLE_READ; requireHistorical() enforces a 10-second wall-clock budget (System.nanoTime()) and rethrows via require(false).

activeHistoryThrough() journal chain: Each entry SHA256-verified against record_digest, sequence chain verified (first_sequence == sequence + 1, previous_commit_digest matches), per-entry revision < MAX_HISTORY guard, cumulative byteCount <= MAX_HISTORY_BYTES (64 MiB). requireNoJournalTail() at the end confirms no dangling entries past expectedRevision.

terminalHistory() final state check: Requires ma_session_head state SEALED, activation_phase = 'released', activation_epoch = 1, activation_event_epoch = 1, writer_generation = 1. writerTokenSha256 from frozen bytes is matched against the DB row — substitution-resistant.

noEarlierAuthorization(): Paginated scan with cursor and count < 100 sentinel; total <= MAX_HISTORY prevents unbounded reads.

No defect found.


Cross-check

yiliang114 (re-approved at 67c8b920): Covered rebase delta; no findings in either file above. ✓
qqqys (COMMENTED at 67c8b92): Same two coverage gaps identified; no defects asserted in those files. ✓


Reviewed with AI assistance.

doudouOUC and others added 6 commits October 19, 2026 22:29
Follow the upstream persistence and transport package split, update renamed exception and formerly implicit references, and retain bounded protocol parsing across the new package boundary.

Co-authored-by: Qwen-Coder <[email protected]>
@doudouOUC
doudouOUC dismissed stale reviews from chiga0 and yiliang114 via 749cfdf October 19, 2026 15:03
@doudouOUC
doudouOUC force-pushed the codex/csi-application-retirement branch from 67c8b92 to 749cfdf Compare October 19, 2026 15:03
@doudouOUC

Copy link
Copy Markdown
Collaborator Author

Resolved the merge conflict introduced by the upstream server package reorganization (#14710) and pushed HEAD 749cfdfdf8 with an explicit old-head force-with-lease.

Blocker Resolution
Main moved server responsibilities into new packages Replayed only this PR's six commits onto main c076c699af; placed the new retirement persistence helpers/tests in managedagent.persistence and the finalization wire codec/test in runtimebroker.transport.
Former same-package references stopped compiling Updated qualified names and imports, adopted the upstream exception rename, and made the existing bounded parser overload accessible to its three repository/admission callers across the new package boundary. Existing parsing limits and protocol behavior are preserved.
Java import ordering after relocation Sorted the affected imports and verified that all 1,985 production/test class files are byte-for-byte identical to the fully tested output.

Validation: frozen dependency installation completed the root build/bundle; root typecheck passed with Node 22.22.3. JDK 21 compilation covered 334 production and 506 test sources after cleaning old package outputs. The affected selection passed 287 tests. The complete unit/H2 phase ran 4,954 tests: 4,936 passed, 18 skipped by platform/opt-in/assumption gates, zero failures or errors. All 102 MySQL 8.4.11 tests passed (31 retained-artifact, 63 inventory, 8 SQL-worker scenarios), including the oversized binary fixture using server-side prepared statements.

The first full verification completed both test phases and then failed on eight import-order violations. After correcting only import ordering, the affected 97 tests passed again and all 1,985 class SHA256 values remained identical. mvn -DskipTests verify then passed both Checkstyle configurations and the SpotBugs gate; the generated SpotBugs analysis covers 919 production classes with zero bugs/errors. The final import ordering and binary equivalence were independently checked by the test engineer. No deployed/Hosted fault acceptance is claimed by these local results.

The latest fetched main 628ab5c1af also pre-merges cleanly. GitHub read-back is OPEN / MERGEABLE / REVIEW_REQUIRED; previous approvals were dismissed by the new head, and its CI is queued. Thread read-back: 2 resolved, 1 unresolved. This cycle began with two human approvals and no changes requested, so ordinary comment processing was suspended; this mechanical repair addressed zero review threads and preserved the existing resolutions.

中文:已解决主干包重组造成的冲突,按新职责目录补齐引用与导入顺序,并保留原有协议与退役行为。4954 项单元/H2 测试中 4936 通过、18 条件跳过,102 项 MySQL 测试全部通过;格式修正后定向复跑 97 项通过,1985 个 class 的 SHA256 保持一致,两套 Checkstyle 与 SpotBugs 均为零错误。新 head 可合并,需重新审查并等待新 CI;当前 2 个线程已解决、1 个仍未解决。

@chiga0 chiga0 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE — round 4 (new head 749cfdfdf8): four fix commits reviewed, no blockers found.


Prior-round findings

Id Finding Status at 749cfdfdf8
R2-3 workerAuthority() credential check AND-accept implicit invariant still present — non-blocking, no change
R2-4 Two-UPDATE CUT→DRAINED in one TransactionTemplate — correct still present — non-blocking

Prior approval blockers: none (closed in round 3).


Delta since round 3 (67c8b92 → 749cfdfdf8)

Six commits. The base also changed (rebase onto current main). The content delta consists of four fix commits on top of the main feature:

cd985fe4ba — compare CSI retirement handle values (+1/−1 production line)

WorkspaceCsiApplicationInventory.java, ma_runtime_slot row validator.

Old: intent.resourceHandleJson().equals(row.text("resource_handle_json")) — string equality, fails when JSON key order differs between writer and reader.
New: matches(parse(row.text(...)), parse(intent.resourceHandleJson())) — both sides parsed as JsonNode, compared structurally via Jackson equals().

Correct fix. matches() re-serialises through JSON.writeValueAsBytes() before comparing, normalising key order. The parse() path returns null on malformed input, and matches() guards observed != null, so bad JSON safely fails validation rather than throwing.

09e456dca6 — qualify retained CSI handle identities across mappers (+20/−3)

WorkspaceCsiReservationStore.requireRetainedIdentity().

Old: !intent.equals(snapshot(...)) — Retirement.equals() uses string equality on resourceHandleJson, fails on equivalent JSON with different key order.
New: fast-path on exact equality; on mismatch: parse both resourceHandleJson values with WorkspaceCsiApplicationJson.object() (bounded to 256 KiB, IllegalArgumentException on malformed), then reconstruct expected with intent.resourceHandleJson() substituted and check all other fields still match. Malformed JSON is caught and re-thrown as unavailable().

Correct fix. The substitution strategy precisely isolates the JSON-ordering difference from all other field comparisons.

4df05e5eca — retain cold recovery receipt overload (+8/−2)

CsiNativeToolReservation.complete().

Adds the missing overload complete(..., boolean recovery, long seq, long rev) → complete(..., recovery, seq, rev, LIVE). The two existing shorter overloads now delegate through this one rather than to the full 8-arg version directly — a safe refactor that restores an overload the cold-recovery path needs.

749cfdfdf8 — align CSI retirement with server package layout (+23/−12)

Follow-on to the upstream package reorganisation (#14710):

  • CsiFileFinalizeProtocol moved runtimebroker → runtimebroker.transport; import references updated across 5 files.
  • ManagedCsiFilesProtocol.parse(byte[], int) widened from package-private to public so JdbcCsiActivationAdmission and JdbcCsiRetirementSeal (now in a different package) can call it. Caller always passes an explicit limit; no bypass of size guard.
  • ApiException → ManagedAgentException in WorkspaceCsiApplicationController and ManagedAgentStore (consistent with #14710).

Mechanical and correct.


Cross-check

yiliang114 (dismissed, was at 67c8b92): No findings in any of the four changed files. ✓
qqqys (COMMENTED at 67c8b92): No findings at the files touched by the fix commits. ✓

No reviewer has reviewed 749cfdfdf8 yet; this is the first review at this head.


Reviewed with AI assistance.

@yiliang114 yiliang114 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE — delta re-review at head 749cfdfd, superseding my 67c8b920 approval that the push dismissed.

The head moved by a rebase onto main de20ab6a (the package-boundaries split) plus one commit, 749cfdfd fix(runtime): align CSI retirement with server package layout. I audited the delta rather than re-running the full pass, since the previously reviewed production logic is unchanged.

What I verified at this head:

  • Retirement behaviour is byte-identical to what I approved. CsiNativeToolReservation, CsiOwnershipRevision, JdbcCsiApplicationRetirement, JdbcCsiApplicationProgress, V12__csi_application_retirement.sql and hosted-csi-session.ts have the same blob shas as 67c8b920; so do the TypeScript finalize-protocol and envelope files. The admit() / retire ordering, latch → join → prepare/complete and the boot6-finalization contract are untouched.
  • The alignment commit is mechanical. ApiException → ManagedAgentException is main's class rename — the body of the new class is identical (same constructors, getStatus()/getCode(), details), and api/ApiException.java no longer exists at the base. The remaining hunks are import/qualified-name updates for persistence/, transport/, workspace/, model/, catalog/.
  • The visibility widenings are required, not incidental. ManagedCsiFilesProtocol.parse(bytes, limit), the CsiNativeActivationProof JSON helpers and HttpRuntimeTransport.BoundedBody* became public because their callers now sit in a different package; call sites are the same ones as before.
  • No stale package references in added lines — repo-wide sweep of the PR diff for managedagent.store., managedagent.service., ApiException, and the pre-move runtimebroker.<protocol> names returns nothing.
  • Migration slot still clean. Base tops out at V11__wake_recovery.sql; V12__csi_application_retirement.sql is the only new migration at head.

CI has not executed this head yet — 5 check-runs pending, the rest skipped, mergeStateStatus: BLOCKED. Not a code finding, just the current state.

One non-blocking note: the PR body still pins "Current head bbea488786…" and the evidence section predates this rebase and the alignment commit. Worth updating when you next touch the description.

My earlier scope caveats stand unchanged: this approval does not cover foreign-owner late-lock ordering, cross-tenant races, private-process death acceptance, or a Linux rerun.

@qqqys qqqys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVE at head 749cfdfdf88309107029ffe664ea2f12b534e16a, superseding my two COMMENT reviews on bbea4887 and 67c8b920. Both of those withheld approval on coverage gaps I have now closed by reading the code myself at this head. This review also corrects a factual error in my earlier one, stated first because it concerns a security control.

Correction: I misdescribed the bearer credential check

In my review of bbea4887 I wrote that workerAuthority "compares with MessageDigest.isEqual against both the provision-seed token and the lease token and answers 401 when neither matches", and called that "two-credential acceptance". That is wrong, and a later reviewer caught it. The actual code at this head (managedagent/persistence/WorkspaceCsiApplicationStore.java:270-275) is:

byte[] credential = token == null ? new byte[0] : token.getBytes(StandardCharsets.UTF_8);
boolean seedMatches  = MessageDigest.isEqual(credential, locked.binding().getProvisionSeed().getToken().getBytes(StandardCharsets.UTF_8));
boolean leaseMatches = MessageDigest.isEqual(credential, locked.binding().getLease().getToken().getBytes(StandardCharsets.UTF_8));
if (!seedMatches || !leaseMatches) {
    throw new RuntimeBrokerException(401, "csi_application_authority_unauthorized", "Original Runtime authentication failed.", false);
}

!seedMatches || !leaseMatches throws unless both match. This is AND-accept, not the OR-accept I described — the logical inverse. My error understated the control's strictness, so nothing was wrongly approved on the strength of it, but a reader trusting my description would have misunderstood which credential is sufficient, and the correction matters for the reason below.

The conjunction is not merely stricter than necessary; its satisfiability is enforced rather than assumed. The earlier reviewer described the seed-equals-lease precondition as an implicit undocumented invariant. Reading the terminal-state gate myself, it is pinned explicitly — JdbcCsiActivationAdmission's terminal check (:693-705) requires, in one conjunction, state == "SEALED", activation_phase == "released", activation_epoch == 1, activation_event_epoch == 1, writer_generation == 1, journal_revision == predecessorRevision + 1, committed_sequence == proof.terminalSequence(), the metadata commit digest equal to last_commit_digest, activation_head_revision == predecessorRevision + 1, the predecessor activation id and worker id matching the row, activation_expires_at matching the predecessor's expiry, frozen.writerTokenSha256 equal to lease_token_hash, and no second row. A binding whose lease had ever rotated away from its provision seed could not satisfy epoch 1 and generation 1, so it never reaches workerAuthority; if it somehow did, the check fails closed with 401. So the AND-accept is sound on exactly the bindings this path admits, and the residual exposure is availability rather than authorization.

The two coverage gaps I named are now closed by my own reading

My previous reviews withheld approval naming WorkspaceCsiApplicationInventory.java and JdbcCsiActivationAdmission.java as unread. I have now read both at this head — for their safety-critical properties rather than every line, and I disclose that distinction below.

WorkspaceCsiApplicationInventory.java (3,441 lines, fetched byte count verified against the API's reported size). The bounds are real and enforced inside the loops rather than after them: MAX_ROWS = 4096 and MAX_BYTES = 32 MiB (:56-57), Jackson constrained by StreamReadConstraints with maxNestingDepth(64) and maxStringLength(MAX_BYTES) (:63), and the scan query built as LIMIT (MAX_ROWS + 1) with setQueryTimeout(historyRemaining(started)) so the read carries both a row ceiling and a shrinking wall-clock budget. The +1 is what makes overflow detectable: on hitting either limit the code calls block(...) with "row_limit" or "byte_limit", sets overflow, and the enclosing loop tests if (overflow) before continuing (:1311, :1334-1347), so a truncated scan cannot be mistaken for a complete one. The connection contract is asserted rather than assumed — requireEncoded(connection != null && !connection.getAutoCommit() && connection.isReadOnly() ...) (:1266) — and the module is built on byte-exactness: canonical rows and snapshots are compared with Arrays.equals at the projection, resource-ref, retirement-carrier and pinned-row sites (:481, :843, :855, :1078, :1223, :1341, :1682), the snapshot carries a hard-coded "qwen-csi-application-inventory/2" version header (:557), per-kind payloads are capped (managed-message-parts at MAX_BYTES, everything else at 8 MiB, :1461), and payload(...) rejects empty or over-limit bytes (:1918).

JdbcCsiActivationAdmission.java (919 lines, byte count verified). Every time fence uses the database clock rather than the JVM's: JdbcRepositorySupport.databaseNowPrecise(connection) at :261, :414 and inside NativeHead.requireCurrentTime (:447-449), with requireCurrentTime invoked at :205, :295, :309, :370 and :465. The two directions are correctly opposed — the live paths require writerExpiresAt > now && activationExpiresAt > now (:296, :310, :449) while the cold path requires writerExpiresAt <= now && history.activation().expiresAt() <= now (:415), so a live writer cannot be displaced and an expired one cannot be treated as live. Locking reads carry tenant and session predicates (:283, :480). The journal replay is bounded and chained: MAX_HISTORY = 4096 and MAX_HISTORY_BYTES = 64 MiB (:22-23), each entry requiring revision < MAX_HISTORY, journal_revision == revision + 1 for contiguity, sha256(bytes) equal to record_digest, a cumulative byteCount <= MAX_HISTORY_BYTES, and previous_commit_digest matching the running digest (:530-572); requireNoJournalTail then confirms nothing exists past the expected revision (:518, :685), and JournalRead(System.nanoTime()) (:633) bounds a historical read's wall clock.

What else I verified at this head, and what the rebase changed

The branch was rebased onto a main that now includes the server package reorganization, and the newest commit aligns this feature with that layout — WorkspaceCsiApplicationStore and WorkspaceCsiApplicationInventory now sit under managedagent/persistence/ rather than managedagent/store/. Build and verify reference distribution is green at this head, which is the lane that compiles the Java module against the reorganized layout, so the boundary-crossing hazard that broke the sibling reorganization PR is not present here.

The positives I verified at the earlier heads still hold and I re-checked rather than assumed them: the retirement endpoint keeps its action set closed at the mapping (freeze|cut|finalize), takes identity from TenantContext and the writer token from the header, and shape-validates the bearer value before use; requireCsiApplicationCredential is still called on every mutating path with verifySaved after it; V12__csi_application_retirement.sql is still purely additive with zero DROP/DELETE/TRUNCATE/MODIFY statements and keeps uq_ma_csi_retirement_target scoped to retirement operations through the generated column; and JdbcCsiRetirementSeal still uses its three tenant-keyed FOR UPDATE reads with byte-and-digest equality on the frozen request. workerAuthority additionally re-derives the expected worker request and requires the incoming body to equal it exactly (:277-278), so the endpoint cannot be used to authorize a request the server did not compose — a check I had not previously noted.

No blocking finding was ever filed against this PR: there is no automated review ledger, no [Critical] inline comment, and the reviewer findings that exist are all explicitly non-blocking. My scan found no provable Critical at any of the three heads.

CI

No failing check at this head. Build and verify reference distribution, Classify PR, Remind on force-push, authorize and label pass; Test (ubuntu-latest, Node 22.x), Lint & Static, Serve A/B, Integration Tests (no-AK, No Sandbox), OpenTUI no-flicker gate and TUI parity snapshots were pending at submission and are not treated as gates. The Flyway uniqueness gate passes, which is the check that matters for the new V12 migration.

Scope of this review

Read at this head, with fetched byte counts checked against the API's reported size: WorkspaceCsiApplicationController.java in full; WorkspaceCsiApplicationStore.java's workerAuthority in full and its credential/verify structure across all mutating paths; WorkspaceCsiApplicationInventory.java's bounds, overflow handling, connection contract, version header and byte-equality sites; JdbcCsiActivationAdmission.java's time fences, locking reads, journal-chain verification, tail check and terminal-state conjunction; JdbcCsiRetirementSeal.java's locking and identity predicates; and V12__csi_application_retirement.sql in full.

Not covered: a line-by-line read of the two large files — I verified their safety-critical properties (bounds, locking, clock source, digest chaining, terminal state) rather than every row-projection and image-comparison branch, so a defect in an individual projection's field mapping could survive this review; the remaining WorkspaceCsiApplication{History,Image,HistoryImage,Json,WorkerMatch}.java; CsiFileFinalizeProtocol.java and its TypeScript counterpart as a compared pair; the packages/core changes in http-managed-session-store.ts and managed-session-authority.ts beyond their diffs; every test file and fixture; and the design docs. I ran no build, test, Maven verify or MySQL lane myself, and the approvals already on the prior head are those reviewers' evidence rather than mine.

中文说明

本轮针对新的提交重新评审,取代我此前两份 Comment,并首先更正其中一处事实错误,因为它涉及安全控制。

更正:我在早先的评审中把持有者令牌校验描述为「两个凭据都不匹配才返回 401」,即任一匹配即通过。实际代码是 !seedMatches || !leaseMatches,即必须同时匹配预置种子令牌与租约令牌,两者是逻辑相反的关系。我的错误低估了该控制的严格程度,因此没有据此错误放过任何问题,但依赖该描述的读者会误解哪一个凭据是充分的。更重要的是,这个「与」条件的可满足性不是靠假设,而是被强制保证的:终局状态校验在一个合取中同时要求状态为 SEALED、激活阶段为 released、激活纪元与事件纪元均为 1、写者代次为 1、日志修订与已提交序号精确衔接、提交摘要一致、前驱激活标识与工作者标识匹配、过期时间匹配,且冻结请求中的写者令牌摘要等于库中租约令牌哈希。凡租约曾独立轮换过的绑定都不可能满足纪元 1 与代次 1,因此根本到不了该接口;即便到达,校验也会以 401 失败关闭。所以残余风险属于可用性而非授权。

此前两份评审列为未读的两个大文件,本轮已由我本人在当前提交上核对。清单类的边界是真实的且在循环内即时生效:行数与字节上限固定,Jackson 的嵌套深度与字符串长度受限,扫描查询按上限加一行取数以使溢出可被察觉,触限时写入阻塞原因并置溢出标志,外层循环在继续前先检查该标志,因此被截断的扫描不会被误认为完整;连接契约以断言方式要求非自动提交且只读;模块整体建立在逐字节相等之上,规范行与快照在多处用字节比较校验,快照带固定版本头,不同类别的负载各有上限,空或超限字节被拒绝。准入类的所有时间栅栏都取数据库时钟而非进程时钟,存活路径要求写者租约与激活都未过期,冷接管路径要求两者都已过期,方向相反且各自正确;加锁读带租户与会话条件;日志重放有行数与累计字节上限,逐条校验修订连续、摘要匹配与前序提交摘要衔接,并在最后确认预期修订之后没有悬空条目,历史读取另有时间预算。

本次变基跨越了主干上的服务端包重组,最新提交把本功能对齐到新的包布局,两个持久化类已从 store 移到 persistence。构建通道在当前提交上通过,而它正是会把 Java 模块与新包布局一起编译的通道,因此同期那个重组改动所踩到的跨包可见性问题在本 PR 上不存在。此前核对过的结论本轮重新确认而非沿用:退役接口的动作集合仍由路由模式限定,身份取自服务端租户上下文,写入令牌取自请求头并在截取前做形态校验,每个变更路径都在加锁后校验凭据并在其后复核已保存状态;数据库迁移仍是纯增量,无任何删除或修改语句,生成列使唯一约束只作用于退役操作;封印逻辑仍使用三处带租户条件的加锁读并对冻结请求做字节与摘要双重比对。另外,持有者接口还会重新推导期望的工作者请求并要求传入请求与之完全相等,因此无法用它去授权一个并非服务端组装的请求——这一点我此前没有记录。

本 PR 从未被提出阻塞性问题:没有自动评审记录,没有严重级行内评论,现有评审意见均明确标注为非阻塞;我在三个提交上的扫描都未发现可证明的阻塞缺陷。CI 无失败项,构建与若干簿记通道通过,单元测试等六项仍在运行,按规则不作为门禁;迁移版本唯一性检查通过。未覆盖:两个大文件的逐行阅读(我核对其边界、加锁、时钟来源、摘要链与终局状态等安全关键属性,而非每一个行投影与镜像比较分支,因此单个投影的字段映射缺陷可能逃过本轮)、其余若干辅助类、跨语言终结协议两侧的并排比对、核心包两个 TypeScript 文件的非改动部分、全部测试与设计文档;也未自行执行构建、测试或数据库通道。

@doudouOUC
doudouOUC merged commit c1d306d into main Oct 19, 2026
115 of 121 checks passed
@doudouOUC
doudouOUC deleted the codex/csi-application-retirement branch October 19, 2026 16:44
@github-actions

Copy link
Copy Markdown
Contributor

Managed Agent gate failed

Run 39278815506 · commit 749cfdfdf883

Failing tests

  • com.alibaba.qwen.code.managedagent.HostedHookFaultGatesIT.fg13cWorkerKillLeavesTheHookUnknownAndKeepsTheSessionOnMySql
  • com.alibaba.qwen.code.managedagent.HostedSessionRelayFaultGatesIT.fg9bRefusedJournalCommitsHealOnlyThroughTheOriginalCommandOnMySql
  • com.alibaba.qwen.code.managedagent.HostedWorkspaceToolTurnIT.sessionStoreFailuresNeverReplayEffectsOnMySql(CapturedOutput)
  • com.alibaba.qwen.code.managedagent.HostedAutomationFaultGatesIT.fg11bHarnessStoreFaultsNeverRunTwiceOnMySql
  • com.alibaba.qwen.code.managedagent.HostedExtensionsIT.disconnectedMcpEffectIsNotReplayedAfterHarnessReplacementOnMySql
  • com.alibaba.qwen.code.managedagent.HostedTeamMemberCommandMySqlIT.memberHarnessRestartDuringCommandWait
  • com.alibaba.qwen.code.managedagent.HostedWorkflowRelayFaultGatesIT.fg10cRefusedRelayCommitsNeverAdvanceAWorkflowOnMySql

Tracking issue

@qwen-code-review-bot

Copy link
Copy Markdown
Collaborator

Released in v0.26.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants