diff --git a/docs/requirements/handoff-HEL-894.json b/docs/requirements/handoff-HEL-894.json new file mode 100644 index 0000000..fbb39ab --- /dev/null +++ b/docs/requirements/handoff-HEL-894.json @@ -0,0 +1,52 @@ +{ + "baseline_version": "1.11", + "read_commit": "ceb0f35418f0d0b28b4e2a359615194db8eb4567", + "task": "HEL-894 返工(总管对 HEL-889 head ceb0f35 独立复审确认的关闭取消两处组合漏洞一次修完):关闭提交阶段被取消仍须保持关闭所有权——semantic.py 原实现 shield(_finish()) 让内部关闭在后台继续,却向外抛取消、释放锁并清 closing,层次被误报可续用,新 tick 把批次领进即将消失的资源(总管实际固定 SDK 屏障复现:取消返回 closing=false/closed=false/client 可用 → 新批 HTTP 已接受未答 → 旧 _finish 关 Qdrant → 不关 Store 也 failed/row_done=0/llm_used=1(QdrantLocal instance is closed);调用方随后关 Store 则晚到 ProgrammingError,重开 pending/row_done=0);取消等锁者不得修改持锁关闭者状态——第二 aclose 等锁即取消,外层 except 清掉第一关闭者的 closing(固定 SDK 复现第一 close 仍 pending 但 signal=false,原 worker 未放行时新批已 done)。零真实调用、零真实嵌入、零下载、不部署、不合并、不改视觉、不碰权威三账、不变真实 cap 与冻结余额、不改运行时/模型/认证", + "requirement_ids": [ + "CG-006", + "CG-008", + "CG-011", + "CG-013", + "CG-014", + "CG-015", + "CG-016", + "CG-018", + "CG-021", + "AM-001", + "AM-002", + "AM-003", + "UX-004", + "UX-006", + "GOV-001", + "GOV-002", + "GOV-003", + "GOV-004", + "GOV-005", + "GOV-006", + "DEL-001" + ], + "deliverable": "在统一候选母线 hel-870-assembly(基于 ceb0f35 正常追加,PR#11 只追加不强推不合并)完成两项修正:1) 两阶段取消语义——aclose 明确排空可撤销阶段(尚未关任何资源:取消什么都不关、closing 复位、层次可续用,保持 HEL-889 行为)与提交不可逆阶段(backend.aclose 已开始:被取消的调用方不清 closing、不放行 tick(半关闭绝不宣称可用)、不释放锁,等待自己启动的层持有关闭任务(_close_task,asyncio.create_task 创建恰一次、存于本层从不丢到后台、重复取消只重新 shield 同一任务)落成后才传播 CancelledError,资源恰关一次;_finish_close 里本层自有执行器 shutdown 改走 asyncio.to_thread,取消方不可能以同步 join 阻塞事件循环;调用方注入执行器仍由调用方持有,与总管脚本口径一致)。2) 所有权最小化——aclose 增加 owns_close 判定:只有真正取得 _aclose_lock 并置位 closing 的调用才可在仍可撤销(无 _close_task)时复位信号;等锁被取消的调用不改变持锁关闭者的任何状态。模块 docstring、aclose docstring、app lifespan 注释同步新协议口径。真崩溃语义不变(保守留账、只发无证明行、不宣称严格一次)。验证:python 3.11.16 venv + requirements.lock 离线 299 pytest 全过(新增 tests/test_rework_hel894.py 5 例,全部屏障驱动真实产品路径:提交阶段取消保持所有权并拒新工作零发送零计费/重复取消仍一次落成/同阶段第二调用等待后幂等返回且第三个等锁者取消不动状态/等锁者取消+持锁排空+新批 tick 拒绝+原 worker 完成组合/排空阶段取消仍可续用续跑),ruff 0 错(src/tests/tools);固定 mem0 2.2.1 确定性替身实跑 tools/verify_close_ownership_hel894.py 16/16(总管两负例同形:F1 提交取消 SDK-only——取消后 closing=true/closed=false/client 可用、取消方等关闭落成才返回、新批 tick 被拒(网关零到达、queued/owner NULL/attempts 0、llm_used=0)、放行后关闭恰一次、重开批次 queued 完好/row_done=0/llm_used=0;F2 +Store 关闭分支同形且无晚到错误;W 等锁者取消——closing 保持、新批 queued、原 worker 放行后 done/row_done=1、一次收尾);总管脚本原件在未改动 ceb0f35 上原样复跑基线与总管独立结果一致(before-ceb0f35.json),修复后原样复跑如实停在其自身前提断言 server.arrived(新协议下 tick 拒新领,前提结构性移除,verbatim-after-fix.log,原负例与基线保留不删);回归 verify_shutdown_queued_hel889.py 12/12、verify_inflight_lifecycle_hel886.py 6/6、verify_semantic_recovery_hel885.py 7/7、verify_mem0_real_hel874.py 12/12、check_release_offline_hel882.py R1–R7 15/15、总管 review_hel882_{partial,extra}.py 原样复跑通过、HEL-889 同形复跑通过;零真实 LLM/真实嵌入/非回环出站,权威三账与冻结余额未写,未部署未合并未交体验地址,不改视觉", + "acceptance": [ + "负例一修复(固定 SDK 实跑,SDK-only 分支):真实 client.close 进入后取消 aclose——取消返回时 closing=true/closed=false/client 可用(不再宣称可续用);新批 tick 被拒:网关零到达、批次 queued/owner NULL/attempts 0、llm_used=0(修复前:closing=false + 新批被领 + QdrantLocal instance is closed + failed/row_done=0/llm_used=1);被取消调用方等层持有关闭任务落成后才传播(closed=true/client 不可用/live_workers=0/close 恰一次);重开批次 queued 完好、row_done=0、llm_used=0", + "负例一加强分支(调用方随后关 Store,单独记录不与 SDK-only 混淆):同上且无任何晚到错误(修复前 ProgrammingError: Cannot operate on a closed database,重开 pending/row_done=0/llm_used=1)", + "负例二修复(固定 SDK 实跑):第一 aclose 排空中、第二等锁即取消——closing 保持置位(修复前被清);新批 tick 被拒仍 queued;原 worker 放行后 done/row_done=1;第一关闭随后一次收尾关库;新批保持 queued", + "所有权完整回归(pytest 屏障驱动真实路径):排空取消可续用(closing 复位、后续批次正常跑完)、提交阶段取消不得半关可用、同阶段第二调用等待后幂等且一次关闭、重复取消仍一次落成、等锁者取消不动状态、并发关闭一次(HEL-889 既有用例保持全绿)、成功关闭拒新任务;原排队取消、活 worker 超时排空、行间续跑、处理中取消单发、全完成零预算收尾全部保持(299 pytest、shutdown-queued 12/12、inflight 6/6、recovery 7/7、contract 12/12、release R1–R7 15/15)", + "总管脚本原件保留:未改动 ceb0f35 上原样复跑基线与总管独立 JSON 一致(before-ceb0f35.json);修复后原样复跑停在其自身前提断言并如实存档(verbatim-after-fix.log);同形重跑断言按新安全协议改写并逐条注明(tools/verify_close_ownership_hel894.py,close-ownership-real-sdk.json 16/16)", + "工程检查:299 pytest(含 5 新例)全过、ruff 0 错(src/tests/tools);本卡未改前端、未重跑前端检查、不冒充历史数字;双目标需求检查 4/4(含本 handoff)" + ], + "deferred": [ + "发布与体验地址:由总管独立复审本 head 后交发布卡按 deploy/hel874-release.md 执行(8360 隔离实例);本卡未部署未合并 PR#11 未交体验地址", + "真实语义激活(CYBERGRIL_SEMANTIC=mem0):需 B 部分预算批准 + 3.11 mem0 栈 wheel 落位;未激活前 stub/FTS 不冒充真实记忆体验", + "A/B/C 执行表数值仍待批准建议:批准前所有 cap 保持 0=拒绝;新增预算由总管统一处理,不作为离线修复阻塞", + "真死进程『严格一次』不在宣称范围:远端无幂等支持时崩溃结果未知,恢复保守留账、只发无证明行(runbook §4 HEL-889/894 段已如实写明)", + "R5 语音 HEL-878/879、R6 天气/素材/完整备份、R7 有条件观察承接不变;视觉仍交原作者,本卡未改视觉;真实体验效果待体验地址交付后由白栖知判断" + ], + "requirement_changes": [], + "verification": [ + "分支 hel-870-assembly 追加提交(最终 head 见交付评论),PR#11 只追加未强推未合并;视觉总监分支未覆盖", + "python 3.11.16 venv + requirements.lock 离线:299 项测试全过(新增 tests/test_rework_hel894.py 5 例,全部屏障驱动真实产品路径,无预置死租约冒充活线程);ruff 0 错(src/tests/tools);本卡未改前端故未重跑前端检查,如实注明", + "固定 mem0 2.2.1 安装(hel857-venv 3.10.12)确定性替身实跑(docs/rework/hel894/):tools/verify_close_ownership_hel894.py 16/16(close-ownership-real-sdk.json,F1/F2/W 为总管两负例同形重跑,断言按新协议改写并注明);总管脚本基线原样复跑与独立结果一致(before-ceb0f35.json);修复后原样复跑停在自身前提断言(verbatim-after-fix.log)", + "回归:verify_shutdown_queued_hel889.py 12/12、verify_inflight_lifecycle_hel886.py 6/6、verify_semantic_recovery_hel885.py 7/7、verify_mem0_real_hel874.py 12/12、check_release_offline_hel882.py R1–R7 15/15、总管 review_hel882_{partial,extra}.py 原样复跑通过、HEL-889 同形复跑(review_hel886_edges_rerun_hel889.py)通过;review_hel885_inflight.py 本轮未重跑,其存档口径不变", + "python3 scripts/check_requirements.py --base-ref origin/main [--handoff docs/requirements/handoff-HEL-894.json] 与 --base-ref origin/agent/agent/de8874a3803b [--handoff …] 四项通过" + ] +} diff --git a/docs/rework/hel894/README.md b/docs/rework/hel894/README.md new file mode 100644 index 0000000..63b8593 --- /dev/null +++ b/docs/rework/hel894/README.md @@ -0,0 +1,70 @@ +# HEL-894 返工证据 · 关闭被取消时的资源所有权 + +总管对 HEL-889 head `ceb0f35418f0d0b28b4e2a359615194db8eb4567` 独立复审 +(`review_hel889_cancel.py`,附件与本目录 `before-ceb0f35.*`)确认的两个组合 +漏洞,在本 head 修复并复验。零真实出站、零真实嵌入、零下载;全部回环 + +确定性 512 维替身(TextEmbedding 构造前安装);未写权威三账、未改冻结余额 +与真实 cap、未部署、未合并、未改视觉。 + +## 修复前基线(本卡在未改动的 ceb0f35 上原样复跑总管脚本) + +`before-ceb0f35.json` 与总管独立结果一致—— + +- finish_cancel(SDK-only 与 +Store 关闭两分支):取消返回时 + closing=false/closed=false/client 可用(宣称可续用)→ 新批被领、HTTP 已 + 接受未答 → 后台旧 `_finish` 关 Qdrant(closed=true、live_workers=1)→ + 不关 Store 也 failed/`Failed to insert any of the 1 extracted memories + into the vector store`/row_done=0/llm_used=1(`QdrantLocal instance is + closed`);+Store 分支晚到 worker 另报 `ProgrammingError: Cannot operate + on a closed database.`,重开 pending/row_done=0/llm_used=1。 +- waiter_cancel:第一关闭排空中、第二等锁即取消后 closing 被清 + (signal=false),原 worker 未放行时新批已 done。 + +## 修复(src/cybergril/memory/semantic.py) + +**两阶段取消语义(HEL-894)**: + +1. **排空阶段(可撤销)**:尚未关任何资源。此阶段取消维持 HEL-889 语义—— + 什么都不关、closing 复位、层次可续用,之后 aclose 再正常收尾。 +2. **提交阶段(不可撤销)**:`backend.aclose()` 一旦开始,资源只能关完。 + 被取消的调用方不清 closing/不放行 tick(半关闭状态绝不宣称可用)、不释放 + 锁,并等待(重复取消也只重新 shield)自己启动的**层持有**关闭任务 + (`_close_task`,创建恰一次、从不丢到后台)落成后才传播 CancelledError; + 资源恰关一次。本层自有执行器的 shutdown 也走 `to_thread`,取消方不可能 + 用同步 join 阻塞事件循环(调用方注入执行器仍由调用方持有,与总管脚本 + 口径一致)。 +3. **所有权最小化**:只有真正取得锁并置位信号的调用(`owns_close`)才可在 + 仍可撤销时复位信号;等锁者被取消不改变持锁关闭者的任何状态(修复负例 + 二)。app lifespan 注释同步为该口径。 + +## 修复后验证 + +- `close-ownership-real-sdk.json`(tools/verify_close_ownership_hel894.py, + 固定 mem0 2.2.1 + 真实 Qdrant/OpenAI client 实跑,总管两负例同形、断言按 + 新协议改写并逐条注明)16/16:F1 提交阶段取消(SDK-only)——取消后 + closing=true/closed=false/client 可用(不再宣称可续用),取消方未返回先 + 等自己启动的关闭落成;新批 tick 被拒(网关零到达、批次 queued/owner + NULL/attempts 0、llm_used=0);放行后关闭恰一次(closed=true、client 不可 + 用、live_workers=0);重开批次 queued 完好、row_done=0、llm_used=0(修复 + 前为 failed/pending + llm_used=1)。F2(+调用方随后关 Store)同形且无任何 + 晚到错误(修复前 ProgrammingError)。W 等锁者取消——closing 保持置位、新 + 批 queued 不被领、原 worker 放行后 done/row_done=1、第一关闭一次收尾。 +- `verbatim-after-fix.log`:总管原脚本**原样**复跑在修复后树上如实停在其自 + 身前提断言 `assert await asyncio.to_thread(server.arrived.wait, 5)`—— + 「取消后新 tick 发出真实 HTTP」这一前提被新协议结构性移除(tick 在 + closing 持有期间拒新领);原负例与基线保留不删。 +- 回归(固定安装实跑):`shutdown-queued-hel889-rerun.json` 12/12(原排队 + 取消/超时排空/行间续跑/排空取消可续用/并发关闭全部保持)、 + `inflight-hel886-rerun.json` 6/6(处理中取消单发/全完成零预算收尾保持)、 + `recovery-hel885-rerun.json` 7/7、`contract-hel874-rerun.json` 12/12、 + `release-offline-hel894.json` R1–R7 15/15、总管 + `review_hel882_{partial,extra}.py` 原样复跑通过 + (`manager-review-*-rerun.json`;extra 内 uv rc=2 为其自身预期负例)、 + `edges-rerun-hel889.json` 同形复跑通过。`review_hel885_inflight.py` 本轮 + 未重跑,其「仍在 2-add 屏障如预期失败」的存档口径(HEL-886/889)不变。 +- 产品测试:python 3.11.16 venv + requirements.lock 离线 **299 pytest 全过** + (新增 tests/test_rework_hel894.py 5 例,全部屏障驱动真实产品路径:提交 + 阶段取消保持所有权并拒新工作/重复取消仍一次落成/同阶段第二调用等待后幂 + 等且等锁者取消不动状态/等锁者取消不改持锁关闭者+tick+原 worker 完成组合/ + 排空阶段取消仍可续用)、ruff 0 错(src/tests/tools)。本卡未改前端,未重 + 跑前端检查,不冒充历史数字。 diff --git a/docs/rework/hel894/before-ceb0f35.json b/docs/rework/hel894/before-ceb0f35.json new file mode 100644 index 0000000..58ba454 --- /dev/null +++ b/docs/rework/hel894/before-ceb0f35.json @@ -0,0 +1,81 @@ +{ + "head": "ceb0f35418f0d0b28b4e2a359615194db8eb4567", + "real_requests": 0, + "real_embeddings": 0, + "finish_cancel_sdk_only": { + "after_cancellation": { + "closing": false, + "closed": false, + "client_usable": true + }, + "hidden_finish": { + "closed": true, + "client_usable": false, + "live_workers": 1, + "batch": { + "state": "pending", + "reason": null, + "owner": "06daaa8f643701f05f768706be2e36a1", + "attempts": 1, + "entry_ids": null + } + }, + "late_worker_error": null, + "persisted": { + "state": "failed", + "reason": "Failed to insert any of the 1 extracted memories into the vector store", + "owner": null, + "attempts": 1, + "entry_ids": null, + "row_done": 0, + "llm_used": 1 + } + }, + "finish_cancel_then_store_close": { + "after_cancellation": { + "closing": false, + "closed": false, + "client_usable": true + }, + "hidden_finish": { + "closed": true, + "client_usable": false, + "live_workers": 1, + "batch": { + "state": "pending", + "reason": null, + "owner": "faa9f8c3c78e33be96ffdb4469bda941", + "attempts": 1, + "entry_ids": null + } + }, + "late_worker_error": "ProgrammingError: Cannot operate on a closed database.", + "persisted": { + "state": "pending", + "reason": null, + "owner": "faa9f8c3c78e33be96ffdb4469bda941", + "attempts": 1, + "entry_ids": null, + "row_done": 0, + "llm_used": 1 + } + }, + "waiter_cancel": { + "active_close_pending": true, + "signal_after_waiter_cancel": false, + "new_batch_before_original_worker_released": { + "state": "done", + "reason": null, + "owner": null, + "attempts": 1, + "entry_ids": "[\"210297a0-b8c2-4b12-ac9c-eeeaa1eb623f\"]" + }, + "original_batch": { + "state": "pending", + "reason": null, + "owner": "86b6785682c351b41c4691168752b058", + "attempts": 1, + "entry_ids": null + } + } +} \ No newline at end of file diff --git a/docs/rework/hel894/before-ceb0f35.log b/docs/rework/hel894/before-ceb0f35.log new file mode 100644 index 0000000..10a09b4 --- /dev/null +++ b/docs/rework/hel894/before-ceb0f35.log @@ -0,0 +1,90 @@ +Failed to load spaCy lemma model: spaCy is not installed. Install it with: pip install mem0ai[nlp] +Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201 +Failed to insert memory 83789ef3-dbc1-486b-aa09-b5a50a16b507: QdrantLocal instance is closed. Please create a new instance. +semantic batch 1 failed: Failed to insert any of the 1 extracted memories into the vector store +Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201 +Failed to insert memory 758c3b89-1564-4908-a125-8262e65da177: QdrantLocal instance is closed. Please create a new instance. +semantic batch 1 failed: Failed to insert any of the 1 extracted memories into the vector store +Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201 +Failed to load spaCy full model: spaCy is not installed. Install it with: pip install mem0ai[nlp] +{ + "head": "ceb0f35418f0d0b28b4e2a359615194db8eb4567", + "real_requests": 0, + "real_embeddings": 0, + "finish_cancel_sdk_only": { + "after_cancellation": { + "closing": false, + "closed": false, + "client_usable": true + }, + "hidden_finish": { + "closed": true, + "client_usable": false, + "live_workers": 1, + "batch": { + "state": "pending", + "reason": null, + "owner": "06daaa8f643701f05f768706be2e36a1", + "attempts": 1, + "entry_ids": null + } + }, + "late_worker_error": null, + "persisted": { + "state": "failed", + "reason": "Failed to insert any of the 1 extracted memories into the vector store", + "owner": null, + "attempts": 1, + "entry_ids": null, + "row_done": 0, + "llm_used": 1 + } + }, + "finish_cancel_then_store_close": { + "after_cancellation": { + "closing": false, + "closed": false, + "client_usable": true + }, + "hidden_finish": { + "closed": true, + "client_usable": false, + "live_workers": 1, + "batch": { + "state": "pending", + "reason": null, + "owner": "faa9f8c3c78e33be96ffdb4469bda941", + "attempts": 1, + "entry_ids": null + } + }, + "late_worker_error": "ProgrammingError: Cannot operate on a closed database.", + "persisted": { + "state": "pending", + "reason": null, + "owner": "faa9f8c3c78e33be96ffdb4469bda941", + "attempts": 1, + "entry_ids": null, + "row_done": 0, + "llm_used": 1 + } + }, + "waiter_cancel": { + "active_close_pending": true, + "signal_after_waiter_cancel": false, + "new_batch_before_original_worker_released": { + "state": "done", + "reason": null, + "owner": null, + "attempts": 1, + "entry_ids": "[\"210297a0-b8c2-4b12-ac9c-eeeaa1eb623f\"]" + }, + "original_batch": { + "state": "pending", + "reason": null, + "owner": "86b6785682c351b41c4691168752b058", + "attempts": 1, + "entry_ids": null + } + } +} diff --git a/docs/rework/hel894/close-ownership-real-sdk.json b/docs/rework/hel894/close-ownership-real-sdk.json new file mode 100644 index 0000000..a291073 --- /dev/null +++ b/docs/rework/hel894/close-ownership-real-sdk.json @@ -0,0 +1,215 @@ +{ + "head": "HEL-894 close ownership under cancellation", + "real_llm_requests": 0, + "real_embeddings": 0, + "boundary": "deterministic 512 vectors, non-loopback forbidden", + "protocol": "drain-phase cancel re-arms; finish-phase cancel keeps markers, refuses ticks, lands the layer-owned close exactly once; lock waiters never touch the owner's state", + "checks": [ + { + "name": "F1 cancelled caller does not return before its close lands", + "ok": true, + "detail": "" + }, + { + "name": "F1 markers stay: closing set, not yet closed, client untouched", + "ok": true, + "detail": "{\"closing\": true, \"closed\": false, \"client_usable\": true}" + }, + { + "name": "F1 tick during closing claims nothing and sends nothing", + "ok": true, + "detail": "{\"gateway_arrived\": false, \"gateway_posts\": 0, \"llm_used\": 0, \"batch\": {\"state\": \"queued\", \"reason\": null, \"owner\": null, \"attempts\": 0, \"entry_ids\": null}}" + }, + { + "name": "F1 layer-owned close lands exactly once, no live workers", + "ok": true, + "detail": "{\"closed\": true, \"client_usable\": false, \"live_workers\": 0, \"close_calls\": 1, \"closing_still_set\": true, \"batch\": {\"state\": \"queued\", \"reason\": null, \"owner\": null, \"attempts\": 0, \"entry_ids\": null}}" + }, + { + "name": "F1 no late error", + "ok": true, + "detail": "None" + }, + { + "name": "F1 reopened batch intact and unbilled", + "ok": true, + "detail": "{\"state\": \"queued\", \"reason\": null, \"owner\": null, \"attempts\": 0, \"entry_ids\": null, \"row_done\": 0, \"llm_used\": 0}" + }, + { + "name": "F2 cancelled caller does not return before its close lands", + "ok": true, + "detail": "" + }, + { + "name": "F2 markers stay: closing set, not yet closed, client untouched", + "ok": true, + "detail": "{\"closing\": true, \"closed\": false, \"client_usable\": true}" + }, + { + "name": "F2 tick during closing claims nothing and sends nothing", + "ok": true, + "detail": "{\"gateway_arrived\": false, \"gateway_posts\": 0, \"llm_used\": 0, \"batch\": {\"state\": \"queued\", \"reason\": null, \"owner\": null, \"attempts\": 0, \"entry_ids\": null}}" + }, + { + "name": "F2 layer-owned close lands exactly once, no live workers", + "ok": true, + "detail": "{\"closed\": true, \"client_usable\": false, \"live_workers\": 0, \"close_calls\": 1, \"closing_still_set\": true, \"batch\": {\"state\": \"queued\", \"reason\": null, \"owner\": null, \"attempts\": 0, \"entry_ids\": null}}" + }, + { + "name": "F2 no late error", + "ok": true, + "detail": "None" + }, + { + "name": "F2 reopened batch intact and unbilled", + "ok": true, + "detail": "{\"state\": \"queued\", \"reason\": null, \"owner\": null, \"attempts\": 0, \"entry_ids\": null, \"row_done\": 0, \"llm_used\": 0}" + }, + { + "name": "W owner close still pending, waiter cancel keeps the signal", + "ok": true, + "detail": "{\"active_close_pending\": true, \"signal_after_waiter_cancel\": true}" + }, + { + "name": "W new batch refused during the owner's close", + "ok": true, + "detail": "{\"state\": \"queued\", \"reason\": null, \"owner\": null, \"attempts\": 0, \"entry_ids\": null}" + }, + { + "name": "W original batch still actively owned while blocked", + "ok": true, + "detail": "{\"state\": \"pending\", \"reason\": null, \"owner\": \"3bd306ef54be3f3e7661b8a4065ebb68\", \"attempts\": 1, \"entry_ids\": null}" + }, + { + "name": "W original worker completes, one close, new batch untouched", + "ok": true, + "detail": "{\"original_batch\": {\"state\": \"done\", \"reason\": null, \"owner\": null, \"attempts\": 1, \"entry_ids\": \"[\\\"564af813-b7a2-4d11-b75e-2819f3a8bdb8\\\"]\"}, \"new_batch_still\": {\"state\": \"queued\", \"reason\": null, \"owner\": null, \"attempts\": 0, \"entry_ids\": null}, \"row_done\": 1, \"gateway_posts_after_release\": 1, \"client_closed\": true}" + } + ], + "finish_cancel_sdk_only": { + "caller_done_after_cancel": false, + "after_cancellation": { + "closing": true, + "closed": false, + "client_usable": true + }, + "tick_during_closing": { + "gateway_arrived": false, + "gateway_posts": 0, + "llm_used": 0, + "batch": { + "state": "queued", + "reason": null, + "owner": null, + "attempts": 0, + "entry_ids": null + } + }, + "finish_landed": { + "closed": true, + "client_usable": false, + "live_workers": 0, + "close_calls": 1, + "closing_still_set": true, + "batch": { + "state": "queued", + "reason": null, + "owner": null, + "attempts": 0, + "entry_ids": null + } + }, + "late_worker_error": null, + "persisted": { + "state": "queued", + "reason": null, + "owner": null, + "attempts": 0, + "entry_ids": null, + "row_done": 0, + "llm_used": 0 + } + }, + "finish_cancel_then_store_close": { + "caller_done_after_cancel": false, + "after_cancellation": { + "closing": true, + "closed": false, + "client_usable": true + }, + "tick_during_closing": { + "gateway_arrived": false, + "gateway_posts": 0, + "llm_used": 0, + "batch": { + "state": "queued", + "reason": null, + "owner": null, + "attempts": 0, + "entry_ids": null + } + }, + "finish_landed": { + "closed": true, + "client_usable": false, + "live_workers": 0, + "close_calls": 1, + "closing_still_set": true, + "batch": { + "state": "queued", + "reason": null, + "owner": null, + "attempts": 0, + "entry_ids": null + } + }, + "late_worker_error": null, + "persisted": { + "state": "queued", + "reason": null, + "owner": null, + "attempts": 0, + "entry_ids": null, + "row_done": 0, + "llm_used": 0 + } + }, + "waiter_cancel": { + "active_close_pending": true, + "signal_after_waiter_cancel": true, + "new_batch_during_closing": { + "state": "queued", + "reason": null, + "owner": null, + "attempts": 0, + "entry_ids": null + }, + "original_batch_while_blocked": { + "state": "pending", + "reason": null, + "owner": "3bd306ef54be3f3e7661b8a4065ebb68", + "attempts": 1, + "entry_ids": null + }, + "after_release": { + "original_batch": { + "state": "done", + "reason": null, + "owner": null, + "attempts": 1, + "entry_ids": "[\"564af813-b7a2-4d11-b75e-2819f3a8bdb8\"]" + }, + "new_batch_still": { + "state": "queued", + "reason": null, + "owner": null, + "attempts": 0, + "entry_ids": null + }, + "row_done": 1, + "gateway_posts_after_release": 1, + "client_closed": true + } + }, + "failures": [] +} \ No newline at end of file diff --git a/docs/rework/hel894/close-ownership-real-sdk.log b/docs/rework/hel894/close-ownership-real-sdk.log new file mode 100644 index 0000000..0d398e1 --- /dev/null +++ b/docs/rework/hel894/close-ownership-real-sdk.log @@ -0,0 +1,4 @@ +semantic shutdown drain: 1 live batch worker(s) still running after 0s — close signal set, waiting for their bounded exit before any resource closes (a live worker is never treated as dead) +Failed to load spaCy lemma model: spaCy is not installed. Install it with: pip install mem0ai[nlp] +Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201 +Failed to load spaCy full model: spaCy is not installed. Install it with: pip install mem0ai[nlp] diff --git a/docs/rework/hel894/contract-hel874-rerun.json b/docs/rework/hel894/contract-hel874-rerun.json new file mode 100644 index 0000000..fb1a6f9 --- /dev/null +++ b/docs/rework/hel894/contract-hel874-rerun.json @@ -0,0 +1,172 @@ +{ + "started": "2026-10-26T17:39:43Z", + "embedding_boundary": "deterministic 512-dimensional vectors installed before TextEmbedding construction; no model loaded; zero real embeddings", + "external_network": "socket.connect rejects all non-loopback hosts", + "install": { + "python": "3.10.12", + "mem0ai": "2.2.1", + "qdrant-client": "1.20.0", + "fastembed": "0.9.1", + "mem0_path": "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87/workdir/hel857-venv/lib/python3.10/site-packages/mem0", + "module_sha256": { + "memory/main.py": "f329ca4a17af1fbefb32ac10d4cc7ae7ddbdb7435a87eb74c30915cff98b8b7c", + "memory/storage.py": "5f5ecdadd2b260fd14f36a0f338336eb760275465dd1056a99a47e1ef07702bd", + "embeddings/fastembed.py": "3ec2ae87df5d0bebedb8b5471366c3412975847458499f66097f7b8c9ac8c9b8", + "llms/openai.py": "37e6d3c22b55df0731740f4e0868b95bd480ce44363227fe53461db328c5f67e", + "vector_stores/qdrant.py": "da570579d5cad69e6f123fdfe32b725235a25604e70047666bec763ba6e2bf43" + }, + "source_tarball_sha256": "9dcef9303ebcec116eec6739f01b8b35bd24459de6a569686b4d19b9412dda23" + }, + "adapter_has_llm_guard": true, + "checks": [ + { + "name": "C1_construct", + "ok": true, + "detail": "client_path=sdk-vector-store-client" + }, + { + "name": "C2_add_anchor_payload", + "ok": true, + "detail": "created=True payload_keys=['created_at', 'data', 'hash', 'input_sha256', 'src_group', 'text_lemmatized', 'turn_ids', 'turn_roles']" + }, + { + "name": "C2_add_user_scope", + "ok": true, + "detail": "user_id present in stored payload" + }, + { + "name": "C2_add_ledger_shape", + "ok": true, + "detail": "embed_items=3 llm_calls=1" + }, + { + "name": "C3_extraction_input_set", + "ok": true, + "detail": "old_memory=True new_row=True history_carry=True" + }, + { + "name": "C3b_unshared_canary_never_outbound", + "ok": true, + "detail": "queued_public_batches=2 leaked=False anchor_taint=False" + }, + { + "name": "C4_search_filters", + "ok": true, + "detail": "hits=3" + }, + { + "name": "C4_search_single_debit", + "ok": true, + "detail": "embed_delta=1 (pre-fix=2)" + }, + { + "name": "C6_concurrency_cap", + "ok": true, + "detail": "outcomes=['ok', 'refused'] used=3 cap=3" + }, + { + "name": "C7_reopen_after_close", + "ok": true, + "detail": "hits_after_reopen=3" + }, + { + "name": "C5_embed_zero_refuses", + "ok": true, + "detail": "err=semantic_embed_budget_not_approved llm_sent=0" + }, + { + "name": "C5_llm_zero_refuses", + "ok": true, + "detail": "err=semantic_llm_budget_not_approved llm_sent=0" + } + ], + "embed_rows_after_first_add": [ + { + "kind": "authority_prefix", + "items": 0, + "note": "authority:synthetic-verify-prefix" + }, + { + "kind": "dense", + "items": 1, + "note": "product:search" + }, + { + "kind": "dense", + "items": 1, + "note": "product:batch:add" + }, + { + "kind": "dense", + "items": 1, + "note": "product:add" + } + ], + "final_embed_rows": [ + { + "kind": "authority_prefix", + "items": 0, + "note": "authority:synthetic-verify-prefix" + }, + { + "kind": "dense", + "items": 1, + "note": "product:search" + }, + { + "kind": "dense", + "items": 1, + "note": "product:batch:add" + }, + { + "kind": "dense", + "items": 1, + "note": "product:add" + }, + { + "kind": "dense", + "items": 1, + "note": "product:search" + }, + { + "kind": "dense", + "items": 1, + "note": "product:batch:add" + }, + { + "kind": "dense", + "items": 1, + "note": "product:add" + }, + { + "kind": "dense", + "items": 1, + "note": "product:search" + }, + { + "kind": "dense", + "items": 1, + "note": "product:batch:add" + }, + { + "kind": "dense", + "items": 1, + "note": "product:add" + }, + { + "kind": "dense", + "items": 1, + "note": "product:search" + }, + { + "kind": "dense", + "items": 1, + "note": "product:search" + } + ], + "final_llm_used": 3, + "finished": "2026-10-26T17:39:45Z", + "gateway_requests_total": 3, + "failures": [], + "temp_dir": "/tmp/multica-task-2026294148/hel874-real-sdk-ubq10yph" +} \ No newline at end of file diff --git a/docs/rework/hel894/edges-rerun-hel889.json b/docs/rework/hel894/edges-rerun-hel889.json new file mode 100644 index 0000000..6798e56 --- /dev/null +++ b/docs/rework/hel894/edges-rerun-hel889.json @@ -0,0 +1,30 @@ +{ + "head": "HEL-889 same-shape rerun of review_hel886_edges.py (fixed tree)", + "real_llm": 0, + "real_embeddings": 0, + "queued_cancel": { + "batch": { + "state": "done", + "owner": null, + "attempts": 1 + }, + "registered_workers": 0, + "stored_entries": 1, + "row_done": 1, + "executor_queue_size": 0 + }, + "shutdown_timeout": { + "aclose_returned_while_worker_alive": false, + "batch_before_store_close": { + "state": "done", + "entry_ids": "[\"a6eb8633-c759-422f-819e-6a521c583a45\"]" + }, + "late_worker_error": null, + "persisted_batch": { + "state": "done", + "entry_ids": "[\"a6eb8633-c759-422f-819e-6a521c583a45\"]" + }, + "persisted_row_done": 1, + "llm_used": 1 + } +} \ No newline at end of file diff --git a/docs/rework/hel894/inflight-hel886-rerun.json b/docs/rework/hel894/inflight-hel886-rerun.json new file mode 100644 index 0000000..0b49f0b --- /dev/null +++ b/docs/rework/hel894/inflight-hel886-rerun.json @@ -0,0 +1,40 @@ +{ + "head": "HEL-886 inflight lifecycle", + "real_llm_requests": 0, + "real_embeddings": 0, + "boundary": "deterministic 512 vectors, non-loopback forbidden", + "checks": [ + { + "name": "L1_cancel_single_send_and_full_record", + "ok": true, + "detail": "arrived=1 concurrent=1 http_total=1 points=1 batch_live={'state': 'pending', 'owner': '93272596c381b3957a60f11caed4a7d2'} batch_concurrent=pending final={'state': 'done', 'reason': None, 'entry_ids': '[\"c3dc3b82-6d22-4cac-9076-75b2b2871a68\"]'} row_done=1" + }, + { + "name": "L2_lease_single_send_and_full_record", + "ok": true, + "detail": "arrived=1 concurrent=1 http_total=1 points=1 batch_live={'state': 'pending', 'owner': 'c6df32af28769cf791c6b7d25f3d8ec1'} batch_concurrent=pending final={'state': 'done', 'reason': None, 'entry_ids': '[\"5d38b54e-cc85-4cd1-b214-1aec5902140a\"]'} row_done=1" + }, + { + "name": "L3_shutdown_drains_live_worker_before_close", + "ok": true, + "detail": "arrived=1 waited=0.25s row_done_at=2000000 batch={'state': 'done', 'finished_at': 2000000}" + }, + { + "name": "L4a_all_done_finalizes_without_new_budget", + "ok": true, + "detail": "before={'state': 'done', 'entry_ids': '[\"0a4a0c10-0187-47e0-98c2-82e2d52ebb87\"]'} after={'state': 'done', 'reason': None, 'entry_ids': '[\"0a4a0c10-0187-47e0-98c2-82e2d52ebb87\"]'} http=1 llm_used=1" + }, + { + "name": "L4b_partial_keeps_the_hard_gate", + "ok": true, + "detail": "after={'state': 'queued', 'reason': 'semantic_llm_budget_exhausted'} http=0" + }, + { + "name": "L5_dead_owner_lease_still_recovers", + "ok": true, + "detail": "recovered={'state': 'failed', 'reason': 'lease_expired'} after={'state': 'done'} http=2" + } + ], + "gateway_requests_total": 7, + "failures": [] +} \ No newline at end of file diff --git a/docs/rework/hel894/manager-review-extra-rerun.json b/docs/rework/hel894/manager-review-extra-rerun.json new file mode 100644 index 0000000..269057e --- /dev/null +++ b/docs/rework/hel894/manager-review-extra-rerun.json @@ -0,0 +1,33 @@ +{ + "head": "59fb06304fb9f230837b43e431e2a1cc303e16c9", + "real_llm_requests": 0, + "real_embeddings": 0, + "midnight_settlement": { + "daily_cap": 100, + "old_hold": 90, + "actual": 10, + "new_day_used_before_next_request": 0, + "request_estimate": 150, + "over_cap_request_allowed": false, + "rows": [ + { + "day": "2026-10-26", + "scene": "dialogue_main", + "used": 10 + } + ] + }, + "aged_unknown_reservation": { + "cap": 1, + "used_before": 1, + "second_allowed": false, + "first_hold_id": 1, + "second_hold_id": null, + "used_after": 1 + }, + "release_documented_download_command": { + "command": "uv pip download --help", + "returncode": 2, + "stderr": "error: unrecognized subcommand 'download'\n\nUsage: uv pip [OPTIONS] \n\nFor more information, try '--help'." + } +} \ No newline at end of file diff --git a/docs/rework/hel894/manager-review-partial-rerun.json b/docs/rework/hel894/manager-review-partial-rerun.json new file mode 100644 index 0000000..52b5e42 --- /dev/null +++ b/docs/rework/hel894/manager-review-partial-rerun.json @@ -0,0 +1,48 @@ +{ + "head": "59fb06304fb9f230837b43e431e2a1cc303e16c9", + "real_llm_requests": 0, + "real_embeddings": 0, + "boundary": "deterministic 512 vectors, non-loopback forbidden", + "missing_authority_constructed_with_positive_caps": false, + "public_batch_enqueued": 1, + "batch_after_first_tick": { + "state": "queued", + "attempts": 0, + "reason": "LLM extraction failed: semantic_llm_budget_exhausted", + "entry_ids": null + }, + "loopback_requests_before_resume": 1, + "stored_points_after_first": [ + { + "src_group": "chat_public:mem0:synthetic:1bc8667410", + "turn_ids": [ + "synthetic" + ], + "turn_roles": [ + [ + "synthetic", + "companion", + 2 + ] + ], + "input_sha256": "840dde45eec07416f21c56cefb0f93f4e71af3edc3100c332f84bb1266637862", + "user_id": "cybergril", + "data": "合成提取记忆HEL874-1", + "text_lemmatized": "合成提取记忆HEL874-1", + "hash": "69195446402294f6e77f8ee993ce3456", + "created_at": "2026-10-26T17:41:21.075520+00:00", + "updated_at": "2026-10-26T17:41:21.075520+00:00" + } + ], + "claimed_completed_message_ids": [ + 2 + ], + "batch_after_resume": { + "state": "done", + "attempts": 1, + "reason": null, + "entry_ids": "[\"2e53e588-eb73-4b9a-8b43-05cc73cb3ca9\", \"20318cc2-8400-4e09-916f-28f00bbf23ce\"]" + }, + "loopback_requests_after_resume": 2, + "unsent_user_row_actually_sent": true +} \ No newline at end of file diff --git a/docs/rework/hel894/recovery-hel885-rerun.json b/docs/rework/hel894/recovery-hel885-rerun.json new file mode 100644 index 0000000..7dd6008 --- /dev/null +++ b/docs/rework/hel894/recovery-hel885-rerun.json @@ -0,0 +1,45 @@ +{ + "head": "HEL-885 rework", + "real_llm_requests": 0, + "real_embeddings": 0, + "boundary": "deterministic 512 vectors, non-loopback forbidden", + "checks": [ + { + "name": "S0_positive_caps_without_authority_fail_closed", + "ok": true, + "detail": "missing=ledger_authority_required empty=ledger_authority_required" + }, + { + "name": "S1_p1_first_tick_partial", + "ok": true, + "detail": "state=queued reason=LLM extraction failed: semantic_llm_budget_exhausted http=1 completed=[2] points=1 per_row_anchor=True" + }, + { + "name": "S2_p1_restart_sends_only_missing_row", + "ok": true, + "detail": "state=done http=1 user_sent=True completed=[1, 2] entry_ids=[\"1b89de13-2e94-4ebd-b5d1-4275b38b1562\", \"bc359f78-1e05-4b10-a067-2b85363db02c\"]" + }, + { + "name": "S3a_lease_expired_batch_recovers", + "ok": true, + "detail": "recovered={'state': 'failed', 'reason': 'lease_expired'} state_after=done http=2" + }, + { + "name": "S3b_concurrent_ticks_single_send", + "ok": true, + "detail": "http=2 states=['done']" + }, + { + "name": "S4a_aged_unknown_llm_reservation_kept", + "ok": true, + "detail": "second_allowed=False used_after_restart=1" + }, + { + "name": "S4b_aged_unknown_embed_reservation_kept", + "ok": true, + "detail": "second_allowed=False used=1 after_release=0" + } + ], + "gateway_requests_total": 6, + "failures": [] +} \ No newline at end of file diff --git a/docs/rework/hel894/release-offline-hel894.json b/docs/rework/hel894/release-offline-hel894.json new file mode 100644 index 0000000..8f4a34d --- /dev/null +++ b/docs/rework/hel894/release-offline-hel894.json @@ -0,0 +1,86 @@ +{ + "started": "2026-10-26T17:40:19Z", + "venv_python": "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-874-db7635e6b65e/workdir/CyberGril/.venv311/bin/python", + "venv_python_version": "3.11.16", + "checks": [ + { + "name": "R1_checkout_fresh_dir", + "ok": true, + "detail": "cloned tracked source into /tmp/multica-task-2026294148/hel882-release-fq8t_q6_/cybergril-hel874/current" + }, + { + "name": "R2_service_imports_product", + "ok": true, + "detail": "" + }, + { + "name": "R6_mem0_coimport_status_recorded", + "ok": true, + "detail": "import mem0 → ModuleNotFoundError: No module named 'mem0' (resolution path in deploy/hel874-release.md §4; no download in this check)" + }, + { + "name": "R7_pip_download_command_exists", + "ok": true, + "detail": "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87/workdir/hel857-venv/bin/python -m pip download --help → rc=0" + }, + { + "name": "R7_removed_uv_pip_download_still_absent", + "ok": true, + "detail": "uv pip download --help → rc=2 (kept absent on purpose; do not re-document it)" + }, + { + "name": "R2_service_serves_health", + "ok": true, + "detail": "version=R4-assembly semantic=stub" + }, + { + "name": "R3_create_status_recorded", + "ok": true, + "detail": "create status=201(409=前次运行的档案仍在,也是保留数据的表现)" + }, + { + "name": "R3_dialogue_refused_honestly", + "ok": true, + "detail": "http=200 events=b'data: {\"t\": \"chat.error\", \"epoch\": 1, \"turn_id\": \"00000000-0000-4000-8000-000000000001\", \"phi\": \"\\xe5\\xa5\\xb9\\xe8\\xbf\\x99\\xe4\\xbc\\x9a\\xe5\\x84\\xbf\\xe6\\xb2\\xa1\\xe6\\x8e\\xa5\\xe4\\xb8\\x8a\\xe8\\xaf'" + }, + { + "name": "R4_service_restarts_on_same_data", + "ok": true, + "detail": "epoch=2" + }, + { + "name": "R5_epoch_bumped_on_reopen", + "ok": true, + "detail": "1 → 2" + }, + { + "name": "R4_companion_created_offline", + "ok": true, + "detail": "status=409" + }, + { + "name": "R4_dialogue_stream_http", + "ok": true, + "detail": "status=200 events=b'data: {\"t\": \"chat.delta\", \"epoch\": 2, \"turn_id\": \"00000000-0000-4000-8000-000000000002\", \"delta\": \"\\xe6\\x89\\xb9\"}\\n\\ndata: {\"t\": \"c'" + }, + { + "name": "R4_messages_roundtrip", + "ok": true, + "detail": "roles=['user', 'user', 'companion']" + }, + { + "name": "R5_data_dir_preserved", + "ok": true, + "detail": "['companion.db']" + }, + { + "name": "R5_companion_row_survives_restart", + "ok": true, + "detail": "companion rows=1" + } + ], + "mem0_import_in_release_venv": "ModuleNotFoundError: No module named 'mem0'", + "removed_uv_pip_download_rc": 2, + "failures": [], + "finished": "2026-10-26T17:40:22Z" +} \ No newline at end of file diff --git a/docs/rework/hel894/shutdown-queued-hel889-rerun.json b/docs/rework/hel894/shutdown-queued-hel889-rerun.json new file mode 100644 index 0000000..5d39540 --- /dev/null +++ b/docs/rework/hel894/shutdown-queued-hel889-rerun.json @@ -0,0 +1,182 @@ +{ + "head": "HEL-889 shutdown ownership & queued-cancel", + "real_llm_requests": 0, + "real_embeddings": 0, + "boundary": "deterministic 512 vectors, non-loopback forbidden", + "checks": [ + { + "name": "Q1 queued snapshot shows phantom-liveness", + "ok": true, + "detail": "" + }, + { + "name": "Q1 cancel releases registry and requeues", + "ok": true, + "detail": "{\"registered_workers\": 0, \"batch\": {\"state\": \"queued\", \"reason\": \"queued_worker_cancelled\", \"owner\": null, \"attempts\": 0, \"entry_ids\": null}, \"row_done\": 0, \"stored_entries\": 0}" + }, + { + "name": "Q1 in-process recovery completes without restart", + "ok": true, + "detail": "{\"batch\": {\"state\": \"done\", \"reason\": null, \"owner\": null, \"attempts\": 1, \"entry_ids\": \"[\\\"stub-1\\\"]\"}, \"registered_workers\": 0, \"stored_entries\": 1, \"row_done\": 1}" + }, + { + "name": "S1 aclose does NOT return while the worker is alive", + "ok": true, + "detail": "" + }, + { + "name": "S1 worker completes and flushes before store close", + "ok": true, + "detail": "{\"state\": \"done\", \"reason\": null, \"owner\": null, \"attempts\": 1, \"entry_ids\": \"[\\\"66f72048-0526-4790-8de0-946ee4fe9251\\\"]\"}" + }, + { + "name": "S1 no late-worker error after honest drain", + "ok": true, + "detail": "" + }, + { + "name": "S1 durable reopen: done + row_done=1 + llm_used=1", + "ok": true, + "detail": "{\"state\": \"done\", \"reason\": null, \"owner\": null, \"attempts\": 1, \"entry_ids\": \"[\\\"66f72048-0526-4790-8de0-946ee4fe9251\\\"]\", \"row_done\": 1, \"llm_used\": 1, \"gateway_posts\": 1}" + }, + { + "name": "S2 shutdown between rows requeues with first row proven", + "ok": true, + "detail": "{\"state\": \"queued\", \"reason\": \"shutdown_between_rows\", \"owner\": null, \"attempts\": 0, \"entry_ids\": null, \"row_done\": 1, \"gateway_posts_during_shutdown\": 1}" + }, + { + "name": "S2 resume sends ONLY the missing row and completes", + "ok": true, + "detail": "{\"state\": \"done\", \"reason\": null, \"owner\": null, \"attempts\": 1, \"entry_ids\": \"[\\\"ccfcad6e-69f4-41c9-830a-b357290ce82d\\\", \\\"085a5ea8-622e-4f5c-8862-8ea20d4b2b23\\\"]\", \"row_done\": 2, \"gateway_posts_resume\": 2}" + }, + { + "name": "S3 cancelled aclose closes nothing and re-arms", + "ok": true, + "detail": "" + }, + { + "name": "S3 worker finishes done and a later aclose closes for real", + "ok": true, + "detail": "" + }, + { + "name": "S4 concurrent aclose drains once and closes once", + "ok": true, + "detail": "{\"batch\": {\"state\": \"done\", \"reason\": null, \"owner\": null, \"attempts\": 1, \"entry_ids\": \"[\\\"bb32ccc4-10c0-4fe5-92a3-248bcc93b2f8\\\"]\", \"row_done\": 1}, \"client_usable_after_close\": false}" + } + ], + "queued_cancel": { + "queued": { + "registered_workers": 1, + "product_executor_queue": 1 + }, + "after_cancel": { + "registered_workers": 0, + "batch": { + "state": "queued", + "reason": "queued_worker_cancelled", + "owner": null, + "attempts": 0, + "entry_ids": null + }, + "row_done": 0, + "stored_entries": 0 + }, + "after_recovery": { + "batch": { + "state": "done", + "reason": null, + "owner": null, + "attempts": 1, + "entry_ids": "[\"stub-1\"]" + }, + "registered_workers": 0, + "stored_entries": 1, + "row_done": 1 + } + }, + "shutdown_timeout": { + "deadline": { + "aclose_returned_while_worker_alive": false, + "batch_before_any_close": { + "state": "pending", + "reason": null, + "owner": "8956b9e9abade1c5e34a3ecc6986b6f2", + "attempts": 1, + "entry_ids": null + }, + "client_usable": true + }, + "before_store_close": { + "state": "done", + "reason": null, + "owner": null, + "attempts": 1, + "entry_ids": "[\"66f72048-0526-4790-8de0-946ee4fe9251\"]" + }, + "late_worker_error": null, + "persisted": { + "state": "done", + "reason": null, + "owner": null, + "attempts": 1, + "entry_ids": "[\"66f72048-0526-4790-8de0-946ee4fe9251\"]", + "row_done": 1, + "llm_used": 1, + "gateway_posts": 1 + } + }, + "between_rows": { + "after_shutdown": { + "state": "queued", + "reason": "shutdown_between_rows", + "owner": null, + "attempts": 0, + "entry_ids": null, + "row_done": 1, + "gateway_posts_during_shutdown": 1 + }, + "after_resume": { + "state": "done", + "reason": null, + "owner": null, + "attempts": 1, + "entry_ids": "[\"ccfcad6e-69f4-41c9-830a-b357290ce82d\", \"085a5ea8-622e-4f5c-8862-8ea20d4b2b23\"]", + "row_done": 2, + "gateway_posts_resume": 2 + } + }, + "cancelled_aclose": { + "after_cancel": { + "client_usable": true, + "batch": { + "state": "pending", + "reason": null, + "owner": "19c694186e6d25be43d24f3f0d0e2128", + "attempts": 1, + "entry_ids": null + }, + "closing_cleared": true + }, + "after_worker": { + "state": "done", + "reason": null, + "owner": null, + "attempts": 1, + "entry_ids": "[\"4649609e-db3b-4e2d-b473-dc30988a744c\"]" + }, + "client_usable_after_real_close": false + }, + "concurrent_aclose": { + "batch": { + "state": "done", + "reason": null, + "owner": null, + "attempts": 1, + "entry_ids": "[\"bb32ccc4-10c0-4fe5-92a3-248bcc93b2f8\"]", + "row_done": 1 + }, + "client_usable_after_close": false + }, + "failures": [] +} \ No newline at end of file diff --git a/docs/rework/hel894/verbatim-after-fix.log b/docs/rework/hel894/verbatim-after-fix.log new file mode 100644 index 0000000..50fb7dd --- /dev/null +++ b/docs/rework/hel894/verbatim-after-fix.log @@ -0,0 +1,19 @@ +Traceback (most recent call last): + File "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-894-8e6b450e162c/workdir/after/review_hel889_cancel.py", line 127, in + result = asyncio.run(main()) + File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run + return loop.run_until_complete(main) + File "/usr/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete + return future.result() + File "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-894-8e6b450e162c/workdir/after/review_hel889_cancel.py", line 121, in main + 'finish_cancel_sdk_only': await finish_cancel(root / 'sdk-only', False), + File "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-894-8e6b450e162c/workdir/after/review_hel889_cancel.py", line 43, in finish_cancel + assert await asyncio.to_thread(server.arrived.wait, 5) +AssertionError +Exception ignored in: +Traceback (most recent call last): + File "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87/workdir/hel857-venv/lib/python3.10/site-packages/qdrant_client/qdrant_client.py", line 172, in __del__ + File "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-894-8e6b450e162c/workdir/after/review_hel889_cancel.py", line 29, in gated_close + File "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87/workdir/hel857-venv/lib/python3.10/site-packages/qdrant_client/qdrant_client.py", line 181, in close + File "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87/workdir/hel857-venv/lib/python3.10/site-packages/qdrant_client/local/qdrant_local.py", line 113, in close +ImportError: sys.meta_path is None, Python is likely shutting down diff --git a/docs/runbook-hel870.md b/docs/runbook-hel870.md index 1ee603d..b9a48d3 100644 --- a/docs/runbook-hel870.md +++ b/docs/runbook-hel870.md @@ -88,6 +88,19 @@ docs/rework/hel874/erratum-hel882.json(旧 runs 有真实本地嵌入,下限 recover+tick 完成,无需重启)与「已开始」(维持单发语义,worker 线程自己 写终态)。真崩溃仍保守留账,不宣称严格一次。 +**HEL-894 关闭取消的所有权(docs/rework/hel894/,固定安装本体验证)**: + +- `aclose` 的取消语义分两阶段:**排空阶段可撤销**(尚未关任何资源——取消 + 什么都不关、closing 复位、层次可续用,与 HEL-889 口径一致);**提交阶段 + 不可撤销**(`backend.aclose()` 已开始——被取消的调用方不清 closing、不放 + 行 tick(半关闭绝不宣称可用)、不释放锁,等待自己启动的层持有关闭任务 + (`_close_task` 创建恰一次、从不丢后台、重复取消只重新 shield)落成后才 + 传播取消,资源恰关一次;本层自有执行器 shutdown 走 `to_thread`,不用同步 + join 阻塞事件循环)。只有真正取得锁并置位信号的调用才可复位信号:**等锁 + 者被取消不改持锁关闭者的任何状态**(总管复现过等锁者清掉第一关闭的 + closing、新批在原 worker 未放行时跑完)。app lifespan 注释同步该口径; + 真崩溃语义不变(保守留账、只发无证明行、不宣称严格一次)。 + ## 5. 体验链路清单(按用户实际体验顺序;只有实际能力标已接) | # | 步骤 | 状态 | 说明 | diff --git a/src/cybergril/api/app.py b/src/cybergril/api/app.py index d2f1501..a3ac2b1 100644 --- a/src/cybergril/api/app.py +++ b/src/cybergril/api/app.py @@ -262,10 +262,13 @@ def create_app( app.state.active["cancel"].set() await app.state.active["finished"].wait() if app.state.semantic: - # HEL-889 shutdown ownership: aclose returns only after every - # live batch worker has actually exited (drain_timeout bounds - # the polite phase, never a licence to close under a worker), - # so the provider clients and the store below close safely. + # HEL-889/894 shutdown ownership: aclose returns only after + # every live batch worker has actually exited (drain_timeout + # bounds the polite phase, never a licence to close under a + # worker). If this await is cancelled after the resource + # close began, the close still lands exactly once before the + # cancellation propagates (HEL-894) — the provider clients + # and the store below stay safe in either order. await app.state.semantic.aclose() for provider in set(router.provider_for(t) for t in router.available_tiers()): await provider.aclose() diff --git a/src/cybergril/memory/semantic.py b/src/cybergril/memory/semantic.py index 6234fef..f9484cb 100644 --- a/src/cybergril/memory/semantic.py +++ b/src/cybergril/memory/semantic.py @@ -82,6 +82,18 @@ Product port of the proven HEL-857/861–869 isolation results (plan-next-HEL-86 half-closed); a queued worker whose waiter was cancelled is released by the deterministic CANCELLED check, so the old false-registry "phantom worker that only a restart could clear" can no longer pin a batch pending forever. +- Cancellation owns nothing it did not start (HEL-894): ``aclose`` is a + two-phase protocol. The DRAIN phase (waiting for live workers) is + revocable — a cancelled caller leaves everything open and re-arms the + layer. The FINISH phase (``backend.aclose`` begun) is irreversible: the + closing markers stay (a half-closed layer is never reported usable, ticks + keep refusing), the layer-owned close task runs exactly once, and the + cancelled caller still waits — repeated cancels included — for the close + it started to land before propagating; the shielded task is collected, + never dropped to the background. A caller cancelled while merely WAITING + for the close lock cannot touch the active closer's state (the manager + reproduced a cancelled waiter clearing the owner's ``closing`` flag and a + new batch running under a drain that was still in progress). - Completed-work finalization needs no new budget (HEL-886): a batch whose every row already carries a completion proof finalizes to ``done`` with zero new HTTP/embed/LLM — recovery of the "row persisted, final status did @@ -1048,14 +1060,18 @@ class SemanticMemory: # blocked batch call can never starve the loop's shared default # executor (search/close paths). ``_closing`` is the cooperative stop # signal; ``_aclose_lock``/``_closed`` make aclose idempotent and - # concurrency-safe. A caller-injected executor (verification barrier - # setups) stays caller-owned — never shut down here. + # concurrency-safe. ``_close_task`` (HEL-894) is the layer-owned + # irreversible close: created once, landed exactly once, never + # abandoned to the background. A caller-injected executor + # (verification barrier setups) stays caller-owned — never shut down + # here. self._owns_executor = executor is None self._executor = executor or concurrent.futures.ThreadPoolExecutor( max_workers=4, thread_name_prefix="cg-semantic-batch") self._closing = threading.Event() self._aclose_lock = asyncio.Lock() self._closed = False + self._close_task: asyncio.Task | None = None # ------------------------------------------------------------ enqueue def public_rows_for_turn(self, turn_id: str) -> list[dict]: @@ -1387,19 +1403,42 @@ class SemanticMemory: so the wait terminates in practice; 4. only then the backend and this layer's executor close. + Cancellation is two-phase (HEL-894), because the manager reproduced a + cancelled aclose releasing the lock mid-``backend.aclose`` while the + shielded close kept running in the background, and a new tick being + claimed straight into resources that were about to vanish: + + - DRAIN (revocable): nothing has closed yet. A cancelled caller + leaves everything OPEN, resets the closing signal, and the layer + stays usable; a later aclose drains again. + - FINISH (irreversible): ``backend.aclose`` has begun, so the close + can only land. A cancelled caller does NOT reset the markers (a + half-closed layer is never reported usable — ticks stay refused), + keeps the lock, and waits — repeated cancels included — for the + layer-owned close task it started before propagating + CancelledError; the task is collected here, never dropped to the + background, and the resources close exactly once. + + Only a call that OWNS the protocol (lock acquired, closing signal + set) may reset that signal, and only while the close is still + revocable: a caller cancelled while merely WAITING for the lock + cannot touch the active closer's state — the manager reproduced a + cancelled waiter clearing the owner's flag mid-drain and a new batch + running to ``done`` while the real close still held the worker. Idempotent and concurrency-safe: concurrent callers serialize on one - lock; a caller cancelled mid-drain leaves everything OPEN (nothing - half-closed, the closing signal reset) for a later aclose to finish. - For genuinely dead processes the crash semantics stay conservative - (HEL-885/886): unknown wire outcomes stay billed, retries send only - rows without a completion proof, strict-once is not claimed. + lock; the close itself runs exactly once. For genuinely dead + processes the crash semantics stay conservative (HEL-885/886): + unknown wire outcomes stay billed, retries send only rows without a + completion proof, strict-once is not claimed. """ if self._closed: return + owns_close = False try: async with self._aclose_lock: if self._closed: return + owns_close = True self._closing.set() deadline = time.monotonic() + drain_timeout warned = False @@ -1429,22 +1468,44 @@ class SemanticMemory: "never treated as dead)", remaining, drain_timeout) await asyncio.sleep(0.05) - async def _finish() -> None: - await self.backend.aclose() - if self._owns_executor: - self._executor.shutdown(wait=True) - self._closed = True - - # Shielded: once draining is complete the closes themselves - # run to completion even if this caller is cancelled. - await asyncio.shield(_finish()) + # Irreversible from here on (HEL-894): resources are closing. + # The close task belongs to the LAYER and runs exactly once, + # whatever happens to the caller that started it. + if self._close_task is None: + self._close_task = asyncio.create_task(self._finish_close()) + try: + await asyncio.shield(self._close_task) + except asyncio.CancelledError: + # The finish phase cannot be revoked: keep the markers + # (ticks stay refused — never half-closed-usable), hold + # the lock, and land the close before propagating; + # repeated cancels only re-shield the same owned task. + while not self._close_task.done(): + with contextlib.suppress(asyncio.CancelledError): + await asyncio.shield(self._close_task) + raise except asyncio.CancelledError: - if not self._closed: - # A cancelled close leaves NOTHING half-closed and re-arms the - # layer: ticks may continue, a later aclose drains again. + if owns_close and self._close_task is None and not self._closed: + # Revocable-phase cancel by the protocol OWNER only: re-arm + # the layer for reuse. A lock waiter (owns_close False) never + # touches the active closer's state, and once the finish task + # exists the close is irreversible and the markers stay. self._closing.clear() raise + async def _finish_close(self) -> None: + """The single layer-owned resource close (HEL-894). + + Runs exactly once however many aclose callers arrive or get + cancelled. ``backend.aclose`` is already off-loop; this layer's OWN + executor joins via ``to_thread`` so a cancelled caller can never + block the event loop on a synchronous shutdown wait either. + """ + await self.backend.aclose() + if self._owns_executor: + await asyncio.to_thread(self._executor.shutdown, True) + self._closed = True + # ------------------------------------------------------------ read gate def chain_resolve(self, hit: dict) -> dict: """Fail-closed provenance chain from a retrieval hit back to archive rows. diff --git a/tests/test_rework_hel894.py b/tests/test_rework_hel894.py new file mode 100644 index 0000000..8f24a9c --- /dev/null +++ b/tests/test_rework_hel894.py @@ -0,0 +1,231 @@ +"""HEL-894 rework regressions: close ownership under cancellation. + +Two defects from the manager's independent pinned-SDK review +(review_hel889_cancel.py): + +D1 — cancelling aclose AFTER ``backend.aclose`` began released the lock, +cleared ``closing`` and left the shielded close running unowned in the +background: the layer looked usable, a new tick claimed a batch onto real +HTTP, then the orphaned finish closed Qdrant under it (batch failed / +row_done=0 / llm_used=1 on ``QdrantLocal instance is closed``; with the +caller closing the store too, the late worker died on ``Cannot operate on a +closed database`` and the reopened batch sat pending). + +D2 — cancelling a SECOND aclose that was still WAITING for the lock cleared +the FIRST closer's ``closing`` flag: a new batch ran to ``done`` while the +real drain still held the original worker. + +The close is now two-phase (HEL-894): a drain-phase cancel re-arms the +layer; once ``backend.aclose`` begins the close is irreversible — markers +stay, ticks stay refused, the layer-owned close task lands exactly once +(repeated cancels included), and only the protocol owner may reset the +signal. The pinned real install is covered live by +tools/verify_close_ownership_hel894.py (manager negatives rerun). +""" +import asyncio +import threading +from contextlib import suppress + +from test_rework_hel886 import batch_row, install_blocking, seed_user_row +from test_rework_hel889 import make_backend, wait_until +from test_semantic_recovery_hel882 import install_fake + +from cybergril.memory.semantic import SemanticMemory +from cybergril.memory.store import Store + + +def gate_client_close(backend, entered, release): + """Gate ONLY the SDK client boundary — the manager's exact shape: the + REAL product aclose path runs and the underlying close still executes, + scheduling is just held at the irreversible boundary.""" + calls = {"count": 0} + real_close = backend._client.close + + def gated_close(*args, **kwargs): + calls["count"] += 1 + entered.set() + assert release.wait(10) + return real_close(*args, **kwargs) + + backend._client.close = gated_close + return calls + + +def batch_row_for(store, turn_id): + return dict(store.query_one( + "SELECT state,reason,owner,attempts,entry_ids FROM sem_batch WHERE turn_id=?", + (turn_id,))) + + +async def test_finish_cancel_keeps_ownership_and_refuses_new_work( + tmp_path, monkeypatch): + """D1: cancel aclose after ``backend.aclose`` began. The cancelled caller + must NOT report the layer usable: markers stay, the new batch is never + claimed (zero wire work, zero budget), and the owned close lands exactly + once before the cancellation propagates.""" + install_fake(monkeypatch) + backend, _cfg = make_backend(tmp_path, "finish") + store = Store(tmp_path / "finish.db") + live = SemanticMemory(store, backend) + entered, release = threading.Event(), threading.Event() + close_calls = gate_client_close(backend, entered, release) + + closing = asyncio.create_task(live.aclose()) + assert await asyncio.to_thread(entered.wait, 5) # the close BEGAN + closing.cancel() + await asyncio.sleep(0.05) # cancel delivered into the owned-close tail + assert not closing.done() # still landing the close it started + assert live._closing.is_set() # never half-closed-usable + assert not live._closed and not backend._client.closed + + seed_user_row(store, "t-finish", "提交阶段取消后不应被领取的合成原话") + live.enqueue_uncovered() + await live.tick() # refused: the close owns the layer + row = batch_row_for(store, "t-finish") + assert row["state"] == "queued" and row["owner"] is None and row["attempts"] == 0 + assert len(backend._memory.llm.calls) == 0 # zero sends, zero budget + + release.set() + with suppress(asyncio.CancelledError): + await closing # the close lands, THEN the cancellation propagates + assert live._closed and backend._client.closed + assert close_calls["count"] == 1 # closed exactly once + assert live._closing.is_set() # a finished close never re-arms + await live.tick() # a closed layer keeps refusing new claims + assert batch_row_for(store, "t-finish")["state"] == "queued" + store.close() # caller order stays safe — no worker was ever started + + +async def test_repeated_cancel_during_finish_lands_close_once( + tmp_path, monkeypatch): + """Repeated cancels while the finish task is gated only re-shield the + same owned close: it still lands exactly once.""" + install_fake(monkeypatch) + backend, _cfg = make_backend(tmp_path, "repeat") + store = Store(tmp_path / "repeat.db") + live = SemanticMemory(store, backend) + entered, release = threading.Event(), threading.Event() + close_calls = gate_client_close(backend, entered, release) + + closing = asyncio.create_task(live.aclose()) + assert await asyncio.to_thread(entered.wait, 5) + for _ in range(3): + closing.cancel() + await asyncio.sleep(0.02) + assert not closing.done() + assert live._closing.is_set() and not live._closed + + release.set() + with suppress(asyncio.CancelledError): + await closing + assert live._closed and close_calls["count"] == 1 + store.close() + + +async def test_second_close_during_finish_waits_and_cancels_cleanly( + tmp_path, monkeypatch): + """Same-phase second/third callers: an uncancelled second aclose waits + for the owner's finish and returns after ONE close; a third cancelled + while still waiting for the lock touches nothing (D2 at the finish + phase).""" + install_fake(monkeypatch) + backend, _cfg = make_backend(tmp_path, "second") + store = Store(tmp_path / "second.db") + live = SemanticMemory(store, backend) + entered, release = threading.Event(), threading.Event() + close_calls = gate_client_close(backend, entered, release) + + first = asyncio.create_task(live.aclose()) + assert await asyncio.to_thread(entered.wait, 5) # finish phase, gated + second = asyncio.create_task(live.aclose()) + third = asyncio.create_task(live.aclose()) + await asyncio.sleep(0.05) # both parked on the close lock + assert not second.done() and not third.done() + third.cancel() + with suppress(asyncio.CancelledError): + await third + assert live._closing.is_set() # the waiter changed nothing + + release.set() + await asyncio.gather(first, second) # both land after the ONE close + assert live._closed and close_calls["count"] == 1 + assert live._closing.is_set() + store.close() + + +async def test_waiter_cancel_never_touches_active_close(tmp_path, monkeypatch): + """D2: the first aclose is mid-drain with a live worker on the wire; a + second aclose cancelled while WAITING for the lock must not clear the + owner's signal — new batches stay queued, the original worker completes, + and the owner's close then lands exactly once.""" + arrived, wire_release = threading.Event(), threading.Event() + install_blocking(monkeypatch, arrived, wire_release) + backend, _cfg = make_backend(tmp_path, "waiter") + store = Store(tmp_path / "waiter.db") + seed_user_row(store, "t-waiter", "等锁者取消期间仍在排空的合成原话") + live = SemanticMemory(store, backend) + live.enqueue_uncovered() + worker = asyncio.create_task(live.tick()) + assert await asyncio.to_thread(arrived.wait, 5) # original worker on the wire + + close_one = asyncio.create_task(live.aclose(drain_timeout=0.05)) + assert await wait_until(lambda: live._closing.is_set()) + close_two = asyncio.create_task(live.aclose()) # still WAITING for the lock + await asyncio.sleep(0.05) + close_two.cancel() + with suppress(asyncio.CancelledError): + await close_two + assert not close_one.done() # the real close is still draining + assert live._closing.is_set() # D2: the waiter cleared nothing + + seed_user_row(store, "t-waiter-new", "关闭期间不应被领取的新批次") + live.enqueue_uncovered() + await live.tick() # refused: the owner's close still holds the layer + new_row = batch_row_for(store, "t-waiter-new") + assert new_row["state"] == "queued" and new_row["owner"] is None + assert len(backend._memory.llm.attempts) == 1 # only the original wire call + + wire_release.set() + await close_one # drain completes, then the close lands + assert backend._client.closed and live._closed + assert batch_row_for(store, "t-waiter")["state"] == "done" + assert len(store.query("SELECT * FROM sem_row_done")) == 1 + assert batch_row_for(store, "t-waiter-new")["state"] == "queued" + with suppress(asyncio.CancelledError, Exception): + await worker + store.close() + + +async def test_drain_cancel_still_rearms_for_reuse(tmp_path, monkeypatch): + """The revocable window stays revocable: a cancel while only DRAINING + (nothing closed yet) re-arms the layer and later batches still run; a + subsequent aclose then closes for real.""" + arrived, wire_release = threading.Event(), threading.Event() + install_blocking(monkeypatch, arrived, wire_release) + backend, _cfg = make_backend(tmp_path, "drain") + store = Store(tmp_path / "drain.db") + seed_user_row(store, "t-drain", "排空阶段取消应当可续用的合成原话") + live = SemanticMemory(store, backend) + live.enqueue_uncovered() + worker = asyncio.create_task(live.tick()) + assert await asyncio.to_thread(arrived.wait, 5) + + closing = asyncio.create_task(live.aclose(drain_timeout=0.05)) + await asyncio.sleep(0.2) # past the deadline, still only draining + closing.cancel() + with suppress(asyncio.CancelledError): + await closing + assert not live._closing.is_set() # re-armed + assert not backend._client.closed # nothing closed + + wire_release.set() + with suppress(asyncio.CancelledError, Exception): + await worker + assert batch_row(store)["state"] == "done" + seed_user_row(store, "t-drain-2", "取消关闭后继续处理的合成原话") + live.enqueue_uncovered() + await live.tick() # the layer is USABLE again + assert batch_row_for(store, "t-drain-2")["state"] == "done" + await live.aclose() + assert backend._client.closed + store.close() diff --git a/tools/verify_close_ownership_hel894.py b/tools/verify_close_ownership_hel894.py new file mode 100644 index 0000000..e2c9bb1 --- /dev/null +++ b/tools/verify_close_ownership_hel894.py @@ -0,0 +1,273 @@ +#!/usr/bin/env python3 +"""HEL-894 · 关闭所有权取消语义验证(零真实出站、零真实嵌入、零权威账写入)。 + +总管独立复审 review_hel889_cancel.py(固定 mem0 2.2.1 + 真实 Qdrant/OpenAI +client + 实际产品 tick/aclose)两个负例的修复后同形重跑。原脚本原件保留、 +修复前基线见 docs/rework/hel894/before-ceb0f35.json;本轮断言按 HEL-894 新 +安全协议改写(不再期待「取消后可续用」——提交阶段已不可撤销,tick 必须拒新, +关闭由层持有任务一次落成)。边界与 tools/verify_shutdown_queued_hel889.py 相 +同:确定性 512 维替身(TextEmbedding 构造前安装)、127.0.0.1 假网关、临时 +账/库;屏障只加在 client.close 之前,底层真实 close 照常执行;单线程执行器 +由调用方注入持有,避免同步 shutdown 阻断观测。 + + F1 提交阶段取消(SDK-only,负例一同形):取消返回后 closing 保持置位、 + closed 尚未落成、client 仍可用;新批 tick 被拒(网关零到达、批次仍 + queued/owner NULL/attempts 0、llm_used=0);被取消的调用方等自己启动 + 的层持有关闭任务落成后才传播取消(closed=true、client 不可用、 + live_workers=0、close 恰一次);重开:批次仍 queued、row_done=0、 + llm_used=0。修复前:closing=false/closed=false/可用 → 新批被领 → 后台 + 旧 _finish 关 Qdrant → QdrantLocal instance is closed → failed/ + row_done=0/llm_used=1。 + F2 提交阶段取消 + 调用方随后关 Store(负例一加强分支,单独记录):同上, + 且无任何晚到错误(修复前:ProgrammingError: Cannot operate on a closed + database,重开 pending/row_done=0/llm_used=1)。 + W 等锁者取消(负例二同形):第一关闭排空中、第二关闭等锁即取消—— + closing 保持置位(修复前被清掉);新批 tick 被拒仍 queued;原 worker + 放行后完成 done/row_done=1;第一关闭随后一次收尾关库;新批保持 queued。 + +证据 JSON 写 argv[1]。运行(相邻目录 CyberGril 为被测 checkout,固定 venv): + + /path/to/hel857-venv/bin/python tools/verify_close_ownership_hel894.py out.json +""" +from __future__ import annotations + +import asyncio +import concurrent.futures +import importlib.util +import json +import sys +import tempfile +import threading +from contextlib import suppress +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +spec = importlib.util.spec_from_file_location( + 'edges', ROOT / 'tools/verify_shutdown_queued_hel889.py') +edges = importlib.util.module_from_spec(spec) +spec.loader.exec_module(edges) # installs the deterministic boundary on import + +REPORT: dict = {"head": "HEL-894 close ownership under cancellation", + "real_llm_requests": 0, "real_embeddings": 0, + "boundary": "deterministic 512 vectors, non-loopback forbidden", + "protocol": "drain-phase cancel re-arms; finish-phase cancel keeps " + "markers, refuses ticks, lands the layer-owned close " + "exactly once; lock waiters never touch the owner's state"} +FAILURES: list[str] = [] + + +def check(name: str, ok: bool, detail: str = "") -> bool: + REPORT.setdefault("checks", []).append({"name": name, "ok": bool(ok), "detail": detail}) + if not ok: + FAILURES.append(f"{name}: {detail}") + return bool(ok) + + +async def finish_cancel(tmp, close_store: bool) -> dict: + """总管负例一同形:取消发生在真实 client.close 已进入之后。""" + server, thread = edges.start_blocking_gateway() + executor = concurrent.futures.ThreadPoolExecutor(max_workers=1) + backend, _ = edges.backend_for(tmp, 'finish', server.server_address[1]) + store = edges.Store(tmp / 'store.db') + live = edges.SemanticMemory(store, backend, executor=executor) + close_entered, close_release = threading.Event(), threading.Event() + close_calls = {"count": 0} + real_close = backend._client.close + + def gated_close(*args, **kwargs): + close_calls["count"] += 1 + close_entered.set() + assert close_release.wait(10) + return real_close(*args, **kwargs) + + backend._client.close = gated_close + posts_before = len(edges.contract.FakeGateway.requests) + task = None + try: + closing = asyncio.create_task(live.aclose()) + assert await asyncio.to_thread(close_entered.wait, 5) # backend.aclose BEGAN + closing.cancel() + await asyncio.sleep(0.05) # cancel lands in the owned-close tail + report = {'caller_done_after_cancel': closing.done(), + 'after_cancellation': {'closing': live._closing.is_set(), + 'closed': live._closed, + 'client_usable': edges.client_usable(backend)}} + edges.seed_turn(store, 'new-turn', '关闭取消后继续相处的合成原话') + live.enqueue_uncovered() + task = asyncio.create_task(live.tick()) + await asyncio.sleep(0.3) # a refused tick would have reached the wire by now + report['tick_during_closing'] = { + 'gateway_arrived': server.arrived.is_set(), + 'gateway_posts': len(edges.contract.FakeGateway.requests) - posts_before, + 'llm_used': backend.llm_guard.used(), + 'batch': edges.batch_row(store, 'new-turn')} + close_release.set() + with suppress(asyncio.CancelledError): + await closing # the layer-owned close lands, then the cancel propagates + assert await edges.wait_until(lambda: live._closed) + report['finish_landed'] = {'closed': live._closed, + 'client_usable': edges.client_usable(backend), + 'live_workers': len(live._live), + 'close_calls': close_calls['count'], + 'closing_still_set': live._closing.is_set(), + 'batch': edges.batch_row(store, 'new-turn')} + if close_store: + store.close() # additional caller closure, recorded separately + server.release.set() + try: + await task + report['late_worker_error'] = None + except Exception as exc: # noqa: BLE001 — record, never hide + report['late_worker_error'] = f'{type(exc).__name__}: {exc}' + reopened = edges.Store(tmp / 'store.db') + report['persisted'] = {**edges.batch_row(reopened, 'new-turn'), + 'row_done': len(reopened.query('SELECT * FROM sem_row_done')), + 'llm_used': backend.llm_guard.used()} + reopened.close() + return report + finally: + close_release.set() + server.release.set() + if task is not None: + with suppress(BaseException): + await task + with suppress(BaseException): + await live.aclose() + store.close() + executor.shutdown(wait=True) + server.shutdown() + server.server_close() + thread.join() + + +async def waiter_cancel(tmp) -> dict: + """总管负例二同形:等锁的第二个关闭被取消,不得动第一关闭者的信号。""" + server, thread = edges.start_blocking_gateway() + backend, _ = edges.backend_for(tmp, 'waiter', server.server_address[1]) + store = edges.Store(tmp / 'store.db') + live = edges.SemanticMemory(store, backend) + edges.seed_turn(store, 'old', '已有活跃任务的合成原话') + live.enqueue_uncovered() + task = asyncio.create_task(live.tick()) + close_one = close_two = None + try: + assert await asyncio.to_thread(server.arrived.wait, 5) + close_one = asyncio.create_task(live.aclose(drain_timeout=0.05)) + assert await edges.wait_until(lambda: live._closing.is_set()) + close_two = asyncio.create_task(live.aclose()) # still WAITING for the lock + await asyncio.sleep(0.05) + close_two.cancel() + with suppress(asyncio.CancelledError): + await close_two + report = {'active_close_pending': not close_one.done(), + 'signal_after_waiter_cancel': live._closing.is_set()} + edges.seed_turn(store, 'new', '关闭期间不应新领任务的合成原话') + live.enqueue_uncovered() + await live.tick() # refused while the owner's close holds the layer + report['new_batch_during_closing'] = edges.batch_row(store, 'new') + report['original_batch_while_blocked'] = edges.batch_row(store, 'old') + posts_before_release = len(edges.contract.FakeGateway.requests) + server.release.set() + with suppress(BaseException): + await task + await close_one # drain completes, then the close lands once + report['after_release'] = { + 'original_batch': edges.batch_row(store, 'old'), + 'new_batch_still': edges.batch_row(store, 'new'), + 'row_done': len(store.query('SELECT * FROM sem_row_done')), + # BlockingGateway records a POST only when its answer is allowed + # through, so the ONE post after release is the original worker's + # in-flight request landing — the refused new batch adds none. + 'gateway_posts_after_release': + len(edges.contract.FakeGateway.requests) - posts_before_release, + 'client_closed': not edges.client_usable(backend)} + return report + finally: + server.release.set() + with suppress(BaseException): + await task + if close_one is not None: + with suppress(BaseException): + await close_one + with suppress(BaseException): + await live.aclose() + store.close() + server.shutdown() + server.server_close() + thread.join() + + +def evaluate(f1: dict, f2: dict, w: dict) -> None: + for tag, f in (("F1", f1), ("F2", f2)): + check(f"{tag} cancelled caller does not return before its close lands", + f["caller_done_after_cancel"] is False) + check(f"{tag} markers stay: closing set, not yet closed, client untouched", + f["after_cancellation"]["closing"] is True + and f["after_cancellation"]["closed"] is False + and f["after_cancellation"]["client_usable"] is True, + json.dumps(f["after_cancellation"], ensure_ascii=False)) + check(f"{tag} tick during closing claims nothing and sends nothing", + f["tick_during_closing"]["gateway_arrived"] is False + and f["tick_during_closing"]["gateway_posts"] == 0 + and f["tick_during_closing"]["llm_used"] == 0 + and f["tick_during_closing"]["batch"]["state"] == "queued" + and f["tick_during_closing"]["batch"]["owner"] is None + and f["tick_during_closing"]["batch"]["attempts"] == 0, + json.dumps(f["tick_during_closing"], ensure_ascii=False)) + check(f"{tag} layer-owned close lands exactly once, no live workers", + f["finish_landed"]["closed"] is True + and f["finish_landed"]["client_usable"] is False + and f["finish_landed"]["live_workers"] == 0 + and f["finish_landed"]["close_calls"] == 1 + and f["finish_landed"]["closing_still_set"] is True, + json.dumps(f["finish_landed"], ensure_ascii=False)) + check(f"{tag} no late error", f["late_worker_error"] is None, str(f["late_worker_error"])) + check(f"{tag} reopened batch intact and unbilled", + f["persisted"]["state"] == "queued" and f["persisted"]["owner"] is None + and f["persisted"]["row_done"] == 0 and f["persisted"]["llm_used"] == 0, + json.dumps(f["persisted"], ensure_ascii=False)) + check("W owner close still pending, waiter cancel keeps the signal", + w["active_close_pending"] is True and w["signal_after_waiter_cancel"] is True, + json.dumps({k: w[k] for k in ("active_close_pending", + "signal_after_waiter_cancel")}, ensure_ascii=False)) + check("W new batch refused during the owner's close", + w["new_batch_during_closing"]["state"] == "queued" + and w["new_batch_during_closing"]["owner"] is None, + json.dumps(w["new_batch_during_closing"], ensure_ascii=False)) + check("W original batch still actively owned while blocked", + w["original_batch_while_blocked"]["state"] == "pending" + and bool(w["original_batch_while_blocked"]["owner"]), + json.dumps(w["original_batch_while_blocked"], ensure_ascii=False)) + check("W original worker completes, one close, new batch untouched", + w["after_release"]["original_batch"]["state"] == "done" + and w["after_release"]["row_done"] == 1 + and w["after_release"]["new_batch_still"]["state"] == "queued" + and w["after_release"]["gateway_posts_after_release"] == 1 + and w["after_release"]["client_closed"] is True, + json.dumps(w["after_release"], ensure_ascii=False)) + + +async def main_async() -> dict: + with tempfile.TemporaryDirectory(prefix='hel894-close-') as directory: + root = Path(directory) + f1 = await finish_cancel(root / 'sdk-only', False) + f2 = await finish_cancel(root / 'finish', True) + w = await waiter_cancel(root / 'waiter') + evaluate(f1, f2, w) + REPORT['finish_cancel_sdk_only'] = f1 + REPORT['finish_cancel_then_store_close'] = f2 + REPORT['waiter_cancel'] = w + + +def main() -> int: + asyncio.run(main_async()) + REPORT["failures"] = FAILURES + out = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / 'hel894-close.json' + out.write_text(json.dumps(REPORT, ensure_ascii=False, indent=2), encoding='utf-8') + print(json.dumps({"ok": not FAILURES, "checks": len(REPORT.get("checks", [])), + "failures": FAILURES, "out": str(out)}, ensure_ascii=False)) + return 1 if FAILURES else 0 + + +if __name__ == '__main__': + raise SystemExit(main())