HEL-889 rework: shutdown never closes under a live worker, and a queued-cancelled worker is released by the authoritative future state — SemanticMemory now runs batch workers on its OWN dedicated ThreadPoolExecutor and keeps each work item's concurrent.futures.Future: cancelling the awaiting tick propagates to that future, and its post-cancel state is the deterministic queued/started oracle (the manager's review_hel886_edges.py reproduced the old false-liveness on the shared default executor: register _live, await to_thread, executor busy -> cancel tick cancels the QUEUED item, _run and its finally never run, _live=1 forever with the batch pending and recovery permanently skipping a worker that does not exist, restart the only way out; now a CANCELLED future proves nothing ever ran: _release_never_started removes the registry entry idempotently and returns the batch to queued with its attempt restored and zero sends, while a running/finished future keeps HEL-886 semantics — the worker thread owns the batch fate, single send, no reclaim, no resend), and aclose becomes a real ownership protocol instead of a bounded promise it could break: a closing flag makes tick refuse new claims and makes both backends' _add_group_sync check should_stop BEFORE each row's wire work (a _ShutdownAbort at a boundary keeps finished rows' sem_row_done proofs and requeues only the unsent remainder — never a mid-row cut, and a single-row batch still completes done); never-started workers are cancelled out of the executor queue under the same authoritative CANCELLED proof; started workers finish their current row and flush, and aclose WAITS for every live worker to actually exit before backend/executor close — drain_timeout only bounds the polite phase (after expiry: honest warning, keep waiting; a live worker is never treated as dead), bounded in practice because Mem0Backend now sets the gateway OpenAI client's timeout (gateway_timeout config, default 60s) instead of the 600s default that made the drain effectively open-ended; a cancelled aclose closes NOTHING (shielded finish, closing signal reset, layer stays usable), concurrent aclose calls serialize on an asyncio.Lock and are idempotent, and the app lifespan comment now states the ownership contract — the manager's fixed-SDK reproduction of the OLD timeout branch (loopback gateway accepts the first HTTP then withholds the answer, aclose(drain_timeout=0.05) returns with the worker alive, app closes the store, late worker dies on 'QdrantLocal instance is closed'/'Cannot operate on a closed database', reopen shows pending/row_done=0/llm_used=1) is closed: aclose does not return while the worker is alive, the worker's writes land BEFORE the app-order store.close(), and the reopened store shows done + row_done=1 + full entry_ids with llm_used=1 and zero late errors; crash semantics unchanged and still honest (unknown wire outcomes billed, proof-gated retries, strict-once not claimed); verification: 294 python tests pass on 3.11.16 venv + requirements.lock offline (7 new tests/test_rework_hel889.py cases, all barrier-driven real product paths: queued-cancel release + in-process recovery via injected single-worker executor / shutdown-timeout never closes under the live worker and flushes before app-order store close / between-rows abort requeues and the next process sends ONLY the missing row / shutdown-before-start zero sends then resumes / cancelled aclose leaves everything open / concurrent aclose serializes / closed layer refuses new claims), ruff clean (src/tests/tools), no frontend changes (frontend checks not re-run, stated honestly); pinned mem0 2.2.1 on the deterministic boundary (512-dim stand-in before TextEmbedding construction, loopback-only): new tools/verify_shutdown_queued_hel889.py 12/12 (Q1 queued-cancel phantom released and recovered in-process with the manager's 41s lease probe, S1 fixed-SDK shutdown-timeout branch, S2 between-rows abort + missing-row-only resume proven by gateway POST counts, S3 cancelled aclose, S4 concurrent aclose), the manager's review_hel886_edges.py re-run VERBATIM on the pristine f1b50ad first reproduced both defects exactly (docs/rework/hel889/edges-verbatim-before-fix-f1b50ad.json matches the manager's independent JSON), the same-shape rerun review_hel886_edges_rerun_hel889.py now passes both scenarios with every original result key (queued: done/attempts=1/registered 0/entries 1/row_done 1; timeout: aclose_returned_while_worker_alive=false, late_worker_error null, persisted done+entry_ids+row_done=1, llm_used=1) while the verbatim original stops at its own premise assert executor._work_queue.qsize()==1 — batch workers no longer ride the loop default executor, the encoded defect is structurally gone (original negative and baseline kept); regressions all green: verify_inflight_lifecycle_hel886.py 6/6 (single-send preserved), verify_semantic_recovery_hel885.py 7/7, verify_mem0_real_hel874.py 12/12, check_release_offline_hel882.py R1-R7 15/15, both manager review_hel882_{partial,extra}.py scripts re-run verbatim pass, review_hel885_inflight.py still fails at its 2-add barrier exactly as documented in HEL-886; runbook §4 gains the HEL-889 ownership/queued-cancel semantics, config/semantic.example.yaml documents gateway_timeout, docs/requirements/handoff-HEL-889.json written, dual-target requirement checks 4/4 (origin/main and origin/agent/agent/de8874a3803b, with and without handoff); zero real LLM, zero real embeddings, zero non-loopback outbound, authoritative ledgers and freezes untouched, not deployed, PR not merged, no visual changes

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
zonggong
2026-10-27 01:24:11 +08:00
co-authored by multica-agent
parent f1b50ad91a
commit 440d95cad8
28 changed files with 2178 additions and 48 deletions
+3
View File
@@ -49,6 +49,9 @@ user_scope: cybergril
gateway_base_url: http://192.168.200.11:8731/v1
gateway_model: halogen-qwen3.8-flash-next
gateway_key: cybergril-local-test
# 每次网关调用的硬超时(秒,HEL-889):关闭排空阶段因此有界——已被接受但
# 长期不答的请求不会把 worker 与进程关闭无限挂住。默认 60,一般不改。
gateway_timeout: 60
# 统一请求闸:产品进程会把 router 的 PersistentBudget 传给后端,SDK 内部提取
# LLM 每次发送前在 "semantic" 类别 + 日 token 池里原子预占(models.yaml 的
+53
View File
@@ -0,0 +1,53 @@
{
"baseline_version": "1.11",
"read_commit": "f1b50ad91ad8c856f28383ee59eddb6547d9c586",
"task": "HEL-889 返工(总管对 HEL-886 候选 f1b50ad 独立复审确认的两个生命周期边界缺口一次修完):关闭超时不得把仍可能写入的活 worker 当死而关掉其依赖(总管实际固定 SDK 复现:回环网关先接受第一 HTTP 未答,aclose(drain_timeout=0.05) 返回时 worker 仍活,按 app 顺序关 Store 后放行,Qdrant 报 QdrantLocal instance is closed、worker 报 ProgrammingError: Cannot operate on a closed database,重开批次仍 pending/row_done=0/llm_used=1——仍活进程主动关资源造成的丢落盘窗口,不能归入真崩溃结果未知)、执行器排队阶段取消不得永久假活跃(先登记 _live 再 await to_thread,执行器忙时取消 tick 会取消排队 future,_run/finally 从未运行,注册表留下不存在的 worker,批次 pending 卡死且之后恢复一直跳过,只能重启;单 worker 执行器+41 秒时钟前进+recover+tick 复现 _live=1/entries=0/row_done=0/队列空);零真实调用、零真实嵌入、零下载、不部署、不合并、不改视觉、不碰权威三账、不新增任何 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(基于 f1b50ad 追加,PR#11 只追加不强推不合并)完成两项修正:1) 关闭所有权协议——批 worker 移入 SemanticMemory 专用执行器(本层持有 concurrent.futures.Future,即权威的排队/已启动判定,且长批次不再挤占 loop 共享默认执行器);aclose 先置 closing 信号:tick 拒新领、后端 _add_group_sync 在每行发送前查 should_stop 只在行边界中止(已完行保留 sem_row_done 证明,未发行回 queued,绝无在飞中断)、未启动 worker 直接按 CANCELLED 权威取消(从未运行=零出站,安全回队并复原 attempts);随后等待所有活跃 worker 真实退出才关 backend 与执行器——drain_timeout 只界定礼貌阶段(超时如实告警并继续等,绝不把活 worker 当死),Mem0Backend 构造时给网关 OpenAI 客户端设 gateway_timeout(默认 60s,可配)保证排空有界;aclose 被取消时什么都不关且 closing 复位可续用,并发 aclose 用 asyncio.Lock 串行化且幂等,完成端关闭 asyncio.shield 保护;真崩溃语义不变(保守留账、只发无证明行、不宣称严格一次)。2) 排队取消恢复——_LiveWorker 增加 started 事件与 future 槽位区分排队/已启动/已完成;取消等待协程时以 future.cancelled() 权威判定:从未运行则立即释放假活跃注册项并回队(attempts 复原、零发送),释放执行器、时钟前进 41 秒后 recover+tick 进程内完成,无需重启;已开始/已完成则维持 HEL-886 语义(worker 线程写终态、并发 tick 不重发,不回到双发)。保留全部已通过行为(回读、隐私、单行恢复、预算硬闸、未知预占不退款、全完成零预算收尾)。app lifespan 注释同步为 HEL-889 所有权口径。验证:python 3.11.16 venv + requirements.lock 离线 294 pytest 全过(新增 tests/test_rework_hel889.py 7 例,全部屏障驱动真实产品路径:排队取消恢复/关闭超时不关活 worker 且落盘先于关库/行间中止下一进程只发缺行/未启动即关闭零发送并可续跑/关闭被取消什么都不关/并发关闭串行化/关闭后拒新领),ruff 0 错(src/tests/tools);固定 mem0 2.2.1 确定性替身实跑 tools/verify_shutdown_queued_hel889.py 12/12(Q1 排队取消、S1 关闭超时分支固定 SDK 实跑、S2 行间中止、S3 关闭被取消、S4 并发关闭);总管 review_hel886_edges.py 原负例与基线保留(edges-verbatim-before-fix-f1b50ad.json 与总管独立结果一致),同形复跑 review_hel886_edges_rerun_hel889.py 全过(queued:done/attempts=1/registered 0/entries 1/row_done 1;timeout:aclose_returned_while_worker_alive=false/late_worker_error=null/persisted done+entry_ids+row_done=1/llm_used=1),原样复跑如实停在其自身前提断言(批 worker 不再走 loop 默认执行器,docs/rework/hel889/original-verbatim-after-fix.log);回归 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 原样复跑通过、review_hel885_inflight.py 仍在 2-add 屏障如预期失败(单发保持);零真实调用、零真实嵌入、零非回环出站,权威三账与冻结余额未写,未部署未合并未交体验地址,不改视觉",
"acceptance": [
"P1 修复(固定 SDK 实跑关闭超时分支):第一 HTTP 已接受未答时 aclose(drain_timeout=0.05) 在 worker 仍活时绝不返回;应答放行后 worker 完成落盘,aclose 才返回、才关 client;按 app 顺序关库重开:批 done、row_done=1、entry_ids 完整、llm_used=1、无任何晚到错误(docs/rework/hel889/edges-real-sdk-hel889.json S1 + HEL-889-edges-rerun-fixed.json shutdown_timeout;修复前基线 aclose_returned_while_worker_alive=true/ProgrammingError/pending/row_done=0 保留对照)",
"P1 关闭取消/并发:排空中的 aclose 被取消什么都不关(client 可用、批次仍 pending、closing 复位可续用),worker 正常完成后再次 aclose 干净收尾;两个 aclose 并发串行化、排空一次、资源只关一次、第三次调用幂等即返(S3/S4 + tests/test_rework_hel889.py)",
"P2 修复(排队取消):单 worker 执行器占住、批次仅入队未启动即取消 tick——假活跃注册项立即释放、批次回 queued 且 attempts 复原、零出站;释放执行器、推进 41 秒后 recover+tick 进程内完成:done、1 条目、1 sem_row_done、注册表清零,无需重启(Q1 + 同形复跑 queued_cancel;修复前基线 pending/_live=1/entries=0/row_done=0 保留对照)",
"已开始取消仍单发:处理中取消/跨租约仍活跃不重发不回收(HEL-886 L1/L2 回归 6/6),review_hel885_inflight.py 仍在 2-add 屏障如预期失败,未回退双发",
"行间中止与恢复:两行批次关闭中止保留第 1 行完成证明、批次回 queued/shutdown_between_rows、关闭期间网关 POST 不新增;下一进程同账同库只发缺行(POST 仅 +1)后 done 且两行 entry_ids 完整(S2 + pytest)",
"原有能力全部保留:回读/隐私/单行恢复/预算硬闸/未知预占不退款/全完成零预算收尾/真死租约回收(recovery-hel885-rerun 7/7、inflight-hel886-rerun 6/6、contract-hel874-rerun 12/12、release-offline R1–R7 15/15、总管 882 两脚本原样复跑通过)",
"工程检查:294 pytest(含 7 新例)全过、ruff 0 错(src/tests/tools);本卡不改前端,未重跑前端 42 项/构建,不以历史数字冒充本轮实测;双目标需求检查 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 段已如实写明)",
"R5 语音 HEL-878/879、R6 天气/素材/完整备份、R7 有条件观察承接不变;视觉仍交原作者,本卡未改视觉;真实体验效果待体验地址交付后由白栖知判断"
],
"requirement_changes": [],
"verification": [
"分支 hel-870-assembly 追加提交(最终 head 见交付评论),PR#11 只追加未强推未合并;视觉总监分支未覆盖",
"python 3.11.16 venv + requirements.lock 离线:294 项测试全过(新增 tests/test_rework_hel889.py 7 例,全部屏障驱动真实产品路径,无预置死租约冒充);ruff 0 错(src/tests/tools);本卡未改前端故未重跑前端检查,如实注明",
"固定 mem0 2.2.1 安装(hel857-venv 3.10.12)确定性替身实跑(docs/rework/hel889/):tools/verify_shutdown_queued_hel889.py 12/12(edges-real-sdk-hel889.json);总管脚本基线原样复跑 edges-verbatim-before-fix-f1b50ad.json 与总管独立结果一致;同形复跑 review_hel886_edges_rerun_hel889.py 全过(HEL-889-edges-rerun-fixed.json);原样复跑停在其自身前提断言(original-verbatim-after-fix.log,原负例与基线不删)",
"回归: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 原样复跑通过;review_hel885_inflight.py 原样复跑仍在 2-add 屏障如预期失败(单发保持,与 HEL-886 存档口径一致)",
"python3 scripts/check_requirements.py --base-ref origin/main [--handoff docs/requirements/handoff-HEL-889.json] 与 --base-ref origin/agent/agent/de8874a3803b [--handoff …] 四项通过"
]
}
+59
View File
@@ -0,0 +1,59 @@
# HEL-889 返工证据 · 关闭所有权与排队取消
总管对 HEL-886 head `f1b50ad91ad8c856f28383ee59eddb6547d9c586` 独立复审
(`review_hel886_edges.py`,附件与本目录 `edges-verbatim-before-fix-*`)确认的两个
缺口,在本 head 修复并复验。零真实出站、零真实嵌入、零下载;全部回环 +
确定性 512 维替身(TextEmbedding 构造前安装);未写权威三账、未改冻结余额、
未部署、未合并、未改视觉。
## 修复前基线(本卡在未改动的 f1b50ad 上原样复跑总管脚本)
`edges-verbatim-before-fix-f1b50ad.json`:与总管独立结果一致——
- queued_cancel:batch pending/owner 在/attempts=1、`registered_workers=1`、
entries 0、row_done 0(假活跃永久卡死,只能重启)。
- shutdown_timeout:`aclose_returned_while_worker_alive=true`,晚到 worker
`ProgrammingError: Cannot operate on a closed database.`,重开仍
pending/row_done=0/llm_used=1(丢落盘窗口)。
## 修复(src/cybergril/memory/semantic.py)
1. **P1 关闭所有权**:批 worker 移入本层专用执行器;`aclose` 先置 closing
(tick 拒新领、worker 只在行边界前停、未启动项直接从队列取消——
concurrent.futures CANCELLED 是权威「从未运行」证明);随后等待所有活跃
worker 真实退出才关 backend/执行器。`drain_timeout` 只界定礼貌阶段,
绝不授权在活 worker 下关资源;网关客户端超时(`gateway_timeout`,默认
60s)保证等待有界。aclose 被取消时什么都不关、信号复位;并发 aclose
串行化且幂等。真正的进程崩溃仍按 HEL-885/886 保守留账,不宣称严格一次。
2. **P2 排队取消**:`_LiveWorker` 区分 queued/started;取消等待协程时以
`future.cancelled()` 权威判定——从未运行则立即释放注册项并把批次回
queued(attempts 复原、零发送),可进程内 recover+tick 完成;已开始则
维持 HEL-886 单发语义(worker 线程自己写终态)。
## 修复后验证
- `edges-real-sdk-hel889.json`(tools/verify_shutdown_queued_hel889.py,固定
mem0 2.2.1 实跑)12/12:Q1 排队取消→释放→进程内完成;S1 关闭超时分支
aclose 在 worker 活着时绝不返回、完成后落盘才关、app 顺序关库重开
done/row_done=1/llm_used=1、无晚到错误;S2 行间中止保留证明、下一进程
只发缺行(POST 仅 +1)done 且两行 entry 完整;S3 被取消的关闭什么都不关;
S4 并发关闭串行化只关一次。
- `HEL-889-edges-rerun-fixed.json` + `review_hel886_edges_rerun_hel889.py`:
总管原脚本同形复跑全过(queued:done/attempts=1/registered 0/entries 1/
row_done 1;timeout:`aclose_returned_while_worker_alive=false`、
late_worker_error null、persisted done+entry_ids+row_done=1、llm_used=1)。
原样复跑在 `original-verbatim-after-fix.log` 如实停在它自己的前提断言
`assert live._live and executor._work_queue.qsize() == 1`——批 worker 已
不再走 loop 默认执行器,该负例的前提结构性消失(原负例与基线保留
不删)。
- 回归:`inflight-hel886-rerun.json` 6/6、`recovery-hel885-rerun.json` 7/7、
`contract-hel874-rerun.json` 12/12、`release-offline-hel889.json` R1–R7
15/15、总管 `review_hel882_{partial,extra}.py` 原样复跑通过
(`manager-review-*-rerun.{json,log}`;extra 内 uv rc=2 为其自身预期负例)。
- `inflight885-verbatim-after-fix.log`:总管 review_hel885_inflight.py 原样
复跑仍在其 2-add 屏障断言失败(单发语义保持,与 HEL-886 存档一致;脚本
自身 finally 中止后不关服务器线程,进程需外部结束,日志截取自其预期
失败点)。
- 产品测试:python 3.11.16 venv + requirements.lock 离线 294 pytest 全过
(新增 tests/test_rework_hel889.py 7 例,全部屏障驱动真实路径)、
ruff 0 错(src/tests/tools)。
@@ -0,0 +1,172 @@
{
"started": "2026-10-26T17:05:47Z",
"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:05:48Z",
"gateway_requests_total": 3,
"failures": [],
"temp_dir": "/tmp/multica-task-2867647507/hel874-real-sdk-e1xct75p"
}
@@ -0,0 +1,24 @@
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]
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
{
"out": "docs/rework/hel889/contract-hel874-rerun.json",
"failures": [],
"checks": {
"C1_construct": true,
"C2_add_anchor_payload": true,
"C2_add_user_scope": true,
"C2_add_ledger_shape": true,
"C3_extraction_input_set": true,
"C3b_unshared_canary_never_outbound": true,
"C4_search_filters": true,
"C4_search_single_debit": true,
"C6_concurrency_cap": true,
"C7_reopen_after_close": true,
"C5_embed_zero_refuses": true,
"C5_llm_zero_refuses": true
}
}
@@ -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\": \"[\\\"afa7bce8-07f7-49ea-a65e-069ebb2baa02\\\"]\"}"
},
{
"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\": \"[\\\"afa7bce8-07f7-49ea-a65e-069ebb2baa02\\\"]\", \"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\": \"[\\\"11c68b0b-78d4-477f-a553-0ea64da583ab\\\", \\\"c70134d2-99cf-4314-8dae-01d86e82e99e\\\"]\", \"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\": \"[\\\"8a11970a-1f3b-4c9e-b9fa-ef5ef9c089e4\\\"]\", \"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": "aa47821695b292f280306d12a8690ad1",
"attempts": 1,
"entry_ids": null
},
"client_usable": true
},
"before_store_close": {
"state": "done",
"reason": null,
"owner": null,
"attempts": 1,
"entry_ids": "[\"afa7bce8-07f7-49ea-a65e-069ebb2baa02\"]"
},
"late_worker_error": null,
"persisted": {
"state": "done",
"reason": null,
"owner": null,
"attempts": 1,
"entry_ids": "[\"afa7bce8-07f7-49ea-a65e-069ebb2baa02\"]",
"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": "[\"11c68b0b-78d4-477f-a553-0ea64da583ab\", \"c70134d2-99cf-4314-8dae-01d86e82e99e\"]",
"row_done": 2,
"gateway_posts_resume": 2
}
},
"cancelled_aclose": {
"after_cancel": {
"client_usable": true,
"batch": {
"state": "pending",
"reason": null,
"owner": "1ad7597b3b7bd8df701cb56bfed9ea87",
"attempts": 1,
"entry_ids": null
},
"closing_cleared": true
},
"after_worker": {
"state": "done",
"reason": null,
"owner": null,
"attempts": 1,
"entry_ids": "[\"c3bbac6e-c569-4880-aa51-774768922365\"]"
},
"client_usable_after_real_close": false
},
"concurrent_aclose": {
"batch": {
"state": "done",
"reason": null,
"owner": null,
"attempts": 1,
"entry_ids": "[\"8a11970a-1f3b-4c9e-b9fa-ef5ef9c089e4\"]",
"row_done": 1
},
"client_usable_after_close": false
},
"failures": []
}
@@ -0,0 +1,12 @@
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]
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 BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
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 BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
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 BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
{"ok": true, "checks": 12, "failures": [], "out": "docs/rework/hel889/edges-real-sdk-hel889.json"}
+34
View File
@@ -0,0 +1,34 @@
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]
{
"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": "[\"d3c48e4b-205b-4066-a570-e5909737138c\"]"
},
"late_worker_error": null,
"persisted_batch": {
"state": "done",
"entry_ids": "[\"d3c48e4b-205b-4066-a570-e5909737138c\"]"
},
"persisted_row_done": 1,
"llm_used": 1
}
}
@@ -0,0 +1,30 @@
{
"head": "f1b50ad91ad8c856f28383ee59eddb6547d9c586",
"real_llm": 0,
"real_embeddings": 0,
"queued_cancel": {
"batch": {
"state": "pending",
"owner": "0698a359dda0416bb7b7b44e82ce2601",
"attempts": 1
},
"registered_workers": 1,
"stored_entries": 0,
"row_done": 0,
"executor_queue_size": 0
},
"shutdown_timeout": {
"aclose_returned_while_worker_alive": true,
"batch_before_store_close": {
"state": "pending",
"entry_ids": null
},
"late_worker_error": "ProgrammingError: Cannot operate on a closed database.",
"persisted_batch": {
"state": "pending",
"entry_ids": null
},
"persisted_row_done": 0,
"llm_used": 1
}
}
@@ -0,0 +1,36 @@
semantic shutdown drain: 1 live batch worker(s) still running after 0s — closing anyway, their outcome stays unknown
semantic shutdown drain: 1 live batch worker(s) still running after 0s — closing anyway, their outcome stays unknown
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 88b59cb3-b8e7-4fda-be99-9384739784c1: 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
{
"head": "f1b50ad91ad8c856f28383ee59eddb6547d9c586",
"real_llm": 0,
"real_embeddings": 0,
"queued_cancel": {
"batch": {
"state": "pending",
"owner": "0698a359dda0416bb7b7b44e82ce2601",
"attempts": 1
},
"registered_workers": 1,
"stored_entries": 0,
"row_done": 0,
"executor_queue_size": 0
},
"shutdown_timeout": {
"aclose_returned_while_worker_alive": true,
"batch_before_store_close": {
"state": "pending",
"entry_ids": null
},
"late_worker_error": "ProgrammingError: Cannot operate on a closed database.",
"persisted_batch": {
"state": "pending",
"entry_ids": null
},
"persisted_row_done": 0,
"llm_used": 1
}
}
@@ -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': '2ef009e061a90c98547e30ee2d034344'} batch_concurrent=pending final={'state': 'done', 'reason': None, 'entry_ids': '[\"43a823a4-f5ca-4e5b-a7c4-087ab5b906a6\"]'} 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': '317012c028229e233165848dee10ccb3'} batch_concurrent=pending final={'state': 'done', 'reason': None, 'entry_ids': '[\"c1885079-9900-4694-bfe8-24892aa8fd8a\"]'} 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': '[\"94a9bb71-a1fa-4f73-92f1-92899035a819\"]'} after={'state': 'done', 'reason': None, 'entry_ids': '[\"94a9bb71-a1fa-4f73-92f1-92899035a819\"]'} 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": []
}
@@ -0,0 +1,23 @@
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]
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
LLM extraction failed: semantic_llm_budget_exhausted
semantic batch 1 requeued (budget): LLM extraction failed: semantic_llm_budget_exhausted
semantic batch 1 requeued (budget): semantic_llm_budget_exhausted
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
{
"out": "docs/rework/hel889/inflight-hel886-rerun.json",
"failures": [],
"checks": {
"L1_cancel_single_send_and_full_record": true,
"L2_lease_single_send_and_full_record": true,
"L3_shutdown_drains_live_worker_before_close": true,
"L4a_all_done_finalizes_without_new_budget": true,
"L4b_partial_keeps_the_hard_gate": true,
"L5_dead_owner_lease_still_recovers": true
}
}
@@ -0,0 +1,15 @@
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]
Traceback (most recent call last):
File "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-889-01bb190e1c83/workdir/review_hel885_inflight.py", line 143, in <module>
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-889-01bb190e1c83/workdir/review_hel885_inflight.py", line 102, in main
'scenarios': [await scenario('cancel'), await scenario('lease')],
File "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-889-01bb190e1c83/workdir/review_hel885_inflight.py", line 84, in scenario
assert await asyncio.to_thread(worker_done.wait, 8)
AssertionError
@@ -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] <COMMAND>\n\nFor more information, try '--help'."
}
}
@@ -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] <COMMAND>\n\nFor more information, try '--help'."
}
}
@@ -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:06:31.737649+00:00",
"updated_at": "2026-10-26T17:06:31.737649+00:00"
}
],
"claimed_completed_message_ids": [
2
],
"batch_after_resume": {
"state": "done",
"attempts": 1,
"reason": null,
"entry_ids": "[\"4e45788c-abe9-4585-943c-ae0ea48b1044\", \"37d81794-2bb5-4143-b347-ff5de238a064\"]"
},
"loopback_requests_after_resume": 2,
"unsent_user_row_actually_sent": true
}
@@ -0,0 +1,53 @@
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]
LLM extraction failed: semantic_llm_budget_exhausted
semantic batch 1 requeued (budget): LLM extraction failed: semantic_llm_budget_exhausted
{
"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:06:31.737649+00:00",
"updated_at": "2026-10-26T17:06:31.737649+00:00"
}
],
"claimed_completed_message_ids": [
2
],
"batch_after_resume": {
"state": "done",
"attempts": 1,
"reason": null,
"entry_ids": "[\"4e45788c-abe9-4585-943c-ae0ea48b1044\", \"37d81794-2bb5-4143-b347-ff5de238a064\"]"
},
"loopback_requests_after_resume": 2,
"unsent_user_row_actually_sent": true
}
@@ -0,0 +1,10 @@
Traceback (most recent call last):
File "/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-889-01bb190e1c83/workdir/review_hel886_edges.py", line 117, in <module>
'queued_cancel': asyncio.run(queued_cancel(tmp)),
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-889-01bb190e1c83/workdir/review_hel886_edges.py", line 43, in queued_cancel
assert live._live and executor._work_queue.qsize() == 1
AssertionError
@@ -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=[\"789be5fc-001c-4fc7-a109-69fb62f5b4e1\", \"77e7ce70-7309-4ced-ba57-81bff84edd3a\"]"
},
{
"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": []
}
@@ -0,0 +1,20 @@
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]
LLM extraction failed: semantic_llm_budget_exhausted
semantic batch 1 requeued (budget): LLM extraction failed: semantic_llm_budget_exhausted
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
Failed to load BM25 encoder: verify boundary forbids non-loopback connection: 198.18.7.201
{
"out": "docs/rework/hel889/recovery-hel885-rerun.json",
"failures": [],
"checks": {
"S0_positive_caps_without_authority_fail_closed": true,
"S1_p1_first_tick_partial": true,
"S2_p1_restart_sends_only_missing_row": true,
"S3a_lease_expired_batch_recovers": true,
"S3b_concurrent_ticks_single_send": true,
"S4a_aged_unknown_llm_reservation_kept": true,
"S4b_aged_unknown_embed_reservation_kept": true
}
}
@@ -0,0 +1,86 @@
{
"started": "2026-10-26T17:06:16Z",
"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-2867647507/hel882-release-jpq_z0co/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:06:19Z"
}
@@ -0,0 +1,16 @@
PASS R1_checkout_fresh_dir — cloned tracked source into /tmp/multica-task-2867647507/hel882-release-jpq_z0co/cybergril-hel874/current
PASS R2_service_imports_product
PASS R6_mem0_coimport_status_recorded — import mem0 → ModuleNotFoundError: No module named 'mem0' (resolution path in deploy/hel874-release.md §4; no download in this check)
PASS R7_pip_download_command_exists — /home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87/workdir/hel857-venv/bin/python -m pip download --help → rc=0
PASS R7_removed_uv_pip_download_still_absent — uv pip download --help → rc=2 (kept absent on purpose; do not re-document it)
PASS R2_service_serves_health — version=R4-assembly semantic=stub
PASS R3_create_status_recorded — create status=201(409=前次运行的档案仍在,也是保留数据的表现)
PASS R3_dialogue_refused_honestly — 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'
PASS R4_service_restarts_on_same_data — epoch=2
PASS R5_epoch_bumped_on_reopen — 1 → 2
PASS R4_companion_created_offline — status=409
PASS R4_dialogue_stream_http — 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'
PASS R4_messages_roundtrip — roles=['user', 'user', 'companion']
PASS R5_data_dir_preserved — ['companion.db']
PASS R5_companion_row_survives_restart — companion rows=1
{"out": "docs/rework/hel889/release-offline-hel889.json", "failures": []}
@@ -0,0 +1,158 @@
"""HEL-889 rerun of the manager's review_hel886_edges.py — same scenarios,
adjusted to the FIXED contracts.
Adjustments vs the original (before/after documented, negative preserved):
1. queued_cancel: the congestion blocker now occupies the PRODUCT's dedicated
batch executor (``SemanticMemory(executor=...)`` — HEL-889 moved batch
workers off the loop's shared default executor onto a dedicated one this
layer owns, precisely so the queue/started truth is observable). The
original blocked the loop default executor because ``to_thread`` put the
worker there; that premise no longer holds, and re-run verbatim the
original stops at its own ``assert live._live and
executor._work_queue.qsize() == 1`` (original-verbatim-after-fix.log — the
queued defect it encoded is gone). This rerun keeps every step of the
manager's sequence: cancel the tick while queued, release, clock +41s,
recover + tick, and the same result fields.
2. shutdown_timeout: identical gateway, identical ``aclose(drain_timeout=0.05)``
(the default-120s branch). The original released the wire barrier only
AFTER ``store.close()`` — an ordering the fixed ownership protocol forbids
(aclose returns only once the live worker exited, so store.close() can
never precede the worker's flush). The barrier is therefore released by a
timer thread 0.3s into the drain; every result key of the original is kept.
Everything else — real pinned SDK, real Qdrant, real OpenAI client,
deterministic 512-dim stand-in installed before TextEmbedding construction,
loopback-only gateway, temp ledgers — is unchanged.
"""
import asyncio
import concurrent.futures
import importlib.util
import json
import sys
import tempfile
import threading
from pathlib import Path
ROOT = Path(__file__).resolve().parent
REPO = ROOT / 'CyberGril'
sys.path.insert(0, str(REPO / 'src'))
spec = importlib.util.spec_from_file_location('contract', REPO / 'tools/verify_mem0_real_hel874.py')
c = importlib.util.module_from_spec(spec)
spec.loader.exec_module(c)
c.install_deterministic_boundary()
from cybergril.memory.semantic import SemanticMemory, StubBackend, Mem0Backend
from cybergril.memory.store import Store
def seed(store):
with store.conn:
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
"(1,'user','独立关闭边界合成原话','edge','sent')")
async def queued_cancel(tmp):
store = Store(tmp / 'queued.db')
seed(store)
clock = [1000.0]
backend = StubBackend()
# HEL-889: batch workers run on the layer's OWN executor — the manager's
# congestion now blocks exactly that one.
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
entered, release = threading.Event(), threading.Event()
blocker = executor.submit(lambda: (entered.set(), release.wait(8)))
assert entered.wait(2)
live = SemanticMemory(store, backend, clock=lambda: clock[0], executor=executor)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
for _ in range(500):
if live._live and all(not h.started.is_set() for h in live._live.values()):
break
await asyncio.sleep(0.01)
assert live._live and executor._work_queue.qsize() == 1
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
release.set()
blocker.result(timeout=2)
await asyncio.sleep(0.05)
clock[0] += 41
live.recover()
await live.tick()
result = {'batch': dict(store.query_one('SELECT state,owner,attempts FROM sem_batch')),
'registered_workers': len(live._live), 'stored_entries': len(backend._entries),
'row_done': len(store.query('SELECT * FROM sem_row_done')),
'executor_queue_size': executor._work_queue.qsize()}
# There is no worker remaining: only a false registry handle prevents recovery.
await live.aclose(drain_timeout=0)
store.close()
executor.shutdown(wait=True)
return result
async def shutdown_timeout(tmp):
arrived, release = threading.Event(), threading.Event()
class Gateway(c.FakeGateway):
def do_POST(self):
arrived.set()
if not release.wait(8):
raise RuntimeError('barrier timed out')
super().do_POST()
server = c._Server(('127.0.0.1', 0), Gateway)
server_thread = threading.Thread(target=server.serve_forever)
server_thread.start()
c.make_ledger(tmp / 'ledger.db', cap=100, llm_cap=10)
cfg = c.config_for(tmp, tmp / 'ledger.db', port=server.server_address[1], cap=100, llm_cap=10)
backend = Mem0Backend(cfg)
store = Store(tmp / 'shutdown.db')
seed(store)
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
try:
assert await asyncio.to_thread(arrived.wait, 3)
# Same code branch as the default 120s deadline, shortened for a bounded test.
closing = asyncio.create_task(live.aclose(drain_timeout=0.05))
await asyncio.sleep(0.3) # deadline long past, worker still alive
result = {'aclose_returned_while_worker_alive': closing.done(),
'batch_before_store_close': dict(store.query_one(
'SELECT state,entry_ids FROM sem_batch'))}
# The fixed protocol never closes under a live worker: the wire answer
# must arrive (here via timer) BEFORE aclose can return and the app
# order store.close() runs.
threading.Timer(0.2, release.set).start()
await closing
result['batch_before_store_close'] = dict(store.query_one(
'SELECT state,entry_ids FROM sem_batch'))
store.close()
try:
await task
result['late_worker_error'] = None
except Exception as exc:
result['late_worker_error'] = f'{type(exc).__name__}: {exc}'
check = Store(tmp / 'shutdown.db')
result['persisted_batch'] = dict(check.query_one('SELECT state,entry_ids FROM sem_batch'))
result['persisted_row_done'] = len(check.query('SELECT * FROM sem_row_done'))
result['llm_used'] = backend.llm_guard.used()
check.close()
return result
finally:
release.set()
server.shutdown()
server.server_close()
server_thread.join()
with tempfile.TemporaryDirectory(dir=ROOT) as td:
tmp = Path(td)
report = {'head': 'HEL-889 same-shape rerun of review_hel886_edges.py (fixed tree)',
'real_llm': 0, 'real_embeddings': 0,
'queued_cancel': asyncio.run(queued_cancel(tmp)),
'shutdown_timeout': asyncio.run(shutdown_timeout(tmp))}
(ROOT / 'HEL-889-edges-rerun-fixed.json').write_text(
json.dumps(report, ensure_ascii=False, indent=2))
print(json.dumps(report, ensure_ascii=False, indent=2))
+13
View File
@@ -75,6 +75,19 @@ docs/rework/hel874/erratum-hel882.json(旧 runs 有真实本地嵌入,下限
HTTP/零新嵌入/cap 不变即 done 且 entry_ids 完整;仍有缺行时维持原硬闸拒绝,
不为收尾加 cap 或退款未知预占。
**HEL-889 关闭所有权与排队取消(docs/rework/hel889/,固定安装本体验证)**:
- `aclose` 绝不在仍可能写入的 worker 下关资源:批 worker 跑在本层专用执行器,
关闭先置信号(拒新领、只在行边界前停、未启动项按 concurrent.futures
CANCELLED 权威取消——从未运行即零发送,可安全回队),再等所有活跃 worker
真实退出才关向量库 client 与执行器;`drain_timeout` 只界定礼貌阶段(超时后
如实告警并继续等),网关客户端超时(`gateway_timeout`,默认 60 秒)保证
等待有界。被取消的关闭什么都不关;并发关闭串行化且幂等。
- 排队阶段取消不再永久假活跃:取消等待协程时以 `future.cancelled()` 区分
「从未运行」(立即释放注册项、批次回 queued、attempts 复原,进程内即可
recover+tick 完成,无需重启)与「已开始」(维持单发语义,worker 线程自己
写终态)。真崩溃仍保守留账,不宣称严格一次。
## 5. 体验链路清单(按用户实际体验顺序;只有实际能力标已接)
| # | 步骤 | 状态 | 说明 |
+4 -2
View File
@@ -262,8 +262,10 @@ def create_app(
app.state.active["cancel"].set()
await app.state.active["finished"].wait()
if app.state.semantic:
# HEL-886: drain live batch workers BEFORE the vector-store
# client / SQLite store close under their durable writes.
# 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.
await app.state.semantic.aclose()
for provider in set(router.provider_for(t) for t in router.available_tiers()):
await provider.aclose()
+251 -46
View File
@@ -61,11 +61,27 @@ Product port of the proven HEL-857/861–869 isolation results (plan-next-HEL-86
row and the terminal ``sem_batch`` state itself. A lease that expires while
its worker is still registered LIVE is never reclaimed (a blocked HTTP call
is not a dead owner) and no concurrent tick resends rows of an active
batch; shutdown drains live workers before closing the vector-store client
and the SQLite store under them. For genuinely dead processes the recovery
stays honest: the crashed attempt's wire outcome is UNKNOWN (its ledger
holds stay billed), the retry sends only rows without a completion proof,
and strict-once delivery is NOT claimed for arbitrary crashes.
batch. For genuinely dead processes the recovery stays honest: the crashed
attempt's wire outcome is UNKNOWN (its ledger holds stay billed), the retry
sends only rows without a completion proof, and strict-once delivery is NOT
claimed for arbitrary crashes.
- Shutdown ownership & queued-worker truth (HEL-889): ``aclose`` NEVER closes
the vector-store client (or lets the SQLite store close) under a worker
that may still write — the manager reproduced the old drain-timeout branch
returning with a live worker, the app closing the store, and the late
worker dying on ``Cannot operate on a closed database`` with its durable
writes lost. The protocol: a closing flag stops new claims and stops
workers between rows (before a row's wire work begins, never mid-row);
never-started workers are cancelled out of the executor queue where
``concurrent.futures`` CANCELLED state is AUTHORITATIVE (provably nothing
sent → safe reschedule, attempt restored); started workers finish their
current row (every wire call is bounded by the gateway client timeout set
at construction) and flush before any resource closes — ``drain_timeout``
bounds only the polite phase, it is never a licence to close under a live
worker. A cancelled ``aclose`` leaves everything open (nothing
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.
- 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
@@ -77,6 +93,9 @@ Product port of the proven HEL-857/861–869 isolation results (plan-next-HEL-86
from __future__ import annotations
import asyncio
import concurrent.futures
import contextlib
import contextvars
import hashlib
import json
import logging
@@ -107,6 +126,16 @@ class SemanticBudgetError(RuntimeError):
"""
class _ShutdownAbort(Exception):
"""aclose() asked a worker to stop BEFORE a row's wire work began.
Raised at a row boundary only (never mid-row): rows that already
finished keep their durable ``sem_row_done`` proofs, the unsent remainder
returns to the queue for the next process, and no wire outcome is left
ambiguous — nothing was in flight when the abort fired.
"""
def _request_definitely_unsent(exc: BaseException) -> bool:
"""True only when the failure provably happened before anything hit the wire.
@@ -177,17 +206,20 @@ class StubBackend:
def _add_group_sync(self, rows: list[dict], anchor: dict, batch_key: str, *,
skip: set[int] | frozenset[int] = frozenset(),
on_row_done=None) -> list[dict]:
on_row_done=None, should_stop=None) -> list[dict]:
"""Per-row mirror of the mem0 contract: one entry per row, each with
that row's own anchor (HEL-885) — orchestration progress parity. The
sync core runs inside the HEL-886 batch worker thread like the real
backend's."""
backend's; ``should_stop`` (HEL-889) is checked before each row so a
shutdown aborts only at a boundary, never mid-row."""
def _add() -> list[dict]:
done = self.completed_message_ids(batch_key) | set(skip)
send = [r for r in rows if r["message_id"] not in done]
created = []
for row in send:
if should_stop is not None and should_stop():
raise _ShutdownAbort()
row_anchor = {
"turn_ids": [row["turn_id"]],
"turn_roles": [[row["turn_id"], row["role"], row["message_id"]]],
@@ -209,9 +241,10 @@ class StubBackend:
async def add_group(self, rows: list[dict], anchor: dict, batch_key: str, *,
skip: set[int] | frozenset[int] = frozenset(),
on_row_done=None) -> list[dict]:
on_row_done=None, should_stop=None) -> list[dict]:
return await asyncio.to_thread(
self._add_group_sync, rows, anchor, batch_key, skip=skip, on_row_done=on_row_done)
self._add_group_sync, rows, anchor, batch_key, skip=skip,
on_row_done=on_row_done, should_stop=should_stop)
async def search(self, query: str, limit: int = 5) -> list[dict]:
def _search() -> list[dict]:
@@ -645,6 +678,10 @@ class Mem0Backend:
self.request_guard = request_guard
self.extract_scene = config.get("extract_scene", "mem0_extract")
self._failures = threading.local()
# HEL-889: every wire call is bounded so the shutdown drain phase has
# a real upper bound — an accepted-but-never-answered gateway call can
# never pin a worker (and aclose) open-endedly.
self.gateway_timeout = float(config.get("gateway_timeout", 60.0))
self.collection = config.get("collection", "cg_public")
self.user_scope = config.get("user_scope", "cybergril")
vector_root = Path(config["vector_root"])
@@ -696,6 +733,11 @@ class Mem0Backend:
client = getattr(llm, "client", None)
if client is not None and hasattr(client, "max_retries"):
client.max_retries = 0
if client is not None:
# HEL-889 bounded-wire guarantee (see __init__): the default 600s
# client timeout would make aclose's drain effectively unbounded.
with contextlib.suppress(Exception):
client.timeout = self.gateway_timeout
def _record_failure(reason: str) -> None:
failures = getattr(self._failures, "list", None)
@@ -823,9 +865,11 @@ class Mem0Backend:
def _add_group_sync(self, rows: list[dict], anchor: dict, batch_key: str, *,
skip: set[int] | frozenset[int] = frozenset(),
on_row_done=None) -> list[dict]:
on_row_done=None, should_stop=None) -> list[dict]:
"""Synchronous core of ``add_group`` — callable from an already-running
worker thread (the HEL-886 batch worker owns the whole execution)."""
worker thread (the HEL-886 batch worker owns the whole execution).
``should_stop`` (HEL-889) is checked before each row's wire work: a
shutdown aborts at a boundary with nothing in flight, never mid-row."""
# HEL-886: prove the remaining work BEFORE any budget gate. A batch
# whose every row already carries a completion proof (vector anchor or
# sem_row_done) finalizes with ZERO new HTTP/embed/LLM — recovery of a
@@ -842,6 +886,11 @@ class Mem0Backend:
self.llm_guard.check(1)
created = []
for row in send:
if should_stop is not None and should_stop():
# aclose() arrived: do not START this row's wire work. Rows
# already finished keep their durable proofs; the remainder
# returns to the queue — nothing was left in flight.
raise _ShutdownAbort()
# Per-row anchor: this add's input set is exactly this row.
row_anchor = {
"turn_ids": [row["turn_id"]],
@@ -878,7 +927,7 @@ class Mem0Backend:
async def add_group(self, rows: list[dict], anchor: dict, batch_key: str, *,
skip: set[int] | frozenset[int] = frozenset(),
on_row_done=None) -> list[dict]:
on_row_done=None, should_stop=None) -> list[dict]:
"""One entry per row, each carrying that row's own anchor (HEL-885).
``skip`` holds message_ids already proven complete (vector-store
@@ -886,10 +935,12 @@ class Mem0Backend:
re-sent. ``on_row_done(row, entries)`` fires in the worker thread as
soon as one row's add fully finished (empty extraction included), so
the caller can durably record per-row progress even if the process
dies mid-batch.
dies mid-batch. ``should_stop`` (HEL-889) aborts BEFORE a row's wire
work when shutdown asks for it — a boundary, never a mid-row cut.
"""
return await asyncio.to_thread(
self._add_group_sync, rows, anchor, batch_key, skip=skip, on_row_done=on_row_done)
self._add_group_sync, rows, anchor, batch_key, skip=skip,
on_row_done=on_row_done, should_stop=should_stop)
async def search(self, query: str, limit: int = 5) -> list[dict]:
self.ledger.check(1) # the query embed is accounted inside the wrapper
@@ -951,7 +1002,8 @@ EmbedLedgerGuard.debit = _ledger_debit
class _LiveWorker:
"""In-process handle on a batch worker thread that is REALLY running.
"""In-process handle on a batch worker thread — queued, started or
running to completion.
HEL-886: the batch's durable fate belongs to its worker thread, never to
the coroutine that happened to start it. A task cancellation cancels only
@@ -961,19 +1013,28 @@ class _LiveWorker:
as this handle is registered, the batch is actively owned — lease expiry
must NOT reclaim it (a slow/blocked call is not a dead owner) and no
concurrent tick may resend its rows.
HEL-889: ``started`` separates QUEUED from STARTED — the registry is
written before submission, but a handle whose work item never left the
executor queue is NOT a live thread, and the cancelling waiter (or
aclose) releases it via the authoritative ``concurrent.futures``
CANCELLED state instead of waiting for a ``finally`` that will never run.
"""
__slots__ = ("batch_id", "owner", "done")
__slots__ = ("batch_id", "owner", "done", "started", "future")
def __init__(self, batch_id: int, owner: str) -> None:
self.batch_id, self.owner = batch_id, owner
self.done = threading.Event()
self.started = threading.Event()
self.future: concurrent.futures.Future | None = None
class SemanticMemory:
"""Owns the batch queue, the anchors and the fail-closed read gate."""
def __init__(self, store, backend, *, clock=time.time) -> None:
def __init__(self, store, backend, *, clock=time.time,
executor: concurrent.futures.Executor | None = None) -> None:
self.store, self.backend, self.clock = store, backend, clock
self.public = PublicView(store)
# HEL-886 live-worker registry: batch_id → handle. Guarded by its own
@@ -981,6 +1042,20 @@ class SemanticMemory:
# threads while the SQLite paths keep their own transactions.
self._live: dict[int, _LiveWorker] = {}
self._live_lock = threading.Lock()
# HEL-889 shutdown ownership: batch workers run on a DEDICATED
# executor so this layer holds the ``concurrent.futures.Future`` for
# each work item — the authoritative queued/started oracle — and a
# 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.
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
# ------------------------------------------------------------ enqueue
def public_rows_for_turn(self, turn_id: str) -> list[dict]:
@@ -1084,7 +1159,46 @@ class SemanticMemory:
(now, now, *dead),
)
# ------------------------------------------------------------ worker truth
def _requeue_owned(self, batch_id: int, owner: str, reason: str) -> None:
"""Return a batch THIS process still owns to the queue.
HEL-889: used only where the stop provably left nothing unresolved on
the wire (never started, or aborted at a row boundary before the next
row's send) — the attempt is restored so a later tick re-claims it.
Unknown wire outcomes never pass through here; those stay
conservative (HEL-885/886: billed holds, proof-gated retries).
"""
with self.store.conn:
self.store.execute(
"UPDATE sem_batch SET state='queued',reason=?,owner=NULL,lease_until=NULL,"
"attempts=MAX(0,attempts-1) WHERE id=? AND owner=? AND state='pending'",
(reason, batch_id, owner),
)
def _release_never_started(self, handle: _LiveWorker, reason: str) -> None:
"""Release a worker whose work item provably NEVER ran.
Idempotent and race-safe: only the caller that actually removes the
handle from the registry performs the batch requeue, so the waiter
cancel path and aclose's queue-cancel path can both fire without
double-restoring the attempt. ``future.cancelled()`` (checked by the
callers) is the authoritative guarantee that no thread will ever
execute ``_run`` — there is no queue/started race to lose.
"""
with self._live_lock:
released = self._live.get(handle.batch_id) is handle
if released:
del self._live[handle.batch_id]
handle.done.set()
if released:
self._requeue_owned(handle.batch_id, handle.owner, reason)
async def tick(self) -> None:
if self._closing.is_set():
# Shutdown owns the process from here: no new claims may start
# real work aclose would then have to drain (HEL-889).
return
self.recover()
owner, now = secrets.token_hex(16), int(self.clock() * 1000)
with self.store.conn:
@@ -1138,10 +1252,25 @@ class SemanticMemory:
failed/abandoned — that was the double-send defect: the cancelled
waiter wrote ``failed``, a second tick reclaimed the batch and
re-sent rows whose first HTTP was still in flight.
HEL-889: ``started`` is set as the FIRST statement, so the
registry always distinguishes a queued item (releasable via the
authoritative future CANCELLED state) from a real thread; a
closing signal aborts BEFORE any outbound work (nothing sent,
attempt restored) or at a row boundary (``_ShutdownAbort`` from
the backend's ``should_stop``), never mid-row.
"""
handle.started.set()
state, reason, entry_ids = "failed", "extraction_failed", None
row_entries: list[str] = []
try:
if self._closing.is_set():
# Shutdown won the race before this worker began: nothing
# was sent, so handing the batch straight back to the
# queue is provably safe.
self._requeue_owned(job["id"], owner, "shutdown_before_start")
state = "queued"
return
anchor = json.loads(job["anchor_json"])
rows = []
for turn_id, role, message_id in anchor["turn_roles"]:
@@ -1160,11 +1289,18 @@ class SemanticMemory:
done_ids |= {r["message_id"] for r in self.store.query(
"SELECT message_id FROM sem_row_done WHERE batch_id=?", (job["id"],))}
created = self.backend._add_group_sync(
rows, anchor, job["batch_key"], skip=done_ids, on_row_done=_row_done)
rows, anchor, job["batch_key"], skip=done_ids, on_row_done=_row_done,
should_stop=lambda: self._closing.is_set())
row_entries.extend(e["id"] for e in created if e["id"] not in row_entries)
entry_ids = json.dumps(
list(dict.fromkeys(row_entries)), ensure_ascii=False)
state, reason = "done", None
except _ShutdownAbort:
# aclose() stopped this batch at a row boundary: finished rows
# keep their durable proofs, the unsent remainder returns to
# the queue for the next process — nothing was in flight.
self._requeue_owned(job["id"], owner, "shutdown_between_rows")
state = "queued"
except Exception as exc: # noqa: BLE001 — job isolation, reason recorded
reason = str(exc) or exc.__class__.__name__
if "budget" in reason:
@@ -1204,41 +1340,110 @@ class SemanticMemory:
with self._live_lock:
self._live.pop(job["id"], None)
# HEL-889: submit through OUR executor and keep the underlying
# ``concurrent.futures.Future`` — cancelling the awaiting task
# propagates to it, and its post-cancel state is the authoritative
# queued/started oracle (no queue-to-thread race to guess at).
ctx = contextvars.copy_context()
future = self._executor.submit(ctx.run, _run)
handle.future = future
try:
await asyncio.to_thread(_run)
await asyncio.wrap_future(future)
except asyncio.CancelledError:
# Only the WAITER was cancelled. The worker thread keeps running
# and writes the batch's durable fate itself; abandoning it as
# "failed" here would let the next tick double-send rows whose
# first HTTP is still in flight (the HEL-886 defect). Nothing to
# clean up — _run owns the registry entry.
# Two provably different cancel windows (HEL-889 P2):
# - CANCELLED: the work item never left the executor queue, no
# thread will EVER run _run (its finally can never clean up).
# Release the false registry entry and hand the batch back to
# the queue — nothing was sent, the attempt is restored.
# - already started/finished: the worker thread owns the batch
# fate (HEL-886) — it writes its durable state and unregisters
# itself; abandoning it here would re-open the double-send.
if future.cancelled():
self._release_never_started(handle, "queued_worker_cancelled")
raise
async def aclose(self, *, drain_timeout: float = 120.0) -> None:
"""Shutdown order (HEL-886): drain OUR still-running workers first.
"""Shutdown ownership protocol (HEL-889): resources NEVER close under
a worker that may still write.
A live worker holds an open HTTP call and will write ``sem_row_done``
and the terminal batch state when it returns; closing the vector-store
client or the SQLite store under it would orphan exactly those durable
writes. Waits up to ``drain_timeout`` seconds, then closes the backend
anyway with an honest warning — the workers' registry entries stay
conservative (their rows resend only without a completion proof).
The manager reproduced the old timeout branch: ``aclose`` gave up
after ``drain_timeout``, the backend closed, the app closed the
store, and the still-running worker died on ``Cannot operate on a
closed database`` with its durable writes lost. Now:
1. the closing flag stops new claims (``tick`` returns) and stops
workers at the NEXT row boundary — before a row's wire work
begins, never mid-row;
2. never-started workers are cancelled out of the executor queue
outright: a ``concurrent.futures`` CANCELLED item provably never
ran, so releasing it and rescheduling its batch is safe;
3. aclose WAITS until every live worker has actually exited.
``drain_timeout`` bounds only the polite phase — after it expires
we log honestly and KEEP WAITING: a live worker may be holding an
accepted-but-unanswered HTTP whose durable write must land, and
treating it as dead is exactly the lost-write window this closes.
Every worker operation is bounded (the gateway client timeout
bounds the wire, set at construction; everything else is local),
so the wait terminates in practice;
4. only then the backend and this layer's executor close.
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.
"""
deadline = time.monotonic() + drain_timeout
while True:
with self._live_lock:
handles = list(self._live.values())
if not handles:
break
left = deadline - time.monotonic()
if left <= 0:
log.warning("semantic shutdown drain: %d live batch worker(s) still running "
"after %.0fs — closing anyway, their outcome stays unknown",
len(handles), drain_timeout)
break
await asyncio.to_thread(
lambda hs=handles, lv=left: [h.done.wait(min(lv, 1.0)) for h in hs])
await self.backend.aclose()
if self._closed:
return
try:
async with self._aclose_lock:
if self._closed:
return
self._closing.set()
deadline = time.monotonic() + drain_timeout
warned = False
while True:
with self._live_lock:
handles = list(self._live.values())
if not handles:
break
for handle in handles:
future = handle.future
if (not handle.started.is_set() and future is not None
and future.cancel()):
# Provably never started — release and reschedule
# right here; the queue-to-thread race cannot
# exist once cancel() itself succeeded.
self._release_never_started(handle, "shutdown_queued_cancelled")
with self._live_lock:
remaining = len(self._live)
if not remaining:
break
if not warned and time.monotonic() >= deadline:
warned = True
log.warning(
"semantic shutdown drain: %d live batch worker(s) still "
"running after %.0fs — close signal set, waiting for their "
"bounded exit before any resource closes (a live worker is "
"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())
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.
self._closing.clear()
raise
# ------------------------------------------------------------ read gate
def chain_resolve(self, hit: dict) -> dict:
+312
View File
@@ -0,0 +1,312 @@
"""HEL-889 rework regressions: the manager's independent-review edge failures.
Two defects against the real product path (review_hel886_edges.py):
P1 — the shutdown drain TIMEOUT closed resources under a live worker:
``aclose`` gave up after ``drain_timeout``, the backend closed, the app closed
the store, and the still-running worker died on ``Cannot operate on a closed
database`` with its durable writes lost (reopened: pending / row_done 0 /
llm_used 1).
P2 — cancelling a tick whose worker was still QUEUED left a phantom registry
entry: ``_run`` (and its finally) never ran, so the batch stayed pending
forever with ``_live=1`` and only a restart could clear it.
These cases drive the REAL product path with barrier-blocked workers and a
single-worker executor (the manager's exact congestion shape), not preseeded
dead leases. The pinned real install is covered live by
tools/verify_shutdown_queued_hel889.py.
"""
import asyncio
import concurrent.futures
import json
import threading
import time
from contextlib import suppress
from test_mem0_backend import _make_ledger
from test_rework_hel885 import seed_public_two_row_turn
from test_rework_hel886 import batch_row, install_blocking, seed_user_row
from test_semantic_recovery_hel882 import config_for, install_fake
from cybergril.memory.semantic import Mem0Backend, SemanticMemory
from cybergril.memory.store import Store
def make_backend(tmp_path, name, *, embed_cap=50, llm_cap=10):
"""(backend, config): the SAME ledger/config must be reused for the
restart step — a second ledger file would fail the frozen-prefix check."""
ledger = tmp_path / f"{name}.sqlite3"
_make_ledger(ledger)
cfg = config_for(tmp_path, ledger, embed_cap=embed_cap, llm_cap=llm_cap)
return Mem0Backend(cfg), cfg
def single_worker_executor():
"""The manager's congestion shape: one worker thread, occupied by an
unrelated blocker, so the batch worker sits QUEUED behind it."""
return concurrent.futures.ThreadPoolExecutor(max_workers=1)
async def wait_until(predicate, timeout=5.0):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return True
await asyncio.sleep(0.01) # never block the loop the tick task runs on
return False
async def test_queued_cancel_releases_and_recovers(tmp_path, monkeypatch):
"""P2 exact shape: the executor is busy, the worker is QUEUED (never
started); cancelling the tick must release the phantom registry entry and
return the batch to the queue — recover + tick then finish it in-process,
no restart, exactly one send."""
install_fake(monkeypatch)
backend, _cfg = make_backend(tmp_path, "queued")
store = Store(tmp_path / "queued.db")
seed_user_row(store, "t-queued", "排队取消恢复的合成原话")
clock = [1000.0]
executor = single_worker_executor()
entered, release = threading.Event(), threading.Event()
blocker = executor.submit(lambda: (entered.set(), release.wait(8)))
assert entered.wait(5)
live = SemanticMemory(store, backend, clock=lambda: clock[0], executor=executor)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
# The batch is claimed and its worker sits in the executor queue.
assert await wait_until(lambda: live._live
and all(not h.started.is_set() for h in live._live.values()))
handle = next(iter(live._live.values()))
assert handle.future is not None and not handle.future.done()
task.cancel() # cancels the QUEUED work item — _run never runs
with suppress(asyncio.CancelledError):
await task
assert not live._live # the phantom entry is gone immediately
after = batch_row(store)
assert after["state"] == "queued" and after["owner"] is None
assert store.query_one("SELECT attempts FROM sem_batch")["attempts"] == 0
assert len(backend._memory.llm.calls) == 0 # nothing was ever sent
release.set()
blocker.result(timeout=5)
clock[0] += 41 # the manager's lease-expiry probe
live.recover() # nothing to fail: queued, not abandoned-pending
assert batch_row(store)["state"] == "queued"
await live.tick() # in-process recovery, no restart
final = batch_row(store)
rows = store.query("SELECT * FROM sem_row_done")
assert final["state"] == "done" and final["reason"] is None
assert len(backend._memory.llm.calls) == 1 # exactly one send, ever
assert len(rows) == 1 and json.loads(final["entry_ids"]) == json.loads(rows[0]["entry_ids"])
await live.aclose()
store.close()
executor.shutdown(wait=True)
async def test_shutdown_timeout_never_closes_under_live_worker(tmp_path, monkeypatch):
"""P1 exact shape: the first HTTP is accepted but unanswered; the drain
deadline (0.05s, the same branch as the default 120s) passes while the
worker is STILL alive. aclose must NOT return-and-close: the worker
finishes, flushes its durable writes, and only then resources close —
app-order store.close() afterwards is safe and nothing is lost."""
arrived, release = threading.Event(), threading.Event()
install_blocking(monkeypatch, arrived, release)
backend, _cfg = make_backend(tmp_path, "shut")
store = Store(tmp_path / "shut.db")
seed_user_row(store, "t-shut", "关闭超时排空的合成原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = 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.3) # the deadline is long past
assert not closing.done() # a live worker is never treated as dead
assert batch_row(store)["state"] == "pending"
assert not backend._client.closed # nothing closed under it
release.set() # the wire answer arrives
await closing
final = batch_row(store)
rows = store.query("SELECT * FROM sem_row_done")
assert final["state"] == "done" and len(rows) == 1 # flushed BEFORE close
assert backend._client.closed # closed only after the drain
with suppress(asyncio.CancelledError, Exception):
await task
store.close() # exact app lifespan order — now safe
check = Store(tmp_path / "shut.db") # durable, no lost-write window
durable = check.query_one("SELECT state,entry_ids FROM sem_batch")
assert durable["state"] == "done" and json.loads(durable["entry_ids"])
assert len(check.query("SELECT * FROM sem_row_done")) == 1
check.close()
async def test_shutdown_between_rows_requeues_and_resume_sends_only_missing(
tmp_path, monkeypatch):
"""aclose arriving BETWEEN rows: finished rows keep their durable proofs,
the unsent remainder returns to the queue, and the next process sends ONLY
the missing row — never a resend of the proven one."""
arrived, release = threading.Event(), threading.Event()
install_blocking(monkeypatch, arrived, release)
backend, cfg = make_backend(tmp_path, "between")
db = tmp_path / "between.db"
store = Store(db)
seed_public_two_row_turn(store, "t-between", "行间关闭第一行", "行间关闭第二行")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await asyncio.to_thread(arrived.wait, 5) # row 1 on the wire
closing = asyncio.create_task(live.aclose(drain_timeout=0.05))
await asyncio.sleep(0.2) # close signal set while row 1 is in flight
release.set()
await closing
after = batch_row(store)
assert after["state"] == "queued" and after["owner"] is None
assert "shutdown" in (after["reason"] or "")
assert len(store.query("SELECT * FROM sem_row_done")) == 1 # row 1 proven
with suppress(asyncio.CancelledError, Exception):
await task
store.close()
# next process: only the unproven row is sent (same ledger, same caps)
backend2 = Mem0Backend(cfg)
store2 = Store(db)
live2 = SemanticMemory(store2, backend2)
calls_before = len(backend2._memory.llm.calls)
await live2.tick()
final = batch_row(store2)
assert final["state"] == "done" and final["reason"] is None
assert len(backend2._memory.llm.calls) - calls_before == 1 # only row 2
assert len(json.loads(final["entry_ids"])) == 2 # both rows' entries
assert len(store2.query("SELECT * FROM sem_row_done")) == 2
await live2.aclose()
store2.close()
async def test_shutdown_before_start_zero_sends_and_resume(tmp_path, monkeypatch):
"""aclose racing a QUEUED worker cancels it out of the executor: provably
nothing was sent, the attempt is restored, and the next process completes
the batch normally."""
install_fake(monkeypatch)
backend, cfg = make_backend(tmp_path, "before")
db = tmp_path / "before.db"
store = Store(db)
seed_user_row(store, "t-before", "未启动即关闭的合成原话")
executor = single_worker_executor()
entered, release = threading.Event(), threading.Event()
blocker = executor.submit(lambda: (entered.set(), release.wait(8)))
assert entered.wait(5)
live = SemanticMemory(store, backend, executor=executor)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await wait_until(lambda: live._live
and all(not h.started.is_set() for h in live._live.values()))
await live.aclose(drain_timeout=0.05) # cancels the queued worker outright
assert not live._live
after = batch_row(store)
assert after["state"] == "queued" and "shutdown" in (after["reason"] or "")
assert store.query_one("SELECT attempts FROM sem_batch")["attempts"] == 0
assert len(backend._memory.llm.calls) == 0 # provably zero sends
with suppress(asyncio.CancelledError, Exception):
await task
store.close()
release.set()
blocker.result(timeout=5)
backend2 = Mem0Backend(cfg) # same ledger/config, fresh instance
store2 = Store(db)
live2 = SemanticMemory(store2, backend2)
await live2.tick()
final = batch_row(store2)
assert final["state"] == "done"
assert len(backend2._memory.llm.calls) == 1
await live2.aclose()
store2.close()
executor.shutdown(wait=True)
async def test_cancelled_aclose_leaves_everything_open(tmp_path, monkeypatch):
"""A close cancelled mid-drain closes NOTHING: the closing signal is
re-armed, the worker keeps running, and a later aclose finishes the job."""
arrived, release = threading.Event(), threading.Event()
install_blocking(monkeypatch, arrived, release)
backend, _cfg = make_backend(tmp_path, "cancelclose")
store = Store(tmp_path / "cancelclose.db")
seed_user_row(store, "t-cc", "关闭被取消的合成原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = 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 draining
closing.cancel()
with suppress(asyncio.CancelledError):
await closing
assert not backend._client.closed # nothing half-closed
assert batch_row(store)["state"] == "pending" # worker still owns it
assert not live._closing.is_set() # the layer is re-armed
await live.tick() # and still usable, not frozen
release.set()
with suppress(asyncio.CancelledError, Exception):
await task
await live.aclose() # a later aclose finishes cleanly
assert backend._client.closed
assert batch_row(store)["state"] == "done"
store.close()
async def test_concurrent_aclose_serializes_and_is_idempotent(tmp_path, monkeypatch):
"""Two aclose callers while a worker is live: both complete, the drain
happens once, resources close once, and a third call returns immediately."""
arrived, release = threading.Event(), threading.Event()
install_blocking(monkeypatch, arrived, release)
backend, _cfg = make_backend(tmp_path, "concurrent")
store = Store(tmp_path / "concurrent.db")
seed_user_row(store, "t-conc", "并发关闭的合成原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await asyncio.to_thread(arrived.wait, 5)
first = asyncio.create_task(live.aclose(drain_timeout=0.05))
second = asyncio.create_task(live.aclose(drain_timeout=5))
await asyncio.sleep(0.2)
release.set()
await asyncio.gather(first, second)
assert backend._client.closed
assert batch_row(store)["state"] == "done"
assert len(store.query("SELECT * FROM sem_row_done")) == 1
await live.aclose() # idempotent no-op
assert backend._client.closed
with suppress(asyncio.CancelledError, Exception):
await task
store.close()
async def test_tick_refuses_claims_after_close(tmp_path, monkeypatch):
"""After aclose the layer is closed: a newly enqueued batch is left
queued — shutdown never accepts work it would have to drain again."""
install_fake(monkeypatch)
backend, _cfg = make_backend(tmp_path, "after")
store = Store(tmp_path / "after.db")
seed_user_row(store, "t-after-1", "关闭后不再领取的第一句")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
await live.tick()
assert batch_row(store)["state"] == "done"
await live.aclose()
seed_user_row(store, "t-after-2", "关闭后不再领取的第二句")
live.enqueue_uncovered()
await live.tick() # closed layer: no new claims
second = store.query_one(
"SELECT state FROM sem_batch WHERE turn_id='t-after-2'")
assert second["state"] == "queued"
assert len(backend._memory.llm.calls) == 1 # only the pre-close batch ran
store.close()
+413
View File
@@ -0,0 +1,413 @@
#!/usr/bin/env python3
"""HEL-889 · 关闭所有权与排队取消验证(零真实出站、零真实嵌入、零权威账写入)。
在固定 mem0ai 2.2.1(hel857-venv)+ 真实嵌入式 Qdrant + 真实 OpenAI 客户端上
复现总管独立复审(review_hel886_edges.py)的两个缺口并证明修复。边界口径与
tools/verify_mem0_real_hel874.py 相同:确定性 512 维替身(TextEmbedding 构造前
安装)、127.0.0.1 假网关、临时账/库。全部场景在同一进程内推进。
Q1 排队未开始取消(总管原负例同形,阻塞改在本产品专用批执行器上):单
worker 执行器被无关任务占住,批次 worker 只入队未启动即取消 tick——
concurrent.futures 的 CANCELLED 是权威「从未运行」证明:假活跃注册项立即
释放、批次回 queued 且 attempts 复原(修复前:pending/_live=1 永久卡死,
只能重启);释放执行器、推进 41 秒后 recover+tick 进程内完成:1 条目、
1 sem_row_done、注册表清零。
S1 关闭超时(固定 SDK 实跑,总管原负例同形):回环网关先接受第一 HTTP 但
阻塞应答,aclose(drain_timeout=0.05)(默认 120 秒的同一超时分支)在
worker 仍活时绝不返回(修复前:返回后 app 关 store,晚到 worker 报
Cannot operate on a closed database,重开仍 pending/row_done=0);应答放
行后 worker 完成并落盘,aclose 才返回、才关 client;按 app 顺序关库重开:
批 done、row_done=1、entry_ids 完整、llm_used=1、无任何晚到错误。
S2 行间中止:两行批次第一 HTTP 阻塞中 aclose;放行后第 1 行保留完成证明,
批次回 queued/shutdown_between_rows;下一进程只发缺行(网关 POST 仅 +1),
done 且两行 entry_ids 完整——不重发已证明行,也不把中止行伪装完成。
S3 关闭被取消:排空等待中的 aclose 任务被取消——什么都没关(client 仍可用、
批次仍 pending),closing 信号复位;worker 正常完成 done;随后再次 aclose
干净收尾。
S4 并发关闭:两个 aclose 同时进入——串行化、排空一次、资源只关一次、批次
done;第三次调用立即返回(幂等)。
证据 JSON 写 argv[1]。运行(仓库根,固定 venv):
/path/to/hel857-venv/bin/python tools/verify_shutdown_queued_hel889.py out.json
"""
from __future__ import annotations
import asyncio
import concurrent.futures
import importlib.util
import json
import sys
import tempfile
import threading
import time
from contextlib import suppress
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
REPO = ROOT
sys.path.insert(0, str(REPO / "src"))
spec = importlib.util.spec_from_file_location('contract', REPO / 'tools/verify_mem0_real_hel874.py')
contract = importlib.util.module_from_spec(spec)
spec.loader.exec_module(contract)
contract.install_deterministic_boundary()
from cybergril.memory.semantic import Mem0Backend, SemanticMemory, StubBackend # noqa: E402 — after boundary
from cybergril.memory.store import Store # noqa: E402
REPORT: dict = {"head": "HEL-889 shutdown ownership & queued-cancel",
"real_llm_requests": 0, "real_embeddings": 0,
"boundary": "deterministic 512 vectors, non-loopback forbidden"}
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 wait_until(predicate, timeout=5.0) -> bool:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return True
await asyncio.sleep(0.01)
return False
def seed_turn(store: Store, turn_id: str, user_text: str, companion_text: str | None = None):
with store.conn:
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
"(1,'user',?,?,'sent')", (user_text, turn_id))
if companion_text is not None:
inserted = store.execute(
"INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
"(2,'companion',?,?,'sent')", (companion_text, turn_id))
store.execute(
"INSERT INTO sharing_attempt(message_id,turn_id,epoch,token,text_hash,"
"expires_at,ack_at,candidates,state) VALUES(?,'" + turn_id + "',1,'synthetic',"
"'synthetic',999999,3,'[]','judged')", (inserted.lastrowid,))
class BlockingGateway(contract.FakeGateway):
"""First POST on this server is accepted but the answer is withheld —
the manager's exact repro shape."""
def do_POST(self): # noqa: N802 — http.server contract
if not getattr(self.server, "accepted", None):
self.server.accepted = [1]
self.server.arrived.set()
if not self.server.release.wait(20):
raise RuntimeError("test barrier timed out")
super().do_POST()
def start_blocking_gateway():
server = contract._Server(('127.0.0.1', 0), BlockingGateway)
server.accepted = []
server.arrived, server.release = threading.Event(), threading.Event()
thread = threading.Thread(target=server.serve_forever)
thread.start()
return server, thread
def backend_for(tmp: Path, name: str, port: int):
tmp.mkdir(parents=True, exist_ok=True)
ledger = tmp / f"{name}.sqlite3"
contract.make_ledger(ledger, cap=100, llm_cap=10)
cfg = contract.config_for(tmp / f"{name}-ledgers", ledger, port=port, cap=100, llm_cap=10)
cfg["vector_root"] = str(tmp / f"{name}-vec")
cfg["history_root"] = str(tmp / f"{name}-hist")
return Mem0Backend(cfg), cfg
def batch_row(store: Store, turn_id: str | None = None) -> dict:
sql = "SELECT state,reason,owner,attempts,entry_ids FROM sem_batch"
row = (store.query_one(sql + " WHERE turn_id=?", (turn_id,)) if turn_id
else store.query_one(sql))
return dict(row) if row else {}
def client_usable(backend: Mem0Backend) -> bool:
try:
backend._client.get_collections()
return True
except Exception:
return False
# ------------------------------------------------------------------ Q1 (stub)
async def q1_queued_cancel(tmp: Path) -> dict:
"""总管原负例同形:单 worker 执行器占住、worker 仅入队即取消。"""
executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
entered, release = threading.Event(), threading.Event()
blocker = executor.submit(lambda: (entered.set(), release.wait(20)))
assert entered.wait(5)
store = Store(tmp / "q1.db")
seed_turn(store, "edge", "排队取消边界合成原话")
clock = [1000.0]
backend = StubBackend()
live = SemanticMemory(store, backend, clock=lambda: clock[0], executor=executor)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await wait_until(lambda: live._live
and all(not h.started.is_set() for h in live._live.values()))
queued_snapshot = {"registered_workers": len(live._live),
"product_executor_queue": live._executor._work_queue.qsize()}
task.cancel()
with suppress(asyncio.CancelledError):
await task
released = {"registered_workers": len(live._live),
"batch": batch_row(store),
"row_done": len(store.query("SELECT * FROM sem_row_done")),
"stored_entries": len(backend._entries)}
release.set()
blocker.result(timeout=5)
clock[0] += 41 # 总管的租约到期探针
live.recover()
await live.tick()
final = {"batch": batch_row(store),
"registered_workers": len(live._live),
"stored_entries": len(backend._entries),
"row_done": len(store.query("SELECT * FROM sem_row_done"))}
await live.aclose(drain_timeout=0)
store.close()
executor.shutdown(wait=True)
return {"queued": queued_snapshot, "after_cancel": released, "after_recovery": final}
# ------------------------------------------------------------- S1..S4 (real)
async def s1_shutdown_timeout(tmp: Path) -> dict:
server, thread = start_blocking_gateway()
try:
backend, _cfg = backend_for(tmp, "s1", server.server_address[1])
store = Store(tmp / "s1.db")
seed_turn(store, "turn-s1", "独立关闭边界合成原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await asyncio.to_thread(server.arrived.wait, 5)
closing = asyncio.create_task(live.aclose(drain_timeout=0.05))
await asyncio.sleep(0.4) # 超时分支已过,worker 仍活
deadline_state = {"aclose_returned_while_worker_alive": closing.done(),
"batch_before_any_close": batch_row(store),
"client_usable": client_usable(backend)}
server.release.set()
await closing
before_store_close = batch_row(store)
late_error = None
with suppress(asyncio.CancelledError, Exception):
try:
await task
except Exception as exc: # noqa: BLE001 — record, never hide
late_error = f"{type(exc).__name__}: {exc}"
store.close() # 与 app lifespan 完全相同的顺序,此刻安全
check_store = Store(tmp / "s1.db")
persisted = {**batch_row(check_store),
"row_done": len(check_store.query("SELECT * FROM sem_row_done")),
"llm_used": backend.llm_guard.used(),
"gateway_posts": len(contract.FakeGateway.requests)}
check_store.close()
return {"deadline": deadline_state, "before_store_close": before_store_close,
"late_worker_error": late_error, "persisted": persisted}
finally:
server.release.set()
server.shutdown()
server.server_close()
thread.join()
async def s2_between_rows(tmp: Path) -> dict:
server, thread = start_blocking_gateway()
try:
backend, cfg = backend_for(tmp, "s2", server.server_address[1])
db = tmp / "s2.db"
store = Store(db)
seed_turn(store, "turn-s2", "行间关闭第一行原话", "行间关闭第二行原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await asyncio.to_thread(server.arrived.wait, 5)
posts_before = len(contract.FakeGateway.requests)
closing = asyncio.create_task(live.aclose(drain_timeout=0.05))
await asyncio.sleep(0.2)
server.release.set()
await closing
after_shutdown = {**batch_row(store),
"row_done": len(store.query("SELECT * FROM sem_row_done")),
"gateway_posts_during_shutdown":
len(contract.FakeGateway.requests) - posts_before}
with suppress(asyncio.CancelledError, Exception):
await task
store.close()
backend2 = Mem0Backend(cfg) # 下一进程:同账同库,无新批准
store2 = Store(db)
live2 = SemanticMemory(store2, backend2)
await live2.tick()
resumed = {**batch_row(store2),
"row_done": len(store2.query("SELECT * FROM sem_row_done")),
"gateway_posts_resume":
len(contract.FakeGateway.requests) - posts_before}
await live2.aclose()
store2.close()
return {"after_shutdown": after_shutdown, "after_resume": resumed}
finally:
server.release.set()
server.shutdown()
server.server_close()
thread.join()
async def s3_cancelled_aclose(tmp: Path) -> dict:
server, thread = start_blocking_gateway()
try:
backend, _cfg = backend_for(tmp, "s3", server.server_address[1])
store = Store(tmp / "s3.db")
seed_turn(store, "turn-s3", "关闭被取消的合成原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await asyncio.to_thread(server.arrived.wait, 5)
closing = asyncio.create_task(live.aclose(drain_timeout=0.05))
await asyncio.sleep(0.2)
closing.cancel()
with suppress(asyncio.CancelledError):
await closing
after_cancel = {"client_usable": client_usable(backend),
"batch": batch_row(store),
"closing_cleared": not live._closing.is_set()}
server.release.set()
with suppress(asyncio.CancelledError, Exception):
await task
after_worker = batch_row(store)
await live.aclose()
return {"after_cancel": after_cancel, "after_worker": after_worker,
"client_usable_after_real_close": client_usable(backend)}
finally:
server.release.set()
server.shutdown()
server.server_close()
thread.join()
async def s4_concurrent_aclose(tmp: Path) -> dict:
server, thread = start_blocking_gateway()
try:
backend, _cfg = backend_for(tmp, "s4", server.server_address[1])
store = Store(tmp / "s4.db")
seed_turn(store, "turn-s4", "并发关闭的合成原话")
live = SemanticMemory(store, backend)
live.enqueue_uncovered()
task = asyncio.create_task(live.tick())
assert await asyncio.to_thread(server.arrived.wait, 5)
first = asyncio.create_task(live.aclose(drain_timeout=0.05))
second = asyncio.create_task(live.aclose(drain_timeout=30))
await asyncio.sleep(0.2)
server.release.set()
await asyncio.gather(first, second)
done_state = {**batch_row(store),
"row_done": len(store.query("SELECT * FROM sem_row_done"))}
await live.aclose() # 幂等
with suppress(asyncio.CancelledError, Exception):
await task
return {"batch": done_state, "client_usable_after_close": client_usable(backend)}
finally:
server.release.set()
server.shutdown()
server.server_close()
thread.join()
def evaluate(q1: dict, s1: dict, s2: dict, s3: dict, s4: dict) -> None:
# Q1: 排队取消立即恢复(总管负例:pending/_live=1 永久卡死)
check("Q1 queued snapshot shows phantom-liveness", q1["queued"]["registered_workers"] == 1
and q1["queued"]["product_executor_queue"] == 1)
check("Q1 cancel releases registry and requeues",
q1["after_cancel"]["registered_workers"] == 0
and q1["after_cancel"]["batch"]["state"] == "queued"
and q1["after_cancel"]["batch"]["attempts"] == 0
and q1["after_cancel"]["stored_entries"] == 0,
json.dumps(q1["after_cancel"], ensure_ascii=False))
check("Q1 in-process recovery completes without restart",
q1["after_recovery"]["batch"]["state"] == "done"
and q1["after_recovery"]["registered_workers"] == 0
and q1["after_recovery"]["stored_entries"] == 1
and q1["after_recovery"]["row_done"] == 1,
json.dumps(q1["after_recovery"], ensure_ascii=False))
# S1: 关闭超时不再把活 worker 当死(总管负例:aclose 返回→关库→丢落盘)
check("S1 aclose does NOT return while the worker is alive",
s1["deadline"]["aclose_returned_while_worker_alive"] is False
and s1["deadline"]["client_usable"] is True)
check("S1 worker completes and flushes before store close",
s1["before_store_close"]["state"] == "done"
and json.loads(s1["before_store_close"]["entry_ids"] or "[]"),
json.dumps(s1["before_store_close"], ensure_ascii=False))
check("S1 no late-worker error after honest drain", s1["late_worker_error"] is None)
check("S1 durable reopen: done + row_done=1 + llm_used=1",
s1["persisted"]["state"] == "done" and s1["persisted"]["row_done"] == 1
and s1["persisted"]["llm_used"] == 1,
json.dumps(s1["persisted"], ensure_ascii=False))
# S2: 行间中止保留证明、下一进程只发缺行
check("S2 shutdown between rows requeues with first row proven",
s2["after_shutdown"]["state"] == "queued"
and "shutdown" in (s2["after_shutdown"]["reason"] or "")
and s2["after_shutdown"]["row_done"] == 1
and s2["after_shutdown"]["gateway_posts_during_shutdown"] == 1,
json.dumps(s2["after_shutdown"], ensure_ascii=False))
check("S2 resume sends ONLY the missing row and completes",
s2["after_resume"]["state"] == "done"
and s2["after_resume"]["row_done"] == 2
and s2["after_resume"]["gateway_posts_resume"] == 2
and len(json.loads(s2["after_resume"]["entry_ids"] or "[]")) == 2,
json.dumps(s2["after_resume"], ensure_ascii=False))
# S3: 被取消的关闭什么都不关
check("S3 cancelled aclose closes nothing and re-arms",
s3["after_cancel"]["client_usable"] is True
and s3["after_cancel"]["batch"]["state"] == "pending"
and s3["after_cancel"]["closing_cleared"] is True)
check("S3 worker finishes done and a later aclose closes for real",
s3["after_worker"]["state"] == "done"
and s3["client_usable_after_real_close"] is False)
# S4: 并发关闭串行化、只关一次
check("S4 concurrent aclose drains once and closes once",
s4["batch"]["state"] == "done" and s4["batch"]["row_done"] == 1
and s4["client_usable_after_close"] is False,
json.dumps(s4, ensure_ascii=False))
async def main_async() -> None:
with tempfile.TemporaryDirectory(prefix="hel889-edges-") as td:
tmp = Path(td)
q1 = await q1_queued_cancel(tmp / "q1")
s1 = await s1_shutdown_timeout(tmp / "s1")
s2 = await s2_between_rows(tmp / "s2")
s3 = await s3_cancelled_aclose(tmp / "s3")
s4 = await s4_concurrent_aclose(tmp / "s4")
evaluate(q1, s1, s2, s3, s4)
REPORT["queued_cancel"] = q1
REPORT["shutdown_timeout"] = s1
REPORT["between_rows"] = s2
REPORT["cancelled_aclose"] = s3
REPORT["concurrent_aclose"] = s4
def main() -> int:
asyncio.run(main_async())
REPORT["failures"] = FAILURES
out = Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT / "hel889-edges.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())