Skip to content

feat(managed): Add bounded SQL history queries - #15839

Merged
doudouOUC merged 3 commits into
mainfrom
feat/managed-sql-authority-window
Oct 29, 2026
Merged

doudouOUC merged 3 commits into
mainfrom
feat/managed-sql-authority-window

Conversation

@doudouOUC

@doudouOUC doudouOUC commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

What this PR does

Adds bounded read APIs for Managed local H2 and Hosted MySQL: recent published message Items with an authenticated older-page cursor, recent committed journal transactions within a captured revision, and exact operation/command ID lookup. Reuses existing tables, snapshots, indexes and authorization. This replaces the earlier broad implementation in this PR; authority windows, history caches, derived history tables/backfill, full-history streaming recovery and cross-consumer/CSI changes have been removed from the final diff.

Why it's needed

History reads should request the needed page or identity from durable SQL instead of requiring a complete history reconstruction or another instance's cache. The existing task, approval, resource and recovery state APIs remain available. Published message snapshots and raw journal transactions retain separate semantics.

Reviewer Test Plan

How to verify

Request a small recent Item page, then follow its opaque cursor toward older Items. Each page must stay within the requested count, return chronological Items, and preserve its original snapshot after a newer projection is published. Wrong-scope, tampered, expired and wrong-direction cursors must fail. Read the returned snapshot coverage before comparing with current Session state: a snapshot may lag, and an empty zero-coverage result does not prove there is no Session history.

Query recent journal transactions using a fixed throughRevision and exclusive beforeRevision; newer commits must not leak into later pages. Verify exact command identity lookup, invalid/future bounds, row and byte limits, digest validation, and refusal of invalid or replaced writer credentials. Existing transcript, forward export, execution and Legacy behavior must remain unchanged.

Evidence (Before & After)

N/A for UI visuals: this change adds query APIs and a thin WebShell client method; existing UI flows are unchanged. TypeScript build144.568s, typecheck55.715s and51/51 client tests passed on ce2cccc; their runtime/type inputs remain unchanged by the final version-only fix. On that source, Lint job123367693818 and the separate contract-version status failed because the changed OpenAPI document kept1.95.0. Commit34619060eb26fb194fc059cf32475a5ce223b4d1 only advances info.version to1.96.0: the actual Node gate was reproduced RED and then passed GREEN, generated client types stayed byte-identical, and format/diff checks passed. No Java preparation, tests or application rebuild were run for this fix. The separately authorized ce2 preview compilation/startup remains historical compile/start evidence with0 tests; its H2 instance and data were preserved. Final-head Java/H2/MySQL/HTTP/contract/admission qualification remains pending run40864187528: metadata head matches34619060eb26fb194fc059cf32475a5ce223b4d1, pending/0jobs at readback, actual checkout and gates unverified. The earlier ce2 full run40850365742 completed cancelled/0jobs after replacement; it is not a pass. Earlier broad-head recovery/residency evidence is not current qualification.

Tested on

OS Status
macOS TypeScript checks passed on ce2; Node version gate passed after the metadata fix; no Java tests
Windows Not tested locally
Linux Not tested locally; CI pending

Environment (optional)

macOS, Node.js 26.12.1, repository-pinned pnpm dependencies. Original verification phase Java preparation and execution: 0; separately authorized preview compilation/startup is recorded above. The original shared Java budget remains CLOSED564.787/600; the remaining 35.213 seconds are forbidden and were not reset.

Risk & Scope

  • Main risk or tradeoff: recent Items come from the newest published snapshot, whose coverage may lag the Session head; this API does not include the live event tail or establish current execution state. Journal transaction count is not visible message count.
  • Not validated / out of scope: new Java/H2/MySQL/HTTP behavior awaits CI. UI adoption, complete snapshot-plus-tail paging, execution-state reconstruction changes, authority eviction/cache design, standalone JSONL optimization and full RSS/scale qualification are outside this increment. Core, CLI, schema, workflows, dependencies, checkpoint/CSI and Legacy sources match the main baseline.
  • Breaking changes / migration notes: additive routes and a separate version-2 backward snapshot cursor; existing forward export cursors and routes retain their behavior. No schema migration, history deletion, replay-floor advance, writer renewal or snapshot publication is introduced. Designs: English, 中文.

Linked Issues

Related to #13184; does not close it. Supersedes the broad scope preserved in Draft #15696 and this PR's earlier commit history.

中文说明

What this PR does

为 Managed 本地 H2 和 Hosted MySQL 增加有界读取接口:最近已发布消息 Item 及经认证的更早页游标、捕获版本内最近已提交的 journal 事务,以及按精确 operation/command ID 点查。复用现有表、快照、索引和授权。本次替换本 PR 此前较宽的实现;最终 diff 已移出 authority 窗口、历史缓存、派生历史表/补建、全历史流式恢复以及跨消费者/CSI 改造。

Why it's needed

历史读取应从持久化 SQL 查询需要的页或身份,不应要求重建完整历史或依赖另一实例的缓存。既有任务、审批、资源和恢复状态接口继续保留。已发布消息快照与原始 journal 事务保持不同的语义。

Reviewer Test Plan

How to verify

请求小容量最近 Item 页,再沿不透明游标向更早的 Item 翻页。每页不得超过指定数量,Item 按时间顺序返回;新 projection 发布后,旧游标仍读取原快照。跨 scope、篡改、过期及方向不符的游标应拒绝。与当前 Session 状态比较前,应检查响应的快照覆盖位置:快照可能落后,零覆盖位置的空结果不能证明 Session 没有历史。

使用固定 throughRevision 和排他 beforeRevision 查询最近 journal 事务,新提交不得进入后续页。验证精确命令身份点查、非法/超前边界、行数与字节预算、摘要校验,以及非法或已被接替的 writer 凭据被拒绝。既有 transcript、正向导出、执行与 Legacy 行为应保持。

Evidence (Before & After)

UI视觉证据N/A:本次增加查询接口及薄WebShell客户端方法,既有UI流程不变。ce2ccccb718c2e47dc06df17f83e84ff6dc94a74的TypeScript构建144.568秒、类型检查55.715秒和51/51客户端测试通过;最终仅版本号修正未改变这些运行时/类型输入。该来源的Lint job123367693818及独立契约版本status因修改OpenAPI后仍保留1.95.0而失败。提交34619060eb26fb194fc059cf32475a5ce223b4d1只把info.version升至1.96.0:实际Node门禁先复现RED、修后GREEN,生成客户端类型逐字不变,格式/diff检查通过。本修复未执行Java准备、测试或应用重建。另行授权的ce2预览编译/启动仍仅是0测试的历史编译启动证据,保留其H2实例与数据。最终head的Java/H2/MySQL/HTTP/contract/admission资格仍待run40864187528:metadata head准确为34619060eb26fb194fc059cf32475a5ce223b4d1,读回时pending/0jobs,实际checkout与gate尚未验收。先前ce2完整run40850365742在替换后completed cancelled/0jobs,不算通过。此前较宽head的恢复/常驻内存证据不算当前资格。

Tested on

OS Status
macOS ce2 的 TypeScript 检查通过;元数据修复后 Node 版本门禁通过;未运行 Java 测试
Windows 本地未测试
Linux 本地未测试;待 CI

Environment (optional)

macOS、Node.js 26.12.1、仓库锁定的 pnpm 依赖。原验证阶段 Java 准备和执行均为 0;另行授权的预览编译/启动见上文。原共享 Java 预算保持 CLOSED564.787/600,剩余 35.213 秒禁用,未重置。

Risk & Scope

  • 主要风险或取舍:最近 Item 来自最新已发布快照,其覆盖位置可能落后于 Session head;此接口不包含实时事件尾部,也不证明当前执行状态。journal 事务数量不等于可见消息数。
  • 未验证及范围外:新增 Java/H2/MySQL/HTTP 行为待 CI。UI 接入、完整快照与实时尾部组合分页、执行状态重建变更、authority 淘汰/缓存设计、独立 JSONL 优化及完整 RSS/规模资格不在本增量内。Core、CLI、schema、workflow、依赖、checkpoint/CSI 与 Legacy 源码保持主干基线。
  • 破坏性变更及迁移:新增路由和独立的版本 2 反向快照游标;既有正向导出游标及路由保留原行为。不新增 schema migration、历史删除、replay floor 推进、writer 续约或快照发布。设计:English、中文。

Linked Issues

关联 #13184,不关闭该 issue。原较宽范围保留在 Draft #15696 及本 PR 先前提交历史中。

Extract the Managed H2/MySQL history and authority window from Draft #15696 onto main. Preserve daemon Legacy readers and notification admission, and defer standalone file-terminal streaming and residency work.

Retain captured canonical prefixes, exact receipts and CSI proof validation. Adopt the validated compact activation lease during streamed authority restoration.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
@qwen-code-review-bot

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

Copy link
Copy Markdown
Collaborator

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

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

@doudouOUC

doudouOUC commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Hourly contract-version fix — 3461906

The exact ce2 checkout failed Lint job123367693818/run40850216729 because the newly changed public contract retained info.version1.95.0; the separate latest-main uniqueness status failed for the same condition. Complete log:88426 bytes, SHA2566bfb6429d9dbac259a49a1f47693b154c448cff08d2058187ad626e4467bb58d. The only tracked increment advances the contract to1.96.0. The actual existing Node gate reproduced RED and passed GREEN against captured main2919258c6f612e70694f2b6f9f96d4105506319a/version1.95.0. Independent test-engineer verification, full-file inverse-byte comparison, identical regenerated client types and formatting/diff checks passed. No Java, application build or unrelated test suites were run; prior ce2 TS51/build/typecheck evidence is reused only for unchanged inputs. Both Java allowances remain CLOSED.

Final-head SDK Java run40864187528 was dispatched once: exact metadata head34619060eb26fb194fc059cf32475a5ce223b4d1, pending/0jobs, actual checkout and all Java/H2/MySQL/API/admission gates unverified. Prior ce2 full run40850365742 became cancelled/0jobs after the new pending request, with no manual cancel by this automation; it is not a pass. The live ce2 H2 preview on5196 and its data were not touched and are not new-head acceptance. All prior reports below retain their exact source boundaries and original text.


小时检查契约版本修复——34619060eb26fb194fc059cf32475a5ce223b4d1

准确ce2 checkout的Lint job123367693818/run40850216729因新增公开接口后info.version仍为1.95.0而失败;独立latest-main版本status同因失败。完整日志88426字节,SHA2566bfb6429d9dbac259a49a1f47693b154c448cff08d2058187ad626e4467bb58d。本轮唯一跟踪增量是版本号升至1.96.0。对照捕获的main2919258c6f612e70694f2b6f9f96d4105506319a/1.95.0,实际既有Node门禁修前RED、修后GREEN;独立test-engineer验证、整文件反向逐字还原、生成类型不变及格式/diff检查均通过。本轮未执行Java、应用构建或无关测试;此前ce2的TS51/build/typecheck证据仅按未变输入复用。两项Java额度均保持CLOSED。

最终准确head SDK Java run40864187528仅派发一次:metadata head为34619060eb26fb194fc059cf32475a5ce223b4d1,pending/0jobs,实际checkout及Java/H2/MySQL/API/准入门禁均未验收。先前ce2完整run40850365742在新的pending请求后变为cancelled/0jobs,本自动化没有执行手动取消,不算通过。5196的ce2 H2预览及数据未动,不作为新head验收。下方历史报告逐字保留各自来源边界与原文。


Author-approved startup demo update — ce2ccccb718c2e47dc06df17f83e84ff6dc94a74

The user separately authorized up to 600 seconds to compile and start a preview, without reopening the original verification budget. Current-source SDK installation and server packaging succeeded; javac compiled 391 server source files and tests were skipped. The executable JAR contains the new query routes. A fresh H2 Managed instance is running on loopback port5196: HTML root200 and Java readiness200/UP. Startup completed within315.129 wall seconds; no Java tests, MySQL, new-query HTTP acceptance or model calls were run. The first launch refused a data directory inside Git; retry used a fresh outside-worktree directory. A diagnostic Node /api/health request returned404; the actual Java readiness endpoint returnedUP. Automatic browser opening was queued, but browser automation is disabled in Work settings, so no visual UI acceptance is claimed. The original CLOSED564.787/600 ledger is byte-identical. Earlier local compilation NOT_RUN entries below describe the verification phase preceding this separately approved startup; compilation is now successful, SQL/HTTP/test qualification still awaits CI.

中文:用户单独批准最多600秒用于编译和启动预览,原验证预算不重开。当前源码SDK安装及服务打包成功,javac编译391个服务源码,测试跳过;JAR包含新查询路由。全新独立H2 Managed实例已在本机5196运行,HTML根路径200、Java readiness200/UP,在315.129秒内完成启动;未运行Java测试、MySQL、新查询HTTP验收或模型调用。首次启动拒绝Git工作树内的数据目录,改为项目外全新目录后正常启动。Node /api/health诊断请求404,正确的Java就绪端点为UP。自动打开请求已排队,但Work设置禁用浏览器自动化,未声明视觉验收。原CLOSED564.787/600账本逐字未变。下文此前编译NOT_RUN对应本次单独启动授权之前的验证阶段;现在编译成功,SQL/HTTP/测试资格仍待CI。


Current scope verification — ce2ccccb718c2e47dc06df17f83e84ff6dc94a74 (replaces broad scope at 7a120ead697409c0d62d315bf2295c28d1294dbd).

The final diff against main baseline 523be857db7bcd7d3346b58b0c9bd08392bb1251 is 23 files, +751/-3, including 237 added / 2 removed production logic lines. It adds recent published Item pages and direct canonical journal recent/command reads. Core/CLI, schema, workflows, dependencies, provider/UI hooks and checkpoint/CSI match that baseline. Authority windows, history caches, derived-index/backfill and full-history streaming recovery are no longer part of this PR. Original broad source is preserved as an ancestor and in Draft #15696.

Evidence Current result
TypeScript build PASS, 144.568 s
Typecheck PASS, 55.715 s; later test error-code literal correction and docs/JSDoc-only updates retain type shapes
Affected WebShell client file 51/51 PASS, zero failed/skipped/missing/unexpected; both new cases executed; one requested file
Scoped Prettier / ESLint / generated API PASS
Source review Two consecutive root clean passes and two independent clean passes; not whole-PR/runtime approval
Java compilation, unit/H2, SQL/HTTP/contract/admission/MySQL NOT RUN locally; CI pending
Full Java CI run 40850365742, metadata head exactly matches ce2ccccb718c2e47dc06df17f83e84ff6dc94a74; pending, 0 jobs at readback; actual checkout and complete qualification not yet verified
Runtime/model/Hosted publication, UI adoption, complete RSS/scale NOT RUN / out of scope

The client test checked source/toolchain/test inputs and built artifacts before/after execution: 23 candidate files, 1,753 inputs and 17,882 artifacts remained stable. Four later documentation/OpenAPI/generated-JSDoc changes reverse exactly to the executed hashes and do not change runtime or type shapes. The commit hook preserved tree 8e9200dee9972b94e80181d84b1821e16fd02c4c.

Semantic limits: recent Items are the newest published snapshot and may lag the Session head. Zero-coverage empty results do not certify no history. The returned coverage and signed backward cursor preserve the same snapshot across pages; existing transcript/live-tail/current-task/approval/recovery APIs are unchanged. Journal pages count transactions rather than visible messages. Reads do not acquire/renew writer ownership or settle uncertain appends. The original Java budget stays CLOSED564.787/600, 35.213 forbidden; no Java preparation/execution or budget reset. All newly written Java tests remain CI-only evidence until execution.


中文:当前范围验证 ce2ccccb718c2e47dc06df17f83e84ff6dc94a74,替换旧 7a120ead 的较宽范围。最终相对 main 基线为 23 文件、+751/-3;生产逻辑 +237/-2。仅增加已发布 Item 的最近页/更早页,以及 canonical journal 最近事务和命令点查;Core/CLI、schema、workflow、依赖、provider/UI hook 与 checkpoint/CSI 保持基线。authority 窗口、历史缓存、派生索引/补建和全历史流式恢复已移出;原实现保留为祖先及 Draft #15696。

本地 build 144.568 秒、typecheck 55.715 秒通过;之后仅测试错误码字符串和说明/JSDoc 调整,类型结构不变。客户端单文件 51/51 PASS,零失败/跳过/缺失/意外执行,包含两个新增用例。Prettier/ESLint/类型生成通过,根与独立各两轮静态 clean;静态审阅不等于全 PR 或运行时验收。执行前后 23 候选、1,753 输入、17,882 产物稳定,之后四个说明文件可精确逆向恢复到已测哈希。提交 hook 未改变已审树。

Java 编译、unit/H2、SQL/HTTP/contract/admission/MySQL 均 本地 NOT_RUN,待 CI。完整 Java run 40850365742 已准确派发一次,metadata head 是上述提交,读回 pending/0 jobs,尚无实际 checkout/完整 gate 验收。共享预算始终 CLOSED564.787/600、35.213 禁用,准备/执行均 0,不重置。旧结果不转作当前通过。

最近 Item 只覆盖最新已发布快照,可能落后实时 head;零覆盖空结果不能证明无历史。分页保留覆盖位置与签名反向游标;既有 transcript、实时尾部、任务、审批和恢复接口不变。事务数量不等于可见消息数。不获取/续 writer、不用查询结算不确定追加。UI 接入、真实模型/Hosted 发布、完整 RSS/规模不在本增量验收内。

Historical verification for superseded broad head 7a120ea — preserved verbatim / 旧范围验证原文保留

Independent verification report / 独立验证报告

Source / 源码: 7a120ead697409c0d62d315bf2295c28d1294dbd, tree dfb598ceda3922e06de13cf4830419639a1a51ee, independent base main 523be857db7bcd7d3346b58b0c9bd08392bb1251. Extracted from Draft #15696; the original branch and interrupted merge remain preserved. / 独立于 main 提取,原 Draft 分支及中断的合并现场均保留。

Verification / 验证 Result / 结果 Boundary / 范围
Directed TypeScript / 定向 TypeScript 209/209 PASS; 0 failure/missing/target skip/unexpected execution Config1 + recorder4 + Session6 + HTTP store196 + streamed cancellation2. Only these selected invocations executed. / 仅执行这些选定用例。
Legacy isolation controls / Legacy 隔离对照 Same5 RED to GREEN Original transcript readers and notification identity admission remain independent of unavailable Managed history; includes more than2200 primed IDs. Callback structural ASTs and literal payloads match before/after. / 原读取及通知准入不依赖不可用的 Managed 历史,含2200以上身份;修前修后测试 AST 与字面量一致。
Compact lease restore / 紧凑租约恢复 Historical qualified RED to current GREEN The old failing source was not rerun as a new RED. Current HTTP test restores the validated lease after100renewals without journal growth. / 原失败保留原来源,当前恢复100次续约后的已校验租约且 journal 不增长。
Build/typecheck/bundle / 构建、类型、打包 PASS140.834s /58.216s /2.512s Final source; pre-commit hook preserved the exact tested tree. / 最终源码及 hook 保持已测 tree。
Formatting/ESLint / 格式与 lint PASS Changed supported files; both scoped design references checked. / 仅变更范围,两份设计链接已核对。
Workflow metadata / workflow 元测试 705PASS /5SKIP /0FAIL All direct parsers of the edited SDK Java workflow plus report guard; five Linux-only cases skipped on macOS. Synthetic shell fixtures are not Java execution. The old unrelated octopus timeout was not retried. / 5项仅 Linux 用例在 macOS 跳过;shell夹具不代表 Java 运行,未重跑旧 octopus 超时。
Independent static review / 独立静态审阅 2incremental clean passes 20excluded paths equal main;41tables844columns equal the parents' exact column union. Static Java review is not Java GREEN or whole-PR approval. / 20处排除项同 main,41表844列为双亲准确列并集;静态审阅不代表 Java 通过或全 PR 批准。

During GREEN runs,261 captured source files and15497 built-artifact files remained unchanged. Their source bytes match committed tree dfb598ceda3922e06de13cf4830419639a1a51ee. / GREEN期间261个源码文件及15497个构建产物保持一致,源码与提交 tree 精确一致。

Failures retained / 保留失败: the first post-isolation build failed on a readonly-array assignment (29.391s), corrected before final successful checks. The initial imported-source build passed146.522s and is not the final-source build. All5 expected RED controls and the historical compact-restore RED remain preserved. / 首次隔离后的构建在 readonly 数组赋值处失败,修正后才得到最终通过;146.522秒初始构建属于修前导入源码,不能替代最终验证。

NOT RUN locally / 本地未运行: Maven/JVM preparation, Java compilation, H2/MySQL/MariaDB profiles, real Hosted/model/HTTP/process execution, native10k/100k scale/checkpoint/context/RSS/network and platform fault acceptance. The same Java budget remains CLOSED564.787/600seconds;35.213seconds remain forbidden and were not reset by this split. Final-head full CI remains required. / 这些资格全部等待最终 head CI,本地 Java 配额未重置或使用剩余预算。

Historical CI / 历史CI: the original report preserves older source boundaries, successes, failures, cancellations and unrun assertions. At194, Broker setup timed out600s before gate execution; multi-node passed10tests. AtAE, Hosted faults had165tests/3failures/4errors/4skips: four Workflow mirrors remained delivered/accepted/pending150s despite canonical consumption, FG9f status mismatch, a Managed history-load fetch timeout and Automation first-slot RuntimeBroker500. These results do not qualify this new head or prove an exclusive PR cause. No ledger, timeout, selector or assertion was weakened; no blind rerun was requested. / 原报告保留全部旧来源;上述结果均不验收新 head,不作排他归因,未修改账本设计、超时、selector 或断言,也未盲目重跑。

Evidence / 本地证据: .qwen/managed-sql-split/ and its test-engineer/ report, exact inventories, source/artifact hashes, RED/GREEN logs, AST proof, exclusion/schema checks and build/style/meta/commit proofs. The old saved merge and full R38 CI logs remain under the original58fb worktree. / 以上为源码与定向验证证据,不代表完整集成或发布已完成。

Full SDK Java CI: run40841759553 was requested once for 7a120ead697409c0d62d315bf2295c28d1294dbd. Metadata matches the final head; actual checkout, profiles and complete qualification remain pending.

@qwen-code-review-bot

Copy link
Copy Markdown
Collaborator

🩺 serve daemon A/B

Built the PR base vs this PR head 7a120ea, 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 41 38

— Qwen Code · serve A/B

@doudouOUC
doudouOUC marked this pull request as draft October 29, 2026 08:48
@qwen-code-review-bot

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

Copy link
Copy Markdown
Collaborator

Thanks for the PR!

This is a re-run at a new head. My previous pass reviewed 7a120ead — the 264-file, ~24.9k-production-line version — and deferred it to a maintainer on scale. That escalation no longer applies and I'm withdrawing it: the diff is now 23 files and 239 production logic lines. Everything below is a fresh judgement on 34619060, not an edit of the old one.

Template looks good ✓ — every required section is present, the Chinese block is a real paragraph-by-paragraph translation, and both design docs are linked from Risk & Scope as the template asks.

Problem: observed, not theoretical. #13184 is still open, labelled type/bug + category/performance + scope/memory-usage (and still carrying need-discussion). Worth being precise about what this PR does and doesn't claim, though: it explicitly does not close #13184, and the design doc disclaims bounded UI history, bounded recovery time and bounded total RSS. The problem it actually addresses is narrower and real — a history read today needs either a full reconstruction or another instance's cache, and neither should be required to fetch one page or one command.

Direction: aligned. Pulling the query layer out of the broad implementation and landing it alone is the right response to the earlier round, and the compatibility section is honest about what stays untouched: canonical history, the schema baseline, replay floor, journal format, admission, cleanup and every execution consumer. No V2 migration, which is what this module's rules require before the first formal release.

Size: this spans packages/managed-agent-server/** and packages/web-shell/**, so it does fall under the cross-package core definition. It clears the gate comfortably:

  • production logic: 239 lines (Java main 232 + web-shell client 7)
  • API contract: 51 · generated types: 50 · tests: 350 · design docs: 66

feat type means no size hard-block regardless, 239 is well under the 500-line maintainer-awareness threshold, and the author holds admin on this repo — so this is maintainer-authored work and the two-tier core gate is exempt. No escalation, and the large-PR advisory doesn't apply.

Approach: I wrote down what I'd do before reading the diff — three bounded read shapes reusing the existing tables, an opaque authenticated backward cursor pinned to snapshot identity, a thin controller, a contract bump, regenerated client types, and H2 + MySQL coverage. The PR matches that almost exactly and beats it in two places: it reuses WebShellExportRequest/WebShellExportPage instead of adding DTOs, and it reuses the existing page() cursor machinery behind a version discriminator rather than building a parallel cursor. Cutting the scope by ~99% of production lines kept all of the substance.

One genuine question, not a blocker: all three new endpoints currently have zero callers. getRecentTranscriptItems is referenced only by its own test, /transcript/items/query has no UI adoption (declared out of scope), and neither internal route has a consumer. I verified this rather than assuming it — the complete 23-file list contains no UI or consumer file, and the base tree has no pre-existing reference to any of the new symbols or paths. Landing the query layer ahead of its consumer is a defensible way to split a large PR, and the surface is properly gated (contract version, surface registry, capability parity all synchronized). But it does commit public WebShell contract 1.96.0 to routes nothing calls yet, and #13184 stays open after this merges. Is the consumer slice already queued, or should the endpoint land with it?

Risk: no elevated risk signals — none of the changed files match the revert-correlated path list.

Moving on to code review. 🔍

中文说明

感谢贡献!

这是一次针对新 head 的重跑。 上一轮我审查的是 7a120ead —— 264 个文件、约 24.9k 生产行的版本 —— 并因规模转交了维护者。该升级已不再适用,我在此撤回:当前 diff 是 23 个文件、239 行生产逻辑。以下所有内容都是对 34619060 的全新判断,不是对旧结论的修改。

模板完整 ✓ —— 所有必填小节都在,中文部分是逐段完整翻译,Risk & Scope 也按模板要求附上了两份设计文档链接。

问题: 是已观测到的问题,不是理论性加固。#13184 仍处于 open 状态,带有 type/bug + category/performance + scope/memory-usage 标签(并且仍带 need-discussion)。不过需要说清本 PR 主张与不主张的范围:它明确不关闭 #13184,设计文档也声明不宣称 UI 全历史、恢复耗时或进程总 RSS 已有界。它真正解决的是一个更窄但真实的问题 —— 今天一次历史读取要么需要完整重建,要么依赖另一实例的缓存,而取一页或一条命令都不应该需要这些。

方向: 对齐。把查询层从较宽的实现里拆出来单独落地,是对上一轮意见的正确回应;兼容性小节对"哪些保持不变"说明得诚实:canonical 历史、schema baseline、replay floor、journal 格式、准入、清理以及所有执行消费者。没有新增 V2 migration,这符合本模块在首个正式版本前的规则要求。

规模: 改动横跨 packages/managed-agent-server/** 与 packages/web-shell/**,因此确实落入跨 package 的核心定义。但它轻松通过了 gate:

  • 生产逻辑:239 行(Java main 232 + web-shell client 7)
  • API 契约:51 · 生成类型:50 · 测试:350 · 设计文档:66

feat 类型意味着无论如何都不触发规模硬阻断,239 行远低于 500 行的"需维护者关注"阈值,且作者在本仓库持有 admin 权限 —— 因此这是维护者自己提交的改动,两层核心 gate 予以免除。无需升级,大 PR 建议也不适用。

方案: 我在读 diff 之前先写下了自己的做法 —— 三个有界读取形态复用现有表、一个以快照身份钉住的不透明已认证反向游标、一个薄 controller、一次契约版本提升、重新生成的客户端类型,以及 H2 + MySQL 覆盖。本 PR 几乎完全吻合,并在两处做得更好:复用 WebShellExportRequest/WebShellExportPage 而不是新增 DTO;用一个版本判别位复用现有 page() 游标机制,而不是另建一套平行游标。把生产行数砍掉约 99% 之后,实质内容一点没丢。

一个真实的疑问,不是阻断项:三个新接口目前都没有任何调用方。 getRecentTranscriptItems 只被它自己的测试引用,/transcript/items/query 没有 UI 接入(已声明为范围外),两个内部路由也没有消费者。这一点我是核实过的,不是推测 —— 完整的 23 个文件清单里没有任何 UI 或消费者文件,且主干代码里对任何新符号或新路径都没有既存引用。先落地查询层、后接消费者,是拆分大 PR 的合理做法,而且这个接口面是被正确管控的(契约版本、surface registry、capability parity 均已同步)。但它确实让公开的 WebShell 契约 1.96.0 承诺了目前无人调用的路由,并且本 PR 合并后 #13184 仍然是 open 的。消费者那一片是已经排上了,还是应该和接口一起落地?

风险: 无升级风险信号 —— 改动文件均未命中与 revert 相关的路径清单。

进入代码审查 🔍

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

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

@qwen-code-review-bot

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

Copy link
Copy Markdown
Collaborator

Code review

My independent proposal, written before opening the diff: three bounded read shapes over the existing tables; for recent Items, take the newest published snapshot and walk its page directory backward, returning a coverage watermark so an empty page can't be mistaken for an empty session; for the older-page cursor, an opaque token that is authenticated and pins snapshot identity so a newer publication can't shift the view mid-paging; for the journal, revision <= through AND revision < before ORDER BY revision DESC LIMIT n+1 with a row and byte budget; for identity lookup, a point query on the existing unique command-key index. Surface it as thin controller methods, bump the contract, regenerate the client types, add one client method, and cover it with H2 unit tests plus a real-MySQL IT.

The PR lands essentially that design, and is better than my baseline in three ways I'd not have thought of:

  • It refuses compacted prefixes outright (compactedThroughRevision() != 0 → 409) instead of trying to serve partial history. That single decision is what makes the backward gap check sound: the terminal condition candidates.getLast().journalRevision() != 1 assumes revision 1 still exists, and the compaction refusal is exactly what guarantees it. The forward path uses head.journalRevision() as its terminal; this is the correct mirror.
  • The cursor version discriminator (position.version() != (backward ? 2 : 1)) makes forward and backward cursors mutually unusable with one changed expression rather than a second cursor type.
  • recentTranscriptItems is a byte-for-byte structural clone of exportPage — same requireReadableSession, same limit() validation, same webShellItem mapping, same WebShellExportPage shape. Only the store call differs. That is the minimal change, and it means the new route inherits the existing authorization path rather than growing its own.

No correctness or security defects found. I went through the paging arithmetic specifically, since that's where this class of change usually breaks:

  • The look-ahead probe in recentItems decrements offset, checks the limit, and encodes next at offset + 1 — so the item it probed but did not include becomes the first item of the next page. No duplicate, no skip. The recentItemsCrossPhysicalPagesAndTerminateWithoutDuplicates test walks all 205 items at limit 37 and asserts the exact sequence, which pins this properly rather than just asserting a page size.
  • When the item count is an exact multiple of limit, the inner loop exits on offset > 0 without setting next, so hasMore correctly comes back false instead of handing out a dead cursor.
  • more = candidates.size() > selected with transactions.getLast() read before the reverse gives the oldest selected revision as the next exclusive bound — correct direction. And selected == 0 can't coincide with more == true: the selected > 0 && guard means the first candidate is always taken when any exist, so the getLast() on an empty list is unreachable.
  • The byte budget reuses MAX_TRANSACTION_BYTES as both the per-row ceiling and the page budget, matching the forward path, so one 8 MiB transaction still makes progress instead of stalling a page forever.
  • On the resume path, offset > rows.size() → invalid cursor, and the snapshot re-query requires state = 'PUBLISHED' AND retain_until >= expires, so the pinned root can't be swapped underneath an outstanding cursor.

Authorization holds up. Both internal routes go through the existing restore(), which does validateScope → requireCredential → requireHead → requireHeadScope → requireReadGrant; neither acquires a writer or renews a lease, and restore() is @Transactional(readOnly = true) with no writes on that path, so calling it from inside the new read-only transactions is safe. The trailing restore() after the rows are built is a real read-then-revalidate check at READ_COMMITTED, not decoration — a grant revoked mid-read turns into an error rather than a leaked page. historyRevision additionally verifies the boundary row at through belongs to the caller's workspace, and commandTransaction cross-checks the size pass against findTransactionByCommand so a hash collision or a revision mismatch surfaces as corruption instead of a wrong row. Tenant isolation is covered by the new contract-test exchanges (200 owning tenant / 404 foreign tenant) and the wrong-writer-token arm of the HTTP test.

Module rules are satisfied. All four artifacts this module requires for an API change move together: OpenAPI contract, mapped routes, SurfaceRegistry, and the parity capture with its regenerated sha256. The generated WebShell types are genuine generator output, not hand-edited — I checked by comparing against the sibling webShellExportSession, whose source JSON lists responses 401, 404, 403, 413, 409 while the generated file sorts them to 400, 401, 403, 404, 409, 413; the new entry shows exactly the same reordering. No V2 migration and no schema version increment. StringUtils is used for the blank checks as the module's library-reuse rules ask. The single AgentStateStore implementor gets the new method with @Override, so the interface addition doesn't break a second implementation.

Two non-blocking observations:

  • commandTransaction reads the journal twice for one row (the bounded sizes query, then findTransactionByCommand unbounded, then a cross-check). It mirrors the existing two-pass style in transactions() and the cross-check does catch a row that moved between reads, so I wouldn't change it — just noting the extra round-trip is deliberate, not accidental.
  • Both new internal endpoints pay restore() twice per request, and restoreHead can pull an activation journal row and SHA-256 it. That roughly doubles the fixed cost of a call on an API whose whole purpose is being cheap. Fine as a security trade, but worth knowing if these get hot.

The Capability.ITEM_LIST choice for the WebShell route is a policy call rather than a technical one — /transcript/query uses TRANSCRIPT_QUERY, while the public item list already uses ITEM_LIST. Since this route returns published snapshot Items rather than transcript events, ITEM_LIST reads as the more accurate fit, but a deployment granting one and not the other will see a difference.

sequenceDiagram
    participant P1 as WebShell client
    participant P2 as Controllers
    participant P3 as ManagedAgentService
    participant P4 as ManagedSnapshotStore
    participant P5 as SQL
    P1->>P2: POST transcript items query (sessionId, cursor, limit)
    P2->>P3: recentTranscriptItems
    P3->>P3: requireReadableSession (tenant and actor)
    P3->>P4: findRecentSnapshotPage, backward true
    P4->>P5: newest PUBLISHED snapshot, pin retain_until
    alt first page, no cursor
        P4->>P5: read last page, walk backward until limit reached
    else resuming from a cursor
        P4->>P4: decode, require version 2, verify scope and expiry
        P4->>P5: re-read the pinned snapshot at its page and offset
    end
    P4-->>P3: items, nextCursor version 2, hasMore, coveredSequence
    P3-->>P1: WebShellExportPage
Loading
Files changed (all 23 shown)
File What changed
docs/design/2026-10-29-managed-sql-history-queries.md New English design doc: scope, the three query shapes, cursor semantics, compatibility and deferred work.
docs/design/2026-10-29-managed-sql-history-queries.zh-CN.md Chinese counterpart, section-for-section aligned with reciprocal links.
packages/managed-agent-server/src/main/java/.../api/ManagedSessionStoreController.java Two new internal GET routes, transactions:recent and transactions:lookup, both taking the writer-token header and delegating straight to the store.
packages/managed-agent-server/src/main/java/.../api/WebShellAgentController.java One new POST route reusing the existing export request and page types.
packages/managed-agent-server/src/main/java/.../persistence/ManagedAgentStore.java findRecentSnapshotPage added beside findSnapshotPage; same session check, delegates to the snapshot store.
packages/managed-agent-server/src/main/java/.../persistence/ManagedSessionStore.java The bulk of the change: backward journal paging, exact command lookup, and the shared historyRevision bounds and prefix check.
packages/managed-agent-server/src/main/java/.../persistence/ManagedSessionStoreModels.java Two new response records.
packages/managed-agent-server/src/main/java/.../persistence/ManagedSnapshotStore.java The existing page() gains a backward flag and a new recentItems walk; cursor version becomes 2 on the backward path.
packages/managed-agent-server/src/main/java/.../session/AgentStateStore.java Interface declaration for the new store method.
packages/managed-agent-server/src/main/java/.../session/ManagedAgentService.java recentTranscriptItems, mirroring exportPage exactly.
packages/managed-agent-server/src/main/resources/openapi/managed-agent-public-api.openapi.json Contract version 1.95.0 to 1.96.0 plus the new WebShell operation, matching its sibling entry's response set.
packages/managed-agent-server/src/test/java/.../ManagedAgentApiContractTest.java Two drift exchanges: 200 for the owning tenant, 404 for a foreign one.
packages/managed-agent-server/src/test/java/.../ManagedSessionQueryMySqlIT.java New: runs the query suite against a real isolated MySQL database.
packages/managed-agent-server/src/test/java/.../ManagedSessionQueryTest.java New: the H2 store-level suite covering paging, lookup, bounds, credentials and a replaced writer.
packages/managed-agent-server/src/test/java/.../ManagedSessionStoreIntegrationTest.java HTTP-level test that both routes read without opening another writer, plus cache-control and wrong-token arms.
packages/managed-agent-server/src/test/java/.../SurfaceAdmissionAcceptanceTest.java Supplies operation and commandId probe params for the lookup route.
packages/managed-agent-server/src/test/java/.../api/SurfaceRegistry.java Three new surface entries reusing existing capabilities.
packages/managed-agent-server/src/test/java/.../persistence/ManagedSchemaSessionMySqlIT.java Asserts the recent-snapshot read on MySQL.
packages/managed-agent-server/src/test/java/.../persistence/ManagedSnapshotNumericPagingTest.java Four new tests: bounded body reads, full backward walk, cursor cross-direction and tamper rejection, snapshot immutability across a newer projection.
packages/managed-agent-server/src/test/resources/capability-parity/managed-surface.txt Three route lines plus the regenerated sha256.
packages/web-shell/client/components/managed/generated/managed-agent-api.ts Regenerated types for the new operation.
packages/web-shell/client/components/managed/java-managed-agent-client.test.ts Two tests: verbatim cursor passthrough, and expired-cursor surfacing without draining or replaying history.
packages/web-shell/client/components/managed/java-managed-agent-client.ts One four-line method.

Test evidence

This is a local invocation, and per the static-review rule I did not build, run or execute anything from this PR — no Maven, no vitest, no server. Everything below is the PR's own CI, read through the API at 34619060. There are no failures on this head, but the suites that matter most have not finished, so nothing here is a pass yet.

54 checks on the commit: 15 success, 30 skipped, 8 in progress, 1 queued, 0 failure. The successes are real but peripheral — lint, the Flyway version-uniqueness check, the Java 11 daemon E2E, the tier selector, and bot orchestration jobs. The load-bearing ones are still running.

Check Conclusion
Lint & Static (ubuntu-latest, Node 22.x) success
SDK Java (fast) / Flyway migration version uniqueness success
SDK Java (fast) / Real daemon E2E / Java 11 success
Select the Managed Agent tier success
Build and verify reference distribution success
Check TUI impact success
SDK Java (fast) / ubuntu-latest / Java 21 in_progress
Test (ubuntu-latest, Node 22.x) in_progress
web-shell E2E Smoke (ubuntu-latest, Node 22.x) in_progress
Integration Tests (no-AK, No Sandbox) in_progress
TUI parity snapshots (ink vs opentui) in_progress
OpenTUI no-flicker gate in_progress
Capture web-shell visuals (ubuntu-latest, Node 22.x) queued
SDK Java (fast) / Runtime Broker and Managed Agent MySQL / Java 21 skipped (fast tier)
SDK Java (fast) / Hosted process fault gates / MySQL 8.4 / Java 21 skipped (fast tier)
SDK Java (fast) / Hosted failover E2E / Java 21 skipped (fast tier)
Test (macos-latest, Node 22.x) skipped
Test (windows-latest, Node 22.x) skipped

The gap that matters: the MySQL evidence does not exist yet on this head. The skipped MySQL legs are not an oversight or infra noise — they are the gate's tiering working as designed. managed-agent-gate.yml selects tier=fast for a pull_request event and only selects tier=full on the first approval of that head, reporting "On a pull request the full suite runs on the first approval of this head." So ManagedSessionQueryMySqlIT and the new ManagedSchemaSessionMySqlIT assertions have not executed against a real MySQL 8.4 on 34619060. yiliang114 approved this exact head at 11:31:57Z, which triggered full-tier run 40866111821 — currently pending with no jobs started. Separately, the author dispatched SDK Java run 40864187528 (workflow_dispatch), also pending with zero jobs.

This is worth being explicit about because the module's own rules say H2 tests alone do not establish MySQL behavior, and the design doc claims "MySQL tests exercise the same journal queries and recent snapshot reads." That claim is currently unverified — the tests are written and correctly structured (ManagedSessionQueryMySqlIT extends ManagedSessionQueryTest, overriding only the datasource), but they have not run here. The backward-paging SQL is the part most likely to differ between engines: ORDER BY journal_revision DESC LIMIT ? with a limit + 1 parameter, and the ma_session_journal_tx gap walk. Note also that the earlier full run 40850365742 on the superseded ce2ccccb head became cancelled with zero jobs — the author says so plainly in the PR body, and that is not a pass.

The author's own reported results — TypeScript build/typecheck passing and 51/51 client tests on the ce2ccccb head, plus a separately authorized H2 preview startup — are the author's claims on an earlier commit, not evidence I re-ran, and they don't cover the current head's Java behavior.

Sandboxed verification would settle the remaining gap: @qwen-code /verify — that the backward journal paging and the recent-snapshot read behave identically on real MySQL 8.4 as on H2 is not observable from the diff, and the two MySQL ITs that would prove it are skipped on the fast tier and still pending on the full tier. The author has write access, so this needs no sponsored run. /tmux is not the right lane here: the PR changes no TUI surface and wires no UI consumer, so there is nothing for a real user to drive.

Real-scenario testing: N/A. Nothing user-visible changes — no UI file is touched, existing transcript and export flows are unchanged by construction (the forward page() overload keeps its original signature and behavior, and backward is false on every existing call path), and the three new endpoints have no callers. Driving them would require building and running the PR's Java server, which the static-review rule forbids on principle. Stating N/A rather than substituting the author's H2 preview.

中文说明

代码审查

我在打开 diff 之前写下的独立方案: 在现有表上做三个有界读取形态;最近 Item 取最新已发布快照并沿页目录反向遍历,同时返回覆盖位置,使空页不会被误读为空 Session;更早页游标使用不透明、已认证且钉住快照身份的令牌,使新快照发布不会在翻页途中改变视图;journal 使用 revision <= through AND revision < before ORDER BY revision DESC LIMIT n+1,配合行数与字节预算;身份点查复用现有命令键唯一索引。对外表现为薄 controller、契约版本提升、重新生成客户端类型、新增一个客户端方法,并以 H2 单测加真实 MySQL IT 覆盖。

本 PR 基本就是这个设计,并在三处比我的基线更好:

  • 它直接拒绝已压缩前缀(compactedThroughRevision() != 0 → 409),而不是尝试提供部分历史。正是这一个决定使反向缺口检查成立:终止条件 candidates.getLast().journalRevision() != 1 假设 revision 1 仍然存在,而拒绝压缩恰好保证了这一点。正向路径以 head.journalRevision() 为终止,这里是正确的镜像。
  • 游标版本判别位(position.version() != (backward ? 2 : 1))用一处表达式就让正反向游标互不可用,而不必引入第二种游标类型。
  • recentTranscriptItems 与 exportPage 在结构上逐行对应 —— 同样的 requireReadableSession、同样的 limit() 校验、同样的 webShellItem 映射、同样的 WebShellExportPage 形态,只有 store 调用不同。这就是最小改动,也意味着新路由继承既有授权路径,而不是另长一套。

未发现正确性或安全缺陷。 我特别核对了分页算术,因为这类改动通常正是在这里出错:

  • recentItems 里的预读探针先递减 offset、再判断 limit、并把 next 编码在 offset + 1 —— 所以它探测到但未纳入的那个 Item,正好成为下一页的第一个。既不重复也不遗漏。recentItemsCrossPhysicalPagesAndTerminateWithoutDuplicates 以 limit 37 走完全部 205 个 Item 并断言精确序列,这是真正钉住了该性质,而不只是断言页大小。
  • 当 Item 总数恰好是 limit 的整数倍时,内层循环因 offset > 0 退出而不设置 next,因此 hasMore 正确返回 false,不会发出一个死游标。
  • more = candidates.size() > selected,且 transactions.getLast() 在 reverse 之前读取,得到的是已选中最旧 revision,作为下一个排他上界 —— 方向正确。而 selected == 0 与 more == true 不可能同时出现:selected > 0 && 这个守卫保证只要存在候选就一定会取第一个,所以空列表上的 getLast() 不可达。
  • 字节预算把 MAX_TRANSACTION_BYTES 同时用作单行上限与整页预算,与正向路径一致,因此单个 8 MiB 事务仍能推进,不会让一页永久卡住。
  • 续读路径上 offset > rows.size() → 游标非法;快照重查要求 state = 'PUBLISHED' AND retain_until >= expires,因此未失效游标所钉住的 root 不会被换掉。

授权是成立的。 两个内部路由都经过既有 restore():validateScope → requireCredential → requireHead → requireHeadScope → requireReadGrant;两者都不获取 writer、不续租,且 restore() 本身是 @Transactional(readOnly = true)、该路径上无写入,所以从新的只读事务内部调用它是安全的。行读完之后再调用一次 restore(),是 READ_COMMITTED 下真实的"读取后复验",不是装饰 —— 读取途中被撤销的授权会变成错误,而不是泄漏一页数据。historyRevision 还额外校验 through 处的边界行属于调用方 workspace;commandTransaction 把 sizes 那一趟与 findTransactionByCommand 交叉核对,因此哈希碰撞或 revision 不一致会表现为损坏,而不是返回错误的行。租户隔离由新增契约测试(本租户 200 / 他租户 404)与 HTTP 测试里的错误 writer token 分支共同覆盖。

模块规则均满足。 本模块对 API 变更要求的四项产物是一起改动的:OpenAPI 契约、路由映射、SurfaceRegistry、以及带重新生成 sha256 的 parity capture。生成的 WebShell 类型确实是生成器产物而非手改 —— 我通过与其兄弟项 webShellExportSession 对比核实:后者源 JSON 的响应顺序是 401, 404, 403, 413, 409,而生成文件排序为 400, 401, 403, 404, 409, 413;新条目呈现完全相同的重排。没有 V2 migration,没有递增 schema 版本。空值检查按模块的库复用规则使用了 StringUtils。AgentStateStore 只有一个实现类并带 @Override 实现新方法,因此新增接口方法不会破坏第二个实现。

两条非阻断观察:

  • commandTransaction 为一行数据读了两次 journal(先带 revision 界的 sizes 查询,再不带界的 findTransactionByCommand,然后交叉核对)。这与 transactions() 既有的两趟风格一致,且交叉核对确实能捕获两次读取之间发生变化的行,所以我不建议改 —— 只是说明这次额外往返是刻意的,不是疏漏。
  • 两个新内部接口每次请求都要付两次 restore(),而 restoreHead 可能读取一条 activation journal 行并做 SHA-256。这大约使一次调用的固定开销翻倍,而这个接口的全部目的正是"便宜"。作为安全取舍是可以的,但如果它们变成热点,值得知道。

WebShell 路由选用 Capability.ITEM_LIST 是策略判断而非技术判断 —— /transcript/query 用的是 TRANSCRIPT_QUERY,而公开 item 列表已经在用 ITEM_LIST。由于本路由返回的是已发布快照 Item 而非 transcript 事件,ITEM_LIST 看起来更贴切,但只授予其中之一的部署会看到差异。

(时序图与文件清单见上文英文部分,此处不重复。)

测试证据

本次是本地调用,并且按照静态审查规则,我没有构建、运行或执行本 PR 的任何内容 —— 没有 Maven、没有 vitest、没有启动服务。以下内容全部是通过 API 读取的、34619060 这个提交上本 PR 自己的 CI。该 head 上没有失败项,但最关键的套件尚未跑完,因此目前没有任何一项算作通过。

该提交上 54 个 check:15 成功、30 跳过、8 进行中、1 排队、0 失败。成功项是真实的,但都属外围 —— lint、Flyway 版本唯一性检查、Java 11 daemon E2E、tier 选择器,以及机器人编排类 job。真正承重的仍在运行。

(CI 表格见上文机器可读区域。)

真正要紧的缺口:该 head 上还不存在 MySQL 证据。 被跳过的 MySQL 环节不是疏忽也不是基础设施噪音 —— 这是 gate 分级机制按设计工作。managed-agent-gate.yml 对 pull_request 事件选择 tier=fast,只在该 head 的首次批准时选择 tier=full,并报告"在 pull request 上,完整套件会在该 head 的首次批准时运行"。因此 ManagedSessionQueryMySqlIT 与新增的 ManagedSchemaSessionMySqlIT 断言尚未在真实 MySQL 8.4 上针对 34619060 执行过。yiliang114 于 11:31:57Z 批准了这个确切的 head,触发了 full tier 运行 40866111821 —— 当前 pending,尚无 job 启动。另外作者派发了 SDK Java 运行 40864187528(workflow_dispatch),同样 pending 且 job 数为 0。

这一点需要说清楚,因为本模块自己的规则指出仅靠 H2 测试不能确立 MySQL 行为,而设计文档写着"MySQL 测试执行同一 journal 查询及最近快照读取"。该主张目前未经验证 —— 测试已写好且结构正确(ManagedSessionQueryMySqlIT extends ManagedSessionQueryTest,只覆写数据源),但在此处尚未运行。反向分页 SQL 是最可能在两种引擎间表现不同的部分:带 limit + 1 参数的 ORDER BY journal_revision DESC LIMIT ?,以及 ma_session_journal_tx 的缺口遍历。另需注意,被取代的 ce2ccccb head 上那次完整运行 40850365742 已变为 cancelled 且 job 数为 0 —— 作者在 PR 正文里明确说明了这点,那不算通过。

作者自报的结果 —— TypeScript 构建/类型检查通过、ce2ccccb head 上客户端测试 51/51、以及一次另行授权的 H2 预览启动 —— 是作者在更早提交上的主张,不是我重新运行的证据,也不覆盖当前 head 的 Java 行为。

沙箱验证可以补齐剩余缺口:@qwen-code /verify —— 反向 journal 分页与最近快照读取在真实 MySQL 8.4 上是否与 H2 表现一致,从 diff 无法观察,而本该证明这一点的两个 MySQL IT 在 fast tier 被跳过、在 full tier 仍 pending。作者拥有写权限,因此无需 sponsored run。/tmux 在此不是合适的通道:本 PR 不改动任何 TUI 界面、也不接入任何 UI 消费者,没有真实用户可驱动的对象。

真实场景测试:N/A。 没有用户可见的变化 —— 未触及任何 UI 文件,既有 transcript 与导出流程在构造上保持不变(正向 page() 重载保留原有签名与行为,且所有既有调用路径上 backward 均为 false),三个新接口都没有调用方。要驱动它们就需要构建并运行本 PR 的 Java 服务,而这在原则上被静态审查规则禁止。此处声明 N/A,而不是用作者的 H2 预览来替代。

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

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

@qwen-code-review-bot

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

Copy link
Copy Markdown
Collaborator

Confidence: 4/5 — I'd merge this. The code is clean, the tests are load-bearing rather than decorative, and it answers the previous round the right way. Held back from 5 only because nothing has actually gone green on this head yet and the MySQL evidence is still pending — both CI-state reservations, not code reservations.

Going back to my independent proposal: the PR matches it and beats it. I would have written roughly this, minus the compacted-prefix refusal, and that refusal turns out to be the load-bearing decision — it is what makes the backward gap check's "revision 1 must still exist" assumption safe instead of accidental. When a diff is smaller than my own baseline plan and more correct than it, that's the answer to "would I curse the author in six months."

The scope reduction is the story here. My last pass deferred a 264-file, ~24.9k-production-line change because nobody could read it — GitHub wouldn't even serve the diff. This is 23 files and 239 production lines, and it kept every part that actually mattered: the bounded reads, the authenticated pinned cursor, the authorization reuse, the H2 and MySQL coverage, the contract/registry/parity/generated-types synchronization. Whatever was cut was not load-bearing. That's how a deferred PR is supposed to come back.

Am I approving because it's genuinely good, or because I ran out of reasons to say no? Genuinely good — but let me name the two things I'd still want a human to weigh, neither of which I think blocks:

The three new endpoints have no callers. getRecentTranscriptItems is referenced only by its own test, /transcript/items/query has no UI adoption, and neither internal route has a consumer. I verified this against the complete file list and the base tree rather than taking the description's word. On a strict reading of "nothing speculative," a public WebShell contract route that nothing calls is surface committed ahead of need — and #13184 stays open after this merges, since the PR explicitly disclaims bounded UI history and bounded RSS. My read is that this is a legitimate first slice of a split the gate itself asked for, and the author was upfront about what's deferred. But it's the author's and maintainer's sequencing call, not mine, so I've put it as a question in Stage 1 rather than a finding here.

The MySQL claim is written but not yet executed. The module's own rules say H2 alone doesn't establish MySQL behavior, and the backward-paging SQL (ORDER BY journal_revision DESC LIMIT ? with a limit + 1 bind, plus the journal gap walk) is exactly the kind of thing that can differ between engines. ManagedSessionQueryMySqlIT is correctly structured and will run on the full tier that yiliang114's approval just triggered — it simply hasn't yet.

On that approval: it is on this exact head, and it is a different vote from mine. main requires two approvals, so a maintainer's sign-off isn't a substitute for this gate's, and I'm not treating it as one.

Verdict: approve — but not in this run. Four pull_request workflow runs are still incomplete on 34619060 (Qwen Code CI, the fast-tier Managed Agent gate, tui-parity, Web-shell Visuals), and the full-tier gate carrying the MySQL legs has no jobs started. Approving now would attest to a result that doesn't exist. So approval is deferred until CI lands green on this commit, and I've left the marker below for the finalize workflow to act on. A useful side effect: the full-tier run's checks land on the same head SHA, so the deferred approval won't fire until the MySQL ITs have actually reported — the gap I flagged above closes itself before the approval does.

No CHANGES_REQUESTED, no escalation. The Stage 0 escalation from my previous pass is withdrawn and I've updated that comment to say so rather than leaving a stale "deferring to a maintainer" standing on a 239-line diff.

中文说明

Confidence: 4/5 —— 我会合并。代码干净,测试是承重的而不是装饰性的,而且它用正确的方式回应了上一轮意见。没给到 5 分只因为该 head 上目前还没有任何东西真正变绿、MySQL 证据仍待定 —— 这两点都是 CI 状态层面的保留,不是代码层面的保留。

回到我自己的独立方案:本 PR 与之一致并且更好。我大概也会写成这样,但不会想到拒绝已压缩前缀这一条,而那恰恰是承重的决定 —— 正是它让反向缺口检查中"revision 1 必须仍然存在"这个假设是安全的,而不是碰巧成立。当一份 diff 比我自己的基线方案更小、又比它更正确时,这就是"六个月后我会不会抱怨作者"的答案。

规模收缩才是这里的主线。上一轮我把一个 264 文件、约 24.9k 生产行的改动转交维护者,因为没人读得完 —— GitHub 甚至拒绝提供 diff。现在是 23 个文件、239 行生产逻辑,并且保留了所有真正要紧的部分:有界读取、已认证且钉住快照的游标、授权复用、H2 与 MySQL 覆盖,以及契约/registry/parity/生成类型的同步。被砍掉的部分都不是承重的。一个被转交的 PR 就应该这样回来。

我是因为它确实好才批准,还是因为说不出反对理由了?确实好 —— 但仍有两点我希望由人来权衡,我认为都不构成阻断:

三个新接口没有调用方。 getRecentTranscriptItems 只被它自己的测试引用,/transcript/items/query 没有 UI 接入,两个内部路由也没有消费者。这一点我是对照完整文件清单和主干代码核实的,不是照搬描述。严格按"不做投机性设计"来读,一个无人调用的公开 WebShell 契约路由,就是先于需求提交的接口面 —— 而且本 PR 合并后 #13184 仍然是 open 的,因为 PR 明确声明不宣称 UI 全历史与 RSS 有界。我的判断是:这是 gate 自己要求的拆分中合理的第一片,作者对延期内容也说明得很清楚。但这是作者与维护者的排序判断,不是我的,所以我把它作为疑问写在 Stage 1,而不是在这里作为发现。

MySQL 主张已写好但尚未执行。 本模块自己的规则指出仅靠 H2 不能确立 MySQL 行为,而反向分页 SQL(带 limit + 1 绑定参数的 ORDER BY journal_revision DESC LIMIT ?,加上 journal 缺口遍历)正是可能在两种引擎间表现不同的那类东西。ManagedSessionQueryMySqlIT 结构正确,并将在 yiliang114 的批准刚刚触发的 full tier 上运行 —— 只是还没跑。

关于那次批准:它落在这个确切的 head 上,而且是与我的票不同的另一票。main 要求两个批准,所以维护者的签核不能替代本 gate 的签核,我也没有把它当作替代。

结论:批准 —— 但不在本次运行中批准。 34619060 上仍有四个 pull_request workflow 运行未完成(Qwen Code CI、fast tier 的 Managed Agent gate、tui-parity、Web-shell Visuals),而承载 MySQL 环节的 full tier gate 尚无 job 启动。现在批准等于为一个还不存在的结果背书。因此批准推迟到 CI 在该提交上全绿之后,我已在下方留下标记供 finalize workflow 执行。一个有用的副作用是:full tier 运行的 check 落在同一个 head SHA 上,所以延迟的批准在 MySQL IT 真正报告之前不会触发 —— 我上面标出的缺口会在批准发生之前自行闭合。

不提交 CHANGES_REQUESTED,不做升级。上一轮的 Stage 0 升级已撤回,我也更新了对应评论以说明此事,而不是让一条过时的"转交维护者"继续挂在一份 239 行的 diff 上。

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

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

@qwen-code-review-bot

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

Copy link
Copy Markdown
Collaborator

✅ Escalation withdrawn — this comment is obsolete, kept for thread continuity.

I wrote this against 7a120ead, when the PR was 264 files and ~24,931 production logic lines spanning four packages. Every one of the three reasons I gave for deferring has been resolved by the two commits since:

  1. "~3.7k lines of the largest production files are unreadable through the API" — those files are no longer in the diff. The PR is now 23 files, the full diff is served normally (1,062 lines), and I read all of it, including the whole of recentItems and recentTransactions.
  2. "The central claim is unmeasured" — the residency claim was dropped along with the authority window, history cache and derived tables. What remains is a bounded-read claim, and it is measured: ManagedSnapshotNumericPagingTest asserts bodyReads == 2 at both 1,000 and 10,000 items, so the bound is pinned by a test rather than asserted in prose.
  3. "The eventsInSequenceRange → iterateEvents sweep is separable" — that sweep is gone from this PR entirely.

The Stage 0 escalation is likewise withdrawn: production logic went from ~24,931 lines to 239, well under the 500-line maintainer-awareness threshold, so there is no longer a scale question for a maintainer to own. The author also holds admin on this repo, which exempts maintainer-authored work from the two-tier core gate in any case.

The two "specific asks before merge" are both void — the residency checks no longer exist in this scope, and HostedMcpSession.managementStatus is no longer touched.

Current status is in the Stage 3 comment above, which now reads: confidence 4/5, approve, deferred until CI lands green on 34619060. yiliang114 has approved this head. The one live question I'd still want answered is the unused-surface one in Stage 1 — the three new endpoints have no callers yet — and that is a sequencing question for the author and maintainer, not a blocker.

@doudouOUC the scope cut was the right call and it made this reviewable. Thank you for taking the earlier round seriously rather than defending the large version.

中文说明

✅ 升级已撤回 —— 本评论已过时,保留仅为保持讨论串连贯。

我写这条评论时针对的是 7a120ead,当时本 PR 是 264 个文件、约 24,931 行生产逻辑,横跨四个 package。我给出的三条转交理由,都已被此后的两个提交解决:

  1. "最大那几个生产文件中约 3.7k 行通过 API 读不到" —— 那些文件已不在 diff 中。本 PR 现在是 23 个文件,完整 diff 可正常提供(1,062 行),我全部读完了,包括 recentItems 与 recentTransactions 的完整实现。
  2. "核心结论没有测量值" —— residency 结论已连同 authority 窗口、历史缓存和派生表一起被移出。剩下的是一个有界读取结论,而且它确实有测量:ManagedSnapshotNumericPagingTest 在 1,000 和 10,000 个 Item 两种规模下都断言 bodyReads == 2,所以这个上界是被测试钉住的,而不是在正文里声称的。
  3. "eventsInSequenceRange → iterateEvents 这批迁移是可拆分的" —— 这批迁移已完全不在本 PR 中。

Stage 0 的规模升级同样撤回:生产逻辑从约 24,931 行降到 239 行,远低于 500 行的"需维护者关注"阈值,因此已不存在需要维护者来定的规模问题。作者在本仓库也持有 admin 权限,而维护者自己提交的改动本就免除于两层核心 gate。

合并前那两条"具体请求"均已失效 —— residency 检查在当前范围内已不存在,HostedMcpSession.managementStatus 也不再被触及。

当前状态见上方的 Stage 3 评论,其结论为:confidence 4/5,批准,推迟到 CI 在 34619060 上全绿之后。yiliang114 已批准该 head。我仍希望得到回答的一个问题是 Stage 1 里的接口面未被使用一事 —— 三个新接口目前都没有调用方 —— 那是作者与维护者之间的排序问题,不是阻断项。

@doudouOUC 收缩范围是正确的决定,也正是它让本 PR 变得可审查。感谢你认真对待上一轮意见,而不是为那个较大的版本辩护。

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

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

@wenshao

wenshao commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator

PR #15839 — Verified: 7a120ead697409c0d62d315bf2295c28d1294dbd

Verdict: merge-ready — 154/154 executed assertions passed, 0 failed. The central claim holds under A/B: completed history stops accumulating in the resident authority at the 1,024-event bound, while the base arm grows linearly to 8,000. Final-head Java/MySQL qualification is still owned by CI (lanes queued at report time).

中文摘要

结论:merge-ready(154/154 断言通过,0 失败)。

  • 中心主张(A/B 实测):用真实构建的 core dist 驱动 authority + JSONL journal。base 在 2,000/8,000 事件后常驻事件数分别为 2,000/8,000(冷重开亦同);head 在 2,000 事件(活态与冷重开)和 8,000 事件(活态)均恒为 1,024,getter 同时给出 eventBytes=291,771、cacheEntries=2,048、cacheBytes=1,229,321。见「Central claim and A/B」表与图 01-residency-ab.png。
  • 历史查询与失败关闭:真实产物写入 64 条完成通知后,恢复投影的常驻通知数组为 0;最早/最新身份均可从历史查到,真正不存在的身份返回 false;删掉 transcript 后查询抛错而非返回 false。
  • 变异矩阵 4/4 全部被杀:紧凑续租快路径(删除后 100 次续租变成 102 次提交)、流式恢复采用 scan 的激活、释放前结算未决续租、事件尾部 1,024 上限(阳性对照 expected 1030 to be 1024)。两条基线在隔离运行下全绿(6/6、1/1)。见 02-mutation-matrix.png。
  • 门禁:authority 套件 100/100,managed reader 套件 18/18(首次与重负载并发时出现 2 个超时,隔离重跑 76.5 s 全绿,属环境负载)。
  • 未覆盖:8,000 事件的冷重开(预算内未跑完,2,000 冷重开已实测 1,024)、真实 Java/MySQL HTTP 路径(Managed history residency 两条 lane 在发布时仍 queued)、Legacy 平台分支、Windows。
  • 非阻塞观察:在 canonical JSONL 中间翻转一个 payload 字节后查询仍作答——该格式没有逐行校验和(PR 明确保留 journal 格式);派生视图(SQL history facts)的来源校验由 Java 测试与 CI 覆盖,本项不在其断言范围。

Central claim and A/B

Claim: completed Managed history is queried from fixed, captured views instead of being retained in resident arrays; recovery and cold reopen stay bounded.

A/B instrument: ab-residency.mjs imports each arm's real packages/core/dist, opens the real LocalManagedSessionAuthority over a LocalJsonlManagedSessionJournalStore, appends committed execution events in batches of 32, then releases the writer lease and reopens cold. Expectations are passed by the runner, never read from the code under test. Base and head share the same dependency tree (the PR touches neither package.json nor pnpm-lock.yaml), and readlink -f on each arm's node_modules/@qwen-code/qwen-code-core points into that arm.

arm events phase committed resident bound result
base 2000 live 2000 2000 2000 PASS
base 2000 cold 2000 2000 2000 PASS
head 2000 live 2000 1024 1024 PASS
head 2000 cold 2000 1024 1024 PASS
base 8000 live 8000 8000 8000 PASS
base 8000 cold 8000 8000 8000 PASS
head 8000 live 8000 1024 1024 PASS
head 8000 cold — not run — not run

Head residency getter at 2,000 events: {"events":1024,"eventBytes":291771,"cacheEntries":2048,"cacheBytes":1229321}.

Witness: 01-residency-ab.png (the table as printed by show-ab.mjs, parsed from the raw arm logs).

Secondary claim probes (p2-history-failclosed.mjs, real head dist): a Managed session with 64 completed notification identities restores with backgroundNotificationTaskIds.length === 0; the oldest and newest identities answer true from history, an absent identity answers false, and removing the transcript makes the query throw. This is the same code path the CLI pins in Session.test.ts ("queries canonical notification history after the positive cache has evicted an old task", "keeps every primed Legacy notification identity without a Managed cache limit").

Mutation matrix

Each row mutates exactly one anchor in the head tree (mutate.py asserts a unique match), runs the named suite, then restores with git checkout HEAD -- and re-checks cleanliness. Witness: 02-mutation-matrix.png.

row guard reverted result named failing assertion
m1 compact renewal fast path (journal.renewActivation) killed expected 102 to be 2 (commits after 100 renewals)
m2 authority.activation = scan.activation after streaming recovery killed restored currentActivation deep-equal mismatch
m3 release settles an in-flight compact renewal first killed expected 1793263789600 to be greater than 1793263830336 (expiry not extended)
m4 resident event tail cap 1,024 → 1,030 (positive control) killed expected 1030 to be 1024

Baselines: the targeted HTTP renewal test passes 1/1 unchanged; the hook-scale suite passes 6/6 when run alone. (An earlier hook-scale baseline run overlapped the 8,000-event cold replay and produced two 120 s/15 s timeouts followed by teardown ENOTEMPTY; the isolated rerun is the qualifying measurement.)

Findings

No blocking findings. Two boundaries recorded rather than scored:

  • Canonical JSONL payload corruption is not detected. Flipping one byte in the middle of the .jsonl transcript left the reader answering from the corrupted file instead of throwing. The preserved journal format carries no per-line checksum, so this is not one of the derived views the PR adds source validation to; the SQL history facts (record_digest, canonical transaction checks) are the validated path. Recorded as INFO payloadBitFlipRead=ANSWERED in p2-head.log.
  • The 8,000-event cold reopen was stopped at the budget boundary. Its live-residency row is measured (1,024); the 2,000-event cold reopen (1,024) covers the same replay path.

Review input that landed during the round

The triage bot posted stages 1–3 while this round ran (head unchanged at 7a120ead). It found no correctness bug and deferred to a maintainer on size (~24.9k production logic lines). Its own "Not verified" section names exactly the gap this round closes: the authority residency window and the absent 10k/100k measurement. Two of its five non-blocking concerns sit on the changed surface and were not re-measured here:

  • HostedMcpSession.managementStatus may rescan full committed history per configuration entry (and dereferences find's possibly-undefined result); the shape predates this PR but now sits on an async path.
  • Session.ts duplicates the managed/Legacy dispatch at three sites and constructs a SessionTranscriptReader per managed notification enqueue.

Both are efficiency/duplication questions, not correctness claims; they are recorded here rather than scored.

Not covered

  • Java/MySQL real HTTP history path, Managed history residency / h2 and / mysql, MySQL ITs, and the Hosted/CSI/Automation/Monitor fault gates: CI lanes were still queued on this head when the round ended (SDK Java run 40841759553). No JVM/Maven execution was performed locally.
  • The 8,000-event cold reopen (see above); base cold at 8,000 is measured.
  • Daemon Legacy platform branches beyond the pinned TypeScript controls; Windows.
  • Full Session.test.ts (CLI) execution: its CLI prerequisites (generated git-commit.ts, rebuilt workspace dists) were not prepared in the rig, so the notification-path claims are evidenced by the core reader probe plus the committed tests, not by running that file.

Methodology

Rigs: two detached worktrees under tmp/pr15839-rig/{base,head} (61b7fdb1 / 7a120ead), each seeded with hardlinked node_modules from the main checkout; the PR changes neither dependency manifest, so the dependency tree is identical and the A/B isolates code. Each arm's core dist was built from its own tree. A/B expectations come from the runner; probes import the built dist and drive real filesystem journals, real readers and the real authority. Raw logs, harness scripts and mutation anchors are in tmp/pr15839-verify-20261029-162217/. The head tree was restored and verified clean after every mutation row; both arms' temp fixtures were removed.

Evidence

residency A/B

mutation matrix

Replace the broad authority and recovery changes with recent published Item pages and bounded canonical journal queries. Preserve existing execution, Legacy, schema and CSI behavior.

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
@doudouOUC doudouOUC changed the title feat(managed): Bound SQL session history and recovery feat(managed): Add bounded SQL history queries Oct 29, 2026
@doudouOUC

Copy link
Copy Markdown
Collaborator Author

Scope update pushed in ce2ccccb718c2e47dc06df17f83e84ff6dc94a74 at the author's requested boundary.

Final change Result
Recent published messages Bounded Item page + signed backward cursor; explicit snapshot coverage
Necessary historical reads Existing SQL journal reverse pages and exact command lookup; existing current-state APIs reused
Removed from final diff Authority/cache windows, derived history tables/backfill, streaming full recovery, broad Core/CLI/CSI consumer migration
Size 264 → 23 files; +29,561 → +751 lines; production +237/-2
Verification Build/typecheck, 51/51 client tests, scoped style/codegen and two root/two independent static clean passes; Java/H2/MySQL/HTTP pending CI

Thank you for the independent verification of 7a120ead. Its 154 executed assertions and residency A/B remain valuable evidence for that superseded broad source; those optimizations are intentionally outside the new diff and are not current qualification. The original verification comment was updated in place with the current report and its prior body preserved verbatim. No new review thread was resolved; 0 total / 0 unresolved. Draft status is preserved.


按作者最新范围要求推送 ce2ccccb718c2e47dc06df17f83e84ff6dc94a74:只保留最近已发布消息 Item 分页、签名反向游标及覆盖位置,以及现有 SQL journal 最近事务/精确命令读取;既有当前状态接口继续复用。移出 authority/缓存窗口、派生历史表/补建、全历史流式恢复及 Core/CLI/CSI 全链路消费者迁移。

264 → 23 文件,新增 29,561 → 751 行;生产逻辑 +237/-2。 build/typecheck、51/51 客户端用例、格式/codegen 与根/独立各两轮静态审阅通过。Java/H2/MySQL/HTTP 仍待准确最终 head CI,本地预算未重置且执行 0。消息快照可能落后实时状态,UI 流程保持不变。

感谢旧 7a120ead 的独立验证;其 154 断言及 A/B 只对应旧较宽来源,不转作本次资格。原验证评论已原地同步当前报告并逐字保留旧正文。线程 0 total / 0 unresolved,本轮解决 0,保持 Draft。

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
@doudouOUC
doudouOUC marked this pull request as ready for review October 29, 2026 11:17
@doudouOUC

Copy link
Copy Markdown
Collaborator Author

Fixed in 34619060eb26fb194fc059cf32475a5ce223b4d1.

Item Action and evidence
Lint job123367693818 and the separate contract-version status Confirmed exact ce2 failure: the new public API retained version1.95.0. Only one OpenAPI line changed to1.96.0; no query, SQL, schema, workflow, checker or runtime logic changed.
Verification The actual Node gate was reproduced RED then passed GREEN against exact captured main1.95.0; independent test-engineer verification, inverse byte comparison, formatting and unchanged generated types passed. Prior ce2 build/typecheck/51 client cases apply only to unchanged inputs. Java preparation/execution0 this round; both allowances remain CLOSED.
Final-head CI SDK Java40864187528 dispatched once; exact metadata head, pending/0jobs, actual checkout and Java/H2/MySQL/API/admission gates unverified. Old ce2 full40850365742 became cancelled/0jobs, not a pass; no manual cancel was issued.
Scope and preview Managed H2/MySQL query-only scope retained. The user's ce2 H2 preview on5196 and its data remain untouched; it is not new-head acceptance. Original report6491674130 was updated in place with all previous text preserved verbatim.
Review state and dedup No formal human approval or CHANGES_REQUESTED, 0 total/0 unresolved threads, 0 replies or resolutions this round. The initial poll exposed historical7a reviews already addressed by summary6493145352; no duplicate replies. GitHub records doudouOUC marking Ready at2026-10-29T11:17:32Z; this automation did not switch Draft/Ready.

已在 34619060eb26fb194fc059cf32475a5ce223b4d1 修复。

事项 处理及证据
Lint job123367693818及独立契约版本status 已确认准确ce2失败:新增公开API后仍为1.95.0。本轮只将OpenAPI一行升至1.96.0,未改查询、SQL、schema、workflow、checker或运行逻辑。
验证 对照准确捕获的main1.95.0,实际Node门禁先RED后GREEN;独立test-engineer验证、反向逐字还原、格式及生成类型不变检查通过。此前ce2的build/typecheck/51客户端用例仅按未变输入复用。本轮Java准备执行0,两项额度均保持CLOSED。
最终head CI SDK Java40864187528仅派发一次,metadata head准确,pending/0jobs,实际checkout及Java/H2/MySQL/API/准入待验收。旧ce2完整40850365742变为cancelled/0jobs,不算通过,本自动化没有手动取消。
范围及预览 保持Managed H2/MySQL查询范围。5196的ce2 H2预览及数据未动,不算新head验收。原独立报告6491674130原地更新,全部旧正文逐字保留。
评审状态与去重 无正式人工批准或CHANGES_REQUESTED;线程0 total/0 unresolved,本轮0回复/解决。首次poll读到的旧7a评审已由summary6493145352处理,不重复回复。GitHub记录doudouOUC于2026-10-29T11:17:32Z切为Ready,本自动化未切换Draft/Ready。

@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.

LGTM. The current head 34619060 adds three bounded SQL history query surfaces (recent transcript-items page, recent journal-transactions page, exact command-identity lookup) on existing H2/MySQL tables and authorization. Verified:

  • Route contracts: new POST /transcript/items/query (WebShell, v2 backward cursors) and internal GET /transactions:recent + /transactions:lookup reuse existing schemas (WebShellExportRequest/WebShellExportPage, writer-token header, READ_COMMITTED isolation) and enforce non-overlapping v2-forward / v1-backward cursor separation.
  • Transactional integrity: recentTransactions validates consecutive revision monotonicity, byte-length bounds, digest checks, workspace ownership, and a read-grant refresh before return. commandTransaction enforces exact operation/commandId identity, single-row matching, and workspace scope.
  • Snapshot isolation: recentItems pins a specific published snapshot (root id/version/projection), refuses tampered/expired/wrong-version cursors, and returns the original snapshot even after a newer projection is published.
  • Test coverage: backward ordering across physical pages and sequence ties, cursor direction/tampering, fixed snapshots, byte and revision bounds, exact command reads, authorization, replaced-writer refusal, MySQL/H2 parity, surface registry, capability-parity capture, and generated TypeScript client tests — all pass locally per author attestation.
  • Compatibility: no schema migration, history deletion, replay-floor advance, writer renewal, Legacy or forward-export behavior change.

No P0/P1 findings. Design docs (EN + CN) present and synchronized; OpenAPI version advanced to 1.96.0 with generated client types byte-identical. Pending CI (Java lanes, Lint, Test) is not a code finding.

@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.

Approving at 34619060eb26fb194fc059cf32475a5ce223b4d1.

Critical-only scan found no blocking defect. This adds read APIs across a tenant/actor authorization boundary, so I spent the budget on the three places a Critical would live: cursor integrity, the authorization chain on each new route, and the bounds and journal-integrity checks on the new queries. All three hold.

Cursors are version-bound, scope-bound and integrity-checked

The backward page reuses the existing forward cursor machinery but cannot be confused with it. ManagedSnapshotStore.page gains a backward flag, and the cursor version is backward ? 2 : 1 on both the encode and the decode side, with the decode check tightened to position.version() != (backward ? 2 : 1). So a forward export cursor presented to the new route is rejected, and a backward cursor cannot be replayed into the existing forward export — which is what keeps the claim that existing forward cursors retain their behaviour true rather than merely intended.

The scope check is retained on the new path: position.scope() must equal ManagedSessionStore.sessionScopeKey(tenant, session), so a cursor minted for one tenant/session cannot page another. verifyCursor(cursor, manifest) is still invoked for any non-blank cursor before recentItems runs, so tampering and expiry are caught by the pre-existing mechanism rather than by anything new. The re-encoded next cursor carries position.expires() forward, so paging does not silently extend a cursor's lifetime.

recentItems bounds its inputs before walking: page < -1 || page >= manifest.pages() || offset < -1, plus page < 0 || offset < 0 whenever a cursor was supplied, all throw invalidCursor(), and offset > rows.size() throws inside the loop. lease.check() runs per page and again before returning, so a lost lease interrupts the walk. The next-cursor offset arithmetic is right — it stores offset + 1 after the loop decremented to the item it did not take, so the following page resumes at exactly that item — and Collections.reverse restores chronological order after the backward walk, matching the documented contract.

Both authorization layers are enforced on the new routes

ManagedAgentService.recentTranscriptItems opens with requireReadableSession(tenantId, actorId, sessionId) before touching the store, which is the same actor-level read gate the sibling transcript(...) uses; ManagedAgentStore.findRecentSnapshotPage then calls requireSession(tenantId, sessionId). So the WebShell route is scoped at both the service and the store, and the new AgentStateStore interface method keeps the two implementations honest at compile time.

The two ManagedSessionStoreController routes follow the existing transactions route's shape exactly: TenantContext from the framework, the writer token from WRITER_TOKEN_HEADER, and workspaceId passed through to the store. Both store methods call historyRevision(...) first, which invokes restore(tenantId, workspaceId, sessionId, writerToken) — the existing writer-credential validation — and then verifies that the row at the resolved through revision actually belongs to the requested workspaceId, throwing journalCorrupt() otherwise. restore is called again after the read. requireTransactionWorkspace(row, workspaceId) is then applied per returned row, so a row from another workspace cannot ride out in a page.

Bounds and journal integrity fail closed

historyRevision refuses a compacted prefix with ERROR_RECOVERY_CONFLICT rather than answering from a history that is no longer retained, and validates throughRevision against 0, MAX_SAFE_COUNTER and head.journalRevision(). recentTransactions bounds limit to 1..100 and requires beforeRevision within [1, through], then derives upper = beforeRevision - 1, which is what makes the bound exclusive so newer commits cannot leak into a later page.

The candidate scan asserts contiguity — candidate.journalRevision() != expected-- against a counter starting at upper — so a gap in the revision sequence is journalCorrupt(), not a short page. Byte lengths are bounded to [1, MAX_TRANSACTION_BYTES], and the accumulation loop breaks at selected == limit or when adding another row would exceed the byte cap with selected > 0, so at least one row always returns when one exists. The completeness check reads with the correct precedence: candidates.isEmpty() || (candidates.size() < limit + 1 && candidates.getLast().journalRevision() != 1) throws, i.e. a partial page is only acceptable when it bottoms out at revision 1.

The full-row query re-fetches with LIMIT selected and cross-checks each row's journalRevision and byteLength against the candidate probe, so a concurrent change between the two reads under READ_COMMITTED is detected rather than returned. more and next are computed from transactions.getLast() before the reverse, which is the correct oldest-selected revision for an exclusive lower bound.

commandTransaction validates operation and commandId for blankness and length, hashes to command_key_hash for a parameterized lookup, requires exactly one match, re-verifies the fetched row's revision and byte length against the size probe, applies the workspace check, and then re-compares the row's operation and commandId against the request — so a hash collision or a probe/row mismatch is a corruption error rather than a wrong answer. An absent identity returns a null transaction alongside through, which is the documented "not found" shape rather than an error.

What I did not read, and the state of the evidence

Not read: ManagedSessionStoreModels.java (+7), the OpenAPI document (+50/−1), the generated web-shell client (+50) and its thin method (+7), the surface-registry and capability-parity pins, the four new or changed test files (+317) and the two design documents. I read every production file that makes an authorization, integrity or bounds decision; the unread set is record definitions, contract and generated artifacts, parity pins and tests, whose failure mode is a red gate rather than a shipped defect.

CI at this head is 13 pass, 0 fail, 9 pending, 23 skipping. No failing check. The pending set includes SDK Java (fast) / ubuntu-latest / Java 21 and Test (ubuntu-latest, Node 22.x), which are the lanes that would execute the new Java suites and the web-shell client tests, so neither has green executed evidence at this exact commit yet. I did not poll them, and pending checks do not on their own hold a verdict. Two things bound that risk: the substantive Java and TypeScript work landed in the parent commit, where the author reports build, typecheck and 51 client tests passing, and this head is a contract-version-only change; and API contract version uniqueness (latest main) now passes here, which is precisely the gate the parent head failed. Build and verify reference distribution, Lint & Static, both Flyway uniqueness lanes and Real daemon E2E are green.

History

There is no blocking finding to reconcile. The PR has zero reviews and zero inline review comments, so there is no ledger and no earlier Critical. One thing is worth recording for the next reader rather than left implicit: @wenshao's merge-ready verification is anchored at 7a120ead6, the original broad commit, and its central A/B claim is about resident authority history being bounded at 1,024 events. The PR was subsequently rescoped — ce2ccccb7 removed the authority windows, history caches, derived history tables and backfill, full-history streaming recovery and the cross-consumer/CSI changes — so that mechanism is no longer in this diff. I am not disputing the verification, which was sound for the head it names; I am noting that it does not cover the current one, and that my approval rests on the reading above rather than on it. The non-blocking observation in that report about canonical JSONL lacking a per-line checksum concerns a journal format this PR explicitly preserves, so it is not a defect introduced here.

The remaining disclosed gap is the author's own and is stated plainly: final-head Java/H2/MySQL/HTTP/contract/admission qualification is still with CI, and the shared Java budget was closed rather than reset. Given that the code paths above are fail-closed by construction and the pending lanes are the ones that would exercise them, I am not treating that as blocking — but it is fair to say the real-database evidence for these queries arrives after this approval rather than before it.

@doudouOUC
doudouOUC merged commit fa7421b into main Oct 29, 2026
82 of 83 checks passed
@doudouOUC
doudouOUC deleted the feat/managed-sql-authority-window branch October 29, 2026 11:34
@qwen-code-review-bot

Copy link
Copy Markdown
Collaborator

Released in v0.26.5.

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.

5 participants