Compare commits

...
Author SHA1 Message Date
阿白叔 c76b755f13 fix: reconcile native save release and resume affected CBB batches 2026-11-24 13:34:56 +08:00
阿白叔 443668aa4b fix: retain native save completion through cancellation and restart 2026-11-24 08:48:33 +08:00
阿白叔 18349413c5 fix: queue catalog reads while recovered sessions exit 2026-11-23 21:52:24 +08:00
阿白叔 e293a9b03c test: await background native mapping handoff 2026-11-23 19:52:33 +08:00
阿白叔 3b4323405a fix: keep prewrite-cancelled CBBs available for fresh admission 2026-11-23 19:34:25 +08:00
阿白叔 48f38d1bdd fix: dismiss a late load-failure prompt after prewrite cancellation 2026-11-23 19:13:08 +08:00
阿白叔 3223889dc7 fix: close owner probe cleanly when its request disappears 2026-11-23 19:10:25 +08:00
阿白叔 f4f5e939eb fix: complete CLI admission and retire finished catalog journals 2026-11-23 18:48:48 +08:00
阿白叔 8e0f78979a fix: handle shared database proof and stale generated cell libraries 2026-11-23 18:33:41 +08:00
阿白叔 4fb978ee21 fix: scope catalog availability and report status progress 2026-11-23 18:30:55 +08:00
阿白叔 31a93cd313 fix: resume verification after an owned session releases 2026-11-23 18:28:40 +08:00
阿白叔 6d2b6de027 fix: validate library and data paths at the application boundary 2026-11-23 18:06:17 +08:00
阿白叔 47c2cfecc6 chore: set version to 0.2.4b6 2026-11-23 13:54:46 +08:00
阿白叔 7c239e123b fix: address PCB access review in CLI and desktop 2026-11-23 12:10:30 +08:00
阿白叔 2d6acc1180 fix: show complete CBB result details 2026-11-23 09:08:19 +08:00
阿白叔 86837155ea fix: preserve catalog state and verify PCB write access 2026-11-20 23:24:47 +08:00
阿白叔 3efeaed656 chore: set version to 0.2.4b5 2026-11-20 16:50:48 +08:00
阿白叔 55cdf2b082 fix: finish owned idle sessions before proving resource release 2026-11-19 11:14:49 +08:00
阿白叔 3bde847ff7 fix: skip unavailable items and isolate batch failures 2026-11-19 10:06:04 +08:00
阿白叔 07eab61695 fix: complete issue17 cleanup and bounded native verification 2026-11-18 19:13:49 +08:00
71 changed files with 5396 additions and 410 deletions

No files matched your search

+8
View File
@@ -193,6 +193,14 @@ Windows 版本判断以 Build 为准:`22000` 及以上归为 Win11,`10240–
GUI 中状态为 `绿色 / Ready` 的条目不能勾选、也不会进入批量队列。 GUI 中状态为 `绿色 / Ready` 的条目不能勾选、也不会进入批量队列。
### PCB 读写确认
桌面普通校验默认在读写确认弹窗无人应答 3 秒后核验占用。可在高级设置取消勾选「无人应答时自动核验 PCB 读写占用」,本次启动的后续批次便会在无人应答时跳过该项。手动选择继续也会核验占用。
命令行使用 `--batch-lmc` 时,加 `--auto-confirm-pcb-open` 可对已识别的读写确认执行同样的核验。带此参数的无界面运行发现该弹窗后立即开始检查。版本选择和 ICDB 维护分别使用各自的入口。
程序核对当前工程、LMC、布局和共享数据库。出现身份不符、实际占用、无法绑定的地址记录、绝对或不唯一的 iCDBDir,以及需要维护的库时,报告会记录具体原因。双击表格备注可查看并复制全文。
### 批量状态桥(只读、默认启用) ### 批量状态桥(只读、默认启用)
`tools/status_bridge/bin/CbbStatusBridge32.exe` 是与 Mentor EE 7.9 x86/MFC ABI `tools/status_bridge/bin/CbbStatusBridge32.exe` 是与 Mentor EE 7.9 x86/MFC ABI
@@ -0,0 +1,191 @@
{
"issue": 17,
"date": "2026-11-18",
"branch": "codex/issue17-batch-cleanup",
"baseline": "14cacb1d1cc9f4be6665fb5ce9434333599d0898",
"scope": "Source GUI and real Mentor, constructed isolated fault; not original field acceptance or frozen ZIP",
"tests": {
"tests": 2455,
"failures": 0,
"errors": 0,
"skipped": 0
},
"test_seconds": 891.372,
"cases": [
{
"1GPHY_8212": "FAIL",
"2GPHY_ZX5201": "PASS"
},
{
"1GPHY_RTL8211F": "PASS"
}
],
"same_ui_process": 65016,
"exact_process_identities_checked": 19,
"exclusive_files_checked": 8,
"automatic_followups": 1,
"original_source": {
"status": "PASS",
"source": "G:\\CbbIssue15FinalAccept-20261117\\run-final-01\\library",
"checked_at": "2026-11-18T11:06:18.160306+00:00",
"files": 28348,
"missing": [],
"added": [],
"changed": [],
"excluded": "top-level .mentor_lib.cbb-upload.* coordinator files, matching pre-test manifest"
},
"source_under_test_sha256": {
"src/cbb_refresh_verify/application.py": "aa02778f4ea4665a9d94926ae86fca32f7dadb535d1460b13fdbb064113eaf33",
"src/cbb_refresh_verify/backup_recovery.py": "eb5813b442de668650fff1ee800d3fba1409af233e374ea37b6ced688cc630e9",
"src/cbb_refresh_verify/batch_status.py": "55a4007cf54491ca8e045a5bf86aa4353ac8437cca5a76cd79304962e3d3fa0a",
"src/cbb_refresh_verify/close_failed_block.vbs": "e5f0d9678e07a239e96e634b90cdc761de52fc136311fae31484fa38d6fd9781",
"src/cbb_refresh_verify/com_runtime.py": "f0f3802d16c791a8bf9dfef44a94917072bfbe8fb3a927d76be8ef0341c7ed35",
"src/cbb_refresh_verify/content_check.py": "8239c17b6e2452917ed573a7deb3e4c8583eaef91bf3630eff5f424d2e398aa9",
"src/cbb_refresh_verify/defaults.py": "a1c03192f4a61ad0924b24bb635705b1ee4811d35483a02864200f95edbbebe3",
"src/cbb_refresh_verify/desktop_worker.py": "81d58513369046300f81cec20a43c3e681e38e46e8131427b354f9dff0e5241a",
"src/cbb_refresh_verify/diagnostic_open.py": "1a12a4a75d8303b3eb85fd0e50923f1e9e7d8cd619e24d6119c1fd286e4985e0",
"src/cbb_refresh_verify/dialog_agent.py": "5acb6e5cf1350a7ca20a6fe480668435fac785835874f266881973010db6504b",
"src/cbb_refresh_verify/dialog_models.py": "f68cee01d927b48364276d3c1f79e63ce8af231878db0b907d292780cfbafb56",
"src/cbb_refresh_verify/dialog_probe.py": "d6ecd359d9e5dbc9376c0a5b123c881670fc01d60dd3290a5f6468a2f599462f",
"src/cbb_refresh_verify/dialog_rules.py": "5531ea7b34cf2094629e7a750cb32a678701c5353a97616bcf7a89b903e386a1",
"src/cbb_refresh_verify/dialog_supervisor.py": "b0eb0aa92a18498843b51b6d8697bd0abfe8b014e1c545e32ddcc8baf7ff7274",
"src/cbb_refresh_verify/failed_session.py": "2b8a6321e1f4ff9b697d0e01ca85a8dd6e3672d3b32a9a6e4816cf495572e1a5",
"src/cbb_refresh_verify/file_probe.py": "849b1a36e4ee1fc6074cee5db5a2d5a4c806fb6e3a309df96e9cd387a66bba28",
"src/cbb_refresh_verify/icdb_maintenance.py": "e81d253d8b4d3e7c1000c45335a392c72b110748675c2c3324ebe524a7252e98",
"src/cbb_refresh_verify/icdb_ownership.py": "b1e25e5eddce70292c0ea2f67c2a3533273e64746b36d500b501b096470f7a5d",
"src/cbb_refresh_verify/icdb_recovery.py": "2d5ef548335ac0ca277241326ee51f5a015d327a646a7c7aa60f67165c1bfca1",
"src/cbb_refresh_verify/integration.py": "f188856af69ba25e265988c51db7a6d4263326440d972ca78378b733b891c1ed",
"src/cbb_refresh_verify/library_lock.py": "1b98c20f6127ad9b29cbf4f082289b093ec89475313e016dcb88202308cf9587",
"src/cbb_refresh_verify/library_manager_verify.py": "71e16a8581ad44b646be78b480f9812d596a6d162b3eec03d078bf4ea4503195",
"src/cbb_refresh_verify/library_reader.py": "7831b502aa1f637426ab2e22f11cb6666e69200b7615925050a5af7472a84b2b",
"src/cbb_refresh_verify/maintenance_entry.py": "ddd0480ad8b04fd99462befbe6683bace526bf5085afb1ee3de918f30e796683",
"src/cbb_refresh_verify/management.py": "b9d297ae673afea09b64bac154a7181da1e01f4c5c0cf5355dddcaeec807f8cf",
"src/cbb_refresh_verify/management_transaction.py": "53ed1564d42492465c90117eeeeee25aa93324b5ddca702d0827ec786c75b1a1",
"src/cbb_refresh_verify/mentor_adapter.py": "b9485603e42fc098ba93fd90b5adce7b0b89085ede6390019d3be9332795eb18",
"src/cbb_refresh_verify/mentor_paths.py": "ba48c0003b3eacc88906497b2e43b299ca4536a9f7dae44bbacf6a6ec694c116",
"src/cbb_refresh_verify/models.py": "94d9d28c61ff7642ae59ac9af91a698bffd15c86a995295576fbbb2143faf789",
"src/cbb_refresh_verify/native_add_failures.py": "192202732423dc624c5548c75e80bb20973e5087c21d4798c9637f25b6de7e94",
"src/cbb_refresh_verify/native_backup.py": "152235f69aefe1bd1338fdd0ed2dec8afb7355de63399f746b02e31047be7909",
"src/cbb_refresh_verify/native_engineering_identity.py": "8c0fc144707d68a9b85f6da50ef950f1f6e7fee248acbf34d19b707d51212be0",
"src/cbb_refresh_verify/native_export_guard.py": "3f6af07737ee670584e6fa9d004c040cf318c3d568e8fa82f84eb70d351b3d6a",
"src/cbb_refresh_verify/native_management.py": "38503011be1c0d4755dd72a4d283d7704937aa576e9f8f9fc3382fc9f4b0be4e",
"src/cbb_refresh_verify/native_occupancy.py": "7d686079d12217382adace6361cd343d977b91075e3b157cf410ca92d07ffc49",
"src/cbb_refresh_verify/native_repair.py": "a720758b8195fd399c81673c13a1d38e69917c9c053e28967ff4e75f40118950",
"src/cbb_refresh_verify/native_repair_ui.py": "9bfb413193d9a917f5ac71d5826e6682b3d0e40d822a5f8366a28f71ca542690",
"src/cbb_refresh_verify/network_path.py": "6b5b159502d42a46bf4ee26d5698fd2c6498b359088e2138eae46e9065b13c6f",
"src/cbb_refresh_verify/operation_lifecycle.py": "d2d654f0e2f7171f60c2d7ad2b4d7cfc3fa3bc9d8a72b64d395a4891b5579007",
"src/cbb_refresh_verify/operation_queue.py": "2a826f8234666867a6dbbacc572a1a8e196864bc3745c8d55dc9e261d6806858",
"src/cbb_refresh_verify/owner_probe.py": "8dcfd60246cb2979db34d02e0a2d605c334b6f7e2666f22daa2f50c0408bc903",
"src/cbb_refresh_verify/pcb_bridge.py": "2f6c2b09642100468814500569dbfc6695fc2a46b9a3b8333daa8e1530cdeef5",
"src/cbb_refresh_verify/pcb_open_consent.py": "ba4d8da5ce3f7ed924621eb37b925371f14d074acaf9814adfb0f77fc6bb73e1",
"src/cbb_refresh_verify/pcb_restore_prompt.py": "a488ab48845173f463042c17ad1e719fe37a4bcf98a660f06453eef171b0e7bb",
"src/cbb_refresh_verify/post_repair_consent.py": "3b1eaff1db58fd311a9dbc5fdcd850911b04cc5afd4e747f70a62b721b8fafa4",
"src/cbb_refresh_verify/post_verify_diagnostics.py": "2442de485bc0d6a34c4b2d9b10bc5f323ea38f9ff66674119a50f5c6043bac63",
"src/cbb_refresh_verify/reimport_recovery.py": "ef148549751fa47518f5f2ca8f32ba25794ec5f22e0de545476ea33f89a3f0bf",
"src/cbb_refresh_verify/residual_sessions.py": "fcf75f47f650a81c2794519bc211640214b6d888bcfb43dd7fbbf146a8a3012e",
"src/cbb_refresh_verify/runtime_logging.py": "44ac25430a89c5ffc9e48e88c227e88052f4c815365e8556f67918f3edaba39e",
"src/cbb_refresh_verify/runtime_timing.py": "c4ed4057b5000e0b86ccc7dd1fe2004d6e0dae29f397fec77b01ad41a81c6367",
"src/cbb_refresh_verify/save_verified_block.vbs": "862fc40f4cf59c73ff0efa3dee1de3fff92df019e43cce46d4fa337378087143",
"src/cbb_refresh_verify/scoped_manifest.py": "f141cfedc901ddadb9be837bc0cbb69c57614d44ab9c347d63bbfa15d4be4a8b",
"src/cbb_refresh_verify/session_record.py": "0273758c6c28557b45230258762756cf05eac5ea2f8f08a8cb7deae2857694fa",
"src/cbb_refresh_verify/status_bridge.py": "05d627d02934a14f5de409472c291d37565a95b836f9c130111aae80612e9196",
"src/cbb_refresh_verify/verify_diagnostics.py": "041b77d7d49e4c86338ed5e5741d0d27a2c42bc358f4da54b3efe64af847e9b8",
"src/cbb_refresh_verify/verify_probe.py": "3ed743df49d195c74f5045985ab23491d103ee2c42c07b558c1e037176402ed2",
"src/cbb_refresh_verify/verify_runner.py": "16a622fb23a903a921e6d949a05f7aaabadac776647efef618004871645d2dc1",
"src/cbb_refresh_verify/write_admission.py": "c5f879bd5cb70a5dedfc64349c8758bf370daa4240491addd2aecd344f3a935c",
"src/cbb_refresh_verify/__init__.py": "673ad8f884cd8a8f4c4097b348be1b77999ec018bdc6c70ab26b8cc383669878",
"src/cbb_refresh_verify/__main__.py": "dc4be034a0e43d4b659a9300137c29a6a6b7a32b7eaef02b6dff9a88c41305c0",
"src/cbb_refresh_verify/assets/cbb_refresh_verify.ico": "62d4472ebaa94f9b39aebae06459685d3322041d0e1a7ada9f368cfd816ba1d6",
"src/cbb_refresh_verify/assets/cbb_refresh_verify.png": "840f657fd7c622d9afd78625a64ed8ad04c90a895dd3c9fd37eebae543cdebe8",
"src/cbb_refresh_verify/assets/cbb_refresh_verify.svg": "cbba5b3f339cbeb5eb43012709237359442ef67c69fc5b6679a8ee4c0a1b7328",
"src/cbb_refresh_verify/assets/dialog_rules.v1.json": "3911080fc799a819662e225a7ad73e883abd8dcc9936cc30ec1b2d6d51a03c6e",
"src/cbb_refresh_verify/ui/backup_notice.py": "1a3fa5ac18a267907faf95f36d61b9f08bcbb939eef4d480dd06af1391a81599",
"src/cbb_refresh_verify/ui/backup_recovery_dialog.py": "c262ec52f870497a18b6034ab98b18498f0e7b703c131cf0d739a17e776deea3",
"src/cbb_refresh_verify/ui/icdb_check_task.py": "955a0f9e2e351e744335c7ff3eab5ad17558a4e364bf13d1e90592e18b118510",
"src/cbb_refresh_verify/ui/main_window.py": "1bb57fa6f35ac570d8810ffa4970c2cb90a6517bc6df70ef2f1a4f0c606cb64c",
"src/cbb_refresh_verify/ui/management_dialog.py": "9e94eda31765ef84b524a9be2d2c81e5aeca85d416c9b64c135d375af88d5250",
"src/cbb_refresh_verify/ui/pcb_open_dialog.py": "1b9689d555d221567263b6b587250b51a11bef276c35d64393e1b3d13803c625",
"src/cbb_refresh_verify/ui/pcb_restore_dialog.py": "11479db5520310af37824e083cb678d69d4cfd12f70dcd29ccb906b929e3d9bd",
"src/cbb_refresh_verify/ui/residual_release_dialog.py": "c2ebc63dd67186dff8ab2300a04ec173219314c2ad01cc70621630f30295a9cc",
"src/cbb_refresh_verify/ui/timed_prompt.py": "bafd5027d396e50458e4bd81e4596be51ebf87353f688e31943a97d71d2d5121",
"src/cbb_refresh_verify/ui/workers.py": "4cc9360a4820ded27a7d5ef709fc9f04b1d4804cb1e7a614f6c357ed547da888",
"src/cbb_refresh_verify/ui/write_owner_dialog.py": "65dc3c8287f4ac5dc767797c13e192f6bd916f9051570a33a2b18f4f8334c3b3",
"src/cbb_refresh_verify/ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"receipts_root": "G:\\CbbIssueLatest-20261118",
"receipt_sha256": {
"issue17-original.zip": {
"bytes": 124556,
"sha256": "fc4b1fa9be56bd1b90e9c88de69b46a9b82f43cece7e807a13581a7627cf05ee"
},
"analysis.md": {
"bytes": 11671,
"sha256": "e0b533ca60ae54b66280edb0b7f868de4a5f155b58ee0da776e52199bddad9f9"
},
"review.md": {
"bytes": 15515,
"sha256": "63caecf5d2e49ee9219eef8d6ab4fea408db3179e820f8552fd64a420390c374"
},
"checks/issue17-full.log": {
"bytes": 2972,
"sha256": "d725001d7b575b60855acef3f8b29b8fd04ea0d108c154d723f8a09608885eb9"
},
"checks/issue17-full.xml": {
"bytes": 358156,
"sha256": "30eb52534613ad1bda0ca2d7a1b7ba355c707060671239f4f9b3fd3a7f734fee"
},
"checks/followup-final.log": {
"bytes": 219,
"sha256": "643e5d25f5ff619c08e211a92d362b32443a3c57b4e9dcab90826c57983c293a"
},
"native/final-source-under-test.json": {
"bytes": 9102,
"sha256": "4ad209d78e01295572f3113e4c9e6f9cb1bbc0a39daded16f7314ef9d52ae2d8"
},
"native/source-copy.json": {
"bytes": 6331491,
"sha256": "f24830cce023a987a450756488425b229a36f9c0a967cee7ddebfa724f571f83"
},
"native/original-source-postcheck.json": {
"bytes": 321,
"sha256": "1cbb127c04eb74387124f2a9fc81d0c4c4017ebc7a36cb5fa1c706726e57904f"
},
"native/native-closure-proof.json": {
"bytes": 4742,
"sha256": "a434f152fdd4554a79b35945c2a8bcaa5d8faf0d38b8557d42ac29e7de30dc83"
},
"native/fault-receipt.json": {
"bytes": 576,
"sha256": "d65146f3e88271646ce2fe363c8d45e1cd70e8255544634ed1eff7ec75059902"
},
"native/actual-first-result.json": {
"bytes": 2622,
"sha256": "4c35bacbb66180f315313b6ef85c3fc564e4909c30d082d30724b31f86e70896"
},
"native/actual-retry-result.json": {
"bytes": 2496,
"sha256": "a63b6023b9176aaa00ffc2e0f5b7db68d6d36c868dca5c6cc66e665b41a1a381"
},
"native/actual-final-result.json": {
"bytes": 2631,
"sha256": "bb35ae4d15fd8f83dab7c035f6891557167331cdb57b466cbb4652992f30fccb"
},
"native/actual-retry-final-result.json": {
"bytes": 2501,
"sha256": "2a8a2e42ce507a5f1e4e23eb610b75ea31133386836dfad737e1e5706ff1dc45"
},
"native/invalid/actual-ui-results.json": {
"bytes": 6124,
"sha256": "1c66d007dcaede8d3a6238ebe14d3444089dc8b4d8e911d5b29bd0aac10b7cda"
},
"native/run-source-01/data/evidence/verify-d182cd8344bf/commit-followup.json": {
"bytes": 452,
"sha256": "097ac62e8c142c8472eb822e5d041f4612b84212e6af492acef705b6283aac07"
}
},
"forced_native_terminations": 0,
"deleted_native_lock_files": 0,
"merged": false,
"released": false,
"issue_closed": false
}
@@ -0,0 +1,45 @@
# 工单 #17 修复与实际验证记录
日期:2026-11-18。分支:`codex/issue17-batch-cleanup`;基线:`14cacb1d1cc9f4be6665fb5ce9434333599d0898`。本记录对应源码 GUI;已发布的 `v0.2.4-beta.4` ZIP 不包含这些未发布修复。
## 问题与修改
工单附件中的批次实际为 6 PASS、1 数据库加载 FAIL、11 READY 跳过,以及 346 项因同库未释放状态被跳过。附件中的数据库加载失败不能直接证明 ICDB 格式损坏。
- 精确识别 EE7.9.5 数据库加载失败后的“是否查看日志”窗口,选择否;监督器已经处理该窗口时,收尾可读取本轮精确证据,正常关闭本任务的空 PCB。未知窗口、已有文档和身份不符仍保留保护。
- 后续同库项前重新核对失败会话;确认释放后清除该失败项的全部库路径别名,继续队列。原失败不改为 PASS。没有确认释放时仍不允许下一个同库写入。
- 成功退出不再误报保留会话。保存日志分别记录工程、文档和 IsSaved;仅短暂 IsSaved 状态允许有界重试,身份不匹配或 COM 错误仍失败。
- 全库状态任务预算从 10 秒调为有界 120 秒;UNKNOWN 显示为“待读取”,不计作工程异常,不进入生产校验。执行前重新读取状态,只有 PENDING 才开始校验;READY 仍跳过。备份恢复等独立操作不共用这个校验门槛。
- 原生已 COMMITTED/CLOSED/EXITED/RELEASED、未中断,但权威仍为 NOT_GREEN,且类别精确为 `MENTOR_VERIFY_NOT_COMMITTED` 时,普通校验允许最多一次补充原生校验。它会再次打开并写入工程,不是只读重查;不适用于打开失败、保存/关闭/释放未确认、诊断或 Repair。两轮证据关联,首轮失败保留,累计总耗时;取消后不再启动补充调用。
## 实际验证方法
证据目录:`G:/CbbIssueLatest-20261118/native`。
从既有隔离库 `G:/CbbIssue15FinalAccept-20261117/run-final-01/library` 冷复制 28,348 个文件,每个文件核对 SHA-256、大小和修改时间,30 个工程引用重绑定到新副本。原复制清单明确排除旧运行顶层 `.mentor_lib.cbb-upload.*` 协调记录。所有原生写入仅针对新副本。
在副本 `1GPHY_8212/Work/database/icdb.dat` 中构造等长头部损坏,原始头部另存。此用例是 **构造损坏,不是现场原始故障复现**。健康项由原生同名更新准备为 PENDING。实际应用运行在隔离桌面,通过真实 GUI 控件提交批次;未替换校验后端,没有前台抢鼠标、强杀原生进程或删除原生锁文件。
源码身份记录为 `final-source-under-test.json`,包含 76 个源码文件/资源的 SHA-256;收尾核对确认与实测源码一致。
## 实测结果
| 用例 | 真实结果与证据 |
| --- | --- |
| 初次试验,修改补充校验逻辑之前 | `actual-first-result.json` 明确保留 FAIL/FAIL:故障项已安全释放,健康项完成保存关闭但权威 PENDING,验收未通过。随后显式重跑健康项达到 READY;这次手动重跑仅用于分析,不算自动链路通过。 |
| 最终源码,故障项 → 健康项 | `actual-final-result.json`:8212 为 FAIL、safe=true(80.390 秒);随后 ZX5201 为 PASS/GREEN、safe=true(88.453 秒)。恰好两行,无 SKIPPED,无后续暂停。执行中修改筛选、清空勾选、切换管理/校验页面,已提交目标仍完整执行。 |
| 同一应用下一批,自动补充校验 | `actual-retry-final-result.json`:RTL 首轮 PENDING/raw=0(91.829 秒),自动补充一次达到 READY/raw=1(74.656 秒);最终一行 PASS,总原生耗时 166.485 秒。`verify-d182cd8344bf/commit-followup.json` 关联首轮失败与 `verify-fde77746a92e`,限制额外调用次数为 1。 |
| 释放与再次使用 | `native-closure-proof.json`:同一 UI PID 65016 中完成两批;核对 19 个进程身份退出及 8 个文件独占打开,无本轮原生进程残留。一个旧 PID 已被晚创建的系统服务复用,通过 WMI 创建时间证明原身份退出,未触碰该系统服务。损坏头部未被偷偷修复。UI 随后正常关闭,退出码 0。 |
| 输入与空闲按钮 | 空 LMC、错误后缀、缺失文件分别显示 INPUT_EMPTY/SUFFIX/MISSING,禁用写入;真实状态读取完成后空闲取消按钮禁用。证据:`invalid/actual-ui-results.json`。 |
夹具准备曾因其他任务的原生会话拒绝一次 Add,原生同名更新留下的缺失条目通过正常 Add 恢复,记录在 `pending-2GPHY_ZX5201.json` / `restored-preparation.json`;不能将这次准备失败混作通过。另一次移动 Cert 的试验没有改变权威 READY,已完整恢复,未用作 PENDING 输入。其他任务的进程均未关闭。
## 自动化验证与边界
`original-source-postcheck.json`:原始隔离输入 28,348 个文件的 SHA-256、大小、修改时间和文件集合全部一致,缺失/新增/变化均为 0;排除项严格沿用复制前的顶层协调记录规则。
全量测试:`python -X utf8 G:/CbbIssueLatest-20261118/run_checks.py issue17-full -q`,**2,455 passed,0 failed/error/skipped**,893.79 秒,实际退出码 0。`python -X utf8 -m compileall -q src tests` 与差异格式检查通过。新增回归均保留 RED/GREEN 记录,覆盖精确窗口、监督器先处理、未知窗口、库路径别名、状态重新准入、独立恢复、32 位 VBS、最多一次补充调用、取消时协调句柄释放及双轮计时。
同目录 `2026-11-18-issue17-cleanup-validation.json` 保存源码指纹、测试统计、关键验收计数和外部原始证据 SHA-256,供复核对应关系。独立代码复核未留下待修问题,并独立核对实际自动链路与全部 76 个源码指纹。
本轮原生样本为一个构造故障接一个健康项,以及同一应用下一批一个健康项的自动补充校验。没有完成现场原始故障一致副本、一个故障接五个健康项的完整矩阵、冻结新包或 Windows 10/11 全环境验收;不能据此宣布现场 ICDB 问题已解决或全部真实占用均可忽略。本轮不关闭工单、不合并、不发行。
@@ -0,0 +1,170 @@
{
"date": "2026-11-19",
"branch": "codex/issue17-batch-cleanup",
"baseline": "07eab61",
"scope": "Final source GUI and actual Mentor, isolated constructed fault; not original field ICDB or frozen EXE acceptance",
"full_tests": {
"tests": 2472,
"failures": 0,
"errors": 0,
"skipped": 0
},
"seconds": 657.842,
"actual": {
"1GPHY_8212": "FAIL",
"1GPHY_RTL8211F": "PASS"
},
"batch_seconds": 314.60899999999674,
"process_identities_checked": 8,
"exclusive_files_checked": 6,
"application_exit": 0,
"automatic_followups": 1,
"source_under_test_sha256": {
"src/cbb_refresh_verify/application.py": "aa02778f4ea4665a9d94926ae86fca32f7dadb535d1460b13fdbb064113eaf33",
"src/cbb_refresh_verify/backup_recovery.py": "eb5813b442de668650fff1ee800d3fba1409af233e374ea37b6ced688cc630e9",
"src/cbb_refresh_verify/batch_status.py": "55a4007cf54491ca8e045a5bf86aa4353ac8437cca5a76cd79304962e3d3fa0a",
"src/cbb_refresh_verify/close_failed_block.vbs": "e5f0d9678e07a239e96e634b90cdc761de52fc136311fae31484fa38d6fd9781",
"src/cbb_refresh_verify/com_runtime.py": "f0f3802d16c791a8bf9dfef44a94917072bfbe8fb3a927d76be8ef0341c7ed35",
"src/cbb_refresh_verify/content_check.py": "8239c17b6e2452917ed573a7deb3e4c8583eaef91bf3630eff5f424d2e398aa9",
"src/cbb_refresh_verify/defaults.py": "a1c03192f4a61ad0924b24bb635705b1ee4811d35483a02864200f95edbbebe3",
"src/cbb_refresh_verify/desktop_worker.py": "81d58513369046300f81cec20a43c3e681e38e46e8131427b354f9dff0e5241a",
"src/cbb_refresh_verify/diagnostic_open.py": "32bef6547d61fe36cbb7c21f35bd45419c4cdaf10c70452ee2368269e6c75d94",
"src/cbb_refresh_verify/dialog_agent.py": "5acb6e5cf1350a7ca20a6fe480668435fac785835874f266881973010db6504b",
"src/cbb_refresh_verify/dialog_models.py": "f68cee01d927b48364276d3c1f79e63ce8af231878db0b907d292780cfbafb56",
"src/cbb_refresh_verify/dialog_probe.py": "d6ecd359d9e5dbc9376c0a5b123c881670fc01d60dd3290a5f6468a2f599462f",
"src/cbb_refresh_verify/dialog_rules.py": "5531ea7b34cf2094629e7a750cb32a678701c5353a97616bcf7a89b903e386a1",
"src/cbb_refresh_verify/dialog_supervisor.py": "b0eb0aa92a18498843b51b6d8697bd0abfe8b014e1c545e32ddcc8baf7ff7274",
"src/cbb_refresh_verify/failed_session.py": "2b8a6321e1f4ff9b697d0e01ca85a8dd6e3672d3b32a9a6e4816cf495572e1a5",
"src/cbb_refresh_verify/file_probe.py": "849b1a36e4ee1fc6074cee5db5a2d5a4c806fb6e3a309df96e9cd387a66bba28",
"src/cbb_refresh_verify/icdb_maintenance.py": "e81d253d8b4d3e7c1000c45335a392c72b110748675c2c3324ebe524a7252e98",
"src/cbb_refresh_verify/icdb_ownership.py": "b1e25e5eddce70292c0ea2f67c2a3533273e64746b36d500b501b096470f7a5d",
"src/cbb_refresh_verify/icdb_recovery.py": "2d5ef548335ac0ca277241326ee51f5a015d327a646a7c7aa60f67165c1bfca1",
"src/cbb_refresh_verify/integration.py": "f188856af69ba25e265988c51db7a6d4263326440d972ca78378b733b891c1ed",
"src/cbb_refresh_verify/library_lock.py": "1b98c20f6127ad9b29cbf4f082289b093ec89475313e016dcb88202308cf9587",
"src/cbb_refresh_verify/library_manager_verify.py": "71e16a8581ad44b646be78b480f9812d596a6d162b3eec03d078bf4ea4503195",
"src/cbb_refresh_verify/library_reader.py": "7831b502aa1f637426ab2e22f11cb6666e69200b7615925050a5af7472a84b2b",
"src/cbb_refresh_verify/maintenance_entry.py": "ddd0480ad8b04fd99462befbe6683bace526bf5085afb1ee3de918f30e796683",
"src/cbb_refresh_verify/management.py": "1a5d33cc75577de11bfbd06c780a46e4679089b44c42f51454e2fdbb4ac4b7ad",
"src/cbb_refresh_verify/management_transaction.py": "53ed1564d42492465c90117eeeeee25aa93324b5ddca702d0827ec786c75b1a1",
"src/cbb_refresh_verify/mentor_adapter.py": "b9485603e42fc098ba93fd90b5adce7b0b89085ede6390019d3be9332795eb18",
"src/cbb_refresh_verify/mentor_paths.py": "ba48c0003b3eacc88906497b2e43b299ca4536a9f7dae44bbacf6a6ec694c116",
"src/cbb_refresh_verify/models.py": "94d9d28c61ff7642ae59ac9af91a698bffd15c86a995295576fbbb2143faf789",
"src/cbb_refresh_verify/native_add_failures.py": "192202732423dc624c5548c75e80bb20973e5087c21d4798c9637f25b6de7e94",
"src/cbb_refresh_verify/native_backup.py": "152235f69aefe1bd1338fdd0ed2dec8afb7355de63399f746b02e31047be7909",
"src/cbb_refresh_verify/native_engineering_identity.py": "8c0fc144707d68a9b85f6da50ef950f1f6e7fee248acbf34d19b707d51212be0",
"src/cbb_refresh_verify/native_export_guard.py": "3f6af07737ee670584e6fa9d004c040cf318c3d568e8fa82f84eb70d351b3d6a",
"src/cbb_refresh_verify/native_management.py": "38503011be1c0d4755dd72a4d283d7704937aa576e9f8f9fc3382fc9f4b0be4e",
"src/cbb_refresh_verify/native_occupancy.py": "7d686079d12217382adace6361cd343d977b91075e3b157cf410ca92d07ffc49",
"src/cbb_refresh_verify/native_repair.py": "a720758b8195fd399c81673c13a1d38e69917c9c053e28967ff4e75f40118950",
"src/cbb_refresh_verify/native_repair_ui.py": "9bfb413193d9a917f5ac71d5826e6682b3d0e40d822a5f8366a28f71ca542690",
"src/cbb_refresh_verify/network_path.py": "6b5b159502d42a46bf4ee26d5698fd2c6498b359088e2138eae46e9065b13c6f",
"src/cbb_refresh_verify/operation_lifecycle.py": "c91041b6e2f7d88f3460b4cdf184df59ff5183c8bc478704e3d442e4ae0406f3",
"src/cbb_refresh_verify/operation_queue.py": "7a2f08d4bc32d1de0a3151d509d41e676fbc962aba2a9346008c71a48adf0e79",
"src/cbb_refresh_verify/owner_probe.py": "8dcfd60246cb2979db34d02e0a2d605c334b6f7e2666f22daa2f50c0408bc903",
"src/cbb_refresh_verify/pcb_bridge.py": "2f6c2b09642100468814500569dbfc6695fc2a46b9a3b8333daa8e1530cdeef5",
"src/cbb_refresh_verify/pcb_open_consent.py": "ba4d8da5ce3f7ed924621eb37b925371f14d074acaf9814adfb0f77fc6bb73e1",
"src/cbb_refresh_verify/pcb_restore_prompt.py": "a488ab48845173f463042c17ad1e719fe37a4bcf98a660f06453eef171b0e7bb",
"src/cbb_refresh_verify/post_repair_consent.py": "3b1eaff1db58fd311a9dbc5fdcd850911b04cc5afd4e747f70a62b721b8fafa4",
"src/cbb_refresh_verify/post_verify_diagnostics.py": "2442de485bc0d6a34c4b2d9b10bc5f323ea38f9ff66674119a50f5c6043bac63",
"src/cbb_refresh_verify/reimport_recovery.py": "ef148549751fa47518f5f2ca8f32ba25794ec5f22e0de545476ea33f89a3f0bf",
"src/cbb_refresh_verify/residual_sessions.py": "fcf75f47f650a81c2794519bc211640214b6d888bcfb43dd7fbbf146a8a3012e",
"src/cbb_refresh_verify/runtime_logging.py": "44ac25430a89c5ffc9e48e88c227e88052f4c815365e8556f67918f3edaba39e",
"src/cbb_refresh_verify/runtime_timing.py": "c4ed4057b5000e0b86ccc7dd1fe2004d6e0dae29f397fec77b01ad41a81c6367",
"src/cbb_refresh_verify/save_verified_block.vbs": "862fc40f4cf59c73ff0efa3dee1de3fff92df019e43cce46d4fa337378087143",
"src/cbb_refresh_verify/scoped_manifest.py": "f141cfedc901ddadb9be837bc0cbb69c57614d44ab9c347d63bbfa15d4be4a8b",
"src/cbb_refresh_verify/session_record.py": "0273758c6c28557b45230258762756cf05eac5ea2f8f08a8cb7deae2857694fa",
"src/cbb_refresh_verify/status_bridge.py": "05d627d02934a14f5de409472c291d37565a95b836f9c130111aae80612e9196",
"src/cbb_refresh_verify/verify_diagnostics.py": "041b77d7d49e4c86338ed5e5741d0d27a2c42bc358f4da54b3efe64af847e9b8",
"src/cbb_refresh_verify/verify_probe.py": "3ed743df49d195c74f5045985ab23491d103ee2c42c07b558c1e037176402ed2",
"src/cbb_refresh_verify/verify_runner.py": "cbdf6cce5a5104edcf1f6b9d66dc2e379d2ffc92989e9cc231c13a4d719e4d8f",
"src/cbb_refresh_verify/write_admission.py": "c5f879bd5cb70a5dedfc64349c8758bf370daa4240491addd2aecd344f3a935c",
"src/cbb_refresh_verify/__init__.py": "673ad8f884cd8a8f4c4097b348be1b77999ec018bdc6c70ab26b8cc383669878",
"src/cbb_refresh_verify/__main__.py": "dc4be034a0e43d4b659a9300137c29a6a6b7a32b7eaef02b6dff9a88c41305c0",
"src/cbb_refresh_verify/assets/cbb_refresh_verify.ico": "62d4472ebaa94f9b39aebae06459685d3322041d0e1a7ada9f368cfd816ba1d6",
"src/cbb_refresh_verify/assets/cbb_refresh_verify.png": "840f657fd7c622d9afd78625a64ed8ad04c90a895dd3c9fd37eebae543cdebe8",
"src/cbb_refresh_verify/assets/cbb_refresh_verify.svg": "cbba5b3f339cbeb5eb43012709237359442ef67c69fc5b6679a8ee4c0a1b7328",
"src/cbb_refresh_verify/assets/dialog_rules.v1.json": "3911080fc799a819662e225a7ad73e883abd8dcc9936cc30ec1b2d6d51a03c6e",
"src/cbb_refresh_verify/ui/backup_notice.py": "1a3fa5ac18a267907faf95f36d61b9f08bcbb939eef4d480dd06af1391a81599",
"src/cbb_refresh_verify/ui/backup_recovery_dialog.py": "5453c1b61ad2969cb3071d7ccf0bba571bcb0d1dac8270b3c96ec0dd1c3d88ff",
"src/cbb_refresh_verify/ui/icdb_check_task.py": "70a678e632487e0e829798284ee7644af0ecb0b27212866dfb23cdb6db6e168d",
"src/cbb_refresh_verify/ui/main_window.py": "368263a7aa57a85de4c76485ff83d68e12bcfd6254a874425bcaa53049c258a1",
"src/cbb_refresh_verify/ui/management_dialog.py": "fc67d7d3a4ba07ccbff5b40f789192c85c8dafa64349446e6a7d86b5f20941d2",
"src/cbb_refresh_verify/ui/pcb_open_dialog.py": "1b9689d555d221567263b6b587250b51a11bef276c35d64393e1b3d13803c625",
"src/cbb_refresh_verify/ui/pcb_restore_dialog.py": "11479db5520310af37824e083cb678d69d4cfd12f70dcd29ccb906b929e3d9bd",
"src/cbb_refresh_verify/ui/residual_release_dialog.py": "c2ebc63dd67186dff8ab2300a04ec173219314c2ad01cc70621630f30295a9cc",
"src/cbb_refresh_verify/ui/timed_prompt.py": "bafd5027d396e50458e4bd81e4596be51ebf87353f688e31943a97d71d2d5121",
"src/cbb_refresh_verify/ui/workers.py": "4cc9360a4820ded27a7d5ef709fc9f04b1d4804cb1e7a614f6c357ed547da888",
"src/cbb_refresh_verify/ui/write_owner_dialog.py": "65dc3c8287f4ac5dc767797c13e192f6bd916f9051570a33a2b18f4f8334c3b3",
"src/cbb_refresh_verify/ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"original_source_postcheck": {
"status": "PASS",
"source": "G:\\CbbIssue15FinalAccept-20261117\\run-final-01\\library",
"checked_at": "2026-11-19T01:53:06.022051+00:00",
"files": 28348,
"missing": [],
"added": [],
"changed": [],
"excluded": "top-level .mentor_lib.cbb-upload.* coordinator files, matching pre-test manifest"
},
"forced_native_terminations": 0,
"native_lock_deletions": 0,
"previous_failed_run_preserved": true,
"raw_evidence_sha256": {
"G:\\CbbBatchIsolationFinal-20261119\\source-under-test.json": {
"bytes": 9066,
"sha256": "47ea3e517051d06467aae4e8174d446013486d4408bfa18ad62a6cfe230211f1"
},
"G:\\CbbBatchIsolationFinal-20261119\\actual-result.json": {
"bytes": 2278,
"sha256": "4cf80df3b3a217acc752ea4113e7cd3fca72dea16927f0a7f40b3bc746cc3030"
},
"G:\\CbbBatchIsolationFinal-20261119\\closure-proof.json": {
"bytes": 5026,
"sha256": "d8cb14b49ba2efa960faba43aec1dd6c7ddff1ba7af343920ec49c141bd39d96"
},
"G:\\CbbBatchIsolationFinal-20261119\\preparation-result.json": {
"bytes": 17036,
"sha256": "a74a5f0dc508c7ae55ca111c1cb8177be35d6872ceb7a65118012586c2b10549"
},
"G:\\CbbBatchIsolationFinal-20261119\\original-source-postcheck.json": {
"bytes": 321,
"sha256": "cfcd3fb37367272f196e0cb48d6dae0cbbe67edc230743b89a92c6394c104cf3"
},
"G:\\CbbBatchIsolationFinal-20261119\\native\\run-source-01\\ui-01\\results\\1795053108621710900-4461.json": {
"bytes": 100,
"sha256": "9f0cb90cca6bc4388da6e21884e13772fd658272d89b1d4f294f0648cc828d40"
},
"G:\\CbbIssueLatest-20261118\\checks\\batch-isolation-final-full.log": {
"bytes": 2981,
"sha256": "955453a903ddb443fd103e3115c54abff9ec94039f3d5d08c6868fdf67d30cd3"
},
"G:\\CbbIssueLatest-20261118\\checks\\batch-isolation-final-full.xml": {
"bytes": 360637,
"sha256": "fa878c69b35f701f00bead1b1df137a96fd35ba14856d88b591542526030f6a7"
},
"G:\\CbbIssueLatest-20261118\\checks\\batch-isolation-full.log": {
"bytes": 13963,
"sha256": "78367028f332c4192e8458c66d25390aee1905160d6eeeb5c7f689cccdf6af5f"
},
"G:\\CbbIssueLatest-20261118\\checks\\batch-isolation-full.xml": {
"bytes": 371306,
"sha256": "57d9c2916a3c104ac4fa498439d84d815886e975d6a2bb86d1521a26fe78173d"
},
"G:\\CbbIssueLatest-20261118\\checks\\batch-isolation-regressions-green.log": {
"bytes": 302,
"sha256": "6167237d4f29af707fa8d05f546dd46fa4be72fbe70153ab3135446c037173ac"
},
"G:\\CbbIssueLatest-20261118\\checks\\cancellation-deadline-red.log": {
"bytes": 7668,
"sha256": "c1354beab3db9a3624e20678be6f3bcc5a823e5331d708f0ce4b34fb3028aa1a"
},
"G:\\CbbIssueLatest-20261118\\batch-isolation-review.md": {
"bytes": 17553,
"sha256": "81181b51d5c30309659db16340b662b2ae62d3cab3139378c74f16a811b012c9"
}
},
"merged": false,
"released": false,
"issue_closed": false
}
@@ -0,0 +1,56 @@
# 异常项跳过与阻塞范围复核
基线:`07eab61`。分支:`codex/issue17-batch-cleanup`。日期:2026-11-19。
## 结论与范围
上一轮不能宣称没有阻塞:生产任务在排队时仍可能无限等待活跃观察会话;ICDB 和管理批次仍将一次未释放结果永久缓存到后续同库项;管理的意外异常和进度接收器异常还能让整批结果丢失。
这轮修正这些分支,不改变原生保存成功条件或 ICDB 诊断判据。普通单项失败保留 FAIL,后续项继续。当前项从未启动时,记录 SKIPPED 和准入原因,不声称新建了待释放会话。确有未释放写入时,冲突项逐项跳过,独立任务继续;没有把“继续遍历”解释为绕过真实占用继续写同一个中心库。
| 条件 | 当前项与后续行为 | 识别依据 |
| --- | --- | --- |
| 前项操作失败但已释放 | 保留原失败,继续下一项 | 原生保存/关闭/退出、资源释放证明各自核对 |
| 后台已登记会话仍运行/初始化 | 当前项未启动即 SKIPPED,继续遍历,无无限排队 | `NATIVE_SESSION_PENDING`,仅活跃观察缓存;历史孤立记录不触发这个准入判定 |
| 前项原生写入仍未确认释放 | 下一项前复核原占用项,确认释放后去除全部库别名缓存;否则跳过冲突项 | `PREVIOUS_SESSION_UNRELEASED`,记录原占用 CBB,不能归为新项 ICDB 错误 |
| 库管理出现未预期异常 | 单项 RECOVERY_REQUIRED;保留未知释放事实,同库冲突项跳过,其他独立库继续 | `BATCH_ITEM_EXCEPTION`,不凭异常类型伪造安全释放 |
| 界面进度接收器失效 | 不改变业务结果和后续执行 | 复用已有容错通知函数 |
| 用户明确停止/关闭队列 | 尊重停止;保留已完成项 | 与“资源未准入”分开,取消优先 |
生产校验、ICDB 检查、库管理、备份恢复及目录读取启用“未准入即跳过/返回”的规则。显式恢复控制仍可接近其原占用会话,普通串行排队和用户主动暂停保留原有行为。只检查缓存的活跃观察状态;不在 GUI 排队谓词里访问文件、查询进程或启动 Mentor。
特别补齐界面调用链:备份恢复、自定义管理入口及主窗口错误处理不得把启动前的 `QueueUnavailable` 转成 FAIL/RECOVERY_REQUIRED 或新增保留租约;全跳过的批次不再刷新空目标集合,也不以刷新失败覆盖结果。
## 验证
证据目录:`G:/CbbBatchIsolation-20261119`;自动化日志:`G:/CbbIssueLatest-20261118/checks`。
- `batch-isolation-red`:9 个新增回归均失败,复现无限等待、缓存不复核与异常逃逸。
- `batch-isolation-edges-red`:复现取消竞争、取消时原结果丢失及进度接收器异常;其中 UI 测试最初错误地要求正常结束的 context 不可被 close/cancel,后改为核对业务结果没有 CANCELLED,未据此修改产品。
- `admission-ui-red`:3 个界面误报未释放分支均失败;修正后新增回归共 16 项通过。
- 相关回归 212 项通过;进一步界面和租约回归 33 项通过。编译检查与 `git diff --check` 通过。
- 首轮全量 `batch-isolation-full` 保留 2 failed / 2,469 passed:新增原占用提示访问字符串注入项的 `block_name` 导致 AttributeError;窗口扫描期间已取消却先超时,返回错误诊断类别。前者用既有合同用例复现,后者新增确定时钟用例复现;均先 RED 后修正。82 项相关回归通过。不是仅调大测试超时;产品扫描返回后立即复核取消,确保不再执行后续窗口动作。最终源码的全量与原生验收重新运行。
- 最终全量 `python -X utf8 G:/CbbIssueLatest-20261118/run_checks.py batch-isolation-final-full -q`:**2,472 passed,0 failure/error/skipped**,665.57 秒,实际退出码 0。相邻 JSON 保存测试统计、最终源码指纹和原始证据 SHA-256。
- 最终原始输入核对 `G:/CbbBatchIsolationFinal-20261119/original-source-postcheck.json`:28,348 个文件 SHA-256、大小、修改时间和集合完全一致;缺失、新增、修改均为 0,顶层旧协调记录的排除规则沿用复制前清单。
### 本轮新源码实际按钮验收
下述首次原生结果保留在 `G:/CbbBatchIsolation-20261119`,对应上述两处补修之前的源码。最终源码另用 `G:/CbbBatchIsolationFinal-20261119` 保存完整记录,不覆盖第一次证据。
`actual-result.json`:同一批次 `1GPHY_8212` 为 FAIL/`MENTOR_DATABASE_LOAD_FAILED`(101.859 秒),完成释放后 `1GPHY_RTL8211F` 为 PASS/GREEN(130.844 秒);权威状态 READY,四项同步、Save/IsSaved/Close 均通过。批次总计 259.875 秒,恰好两行,零 SKIPPED。运行中改变搜索条件、清空勾选、切换管理/校验页,提交时目标保持一致,任务结束后取消按钮禁用。
`closure-proof.json`:5 个精确进程身份退出,6 个关键文件独占打开,76 个源码/资源 SHA-256 与实际测试版本一致。原构造损坏头部未变,未强杀原生进程、未删除原生锁;应用随后正常关闭,退出码 0。本轮健康项首轮即 READY,没有触发旧版本已单独实测过的补充校验分支,不能把本次结果写成又一次自动补充校验验收。
**最终源码重验**(`G:/CbbBatchIsolationFinal-20261119`):8212 为 FAIL/`MENTOR_DATABASE_LOAD_FAILED`、safe=true(88.265 秒);RTL 首轮 `verify-f1c25f324bb3` 为 FAIL/NOT_GREEN、safe=true(101.937 秒),自动补充一次 `verify-f011eceff63f` 后 PASS/GREEN、权威 READY、safe=true(101.078 秒)。报告累计健康项原生耗时 203.015 秒,批次 314.609 秒,恰好 FAIL/PASS 两行、零 SKIPPED。首轮失败原样保留,`commit-followup.json` 为 READY,限制额外调用 1 次。
最终 `closure-proof.json` 核对 8 个精确进程身份退出、6 个关键文件独占打开、全部 76 个源码/资源哈希一致。故障头部未改变,没有强杀或删原生锁;最终应用也正常关闭 exit 0,`ui-01/results` 保存 finish 回执。正常关闭时的初始保守 shutdown 盘点文件不是最终释放证明,保留其原值,由独立进程/文件证明和退出回执确认收尾。
本次实际验证复用此前明确隔离的构造损坏库。新建独立 GUI 数据/证据目录;健康项通过正常原生同名更新准备为 PENDING,未修改客户库。原生准备过程为 UPLOADED、safe=true;准备阶段的 after-remove catalog 窗口观察线程曾记录 `EnumDesktopWindows` 错误码 0,主目录读取成功且已退出;该条原始日志保留,不能据此声称所有原生线程均无异常。
新源码 GUI 读取时,测试驱动 UIA 在重绘期间遇到 `CurrentIsEnabled/-2147220991`,原控制结果保留。只给只读枚举增加有限重试,恢复同一个应用,不重复回放已提交的写动作。产品后端未替换为模拟校验。
## 验收边界
不会承诺“所有写操作永远能继续”:同一原生写会话、中心库或共享数据库仍在使用时,冲突写入必须保持未执行。用户主动暂停、停止以及手动打开的原生维护窗口也不是工程损坏。准确报告这些状态比把它们标成 ICDB 故障更重要。
ICDB 问题仍需本轮原生错误内容支撑;数据库一般加载失败、共享库访问失败、无法确认状态和会话未释放不等同于 ICDB 损坏。构造头部损坏的通过结果也不等于客户原始故障已修复。本轮不发布新包、不合并、不关闭工单。
@@ -0,0 +1,210 @@
{
"date": "2026-11-19",
"baseline": "3bde847",
"branch": "codex/issue17-batch-cleanup",
"scope": "Source GUI/native, deliberately delayed owned empty PCB cleanup in isolated constructed failure; not customer-original or frozen EXE acceptance",
"tests": {
"tests": 2500,
"failures": 0,
"errors": 0,
"skipped": 0
},
"test_seconds": 459.075,
"batch": {
"1GPHY_8212": "FAIL",
"1GPHY_RTL8211F": "PASS"
},
"batch_seconds": 327.85899999999674,
"owned_idle_cleanup": "CLIENT_EXITED",
"original_business_status": "FAIL",
"original_safe_to_continue": false,
"late_resource_safe_to_continue": true,
"release_proof_scope": "BLOCK",
"process_identities_checked": 8,
"exclusive_files_checked": 7,
"source_under_test_sha256": {
"src/cbb_refresh_verify/application.py": "aa02778f4ea4665a9d94926ae86fca32f7dadb535d1460b13fdbb064113eaf33",
"src/cbb_refresh_verify/backup_recovery.py": "eb5813b442de668650fff1ee800d3fba1409af233e374ea37b6ced688cc630e9",
"src/cbb_refresh_verify/batch_status.py": "55a4007cf54491ca8e045a5bf86aa4353ac8437cca5a76cd79304962e3d3fa0a",
"src/cbb_refresh_verify/close_failed_block.vbs": "e5f0d9678e07a239e96e634b90cdc761de52fc136311fae31484fa38d6fd9781",
"src/cbb_refresh_verify/com_runtime.py": "f0f3802d16c791a8bf9dfef44a94917072bfbe8fb3a927d76be8ef0341c7ed35",
"src/cbb_refresh_verify/content_check.py": "8239c17b6e2452917ed573a7deb3e4c8583eaef91bf3630eff5f424d2e398aa9",
"src/cbb_refresh_verify/defaults.py": "a1c03192f4a61ad0924b24bb635705b1ee4811d35483a02864200f95edbbebe3",
"src/cbb_refresh_verify/desktop_worker.py": "81d58513369046300f81cec20a43c3e681e38e46e8131427b354f9dff0e5241a",
"src/cbb_refresh_verify/diagnostic_open.py": "32bef6547d61fe36cbb7c21f35bd45419c4cdaf10c70452ee2368269e6c75d94",
"src/cbb_refresh_verify/dialog_agent.py": "5acb6e5cf1350a7ca20a6fe480668435fac785835874f266881973010db6504b",
"src/cbb_refresh_verify/dialog_models.py": "f68cee01d927b48364276d3c1f79e63ce8af231878db0b907d292780cfbafb56",
"src/cbb_refresh_verify/dialog_probe.py": "d6ecd359d9e5dbc9376c0a5b123c881670fc01d60dd3290a5f6468a2f599462f",
"src/cbb_refresh_verify/dialog_rules.py": "5531ea7b34cf2094629e7a750cb32a678701c5353a97616bcf7a89b903e386a1",
"src/cbb_refresh_verify/dialog_supervisor.py": "b0eb0aa92a18498843b51b6d8697bd0abfe8b014e1c545e32ddcc8baf7ff7274",
"src/cbb_refresh_verify/failed_session.py": "2b8a6321e1f4ff9b697d0e01ca85a8dd6e3672d3b32a9a6e4816cf495572e1a5",
"src/cbb_refresh_verify/file_probe.py": "2471d605bdee5eda781ea96f89bbfb598357c4cdfa5f7d99a8bc9ae882e12240",
"src/cbb_refresh_verify/icdb_maintenance.py": "e81d253d8b4d3e7c1000c45335a392c72b110748675c2c3324ebe524a7252e98",
"src/cbb_refresh_verify/icdb_ownership.py": "b1e25e5eddce70292c0ea2f67c2a3533273e64746b36d500b501b096470f7a5d",
"src/cbb_refresh_verify/icdb_recovery.py": "2d5ef548335ac0ca277241326ee51f5a015d327a646a7c7aa60f67165c1bfca1",
"src/cbb_refresh_verify/integration.py": "f188856af69ba25e265988c51db7a6d4263326440d972ca78378b733b891c1ed",
"src/cbb_refresh_verify/library_lock.py": "b55b608352c68ef30ad8e70a762bb148136a05adc1c2b71a261d50039a420507",
"src/cbb_refresh_verify/library_manager_verify.py": "71e16a8581ad44b646be78b480f9812d596a6d162b3eec03d078bf4ea4503195",
"src/cbb_refresh_verify/library_reader.py": "7831b502aa1f637426ab2e22f11cb6666e69200b7615925050a5af7472a84b2b",
"src/cbb_refresh_verify/maintenance_entry.py": "ddd0480ad8b04fd99462befbe6683bace526bf5085afb1ee3de918f30e796683",
"src/cbb_refresh_verify/management.py": "1a5d33cc75577de11bfbd06c780a46e4679089b44c42f51454e2fdbb4ac4b7ad",
"src/cbb_refresh_verify/management_transaction.py": "53ed1564d42492465c90117eeeeee25aa93324b5ddca702d0827ec786c75b1a1",
"src/cbb_refresh_verify/mentor_adapter.py": "b9485603e42fc098ba93fd90b5adce7b0b89085ede6390019d3be9332795eb18",
"src/cbb_refresh_verify/mentor_paths.py": "ba48c0003b3eacc88906497b2e43b299ca4536a9f7dae44bbacf6a6ec694c116",
"src/cbb_refresh_verify/models.py": "94d9d28c61ff7642ae59ac9af91a698bffd15c86a995295576fbbb2143faf789",
"src/cbb_refresh_verify/native_add_failures.py": "192202732423dc624c5548c75e80bb20973e5087c21d4798c9637f25b6de7e94",
"src/cbb_refresh_verify/native_backup.py": "152235f69aefe1bd1338fdd0ed2dec8afb7355de63399f746b02e31047be7909",
"src/cbb_refresh_verify/native_engineering_identity.py": "8c0fc144707d68a9b85f6da50ef950f1f6e7fee248acbf34d19b707d51212be0",
"src/cbb_refresh_verify/native_export_guard.py": "3f6af07737ee670584e6fa9d004c040cf318c3d568e8fa82f84eb70d351b3d6a",
"src/cbb_refresh_verify/native_management.py": "38503011be1c0d4755dd72a4d283d7704937aa576e9f8f9fc3382fc9f4b0be4e",
"src/cbb_refresh_verify/native_occupancy.py": "7d686079d12217382adace6361cd343d977b91075e3b157cf410ca92d07ffc49",
"src/cbb_refresh_verify/native_repair.py": "a720758b8195fd399c81673c13a1d38e69917c9c053e28967ff4e75f40118950",
"src/cbb_refresh_verify/native_repair_ui.py": "9bfb413193d9a917f5ac71d5826e6682b3d0e40d822a5f8366a28f71ca542690",
"src/cbb_refresh_verify/network_path.py": "6b5b159502d42a46bf4ee26d5698fd2c6498b359088e2138eae46e9065b13c6f",
"src/cbb_refresh_verify/operation_lifecycle.py": "b8bebad94885e576403b099d9819027e59834bf25185b3ccabfccdc375d16055",
"src/cbb_refresh_verify/operation_queue.py": "7a2f08d4bc32d1de0a3151d509d41e676fbc962aba2a9346008c71a48adf0e79",
"src/cbb_refresh_verify/owner_probe.py": "8dcfd60246cb2979db34d02e0a2d605c334b6f7e2666f22daa2f50c0408bc903",
"src/cbb_refresh_verify/pcb_bridge.py": "2f6c2b09642100468814500569dbfc6695fc2a46b9a3b8333daa8e1530cdeef5",
"src/cbb_refresh_verify/pcb_open_consent.py": "ba4d8da5ce3f7ed924621eb37b925371f14d074acaf9814adfb0f77fc6bb73e1",
"src/cbb_refresh_verify/pcb_restore_prompt.py": "a488ab48845173f463042c17ad1e719fe37a4bcf98a660f06453eef171b0e7bb",
"src/cbb_refresh_verify/post_repair_consent.py": "3b1eaff1db58fd311a9dbc5fdcd850911b04cc5afd4e747f70a62b721b8fafa4",
"src/cbb_refresh_verify/post_verify_diagnostics.py": "2442de485bc0d6a34c4b2d9b10bc5f323ea38f9ff66674119a50f5c6043bac63",
"src/cbb_refresh_verify/reimport_recovery.py": "ef148549751fa47518f5f2ca8f32ba25794ec5f22e0de545476ea33f89a3f0bf",
"src/cbb_refresh_verify/residual_sessions.py": "fa5ae0d857b8791b444d3b35366d4b311e444da61c042f77eb157ca3ab970ad1",
"src/cbb_refresh_verify/runtime_logging.py": "44ac25430a89c5ffc9e48e88c227e88052f4c815365e8556f67918f3edaba39e",
"src/cbb_refresh_verify/runtime_timing.py": "c4ed4057b5000e0b86ccc7dd1fe2004d6e0dae29f397fec77b01ad41a81c6367",
"src/cbb_refresh_verify/save_verified_block.vbs": "862fc40f4cf59c73ff0efa3dee1de3fff92df019e43cce46d4fa337378087143",
"src/cbb_refresh_verify/scoped_manifest.py": "f141cfedc901ddadb9be837bc0cbb69c57614d44ab9c347d63bbfa15d4be4a8b",
"src/cbb_refresh_verify/session_record.py": "d0fdcd3c403ce09adc49857340c0bbef7caae31e1360a0d2d4c9e7d2d5062b16",
"src/cbb_refresh_verify/status_bridge.py": "05d627d02934a14f5de409472c291d37565a95b836f9c130111aae80612e9196",
"src/cbb_refresh_verify/verify_diagnostics.py": "041b77d7d49e4c86338ed5e5741d0d27a2c42bc358f4da54b3efe64af847e9b8",
"src/cbb_refresh_verify/verify_probe.py": "3ed743df49d195c74f5045985ab23491d103ee2c42c07b558c1e037176402ed2",
"src/cbb_refresh_verify/verify_runner.py": "214f9a7313369d45f03141c0c99fbbe1038f936ba8821c17eabc4780df2caf81",
"src/cbb_refresh_verify/write_admission.py": "c5f879bd5cb70a5dedfc64349c8758bf370daa4240491addd2aecd344f3a935c",
"src/cbb_refresh_verify/__init__.py": "673ad8f884cd8a8f4c4097b348be1b77999ec018bdc6c70ab26b8cc383669878",
"src/cbb_refresh_verify/__main__.py": "dc4be034a0e43d4b659a9300137c29a6a6b7a32b7eaef02b6dff9a88c41305c0",
"src/cbb_refresh_verify/assets/cbb_refresh_verify.ico": "62d4472ebaa94f9b39aebae06459685d3322041d0e1a7ada9f368cfd816ba1d6",
"src/cbb_refresh_verify/assets/cbb_refresh_verify.png": "840f657fd7c622d9afd78625a64ed8ad04c90a895dd3c9fd37eebae543cdebe8",
"src/cbb_refresh_verify/assets/cbb_refresh_verify.svg": "cbba5b3f339cbeb5eb43012709237359442ef67c69fc5b6679a8ee4c0a1b7328",
"src/cbb_refresh_verify/assets/dialog_rules.v1.json": "3911080fc799a819662e225a7ad73e883abd8dcc9936cc30ec1b2d6d51a03c6e",
"src/cbb_refresh_verify/ui/backup_notice.py": "1a3fa5ac18a267907faf95f36d61b9f08bcbb939eef4d480dd06af1391a81599",
"src/cbb_refresh_verify/ui/backup_recovery_dialog.py": "5453c1b61ad2969cb3071d7ccf0bba571bcb0d1dac8270b3c96ec0dd1c3d88ff",
"src/cbb_refresh_verify/ui/icdb_check_task.py": "70a678e632487e0e829798284ee7644af0ecb0b27212866dfb23cdb6db6e168d",
"src/cbb_refresh_verify/ui/main_window.py": "368263a7aa57a85de4c76485ff83d68e12bcfd6254a874425bcaa53049c258a1",
"src/cbb_refresh_verify/ui/management_dialog.py": "fc67d7d3a4ba07ccbff5b40f789192c85c8dafa64349446e6a7d86b5f20941d2",
"src/cbb_refresh_verify/ui/pcb_open_dialog.py": "1b9689d555d221567263b6b587250b51a11bef276c35d64393e1b3d13803c625",
"src/cbb_refresh_verify/ui/pcb_restore_dialog.py": "11479db5520310af37824e083cb678d69d4cfd12f70dcd29ccb906b929e3d9bd",
"src/cbb_refresh_verify/ui/residual_release_dialog.py": "c2ebc63dd67186dff8ab2300a04ec173219314c2ad01cc70621630f30295a9cc",
"src/cbb_refresh_verify/ui/timed_prompt.py": "bafd5027d396e50458e4bd81e4596be51ebf87353f688e31943a97d71d2d5121",
"src/cbb_refresh_verify/ui/workers.py": "4cc9360a4820ded27a7d5ef709fc9f04b1d4804cb1e7a614f6c357ed547da888",
"src/cbb_refresh_verify/ui/write_owner_dialog.py": "65dc3c8287f4ac5dc767797c13e192f6bd916f9051570a33a2b18f4f8334c3b3",
"src/cbb_refresh_verify/ui/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
},
"original_source_postcheck": {
"status": "PASS",
"source": "G:\\CbbIssue15FinalAccept-20261117\\run-final-01\\library",
"checked_at": "2026-11-19T02:50:46.654715+00:00",
"files": 28348,
"missing": [],
"added": [],
"changed": [],
"excluded": "top-level .mentor_lib.cbb-upload.* coordinator files, matching pre-test manifest"
},
"automatic_followups": 1,
"application_exit": 0,
"forced_terminations": 0,
"native_lock_deletions": 0,
"evidence_sha256": {
"G:\\CbbOwnedRelease-20261119\\source-under-test.json": {
"bytes": 9066,
"sha256": "c5f04fa2c48582cf3538d17f7e7357b9ebcbd038d36d067f30c35fe8072ef2ec"
},
"G:\\CbbOwnedRelease-20261119\\fault-injection.json": {
"bytes": 2503,
"sha256": "1fb89d1b8c2a84d80393ede444ab11b6aa80264f9ec2ab1552550458ae2f964f"
},
"G:\\CbbOwnedRelease-20261119\\actual-result.json": {
"bytes": 6261,
"sha256": "efeedd20114e13796c9001c6aaf1c936e40448e3c1e0d366b3e08703e9218820"
},
"G:\\CbbOwnedRelease-20261119\\closure-proof.json": {
"bytes": 16836,
"sha256": "d772e924022bfae174004300516eb96eb7c72aab851b568407ba6dc3c214eca6"
},
"G:\\CbbOwnedRelease-20261119\\preparation-result.json": {
"bytes": 17126,
"sha256": "288913089686d6cee5e420bc1feba8ab5ddf40d97d1254be9b200afbcf35dc31"
},
"G:\\CbbOwnedRelease-20261119\\original-source-postcheck.json": {
"bytes": 321,
"sha256": "db9851f093513fbaa52bb66863664ea52dfb126b7de81f659ef92d8b427c4d69"
},
"G:\\CbbOwnedRelease-20261119\\native\\run-source-01\\data\\evidence\\verify-b5a731c7b22a\\result.json": {
"bytes": 1356,
"sha256": "21fd5904fa62fcf71a2b9dd24aa906b5046bdb5d372e89034dc322e504b44dd5"
},
"G:\\CbbOwnedRelease-20261119\\native\\run-source-01\\data\\evidence\\verify-b5a731c7b22a\\session.json": {
"bytes": 2387,
"sha256": "3b7341f101f1b655db6521b111b81596e250f2f4528e8224a200fab435e30d28"
},
"G:\\CbbOwnedRelease-20261119\\native\\run-source-01\\data\\evidence\\verify-b5a731c7b22a\\startup-close.json": {
"bytes": 1658,
"sha256": "4342b450f365769ae0664d86e4905a960a47c228c7882896949adb6b604036d5"
},
"G:\\CbbOwnedRelease-20261119\\native\\run-source-01\\data\\evidence\\verify-b5a731c7b22a\\owned-idle-cleanup-result.json": {
"bytes": 764,
"sha256": "cb60648b4d474ac36f961d4d22acdbdccf683cd4cd4265d91704b41fc94ba47b"
},
"G:\\CbbOwnedRelease-20261119\\native\\run-source-01\\data\\evidence\\verify-b5a731c7b22a\\late-release-result.json": {
"bytes": 5657,
"sha256": "b5c7558f75187bdd4e3556863b1f61e42eb10e82bbc39d090200eb7f386c3776"
},
"G:\\CbbOwnedRelease-20261119\\native\\run-source-01\\ui-01\\results\\1795056556817677800-f459.json": {
"bytes": 100,
"sha256": "9f0cb90cca6bc4388da6e21884e13772fd658272d89b1d4f294f0648cc828d40"
},
"G:\\CbbIssueLatest-20261118\\checks\\owned-release-final-full.log": {
"bytes": 2979,
"sha256": "e195023875728737aac8252af3b60a2550fd03d882348e3b5119bfe961c5b2e1"
},
"G:\\CbbIssueLatest-20261118\\checks\\owned-release-final-full.xml": {
"bytes": 364840,
"sha256": "22868613cbbc42603ba9706a69a763408501e4737b37ad273afedd8c40024e95"
},
"G:\\CbbIssueLatest-20261118\\checks\\owned-release-full.log": {
"bytes": 8164,
"sha256": "13144d335d9810ea17d86cd5c69637d9d2ad895919471bbf218e52e1560309cb"
},
"G:\\CbbIssueLatest-20261118\\checks\\owned-release-full.xml": {
"bytes": 369719,
"sha256": "b38fb41722f538db280c17c9b660efe3f221827718b968739108f1c4b0f99751"
},
"G:\\CbbIssueLatest-20261118\\checks\\owned-release-metadata-green.log": {
"bytes": 215,
"sha256": "fb872df90264cbf29bd633aed47619c8699d3d78fa3ae54c2a99119b22c1d9f6"
},
"G:\\CbbIssueLatest-20261118\\checks\\owned-idle-red.log": {
"bytes": 40884,
"sha256": "c120c4601b49a7d78fb6bf43f6d67741bbb5997f8d121b237e5c054073018c24"
},
"G:\\CbbIssueLatest-20261118\\checks\\retained-target-red.log": {
"bytes": 14393,
"sha256": "22fc9e83e0badc075193472a3a3326ab8c5e63ba6f932b410d94bbecf7227771"
},
"G:\\CbbIssueLatest-20261118\\checks\\owned-cleanup-binding-red.log": {
"bytes": 6208,
"sha256": "f3916183b5de3c755ee0de0dc5d2979378fa1dbecae865b8d25cb9499eaab89d"
},
"G:\\CbbIssueLatest-20261118\\checks\\owned-cleanup-binding-green.log": {
"bytes": 296,
"sha256": "46d2ef54e220d7757628be683706ac5e3582909ab179dd75b961ed4f5541d2fb"
},
"G:\\CbbIssueLatest-20261118\\owned-release-review.md": {
"bytes": 13350,
"sha256": "7cf8e8d5652af4382397e6507a280dfaacb41a10ad4f06d395d9aebb55fc3006"
}
},
"merged": false,
"released": false,
"issue_closed": false
}
@@ -0,0 +1,52 @@
# 本任务会话主动收尾与共享资源释放验证
基线:`3bde847`;分支:`codex/issue17-batch-cleanup`。日期:2026-11-19。
## 已确认的问题
1. `recheck_failed_release` 发现登记进程 ACTIVE 时直接返回;后台观察只接续已取消的启动,没有接续终态失败后本任务留下的空闲客户端。
2. 普通校验的 `LibraryLock(checkpoint=False)` 没有携带 `block_name`,保留租约成为无工程身份的整库范围。已实际复现:目标 Bad 的释放,被无关 Other 工程的 `sAddress.adr` 扩大阻塞。
3. 文件占用探测返回 Win32 32/33 时没有文件路径,无法从记录中准确判断是工程还是共享数据库占用。
## 当前收尾顺序
失败仍保持失败。先观察本次精确会话;只对已登记且工作进程/助手已退出的安全空客户端执行一次正常关闭,再独立证明工程和共享资源释放,之后才允许同库后续项继续。
自动正常关闭的条件为:请求、会话、操作、库、私有桌面和结果匹配;Verify 结果还必须匹配 CBB 名称及自身证据路径;进程创建身份、镜像、用户和 Windows 会话一致;所有 worker/helper 原身份已退出;没有其他原生写入任务。仅接续明确数据库启动失败且未进入 Save 的空 PCB、保存/关闭均有明确返回的空 PCB,或本任务只读目录调用留下的空 Library Manager。
有文档(包括隐藏文档)、未知窗口、进度、保存结果未知、身份变化、记录损坏、正在运行的工作进程或其他任务时不自动关闭。服务器不作为自动关闭目标。关闭前持久化一次性意图,并再次核对窗口、请求、结果和 worker-state;状态变化即不发送 Close。正常关闭等待最多 3 秒,不循环发送、不强杀、不删除原生锁。
`CLIENT_EXITED` 只描述客户端退出,明确保留 `resource_release_confirmed=false`。随后仍需独立释放证明覆盖目标工程、LMC 与 SymbolLibs 共享数据库。Verify 租约现在携带目标 CBB,复核不再无故扫描全部其他工程。共享库或其他程序仍占用时保留未释放状态;实际 Win32 32/33 记录为 IN_USE,保存准确的 `blocked_resources` 路径,超时/权限/无法确认等仍为 UNCONFIRMED。历史业务结果文件不被修改。
冷启动发现旧会话时仍按只读观察处理;用户的明确释放操作保持原有入口。新主动收尾接在正在执行的批次复核及非只读后台收尾观察中。
## 回归证据
自动化日志位于 `G:/CbbIssueLatest-20261118/checks`。
- `owned-idle-red`:18 条新增测试先失败,复现被动观察不能正常收尾的缺口。
- `retained-target-red`:真正文件探测复现无关 Other 地址扩大释放范围;补上租约 block_name 后通过。
- `owned-release-observer`:真实 Win32 share=0 句柄占住共享 icdb,客户端正常关闭但资源仍未释放;同时发现错误缺少路径,随后补齐。
- `owned-cleanup-parser-red`、`owned-cleanup-binding-red`:错误 JSON 类型、错置结果和意图持久化后状态改变均先复现,再修正为拒绝动作。
- 早期相关回归 162 项通过;随后资源回归 51 项通过;最终相关回归 84 项通过。编译与差异格式检查通过。
- 首轮全量 `owned-release-full` 保留 2 failed / 2,498 passed:恢复交接测试的 300ms 时限在实际文件复制到达其指定停顿点前触发,失败断言为 `entered.is_set()`,不是晚安装或跨库准入失效。仅调整该用例的局部时钟:准备期间冻结,到指定边界后推进以触发真实交接,再恢复实时时钟验证租约与后续操作。文件复制、库锁、TaskHandoff 与“不晚安装/不晚校验”断言均保留,未放宽产品超时;40 项相关用例通过。最终全量另记,不覆盖失败日志。
- 最终 `python -X utf8 G:/CbbIssueLatest-20261118/run_checks.py owned-release-final-full -q`:**2,500 passed,0 failed/error/skipped**,461.69 秒,实际退出码 0。相邻 JSON 保存测试统计、源码指纹和证据 SHA-256;独立复核无遗留代码问题。
- `G:/CbbOwnedRelease-20261119/original-source-postcheck.json`:原始隔离输入 28,348 个文件的 SHA-256、大小、修改时间及集合一致,新增、缺失、修改均为 0;排除项仍是复制前清单明确排除的旧顶层协调文件。
## 实际应用按钮验收
独立证据目录:`G:/CbbOwnedRelease-20261119`。复用此前明确隔离的库和构造损坏头部;健康项通过原生同名更新准备为 PENDING,未替换校验后端。76 个源码与资源 SHA-256 在运行前冻结、运行后逐一核对。
为了实际触发旧收尾失败,验证驱动只对本轮已登记、身份核实的私有桌面空 PCB 窗口临时设置不可用。原生数据库加载错误仍被正常识别;等待原始 `startup-close.json` 返回 RETAINED 后,立即恢复窗口可用。恢复不发送 Close、不结束进程;后续 Close 由产品自身完成。这是刻意制造的收尾延迟,不是客户现场原始故障复现。
`fault-injection.json`:PCB PID 65168,桌面 `CbbVerify_0058861f6eea`,干预仅两次 EnableWindow(false),66.469 秒后恢复;原收尾记录 PCB/启动器未退出、safe=false。
`verify-b5a731c7b22a/session.json` 保存一次 `owned_idle_cleanup`;`owned-idle-cleanup-result.json` 为 CLIENT_EXITED。原 `result.json` 仍是 FAIL/`MENTOR_DATABASE_LOAD_FAILED`、safe=false;独立 `late-release-result.json` 保存业务 FAIL、资源 safe=true 及 fresh RELEASE_CONFIRMED,范围为该 CBB 加共享数据库,明确包含 `SymbolLibs/__ReusableBlocksSymb/icdb.dat`。
后续 RTL 实际继续执行:首轮 `verify-5d4a9fe55bb4` 完成保存关闭、权威 PENDING;自动一次 `verify-8a460f0dd044` 后 PASS/GREEN、权威 READY。两轮累计 188.453 秒;批次共 327.859 秒,恰好 FAIL/PASS 两行,零 SKIPPED。运行期间切换筛选、清空勾选、切换页签,提交目标不变。
`closure-proof.json`:8 个登记进程身份退出、7 个关键文件独占打开、76 个源码指纹一致;保留原始失败与收尾失败,实际未强杀、未删原生锁。应用随后正常关闭 exit 0,控制回执位于 `native/run-source-01/ui-01/results`。只读 Library Manager 空壳自动收尾有回归覆盖,本轮未另外制造其真实残留。
## 边界
客户原始故障一致副本、冻结 EXE 和所有安装环境未在本轮验收。真实共享写入或未知保存状态仍不能强行解除;这个保护不会被“继续下一项”的要求替代。本轮不合并、不发行、不关闭工单。
@@ -0,0 +1,13 @@
# 工单 #19 审查后续验证
## 合入与发布
PR #18 的目标为 main,PR #20 叠在 PR #18 的分支上。计划先合入 #18,再将 #20 的变更合入 main。发版前在 main 核对两轮改动和测试证据,从最终提交构建新测试版。现有 beta.5 标签对应提交 `3efeaed`。其中不含 PR #20 的目录扫描、读写确认和完整备注改动。
## 占用验证
- 在 Windows 上保留实际文件探测,分别验证共享数据库由独占句柄持有和释放后的选择。另用存在地址记录的工作目录覆盖原生只读检查的调度、正反回执解析和再次探测。该用例替换 Mentor 回执来源。
- 在隔离工程 1GPHY_RTL8211F 上,以之前捕获的项目地址记录调用实际 Mentor Project Backup。原生结果为 `NOT_IN_USE`、`repair_required=true`、`inspection_only=true`、`repair_requested=false`,退出码 0。程序拒绝自动继续。工程地址、工程数据库和共享符号数据库的哈希保持一致,原生检查进程已退出。原始回执 SHA-256 为 `22812c4423bc06fedce4eb9c89ee17e1fe10452fde76aff02ae0380a4505d1d6`。
- 批次回归核对前项保持 SKIPPED,释放复核成功后实际调度同库下一项。工单原先的 5 个工程、364 项生产库及 Win10/SMB 仍待现场复验。
最终全量 Python 测试 2,526 项通过,用时 366.39 秒,退出码 0。编译和差异检查通过。本轮未复现审查机的文件探测挂起。
@@ -0,0 +1,18 @@
# 工单 #17:失败项收尾与后续任务准入
按用户“开始修复,并实际验证收尾闭环”的授权实施。沿用 2026-11-18 工单附件分析;不改 ICDB 自动 Repair、READY 跳过策略和原生 Verify 路线。
1. 以工单精确数据库加载失败问题补回归:直接遇到“是否查看日志”、监督器先行点否、空 PCB 关闭、未知弹窗保留。
2. 修复成功 worker 误报保留会话;保存后分别记录工程路径、文档名、IsSaved,短暂状态有界重试,不放宽身份/Close/READY 条件。
3. 目录完整状态查询采用足够且有界的任务预算;UNKNOWN 独立显示,不进入生产批量校验;目录结束后刷新取消按钮状态。
4. 批次在后续同库项前复核先前未释放项,释放成功后清除其全部路径别名,原失败不改为 PASS。真实未释放仍不可强行写入;不同库继续独立。
5. 实测使用既有隔离验证库的全量一致副本,记录来源、完整复制哈希及工程引用重绑定。健康项先通过原生同名更新成为 PENDING;只在本次副本制造打开故障。通过实际应用按钮运行故障批次、再次运行批次,检查真实原生启动、Save/Close、READY、精确 PID 退出、协调句柄和会话记录,不以模拟或原本 READY 的跳过代替通过。
6. 全量测试和编译检查,记录源码身份、实际步骤及未通过边界。保留工单打开,不自动合并或发行。
工单附件将“任何收尾失败都继续写下一块”与“基础设施错误十次熔断”并列。本次优先消除可自动完成的失败收尾及过期阻塞,不以强杀未知写入或伪造 RELEASED 达成队列继续。
实测补充:首次原生同名导入后,健康控制项完成 Save/Close/退出、三次权威 PENDING/raw=0,未生成 Cert;同一应用显式再次校验触发原生“保存复用块”确认并达到 READY/raw=1。保留首轮失败,不把它重记为通过。
据此新增有界提交补完:仅普通校验得到 MENTOR_VERIFY_NOT_COMMITTED,且 COMMITTED/CLOSED/EXITED/RELEASED、未中断、权威 NOT_GREEN 时,记录检查点后最多再执行一次完整原生校验。它会再次打开工程并执行原生写入,**不是只读状态重查**。不适用于数据库打开失败、未知保存/关闭/释放、诊断、自动 Repair 或 Repair 确认流程。第二次仍不为 READY 就保留失败,不循环。两轮证据关联、累计耗时,首轮证据不覆盖;取消后不进入第二轮,补完前取消也必须释放已完成首轮的协调句柄。自动链路仍需实际按钮验收,显式重跑成功本身不算通过。
最终源码按钮验收已记录:故障项 FAIL 安全释放后下一项 PASS;同一应用下一批首轮 PENDING 后自动一次补完为 READY。未强杀、删除原生锁或手动释放。进程/独占文件核对通过;完整边界与证据见 `docs/releases/2026-11-18-issue17-cleanup-validation.md`,保留现场原始故障与冻结包验收缺口。
+2
View File
@@ -1,5 +1,6 @@
from pathlib import Path from pathlib import Path
import os import os
from shutil import copyfile
import struct import struct
project_root = Path(SPECPATH).parent project_root = Path(SPECPATH).parent
assets_root = project_root / 'src' / 'cbb_refresh_verify' / 'assets' assets_root = project_root / 'src' / 'cbb_refresh_verify' / 'assets'
@@ -42,3 +43,4 @@ pyz = PYZ(a.pure)
exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='CbbRefreshVerify', console=False, exe = EXE(pyz, a.scripts, [], exclude_binaries=True, name='CbbRefreshVerify', console=False,
icon=str(assets_root / 'cbb_refresh_verify.ico')) icon=str(assets_root / 'cbb_refresh_verify.ico'))
coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, name='CbbRefreshVerify-Background') coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, name='CbbRefreshVerify-Background')
copyfile(project_root / 'packaging' / '使用说明.txt', Path(coll.name) / '使用说明.txt')
+27
View File
@@ -0,0 +1,27 @@
CBB 刷新校验使用说明
将 ZIP 完整解压到可写文件夹,保留 CbbRefreshVerify.exe 和 _internal,
双击 CbbRefreshVerify.exe。目标电脑需要安装 Mentor EE 7.9.5,
并能访问中心库及其依赖。写入或恢复前请手动保留可用备份。
在「检验」页选择 .lmc 文件并点击「读取 CBB」。目录预览先出现,
READY 和待验证状态会随后由 Mentor 核对。确认中心库和目标工程后
开始校验。校验会保存工程,经 Mentor 确认为 READY 才显示通过。
点击「取消当前任务并停止队列」后,程序等待原生操作安全退出。
重新提交同库任务时,若仍在收尾,界面会显示等待原因。可通过
「释放残留会话」核对占用的库、工程和进程,查看历史操作记录。
应用默认把日志、批次报告和证据保存在程序旁的 data 目录下。
可在「检验」页点「打开日志目录」。使用命令行时,可指定数据目录。
data\logs\application.log 包含启动和任务状态,data\reports 包含批次结果。
PowerShell 批次示例(在 CbbRefreshVerify.exe 所在目录中运行)
$run = Start-Process .\CbbRefreshVerify.exe -ArgumentList '--batch-lmc', '"D:\测试库\mentor_lib.lmc"', '--block', 'CBB_01', '--data-root', '"D:\CBB日志"' -RedirectStandardError .\batch-error.txt -PassThru -Wait
$run.ExitCode
--block 可重复指定工程。--auto-confirm-pcb-open 允许命令行在核验
资源可写后继续处理已识别的 PCB 读写确认。退出码 0 表示所选项全部
通过,1 表示输入或启动失败,2 表示批次有未通过项或命令参数错误。
启动或输入错误写入重定向的 batch-error.txt。
+1 -1
View File
@@ -3,7 +3,7 @@ requires = ["setuptools>=84.1.0"]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
[project] [project]
name = "cbb-refresh-verify" name = "cbb-refresh-verify"
version = "0.2.4b4" version = "0.2.4b6"
requires-python = ">=3.12,<3.13" requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"] dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.2.4b4" __version__ = "0.2.4b6"
+77 -11
View File
@@ -3,6 +3,7 @@ import argparse, os, sys
from contextlib import contextmanager from contextlib import contextmanager
from pathlib import Path from pathlib import Path
from typing import Sequence from typing import Sequence
from .network_path import NetworkPathError
from .runtime_logging import configure from .runtime_logging import configure
@@ -62,6 +63,29 @@ def resolve_data_root(cli_value: Path | None) -> Path:
local = os.environ.get("LOCALAPPDATA") local = os.environ.get("LOCALAPPDATA")
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve() return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
def _report_entry_error(message: str, *, command_line: bool) -> int:
if not command_line:
import win32api
import win32con
win32api.MessageBox(None, message, 'CBB 刷新校验启动失败', win32con.MB_ICONERROR)
elif sys.stderr is not None:
print(message, file=sys.stderr, flush=True)
elif os.name == 'nt':
# PyInstaller's windowed executable leaves sys.stderr unset even
# when the caller supplied a redirected Windows stderr handle.
import pywintypes
import win32api
import win32console
import win32file
try:
handle = win32api.GetStdHandle(win32console.STD_ERROR_HANDLE)
if handle:
win32file.WriteFile(handle, (message + '\n').encode('utf-8'))
except pywintypes.error:
pass
return 1
def _positive_int(value): def _positive_int(value):
try: try:
number = int(value) number = int(value)
@@ -143,6 +167,8 @@ def main(argv: Sequence[str] | None = None) -> int:
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS) parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS) parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS) parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
parser.add_argument('--auto-confirm-pcb-open', action='store_true',
help='With --batch-lmc, continue through the known PCB prompt after checking resource access')
parser.add_argument('--limit', type=_positive_int, help='Maximum requested CBB names for --batch-lmc (default: all)') parser.add_argument('--limit', type=_positive_int, help='Maximum requested CBB names for --batch-lmc (default: all)')
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS) parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS) parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
@@ -169,14 +195,24 @@ def main(argv: Sequence[str] | None = None) -> int:
return dialog_agent_main(args.dialog_agent) return dialog_agent_main(args.dialog_agent)
if args.verify_worker: if args.verify_worker:
return _native_worker_entry('verify', args.verify_worker) return _native_worker_entry('verify', args.verify_worker)
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start") command_line = bool(args.batch_lmc or args.smoke_test)
data_root = args.data_root
try:
data_root = resolve_data_root(data_root)
context = configure(data_root)
except (OSError, ValueError, RuntimeError):
location = data_root if data_root is not None else '默认数据目录'
return _report_entry_error(f'DATA_ROOT_UNWRITABLE: 无法写入数据目录 {location}。'
'请指定可写的 --data-root。', command_line=command_line)
logger = context.logger
logger.info("application_start")
try: try:
if args.batch_lmc: if args.batch_lmc:
from .verify_runner import (VerifyRequest, native_lm_verify_enabled, from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
run_batch, write_batch_report, failure_report_path) run_batch, write_batch_report, failure_report_path)
from .library_reader import read_library_fast from .library_reader import read_library_fast
from .batch_status import authoritative_status_map from .batch_status import authoritative_status_map
from .network_path import LibraryPathLease, select_library_file from .network_path import LibraryPathLease, select_library_file, validate_library_file
with LibraryPathLease.acquire(args.batch_lmc) as lease: with LibraryPathLease.acquire(args.batch_lmc) as lease:
mentor_path = select_library_file(lease.mentor_path) mentor_path = select_library_file(lease.mentor_path)
logger.info( logger.info(
@@ -184,15 +220,18 @@ def main(argv: Sequence[str] | None = None) -> int:
lease.display_path, mentor_path, lease.drive or '-', lease.display_path, mentor_path, lease.drive or '-',
lease.remote_root or '-', lease.created) lease.remote_root or '-', lease.created)
names = list(args.block) names = list(args.block)
if not names: if names:
validate_library_file(mentor_path)
else:
library = read_library_fast( library = read_library_fast(
mentor_path, mentor_path,
status_reader=lambda path, names: authoritative_status_map( status_reader=lambda path, names: authoritative_status_map(
names, path, context.root/'status-scan.jsonl'), names, path, context.root/'status-scan.jsonl'),
) )
if library.error: raise RuntimeError(library.error) if library.error: raise NetworkPathError(library.error)
names = [record.name for record in library.records if record.status != 'READY'] names = [record.name for record in library.records if record.status != 'READY']
if not names: raise RuntimeError('中心库未读取到需要校验的 CBB') if not names:
raise NetworkPathError('INPUT_NO_BLOCKS: 中心库未读取到需要校验的 CBB。')
total = len(names) total = len(names)
if args.limit is not None: if args.limit is not None:
names = names[:args.limit] names = names[:args.limit]
@@ -203,7 +242,8 @@ def main(argv: Sequence[str] | None = None) -> int:
mentor_bin=args.mentor_bin, logging_context=context, mentor_bin=args.mentor_bin, logging_context=context,
mapped_drive=lease.drive, mapped_drive=lease.drive,
mapped_remote_root=lease.remote_root, mapped_remote_root=lease.remote_root,
native_lm_verify=native_lm_verify_enabled()) native_lm_verify=native_lm_verify_enabled(),
auto_confirm_pcb_open=args.auto_confirm_pcb_open)
for name in names] for name in names]
def retain_mapping(reason): def retain_mapping(reason):
lease.retain_for_recovery() lease.retain_for_recovery()
@@ -214,10 +254,30 @@ def main(argv: Sequence[str] | None = None) -> int:
lease.drive or '-', lease.remote_root or '-', lease.display_path, lease.drive or '-', lease.remote_root or '-', lease.display_path,
mentor_path, reason) mentor_path, reason)
try: try:
from threading import Event from .operation_queue import BatchTaskContext, NativeQueue, request_library_keys
stop = Event() from .session_record import discover_sessions, handoff_session
with batch_stop_signals(stop): from .residual_sessions import recoverable_orphan_session
results = run_batch(requests, stop=stop)
aliases = tuple(request_library_keys(requests[0]))
task = BatchTaskContext(str(mentor_path), aliases=aliases,
targets=tuple(names), native_policy='external')
queue = NativeQueue()
with batch_stop_signals(task.stop):
for old_session in discover_sessions(context.root):
if old_session.get('status') != 'ACTIVE':
continue
old_request = VerifyRequest(Path(old_session['library']), names[0], context.root)
if request_library_keys(old_request).intersection(aliases):
path = old_session['path']
handoff_session(path, evidence_root=context.root,
observe_only=lambda path=path: not recoverable_orphan_session(path))
def admit(_request, action):
return queue.run(action, stop=task.stop, context=task,
wait_for_release_seconds=120,
waiting=lambda: logger.info('batch_waiting_for_session_release library=%s', mentor_path))
results = run_batch(requests, stop=task.stop, context=task, item_executor=admit)
except Exception: except Exception:
retain_mapping('batch_exception') retain_mapping('batch_exception')
raise raise
@@ -245,6 +305,12 @@ def main(argv: Sequence[str] | None = None) -> int:
logger.info('gui_smoke_window_created title=%s', window.windowTitle()) logger.info('gui_smoke_window_created title=%s', window.windowTitle())
QTimer.singleShot(250, app.quit) QTimer.singleShot(250, app.quit)
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
except Exception: logger.exception("application_startup_failure"); return 1 except NetworkPathError as error:
logger.warning('application_input_failure %s', error)
return _report_entry_error(str(error), command_line=command_line)
except Exception:
logger.exception('application_startup_failure')
return _report_entry_error(f'APPLICATION_STARTUP_FAILED: 无法完成启动或批次,请查看日志目录 {context.root}。',
command_line=command_line)
finally: finally:
for handler in logger.handlers: handler.flush() for handler in logger.handlers: handler.flush()
+4 -1
View File
@@ -101,7 +101,10 @@ def _native_scope_match(command, *, roots=(), files=()):
def _project_text(path): def _project_text(path):
data = path.read_bytes() return _decode_project_text(path.read_bytes())
def _decode_project_text(data):
if data.startswith((b'\xff\xfe', b'\xfe\xff')): if data.startswith((b'\xff\xfe', b'\xfe\xff')):
return data.decode('utf-16') return data.decode('utf-16')
try: try:
+38 -25
View File
@@ -172,12 +172,13 @@ class BatchCheckpoint:
) )
return cls(records) return cls(records)
def append(self, path: Path, record: BatchStatusRecord) -> None: def append(self, path: Path | None, record: BatchStatusRecord) -> None:
checkpoint = Path(path) if path is not None:
checkpoint.parent.mkdir(parents=True, exist_ok=True) checkpoint = Path(path)
with checkpoint.open("a", encoding="utf-8", newline="\n") as handle: checkpoint.parent.mkdir(parents=True, exist_ok=True)
handle.write(json.dumps(record.to_json(), ensure_ascii=False, separators=(",", ":")) + "\n") with checkpoint.open("a", encoding="utf-8", newline="\n") as handle:
handle.flush() handle.write(json.dumps(record.to_json(), ensure_ascii=False, separators=(",", ":")) + "\n")
handle.flush()
self.records[record.block_name] = record self.records[record.block_name] = record
@@ -200,16 +201,20 @@ class BatchStatusSession:
self.rotate_every = max(1, int(rotate_every)) self.rotate_every = max(1, int(rotate_every))
self.restart_count = 0 self.restart_count = 0
def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path, def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path | None,
*, block_type: str = "RULP", resume: bool = False) -> list[BatchStatusRecord]: *, block_type: str = "RULP", resume: bool = False, progress=None) -> list[BatchStatusRecord]:
fingerprint = fingerprint_library(Path(lmc_file)) from .operation_queue import check_active
if resume:
checkpoint = BatchCheckpoint.load(checkpoint_path) check_active()
else: fingerprint = fingerprint_library(Path(lmc_file)).sha256 if checkpoint_path is not None else ''
checkpoint = BatchCheckpoint() checkpoint = BatchCheckpoint()
checkpoint_file = Path(checkpoint_path) if checkpoint_path is not None:
checkpoint_file.parent.mkdir(parents=True, exist_ok=True) if resume:
checkpoint_file.write_text('', encoding='utf-8') checkpoint = BatchCheckpoint.load(checkpoint_path)
else:
checkpoint_file = Path(checkpoint_path)
checkpoint_file.parent.mkdir(parents=True, exist_ok=True)
checkpoint_file.write_text('', encoding='utf-8')
results: list[BatchStatusRecord] = [] results: list[BatchStatusRecord] = []
names = tuple(str(name) for name in names) names = tuple(str(name) for name in names)
server = self.bridge if all(callable(getattr(self.bridge, method, None)) server = self.bridge if all(callable(getattr(self.bridge, method, None))
@@ -219,10 +224,13 @@ class BatchStatusSession:
try: try:
queried = 0 queried = 0
for index, name in enumerate(names): for index, name in enumerate(names):
check_active()
previous = checkpoint.get(name) previous = checkpoint.get(name)
if (previous and previous.status in {'READY', 'PENDING'} if (previous and previous.status in {'READY', 'PENDING'}
and previous.fingerprint == fingerprint.sha256 and previous.block_type == block_type): and previous.fingerprint == fingerprint and previous.block_type == block_type):
results.append(previous) results.append(previous)
if progress is not None:
progress(len(results), len(names))
continue continue
try: try:
result: BridgeResult = self.bridge.query( result: BridgeResult = self.bridge.query(
@@ -232,12 +240,12 @@ class BatchStatusSession:
record = BatchStatusRecord( record = BatchStatusRecord(
block_name=name, status=result.status, source=result.source, block_name=name, status=result.status, source=result.source,
raw_status=result.raw_status, detail=result.detail, raw_status=result.raw_status, detail=result.detail,
fingerprint=fingerprint.sha256, timestamp=_now(), fingerprint=fingerprint, timestamp=_now(),
block_type=block_type, block_type=block_type,
) )
except BridgeUnavailable as error: except BridgeUnavailable as error:
record = BatchStatusRecord(block_name=name, status="UNAVAILABLE", record = BatchStatusRecord(block_name=name, status="UNAVAILABLE",
detail=str(error), fingerprint=fingerprint.sha256, detail=str(error), fingerprint=fingerprint,
timestamp=_now(), block_type=block_type) timestamp=_now(), block_type=block_type)
except BridgeResponseError as error: except BridgeResponseError as error:
message = str(error) message = str(error)
@@ -252,7 +260,7 @@ class BatchStatusSession:
else "UNAVAILABLE" if unavailable else "UNAVAILABLE" if unavailable
else "MALFORMED" if malformed else "ERROR") else "MALFORMED" if malformed else "ERROR")
record = BatchStatusRecord(block_name=name, status=status, detail=message, record = BatchStatusRecord(block_name=name, status=status, detail=message,
fingerprint=fingerprint.sha256, timestamp=_now(), block_type=block_type) fingerprint=fingerprint, timestamp=_now(), block_type=block_type)
if server is not None and status != "UNAVAILABLE": if server is not None and status != "UNAVAILABLE":
try: try:
server.restart() server.restart()
@@ -260,14 +268,17 @@ class BatchStatusSession:
pass pass
except Exception as error: # bridge failures isolate one CBB except Exception as error: # bridge failures isolate one CBB
record = BatchStatusRecord(block_name=name, status="ERROR", detail=str(error), record = BatchStatusRecord(block_name=name, status="ERROR", detail=str(error),
fingerprint=fingerprint.sha256, timestamp=_now(), block_type=block_type) fingerprint=fingerprint, timestamp=_now(), block_type=block_type)
if server is not None: if server is not None:
try: try:
server.restart() server.restart()
except BridgeUnavailable: except BridgeUnavailable:
pass pass
check_active()
checkpoint.append(checkpoint_path, record) checkpoint.append(checkpoint_path, record)
results.append(record) results.append(record)
if progress is not None:
progress(len(results), len(names))
if record.status == "UNAVAILABLE" and index + 1 < len(names): if record.status == "UNAVAILABLE" and index + 1 < len(names):
# Startup/protocol failures cannot be repaired by retrying # Startup/protocol failures cannot be repaired by retrying
# the same request contract for every CBB. # the same request contract for every CBB.
@@ -276,11 +287,13 @@ class BatchStatusSession:
for remaining in names[index + 1:]: for remaining in names[index + 1:]:
unavailable_record = BatchStatusRecord( unavailable_record = BatchStatusRecord(
block_name=remaining, status=record.status, detail=record.detail, block_name=remaining, status=record.status, detail=record.detail,
fingerprint=fingerprint.sha256, timestamp=_now(), fingerprint=fingerprint, timestamp=_now(),
block_type=block_type, block_type=block_type,
) )
checkpoint.append(checkpoint_path, unavailable_record) checkpoint.append(checkpoint_path, unavailable_record)
results.append(unavailable_record) results.append(unavailable_record)
if progress is not None:
progress(len(results), len(names))
break break
queried += 1 queried += 1
if server is not None and queried % self.rotate_every == 0 and name != names[-1]: if server is not None and queried % self.rotate_every == 0 and name != names[-1]:
@@ -291,9 +304,9 @@ class BatchStatusSession:
return results return results
def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_path: Path, def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_path: Path | None = None,
*, bridge_path: Path | None = None, *, bridge_path: Path | None = None,
timeout_seconds: float = 10.0) -> dict[str, str]: timeout_seconds: float = 10.0, progress=None) -> dict[str, str]:
"""Return only bridge-backed statuses for an optional UI integration. """Return only bridge-backed statuses for an optional UI integration.
Production always queries fresh statuses, including after native writes; Production always queries fresh statuses, including after native writes;
@@ -306,7 +319,7 @@ def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_pa
names = tuple(str(name) for name in names) names = tuple(str(name) for name in names)
try: try:
records = BatchStatusSession(bridge, timeout_seconds=timeout_seconds).scan( records = BatchStatusSession(bridge, timeout_seconds=timeout_seconds).scan(
names, lmc_file, checkpoint_path, resume=False) names, lmc_file, checkpoint_path, resume=False, progress=progress)
return {record.block_name: record.status for record in records} return {record.block_name: record.status for record in records}
except BridgeUnavailable: except BridgeUnavailable:
return {name: "UNAVAILABLE" for name in names} return {name: "UNAVAILABLE" for name in names}
+7 -2
View File
@@ -299,6 +299,10 @@ def launch_save_helper(command, *, start_gate=None, identity_path=None, operatio
return helper return helper
def supervisor_has_exited():
return _supervisor_lost.is_set()
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False, def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False,
session_record_path=None, operation_id=None, supervisor_identity=None): session_record_path=None, operation_id=None, supervisor_identity=None):
"""Record stop intent; a watchdog cannot interrupt an in-flight COM call. """Record stop intent; a watchdog cannot interrupt an in-flight COM call.
@@ -512,8 +516,9 @@ class DesktopWorker:
def bind_session(self, job): def bind_session(self, job):
from .session_record import register_worker_session from .session_record import register_worker_session
from .library_lock import duplicate_worker_lease from .library_lock import duplicate_worker_lease
lease = (None if job.get('inspection_only') is True else read_only = (job.get('inspection_only') is True or
duplicate_worker_lease(job['library'], self.handle)) (job.get('operation') == 'catalog' and job.get('worker_role') == 'catalog_readonly'))
lease = None if read_only else duplicate_worker_lease(job['library'], self.handle)
register_worker_session(self, {**job, 'worker_lease_handle': lease}) register_worker_session(self, {**job, 'worker_lease_handle': lease})
def native_write_pending(self): def native_write_pending(self):
@@ -463,6 +463,7 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No
if not session.pcb_alive(): if not session.pcb_alive():
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence') raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence')
windows = scan(deadline) windows = scan(deadline)
_cancel(job)
if any(window['pid'] != int(pcb_pid) for window in windows): if any(window['pid'] != int(pcb_pid) for window in windows):
raise RuntimeError('DIAGNOSTIC_PID_MISMATCH') raise RuntimeError('DIAGNOSTIC_PID_MISMATCH')
frame = _target_frame(windows, Path(job['pcb']).stem, require_ready=False) frame = _target_frame(windows, Path(job['pcb']).stem, require_ready=False)
+92 -3
View File
@@ -43,7 +43,21 @@ def _cancel_target(snapshot):
from .post_repair_consent import exact_prompt from .post_repair_consent import exact_prompt
from .dialog_rules import pcb_version_choice from .dialog_rules import pcb_version_choice
if exact_prompt(snapshot): if exact_prompt(snapshot):
return 'read_write_access', next(c for c in snapshot.controls if c.control_id == 7) no = next((c for c in snapshot.controls if c.class_name == 'Button'
and c.control_id == 7 and c.enabled), None)
return ('read_write_access', no) if no is not None else None
text = ' '.join(' '.join(c.name for c in snapshot.controls
if c.class_name == 'Static').split())
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
if (snapshot.window_class == '#32770' and snapshot.title == 'Expedition PCB'
and text == ('Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed. '
'Do you wish to view the log file now?')
and {c.control_id for c in buttons} == {6, 7}
and len(buttons) == 2):
no = next(c for c in buttons if c.control_id == 7)
if no.enabled:
return 'database_load_log', no
if pcb_version_choice(snapshot) is not None: if pcb_version_choice(snapshot) is not None:
buttons = [c for c in snapshot.controls if c.class_name == 'Button'] buttons = [c for c in snapshot.controls if c.class_name == 'Button']
cancel = [c for c in buttons if c.control_id == 2 and c.name == 'Cancel' and c.enabled] cancel = [c for c in buttons if c.control_id == 2 and c.name == 'Cancel' and c.enabled]
@@ -62,6 +76,67 @@ def _tip_target(snapshot):
return target if target is not None and target.class_name == 'Button' else None return target if target is not None and target.class_name == 'Button' else None
def _database_log_declined(root, pcb_pid):
"""The supervisor can dismiss this exact failed-open question before cleanup."""
from dataclasses import fields
from .dialog_models import WindowSnapshot
path = root/'dialogs.jsonl'
try:
if path.stat().st_size > 1024*1024:
return False
for line in path.read_text(encoding='utf-8').splitlines():
record = json.loads(line)
if (record.get('pid') != pcb_pid or record.get('phase') != 'PCB_STARTING'
or record.get('error_code') != 'MENTOR_DATABASE_LOAD_FAILED'
or record.get('action') != 'acknowledge_fatal'
or record.get('accepted_control') != [7]):
continue
snapshot = WindowSnapshot.from_record({f.name:record[f.name]
for f in fields(WindowSnapshot) if f.name in record})
target = _cancel_target(snapshot)
if target is not None and target[0] == 'database_load_log':
return True
except (OSError, ValueError, TypeError, KeyError):
pass
return False
def _read_write_declined(job, root, pcb_pid):
from .dialog_models import WindowSnapshot
from .session_record import IDENTITY_KEYS
choice_path = root/'pcb-open-user-choice.json'
dialogs_path = root/'dialogs.jsonl'
try:
if (choice_path.stat().st_size > 1024*1024 or dialogs_path.stat().st_size > 1024*1024
or not job.get('operation_id') or (root/'save.log').exists()):
return False
choice = json.loads(choice_path.read_text(encoding='utf-8'))
binding = {key: job[key] for key in ('operation_id', 'desktop', 'project', 'pcb')}
if (any(choice.get(key) != value for key, value in binding.items())
or choice.get('library') != job['lmc_file'] or choice.get('choice') not in ('skip', 'cancel')):
return False
owner = choice['owner']['target']
if (owner.get('pid') != pcb_pid or not owner.get('owner_sid')
or any(owner.get(key) is None for key in IDENTITY_KEYS)):
return False
original = choice['snapshot']
snapshot = WindowSnapshot.from_record(original)
target = _cancel_target(snapshot)
if snapshot.pid != pcb_pid or target is None or target[0] != 'read_write_access':
return False
expected = 'PCB_OPEN_SKIPPED' if choice['choice'] == 'skip' else 'USER_CANCELLED'
for line in dialogs_path.read_text(encoding='utf-8').splitlines():
record = json.loads(line)
if (record.get('action') == 'user_confirmed_pcb_open' and record.get('accepted_control') == [7]
and record.get('error_code') == expected
and all(record.get(key) == value for key, value in original.items())):
return owner
except (OSError, ValueError, TypeError, KeyError, AttributeError):
pass
return False
def cancelled_prewrite_startup(job, pcb_pid=None): def cancelled_prewrite_startup(job, pcb_pid=None):
"""Positive ordinary pre-document cancellation proof; absence of Save is insufficient.""" """Positive ordinary pre-document cancellation proof; absence of Save is insufficient."""
from .session_record import IDENTITY_KEYS, read_session_record from .session_record import IDENTITY_KEYS, read_session_record
@@ -150,7 +225,8 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
sent = False sent = False
declined_hwnd = None declined_hwnd = None
declined_kind = None declined_kind = None
cancelled_open = False cancelled_open = _database_log_declined(root, pcb_pid)
decline_owner = None
dismissed_tips = set() dismissed_tips = set()
close_handle = None close_handle = None
close_identity = None close_identity = None
@@ -163,8 +239,19 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
or residual_sessions._handle_identity(close_handle) != close_identity or residual_sessions._handle_identity(close_handle) != close_identity
or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid): or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid):
raise ValueError('STARTUP_ACTION_UNCONFIRMED') raise ValueError('STARTUP_ACTION_UNCONFIRMED')
if decline_owner:
actual = {'pid': pcb_pid, **close_identity,
**residual_sessions._force_ownership(close_handle, pcb_pid)}
if any(actual.get(key) != value for key, value in decline_owner.items()):
raise ValueError('STARTUP_ACTION_UNCONFIRMED: 原进程身份变化')
win32gui.PostMessage(hwnd, message, 0, 0) win32gui.PostMessage(hwnd, message, 0, 0)
while True: while True:
# PCB can dismiss the prompt before the supervisor records its action.
if not cancelled_open:
decline_owner = _read_write_declined(job, root, pcb_pid)
if decline_owner:
cancelled_open = True
result['cancelled_prompt'] = 'read_write_access'
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid] records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
if not records: if not records:
if (close_handle is not None if (close_handle is not None
@@ -182,6 +269,8 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited, result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited,
'addresses': addresses, 'addresses': addresses,
'safe_to_continue': launcher_exited and (cancelled_open or not addresses)} 'safe_to_continue': launcher_exited and (cancelled_open or not addresses)}
if addresses:
result['release']['resource_release_confirmed'] = False
if result['release']['safe_to_continue']: if result['release']['safe_to_continue']:
result['status'] = 'CLOSED' result['status'] = 'CLOSED'
result.pop('detail', None) result.pop('detail', None)
@@ -317,7 +406,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
close_identity = residual_sessions._handle_identity(close_handle) close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe': if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED') raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
if cancelled_diagnostic or cancelled_prewrite: if cancelled_diagnostic or cancelled_prewrite or decline_owner:
cleanup_post(main[0],win32con.WM_CLOSE) cleanup_post(main[0],win32con.WM_CLOSE)
else: else:
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0) win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
+133 -12
View File
@@ -2,7 +2,7 @@
from contextlib import contextmanager, ExitStack from contextlib import contextmanager, ExitStack
import hashlib import hashlib
import json import json
from pathlib import Path from pathlib import Path, PureWindowsPath
import re import re
import stat import stat
import subprocess import subprocess
@@ -13,13 +13,14 @@ from uuid import uuid4
@contextmanager @contextmanager
def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None): def hold_release_files(library, roots=None, *, saved_project=None, timeout_seconds=10, stop=None):
"""Only this pure probe may be terminated. stdin EOF releases its handles.""" """Only this pure probe may be terminated. stdin EOF releases its handles."""
with tempfile.TemporaryDirectory(prefix='cbb-file-probe-') as folder: with tempfile.TemporaryDirectory(prefix='cbb-file-probe-') as folder:
job = Path(folder)/'request.json' job = Path(folder)/'request.json'
token = uuid4().hex token = uuid4().hex
job.write_text(json.dumps({'token': token, 'library': str(library), job.write_text(json.dumps({'token': token, 'library': str(library),
'roots': [str(p) for p in roots] if roots is not None else None}), 'utf-8') 'roots': [str(p) for p in roots] if roots is not None else None,
'saved_project': [str(p) for p in saved_project] if saved_project is not None else None}), 'utf-8')
command = ([sys.executable] if getattr(sys, 'frozen', False) else command = ([sys.executable] if getattr(sys, 'frozen', False) else
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--file-probe', str(job)] [sys.executable, '-m', 'cbb_refresh_verify']) + ['--file-probe', str(job)]
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
@@ -27,20 +28,27 @@ def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None):
try: try:
deadline = time.monotonic()+max(.1, min(10, timeout_seconds)) deadline = time.monotonic()+max(.1, min(10, timeout_seconds))
result_path = job.with_name('result.json') result_path = job.with_name('result.json')
while not result_path.exists(): while True:
if stop is not None and stop.is_set(): if stop is not None and stop.is_set():
raise InterruptedError('FILE_PROBE_CANCELLED') raise InterruptedError('FILE_PROBE_CANCELLED')
if time.monotonic() >= deadline: if time.monotonic() >= deadline:
raise TimeoutError('FILE_PROBE_TIMEOUT: 文件占用检查超时,未证明释放') raise TimeoutError('FILE_PROBE_TIMEOUT: 文件占用检查超时,未证明释放')
if process.poll() is not None: try:
raise OSError('FILE_PROBE_UNCONFIRMED: 文件探测未返回证据') record = json.loads(result_path.read_text('utf-8'))
break
except FileNotFoundError:
if process.poll() is not None and not result_path.exists():
raise OSError('FILE_PROBE_UNCONFIRMED: 文件探测未返回证据') from None
except PermissionError:
# Windows may temporarily share-lock a newly published receipt.
pass
time.sleep(.02) time.sleep(.02)
if stop is not None and stop.is_set(): if stop is not None and stop.is_set():
raise InterruptedError('FILE_PROBE_CANCELLED') raise InterruptedError('FILE_PROBE_CANCELLED')
record = json.loads(result_path.read_text('utf-8'))
if record.get('token') != token or record.get('status') != 'HELD' or process.poll() is not None: if record.get('token') != token or record.get('status') != 'HELD' or process.poll() is not None:
error = OSError('FILE_PROBE_UNCONFIRMED: '+str(record.get('error', '探测身份或句柄失效'))) error = OSError('FILE_PROBE_UNCONFIRMED: '+str(record.get('error', '探测身份或句柄失效')))
error.winerror = record.get('winerror') error.winerror = record.get('winerror')
error.blocked_resources = record.get('blocked_resources', [])
raise error raise error
# Duplicate the already-open handles before acknowledging the probe. # Duplicate the already-open handles before acknowledging the probe.
# Its exit can never create a gap in the parent's commit protection. # Its exit can never create a gap in the parent's commit protection.
@@ -64,6 +72,50 @@ def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None):
process.wait(3) process.wait(3)
def _shared_server_shutdown(address, data, database, entries):
"""Bind the retained advertisement to the exact native server shutdown."""
lines = data.decode('ascii', errors='replace').splitlines()
if len(lines) < 6 or lines[-1] != '.' or not re.fullmatch(r'(?:[0-9a-f]{4}-){11}[0-9a-f]{4}', lines[0], re.I):
return None
guid = lines[0]
session = re.fullmatch(r'(\d{4}-\d{2}-\d{2}) \d{2}\.\d{2}\.\d{2}-([1-9]\d{0,9})', lines[-2])
if session is None:
return None
log = address.parent/'log'/session[0]/(session[1].replace('-', '.')+'.txt')
if (log not in entries or not stat.S_ISREG(entries[log].st_mode)
or max(entries[database].st_mtime_ns, entries[address].st_mtime_ns) > entries[log].st_mtime_ns):
return None
with log.open('rb') as stream:
raw = stream.read(2*1024*1024+1)
if len(raw) > 2*1024*1024:
return None
from .icdb_recovery import decode_log
messages = re.findall(r'^\[[^\r\n]+\] \[[^\r\n]+\] \[\d+\] ([^\r\n]*)', decode_log(raw), re.M)
if not messages or messages[-1] != 'S: STOP' or messages.count('S: STOP') != 1:
return None
close_prefix = f'Single file [{database}] closed with size ['.casefold()
last_close = next((message for message in reversed(messages)
if message.casefold().startswith(close_prefix)), '')
if not last_close.casefold().startswith(close_prefix + f'{entries[database].st_size} ('):
return None
ordered = (
lambda line: line.startswith('iCDB Server ver.'),
lambda line: line.startswith('Machine [') and line.endswith(f' PID [{session[2]}]'),
lambda line: line.casefold().startswith(f'S: Project path [{database.parent}] on file system ['.casefold()),
lambda line: line == f'S: Server GUID [{guid}]',
lambda line: line == 'S: Wrote data to server address file',
lambda line: line == 'iCDB Server PI: Database closed',
lambda line: line == last_close,
lambda line: line.casefold() == f'AT: ERROR: Could not remove server address file [{address}]'.casefold(),
)
remaining = iter(messages[:-1])
if not all(any(matches(message) for message in remaining) for matches in ordered):
return None
return {'server_guid': guid, 'server_pid': int(session[2]), 'database': str(database.parent),
'log': str(log), 'log_sha256': hashlib.sha256(raw).hexdigest()}
def _snapshot(library, roots): def _snapshot(library, roots):
from .scoped_manifest import scan_tree from .scoped_manifest import scan_tree
entries = {library: library.lstat()} entries = {library: library.lstat()}
@@ -75,11 +127,20 @@ def _snapshot(library, roots):
if library not in native: if library not in native:
raise ValueError('目标库身份缺失') raise ValueError('目标库身份缺失')
addresses = sorted(path for path in entries if path.name.casefold() == 'saddress.adr') addresses = sorted(path for path in entries if path.name.casefold() == 'saddress.adr')
targets, signatures = [], {} targets, signatures, shared_shutdowns = [], {}, {}
from .icdb_ownership import shared_symbol_database
shared = shared_symbol_database(library)
for address in addresses: for address in addresses:
data = address.read_bytes() data = address.read_bytes()
signatures[str(address)] = hashlib.sha256(data).hexdigest() signatures[str(address)] = hashlib.sha256(data).hexdigest()
database = address.parent.parent database = address.parent.parent
if address == shared/'cdbsvr/sAddress.adr' and shared/'icdb.dat' in native:
targets.append({'scope': 'shared_symbols', 'database': str(shared), 'address': str(address)})
with_shutdown = _shared_server_shutdown(address, data, shared/'icdb.dat', entries)
if with_shutdown is not None:
shared_shutdowns[str(address)] = with_shutdown
signatures[with_shutdown['log']] = with_shutdown['log_sha256']
continue
matches = [] matches = []
for project in database.parent.glob('*.prj'): for project in database.parent.glob('*.prj'):
if project not in entries or project.stat().st_size > 1024*1024: if project not in entries or project.stat().st_size > 1024*1024:
@@ -95,6 +156,7 @@ def _snapshot(library, roots):
signatures[str(matches[0])] = hashlib.sha256(matches[0].read_bytes()).hexdigest() signatures[str(matches[0])] = hashlib.sha256(matches[0].read_bytes()).hexdigest()
return {'exclusive_files': [str(p) for p in native], 'addresses': [str(p) for p in addresses], return {'exclusive_files': [str(p) for p in native], 'addresses': [str(p) for p in addresses],
'inspection_targets': targets, 'signatures': signatures, 'binding_files': sorted(signatures), 'inspection_targets': targets, 'signatures': signatures, 'binding_files': sorted(signatures),
'shared_shutdowns': shared_shutdowns,
'resource_scope': {'library': str(library), 'roots': [str(p) for p in roots], 'resource_scope': {'library': str(library), 'roots': [str(p) for p in roots],
'projects': sorted(str(p) for p in entries if p.suffix.casefold() == '.prj'), 'projects': sorted(str(p) for p in entries if p.suffix.casefold() == '.prj'),
'shared_dependencies': sorted(str(p.parent) for p in native 'shared_dependencies': sorted(str(p.parent) for p in native
@@ -102,12 +164,61 @@ def _snapshot(library, roots):
'databases': sorted({str(p.parent) for p in native if p.name.casefold() == 'icdb.dat'})}} 'databases': sorted({str(p.parent) for p in native if p.name.casefold() == 'icdb.dat'})}}
def _saved_project_snapshot(library, project, pcb, checked_path):
from .backup_recovery import _decode_project_text
from .icdb_ownership import database_directories
if (project.suffix.casefold() != '.prj' or not project.is_relative_to(library.parent)
or pcb.suffix.casefold() != '.pcb' or not pcb.is_relative_to(project.parent)):
raise ValueError('保存释放检查的工程范围不属于所选库')
candidates = {path/'icdb.dat': False for path in database_directories(library, project, pcb)}
signatures = {}
auxiliary = checked_path(pcb.parent/'pcb.prj')
configs = (project, auxiliary) if auxiliary.exists() and auxiliary != project else (project,)
for config in configs:
if not config.is_file():
raise ValueError(f'保存释放检查缺少工程配置:{config}')
with config.open('rb') as stream:
data = stream.read(1024*1024+1)
if len(data) > 1024*1024:
raise ValueError(f'工程配置过大:{config}')
references = re.findall(r'^KEY[ \t]+iCDBDir\b[^\r\n]*', _decode_project_text(data), re.I | re.M)
signatures[str(config)] = hashlib.sha256(data).hexdigest()
if not references:
continue
reference = (re.fullmatch(r'KEY[ \t]+iCDBDir[ \t]+"([^"\r\n]+)"[ \t]*', references[0], re.I)
if len(references) == 1 else None)
if reference is None or PureWindowsPath(reference[1]).anchor:
raise ValueError(f'工程 iCDBDir 必须唯一且为相对路径:{config}')
target = checked_path(config.parent/reference[1]/'icdb.dat')
if not target.is_relative_to(project.parent):
raise ValueError(f'工程 iCDBDir 越出工程范围:{config}')
candidates[target] = True
files = [str(library)]
for candidate, required in candidates.items():
path = checked_path(candidate)
try:
info = path.lstat()
except FileNotFoundError:
if required:
raise ValueError(f'工程引用的数据库不存在:{path}') from None
continue
if not stat.S_ISREG(info.st_mode):
raise ValueError(f'数据库路径不是普通文件:{path}')
files.append(str(path))
return {'exclusive_files': list(dict.fromkeys(files)), 'binding_files': list(signatures),
'signatures': signatures}
def file_probe_main(job): def file_probe_main(job):
"""No native launch, writes, repair, address deletion or process termination.""" """No native launch, writes, repair, address deletion or process termination."""
import win32con, win32file import win32con, win32file
job = Path(job) job = Path(job)
request = json.loads(job.read_text('utf-8')) request = json.loads(job.read_text('utf-8'))
result = {'token': request['token'], 'status': 'UNCONFIRMED'} result = {'token': request['token'], 'status': 'UNCONFIRMED'}
opening = None
try: try:
def checked_path(value): def checked_path(value):
path = Path(value).absolute() path = Path(value).absolute()
@@ -123,20 +234,29 @@ def file_probe_main(job):
roots = [checked_path(p) for p in request['roots']] if request['roots'] is not None else [library.parent] roots = [checked_path(p) for p in request['roots']] if request['roots'] is not None else [library.parent]
if library.suffix.casefold() != '.lmc' or any(not p.is_relative_to(library.parent) for p in roots): if library.suffix.casefold() != '.lmc' or any(not p.is_relative_to(library.parent) for p in roots):
raise ValueError('文件探测范围不属于所选库') raise ValueError('文件探测范围不属于所选库')
snapshot = _snapshot(library, roots) def read_snapshot():
if request.get('saved_project') is None:
return _snapshot(library, roots)
project, pcb = (checked_path(path) for path in request['saved_project'])
return _saved_project_snapshot(library, project, pcb, checked_path)
snapshot = read_snapshot()
with ExitStack() as stack: with ExitStack() as stack:
handles = [] handles = []
for path in snapshot['exclusive_files']: for path in snapshot['exclusive_files']:
opening = path
handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None, handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close) stack.callback(handle.Close)
handles.append(int(handle)) handles.append(int(handle))
for path in snapshot['binding_files']: for path in snapshot['binding_files']:
opening = path
handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ, handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ,
None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close) stack.callback(handle.Close)
handles.append(int(handle)) handles.append(int(handle))
if _snapshot(library, roots) != snapshot: opening = None
if read_snapshot() != snapshot:
raise ValueError('占用检查期间资源集合变化') raise ValueError('占用检查期间资源集合变化')
pending = job.with_name('result.pending') pending = job.with_name('result.pending')
pending.write_text(json.dumps({**result, **snapshot, 'status': 'HELD', 'handles': handles}), 'utf-8') pending.write_text(json.dumps({**result, **snapshot, 'status': 'HELD', 'handles': handles}), 'utf-8')
@@ -145,7 +265,8 @@ def file_probe_main(job):
return 0 return 0
except Exception as error: except Exception as error:
pending = job.with_name('result.pending') pending = job.with_name('result.pending')
pending.write_text(json.dumps({**result, 'error': str(error), blocked = [opening] if opening and getattr(error, 'winerror', None) in (32,33) else []
'winerror': getattr(error, 'winerror', None)}), 'utf-8') pending.write_text(json.dumps({**result, 'error': (opening+': ' if opening else '')+str(error),
'winerror': getattr(error, 'winerror', None), 'blocked_resources': blocked}), 'utf-8')
pending.replace(job.with_name('result.json')) pending.replace(job.with_name('result.json'))
return 1 return 1
+42 -2
View File
@@ -1,5 +1,6 @@
"""Known native database owners touched by a CBB verification operation.""" """Known native database owners touched by a CBB verification operation."""
from pathlib import Path from pathlib import Path
import time
def session_resource_scope(job): def session_resource_scope(job):
@@ -8,18 +9,22 @@ def session_resource_scope(job):
project, pcb = job.get('project'), job.get('pcb') project, pcb = job.get('project'), job.get('pcb')
projects = [str(Path(project))] if project else [] projects = [str(Path(project))] if project else []
databases = [str(Path(p).parent/'database') for p in (project, pcb) if p] databases = [str(Path(p).parent/'database') for p in (project, pcb) if p]
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb' shared = shared_symbol_database(library)
return {'scope_state': 'DECLARED' if project else 'RECHECK_REQUIRED', return {'scope_state': 'DECLARED' if project else 'RECHECK_REQUIRED',
'library': str(library), 'operation_id': job.get('operation_id'), 'library': str(library), 'operation_id': job.get('operation_id'),
'block_name': job.get('block'), 'projects': projects, 'block_name': job.get('block'), 'projects': projects,
'databases': list(dict.fromkeys(databases)), 'shared_dependencies': [str(shared)]} 'databases': list(dict.fromkeys(databases)), 'shared_dependencies': [str(shared)]}
def shared_symbol_database(library):
return Path(library).parent/'SymbolLibs/__ReusableBlocksSymb'
def database_directories(lmc_file, project, pcb): def database_directories(lmc_file, project, pcb):
return tuple(dict.fromkeys(( return tuple(dict.fromkeys((
Path(project).parent/'database', Path(project).parent/'database',
Path(pcb).parent/'database', Path(pcb).parent/'database',
Path(lmc_file).parent/'SymbolLibs/__ReusableBlocksSymb', shared_symbol_database(lmc_file),
))) )))
@@ -29,6 +34,36 @@ def unreleased_addresses(lmc_file, project, pcb):
if (path/'cdbsvr/sAddress.adr').exists()] if (path/'cdbsvr/sAddress.adr').exists()]
def wait_for_saved_database_release(library, project, pcb, *, stop=None,
report_pending=lambda **event: None, timeout_seconds=75):
"""Check scoped files after PCB exits, outside the host native channel."""
from .file_probe import hold_release_files
from .operation_queue import note_metadata_progress
deadline = time.monotonic() + timeout_seconds
reported = None
while True:
try:
with hold_release_files(library, saved_project=(project, pcb), timeout_seconds=deadline-time.monotonic(),
stop=stop) as proof:
return {**proof, 'status': 'RELEASE_CONFIRMED', 'blocked_resources': []}
except (OSError, ValueError) as error:
winerror = getattr(error, 'winerror', None)
blocked = getattr(error, 'blocked_resources', [])
remaining = deadline - time.monotonic()
if winerror not in (32, 33) or remaining <= 0:
return {'status': 'IN_USE' if winerror in (32, 33) else 'UNCONFIRMED',
'detail': str(error), 'winerror': winerror, 'blocked_resources': blocked}
if stop is not None and stop.is_set():
return {'status': 'UNCONFIRMED', 'detail': '已取消释放检查',
'blocked_resources': blocked}
note_metadata_progress()
if blocked != reported:
report_pending(blocked_resources=blocked)
reported = blocked
time.sleep(min(1, remaining))
def inspect_release_addresses(snapshot, *, stop=None): def inspect_release_addresses(snapshot, *, stop=None):
"""An address is a reason for native inspection, never an occupancy verdict.""" """An address is a reason for native inspection, never an occupancy verdict."""
import tempfile import tempfile
@@ -37,6 +72,11 @@ def inspect_release_addresses(snapshot, *, stop=None):
from .library_lock import LibraryBusy from .library_lock import LibraryBusy
results = [] results = []
for item in snapshot['inspection_targets']: for item in snapshot['inspection_targets']:
if item.get('scope') == 'shared_symbols':
if item['address'] in snapshot.get('shared_shutdowns', {}):
continue
raise LibraryBusy('SHARED_ICDB_INSPECTION_UNAVAILABLE: 共享符号库地址需要原生核对:'
+ item['address'])
target = RepairTarget(Path(item['project']), Path(item['database'])) target = RepairTarget(Path(item['project']), Path(item['database']))
root = Path(tempfile.mkdtemp(prefix='cbb-release-inspection-')) root = Path(tempfile.mkdtemp(prefix='cbb-release-inspection-'))
result = run_native_repair(target, root, inspection_only=True, stop=stop) result = run_native_repair(target, root, inspection_only=True, stop=stop)
+6 -1
View File
@@ -373,6 +373,9 @@ def _owner_matches_scope(item, library, roots):
return None return None
candidates = [] candidates = []
worker_flags = {'--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker'} worker_flags = {'--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker'}
path_flags = {'-icdb', '-project', '-p'}
if ntpath.basename(str(item.get('name') or args[0])).casefold() == 'icdbnetserver.exe':
path_flags.add('-db')
for index, arg in enumerate(args[1:], 1): for index, arg in enumerate(args[1:], 1):
if arg.casefold() in worker_flags and index + 1 < len(args): if arg.casefold() in worker_flags and index + 1 < len(args):
try: try:
@@ -388,7 +391,7 @@ def _owner_matches_scope(item, library, roots):
value = arg.split('=', 1)[1] if arg.startswith('-') and '=' in arg else arg value = arg.split('=', 1)[1] if arg.startswith('-') and '=' in arg else arg
if (ntpath.isabs(value) and (ntpath.splitext(value)[1].casefold() in ('.prj', '.pcb', '.lmc') if (ntpath.isabs(value) and (ntpath.splitext(value)[1].casefold() in ('.prj', '.pcb', '.lmc')
or arg.casefold().startswith(('-project=', '-icdb=')) or arg.casefold().startswith(('-project=', '-icdb='))
or args[index - 1].casefold() in ('-icdb', '-project', '-p'))): or args[index - 1].casefold() in path_flags)):
candidates.append(value) candidates.append(value)
normalized_roots = [ntpath.normcase(ntpath.normpath(str(root))) for root in roots] normalized_roots = [ntpath.normcase(ntpath.normpath(str(root))) for root in roots]
expected_library = ntpath.normcase(ntpath.normpath(str(library))) expected_library = ntpath.normcase(ntpath.normpath(str(library)))
@@ -559,6 +562,7 @@ def _prove_library_released(library, block_name=None, *, block_names=(), allow_u
except OSError as error: except OSError as error:
blocked = LibraryBusy(str(error)) blocked = LibraryBusy(str(error))
blocked.winerror = getattr(error, 'winerror', None) blocked.winerror = getattr(error, 'winerror', None)
blocked.blocked_resources = getattr(error, 'blocked_resources', [])
raise blocked from error raise blocked from error
note_metadata_progress() note_metadata_progress()
if files['addresses']: if files['addresses']:
@@ -576,6 +580,7 @@ def _prove_library_released(library, block_name=None, *, block_names=(), allow_u
except OSError as error: except OSError as error:
blocked = LibraryBusy(str(error)) blocked = LibraryBusy(str(error))
blocked.winerror = getattr(error, 'winerror', None) blocked.winerror = getattr(error, 'winerror', None)
blocked.blocked_resources = getattr(error, 'blocked_resources', [])
raise blocked from error raise blocked from error
if any(current[key] != files[key] for key in ( if any(current[key] != files[key] for key in (
'exclusive_files', 'addresses', 'signatures', 'inspection_targets')): 'exclusive_files', 'addresses', 'signatures', 'inspection_targets')):
+2 -10
View File
@@ -4,7 +4,7 @@ import logging
import json import json
from collections import Counter, defaultdict from collections import Counter, defaultdict
from .models import CbbRecord, LibraryReadResult from .models import CbbRecord, LibraryReadResult
from .network_path import absolute_preserving_drive from .network_path import absolute_preserving_drive, validate_library_file
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
CACHE_SCHEMA_VERSION = 2 CACHE_SCHEMA_VERSION = 2
@@ -206,15 +206,7 @@ def read_library_fast(path: Path, *, status_reader=None):
"""Discover directories; this does not validate native format/registration.""" """Discover directories; this does not validate native format/registration."""
try: try:
path = Path(path) path = Path(path)
if path.suffix.casefold() != '.lmc': validate_library_file(path)
return LibraryReadResult((), 'INPUT_SUFFIX: 请选择 .lmc 中心库文件。')
if not path.is_file():
return LibraryReadResult((), f'INPUT_MISSING: 中心库不存在或不是文件: {path}')
with path.open('rb') as stream:
if not stream.read(1):
return LibraryReadResult((), 'INPUT_EMPTY: 中心库文件为空。')
if any(lock.is_dir() for lock in (path.with_suffix('.lock'), path.with_name('.'+path.stem+'.cbb-upload.lock'))):
return LibraryReadResult((), 'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录。')
folder = path.parent/'ReusableBlocksLP' folder = path.parent/'ReusableBlocksLP'
if folder.exists() and not folder.is_dir(): if folder.exists() and not folder.is_dir():
return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}') return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}')
@@ -0,0 +1,171 @@
"""Preserve one generated PCB Cell Library after a bound integration failure."""
from contextlib import contextmanager, ExitStack
import hashlib
import json
import os
from pathlib import Path
import re
import stat
def _cache_paths(pcb):
cache = Path(pcb).parent/'Work/Layout_Temp'
return cache, cache/'JobPrefsDB.jpf'
def _cache_identity(cache):
metadata = cache.lstat()
if not stat.S_ISDIR(metadata.st_mode) or metadata.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError('本地 Cell Library 不是普通目录')
if cache.resolve(strict=True) != cache:
raise ValueError('本地 Cell Library 路径含链接')
return {'device': metadata.st_dev, 'file_id': metadata.st_ino,
'created_ns': metadata.st_ctime_ns}
def _digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def capture_binding_change(job, config, emit):
"""Keep the exact changed pcb.prj and the pre-launch generated directory identity."""
from .management import _write_json
cache, preferences = _cache_paths(job['pcb'])
if not preferences.is_file():
return
try:
record = {key: str(job[key]) for key in ('operation_id', 'project', 'pcb', 'lmc_file', 'block_name')}
record.update(config=str(config), config_sha256=_digest(config), original_cache=_cache_identity(cache))
_write_json(Path(job['root'])/'local-cell-library-binding.json', record)
except (OSError, ValueError, KeyError) as error:
emit(stage='local_cell_library_binding_unavailable', detail=str(error))
def _explicit_cache_error(text, preferences):
native = str(text).replace('/', '\\').casefold()
path = str(preferences).replace('/', '\\').casefold()
return ('could not load job preferences db' in native and 'unable to create local cell library' in native
and re.search(re.escape(path) + r'(?![\w.\\/])', native) is not None)
@contextmanager
def _hold_primary_files(proof, cache, required):
"""Keep the proven databases protected while moving the generated directory."""
import win32con
import win32file
paths = {Path(p) for p in proof['exclusive_files'] if not Path(p).is_relative_to(cache)}
if not required <= paths:
raise ValueError('缺少主要工程文件占用证明')
with ExitStack() as stack:
for path in sorted(paths):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
for name, digest in proof['signatures'].items():
path = Path(name)
if not path.is_relative_to(cache):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, win32con.FILE_SHARE_READ, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
if _digest(path) != digest:
raise ValueError('会话地址或工程绑定已变化')
yield
def preserve_failed_cache(request, result, *, stop=None):
"""After clean exit, preserve generated files and return one retry's receipt."""
if not result.safe_to_continue or not result.evidence_path or (stop is not None and stop.is_set()):
return None
import pywintypes
from .backup_recovery import _project_text
from .library_lock import _prove_library_released
from .management import _write_json
from .mentor_adapter import _CENTRAL_LIBRARY_KEY
from .operation_queue import QueueCancelled, check_active, local_commit
from .scoped_manifest import scan_tree
from .verify_runner import preflight
root = Path(result.evidence_path).parent
receipt_path = root/'local-cell-library-retry.json'
binding_path = root/'local-cell-library-binding.json'
if not binding_path.is_file() or receipt_path.exists():
return None
try:
job = json.loads((root/'request.json').read_text(encoding='utf-8'))
binding = json.loads(binding_path.read_text(encoding='utf-8'))
project, pcb = preflight(request)
if (binding.get('operation_id') != job.get('operation_id') or not job.get('operation_id')
or binding.get('block_name') != request.block_name
or any(not binding.get(key) or Path(binding[key]).resolve() != Path(path).resolve()
for key, path in [('lmc_file', request.lmc_file), ('project', project), ('pcb', pcb)])):
return None
cache, preferences = _cache_paths(pcb)
config = pcb.with_name('pcb.prj')
if not _explicit_cache_error(result.stderr, preferences):
return None
events = [json.loads(line) for line in (root/'events.jsonl').read_text(encoding='utf-8').splitlines()]
stages = {event.get('stage') for event in events}
identity_bound = any(event.get('stage') == 'identity_verified'
and Path(event.get('project') or '.').resolve() == project.resolve()
and Path(event.get('document') or '.').name.casefold() == pcb.name.casefold()
for event in events)
if (not identity_bound
or not any(event.get('stage') == 'central_library_path' and event.get('status') == 'UPDATED'
and Path(event.get('path') or '.').resolve() == config.resolve()
and Path(event.get('target') or '.').resolve() == Path(request.lmc_file).resolve()
for event in events)
or stages.intersection({'save_start', 'save_helper', 'save_progress', 'saved_and_closed'})
or (root/'save.log').exists()
or not any(event.get('stage') == 'integration_error'
and _explicit_cache_error(event.get('detail'), preferences) for event in events)):
return None
def validate_binding():
if (config.resolve(strict=True) != config or config != Path(binding['config'])
or _digest(config) != binding['config_sha256'] or _cache_identity(cache) != binding['original_cache']):
raise ValueError('PCB 项目绑定或生成目录身份已变化')
references = _CENTRAL_LIBRARY_KEY.findall(_project_text(config))
if not references or any((config.parent/target).resolve() != Path(request.lmc_file).resolve()
for _, target, _ in references):
raise ValueError('PCB 项目未绑定当前中心库')
members = scan_tree(cache, check=check_active)
if not all(path in members and stat.S_ISREG(members[path].st_mode)
for path in (preferences, cache/'CellDB.cel')):
raise ValueError('未确认 Mentor 生成的本地 Cell Library 文件')
validate_binding()
with _prove_library_released(request.lmc_file, block_name=request.block_name, stop=stop) as proof:
if proof.get('data_recovery_required') is True or proof.get('blocked_resources'):
raise ValueError('数据库资源仍待确认')
# Windows cannot rename this directory while an exclusive handle to
# its generated LayoutDB is held. The current library lease stays held.
validate_binding()
preserved = project.parent.parent/('Layout_Temp.before-rebuild-' + root.name)
if os.path.lexists(preserved):
return None
receipt = {'kind': 'LOCAL_CELL_LIBRARY_RETRY', 'status': 'PRESERVE_REQUESTED',
'original_operation_id': binding['operation_id'],
'initial_evidence': str(result.evidence_path), 'cache': str(cache),
'preserved_name': preserved.name, 'preserved_path': str(preserved)}
_write_json(receipt_path, receipt)
required = {Path(request.lmc_file).resolve(), (pcb.parent/'Layout/LayoutDB.lyt').resolve()}
with _hold_primary_files(proof, cache, required), local_commit():
if stop is not None and stop.is_set():
return None
validate_binding()
cache.rename(preserved)
receipt['status'] = 'PRESERVED'
_write_json(receipt_path, receipt)
return receipt
except QueueCancelled:
raise
except (OSError, ValueError, KeyError, TypeError, RuntimeError, pywintypes.error) as error:
try:
_write_json(root/'local-cell-library-retry-unavailable.json', {
'initial_evidence': str(result.evidence_path), 'detail': str(error)})
except OSError:
pass
return None
+28 -9
View File
@@ -171,7 +171,7 @@ def _may_have_mutated(record):
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None, version_prompt=None, def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None, version_prompt=None,
write_admission=None): write_admission=None):
from .verify_runner import VerifyRequest, run_verify from .verify_runner import VerifyRequest, run_verify, _notify_progress
from .backup_recovery import _idle_check from .backup_recovery import _idle_check
from contextlib import ExitStack from contextlib import ExitStack
from .operation_queue import check_active, native_channel, task_stop, remember_result from .operation_queue import check_active, native_channel, task_stop, remember_result
@@ -216,7 +216,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
_write_json(report, {**asdict(request), 'stage': stage, 'status': 'RUNNING', _write_json(report, {**asdict(request), 'stage': stage, 'status': 'RUNNING',
'safe_to_continue': False, 'history': history, 'backup_policy': 'manual'}) 'safe_to_continue': False, 'history': history, 'backup_policy': 'manual'})
if progress: if progress:
progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details}) _notify_progress(progress, {'stage': stage, 'block': request.name, 'operation': request.operation, **details})
def finish(status, detail='', safe=True): def finish(status, detail='', safe=True):
nonlocal change_report nonlocal change_report
remember_result(ManagementResult(request.operation, request.library, request.name, request.partition, remember_result(ManagementResult(request.operation, request.library, request.name, request.partition,
@@ -465,7 +465,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, context=None, **kwargs): def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, context=None, **kwargs):
from threading import Event from threading import Event
from .write_admission import WriteAdmission from .write_admission import WriteAdmission
from .operation_queue import QueueCancelled, TaskHandoff, request_library_keys, remember_result, current_context from .verify_runner import _notify_progress
from .operation_queue import QueueCancelled, QueueUnavailable, TaskHandoff, request_library_keys, remember_result, current_context
context = context or current_context() context = context or current_context()
if context is not None: if context is not None:
stop = stop if stop is not None else context.stop stop = stop if stop is not None else context.stop
@@ -474,19 +475,30 @@ def run_management_batch(requests, *, stop=None, progress=None, item_executor=No
stop = Event() stop = Event()
kwargs.setdefault('write_admission',WriteAdmission(prompt=kwargs.get('version_prompt'),stop=stop)) kwargs.setdefault('write_admission',WriteAdmission(prompt=kwargs.get('version_prompt'),stop=stop))
results = [] results = []
retained_libraries = set() retained_libraries = {}
cancelled = False cancelled = False
for request in requests: for request in requests:
keys = request_library_keys(request, context) keys = request_library_keys(request, context)
stopped = (cancelled or stop.is_set() or context is not None stopped = (cancelled or stop.is_set() or context is not None
and (context.stop.is_set() or context.stop_after_current.is_set())) and (context.stop.is_set() or context.stop_after_current.is_set()))
if not stopped:
for index in {retained_libraries[key][1] for key in keys.intersection(retained_libraries)}:
previous = next(value[0] for value in retained_libraries.values() if value[1] == index)
from .operation_lifecycle import recheck_failed_release
refreshed = recheck_failed_release(previous.library, previous.name, results[index], stop=stop)
if refreshed.safe_to_continue:
results[index] = refreshed
retained_libraries = {k:v for k,v in retained_libraries.items() if v[1] != index}
if stopped or keys.intersection(retained_libraries): if stopped or keys.intersection(retained_libraries):
previous = (retained_libraries[next(iter(keys.intersection(retained_libraries)))][0]
if not stopped else None)
result = ManagementResult(request.operation, request.library, request.name, request.partition, result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'complete', 'SKIPPED', True, request.source, request.auto_verify, 'admission', 'SKIPPED', True,
'队列已停止,未操作此 CBB' if stopped else '同库原生会话尚未释放,未启动新的写入') '队列已停止,未操作此 CBB' if stopped else
f'PREVIOUS_SESSION_UNRELEASED: 前项 {previous.name} 的同库会话尚未释放,当前项未启动。')
results.append(result) results.append(result)
if progress: if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail}) _notify_progress(progress, {'stage': result.status, 'block': result.name, 'detail': result.detail})
continue continue
def action(): def action():
result = run_management(request, progress=progress, stop=stop, **kwargs) result = run_management(request, progress=progress, stop=stop, **kwargs)
@@ -497,6 +509,9 @@ def run_management_batch(requests, *, stop=None, progress=None, item_executor=No
return result return result
try: try:
result = item_executor(request, action) if item_executor is not None else action() result = item_executor(request, action) if item_executor is not None else action()
except QueueUnavailable as error:
result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'admission', 'SKIPPED', True, str(error))
except QueueCancelled as error: except QueueCancelled as error:
known = error.result if isinstance(error, TaskHandoff) else None known = error.result if isinstance(error, TaskHandoff) else None
if isinstance(known, ManagementResult): if isinstance(known, ManagementResult):
@@ -510,12 +525,16 @@ def run_management_batch(requests, *, stop=None, progress=None, item_executor=No
request.source, request.auto_verify, 'complete', request.source, request.auto_verify, 'complete',
'TIMEOUT' if isinstance(error, TaskHandoff) and not error.cancelled else 'CANCELLED', 'TIMEOUT' if isinstance(error, TaskHandoff) and not error.cancelled else 'CANCELLED',
not isinstance(error, TaskHandoff), str(error)) not isinstance(error, TaskHandoff), str(error))
except Exception as error:
result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'exception', 'RECOVERY_REQUIRED', False,
'BATCH_ITEM_EXCEPTION: '+str(error))
results.append(result) results.append(result)
if progress: if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail, _notify_progress(progress, {'stage': result.status, 'block': result.name, 'detail': result.detail,
'evidence_path': str(result.evidence_path or '')}) 'evidence_path': str(result.evidence_path or '')})
if not result.safe_to_continue: if not result.safe_to_continue:
retained_libraries.update(keys) retained_libraries.update({key:(request, len(results)-1) for key in keys})
if result.status == 'CANCELLED': if result.status == 'CANCELLED':
cancelled = True cancelled = True
return results return results
+21 -7
View File
@@ -709,8 +709,11 @@ def execute_job(job, emit):
else: else:
from .maintenance_entry import maintenance_project_files from .maintenance_entry import maintenance_project_files
for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])): for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])):
ensure_project_central_library(config, job['lmc_file'], changed = ensure_project_central_library(config, job['lmc_file'],
evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit) evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit)
if changed and prewrite_eligible and config == Path(job['pcb']).with_name('pcb.prj'):
from .local_cell_library import capture_binding_change
capture_binding_change(job, config, emit)
if prewrite_eligible: if prewrite_eligible:
from .diagnostic_open import snapshot_diagnostic_logs from .diagnostic_open import snapshot_diagnostic_logs
from .session_record import process_identity from .session_record import process_identity
@@ -841,6 +844,8 @@ def execute_job(job, emit):
cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe' cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe'
from .desktop_worker import launch_save_helper from .desktop_worker import launch_save_helper
helper_gate = root/'start-save.signal' helper_gate = root/'start-save.signal'
from .residual_sessions import OrphanedVerifySavePrompt
orphaned_prompt = OrphanedVerifySavePrompt(job, worker_pid, emit)
with (root/'save.log').open('w', encoding='utf-8') as log: with (root/'save.log').open('w', encoding='utf-8') as log:
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project'], helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project'],
Path(job['pcb']).name, str(job.get('cancel_signal') or ''), str(helper_gate)], Path(job['pcb']).name, str(job.get('cancel_signal') or ''), str(helper_gate)],
@@ -858,11 +863,12 @@ def execute_job(job, emit):
last_markers = current last_markers = current
from .runtime_timing import parse_save_progress from .runtime_timing import parse_save_progress
emit(stage='save_progress', helper_exited=False, **parse_save_progress('\n'.join(current))) emit(stage='save_progress', helper_exited=False, **parse_save_progress('\n'.join(current)))
orphaned_prompt.poll(current)
time.sleep(.2) time.sleep(.2)
code = helper.returncode code = helper.returncode
save_log = (root/'save.log').read_bytes().decode('utf-8', errors='replace') save_log = (root/'save.log').read_bytes().decode('utf-8', errors='replace')
from .runtime_timing import parse_save_progress from .runtime_timing import parse_save_progress
emit(stage='save_progress', helper_exited=True, **parse_save_progress(save_log)) emit(stage='save_progress', helper_exited=True, helper_exit_code=code, **parse_save_progress(save_log))
markers = set(save_log.splitlines()) markers = set(save_log.splitlines())
from .operation_lifecycle import classify_save_state from .operation_lifecycle import classify_save_state
write_facts = classify_save_state(save_log.splitlines(), helper_exited=True, native_released=None) write_facts = classify_save_state(save_log.splitlines(), helper_exited=True, native_released=None)
@@ -911,7 +917,7 @@ def execute_job(job, emit):
pass pass
if helper is not None and helper.poll() is None: if helper is not None and helper.poll() is None:
emit(stage='save_helper_retained', helper_pid=helper.pid) emit(stage='save_helper_retained', helper_pid=helper.pid)
elif helper is not None: elif helper is not None and not completed:
# A failed/truncated Save result never authorizes discard-close. # A failed/truncated Save result never authorizes discard-close.
emit(stage='save_result_retained', detail='保存或关闭结果不完整,保留原生会话供核对') emit(stage='save_result_retained', detail='保存或关闭结果不完整,保留原生会话供核对')
elif diagnostic_close_attempted: elif diagnostic_close_attempted:
@@ -1019,17 +1025,25 @@ def worker_main(request_path):
'integration_action_complete': 'POSTCALL', 'saved_and_closed': 'RELEASE_CHECK', 'integration_action_complete': 'POSTCALL', 'saved_and_closed': 'RELEASE_CHECK',
'complete': 'FINISHED', 'failed': 'UNCONFIRMED'}.get(event.get('stage')) 'complete': 'FINISHED', 'failed': 'UNCONFIRMED'}.get(event.get('stage'))
identities = [(role, event.get(key)) for role, key in identities = [(role, event.get(key)) for role, key in
(('native', 'pcb_pid'), ('native', 'lm_pid'), ('helper', 'helper_pid')) (('native', 'pcb_pid'), ('native', 'lm_pid'))
if event.get(key)] if event.get(key)]
facts = None facts = None
continuing_save = False
if event.get('stage') == 'save_progress': if event.get('stage') == 'save_progress':
from .operation_lifecycle import classify_save_state from .operation_lifecycle import classify_save_state
facts = classify_save_state(event.get('markers', ()), facts = classify_save_state(event.get('markers', ()),
helper_exited=event.get('helper_exited'), native_released=None) helper_exited=event.get('helper_exited'), native_released=None)
phase = ('POSTCALL' if event.get('helper_exited') is True else facts['save_close_confirmed'] = (
'CLOSING' if 'CLOSE_START' in event.get('markers', ()) else 'NATIVE_CALL') event.get('helper_exited') is True and event.get('helper_exit_code') == 0
and facts['interrupted'] is False
and save_log_has_core_markers('\n'.join(event.get('markers', ())))
)
# Save and Close run in one already admitted helper.
continuing_save = event.get('helper_exited') is not True
phase = 'NATIVE_CALL' if continuing_save else 'POSTCALL'
if phase or identities: if phase or identities:
update_worker_state(job, phase or 'UNCONFIRMED', identities=identities, write_outcome=facts) update_worker_state(job, phase or 'UNCONFIRMED', identities=identities,
write_outcome=facts, continuation=continuing_save)
event.update(time=time.strftime('%Y-%m-%d %H:%M:%S'), block=job['block_name'], event.update(time=time.strftime('%Y-%m-%d %H:%M:%S'), block=job['block_name'],
monotonic_seconds=time.monotonic()) monotonic_seconds=time.monotonic())
with (root/'events.jsonl').open('a', encoding='utf-8') as stream: with (root/'events.jsonl').open('a', encoding='utf-8') as stream:
+131 -25
View File
@@ -24,9 +24,10 @@ _retained_workers = []
class NativeOperationError(RuntimeError): class NativeOperationError(RuntimeError):
def __init__(self, detail, *, safe_to_continue): def __init__(self, detail, *, safe_to_continue, blocking_manager_pids=()):
super().__init__(detail) super().__init__(detail)
self.safe_to_continue = safe_to_continue self.safe_to_continue = safe_to_continue
self.blocking_manager_pids = tuple(blocking_manager_pids)
# Coordinator-owned Create/Add/conflict/update/remove/backup-reimport evidence: # Coordinator-owned Create/Add/conflict/update/remove/backup-reimport evidence:
# diagnostics/issue2-native-crud-20261103/engine-e2e/cycle-result.json # diagnostics/issue2-native-crud-20261103/engine-e2e/cycle-result.json
_PRODUCTION_ADD_VALIDATED = True _PRODUCTION_ADD_VALIDATED = True
@@ -245,13 +246,17 @@ class NativeManagementAdapter:
if hasattr(worker, 'bind_session'): if hasattr(worker, 'bind_session'):
worker.bind_session(job) worker.bind_session(job)
from contextlib import nullcontext from contextlib import nullcontext
from .operation_queue import commit_worker_start, native_channel from .operation_queue import commit_worker_start, native_channel, task_stop
# Only admitted native waiting outlives the UI's metadata deadline. # Only admitted native waiting outlives the UI's metadata deadline.
channel = native_channel(read_only=True) if job.get('worker_role') == 'catalog_readonly' else nullcontext() read_only = job.get('worker_role') == 'catalog_readonly'
channel = native_channel(read_only=True) if read_only else nullcontext()
stop = task_stop(self.stop) if read_only else self.stop
cancelled = False
with channel: with channel:
commit_worker_start(worker, job) commit_worker_start(worker, job)
while worker.poll() is None and time.monotonic() < deadline: while worker.poll() is None and time.monotonic() < deadline:
if self.stop is not None and self.stop.is_set(): if stop is not None and stop.is_set():
cancelled = True
Path(job['cancel_signal']).touch() Path(job['cancel_signal']).touch()
break break
time.sleep(.1) time.sleep(.1)
@@ -268,8 +273,9 @@ class NativeManagementAdapter:
if self.session_progress is not None else None) if self.session_progress is not None else None)
if add_job: if add_job:
(evidence/'cancel-native-add.signal').touch() (evidence/'cancel-native-add.signal').touch()
reason = 'CANCELLED' if cancelled else 'TIMEOUT'
return {'success': False, 'safe_to_continue': False, return {'success': False, 'safe_to_continue': False,
'detail': f'TIMEOUT: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'} 'detail': f'{reason}: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'}
try: try:
result = json.loads((evidence/'result.json').read_text(encoding='utf-8')) result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
if not isinstance(result.get('safe_to_continue'), bool): if not isinstance(result.get('safe_to_continue'), bool):
@@ -281,15 +287,20 @@ class NativeManagementAdapter:
finally: finally:
worker.close() worker.close()
def catalog(self, library, evidence): def catalog(self, library, evidence, *, include_engineering_identity=True):
result = self._worker({'operation': 'catalog', 'worker_role': 'catalog_readonly', result = self._worker({'operation': 'catalog', 'worker_role': 'catalog_readonly',
'library': str(absolute_preserving_drive(library))}, evidence) 'library': str(absolute_preserving_drive(library)),
'include_engineering_identity': include_engineering_identity}, evidence)
if not result.get('success') or not result.get('safe_to_continue'): if not result.get('success') or not result.get('safe_to_continue'):
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'), raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
safe_to_continue=result.get('safe_to_continue') is True) safe_to_continue=result.get('safe_to_continue') is True,
blocking_manager_pids=result.get('blocking_manager_pids', ()))
return Catalog(Path(result['library']), int(result['flow']), return Catalog(Path(result['library']), int(result['flow']),
tuple(CatalogEntry(**entry) for entry in result['entries']), result['safe_to_continue']) tuple(CatalogEntry(**entry) for entry in result['entries']), result['safe_to_continue'])
def catalog_registrations(self, library, evidence):
return self.catalog(library, evidence, include_engineering_identity=False)
def remove(self, request, evidence): def remove(self, request, evidence):
caps = self.capabilities() caps = self.capabilities()
if not caps['remove'].supported: if not caps['remove'].supported:
@@ -1082,6 +1093,77 @@ def _wait_native_exit(pids, timeout=10):
return True return True
def _catalog_shared_dependencies(library):
from .icdb_ownership import shared_symbol_database
database = shared_symbol_database(library) / 'icdb.dat'
try:
info = database.stat()
except FileNotFoundError:
return set()
return {(info.st_dev, info.st_ino, database.resolve())}
def _probe_catalog_files(library):
import pywintypes, win32con, win32file
from contextlib import ExitStack
with ExitStack() as handles:
paths = (library, *(path for _, _, path in _catalog_shared_dependencies(library)))
for path in paths:
try:
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
except (OSError, pywintypes.error) as error:
raise OSError(f'{path}:{error}') from error
handles.callback(handle.Close)
def _open_catalog_manager_library(pid):
from .residual_sessions import _process_windows, _window_error
windows = _process_windows({pid})
if _window_error(windows, pid):
return None
paths = set()
for window in windows[pid]:
title = window['title']
if title.startswith('Library Manager: '):
path = Path(title.removeprefix('Library Manager: ').strip())
if path.is_absolute() and path.suffix.casefold() == '.lmc':
paths.add(path)
return next(iter(paths)) if len(paths) == 1 else None
def _check_catalog_owners(library, processes):
"""A foreign LM is compatible only with a disjoint library and free target resources."""
library = Path(library).resolve()
manager_pids = [pid for pid, *_ in processes]
target_dependencies = _catalog_shared_dependencies(library)
for pid in manager_pids:
try:
current = _open_catalog_manager_library(pid)
if current is None:
detail = '无法确认已运行的 Library Manager 对应哪个库'
else:
other = current.resolve(strict=True)
if library.samefile(other):
detail = '当前库已在另一个 Library Manager 中打开'
elif any(left[2] == right[2] or (left[1] and left[:2] == right[:2])
for left in target_dependencies for right in _catalog_shared_dependencies(other)):
detail = '另一个 Library Manager 正在使用相同的共享符号库'
else:
continue
except (OSError, ValueError) as error:
detail = f'无法确认另一中心库的资源范围:{error}'
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pid} · {detail}。',
safe_to_continue=True, blocking_manager_pids=(pid,))
try:
_probe_catalog_files(library)
except OSError as error:
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {manager_pids} · 当前库资源占用未确认:{error}',
safe_to_continue=True, blocking_manager_pids=manager_pids) from error
def _catalog_native(job, root): def _catalog_native(job, root):
import gc, pythoncom import gc, pythoncom
from .com_runtime import initialize_com, uninitialize_com from .com_runtime import initialize_com, uninitialize_com
@@ -1097,7 +1179,8 @@ def _catalog_native(job, root):
uninitialize_com(initialized) uninitialize_com(initialized)
# A failed COM activation can have created an unaccounted server. An empty # A failed COM activation can have created an unaccounted server. An empty
# PID list is missing release evidence, not proof that nothing was launched. # PID list is missing release evidence, not proof that nothing was launched.
result['safe_to_continue'] = bool(result.get('native_pids')) and _wait_native_exit(result['native_pids']) result['safe_to_continue'] = bool(result.get('no_new_manager') or (
result.get('native_pids') and _wait_native_exit(result['native_pids'])))
return result return result
@@ -1116,8 +1199,16 @@ def _catalog_com(job, root):
desktop, name = _current_desktop() desktop, name = _current_desktop()
if name != job['desktop'] or not name.startswith('CbbManagement_'): if name != job['desktop'] or not name.startswith('CbbManagement_'):
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。') raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
if _process_details('LibraryManager.exe'): previous_managers = _process_details('LibraryManager.exe')
raise RuntimeError('已有 Library Manager 运行,请关闭后重试。') if previous_managers:
if job.get('worker_role') != 'catalog_readonly' or job.get('include_engineering_identity', True):
raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
expected = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
if hash_file(expected) != _BINARY_PROOF['lm/win32/bin/LibraryManager.exe']:
pids = sorted(pid for pid, *_ in previous_managers)
raise NativeOperationError(f'LIBRARY_MANAGER_BUSY: PID {pids} · 当前安装尚未验证并行目录读取。',
safe_to_continue=True, blocking_manager_pids=pids)
_check_catalog_owners(job['library'], previous_managers)
except Exception as error: except Exception as error:
error.safe_to_continue = True error.safe_to_continue = True
raise raise
@@ -1173,16 +1264,26 @@ def _catalog_com(job, root):
# Keep the launch pending until its exact native identity is recorded. # Keep the launch pending until its exact native identity is recorded.
app = dispatch_native(job, lambda: win32com.client.DispatchEx('LibraryManager.Application'), app = dispatch_native(job, lambda: win32com.client.DispatchEx('LibraryManager.Application'),
asynchronous=True) asynchronous=True)
app.Visible = True
processes = _process_details('LibraryManager.exe') processes = _process_details('LibraryManager.exe')
owned_pids.update(int(p[0]) for p in processes) previous_pids = {pid for pid, *_ in previous_managers}
from .session_record import update_worker_state new_processes = [process for process in processes if process[0] not in previous_pids]
update_worker_state(job, 'POSTCALL', identities=[('native', pid) for pid in owned_pids]) if not new_processes and previous_pids and {p[0] for p in processes} == previous_pids:
if len(owned_pids) != 1: # DispatchEx reused an existing instance. Drop this proxy without invoking any method.
result.update(no_new_manager=True, blocking_manager_pids=sorted(previous_pids))
raise RuntimeError(f'LIBRARY_MANAGER_BUSY: 当前 COM 注册复用了已有 Library Manager,PID {sorted(previous_pids)}。')
if len(new_processes) != 1:
raise RuntimeError('无法唯一确认本次 Library Manager 进程。') raise RuntimeError('无法唯一确认本次 Library Manager 进程。')
pid, executable, *_ = new_processes[0]
expected_binary = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe' expected_binary = Path(job['mentor_home'])/'lm/win32/bin/LibraryManager.exe'
if Path(processes[0][1]).resolve() != expected_binary.resolve(): if Path(executable).resolve() != expected_binary.resolve():
raise RuntimeError('COM 注册指向不同的 Library Manager 安装,拒绝打开中心库。') raise RuntimeError('COM 注册指向不同的 Library Manager 安装,拒绝打开中心库。')
if job.get('session_record_path') or previous_pids:
desktop_pids = {win32process.GetWindowThreadProcessId(hwnd)[1] for hwnd in desktop.EnumDesktopWindows()}
if pid not in desktop_pids:
raise RuntimeError('无法确认新 Library Manager 位于本次私有桌面。')
owned_pids.add(pid)
update_worker_state(job, 'POSTCALL', identities=[('native', pid)])
app.Visible = True
watcher = threading.Thread(target=observe_dialogs, daemon=True) watcher = threading.Thread(target=observe_dialogs, daemon=True)
watcher.start() watcher.start()
if job['operation'] in ('probe_create_add', 'probe_create'): if job['operation'] in ('probe_create_add', 'probe_create'):
@@ -1217,17 +1318,20 @@ def _catalog_com(job, root):
for i in range(1, int(parts.Count) + 1): for i in range(1, int(parts.Count) + 1):
partition = parts.Item(i) partition = parts.Item(i)
for j in range(1, int(partition.Count) + 1): for j in range(1, int(partition.Count) + 1):
if job.get('worker_role') == 'catalog_readonly':
_require_management_continuation(job, root)
item = partition.Item(j) item = partition.Item(j)
block_name, partition_name = str(item.Name), str(item.PartitionName) block_name, partition_name = str(item.Name), str(item.PartitionName)
validate_name(block_name) validate_name(block_name)
identity = {} identity = {}
work = Path(job['library']).parent/'ReusableBlocksLP'/block_name/'Work' if job.get('include_engineering_identity', True):
projects = list(work.glob('*.prj')) work = Path(job['library']).parent/'ReusableBlocksLP'/block_name/'Work'
if len(projects) == 1: projects = list(work.glob('*.prj'))
try: if len(projects) == 1:
identity = engineering_identity(projects[0]) try:
except (ValueError, OSError): identity = engineering_identity(projects[0])
pass except (ValueError, OSError):
pass
entries.append(asdict(CatalogEntry(block_name, partition_name, identity))) entries.append(asdict(CatalogEntry(block_name, partition_name, identity)))
item = None item = None
partition = None partition = None
@@ -1255,7 +1359,7 @@ def _catalog_com(job, root):
result['close_detail'] = str(error) result['close_detail'] = str(error)
result['close_exception'] = _exception_details(error) result['close_exception'] = _exception_details(error)
library = None library = None
if app is not None and not job.get('_native_add_pending'): if app is not None and owned_pids and not job.get('_native_add_pending'):
try: try:
dispatch_native(job, lambda: app.Quit(), phase='CLOSING') dispatch_native(job, lambda: app.Quit(), phase='CLOSING')
except Exception as error: except Exception as error:
@@ -1374,6 +1478,8 @@ def management_worker_main(request_path, *, catalog_readonly=False):
except Exception as error: except Exception as error:
if getattr(error, 'safe_to_continue', None) is True: if getattr(error, 'safe_to_continue', None) is True:
result['safe_to_continue'] = True result['safe_to_continue'] = True
if getattr(error, 'blocking_manager_pids', ()):
result['blocking_manager_pids'] = list(error.blocking_manager_pids)
result['detail'] = str(error) result['detail'] = str(error)
result['exception'] = _exception_details(error) result['exception'] = _exception_details(error)
finally: finally:
+35 -16
View File
@@ -183,22 +183,41 @@ def _normalize_input_path(path) -> str:
def select_library_file(path) -> Path: def select_library_file(path) -> Path:
"""Return a concrete LMC, accepting a directory with exactly one LMC.""" """Return a concrete LMC, accepting a directory with exactly one LMC."""
candidate = Path(path) candidate = Path(path)
if candidate.is_file(): try:
if candidate.suffix.casefold() != ".lmc": if candidate.is_file():
raise NetworkPathError(f"中心库文件必须是 .lmc: {candidate}") if candidate.suffix.casefold() != ".lmc":
return candidate raise NetworkPathError(f"INPUT_SUFFIX: 中心库文件必须是 .lmc: {candidate}")
if candidate.is_dir(): return candidate
files = sorted( if candidate.is_dir():
(item for item in candidate.iterdir() files = [item for item in candidate.iterdir()
if item.is_file() and item.suffix.casefold() == ".lmc"), if item.suffix.casefold() == ".lmc" and item.is_file()]
key=lambda item: item.name.casefold(), if len(files) != 1:
) raise NetworkPathError(
if len(files) != 1: f"INPUT_DIRECTORY: 中心库目录必须包含唯一的 .lmc 文件,当前找到 {len(files)} 个: {candidate}"
raise NetworkPathError( )
f"中心库目录必须包含唯一的 .lmc 文件,当前找到 {len(files)} 个: {candidate}" return files[0]
) except PermissionError as error:
return files[0] raise NetworkPathError(f"INPUT_PERMISSION: 无权读取中心库: {candidate}") from error
raise NetworkPathError(f"中心库路径不存在或不可访问: {candidate}") raise NetworkPathError(f"INPUT_MISSING: 中心库路径不存在或不可访问: {candidate}")
def validate_library_file(path: Path) -> None:
"""Reject invalid LMC inputs before a directory scan or native dispatch."""
if path.suffix.casefold() != '.lmc':
raise NetworkPathError(f'INPUT_SUFFIX: 请选择 .lmc 中心库文件: {path}')
try:
if not path.is_file():
raise NetworkPathError(f'INPUT_MISSING: 中心库不存在或不是文件: {path}')
with path.open('rb') as stream:
if not stream.read(1):
raise NetworkPathError(f'INPUT_EMPTY: 中心库文件为空: {path}')
if any(lock.is_dir() for lock in
(path.with_suffix('.lock'), path.with_name('.' + path.stem + '.cbb-upload.lock'))):
raise NetworkPathError(f'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录: {path}')
except FileNotFoundError as error:
raise NetworkPathError(f'INPUT_MISSING: 中心库不存在: {path}') from error
except PermissionError as error:
raise NetworkPathError(f'INPUT_PERMISSION: 无权读取中心库: {path}') from error
@dataclass @dataclass
+19 -5
View File
@@ -6,13 +6,13 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
"""Refresh resource facts after a late exit; keep the original business failure.""" """Refresh resource facts after a late exit; keep the original business failure."""
if result.safe_to_continue or not result.evidence_path: if result.safe_to_continue or not result.evidence_path:
return result return result
from .operation_queue import BatchTaskContext, TaskHandoff, current_context, task_stop from .operation_queue import BatchTaskContext, QueueCancelled, current_context, task_stop
if current_context() is None: if current_context() is None:
context = BatchTaskContext(library=str(library), targets=(block,)) context = BatchTaskContext(library=str(library), targets=(block,))
try: try:
return context.run(lambda: recheck_failed_release(library, block, result, stop=stop), return context.run(lambda: recheck_failed_release(library, block, result, stop=stop),
stop=stop, timeout_seconds=timeout_seconds) stop=stop, timeout_seconds=timeout_seconds)
except TaskHandoff: except QueueCancelled:
return result return result
stop = task_stop(stop) stop = task_stop(stop)
from pathlib import Path from pathlib import Path
@@ -28,7 +28,10 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
if record.get('block') != block or Path(record.get('library', '')).resolve() != Path(library).resolve(): if record.get('block') != block or Path(record.get('library', '')).resolve() != Path(library).resolve():
return result return result
if inspect_session_record(session, evidence_root=evidence.parent).get('status') == 'ACTIVE': if inspect_session_record(session, evidence_root=evidence.parent).get('status') == 'ACTIVE':
return result from .residual_sessions import finish_owned_idle_session
finish_owned_idle_session(session, stop=stop)
if inspect_session_record(session, evidence_root=evidence.parent).get('status') == 'ACTIVE':
return result
else: else:
record = json.loads(evidence.read_text('utf-8')) record = json.loads(evidence.read_text('utf-8'))
if (record.get('name') != block or record.get('operation') not in ('add', 'update', 'remove') if (record.get('name') != block or record.get('operation') not in ('add', 'update', 'remove')
@@ -42,7 +45,10 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
if Path(owned.get('library', '')).resolve() != Path(library).resolve(): if Path(owned.get('library', '')).resolve() != Path(library).resolve():
return result return result
if inspect_session_record(candidate, evidence_root=evidence.parent).get('status') == 'ACTIVE': if inspect_session_record(candidate, evidence_root=evidence.parent).get('status') == 'ACTIVE':
return result from .residual_sessions import finish_owned_idle_session
finish_owned_idle_session(candidate, stop=stop)
if inspect_session_record(candidate, evidence_root=evidence.parent).get('status') == 'ACTIVE':
return result
bound.append(candidate) bound.append(candidate)
if not bound: if not bound:
return result # A generic timeout without a bound owner is not an exit fact. return result # A generic timeout without a bound owner is not an exit fact.
@@ -60,7 +66,15 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
business_status=result.status, safe_to_continue=True, release_proof=proof), business_status=result.status, safe_to_continue=True, release_proof=proof),
ensure_ascii=False, default=str, indent=2), 'utf-8') ensure_ascii=False, default=str, indent=2), 'utf-8')
return replace(result, safe_to_continue=True, release_proof=proof) return replace(result, safe_to_continue=True, release_proof=proof)
except Exception: except Exception as error:
try:
evidence.with_name('late-release-attempt.json').write_text(json.dumps(dict(
business_status=result.status, safe_to_continue=False,
status='IN_USE' if getattr(error,'winerror',None) in (32,33) else 'UNCONFIRMED',
library=str(library), block=block, detail=str(error),
blocked_resources=getattr(error,'blocked_resources',[])),ensure_ascii=False,indent=2),'utf-8')
except OSError:
pass
return result return result
+110 -10
View File
@@ -1,5 +1,5 @@
"""Cooperative FIFO admission for this application's native operations.""" """Cooperative FIFO admission for this application's native operations."""
from contextlib import contextmanager from contextlib import contextmanager, nullcontext
from dataclasses import dataclass, field from dataclasses import dataclass, field
import ntpath import ntpath
from threading import Condition, Event, RLock, Thread, local from threading import Condition, Event, RLock, Thread, local
@@ -11,6 +11,22 @@ class QueueCancelled(RuntimeError):
pass pass
class QueueUnavailable(RuntimeError):
"""Admission failed before action dispatch; this task created no native session."""
def __init__(self, library, sessions=(), *, timed_out=False):
self.library = str(library)
self.sessions = tuple(sessions)
self.timed_out = timed_out
details = []
for session in self.sessions:
block = session.get('block') or '当前库'
resources = '、'.join(map(str, session.get('blocked_resources') or ()))
details.append(' / '.join(filter(None, (block, session.get('operation_id'),
resources, session.get('path')))))
message = f'NATIVE_SESSION_PENDING: {self.library} 的已登记会话待释放,当前项未启动。'
super().__init__(message + (' ' + ';'.join(details) if details else ''))
class TaskHandoff(QueueCancelled): class TaskHandoff(QueueCancelled):
"""The call is still observable; this is never a release receipt.""" """The call is still observable; this is never a release receipt."""
def __init__(self, context, *, cancelled=False, result=None): def __init__(self, context, *, cancelled=False, result=None):
@@ -75,6 +91,8 @@ class _Call:
shutdown_handoff: bool = False shutdown_handoff: bool = False
native_handoff: str = '' native_handoff: str = ''
handoff_cancelled: bool = False handoff_cancelled: bool = False
queue_pause: object = None
queued_for_slot: bool = False
phase_started: float = field(default_factory=time.monotonic) phase_started: float = field(default_factory=time.monotonic)
result: object = None result: object = None
last_result: object = None last_result: object = None
@@ -94,6 +112,11 @@ def task_stop(fallback=None):
return getattr(_local, 'call', None) or fallback return getattr(_local, 'call', None) or fallback
def allow_other_libraries():
call = getattr(_local, 'call', None)
return call.queue_pause() if call is not None and call.queue_pause is not None else nullcontext()
def check_active(): def check_active():
call = getattr(_local, 'call', None) call = getattr(_local, 'call', None)
if call is not None and call.is_set(): if call is not None and call.is_set():
@@ -377,7 +400,8 @@ class BatchTaskContext:
call.abandoned = True call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result) raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
elapsed = time.monotonic()-call.phase_started elapsed = time.monotonic()-call.phase_started
if not call.native_depth and not call.commit_depth and (call.abandoned or elapsed >= timeout_seconds): expired = not call.queued_for_slot and elapsed >= timeout_seconds
if not call.native_depth and not call.commit_depth and (call.abandoned or expired):
cancelled = call.is_set() cancelled = call.is_set()
call.abandoned = True call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result) raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
@@ -386,6 +410,13 @@ class BatchTaskContext:
return call.result return call.result
@dataclass(eq=False)
class _Ticket:
roots: frozenset
ready: bool = False
paused: bool = False
class NativeQueue: class NativeQueue:
def __init__(self): def __init__(self):
self.condition = Condition() self.condition = Condition()
@@ -409,17 +440,84 @@ class NativeQueue:
for context in contexts) for context in contexts)
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None, def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None,
context=None, timeout_seconds=10): context=None, timeout_seconds=10, skip_unavailable=False, wait_for_release_seconds=None):
release_deadline = None
def available_now(): def available_now():
nonlocal release_deadline
if not ready(): if not ready():
return False return False
if context is None: if context is None:
return True # Explicit recovery controls must still reach their retained clients. return True # Explicit recovery controls must still reach their retained clients.
from .session_record import _live_library_available from .session_record import _live_library_available
return all(_live_library_available(path) for path in (context.library, *context.aliases)) for path in (context.library, *context.aliases):
ticket = [object(), False] if not _live_library_available(path):
if skip_unavailable and wait_for_release_seconds is None:
raise QueueUnavailable(path)
if wait_for_release_seconds is not None:
now = time.monotonic()
if release_deadline is None:
release_deadline = now + wait_for_release_seconds
if now >= release_deadline:
from .session_record import retained_session_states
raise QueueUnavailable(path, retained_session_states(path), timed_out=True)
return False
return True
roots = frozenset(ntpath.dirname(_path_key(path))
for path in (context.library, *context.aliases)) if context is not None else frozenset()
ticket = _Ticket(roots)
acquired, notified = False, False acquired, notified = False, False
previous_state = None previous_state = None
def first_ready():
paused = [entry for entry in self.pending if entry.paused]
return next((entry for entry in self.pending if entry.ready and not any(
owner is not entry and (not entry.roots or owner.roots & entry.roots)
for owner in paused)), None)
@contextmanager
def pause():
nonlocal acquired
call = _local.call
with self.condition:
can_pause = acquired and not call.native_depth and not call.commit_depth
if can_pause:
ticket.ready, ticket.paused = False, True
self.active = acquired = False
self.condition.notify_all()
if not can_pause:
# Nested Verify may still be part of a management transaction.
yield
return
try:
yield
finally:
with _tasks_guard:
call.queued_for_slot = True
try:
with self.condition:
ticket.ready = True
while ticket in self.pending and not self.closed and not call.is_set():
if not self.active and first_ready() is ticket:
self.active = acquired = True
break
self.condition.wait(.1)
ticket.paused = ticket.ready = False
self.condition.notify_all()
if not acquired:
raise QueueCancelled('已取消等待原生通道,未提交新的调用。')
finally:
with _tasks_guard:
call.queued_for_slot = False
call.phase_started = time.monotonic()
def run_admitted():
call = _local.call
previous_pause, call.queue_pause = call.queue_pause, pause
try:
return action()
finally:
call.queue_pause = previous_pause
with self.condition: with self.condition:
if self.closed: if self.closed:
raise QueueCancelled('队列已关闭,未启动新的操作。') raise QueueCancelled('队列已关闭,未启动新的操作。')
@@ -428,20 +526,22 @@ class NativeQueue:
self.pending.append(ticket) self.pending.append(ticket)
try: try:
while not acquired: while not acquired:
if (self.closed or stop is not None and stop.is_set()
or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())):
raise QueueCancelled('已取消排队,未启动原生操作。')
available = available_now() # Cached predicates only, outside the queue lock. available = available_now() # Cached predicates only, outside the queue lock.
with self.condition: with self.condition:
if (self.closed or stop is not None and stop.is_set() if (self.closed or stop is not None and stop.is_set()
or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())): or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())):
raise QueueCancelled('已取消排队,未启动原生操作。') raise QueueCancelled('已取消排队,未启动原生操作。')
ticket[1] = bool(available) ticket.ready = bool(available)
first = next((entry for entry in self.pending if entry[1]), None) if not self.active and first_ready() is ticket:
if not self.active and first is ticket:
self.active = acquired = True self.active = acquired = True
else: else:
self.condition.wait(.1) self.condition.wait(.1)
if acquired and not available_now(): if acquired and not available_now():
with self.condition: with self.condition:
ticket[1] = self.active = acquired = False ticket.ready = self.active = acquired = False
self.condition.notify_all() self.condition.notify_all()
if not acquired and waiting is not None: if not acquired and waiting is not None:
try: try:
@@ -454,7 +554,7 @@ class NativeQueue:
if (stop is not None and stop.is_set() if (stop is not None and stop.is_set()
or context is not None and context.stop_after_current.is_set()): or context is not None and context.stop_after_current.is_set()):
raise QueueCancelled('已取消排队,未启动原生操作。') raise QueueCancelled('已取消排队,未启动原生操作。')
return context.run(action, stop=stop, timeout_seconds=timeout_seconds) if context else action() return context.run(run_admitted, stop=stop, timeout_seconds=timeout_seconds) if context else action()
finally: finally:
with self.condition: with self.condition:
self.pending = [entry for entry in self.pending if entry is not ticket] self.pending = [entry for entry in self.pending if entry is not ticket]
+9 -1
View File
@@ -61,7 +61,12 @@ def owner_probe_main(job):
import pythoncom import pythoncom
import win32com.client import win32com.client
job = Path(job) job = Path(job)
request = json.loads(job.read_text('utf-8')) try:
request = json.loads(job.read_text('utf-8'))
except (OSError, ValueError):
return 1
if not isinstance(request, dict):
return 1
full_snapshot = request == {'snapshot_version': 1} and type(request.get('snapshot_version')) is int full_snapshot = request == {'snapshot_version': 1} and type(request.get('snapshot_version')) is int
names = request.get('names') names = request.get('names')
if not full_snapshot: if not full_snapshot:
@@ -84,5 +89,8 @@ def owner_probe_main(job):
response = {'snapshot_version': 1} if full_snapshot else {'names': names} response = {'snapshot_version': 1} if full_snapshot else {'names': names}
job.with_name('result.json').write_text(json.dumps({**response, 'owners': rows}), encoding='utf-8') job.with_name('result.json').write_text(json.dumps({**response, 'owners': rows}), encoding='utf-8')
return 0 return 0
except OSError:
# The supervisor may remove its temporary request while this helper exits.
return 1
finally: finally:
pythoncom.CoUninitialize() pythoncom.CoUninitialize()
+121 -37
View File
@@ -1,6 +1,7 @@
"""Explicit user answers to the owned PCB's exact read/write question.""" """Bound authorization for the owned PCB's exact read/write question."""
from contextlib import contextmanager, ExitStack from contextlib import contextmanager, ExitStack
from pathlib import Path from pathlib import Path, PureWindowsPath
import re
from threading import Lock from threading import Lock
import time import time
@@ -15,8 +16,9 @@ def _prompt_identity(snapshot):
class OpenChoice: class OpenChoice:
def __init__(self, block, library): def __init__(self, block, library, *, auto_confirm=False):
self.block, self.library = block, library self.block, self.library = block, library
self.auto_confirm = auto_confirm
self.decision = None self.decision = None
self.decision_origin = None self.decision_origin = None
self._lock = Lock() self._lock = Lock()
@@ -26,8 +28,8 @@ class OpenChoice:
raise ValueError('无效的打开工程选择') raise ValueError('无效的打开工程选择')
with self._lock: with self._lock:
if self.decision is None: if self.decision is None:
self.decision = decision
self.decision_origin = origin self.decision_origin = origin
self.decision = decision
def validate_owner(job, target_pid, launcher_pid, worker_pid): def validate_owner(job, target_pid, launcher_pid, worker_pid):
@@ -47,14 +49,15 @@ def validate_owner(job, target_pid, launcher_pid, worker_pid):
@contextmanager @contextmanager
def resource_guard(job, allowed_pids): def resource_guard(job, allowed_pids, *, require_complete_proof=False):
import hashlib import hashlib
from .file_probe import hold_release_files from .file_probe import hold_release_files
from .icdb_ownership import shared_symbol_database
from .maintenance_entry import maintenance_project_files from .maintenance_entry import maintenance_project_files
from .native_repair import RepairTarget, run_native_repair from .native_repair import RepairTarget, run_native_repair
from .native_occupancy import confirmed_inspection from .native_occupancy import confirmed_inspection
from .session_record import IDENTITY_KEYS from .session_record import IDENTITY_KEYS
from .operation_queue import task_stop from .operation_queue import check_active, task_stop
from .management import _write_json from .management import _write_json
from .owner_probe import query_process_snapshot from .owner_probe import query_process_snapshot
from .library_lock import _owner_is_blocking from .library_lock import _owner_is_blocking
@@ -72,27 +75,79 @@ def resource_guard(job, allowed_pids):
for row in query_process_snapshot(): for row in query_process_snapshot():
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots): if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。') raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
check_active()
check() check()
stop = task_stop(None) stop = task_stop(None)
with ExitStack() as stack: with ExitStack() as stack:
files = stack.enter_context(hold_release_files(library, roots, stop=stop)) files = stack.enter_context(hold_release_files(library, roots, stop=stop))
inspections = [] inspections = []
if require_complete_proof:
from .backup_recovery import _project_text
references = re.findall(r'^KEY ProjectFile "([^"]+)"', _project_text(pcb), re.M)
if len(references) != 1 or (pcb.parent/references[0]).resolve() != project.resolve():
raise ValueError(f'PCB_OPEN_PROJECT_CHANGED: PCB 未唯一关联当前工程:{pcb}')
required_files = {library.resolve(), (pcb.parent/'Layout/LayoutDB.lyt').resolve()}
for config in configs:
text = _project_text(config)
references = re.findall(r'^KEY iCDBDir\b.*$', text, re.M)
if not references and config != project:
continue
reference = re.fullmatch(r'KEY iCDBDir "([^"]+)"\s*', references[0]) if len(references) == 1 else None
if reference is None or PureWindowsPath(reference[1]).anchor:
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: iCDBDir 必须唯一且为相对路径:{config}')
database = (config.parent/reference[1]).resolve()
if not database.is_relative_to(project.parent.resolve()):
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: iCDBDir 越出工程:{database}')
required_files.add(database/'icdb.dat')
shared = shared_symbol_database(library)
if shared.exists():
required_files.add((shared/'icdb.dat').resolve())
missing = required_files - {Path(path).resolve() for path in files['exclusive_files']}
if missing:
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 缺少文件占用证明:'
+ '、'.join(str(path) for path in sorted(missing)))
if files['addresses']: if files['addresses']:
targets = files['inspection_targets'] targets = files['inspection_targets']
if any(Path(item['project']).resolve() not in {p.resolve() for p in configs} for item in targets): for item in targets:
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置,需人工核对') if item.get('scope') == 'shared_symbols':
address = Path(item['address'])
shared = shared_symbol_database(library).resolve()
if (Path(item['database']).resolve() != shared
or address.resolve() != shared/'cdbsvr/sAddress.adr'
or str(address) not in files['binding_files']
or shared/'icdb.dat' not in {Path(p).resolve() for p in files['exclusive_files']}):
raise ValueError(f'SHARED_ICDB_BINDING_UNCONFIRMED: {address}')
if str(address) in files.get('shared_shutdowns', {}):
continue
_write_json(Path(job['root'])/'pcb-open-resource-denied.json', {
'status': 'SHARED_ICDB_INSPECTION_UNAVAILABLE',
'operation_id': job.get('operation_id'), 'library': str(library),
'database': str(shared), 'address': str(address),
'address_sha256': files['signatures'][str(address)],
'exclusive_file_observed': True,
})
raise ValueError('SHARED_ICDB_INSPECTION_UNAVAILABLE: 共享符号库地址需要原生核对:'+str(address))
if Path(item['project']).resolve() not in {p.resolve() for p in configs}:
raise ValueError(f"PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置:{item['database']}")
stack.close() # Native inspection must access the DB; repeat exact proof afterwards. stack.close() # Native inspection must access the DB; repeat exact proof afterwards.
for index, item in enumerate(targets): for index, item in enumerate(targets):
if item.get('scope') == 'shared_symbols':
continue
target = RepairTarget(Path(item['project']), Path(item['database'])) target = RepairTarget(Path(item['project']), Path(item['database']))
evidence = Path(job['root'])/('open-inspection-'+str(index)) evidence = Path(job['root'])/('open-inspection-'+str(index))
result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'), result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'),
timeout_seconds=min(45, float(job.get('timeout', 45))), inspection_only=True, stop=stop) timeout_seconds=min(45, float(job.get('timeout', 45))), inspection_only=True, stop=stop)
identity = result.get('native_identity') or {} identity = result.get('native_identity') or {}
if (not confirmed_inspection(target, result) or result['status'] != 'NOT_IN_USE' if (not confirmed_inspection(target, result)
or identity.get('pid') != result.get('native_pid') or identity.get('pid') != result.get('native_pid')
or any(identity.get(key) is None for key in IDENTITY_KEYS) or any(identity.get(key) is None for key in IDENTITY_KEYS)
or not identity.get('image') or not identity.get('owner_sid')): or not identity.get('image') or not identity.get('owner_sid')):
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 原生检查未确认当前数据库未占用') raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: 原生占用检查无法确认:{target.database}')
if result['status'] == 'IN_USE':
raise ValueError(f'PCB_OPEN_DATABASE_IN_USE: 原生检查确认数据库占用:{target.database}')
if require_complete_proof and result['repair_required']:
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: 原生检查提示需要维护:{target.database}')
inspections.append(result) inspections.append(result)
current = stack.enter_context(hold_release_files(library, roots, stop=stop)) current = stack.enter_context(hold_release_files(library, roots, stop=stop))
if any(current[key] != files[key] for key in ( if any(current[key] != files[key] for key in (
@@ -101,17 +156,21 @@ def resource_guard(job, allowed_pids):
if binding() != original_binding: if binding() != original_binding:
raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化') raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化')
check() check()
check_active()
_write_json(Path(job['root'])/'pcb-open-resource-proof.json', { _write_json(Path(job['root'])/'pcb-open-resource-proof.json', {
'operation_id': job.get('operation_id'), 'library': str(library), 'operation_id': job.get('operation_id'), 'library': str(library),
'project': str(project), 'pcb': str(pcb), 'binding': original_binding, 'project': str(project), 'pcb': str(pcb), 'binding': original_binding,
'exclusive_files': files['exclusive_files'], 'addresses': files['addresses'], 'exclusive_files': files['exclusive_files'], 'addresses': files['addresses'],
'native_inspections': inspections, 'repair_confirmed': False}) 'native_inspections': inspections, 'shared_shutdowns': files.get('shared_shutdowns', {}),
'repair_confirmed': False})
yield yield
class OpenController: class OpenController:
def __init__(self, job): def __init__(self, job, *, auto_confirm=False, require_complete_proof=False):
self.job = job self.job = job
self.auto_confirm = auto_confirm
self.require_complete_proof = require_complete_proof or auto_confirm
self.choice = None self.choice = None
self.original = self.owner = None self.original = self.owner = None
self.sent = False self.sent = False
@@ -120,14 +179,21 @@ class OpenController:
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, show, perform): def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, show, perform):
from .dialog_supervisor import DialogPollResult from .dialog_supervisor import DialogPollResult
from .management import _write_json from .management import _write_json
from .operation_queue import QueueCancelled, check_active
try: try:
if not exact_prompt(snapshot) or snapshot.pid != target_pid or len(snapshots) != 1: if not exact_prompt(snapshot) or snapshot.pid != target_pid or len(snapshots) != 1:
raise ValueError('PCB_OPEN_PROMPT_CHANGED') raise ValueError('PCB_OPEN_PROMPT_CHANGED')
owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid) owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid)
if self.choice is None: if self.choice is None:
self.owner, self.original = owner, snapshot self.owner, self.original = owner, snapshot
self.choice = OpenChoice(self.job['block_name'], self.job['lmc_file']) self.choice = OpenChoice(self.job['block_name'], self.job['lmc_file'],
show(self.choice) auto_confirm=self.auto_confirm)
if show is not None:
show(self.choice)
elif self.auto_confirm:
self.choice.choose('continue', origin='headless_opt_in')
else:
raise ValueError('PCB_OPEN_CONFIRMATION_REQUIRED')
if (owner != self.owner or snapshot.hwnd != self.original.hwnd if (owner != self.owner or snapshot.hwnd != self.original.hwnd
or _prompt_identity(snapshot) != _prompt_identity(self.original)): or _prompt_identity(snapshot) != _prompt_identity(self.original)):
raise ValueError('PCB_OPEN_IDENTITY_CHANGED') raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
@@ -137,36 +203,54 @@ class OpenController:
raise ValueError('PCB_OPEN_ANSWER_NOT_COMPLETED') raise ValueError('PCB_OPEN_ANSWER_NOT_COMPLETED')
if self.choice.decision is None: if self.choice.decision is None:
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots)) return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
control = 6 if self.choice.decision == 'continue' else 7 decision = self.choice.decision
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'], origin = self.choice.decision_origin
'target': {'control_id': control}, 'desktop': self.job['desktop'], skipped_detail = ('超时默认跳过本项。' if origin == 'timeout_default' else '用户跳过本项。')
'pid': target_pid, 'owner': owner, 'choice': self.choice.decision} if decision == 'continue':
action['decision_origin'] = self.choice.decision_origin
def send():
_write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict(
choice=self.choice.decision, decision_origin=self.choice.decision_origin,
project=self.job['project'], pcb=self.job['pcb'],
library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record()))
self.sent, self.sent_at = True, time.monotonic()
return perform(snapshot, action, snapshot.phase)
if control == 6:
allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')} allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')}
with resource_guard(self.job, allowed): try:
pass guard = (resource_guard(self.job, allowed, require_complete_proof=True) if self.require_complete_proof
# Deliberate TOCTOU tradeoff: release probes before Yes so Mentor else resource_guard(self.job, allowed))
# can acquire the files without a sharing violation; recheck identity. with guard:
pass
# Mentor needs the handles released before Yes. Recheck the
# owner here and the actual window in the private agent.
check_active()
except QueueCancelled:
decision, skipped_detail = 'cancel', '校验已取消。'
except Exception as error:
if not self.require_complete_proof:
raise
decision, skipped_detail = 'skip', str(error)
if validate_owner(self.job, target_pid, launcher_pid, worker_pid) != owner: if validate_owner(self.job, target_pid, launcher_pid, worker_pid) != owner:
raise ValueError('PCB_OPEN_IDENTITY_CHANGED') raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
result = send() if decision == 'continue':
else: try:
result = send() check_active()
except QueueCancelled:
decision, skipped_detail = 'cancel', '校验已取消。'
control = 6 if decision == 'continue' else 7
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'],
'target': {'control_id': control}, 'desktop': self.job['desktop'],
'pid': target_pid, 'owner': owner, 'choice': decision, 'decision_origin': origin}
_write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict(
choice=decision, decision_origin=origin, detail=skipped_detail if control == 7 else '',
operation_id=self.job.get('operation_id'), desktop=self.job['desktop'],
project=self.job['project'], pcb=self.job['pcb'],
library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record()))
if control == 6:
try:
check_active()
except QueueCancelled:
return DialogPollResult(error_code='USER_CANCELLED', detail='校验已取消。',
snapshot=snapshot, observed_snapshots=tuple(snapshots))
self.sent, self.sent_at = True, time.monotonic()
result = perform(snapshot, action, snapshot.phase)
error = result.error_code error = result.error_code
if not error and result.accepted_controls != (control,): if not error and result.accepted_controls != (control,):
error = 'PCB_OPEN_ANSWER_FAILED' error = 'PCB_OPEN_ANSWER_FAILED'
if not error and control == 7: if not error and control == 7:
error = 'PCB_OPEN_SKIPPED' if self.choice.decision == 'skip' else 'USER_CANCELLED' error = 'PCB_OPEN_SKIPPED' if decision == 'skip' else 'USER_CANCELLED'
skipped_detail = ('超时默认跳过本项。' if self.choice.decision_origin == 'timeout_default'
else '用户跳过本项。')
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot, return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
error_code=error, detail=result.detail or (skipped_detail if control == 7 else ''), error_code=error, detail=result.detail or (skipped_detail if control == 7 else ''),
accepted_controls=result.accepted_controls, channel=result.channel, accepted_controls=result.accepted_controls, channel=result.channel,
+335 -1
View File
@@ -394,6 +394,78 @@ def _save_question(windows, *, incomplete=None):
return None return None
class OrphanedVerifySavePrompt:
"""Continue the registered worker's already started Save after supervisor loss."""
def __init__(self, job, pcb_pid, emit, *, clock=time.monotonic):
self.job = job
self.pid = pcb_pid
self.emit = emit
self.clock = clock
self.pending = None
self.clicked = False
def poll(self, markers):
from .desktop_worker import supervisor_has_exited
if (self.clicked or 'SAVE_START' not in markers
or any(marker == 'SAVE_OK' or marker.startswith(('SAVE_REJECTED', 'SAVE_RESULT_UNKNOWN'))
for marker in markers)
or not supervisor_has_exited()
or self.job.get('interactive_input') is not False
or not self.job.get('desktop', '').startswith('CbbVerify_')
or not self.job.get('session_record_path')):
return
from .session_record import IDENTITY_KEYS, process_identity, read_session_record
import win32con
state_path = Path(self.job['session_record_path']).with_name('worker-state.json')
try:
state = read_session_record(state_path, evidence_root=state_path.parent)
if (state['operation_id'] != self.job['operation_id']
or state.get('phase') != 'NATIVE_CALL'):
self.pending = None
return
identity = next((row for row in state['processes']
if row['role'] == 'native' and row['pid'] == self.pid), None)
actual = process_identity(self.pid) if identity is not None else None
if actual is None or any(actual[key] != identity[key] for key in IDENTITY_KEYS):
self.pending = None
return
windows = _process_windows({self.pid})
matches = []
for window in windows.get(self.pid, ()):
if (window['desktop'] != self.job['desktop'] or window['class'] != '#32770'
or window['title'] != 'Expedition PCB' or not window['enabled']):
continue
texts = [child['text'].strip().casefold() for child in window['children']
if child['class'] == 'Static' and child['text'].strip()]
buttons = [child for child in window['children'] if child['class'] == 'Button']
if (texts == ['do you want to save the reusable block cell?']
and sorted(item['id'] for item in buttons) == [6, 7]
and all(item['enabled'] for item in buttons)):
button = next(item['hwnd'] for item in buttons if item['id'] == 6)
matches.append((window, button))
if self.pid in windows.incomplete or len(matches) != 1:
self.pending = None
return
window, button = matches[0]
now = self.clock()
signature = (window['hwnd'], button)
if self.pending is None or self.pending[0] != signature:
self.pending = (signature, now)
return
if now - self.pending[1] < 3:
return
_post_window_message(window, button, self.pid, win32con.BM_CLICK)
self.clicked = True
self.emit(stage='orphaned_save_confirmed', native_pid=self.pid, hwnd=window['hwnd'],
rule_id='reusable-block-save', accepted_control=[6])
except Exception:
# Read errors must leave the already executing native write alone.
self.pending = None
def _cancel_question(name, windows, *, incomplete=None): def _cancel_question(name, windows, *, incomplete=None):
if (name.casefold() != 'icdbprojectbackup.exe' if (name.casefold() != 'icdbprojectbackup.exe'
or native_activity(name, windows, incomplete=incomplete)['status'] != 'ACTIVE'): or native_activity(name, windows, incomplete=incomplete)['status'] != 'ACTIVE'):
@@ -612,7 +684,7 @@ def _cancelled_diagnostic_record(row):
or not same(job['cancel_signal'], session['cancel_signal']) or not same(job['cancel_signal'], session['cancel_signal'])
or Path(job['cancel_signal']).parent != root or not Path(job['cancel_signal']).is_file() or Path(job['cancel_signal']).parent != root or not Path(job['cancel_signal']).is_file()
or result.get('status') != 'CANCELLED' or result.get('error_stage') != 'PCB_STARTING' or result.get('status') != 'CANCELLED' or result.get('error_stage') != 'PCB_STARTING'
or result.get('write_outcome', {}).get('save_state') != 'UNKNOWN' or (result.get('write_outcome') or {}).get('save_state') != 'UNKNOWN'
or state.get('phase') != 'UNCONFIRMED' or (root/'save.log').exists()): or state.get('phase') != 'UNCONFIRMED' or (root/'save.log').exists()):
continue continue
native = [p for p in identities if p.get('role') == 'native' and p['pid'] == row['pid']] native = [p for p in identities if p.get('role') == 'native' and p['pid'] == row['pid']]
@@ -818,6 +890,268 @@ def resume_cancelled_startup(path, *, stop=None):
return False return False
def _recorded_process_exited(identity):
import pywintypes
import win32con
import win32event
try:
with _process_handle(identity['pid']) as handle:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
return True
return _handle_identity(handle)['created_handle'] != identity['created_handle']
except pywintypes.error as error:
return error.winerror == 87
def _saved_and_closed(facts):
return (isinstance(facts, dict) and facts.get('interrupted') is False
and all(facts.get(key) == value for key, value in (
('save_state', 'COMMITTED'), ('close_state', 'CLOSED'), ('helper_state', 'EXITED'))))
def _worker_save_facts(state, identities):
if (state.get('phase') in ('POSTCALL', 'RELEASE_CHECK', 'FINISHED', 'UNCONFIRMED')
and any(p.get('role') == 'helper' for p in identities)):
facts = state.get('write_outcome')
if isinstance(facts, dict) and facts.get('save_close_confirmed') is True:
return facts
return None
def recoverable_orphan_session(path):
from .session_record import IDENTITY_KEYS, MAX_BYTES, read_session_record, _session
import stat
path = Path(path)
try:
session = read_session_record(path, evidence_root=path.parent)
operation = session.get('operation')
desktop = str(session.get('desktop', ''))
if operation == 'verify' and desktop.startswith('CbbVerify_'):
_, state, identities = _session(path, path.parent)
if not _saved_and_closed(_worker_save_facts(state, identities)):
return False
elif (operation != 'catalog' or session.get('worker_role') != 'catalog_readonly'
or not desktop.startswith('CbbManagement_')):
return False
request = path.with_name('request.json')
if request.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
return False
with request.open('rb') as stream:
data = stream.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
return False
job = json.loads(data)
if (any(job.get(key) != session.get(key) for key in
('operation_id', 'operation', 'library', 'desktop', 'worker_role'))
or Path(job['session_record_path']).resolve() != path.resolve()):
return False
if operation == 'verify' and (job.get('interactive_input') is not False
or job.get('block') != session.get('block') or job.get('lmc_file') != session['library']
or Path(job.get('root', '')).resolve() != path.parent.resolve()):
return False
identity = job['supervisor_identity']
if (not isinstance(identity, dict) or any(identity.get(key) is None for key in IDENTITY_KEYS)
or type(identity['pid']) is not int or identity['pid'] <= 0
or identity['pid'] != job.get('supervisor_pid')):
return False
if session.get('supervisor_identity') != identity:
if operation != 'catalog' or session.get('supervisor_identity') is not None:
return False
lost = read_session_record(path.with_name('supervisor-lost.json'), evidence_root=path.parent)
if lost.get('operation_id') != session['operation_id'] or lost.get('phase') != 'SUPERVISOR_LOST':
return False
return _recorded_process_exited(identity)
except (OSError, ValueError, TypeError, KeyError, AttributeError):
return False
def finish_owned_idle_session(path, *, stop=None):
"""One normal close for a registered, settled, empty client; never a server."""
from contextlib import ExitStack
import stat
import pywintypes, win32con, win32event
from .session_record import _session, active_write_records, write_session_record
from .operation_queue import check_active, native_phase
path = Path(path)
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired or stop is not None and stop.is_set(): return False
session, state, identities = _session(path, path.parent)
if 'owned_idle_cleanup' in session: return False
def read(name):
item = path.with_name(name)
if item.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError('OWNED_CLEANUP_REPARSE_POINT')
with item.open('rb') as stream: data = stream.read(1024*1024+1)
if len(data) > 1024*1024: raise ValueError('OWNED_CLEANUP_RECORD_TOO_LARGE')
return json.loads(data)
job = read('request.json')
if not isinstance(job, dict): return False
if (any(job.get(k) != session.get(k) for k in ('operation_id','operation','library','desktop','block'))
or Path(job.get('session_record_path','')).resolve() != path.resolve()): return False
operation, desktop = job['operation'], job['desktop']
def read_result():
try:
return read('result.json')
except FileNotFoundError:
return None
result = read_result()
if result is None:
if (state.get('phase') not in ('PRECALL', 'POSTCALL', 'RELEASE_CHECK', 'FINISHED', 'UNCONFIRMED')
or not recoverable_orphan_session(path)):
return False
elif not isinstance(result, dict) or result.get('safe_to_continue') is not False:
return False
cancelled_before_write = None
if operation == 'verify':
if (not desktop.startswith('CbbVerify_') or job.get('interactive_input') is not False
or Path(job.get('root', '')).resolve() != path.parent.resolve()
or job.get('lmc_file') != job['library']):
return False
if result is not None:
if (result.get('status') not in ('FAIL', 'BLOCKED', 'TIMEOUT', 'CANCELLED')
or result.get('block_name') != job['block']
or Path(result.get('evidence_path', '')).resolve() != path.with_name('result.json').resolve()):
return False
facts = result.get('write_outcome')
worker_facts = _worker_save_facts(state, identities)
provisional = (isinstance(facts, dict) and facts.get('helper_state') in ('RUNNING', 'UNKNOWN')
and facts.get('interrupted') is False and facts.get('save_state') != 'REJECTED'
and facts.get('close_state') != 'FAILED')
if facts is None or provisional or (session.get('supervisor_identity') and _saved_and_closed(facts)):
facts = worker_facts
failed_open = (result.get('error_stage') == 'PCB_STARTING'
and result.get('error_category') in ('MENTOR_DATABASE_LOAD_FAILED', 'ICDB_REPAIR_REQUIRED')
and not path.with_name('save.log').exists())
if (result.get('status') == 'CANCELLED' and result.get('error_stage') == 'PCB_STARTING'
and state.get('phase') == 'UNCONFIRMED'):
from .failed_session import cancelled_prewrite_startup
cancelled_before_write = cancelled_prewrite_startup(job)
if not (failed_open or _saved_and_closed(facts) or cancelled_before_write is not None):
return False
client_name = 'expeditionpcb.exe'
elif operation == 'catalog' and job.get('worker_role') == 'catalog_readonly' and desktop.startswith('CbbManagement_'):
client_name = 'librarymanager.exe'
else:
return False
workers = [p for p in identities if p.get('role') in ('worker','helper')]
clients = [p for p in identities if p.get('role') == 'native' and Path(p['image']).name.casefold() == client_name]
if not workers or len(clients) != 1: return False
if any(r.get('operation_id') != session['operation_id'] for r in active_write_records(session['library'])):
return False
with ExitStack() as held:
for worker in workers:
try:
handle = held.enter_context(_process_handle(worker['pid']))
if (win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
and _handle_identity(handle) == {k:worker[k] for k in ('created_handle','image')}):
return False
except pywintypes.error as error:
if error.winerror != 87: raise
client = clients[0]
handle = held.enter_context(_process_handle(client['pid']))
def same_client():
owner = _force_ownership(handle, client['pid'])
return (win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_TIMEOUT
and owner.get('force_user_confirmed') is True
and _handle_identity(handle) == {k:client[k] for k in ('created_handle','image')}
and all(owner.get(k) == client[k] for k in ('owner_sid','session_id')))
def empty_target():
snapshot = _process_windows({client['pid']}, include_hidden_documents=True)
windows = snapshot.get(client['pid'], [])
if (any(w.get('desktop') != desktop or w.get('documents')
or any(c['class'].casefold().startswith('afx:') and c.get('visible') is False
for c in w.get('children',[])) for w in windows)):
return None
return close_target(client_name, windows, incomplete=_window_error(snapshot,client['pid']))[0]
def load_failure_button():
from .failed_session import _startup_snapshot, _cancel_target
snapshot = _process_windows({client['pid']}, include_hidden_documents=True)
windows = snapshot.get(client['pid'], [])
if (_window_error(snapshot, client['pid']) or not windows
or any(w.get('desktop') != desktop for w in windows)):
return None
modals = [w for w in windows if w['class'] == '#32770']
if len(modals) != 1:
return None
with _window_desktop(desktop):
observed = _startup_snapshot(modals[0]['hwnd'], client['pid'])
target = _cancel_target(observed)
if target is None or target[0] != 'database_load_log':
return None
return observed, target[1].handle
if not same_client(): return False
if (cancelled_before_write is not None
and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write):
return False
target = empty_target()
failure = load_failure_button() if target is None and cancelled_before_write is not None else None
if (target is None and failure is None) or stop is not None and stop.is_set(): return False
check_active()
current, _, _ = _session(path, path.parent)
if current != session: return False
claim = dict(operation_id=session['operation_id'],pid=client['pid'],identity=client,
status='REQUESTED',hwnd=target['hwnd'] if target is not None else failure[1],
desktop=desktop)
write_session_record(path, {**session,'owned_idle_cleanup':claim})
# Re-read after durable I/O; never act on a window that gained a document.
latest, latest_state, latest_identities = _session(path, path.parent)
if (latest_state != state or latest_identities != identities
or latest.get('owned_idle_cleanup') != claim
or any(latest.get(k) != v for k,v in session.items() if k != 'recorded_at')
or not same_client() or read('request.json') != job
or (empty_target() != target if failure is None else load_failure_button() != failure)
or (cancelled_before_write is not None
and cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write)
or read_result() != result or result is None and not recoverable_orphan_session(path)
or stop is not None and stop.is_set()):
# Nothing was sent. The still-matching claim can be retried.
if latest.get('owned_idle_cleanup') == claim:
latest.pop('owned_idle_cleanup')
write_session_record(path, latest)
return False
with native_phase(read_only=True):
if failure is not None:
_post_window_message({'desktop': desktop}, failure[1], client['pid'], win32con.BM_CLICK)
deadline = time.monotonic() + 5
while time.monotonic() < deadline and same_client():
if stop is not None and stop.is_set():
break
target = empty_target()
if target is not None:
break
time.sleep(.1)
if (target is not None and (not same_client() or empty_target() != target
or cancelled_prewrite_startup(job, client['pid']) != cancelled_before_write)):
target = None
if target is not None and (stop is None or not stop.is_set()):
_post_window_message(target, target['hwnd'], client['pid'], win32con.WM_CLOSE)
deadline = time.monotonic() + 3
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
break
if stop is not None and stop.is_set():
break
exited = win32event.WaitForSingleObject(handle,0) == win32con.WAIT_OBJECT_0
write_session_record(path.with_name('owned-idle-cleanup-result.json'),dict(
operation_id=session['operation_id'],library=session['library'],
status='CLIENT_EXITED' if exited else 'WAITING',claim=claim,
resource_release_confirmed=False))
return True # Client exit is still not independent resource release proof.
except (OSError,pywintypes.error,ValueError,KeyError,TypeError,RuntimeError):
return False
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
def _request_close(row, *, stop=None): def _request_close(row, *, stop=None):
import win32con, win32event import win32con, win32event
with _process_handle(row['pid']) as handle: with _process_handle(row['pid']) as handle:
+20 -8
View File
@@ -1,6 +1,6 @@
Option Explicit Option Explicit
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK, remaining Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK, remaining
Dim nativeError, nativeDescription Dim nativeError, nativeDescription, actualProject, actualDocument, expectedDocument, savedState
WaitForStartGate WaitForStartGate
CheckCancellation CheckCancellation
expected = WScript.Arguments(0) expected = WScript.Arguments(0)
@@ -79,13 +79,25 @@ If Not stable Then
WScript.Quit 7 WScript.Quit 7
End If End If
WScript.Echo "POST_SAVE_SYNCHRONIZED" WScript.Echo "POST_SAVE_SYNCHRONIZED"
On Error Resume Next expectedDocument = ""
operationOK = doc.IsSaved() And LCase(pi.ProjectFile) = LCase(expected) If WScript.Arguments.Count > 1 Then expectedDocument = WScript.Arguments(1)
If WScript.Arguments.Count > 1 Then operationOK = operationOK And LCase(doc.Name) = LCase(WScript.Arguments(1)) For attempt = 1 To 10
nativeError = Err.Number On Error Resume Next
nativeDescription = Err.Description savedState = doc.IsSaved()
Err.Clear actualProject = pi.ProjectFile
On Error GoTo 0 actualDocument = ""
If expectedDocument <> "" Then actualDocument = doc.Name
nativeError = Err.Number
nativeDescription = Err.Description
Err.Clear
On Error GoTo 0
WScript.Echo "POST_SAVE_IDENTITY|project=" & actualProject & "|expected=" & expected & "|document=" & actualDocument & "|expected_document=" & expectedDocument
WScript.Echo "POST_SAVE_STATE|saved=" & CStr(savedState) & "|attempt=" & CStr(attempt) & "|error=" & CStr(nativeError)
operationOK = savedState And LCase(actualProject) = LCase(expected) And LCase(actualDocument) = LCase(expectedDocument)
If operationOK Or nativeError <> 0 Then Exit For
If LCase(actualProject) <> LCase(expected) Or LCase(actualDocument) <> LCase(expectedDocument) Then Exit For
WScript.Sleep 200
Next
If nativeError <> 0 Or Not operationOK Then If nativeError <> 0 Or Not operationOK Then
WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|identity_or_saved_state_unconfirmed|" & nativeDescription WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|identity_or_saved_state_unconfirmed|" & nativeDescription
WScript.Quit 8 WScript.Quit 8
+33 -8
View File
@@ -164,6 +164,8 @@ def register_worker_session(worker, job):
'lease_state': 'ACTIVE', 'resource_scope': session_resource_scope(job), 'lease_state': 'ACTIVE', 'resource_scope': session_resource_scope(job),
'worker_protection': protection, 'task_operation_id': context.operation_id if context else None, 'worker_protection': protection, 'task_operation_id': context.operation_id if context else None,
'blocked_resources': [], 'data_recovery_required': None}) 'blocked_resources': [], 'data_recovery_required': None})
if (protection == 'catalog_readonly' or job.get('operation') == 'verify') and job.get('supervisor_identity'):
record['supervisor_identity'] = job['supervisor_identity']
if job.get('start_gate_protocol') == 'event-v1': if job.get('start_gate_protocol') == 'event-v1':
import win32api, win32con, win32event import win32api, win32con, win32event
event = win32event.CreateEvent(None, True, False, None) event = win32event.CreateEvent(None, True, False, None)
@@ -315,7 +317,7 @@ def _result(status, detail='', *, session=None, state=None, proof=None):
(session or {}).get('data_recovery_required'))} (session or {}).get('data_recovery_required'))}
def _reconcile(path, root, handles, stack, *, release=True): def _reconcile(path, root, handles, stack, *, release=True, stop=None):
import pywintypes, win32api, win32con, win32event import pywintypes, win32api, win32con, win32event
from .residual_sessions import _handle_identity, _force_ownership from .residual_sessions import _handle_identity, _force_ownership
session, state, processes = _session(path, root) session, state, processes = _session(path, root)
@@ -353,11 +355,12 @@ def _reconcile(path, root, handles, stack, *, release=True):
if active: if active:
return _result('ACTIVE', '原生调用尚未确认返回', session=session, state=state) return _result('ACTIVE', '原生调用尚未确认返回', session=session, state=state)
if not release: if not release:
return _result('UNCONFIRMED', '记录中的进程已退出,需确认库占用已释放', session=session, state=state) return {**_result('UNCONFIRMED', '记录中的进程已退出,需确认库占用已释放',
session=session, state=state), 'processes_exited': True}
from .library_lock import release_retained_library from .library_lock import release_retained_library
try: try:
proof = release_retained_library(session['library'], Path(path).parent/'release-proof', proof = release_retained_library(session['library'], Path(path).parent/'release-proof',
block_name=session.get('block')) block_name=session.get('block'), **({'stop': stop} if stop is not None else {}))
except Exception as error: except Exception as error:
return _result('UNCONFIRMED', str(error), session=session, state=state) return _result('UNCONFIRMED', str(error), session=session, state=state)
if proof.get('status') != 'RELEASE_CONFIRMED': if proof.get('status') != 'RELEASE_CONFIRMED':
@@ -367,10 +370,10 @@ def _reconcile(path, root, handles, stack, *, release=True):
return _result('RELEASED', session=session, state=state, proof=proof) return _result('RELEASED', session=session, state=state, proof=proof)
def reconcile_session_record(path, *, evidence_root): def reconcile_session_record(path, *, evidence_root, stop=None):
with ExitStack() as stack: with ExitStack() as stack:
try: try:
return _reconcile(Path(path), Path(evidence_root), {}, stack) return _reconcile(Path(path), Path(evidence_root), {}, stack, stop=stop)
except Exception as error: except Exception as error:
return _result('UNCONFIRMED', str(error)) return _result('UNCONFIRMED', str(error))
@@ -409,8 +412,8 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
pass pass
if result['status'] == 'ACTIVE' and not observation_only and not stop.is_set(): if result['status'] == 'ACTIVE' and not observation_only and not stop.is_set():
try: try:
from .residual_sessions import resume_cancelled_startup from .residual_sessions import resume_cancelled_startup, finish_owned_idle_session
if resume_cancelled_startup(path, stop=stop): if resume_cancelled_startup(path, stop=stop) or finish_owned_idle_session(path, stop=stop):
# Cleanup is not release proof. Re-read all held identities # Cleanup is not release proof. Re-read all held identities
# and independently prove the resource release as usual. # and independently prove the resource release as usual.
result = _reconcile(Path(path), Path(evidence_root), handles, stack) result = _reconcile(Path(path), Path(evidence_root), handles, stack)
@@ -481,7 +484,7 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
if progress is not None: if progress is not None:
progress(value) progress(value)
def observation_only(): def observation_only():
if not observe_only: if not (observe_only() if callable(observe_only) else observe_only):
return False return False
with _observer_guard: with _observer_guard:
value = _retained_results.get(key, {}) value = _retained_results.get(key, {})
@@ -510,6 +513,26 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
thread.start() thread.start()
def _completed_read_only_catalog(path, session, observed):
if (session.get('operation') != 'catalog' or session.get('worker_role') != 'catalog_readonly'
or observed.get('phase') != 'FINISHED' or observed.get('processes_exited') is not True):
return False
# A final worker receipt and fresh exit facts retire the read-only journal
# from recovery discovery. The original files remain available as evidence.
result_path = path.with_name('result.json')
try:
if result_path.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
return False
with result_path.open('rb') as stream:
data = stream.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
return False
result = json.loads(data)
return isinstance(result, dict) and result.get('safe_to_continue') is True
except (OSError, ValueError):
return False
def discover_sessions(evidence_root, *, library=None): def discover_sessions(evidence_root, *, library=None):
"""Only our bounded journals are inputs; never execute a stored command.""" """Only our bounded journals are inputs; never execute a stored command."""
root = Path(evidence_root) root = Path(evidence_root)
@@ -550,6 +573,8 @@ def discover_sessions(evidence_root, *, library=None):
if library is not None and _library_key(value.get('library', '')) != _library_key(library): if library is not None and _library_key(value.get('library', '')) != _library_key(library):
continue continue
observed = inspect_session_record(path, evidence_root=root) observed = inspect_session_record(path, evidence_root=root)
if _completed_read_only_catalog(path, value, observed):
continue
value = {**value, **observed, 'library': value.get('library'), value = {**value, **observed, 'library': value.get('library'),
'block': value.get('block'), 'operation_id': value['operation_id'], 'path': str(path)} 'block': value.get('block'), 'operation_id': value['operation_id'], 'path': str(path)}
except (OSError, ValueError): except (OSError, ValueError):
@@ -113,13 +113,17 @@ class BackupRecoveryDialog(QDialog):
options = {'version_prompt': lambda choice:self._emit(context, 'choice',choice),'stop':context.stop} if self.recoverer is None else {} options = {'version_prompt': lambda choice:self._emit(context, 'choice',choice),'stop':context.stop} if self.recoverer is None else {}
action = lambda: recoverer(request, source, progress=lambda event:self._emit(context, 'progress',event), **options) action = lambda: recoverer(request, source, progress=lambda event:self._emit(context, 'progress',event), **options)
if self.native_queue is None: return context.run(action) if self.native_queue is None: return context.run(action)
from ..operation_queue import QueueCancelled from ..operation_queue import QueueCancelled, QueueUnavailable
def restore(): def restore():
self._emit(context, 'progress',{'stage': 'queue_acquired'}) self._emit(context, 'progress',{'stage': 'queue_acquired'})
return action() return action()
try: try:
return self.native_queue.run(restore, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress', return self.native_queue.run(restore, stop=context.stop, context=context, skip_unavailable=True, waiting=lambda: self._emit(context, 'progress',
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'})) {'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
except QueueUnavailable as error:
from ..verify_runner import VerifyResult
return VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
error_stage='admission')
except QueueCancelled as error: except QueueCancelled as error:
from ..operation_queue import TaskHandoff from ..operation_queue import TaskHandoff
from ..verify_runner import VerifyResult, _handoff_verify_result from ..verify_runner import VerifyResult, _handoff_verify_result
+21 -7
View File
@@ -1,7 +1,7 @@
"""A check batch owns its snapshot and yields the native queue after each CBB.""" """A check batch owns its snapshot and yields the native queue after each CBB."""
from PySide6.QtCore import QObject, QThreadPool, Signal from PySide6.QtCore import QObject, QThreadPool, Signal
from .workers import ServiceWorker from .workers import ServiceWorker
from ..operation_queue import QueueCancelled, BatchTaskContext from ..operation_queue import QueueCancelled, QueueUnavailable, BatchTaskContext, request_library_keys
from ..verify_runner import VerifyResult, run_verify, write_batch_report from ..verify_runner import VerifyResult, run_verify, write_batch_report
from ..icdb_maintenance import write_maintenance_report from ..icdb_maintenance import write_maintenance_report
@@ -30,7 +30,7 @@ class IcdbCheckTask(QObject):
self.running = False self.running = False
self.report = None self.report = None
self.report_error = '' self.report_error = ''
self.retained_libraries = set() self.retained_libraries = {}
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1) self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
def _emit_event(self, event): def _emit_event(self, event):
@@ -66,9 +66,6 @@ class IcdbCheckTask(QObject):
if self.stop.is_set(): if self.stop.is_set():
self.results.extend(VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB') self.results.extend(VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
for _ in self.requests[len(self.results):]) for _ in self.requests[len(self.results):])
while len(self.results) < len(self.requests) and str(
self.requests[len(self.results)].lmc_file).casefold() in self.retained_libraries:
self.results.append(VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的检查'))
if len(self.results) == len(self.requests): if len(self.results) == len(self.requests):
self._report(); return self._report(); return
if self.paused: return if self.paused: return
@@ -76,6 +73,19 @@ class IcdbCheckTask(QObject):
def check(): def check():
from ..session_record import library_available, library_wait_reason from ..session_record import library_available, library_wait_reason
try: try:
keys = request_library_keys(request, self.context)
for index in {self.retained_libraries[key] for key in keys.intersection(self.retained_libraries)}:
previous = self.requests[index]
from ..operation_lifecycle import recheck_failed_release
refreshed = recheck_failed_release(previous.lmc_file, previous.block_name,
self.results[index], stop=self.stop)
if refreshed.safe_to_continue:
self.results[index] = refreshed
self.retained_libraries = {k:v for k,v in self.retained_libraries.items() if v != index}
if keys.intersection(self.retained_libraries):
index = self.retained_libraries[next(iter(keys.intersection(self.retained_libraries)))]
return VerifyResult('SKIPPED', error_category='PREVIOUS_SESSION_UNRELEASED',
error_stage='admission', stderr=f'前项 {self.requests[index].block_name} 的同库会话尚未释放,当前项未启动。')
def execute(): def execute():
if self.status_reader is not None: if self.status_reader is not None:
statuses = self.status_reader((request.block_name,), request.lmc_file) statuses = self.status_reader((request.block_name,), request.lmc_file)
@@ -92,12 +102,15 @@ class IcdbCheckTask(QObject):
from ..operation_lifecycle import recheck_failed_release from ..operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.lmc_file, request.block_name, result) result = recheck_failed_release(request.lmc_file, request.block_name, result)
return result return result
return self.queue.run(execute, stop=self.stop, context=self.context, return self.queue.run(execute, stop=self.stop, context=self.context, skip_unavailable=True,
wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)), wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)),
ready=lambda: not self.paused, ready=lambda: not self.paused,
waiting=lambda: self._emit_event({'stage': 'waiting_native_slot', 'block': request.block_name, waiting=lambda: self._emit_event({'stage': 'waiting_native_slot', 'block': request.block_name,
'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file), 'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file),
'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'})) 'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'}))
except QueueUnavailable as error:
return VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
error_stage='admission')
except QueueCancelled as error: except QueueCancelled as error:
from ..operation_queue import TaskHandoff from ..operation_queue import TaskHandoff
from ..verify_runner import _handoff_verify_result from ..verify_runner import _handoff_verify_result
@@ -116,7 +129,8 @@ class IcdbCheckTask(QObject):
request = self.requests[len(self.results)] request = self.requests[len(self.results)]
name = request.block_name name = request.block_name
if not result.safe_to_continue: if not result.safe_to_continue:
self.retained_libraries.add(str(request.lmc_file).casefold()) self.retained_libraries.update({key:len(self.results)
for key in request_library_keys(request, self.context)})
self.results.append(result) self.results.append(result)
if result.status in ('CANCELLED', 'QUEUE_STOP'): self.stop.set() if result.status in ('CANCELLED', 'QUEUE_STOP'): self.stop.set()
self.item_done.emit(name, result) self.item_done.emit(name, result)
+292 -63
View File
@@ -5,18 +5,20 @@ import ntpath
import time import time
from collections import Counter from collections import Counter
from dataclasses import replace from dataclasses import replace
from datetime import datetime
from types import SimpleNamespace from types import SimpleNamespace
import json import json
from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled, TaskHandoff from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled, TaskHandoff
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt, QTimer from PySide6.QtCore import QObject, QThreadPool, Signal, Qt, QTimer
from PySide6.QtGui import QColor, QIcon from PySide6.QtGui import QColor, QIcon, QTextCursor
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout, from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton, QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox, QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
QTabBar, QStackedWidget, QSizePolicy) QTabBar, QStackedWidget, QSizePolicy, QDialog, QDialogButtonBox, QPlainTextEdit)
from PySide6.QtWidgets import QStyle from PySide6.QtWidgets import QStyle
from shiboken6 import isValid
def _path_key(value): def _path_key(value):
@@ -76,6 +78,8 @@ STATUS_LABELS = {
'MALFORMED': '状态桥协议错误', 'MALFORMED': '状态桥协议错误',
'CRASHED': '状态桥崩溃', 'CRASHED': '状态桥崩溃',
} }
CATALOG_MANAGER_WAIT_SECONDS = 120
VERIFY_RELEASE_WAIT_SECONDS = 120
def application_icon_path(): def application_icon_path():
return Path(__file__).resolve().parents[1] / 'assets' / 'cbb_refresh_verify.ico' return Path(__file__).resolve().parents[1] / 'assets' / 'cbb_refresh_verify.ico'
@@ -117,17 +121,22 @@ class MainWindow(QWidget):
self.native_backup_timer.timeout.connect(self._poll_native_backup) self.native_backup_timer.timeout.connect(self._poll_native_backup)
self._injected_reader = reader is not None self._injected_reader = reader is not None
self.reader = reader or read_library_fast self.reader = reader or read_library_fast
self.catalog_reader = catalog_reader or (None if reader is not None else getattr(self.management_adapter,'catalog',None)) self.catalog_reader = catalog_reader or (None if reader is not None else getattr(
self.management_adapter, 'catalog_registrations', getattr(self.management_adapter, 'catalog', None)))
self._view_revision = 0 self._view_revision = 0
self._jobs = {} self._jobs = {}
self._dialogs = [] self._dialogs = []
self._current_job = None self._current_job = None
self._stale_table = False self._stale_table = False
self._table_library_path = None
self._catalog_snapshot_time = ''
self._catalog_retry = False
self._read_counts = (None, None, None) self._read_counts = (None, None, None)
self._diagnostic_evidence = {} self._diagnostic_evidence = {}
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8) self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8)
self.lifecycle_pool = QThreadPool(self); self.lifecycle_pool.setMaxThreadCount(1) self.lifecycle_pool = QThreadPool(self); self.lifecycle_pool.setMaxThreadCount(1)
self.lease_pool = QThreadPool(self); self.lease_pool.setMaxThreadCount(1) self.lease_pool = QThreadPool()
self.lease_pool.setMaxThreadCount(1)
self._lifecycle_workers = set() self._lifecycle_workers = set()
self._lifecycle_contexts = set() self._lifecycle_contexts = set()
self._lease_pending = 0 self._lease_pending = 0
@@ -154,8 +163,7 @@ class MainWindow(QWidget):
self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set() self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set()
self._row_by_name = {} self._row_by_name = {}
self._records_by_name = {} self._records_by_name = {}
self.status_refresher = status_refresher or (lambda names, path: authoritative_status_map( self.status_refresher = status_refresher or authoritative_status_map
names, path, self.data_root / 'status-refresh.jsonl'))
self.skipped_names = set(); self.skip_reasons = {} self.skipped_names = set(); self.skip_reasons = {}
self._global_icdb_run = False self._global_icdb_run = False
self._icdb_completed = 0 self._icdb_completed = 0
@@ -176,6 +184,9 @@ class MainWindow(QWidget):
self.native_lm_verify_check.setChecked(native_lm_verify_enabled()) self.native_lm_verify_check.setChecked(native_lm_verify_enabled())
self.native_lm_verify_check.setToolTip( self.native_lm_verify_check.setToolTip(
'仅在 Win10 兼容测试时启用;默认仍使用已验证的 ReusableCircuit 直接流程。') '仅在 Win10 兼容测试时启用;默认仍使用已验证的 ReusableCircuit 直接流程。')
self.auto_confirm_pcb_open_check = QCheckBox('无人应答时自动核验 PCB 读写占用')
self.auto_confirm_pcb_open_check.setChecked(True)
self.auto_confirm_pcb_open_check.setToolTip('普通校验中,3 秒后检查占用,确认可写后继续。关闭后默认跳过本项。')
self.advanced_toggle = QToolButton(); self.advanced_toggle.setText('高级设置') self.advanced_toggle = QToolButton(); self.advanced_toggle.setText('高级设置')
self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton)) self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton))
self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False) self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False)
@@ -185,10 +196,12 @@ class MainWindow(QWidget):
advanced_layout.addRow('DMS 登录配置', self.dms_edit) advanced_layout.addRow('DMS 登录配置', self.dms_edit)
advanced_layout.addRow('Mentor bin', self.mentor_bin_edit) advanced_layout.addRow('Mentor bin', self.mentor_bin_edit)
advanced_layout.addRow('触发方式', self.native_lm_verify_check) advanced_layout.addRow('触发方式', self.native_lm_verify_check)
advanced_layout.addRow('读写确认', self.auto_confirm_pcb_open_check)
self.advanced_panel.setVisible(False) self.advanced_panel.setVisible(False)
self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible) self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible)
self.cbb_table = QTableWidget(0, 4) self.cbb_table = QTableWidget(0, 4)
self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '备注']) self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '备注(双击查看)'])
self.cbb_table.cellDoubleClicked.connect(self._show_result_detail)
self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
self.cbb_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch) self.cbb_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
for column in (1, 2): for column in (1, 2):
@@ -212,6 +225,9 @@ class MainWindow(QWidget):
self.status_filter.currentIndexChanged.connect(self._apply_filters) self.status_filter.currentIndexChanged.connect(self._apply_filters)
self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展') self.timeout_spin = QSpinBox(); self.timeout_spin.setRange(30, 1800); self.timeout_spin.setValue(DEFAULT_TIMEOUT_SECONDS); self.timeout_spin.setSuffix(' 秒 / 无进展')
self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library) self.load_button = QPushButton('读取 CBB'); self.load_button.clicked.connect(self.load_library)
self.catalog_status_button = QPushButton('刷新已登记项状态')
self.catalog_status_button.clicked.connect(self._refresh_registered_catalog)
self.catalog_status_button.hide()
self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library) self.browse_button = QPushButton('选择'); self.browse_button.clicked.connect(self.choose_library)
self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected) self.selected_batch_button = QPushButton('批量校验已选'); self.selected_batch_button.clicked.connect(self.verify_selected)
self.batch_button = QPushButton('校验可见非 READY'); self.batch_button.clicked.connect(self.verify_all) self.batch_button = QPushButton('校验可见非 READY'); self.batch_button.clicked.connect(self.verify_all)
@@ -250,7 +266,7 @@ class MainWindow(QWidget):
self.output.setMaximumHeight(180) self.output.setMaximumHeight(180)
layout = QVBoxLayout(self) layout = QVBoxLayout(self)
row = QHBoxLayout(); row.addWidget(QLabel('中心库')); row.addWidget(self.lmc_edit) row = QHBoxLayout(); row.addWidget(QLabel('中心库')); row.addWidget(self.lmc_edit)
row.addWidget(self.browse_button); row.addWidget(self.load_button) row.addWidget(self.browse_button); row.addWidget(self.load_button); row.addWidget(self.catalog_status_button)
layout.addLayout(row) layout.addLayout(row)
self.library_notice = QLabel() self.library_notice = QLabel()
self.library_notice.setWordWrap(True) self.library_notice.setWordWrap(True)
@@ -349,6 +365,7 @@ class MainWindow(QWidget):
self._update() self._update()
def _invalidate(self): def _invalidate(self):
self._cancel_catalog_read()
if self._current_job is not None and self._current_job.kind == 'read': if self._current_job is not None and self._current_job.kind == 'read':
self._current_job.context.close(timeout_seconds=0) self._current_job.context.close(timeout_seconds=0)
self._view_revision += 1 self._view_revision += 1
@@ -356,6 +373,7 @@ class MainWindow(QWidget):
self._reimport_offers = () self._reimport_offers = ()
self._diagnostic_evidence.clear() self._diagnostic_evidence.clear()
self._resume_batch = None self._resume_batch = None
self._catalog_retry = False
self._stale_table = bool(self._records_by_name) self._stale_table = bool(self._records_by_name)
self._release_library_lease() self._release_library_lease()
self.loaded_path = None self.loaded_path = None
@@ -392,21 +410,24 @@ class MainWindow(QWidget):
if signal == 'version_choice': value.choose('cancel') if signal == 'version_choice': value.choose('cancel')
def _finish_job(self, job): def _finish_job(self, job):
view_alive = isValid(self) and isValid(self.cbb_table)
if job.keep_session: if job.keep_session:
if self._job_current(job): self._finished() if view_alive and self._job_current(job): self._finished()
return return
paused = getattr(job, 'paused_check', None) paused = getattr(job, 'paused_check', None)
if paused is not None and paused.active and not paused.stop.is_set() and not self._closing: if view_alive and paused is not None and paused.active and not paused.stop.is_set() and not self._closing:
paused.resume() paused.resume()
job.active = False job.active = False
self._jobs.pop(job.context.operation_id, None) self._jobs.pop(job.context.operation_id, None)
state = job.context.close(timeout_seconds=0) state = job.context.close(timeout_seconds=0)
if job.lease is not None and job.lease is not self.library_lease: if job.lease is not None and (not view_alive or job.lease is not self.library_lease):
if state['pending'] or id(job.lease) in self._shutdown_leases: if state['pending'] or id(job.lease) in self._shutdown_leases:
self._retain_path_lease(job.lease) self._retain_path_lease(job.lease)
elif not any(other.lease is job.lease for other in self._jobs.values()): elif not any(other.lease is job.lease for other in self._jobs.values()):
self._close_path_lease(job.lease) self._close_path_lease(job.lease)
if self._job_current(job): self._finished() if view_alive:
if self._job_current(job): self._finished()
else: self._update()
def _release_library_lease(self): def _release_library_lease(self):
lease, self.library_lease = self.library_lease, None lease, self.library_lease = self.library_lease, None
@@ -440,7 +461,10 @@ class MainWindow(QWidget):
def _lease_action(self, action, completed=None, failed=None, *, hold_busy=False, def _lease_action(self, action, completed=None, failed=None, *, hold_busy=False,
library=None, completed_always=False): library=None, completed_always=False):
# The serial pool orders retain before every subsequent close. # The serial pool outlives the view and orders retain before close.
if not isValid(self) or not isValid(self.cbb_table):
self.lease_pool.start(ServiceWorker(action))
return
owner = (self._view_revision, id(self._current_job)) owner = (self._view_revision, id(self._current_job))
def current(): def current():
from shiboken6 import isValid from shiboken6 import isValid
@@ -460,7 +484,10 @@ class MainWindow(QWidget):
worker = ServiceWorker(lambda:context.run(action)) worker = ServiceWorker(lambda:context.run(action))
self._lease_workers.add(worker) self._lease_workers.add(worker)
if completed is not None: if completed is not None:
worker.signals.succeeded.connect(lambda result:completed(result) if completed_always or current() else None) def ready(result):
if isValid(self) and isValid(self.cbb_table) and (completed_always or current()):
completed(result)
worker.signals.succeeded.connect(ready)
worker.signals.failed.connect(lambda error:(failed or self._display_error)(error) if current() else None) worker.signals.failed.connect(lambda error:(failed or self._display_error)(error) if current() else None)
def finished(): def finished():
self._lease_workers.discard(worker) self._lease_workers.discard(worker)
@@ -509,8 +536,8 @@ class MainWindow(QWidget):
'请选择一个当前可见的非 READY CBB。' if native_target is None else '') '请选择一个当前可见的非 READY CBB。' if native_target is None else '')
self.native_repair_button.setToolTip(reason or '打开原生工具;请在其中手动选择 Repair。') self.native_repair_button.setToolTip(reason or '打开原生工具;请在其中手动选择 Repair。')
ready = ready and not self._native_backup_same_library() ready = ready and not self._native_backup_same_library()
self.batch_button.setEnabled(ready and bool(self._eligible_names())) self.batch_button.setEnabled(ready and bool(self._eligible_names(require_status=True)))
self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True))) self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True, require_status=True)))
self.icdb_repair_button.setEnabled(ready and not self._icdb_active() and bool(self._maintenance_names())) self.icdb_repair_button.setEnabled(ready and not self._icdb_active() and bool(self._maintenance_names()))
self.icdb_stop_button.setEnabled(self._icdb_active() and not self.icdb_task.stop.is_set()) self.icdb_stop_button.setEnabled(self._icdb_active() and not self.icdb_task.stop.is_set())
self.backup_restore_button.setEnabled(ready and bool( self.backup_restore_button.setEnabled(ready and bool(
@@ -540,15 +567,28 @@ class MainWindow(QWidget):
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
notice = ('上次操作结果待复查,执行前将重新检查占用。' notice = ('上次操作结果待复查,执行前将重新检查占用。'
if self._management_library_unsafe(current_library) else '') if self._management_library_unsafe(current_library) else '')
notice = '旧表已失效,请重新读取中心库。' if self._stale_table else notice if self._stale_table:
if self._catalog_snapshot_time:
when = self._catalog_snapshot_time
notice = f'显示上次完整清单({when},待刷新)· {self._table_library_path}'
else:
notice = '当前显示上次读取结果(已失效)· 请重新读取中心库。'
self.catalog_status_button.setVisible(
self._catalog_retry and not self._closing and self._table_library_path == self.lmc_edit.text()
and self._read_counts[1] is not None and self.mentor_lmc_path is not None)
self.catalog_status_button.setEnabled(not self.busy)
self.load_button.setText('重试读取' if self._catalog_retry else '读取 CBB')
self.library_notice.setText(notice) self.library_notice.setText(notice)
self.library_notice.setVisible(bool(notice)) self.library_notice.setVisible(bool(notice))
for widget in (self.lmc_edit, self.browse_button, self.load_button, for widget in (self.lmc_edit, self.browse_button, self.load_button,
self.timeout_spin, self.advanced_toggle, self.advanced_panel): self.timeout_spin, self.advanced_toggle, self.advanced_panel):
widget.setEnabled(not self._closing) widget.setEnabled(not self._closing)
counts = self.visible_counts() counts = self.visible_counts()
unknown = sum(r.status == 'UNKNOWN' for r in self.visible_records())
pending = sum(r.status == 'PENDING' for r in self.visible_records())
self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · ' self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · '
f'READY {counts["ready"]} · 异常/待确认 {counts["error"]}') f'READY {counts["ready"]} · 待验证 {pending} · 待读取 {unknown} · '
f'异常 {counts["error"]}')
directory, native, missing = self._read_counts directory, native, missing = self._read_counts
if directory is not None: if directory is not None:
self.counts_label.setText(self.counts_label.text() + self.counts_label.setText(self.counts_label.text() +
@@ -575,6 +615,7 @@ class MainWindow(QWidget):
def _show_unfinished_management(self): def _show_unfinished_management(self):
from cbb_refresh_verify.management import unfinished_operations from cbb_refresh_verify.management import unfinished_operations
from cbb_refresh_verify.session_record import discover_sessions, handoff_session from cbb_refresh_verify.session_record import discover_sessions, handoff_session
from cbb_refresh_verify.residual_sessions import recoverable_orphan_session
root = self.data_root root = self.data_root
revision, owner = self._view_revision, self._current_job revision, owner = self._view_revision, self._current_job
context = BatchTaskContext(str(root)) context = BatchTaskContext(str(root))
@@ -588,8 +629,9 @@ class MainWindow(QWidget):
sessions = discover_sessions(root) sessions = discover_sessions(root)
for session in sessions: for session in sessions:
if session['status'] == 'ACTIVE': if session['status'] == 'ACTIVE':
handoff_session(session['path'], evidence_root=root, path = session['path']
observe_only=True, handoff_session(path, evidence_root=root,
observe_only=lambda path=path: not recoverable_orphan_session(path),
progress=lambda value: notify({'stage': 'session_observation', **value})) progress=lambda value: notify({'stage': 'session_observation', **value}))
return unfinished, sessions return unfinished, sessions
worker = ServiceWorker(lambda:context.run(inspect)) worker = ServiceWorker(lambda:context.run(inspect))
@@ -956,12 +998,13 @@ class MainWindow(QWidget):
def visible_counts(self): def visible_counts(self):
records = self.visible_records() records = self.visible_records()
return {'visible': len(records), 'ready': sum(r.status == 'READY' for r in records), return {'visible': len(records), 'ready': sum(r.status == 'READY' for r in records),
'error': sum(r.status not in {'READY', 'PENDING'} or r.name in self.skipped_names 'error': sum(r.status not in {'READY', 'PENDING', 'UNKNOWN'} or r.name in self.skipped_names
for r in records)} for r in records)}
def _eligible_names(self, *, checked_only=False): def _eligible_names(self, *, checked_only=False, require_status=False):
records = self.selected_records() if checked_only else self.visible_records() records = self.selected_records() if checked_only else self.visible_records()
return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names] return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names
and (not require_status or self.catalog_reader is None or r.status == 'PENDING')]
def _maintenance_names(self): def _maintenance_names(self):
records = self.selected_records() or self.visible_records() records = self.selected_records() or self.visible_records()
@@ -1030,13 +1073,14 @@ class MainWindow(QWidget):
if isinstance(error, TaskHandoff) and job.lease is not None: if isinstance(error, TaskHandoff) and job.lease is not None:
self._retain_path_lease(job.lease) self._retain_path_lease(job.lease)
if not self._job_current(job): return if not self._job_current(job): return
if isinstance(error, QueueCancelled): self._display_error(error) if isinstance(error, QueueCancelled):
self._display_error('已取消读取中心库。' if job.kind == 'read' else error)
else: self._failed(error) else: self._failed(error)
self.worker.signals.failed.connect(failed) self.worker.signals.failed.connect(failed)
self.worker.signals.finished.connect(lambda: (self._lifecycle_workers.discard(worker), self._finish_job(job))) self.worker.signals.finished.connect(lambda: (self._lifecycle_workers.discard(worker), self._finish_job(job)))
self.pool.start(self.worker) self.pool.start(self.worker)
def _queued_action(self, action, *, label='', library=None, job=None): def _queued_action(self, action, *, label='', library=None, job=None, wait_for_release=False):
from cbb_refresh_verify.session_record import library_available, library_wait_reason from cbb_refresh_verify.session_record import library_available, library_wait_reason
if library is None: if library is None:
from PySide6.QtCore import QThread from PySide6.QtCore import QThread
@@ -1054,7 +1098,8 @@ class MainWindow(QWidget):
event['detail'] = label+'中…' event['detail'] = label+'中…'
emit(event) emit(event)
return action() return action()
return lambda: self.native_queue.run(execute, stop=stop, context=job.context if job else None, return lambda: self.native_queue.run(execute, stop=stop, context=job.context if job else None, skip_unavailable=True,
wait_for_release_seconds=VERIFY_RELEASE_WAIT_SECONDS if wait_for_release else None,
wait_state=lambda: library_wait_reason(library), wait_state=lambda: library_wait_reason(library),
waiting=lambda: emit({'stage': 'waiting_native_slot', waiting=lambda: emit({'stage': 'waiting_native_slot',
'library': str(library), 'retained': not library_available(library), 'library': str(library), 'retained': not library_available(library),
@@ -1248,12 +1293,22 @@ class MainWindow(QWidget):
self._bind_summary_action(summary, action, recover) self._bind_summary_action(summary, action, recover)
summary.show(); self._update() summary.show(); self._update()
def _cancel_catalog_read(self):
for job in self._jobs.values():
if job.kind == 'catalog':
job.context.cancel()
self.native_queue.wake()
def load_library(self): def load_library(self):
if self._closing or not self.lmc_edit.text(): return if self._closing or not self.lmc_edit.text(): return
if (self._current_job is not None and self._current_job.kind == 'read' if any(job.kind in ('read', 'catalog') and job.active
and self._current_job.active and self._current_job.revision == self._view_revision): return and not job.context.stop.is_set() and job.revision == self._view_revision
for job in self._jobs.values()):
return
self._cancel_catalog_read()
self._view_revision += 1 self._view_revision += 1
self._diagnostic_evidence.clear() self._diagnostic_evidence.clear()
self._catalog_retry = False
self._stale_table = bool(self._records_by_name) self._stale_table = bool(self._records_by_name)
job = self._new_job('read', library=self.lmc_edit.text()) job = self._new_job('read', library=self.lmc_edit.text())
job.lease = None job.lease = None
@@ -1270,6 +1325,7 @@ class MainWindow(QWidget):
self._release_library_lease() self._release_library_lease()
self.loaded_path = None self.loaded_path = None
path = self.lmc_edit.text() path = self.lmc_edit.text()
preserve = self._read_counts[1] is not None
self.status_label.setText('正在读取中心库…') self.status_label.setText('正在读取中心库…')
def read(): def read():
import pythoncom import pythoncom
@@ -1291,9 +1347,6 @@ class MainWindow(QWidget):
recovery_view = False recovery_view = False
result = self.reader(mentor_path) result = self.reader(mentor_path)
job.context.check_active() job.context.check_active()
if not result.error:
self._publish_check_statuses(mentor_path,
{record.name: record.status for record in result.records}, lease)
if self.logging_context: if self.logging_context:
statuses = Counter(record.status for record in result.records) statuses = Counter(record.status for record in result.records)
unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}] unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}]
@@ -1302,8 +1355,9 @@ class MainWindow(QWidget):
len(result.records), int((time.monotonic() - started) * 1000), len(result.records), int((time.monotonic() - started) * 1000),
dict(statuses), unknown[:20]) dict(statuses), unknown[:20])
skip_reasons = {} skip_reasons = {}
if not result.error: if not result.error and (self.catalog_reader is None or result.catalog_verified):
for record in result.records: for record in result.records:
job.context.check_active()
reason = preflight_skip_reason(mentor_path, record.name) reason = preflight_skip_reason(mentor_path, record.name)
if reason: if reason:
skip_reasons[record.name] = reason skip_reasons[record.name] = reason
@@ -1318,16 +1372,27 @@ class MainWindow(QWidget):
if path != self.lmc_edit.text() or job.revision != self._view_revision: if path != self.lmc_edit.text() or job.revision != self._view_revision:
self._close_path_lease(lease) self._close_path_lease(lease)
return return
if result.error: if result.error or (job.active and job.context.stop.is_set()):
self._close_path_lease(lease) self._close_path_lease(lease)
self.status_label.setText(result.error); return self.status_label.setText(result.error or '已取消读取中心库。')
return
self.library_lease = lease self.library_lease = lease
self.mentor_lmc_path = mentor_path
if preserve and self.catalog_reader is not None and not result.catalog_verified:
self._start_catalog(job, result, lease, mentor_path, loaded)
return
if result.catalog_verified or self.catalog_reader is None:
self._publish_check_statuses(mentor_path,
{record.name: record.status for record in result.records
if record.catalog_source != 'directory_only'}, lease)
preview = self.catalog_reader is not None and not result.catalog_verified
self._stale_table = False self._stale_table = False
self._table_library_path = path
self._catalog_snapshot_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') if result.catalog_verified else ''
self._read_counts = (result.directory_count, result.native_count, self._read_counts = (result.directory_count, result.native_count,
result.missing_project_count if result.missing_project_count is not None else len(skip_reasons)) result.missing_project_count if result.missing_project_count is not None else len(skip_reasons))
self._maintenance_recovery_view = recovery_view self._maintenance_recovery_view = recovery_view
self.mentor_lmc_path = mentor_path self.loaded_path = path if not preview or self._injected_reader else None
self.loaded_path = path
try: try:
if self._settings_enabled: if self._settings_enabled:
self.data_root.mkdir(parents=True, exist_ok=True) self.data_root.mkdir(parents=True, exist_ok=True)
@@ -1396,7 +1461,7 @@ class MainWindow(QWidget):
self.status_label.setText('协调阻止恢复视图:仅按目录显示工程,状态未确认(UNKNOWN),不代表损坏。' self.status_label.setText('协调阻止恢复视图:仅按目录显示工程,状态未确认(UNKNOWN),不代表损坏。'
'仅可明确执行 ICDB 维护或释放检查,其他写入与原生状态读取已禁用。') '仅可明确执行 ICDB 维护或释放检查,其他写入与原生状态读取已禁用。')
self._apply_filters() self._apply_filters()
if self.catalog_reader is not None and not result.catalog_verified: if preview:
self._start_catalog(job, result, lease, mentor_path, loaded) self._start_catalog(job, result, lease, mentor_path, loaded)
self._start(read, loaded, queued=False, job=job, metadata_only=True, self._start(read, loaded, queued=False, job=job, metadata_only=True,
stale=lambda payload: self._close_path_lease(payload[2])) stale=lambda payload: self._close_path_lease(payload[2]))
@@ -1407,20 +1472,54 @@ class MainWindow(QWidget):
job = SimpleNamespace(context=context, kind='catalog', revision=read_job.revision, job = SimpleNamespace(context=context, kind='catalog', revision=read_job.revision,
lease=lease, requests=(), records={}, active=True, keep_session=False) lease=lease, requests=(), records={}, active=True, keep_session=False)
self._jobs[context.operation_id] = job self._jobs[context.operation_id] = job
def reconcile(): root = self.data_root/'catalog'/context.operation_id
catalog = self.catalog_reader(Path(library), self.data_root/'catalog'/context.operation_id) checkpoint = root/'status-refresh.pending.jsonl' if self.status_refresher is authoritative_status_map else None
started = time.monotonic()
def phase(stage, detail):
if self.logging_context:
self.logging_context.logger.info('%s library=%s elapsed_ms=%d detail=%s', stage,
library, int((time.monotonic()-started)*1000), detail)
try:
self.signals.event.emit((read_job.revision, read_job, {
'stage': stage, 'detail': detail, 'library': str(library),
'catalog_id': context.operation_id,
}))
except RuntimeError:
pass # A closed Qt receiver cannot change the scan outcome.
def reconcile(evidence):
phase('catalog_start', '正在读取 Mentor 原生目录…')
catalog = self.catalog_reader(Path(library), evidence)
if _path_key(catalog.library) != _path_key(library) or not catalog.safe_to_continue or catalog.flow != 1: if _path_key(catalog.library) != _path_key(library) or not catalog.safe_to_continue or catalog.flow != 1:
raise ValueError('CATALOG_UNCONFIRMED: 原生目录身份或退出未确认。') raise ValueError('CATALOG_UNCONFIRMED: 原生目录身份或退出未确认。')
native = {entry.name: entry for entry in catalog.entries if entry.partition == 'Logical-Physical'} native = {entry.name: entry for entry in catalog.entries if entry.partition == 'Logical-Physical'}
directories = {record.name: record for record in initial.records} directories = {record.name: record for record in initial.records}
names = tuple(sorted(native.keys() | directories.keys())) names = tuple(sorted(native.keys() | directories.keys()))
try: context.check_active()
phase('catalog_status', f'已核对 0/{len(native)} 项原生状态…')
if checkpoint is None:
statuses = self.status_refresher(tuple(native), Path(library)) statuses = self.status_refresher(tuple(native), Path(library))
except Exception: else:
statuses = {name:'UNAVAILABLE' for name in native} from cbb_refresh_verify.operation_queue import note_metadata_progress
self._publish_check_statuses(library, statuses, lease) last_notice = 0.0
def report_progress(done, total):
nonlocal last_notice
note_metadata_progress()
now = time.monotonic()
if done == total or now - last_notice >= .2:
last_notice = now
phase('catalog_status', f'已核对 {done}/{total} 项原生状态…')
statuses = self.status_refresher(tuple(native), Path(library), checkpoint, progress=report_progress)
if any(statuses.get(name) not in {'READY', 'PENDING'} for name in native):
raise ValueError('原生状态读取未确认,请重新读取中心库。')
context.check_active()
phase('catalog_reconcile', '正在合并目录和状态…')
records, reasons = [], {} records, reasons = [], {}
for name in names: for name in names:
context.check_active()
source = ('both' if name in native and name in directories else source = ('both' if name in native and name in directories else
'native_only' if name in native else 'directory_only') 'native_only' if name in native else 'directory_only')
reason = ('CATALOG_NOT_REGISTERED: 仅发现目录,原生目录未登记。' if name not in native else reason = ('CATALOG_NOT_REGISTERED: 仅发现目录,原生目录未登记。' if name not in native else
@@ -1435,18 +1534,99 @@ class MainWindow(QWidget):
result = LibraryReadResult(tuple(records), directory_count=len(directories), native_count=len(native), result = LibraryReadResult(tuple(records), directory_count=len(directories), native_count=len(native),
missing_project_count=sum(name in native for name in reasons), catalog_verified=True) missing_project_count=sum(name in native for name in reasons), catalog_verified=True)
return result, reasons, lease, library, False return result, reasons, lease, library, False
worker = ServiceWorker(lambda:self.native_queue.run(reconcile, context=context))
def attempt(evidence):
return self.native_queue.run(lambda: reconcile(evidence), context=context,
timeout_seconds=120, wait_for_release_seconds=CATALOG_MANAGER_WAIT_SECONDS,
waiting=lambda: phase('catalog_waiting', '等待后台会话退出或原生队列空闲,随后自动读取。'))
def scan():
from cbb_refresh_verify.native_management import NativeOperationError
from cbb_refresh_verify.owner_probe import query_owners
try:
return attempt(root)
except NativeOperationError as error:
if not error.safe_to_continue or not str(error).startswith('LIBRARY_MANAGER_BUSY:'):
raise
phase('catalog_waiting', f'{error} 等待释放后自动重试读取。')
deadline = time.monotonic() + CATALOG_MANAGER_WAIT_SECONDS
blockers = set(error.blocking_manager_pids)
while time.monotonic() < deadline:
context.check_active()
try:
owners = query_owners(('LibraryManager.exe',),
timeout_seconds=min(2, max(.1, deadline - time.monotonic())))
except (OSError, RuntimeError):
context.stop.wait(1)
continue
context.check_active()
if not owners or blockers and blockers.isdisjoint(owner['pid'] for owner in owners):
return attempt(root/'retry')
context.stop.wait(1)
context.check_active()
raise
self.status_label.setText('正在读取 Mentor 原生目录…')
worker = ServiceWorker(scan)
self._lifecycle_workers.add(worker) self._lifecycle_workers.add(worker)
def completed(payload):
if self._job_current(read_job): deliver(payload)
def failed(error): def failed(error):
if self._job_current(read_job): from cbb_refresh_verify.native_management import NativeOperationError
self.status_label.setText(f'目录已显示;原生目录未确认:{error}')
if isinstance(error, TaskHandoff) or (isinstance(error, NativeOperationError)
and not error.safe_to_continue):
self._retain_path_lease(lease)
if not self._job_current(read_job):
return
cancelled = context.stop.is_set() or isinstance(error, QueueCancelled)
detail = '已取消读取中心库。' if cancelled else f'原生目录未确认,请重新读取:{error}'
phase('catalog_cancelled' if cancelled else 'catalog_failed', detail)
self._catalog_retry = True
self._stale_table = bool(self._records_by_name) and bool(self._catalog_snapshot_time)
self.status_label.setText(detail)
def completed(payload):
if not self._job_current(read_job):
return
if context.stop.is_set():
failed(QueueCancelled('读取已取消'))
return
try:
if checkpoint is not None:
checkpoint.replace(self.data_root/'status-refresh.jsonl')
except OSError as error:
failed(error)
return
deliver(payload)
phase('catalog_done', f'已读取 {len(payload[0].records)} 项。')
worker.signals.succeeded.connect(completed) worker.signals.succeeded.connect(completed)
worker.signals.failed.connect(failed) worker.signals.failed.connect(failed)
worker.signals.finished.connect(lambda:(self._lifecycle_workers.discard(worker),self._finish_job(job))) worker.signals.finished.connect(lambda:(self._lifecycle_workers.discard(worker),self._finish_job(job)))
self.pool.start(worker) self.pool.start(worker)
def _refresh_registered_catalog(self):
if (self.busy or not self._catalog_retry or self.mentor_lmc_path is None
or self._table_library_path != self.lmc_edit.text() or self._read_counts[1] is None):
return
library, lease = self.mentor_lmc_path, self.library_lease
names = tuple(name for name, record in self._records_by_name.items()
if record.catalog_source in {'both', 'native_only'})
if not names:
self.status_label.setText('上次清单中没有已登记项。')
return
job = self._new_job('status', library=library, targets=names, lease=lease)
self.status_label.setText('正在刷新上次登记项的原生状态…')
def refreshed(statuses):
if any(statuses.get(name) not in {'READY', 'PENDING'} for name in names):
self.status_label.setText('原生状态未确认,保留上次读取结果。')
return
self._apply_refreshed_records((names, statuses, None, ''))
self.status_label.setText(f'已刷新 {len(names)} 项原生状态,目录仍待重新读取。')
self._start(lambda: self.status_refresher(names, Path(library)), refreshed, job=job)
def _execution_status_reader(self, operation_id, lease): def _execution_status_reader(self, operation_id, lease):
"""Recheck registration once per submission and status at each admission.""" """Recheck registration once per submission and status at each admission."""
catalog_reader, status_reader = self.catalog_reader, self.status_refresher catalog_reader, status_reader = self.catalog_reader, self.status_refresher
@@ -1480,10 +1660,10 @@ class MainWindow(QWidget):
return [record.name for record in self.selected_records()] return [record.name for record in self.selected_records()]
def verify_selected(self): def verify_selected(self):
self._confirm_verify(self._eligible_names(checked_only=True)) self._confirm_verify(self._eligible_names(checked_only=True, require_status=True))
def verify_all(self): def verify_all(self):
self._confirm_verify(self._eligible_names()) self._confirm_verify(self._eligible_names(require_status=True))
def _confirm_verify(self, names): def _confirm_verify(self, names):
from .backup_notice import MANUAL_BACKUP_NOTICE from .backup_notice import MANUAL_BACKUP_NOTICE
@@ -1709,7 +1889,7 @@ class MainWindow(QWidget):
if self._native_backup_same_library(): if self._native_backup_same_library():
self.status_label.setText('请先关闭该库的版本与备份窗口。') self.status_label.setText('请先关闭该库的版本与备份窗口。')
return return
eligible = set(self._maintenance_names() if maintenance else self._eligible_names()) eligible = set(self._eligible_names(require_status=True))
names = [name for name in names if name in eligible] names = [name for name in names if name in eligible]
if not names: if not names:
self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。') self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。')
@@ -1718,6 +1898,8 @@ class MainWindow(QWidget):
requests = ([request for request in request_snapshot if request.block_name in names] if request_snapshot is not None requests = ([request for request in request_snapshot if request.block_name in names] if request_snapshot is not None
else [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names]) else [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names])
if not requests: return if not requests: return
auto_confirm = self.auto_confirm_pcb_open_check.isChecked()
requests = [replace(request, auto_confirm_pcb_open=auto_confirm) for request in requests]
library = requests[0].lmc_file library = requests[0].lmc_file
if any(job.active and job.kind == 'verify' and job.requests == tuple(requests) if any(job.active and job.kind == 'verify' and job.requests == tuple(requests)
and _path_key(job.context.library) == _path_key(library) for job in self._jobs.values()): return and _path_key(job.context.library) == _path_key(library) for job in self._jobs.values()): return
@@ -1744,7 +1926,8 @@ class MainWindow(QWidget):
def action(): def action():
from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify
verify = self.verifier or (lambda req: run_verify( verify = self.verifier or (lambda req: run_verify(
req, progress=lambda e: self._emit_job(job, 'event', e), req,
progress=lambda e: self._emit_job(job, 'event', e),
flag_reader=read_library_flag_if_available, flag_reader=read_library_flag_if_available,
version_prompt=lambda choice: self._emit_job(job, 'version_choice', choice), stop=job.context.stop)) version_prompt=lambda choice: self._emit_job(job, 'version_choice', choice), stop=job.context.stop))
def verifier(req): def verifier(req):
@@ -1757,11 +1940,16 @@ class MainWindow(QWidget):
if statuses.get(req.block_name) == 'NOT_REGISTERED': if statuses.get(req.block_name) == 'NOT_REGISTERED':
from cbb_refresh_verify.verify_runner import VerifyResult from cbb_refresh_verify.verify_runner import VerifyResult
return VerifyResult('SKIPPED', stderr='仅发现目录,原生目录未登记此 CBB。') return VerifyResult('SKIPPED', stderr='仅发现目录,原生目录未登记此 CBB。')
if statuses.get(req.block_name) != 'PENDING':
from cbb_refresh_verify.verify_runner import VerifyResult
return VerifyResult('SKIPPED', error_category='STATUS_UNCONFIRMED',
error_stage='admission', stderr='STATUS_UNCONFIRMED: 当前状态未确认,未启动校验;请重新读取。')
if maintenance: if maintenance:
self._emit_job(job, 'event', {'block': req.block_name, 'stage': 'icdb_check_start'}) self._emit_job(job, 'event', {'block': req.block_name, 'stage': 'icdb_check_start'})
return verify(req) return verify(req)
results = run_batch(requests, verifier=verifier, stop=job.context.stop, context=job.context, results = run_batch(requests, verifier=verifier, stop=job.context.stop, context=job.context,
item_executor=lambda req, action: self._queued_action(action, library=req.lmc_file, job=job)(), item_executor=lambda req, action: self._queued_action(
action, library=req.lmc_file, job=job, wait_for_release=True)(),
progress=lambda name, result: self._emit_job(job, 'event', {'block': name, 'stage': result.status, progress=lambda name, result: self._emit_job(job, 'event', {'block': name, 'stage': result.status,
'error_category': result.error_category, 'evidence': str(result.evidence_path or ''), 'error_category': result.error_category, 'evidence': str(result.evidence_path or ''),
'detail': result.stderr or result.stdout})) 'detail': result.stderr or result.stdout}))
@@ -1774,16 +1962,20 @@ class MainWindow(QWidget):
write_maintenance_report(requests, results, report, ()) write_maintenance_report(requests, results, report, ())
except Exception as error: except Exception as error:
self._emit_job(job, 'event', {'stage': 'report_failed', 'detail': str(error)}) self._emit_job(job, 'event', {'stage': 'report_failed', 'detail': str(error)})
affected = [req.block_name for req, result in zip(requests, results) if result.status != 'SKIPPED'] # A proven pre-write cancel can be submitted again. The next
# admission still rereads the catalog, status and occupancy.
affected = [req.block_name for req, result in zip(requests, results)
if result.status != 'SKIPPED'
and not (result.status == 'CANCELLED' and result.cancelled_before_write)]
safe = all(result.safe_to_continue for result in results) safe = all(result.safe_to_continue for result in results)
self._emit_job(job, 'batch_ready', (results, report)) self._emit_job(job, 'batch_ready', (results, report))
refresh = None refresh = None
if safe and not job.context.stop.is_set(): if safe and affected and not job.context.stop.is_set():
from cbb_refresh_verify.operation_queue import QueueCancelled from cbb_refresh_verify.operation_queue import QueueCancelled, QueueUnavailable
try: try:
refresh = self._queued_action(lambda: self._read_affected_records(affected, library=library, lease=job.lease), refresh = self._queued_action(lambda: self._read_affected_records(affected, library=library, lease=job.lease),
label='批次已结束,状态刷新', library=library, job=job)() label='批次已结束,状态刷新', library=library, job=job)()
except QueueCancelled: except (QueueCancelled, QueueUnavailable):
pass # Cancelling the refresh must not erase completed item results. pass # Cancelling the refresh must not erase completed item results.
return results, report, affected, refresh return results, report, affected, refresh
self._start(action, self._batch_refreshed, queued=False, job=job, bounded=False) self._start(action, self._batch_refreshed, queued=False, job=job, bounded=False)
@@ -1889,13 +2081,18 @@ class MainWindow(QWidget):
from shiboken6 import isValid from shiboken6 import isValid
if not isValid(self) or not isValid(self.cbb_table): if not isValid(self) or not isValid(self.cbb_table):
return return
if event.get('stage') in {'catalog_start', 'catalog_status', 'catalog_waiting', 'catalog_reconcile'}:
catalog_job = self._jobs.get(event.get('catalog_id'))
if catalog_job is None or catalog_job.context.stop.is_set():
return
self.status_label.setText(event['detail'])
if event.get('stage') == 'waiting_native_slot': if event.get('stage') == 'waiting_native_slot':
self.status_label.setText(event.get('detail', '已排队,等待执行')) self.status_label.setText(event.get('detail', '已排队,等待执行'))
self._queue_waiting(event) self._queue_waiting(event)
elif event.get('stage') == 'native_slot_acquired': elif event.get('stage') == 'native_slot_acquired':
self.status_label.setText(event.get('detail') or '正在执行当前任务…') self.status_label.setText(event.get('detail') or '正在执行当前任务…')
self._update() self._update()
if event.get('stage') in ('session_handoff', 'save_stop_requested'): if event.get('stage') in ('session_handoff', 'save_stop_requested', 'post_save_release_pending'):
self.status_label.setText(event.get('detail', '当前状态无法确认')) self.status_label.setText(event.get('detail', '当前状态无法确认'))
if (event.get('stage') == 'session_observation' and event.get('status') == 'RELEASED' if (event.get('stage') == 'session_observation' and event.get('status') == 'RELEASED'
and event.get('release_proof')): and event.get('release_proof')):
@@ -1933,6 +2130,36 @@ class MainWindow(QWidget):
self.cbb_table.item(row, 3).setToolTip(detail) self.cbb_table.item(row, 3).setToolTip(detail)
if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line) if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line)
def _show_result_detail(self, row, column):
if column != 3:
return
item = self.cbb_table.item(row, column)
name = self.cbb_table.item(row, 0)
if item is None or name is None or not item.toolTip():
return
dialog = QDialog(self)
dialog.setAttribute(Qt.WA_DeleteOnClose)
dialog.setWindowTitle(f'{name.text()} 结果详情')
dialog.resize(660, 380)
layout = QVBoxLayout(dialog)
text = QPlainTextEdit(dialog)
text.setReadOnly(True)
text.setPlainText(item.toolTip())
text.moveCursor(QTextCursor.Start)
layout.addWidget(text)
buttons = QDialogButtonBox(QDialogButtonBox.Close, dialog)
copy = buttons.addButton('复制全文', QDialogButtonBox.ActionRole)
def copy_detail():
from PySide6.QtWidgets import QApplication
QApplication.clipboard().setText(text.toPlainText())
copy.clicked.connect(copy_detail)
buttons.rejected.connect(dialog.close)
layout.addWidget(buttons)
dialog.show()
def _mark_row_ready(self, row): def _mark_row_ready(self, row):
"""Color authoritative READY rows while retaining management selection.""" """Color authoritative READY rows while retaining management selection."""
name_item = self.cbb_table.item(row, 0) name_item = self.cbb_table.item(row, 0)
@@ -1990,12 +2217,12 @@ class MainWindow(QWidget):
if len(outcome) <= 2: if len(outcome) <= 2:
return return
results, _, affected, refresh = outcome results, _, affected, refresh = outcome
if refresh is None: if refresh is not None:
self._apply_refreshed_records(refresh)
elif affected:
reason = ('状态尚未复核,请重新读取。' if all(r.safe_to_continue for r in results) reason = ('状态尚未复核,请重新读取。' if all(r.safe_to_continue for r in results)
else '会话或数据库安全未确认;暂缓原生状态复核,请确认释放后重新读取。') else '会话或数据库安全未确认;暂缓原生状态复核,请确认释放后重新读取。')
self._defer_status_refresh(affected, reason) self._defer_status_refresh(affected, reason)
else:
self._apply_refreshed_records(refresh)
from shiboken6 import isValid from shiboken6 import isValid
summary = getattr(self, 'summary', None) summary = getattr(self, 'summary', None)
self.status_label.setText(summary.text().replace('\n', ' ') if summary is not None and isValid(summary) self.status_label.setText(summary.text().replace('\n', ' ') if summary is not None and isValid(summary)
@@ -2147,8 +2374,8 @@ class MainWindow(QWidget):
'已请求取消;检查将停止,原生写入只等待安全结束,不强制终止。'); self._update() '已请求取消;检查将停止,原生写入只等待安全结束,不强制终止。'); self._update()
def _failed(self, error): def _failed(self, error):
from cbb_refresh_verify.operation_queue import QueueCancelled from cbb_refresh_verify.operation_queue import QueueCancelled, QueueUnavailable
if self.library_lease is not None and not isinstance(error, QueueCancelled): if self.library_lease is not None and not isinstance(error, (QueueCancelled, QueueUnavailable)):
self._retain_path_lease(self.library_lease, hold_busy=True) self._retain_path_lease(self.library_lease, hold_busy=True)
self._display_error(error) self._display_error(error)
@@ -2240,6 +2467,8 @@ class MainWindow(QWidget):
self.status_label.setText('当前操作尚未结束,仍在等待安全关闭。') self.status_label.setText('当前操作尚未结束,仍在等待安全关闭。')
def _close_when_idle(self): def _close_when_idle(self):
if not isValid(self):
return
owners = [self, *self.icdb_tasks, *self._dialogs] owners = [self, *self.icdb_tasks, *self._dialogs]
for name in ('management_dialog', 'backup_dialog', 'release_dialog'): for name in ('management_dialog', 'backup_dialog', 'release_dialog'):
owners.append(getattr(self, name, None)) owners.append(getattr(self, name, None))
@@ -193,12 +193,12 @@ class ManagementDialog(QDialog):
action = lambda: self.runner(requests, adapter=self.adapter, stop=context.stop, action = lambda: self.runner(requests, adapter=self.adapter, stop=context.stop,
progress=lambda event:self._emit(context, 'progress',event),**choices) progress=lambda event:self._emit(context, 'progress',event),**choices)
if self.native_queue is None: return context.run(action) if self.native_queue is None: return context.run(action)
from ..operation_queue import QueueCancelled from ..operation_queue import QueueCancelled, QueueUnavailable
from ..session_record import library_available, library_wait_reason from ..session_record import library_available, library_wait_reason
try: try:
if self.runner is run_management_batch: if self.runner is run_management_batch:
def item(request, action): def item(request, action):
return self.native_queue.run(action, stop=context.stop, context=context, return self.native_queue.run(action, stop=context.stop, context=context, skip_unavailable=True,
wait_state=lambda: library_wait_reason(request.library), wait_state=lambda: library_wait_reason(request.library),
waiting=lambda: self._emit(context, 'progress',{'stage': 'waiting_native_slot', waiting=lambda: self._emit(context, 'progress',{'stage': 'waiting_native_slot',
'retained': not library_available(request.library), 'retained': not library_available(request.library),
@@ -206,11 +206,15 @@ class ManagementDialog(QDialog):
return self.runner(requests, adapter=self.adapter, stop=context.stop, return self.runner(requests, adapter=self.adapter, stop=context.stop,
progress=lambda event:self._emit(context, 'progress',event), item_executor=item, progress=lambda event:self._emit(context, 'progress',event), item_executor=item,
version_prompt=lambda choice:self._emit(context, 'choice',choice), context=context) version_prompt=lambda choice:self._emit(context, 'choice',choice), context=context)
return self.native_queue.run(action, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress', return self.native_queue.run(action, stop=context.stop, context=context, skip_unavailable=True, waiting=lambda: self._emit(context, 'progress',
{'stage': 'waiting_native_slot', {'stage': 'waiting_native_slot',
'retained': not library_available(self.template.library), 'retained': not library_available(self.template.library),
'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}), 'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}),
wait_state=lambda: library_wait_reason(self.template.library)) wait_state=lambda: library_wait_reason(self.template.library))
except QueueUnavailable as error:
from ..management import ManagementResult
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
'admission', 'SKIPPED', True, str(error)) for r in requests]
except QueueCancelled as error: except QueueCancelled as error:
from ..operation_queue import TaskHandoff from ..operation_queue import TaskHandoff
from ..management import ManagementResult from ..management import ManagementResult
+7 -5
View File
@@ -8,17 +8,19 @@ class PcbOpenDialog(QMessageBox):
self.choice = choice self.choice = choice
self.setWindowTitle('确认打开 PCB 工程') self.setWindowTitle('确认打开 PCB 工程')
self.setIcon(QMessageBox.Question) self.setIcon(QMessageBox.Question)
advice = ('程序将检查工程和共享库占用,再决定是否继续。' if choice.auto_confirm else
'请确认没有其他用户打开此工程,再选择继续以读写权限打开。')
self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n' self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n'
'PCB 提示上次可能未正常关闭,或工程仍被其他用户打开。\n' 'PCB 提示上次可能未正常关闭,或工程仍被其他用户打开。\n'
'请确认没有其他用户打开此工程,再选择继续以读写权限打开。') + advice)
self.continue_button = self.addButton('确认无人使用,继续打开', QMessageBox.ActionRole) self.continue_button = self.addButton(
'检查占用后继续' if choice.auto_confirm else '确认无人使用,继续打开', QMessageBox.ActionRole)
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole) self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole) self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
self.setDefaultButton(self.skip_button)
self.setEscapeButton(self.cancel_button) self.setEscapeButton(self.cancel_button)
self.setModal(True) self.setModal(True)
self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else
'skip' if b is self.skip_button else 'cancel', 'skip' if b is self.skip_button else 'cancel',
origin=self.property('selectionOrigin') or 'user')) origin=self.property('selectionOrigin') or 'user'))
self.finished.connect(lambda _: choice.choose('cancel')) self.finished.connect(lambda _: choice.choose('cancel'))
arm_default(self, self.skip_button) arm_default(self, self.continue_button if choice.auto_confirm else self.skip_button)
@@ -4,7 +4,7 @@ from threading import Event
from PySide6.QtCore import QThreadPool, Signal, Qt from PySide6.QtCore import QThreadPool, Signal, Qt
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton, from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox) QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QToolButton)
from .workers import ServiceWorker from .workers import ServiceWorker
from .timed_prompt import arm_default from .timed_prompt import arm_default
@@ -36,8 +36,15 @@ class ResidualReleaseDialog(QDialog):
self.message = QLabel('正在检查当前库关联的会话…') self.message = QLabel('正在检查当前库关联的会话…')
self.message.setWordWrap(True) self.message.setWordWrap(True)
layout.addWidget(self.message) layout.addWidget(self.message)
self.runtime_toggle = QToolButton()
self.runtime_toggle.setCheckable(True)
self.runtime_toggle.hide()
layout.addWidget(self.runtime_toggle)
self.runtime_label = QLabel() self.runtime_label = QLabel()
self.runtime_label.setWordWrap(True) self.runtime_label.setWordWrap(True)
self.runtime_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
self.runtime_label.hide()
self.runtime_toggle.toggled.connect(self.runtime_label.setVisible)
layout.addWidget(self.runtime_label) layout.addWidget(self.runtime_label)
self.table = QTableWidget(0, 8) self.table = QTableWidget(0, 8)
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径', '确认范围', '执行结果']) self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径', '确认范围', '执行结果'])
@@ -58,7 +65,7 @@ class ResidualReleaseDialog(QDialog):
for button in (self.refresh_button, self.confirm_button, self.details_button, self.prompt_button, for button in (self.refresh_button, self.confirm_button, self.details_button, self.prompt_button,
self.cancel_native_button, self.force_button, self.close_button): buttons.addWidget(button) self.cancel_native_button, self.force_button, self.close_button): buttons.addWidget(button)
layout.addLayout(buttons) layout.addLayout(buttons)
self.refresh_button.clicked.connect(self.refresh) self.refresh_button.clicked.connect(lambda: self.refresh(reconcile=True))
self.confirm_button.clicked.connect(self.confirm_release) self.confirm_button.clicked.connect(self.confirm_release)
self.close_button.clicked.connect(self.close) self.close_button.clicked.connect(self.close)
self.prompt_button.clicked.connect(self.answer_prompt) self.prompt_button.clicked.connect(self.answer_prompt)
@@ -207,7 +214,7 @@ class ResidualReleaseDialog(QDialog):
self._start(lambda: answer_save_question(session, code), self._start(lambda: answer_save_question(session, code),
lambda _: setattr(self, '_refresh_after', True)) lambda _: setattr(self, '_refresh_after', True))
def refresh(self): def refresh(self, *, reconcile=False):
if self.busy: return if self.busy: return
from cbb_refresh_verify.library_lock import inspect_residual_sessions from cbb_refresh_verify.library_lock import inspect_residual_sessions
self.plan = None self.plan = None
@@ -226,19 +233,51 @@ class ResidualReleaseDialog(QDialog):
text += '确认后将复查库占用状态。' text += '确认后将复查库占用状态。'
self.message.setText(text) self.message.setText(text)
states = {'ACTIVE': '进行中', 'UNCONFIRMED': '待核对', 'IDENTITY_CHANGED': '待核对'} states = {'ACTIVE': '进行中', 'UNCONFIRMED': '待核对', 'IDENTITY_CHANGED': '待核对'}
self.runtime_label.setText('\n'.join( history = plan.get('runtime_sessions', [])
f'{states.get(row["status"], "待核对")} · {row.get("block") or "当前库"} · ' lines = []
f'{row.get("detail") or "操作状态需重新核对"}' for row in plan.get('runtime_sessions', []))) for row in history:
pids = ', '.join(str(p['pid']) for p in row.get('processes', []) if 'pid' in p)
scope = row.get('resource_scope') or {}
resources = row.get('blocked_resources') or scope.get('shared_dependencies') or ()
detail = row.get('detail') or '操作状态需重新核对'
operation = {'catalog': '读取中心库', 'verify': '校验', 'repair': 'ICDB 维护'}.get(
row.get('operation'), row.get('operation') or '原生操作')
identity = ' · '.join(filter(None, (operation, row.get('recorded_at'),
f'PID {pids}' if pids else row.get('operation_id'))))
lines.append(f'{states.get(row["status"], "待核对")} · {row.get("block") or "当前库"} · {identity}\n'
+ ' · '.join((detail, *map(str, resources))))
self.runtime_label.setText('\n\n'.join(lines))
self.runtime_toggle.setText(f'会话记录({len(history)})')
self.runtime_toggle.setVisible(bool(history))
self.runtime_label.setVisible(bool(history) and self.runtime_toggle.isChecked())
def inspect(): def inspect():
from cbb_refresh_verify.network_path import select_library_file from cbb_refresh_verify.network_path import select_library_file
from cbb_refresh_verify.session_record import discover_sessions, retained_session_states from cbb_refresh_verify.session_record import (
discover_sessions, reconcile_session_record, record_session_release, retained_session_states)
library = self.library if self.library.suffix.casefold() == '.lmc' else select_library_file(self.library) library = self.library if self.library.suffix.casefold() == '.lmc' else select_library_file(self.library)
plan = inspect_residual_sessions(library) plan = inspect_residual_sessions(library)
states = {row['path']: row for row in retained_session_states(library)} evidence_root = self.evidence_dir.parent
states.update({str(Path(row['path']).absolute()).casefold(): row for row in cached = {row.get('operation_id') or row['path']: row for row in retained_session_states(library)}
discover_sessions(self.evidence_dir.parent, library=library)}) discovered = {row.get('operation_id') or row['path']: row for row in
return {**plan, 'runtime_sessions': list(states.values())} discover_sessions(evidence_root, library=library)}
self._start(inspect, ready, metadata_only=True) for key, row in discovered.items():
cached[key] = row
if reconcile:
for key, row in discovered.items():
if row.get('processes_exited') is not True:
continue
result = reconcile_session_record(row['path'], evidence_root=evidence_root, stop=self.stop)
if result['status'] == 'RELEASED' and result.get('release_proof'):
receipts = record_session_release(result['release_proof'], [row])
if not receipts:
cached.pop(key, None)
else:
cached[key] = {**row, 'detail': '\n'.join(receipts)}
else:
cached[key] = {**row, **result}
return {**plan, 'runtime_sessions': list(cached.values())}
self._start(inspect, ready, metadata_only=not reconcile)
def force_release(self): def force_release(self):
if self.busy or not self.plan or not self.plan['sessions']: return if self.busy or not self.plan or not self.plan['sessions']: return
+173 -16
View File
@@ -83,6 +83,9 @@ class VerifyRequest:
maintenance: bool = False maintenance: bool = False
post_repair_proof: object | None = field(default=None, repr=False, compare=False) post_repair_proof: object | None = field(default=None, repr=False, compare=False)
diagnostic_only: bool = False diagnostic_only: bool = False
# Explicit True/False selects ordinary Verify's complete access proof.
# None preserves the manual confirmation policy for other callers.
auto_confirm_pcb_open: bool | None = None
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -105,6 +108,7 @@ class VerifyResult:
release_proof: dict | None = None release_proof: dict | None = None
write_outcome: dict | None = None write_outcome: dict | None = None
session_record_path: Path | None = None session_record_path: Path | None = None
cancelled_before_write: bool = False
def resolve_importer(mentor_bin: str | None = None) -> Path: def resolve_importer(mentor_bin: str | None = None) -> Path:
@@ -657,7 +661,7 @@ def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner
Path(request.evidence_dir)/'previous-release', block_name=request.block_name, Path(request.evidence_dir)/'previous-release', block_name=request.block_name,
progress=progress, stop=stop) progress=progress, stop=stop)
check_active() check_active()
library_lock = LibraryLock(request.lmc_file, checkpoint=False, library_lock = LibraryLock(request.lmc_file, checkpoint=False, block_name=request.block_name,
safe_to_release=clients_released) safe_to_release=clients_released)
library_lock.__enter__() library_lock.__enter__()
check_active() check_active()
@@ -670,6 +674,72 @@ def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner
request, progress=progress, flag_reader=flag_reader, request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check, process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop) dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
local_retry = None
if (library_lock is not None and result.error_category == 'MENTOR_LOCAL_CELL_LIBRARY'
and not request.diagnostic_only and not request.auto_repair and not request.native_lm_verify
and not request.interactive_input and request.post_repair_proof is None):
from .local_cell_library import preserve_failed_cache
release_confirmed = result.safe_to_continue
local_retry = preserve_failed_cache(request, result, stop=stop)
if local_retry is not None:
initial_seconds = result.timings_seconds.get('total', 0.0)
original_evidence = result.evidence_path
_notify_progress(progress, {'stage': 'local_cell_library_retry', 'block': request.block_name,
'detail': '已保留旧本地 Cell Library,重新打开一次让 Mentor 重建。'})
check_active()
release_confirmed = False
result = _run_verify_serialized(request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
local_retry.update(status='REBUILT_AND_VERIFIED' if result.status == 'PASS' else 'REVERIFY_FAILED',
retry_evidence=str(result.evidence_path or ''))
_write_optional_evidence(original_evidence.with_name('local-cell-library-retry.json'), local_retry)
retry_seconds = result.timings_seconds.get('total', 0.0)
result = replace(result, recovery_attempts=(*result.recovery_attempts, local_retry),
timings_seconds={**result.timings_seconds, 'initial_verify': initial_seconds,
'local_cell_library_retry': retry_seconds, 'total': initial_seconds + retry_seconds})
if result.evidence_path:
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
facts = result.write_outcome or {}
if (local_retry is None and not request.diagnostic_only and not request.auto_repair and request.post_repair_proof is None
and result.status == 'FAIL' and result.safe_to_continue and result.evidence_path
and result.library_flag == 'NOT_GREEN' and result.error_stage == 'library_flag'
and result.error_category == 'MENTOR_VERIFY_NOT_COMMITTED'
and all(facts.get(key) == value for key, value in (
('save_state','COMMITTED'), ('close_state','CLOSED'), ('helper_state','EXITED'),
('resource_state','RELEASED'), ('interrupted',False)))
and not (stop is not None and stop.is_set())):
# A new reusable design can save its Work data on the first open,
# then publish Cert on the next native Save. Never retry an open/write failure.
followup_path = result.evidence_path.with_name('commit-followup.json')
followup = dict(kind='NATIVE_COMMIT_FOLLOWUP', status='STARTED',
library=str(request.lmc_file), block=request.block_name, max_additional_runs=1,
original_evidence=str(result.evidence_path))
initial_seconds = result.timings_seconds.get('total', 0.0)
release_confirmed = True # Completed first run stays releasable until the next native attempt.
try:
followup_path.write_text(json.dumps(followup, ensure_ascii=False, indent=2), encoding='utf-8')
except OSError as error:
_notify_progress(progress, {'stage':'commit_followup_unavailable', 'block':request.block_name,
'detail':str(error)})
else:
check_active()
_notify_progress(progress, {'stage':'commit_followup', 'block':request.block_name,
'detail':'原生已保存关闭并释放,但 READY 尚未提交;补充一次原生校验。'})
check_active()
release_confirmed = False
result = _run_verify_serialized(request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
followup.update(status='READY' if result.status == 'PASS' and result.library_flag == 'GREEN'
and result.safe_to_continue else 'UNCONFIRMED', final_evidence=str(result.evidence_path or ''))
_write_optional_evidence(followup_path, followup)
second_seconds = result.timings_seconds.get('total', 0.0)
result = replace(result, recovery_attempts=(*result.recovery_attempts, followup),
timings_seconds={**result.timings_seconds, 'initial_verify':initial_seconds,
'commit_followup':second_seconds, 'total':initial_seconds+second_seconds})
if result.evidence_path:
_write_optional_evidence(result.evidence_path, {'block_name':request.block_name, **asdict(result)})
if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'} if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'}
and result.error_category == 'ICDB_REPAIR_REQUIRED' and result.error_category == 'ICDB_REPAIR_REQUIRED'
and result.evidence_path): and result.evidence_path):
@@ -1084,8 +1154,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .failed_session import cancelled_prewrite_startup from .failed_session import cancelled_prewrite_startup
_stop_worker(process, wait_for_native_write=False if request.diagnostic_only else _stop_worker(process, wait_for_native_write=False if request.diagnostic_only else
lambda:cancelled_prewrite_startup(job,target_pid) is None) lambda:cancelled_prewrite_startup(job,target_pid) is None)
prewrite = cancelled_prewrite_startup(job, target_pid) is not None
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。', return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
safe_to_continue=False, error_stage=phase.value)) safe_to_continue=False, error_stage=phase.value,
cancelled_before_write=prewrite))
if events.exists(): if events.exists():
with events.open(encoding='utf-8') as stream: with events.open(encoding='utf-8') as stream:
stream.seek(offset) stream.seek(offset)
@@ -1165,14 +1237,18 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
diagnostic_closing = True diagnostic_closing = True
from .dialog_supervisor import DialogPollResult from .dialog_supervisor import DialogPollResult
dialog_result = DialogPollResult(activity=False) dialog_result = DialogPollResult(activity=False)
if (version_prompt is not None and consent is None and dialog_agent is not None if ((version_prompt is not None or request.auto_confirm_pcb_open)
and consent is None and dialog_agent is not None
and not request.diagnostic_only and not request.native_lm_verify and not request.diagnostic_only and not request.native_lm_verify
and not request.maintenance and not request.interactive_input
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED' and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
and dialog_result.snapshot is not None): and dialog_result.snapshot is not None):
from .pcb_open_consent import OpenController, exact_prompt from .pcb_open_consent import OpenController, exact_prompt
if exact_prompt(dialog_result.snapshot): if exact_prompt(dialog_result.snapshot):
if open_controller is None: if open_controller is None:
open_controller = OpenController(job) open_controller = OpenController(
job, auto_confirm=request.auto_confirm_pcb_open is True,
require_complete_proof=request.auto_confirm_pcb_open is not None)
dialog_result = open_controller.handle(dialog_result.snapshot, dialog_result.observed_snapshots, dialog_result = open_controller.handle(dialog_result.snapshot, dialog_result.observed_snapshots,
target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid, target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid,
show=version_prompt, perform=dialog_supervisor.backend.perform) show=version_prompt, perform=dialog_supervisor.backend.perform)
@@ -1230,6 +1306,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'CANCELLED' if dialog_result.error_code == 'USER_CANCELLED' else 'CANCELLED' if dialog_result.error_code == 'USER_CANCELLED' else
'SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else 'FAIL', 'SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else 'FAIL',
stderr=f'{dialog_result.error_code}: {dialog_result.detail}', stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
error_category='PCB_OPEN_SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else '',
error_stage=phase.value, error_stage=phase.value,
safe_to_continue=False, safe_to_continue=False,
)) ))
@@ -1364,6 +1441,34 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
release_result = {**(release_result or {}), 'icdb_addresses': addresses} release_result = {**(release_result or {}), 'icdb_addresses': addresses}
except OSError as error: except OSError as error:
close_errors.append(str(error)) close_errors.append(str(error))
try:
save_lines = (root/'save.log').read_text('utf-8', errors='replace').splitlines()
except FileNotFoundError:
save_lines = []
except OSError as error:
save_lines = []
close_errors.append(str(error))
if (worker_exited and automation_release.get('safe_to_continue') and not close_errors
and release_result.get('safe_to_continue') and not request.diagnostic_only
and {'SAVE_START', 'SAVE_OK', 'IS_SAVED', 'CLOSE_OK'}.issubset(save_lines)):
from .icdb_ownership import wait_for_saved_database_release
from .operation_queue import allow_other_libraries, task_stop
timing.begin('database_release')
try:
with allow_other_libraries():
database_release = wait_for_saved_database_release(
request.lmc_file, project, pcb, stop=task_stop(stop),
report_pending=lambda **event: _notify_progress(progress, {
'stage': 'post_save_release_pending', 'block': request.block_name,
'detail': '已保存,等待 iCDB 释放数据库', **event}))
except Exception as error:
database_release = {'status': 'UNCONFIRMED', 'detail': str(error),
'blocked_resources': []}
finally:
timing.end('database_release')
release_result = {**release_result, 'database_release': database_release,
'blocked_resources': database_release['blocked_resources'],
'safe_to_continue': database_release['status'] == 'RELEASE_CONFIRMED'}
if close_errors: if close_errors:
release_result = {**(release_result or {}), 'safe_to_continue': False, release_result = {**(release_result or {}), 'safe_to_continue': False,
'close_errors': close_errors} 'close_errors': close_errors}
@@ -1393,12 +1498,24 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'close_errors': [*close_errors, str(error)]} 'close_errors': [*close_errors, str(error)]}
try: try:
from .operation_lifecycle import classify_save_state from .operation_lifecycle import classify_save_state
save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines() facts = classify_save_state(save_lines,
if (root/'save.log').is_file() else [])
_write_optional_evidence(root/'write-outcome.json', classify_save_state(save_lines,
helper_exited=(False if automation_release.get('remaining_pids') else helper_exited=(False if automation_release.get('remaining_pids') else
True if worker_exited and automation_release.get('safe_to_continue') else None), True if worker_exited and automation_release.get('safe_to_continue') else None),
native_released=release_result.get('safe_to_continue') is True)) native_released=release_result.get('safe_to_continue') is True)
if 'SAVE_START' in save_lines and getattr(process, 'session_record_path', None):
from .session_record import read_session_record
try:
state = read_session_record(root/'worker-state.json', evidence_root=root)
except (OSError, ValueError):
state = {}
receipt = state.get('write_outcome')
confirmed = (state.get('operation_id') == job['operation_id']
and isinstance(receipt, dict) and receipt.get('save_close_confirmed') is True)
facts['save_close_confirmed'] = confirmed
if facts['helper_state'] == 'EXITED' and not confirmed:
facts['interrupted'] = True
facts['detail'] = '缺少保存助手正常退出的完整记录'
_write_optional_evidence(root/'write-outcome.json', facts)
(root/'session-release.json').write_text(json.dumps({ (root/'session-release.json').write_text(json.dumps({
**(release_result or {}), 'block': request.block_name, **(release_result or {}), 'block': request.block_name,
'library': str(request.lmc_file), 'worker_exited': worker_exited, 'library': str(request.lmc_file), 'worker_exited': worker_exited,
@@ -1413,8 +1530,17 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
pass pass
if not release_result or not release_result.get('safe_to_continue'): if not release_result or not release_result.get('safe_to_continue'):
if 'result' in locals(): if 'result' in locals():
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status, safe_to_continue=False, database_release = (release_result or {}).get('database_release')
stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip()) if database_release and database_release['status'] != 'RELEASE_CONFIRMED':
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status,
safe_to_continue=False, error_category='ICDB_RELEASE_PENDING', error_stage='release_check',
release_proof=database_release,
stderr=(result.stderr + '\nICDB_RELEASE_PENDING: 已保存,数据库释放未确认。'
+ database_release['detail']).strip())
else:
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status,
safe_to_continue=False,
stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip())
recovery = {'desktop': job['desktop'], 'project': str(project), recovery = {'desktop': job['desktop'], 'project': str(project),
'pcb': str(pcb), 'release': release_result, 'pcb': str(pcb), 'release': release_result,
'action': '停止批次;检查原生会话及数据库;不要删除锁文件或自动恢复。'} 'action': '停止批次;检查原生会话及数据库;不要删除锁文件或自动恢复。'}
@@ -1465,7 +1591,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None, def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None,
context=None): context=None):
"""Run serially and stop when database/session safety is unconfirmed.""" """Run serially; isolate failures and skip writes to resources still retained."""
if max_workers != 1: if max_workers != 1:
raise ValueError('Only serial Verify is supported for the shared Library Manager session') raise ValueError('Only serial Verify is supported for the shared Library Manager session')
if context is not None: if context is not None:
@@ -1476,15 +1602,40 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
stop=stop, context=context) # noqa: E731 stop=stop, context=context) # noqa: E731
results = [] results = []
queue_stop = False queue_stop = False
retained_libraries = set() retained_libraries = {}
timed_out_admissions = {}
for request in requests: for request in requests:
from .operation_queue import request_library_keys from .operation_queue import request_library_keys
library_keys = request_library_keys(request, context) library_keys = request_library_keys(request, context)
for index in {retained_libraries[key][1] for key in library_keys.intersection(retained_libraries)}:
previous = next(value[0] for value in retained_libraries.values() if value[1] == index)
if queue_stop or stop is not None and stop.is_set():
break
if not results[index].evidence_path:
continue
from .operation_lifecycle import recheck_failed_release
refreshed = recheck_failed_release(previous.lmc_file, previous.block_name, results[index], stop=stop)
if refreshed.safe_to_continue:
results[index] = refreshed
retained_libraries = {k:v for k,v in retained_libraries.items() if v[1] != index}
cached_timeout = None
if library_keys.intersection(timed_out_admissions):
from .session_record import library_available
for key in library_keys.intersection(timed_out_admissions):
blocked_library, previous_result = timed_out_admissions[key]
if not library_available(blocked_library, live_only=True):
cached_timeout = previous_result
break
del timed_out_admissions[key]
if (queue_stop or stop is not None and stop.is_set() if (queue_stop or stop is not None and stop.is_set()
or context is not None and context.stop.is_set()): or context is not None and context.stop.is_set()):
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB') result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
elif library_keys.intersection(retained_libraries): elif library_keys.intersection(retained_libraries):
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入') previous, index = retained_libraries[next(iter(library_keys.intersection(retained_libraries)))]
result = VerifyResult('SKIPPED', error_category='PREVIOUS_SESSION_UNRELEASED',
error_stage='admission', stderr=f'前项 {getattr(previous, "block_name", previous)} 的同库会话尚未释放,当前项未启动。')
elif cached_timeout is not None:
result = cached_timeout
else: else:
try: try:
def execute(): def execute():
@@ -1495,15 +1646,21 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
return result return result
result = item_executor(request, execute) if item_executor is not None else execute() result = item_executor(request, execute) if item_executor is not None else execute()
except Exception as error: except Exception as error:
from .operation_queue import QueueCancelled, TaskHandoff from .operation_queue import QueueCancelled, QueueUnavailable, TaskHandoff
# An unexpected exception cannot establish database safety. # An unexpected exception cannot establish database safety.
result = (_handoff_verify_result(error) if isinstance(error, TaskHandoff) else result = (VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
error_stage='admission', evidence_path=next(
(Path(row['path']) for row in error.sessions if row.get('path')), None))
if isinstance(error, QueueUnavailable) else
_handoff_verify_result(error) if isinstance(error, TaskHandoff) else
VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL', VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled))) stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled)))
if isinstance(error, QueueUnavailable) and error.timed_out:
timed_out_admissions.update(dict.fromkeys(library_keys, (error.library, result)))
results.append(result) results.append(result)
# Never start another writer after an unconfirmed native shutdown. # Never start another writer after an unconfirmed native shutdown.
if not result.safe_to_continue: if not result.safe_to_continue:
retained_libraries.update(library_keys) retained_libraries.update({key:(request, len(results)-1) for key in library_keys})
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'} queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'}
if queue_stop and stop is not None: if queue_stop and stop is not None:
stop.set() stop.set()
+118
View File
@@ -0,0 +1,118 @@
"""Verify the Windows desktop and CLI input paths in a candidate package."""
from contextlib import contextmanager
import json
import locale
from pathlib import Path
import subprocess
import sys
import time
from uuid import uuid4
import ntsecuritycon
import pywintypes
import win32api
import win32con
import win32gui
import win32process
import win32security
@contextmanager
def deny_access(path, rights):
dacl_info = win32security.DACL_SECURITY_INFORMATION
original = win32security.GetFileSecurity(str(path), dacl_info)
sid, _, _ = win32security.LookupAccountName(None, win32api.GetUserName())
acl = win32security.ACL()
acl.AddAccessDeniedAce(win32security.ACL_REVISION, rights, sid)
acl.AddAccessAllowedAce(win32security.ACL_REVISION, win32con.GENERIC_ALL, sid)
restricted = win32security.SECURITY_DESCRIPTOR()
restricted.SetSecurityDescriptorDacl(True, acl, False)
win32security.SetFileSecurity(str(path), dacl_info, restricted)
try:
yield
finally:
win32security.SetFileSecurity(str(path), dacl_info, original)
def cli(exe, library, data_root, expected):
result = subprocess.run(
[str(exe), '--batch-lmc', str(library), '--block', 'Fixture', '--data-root', str(data_root)],
capture_output=True, timeout=15, creationflags=subprocess.CREATE_NO_WINDOW,
)
try:
detail = result.stderr.decode('utf-8')
except UnicodeDecodeError:
detail = result.stderr.decode(locale.getencoding())
assert result.returncode == 1 and expected in detail, (result.returncode, detail)
assert 'Traceback' not in detail and not (data_root / 'reports').exists()
return {'exit_code': result.returncode, 'message': detail.strip()}
def startup_dialog(exe, data_root):
from cbb_refresh_verify.desktop_worker import DesktopWorker
worker = DesktopWorker([str(exe), '--data-root', str(data_root)], 'CbbInputSmoke_' + uuid4().hex[:8])
try:
deadline = time.monotonic() + 15
while worker.poll() is None and time.monotonic() < deadline:
try:
windows = worker.desktop.EnumDesktopWindows()
except pywintypes.error as error:
if error.winerror != 0:
raise
windows = ()
for hwnd in windows:
if win32process.GetWindowThreadProcessId(hwnd)[1] != worker.pid or not win32gui.IsWindowVisible(hwnd):
continue
title = win32gui.GetWindowText(hwnd)
assert title == 'CBB 刷新校验启动失败', title
if win32gui.GetClassName(hwnd) != '#32770':
continue
children = []
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child) or True, None)
button = next((child for child in children if win32gui.GetClassName(child) == 'Button'), None)
if button is None:
continue
texts = [win32gui.GetWindowText(child) for child in children]
message = next((text for text in texts if 'DATA_ROOT_UNWRITABLE' in text), '')
assert str(data_root) in message and '无法写入数据目录' in message, texts
win32gui.PostMessage(button, win32con.BM_CLICK, 0, 0)
code = worker.wait(5)
assert code == 1
return {'exit_code': code, 'title': title, 'message': message}
time.sleep(0.1)
raise AssertionError(f'Startup dialog did not appear, exit={worker.poll()}')
finally:
if worker.poll() is None:
win32process.TerminateProcess(worker.handle, 1)
worker.wait(5)
worker.close()
def main():
workspace, executable, evidence_dir = (Path(arg).resolve() for arg in sys.argv[1:])
sys.path.insert(0, str(workspace / 'src'))
evidence_dir.mkdir(parents=True, exist_ok=False)
assert (executable.parent / '使用说明.txt').read_bytes() == (workspace / 'packaging' / '使用说明.txt').read_bytes()
empty_library = evidence_dir / 'empty.lmc'
empty_library.touch()
unreadable_library = evidence_dir / 'unreadable.lmc'
unreadable_library.write_bytes(b'fixture')
data_root = evidence_dir / 'data'
data_root.mkdir()
blocked_root = evidence_dir / 'readonly'
blocked_root.mkdir()
results = {'guide': 'matched', 'empty_lmc': cli(executable, empty_library, data_root, 'INPUT_EMPTY')}
with deny_access(unreadable_library, ntsecuritycon.FILE_READ_DATA):
results['unreadable_lmc'] = cli(executable, unreadable_library, data_root, 'INPUT_PERMISSION')
with deny_access(blocked_root, ntsecuritycon.FILE_ADD_FILE | ntsecuritycon.FILE_ADD_SUBDIRECTORY):
results['cli_data_root'] = cli(executable, empty_library, blocked_root, 'DATA_ROOT_UNWRITABLE')
results['gui_data_root'] = startup_dialog(executable, blocked_root)
summary = json.dumps(results, ensure_ascii=False, indent=2)
(evidence_dir / 'result.json').write_text(summary + '\n', encoding='utf-8')
print(summary)
if __name__ == '__main__':
main()
+37
View File
@@ -110,3 +110,40 @@ def test_supervisor_crash_preserves_registered_save_caller_and_native(tmp_path):
if win32process.GetExitCodeProcess(handle) == 259: if win32process.GetExitCodeProcess(handle) == 259:
win32process.TerminateProcess(handle, 0) win32process.TerminateProcess(handle, 0)
handle.Close() handle.Close()
def test_registered_save_records_completion_after_supervisor_loss(tmp_path, monkeypatch):
from threading import Event
from cbb_refresh_verify import desktop_worker, session_record
root = tmp_path
state_path = root/'worker-state.json'
job = {'root': str(root), 'block_name': 'CBB', 'operation_id': 'save-orphan',
'session_record_path': str(root/'session.json')}
request = root/'request.json'
request.write_text(json.dumps(job), encoding='utf-8')
lost = Event()
monkeypatch.setattr(desktop_worker, '_supervisor_lost', lost)
monkeypatch.setattr(desktop_worker, '_native_phases', {})
def execute(job, emit):
emit(stage='save_start')
emit(stage='save_helper', helper_pid=987)
lost.set()
emit(stage='save_progress', markers=['SAVE_START', 'SAVE_OK', 'CLOSE_START'],
helper_exited=False)
state = session_record.read_session_record(state_path, evidence_root=root)
assert state['phase'] == 'NATIVE_CALL'
emit(stage='save_progress', markers=['SAVE_START', *FULL_SAVE.splitlines()],
helper_exited=True, helper_exit_code=0)
with pytest.raises(RuntimeError, match='WORKER_CANCELLED'):
emit(stage='integration_action')
return {'status': 'FAIL', 'stderr': 'supervisor interrupted'}
monkeypatch.setattr(adapter, 'execute_job', execute)
assert adapter.worker_main(request) == 1
state = session_record.read_session_record(state_path, evidence_root=root)
assert state['phase'] == 'POSTCALL'
facts = state['write_outcome']
assert facts['save_close_confirmed'] is True
assert (facts['save_state'], facts['close_state'], facts['helper_state']) == (
'COMMITTED', 'CLOSED', 'EXITED')
+183 -98
View File
@@ -1,99 +1,184 @@
from pathlib import Path from pathlib import Path
import pytest
def test_cli_signal_requests_cooperative_batch_stop(tmp_path, monkeypatch):
import signal
from cbb_refresh_verify import application, verify_runner @pytest.mark.parametrize('filename, contents, code', [
library = tmp_path/'center.lmc' ('empty.lmc', b'', 'INPUT_EMPTY'),
library.touch() ('missing.lmc', None, 'INPUT_MISSING'),
old = signal.getsignal(signal.SIGINT) ('library.txt', b'library', 'INPUT_SUFFIX'),
def run(requests, *, stop): ])
signal.getsignal(signal.SIGINT)(signal.SIGINT, None) def test_explicit_cli_block_validates_lmc_before_dispatch(tmp_path, monkeypatch, capsys, filename, contents, code):
assert stop.is_set() from cbb_refresh_verify import application, verify_runner
return [verify_runner.VerifyResult('CANCELLED')]
monkeypatch.setattr(verify_runner, 'run_batch', run) path = tmp_path / filename
assert application.main(['--batch-lmc', str(library), '--block', 'A', if contents is not None:
'--data-root', str(tmp_path/'data')]) == 2 path.write_bytes(contents)
assert signal.getsignal(signal.SIGINT) is old monkeypatch.setattr(verify_runner, 'run_batch', lambda *a, **kw: pytest.fail('invalid input dispatched'))
assert application.main(['--batch-lmc', str(path), '--block', 'A',
def test_smoke_arguments_exit_zero_and_write_lifecycle_log(tmp_path: Path): '--data-root', str(tmp_path / 'data')]) == 1
import subprocess, sys assert code in capsys.readouterr().err
result = subprocess.run([sys.executable, '-m', 'cbb_refresh_verify', '--smoke-test', '--data-root', str(tmp_path)], timeout=30)
assert result.returncode == 0
text = (tmp_path / "logs" / "application.log").read_text(encoding="utf-8") def test_explicit_cli_block_reports_unreadable_lmc(tmp_path, monkeypatch, capsys):
assert "application_start" in text from cbb_refresh_verify import application, verify_runner
assert "application_clean_shutdown" in text
assert "gui_smoke_window_created" in text path = tmp_path / 'library.lmc'
path.write_bytes(b'library')
original_open = Path.open
def test_module_entrypoint_propagates_main_exit_code():
import subprocess, sys def open_path(candidate, *args, **kwargs):
code = ( if candidate == path:
"import cbb_refresh_verify.application as a; a.main=lambda: 7; " raise PermissionError('denied')
"import runpy; runpy.run_module('cbb_refresh_verify.__main__', run_name='__main__')" return original_open(candidate, *args, **kwargs)
)
result = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True) monkeypatch.setattr(Path, 'open', open_path)
assert result.returncode == 7 monkeypatch.setattr(verify_runner, 'run_batch', lambda *a, **kw: pytest.fail('unreadable input dispatched'))
assert application.main(['--batch-lmc', str(path), '--block', 'A',
'--data-root', str(tmp_path / 'data')]) == 1
def test_batch_cli_acquires_unc_lease_before_directory_scan(tmp_path, monkeypatch): assert 'INPUT_PERMISSION' in capsys.readouterr().err
import cbb_refresh_verify.application as application
import cbb_refresh_verify.library_reader as library_reader
import cbb_refresh_verify.network_path as network_path def test_cli_unwritable_data_root_returns_input_exit_code(tmp_path, capsys):
from cbb_refresh_verify import application
events = []
path = tmp_path / 'data'
class Lease: path.touch()
display_path = r'\\server\share\library' assert application.main(['--batch-lmc', str(tmp_path / 'library.lmc'), '--data-root', str(path)]) == 1
mentor_path = tmp_path error = capsys.readouterr().err
drive = 'Z:' assert 'DATA_ROOT_UNWRITABLE' in error and str(path) in error
remote_root = r'\\server\share' assert 'Traceback' not in error
created = True
def __enter__(self):
events.append('enter') def test_windowed_cli_can_write_to_redirected_windows_stderr(tmp_path):
return self import subprocess
def __exit__(self, *_args): import sys
events.append('exit')
def close(self): path = tmp_path / 'data'
events.append('close') path.touch()
command = (
class Library: 'import sys; from cbb_refresh_verify.application import main; '
error = 'stop after path setup' 'sys.stderr = None; raise SystemExit(main(sys.argv[1:]))'
records = () )
result = subprocess.run([sys.executable, '-X', 'utf8', '-c', command,
monkeypatch.setattr(application, 'configure', lambda *_args: type('C', (), { '--batch-lmc', str(tmp_path / 'library.lmc'), '--data-root', str(path)],
'root': tmp_path, capture_output=True, encoding='utf-8', timeout=15,
'logger': type('L', (), {'info': lambda *a, **k: None, creationflags=subprocess.CREATE_NO_WINDOW)
'exception': lambda *a, **k: None, assert result.returncode == 1
'handlers': ()})(), assert 'DATA_ROOT_UNWRITABLE' in result.stderr and str(path) in result.stderr
})())
monkeypatch.setattr(network_path, 'LibraryPathLease', type('LP', (), {
'acquire': staticmethod(lambda path: (events.append(('acquire', path)) or Lease())) def test_desktop_unwritable_data_root_shows_chinese_startup_error(tmp_path, monkeypatch):
})) import win32api
monkeypatch.setattr(network_path, 'select_library_file', lambda path: ( from cbb_refresh_verify import application
events.append(('select', path)) or path
)) path = tmp_path / 'data'
path.touch()
# The command exits after the fake reader reports an empty/error library; messages = []
# ordering is the contract under test. monkeypatch.setattr(win32api, 'MessageBox', lambda parent, detail, title, flags: messages.append((title, detail)))
monkeypatch.setattr(library_reader, 'read_library_fast', lambda path, **kwargs: Library())
result = application.main(['--batch-lmc', r'\\server\share\library']) assert application.main(['--data-root', str(path)]) == 1
assert len(messages) == 1
assert result == 1 assert '启动失败' in messages[0][0]
assert events[:3] == [('acquire', Path(r'\\server\share\library')), 'enter', assert '无法写入数据目录' in messages[0][1] and str(path) in messages[0][1]
('select', tmp_path)]
def test_cli_signal_requests_cooperative_batch_stop(tmp_path, monkeypatch):
def test_native_log_helper_mode_does_not_load_ui_or_mgcpcb(tmp_path, monkeypatch): import signal
import json from cbb_refresh_verify import application, verify_runner
import cbb_refresh_verify.application as application library = tmp_path/'center.lmc'
request = tmp_path/'request.json' library.write_bytes(b'library')
pcb = tmp_path/'Work/PCB/test.pcb' old = signal.getsignal(signal.SIGINT)
pcb.parent.mkdir(parents=True) def run(requests, *, stop, context, item_executor):
request.write_text(json.dumps({'root': str(tmp_path), 'pcb': str(pcb)}), encoding='utf-8') assert context.stop is stop and callable(item_executor)
monkeypatch.setattr(application, 'configure', lambda *_: (_ for _ in ()).throw( signal.getsignal(signal.SIGINT)(signal.SIGINT, None)
AssertionError('log capture must not create a GUI/logger session'))) assert stop.is_set()
result = application.main(['--collect-failure-logs', str(request)]) return [verify_runner.VerifyResult('CANCELLED')]
assert result == 0 monkeypatch.setattr(verify_runner, 'run_batch', run)
assert application.main(['--batch-lmc', str(library), '--block', 'A',
'--data-root', str(tmp_path/'data')]) == 2
assert signal.getsignal(signal.SIGINT) is old
def test_smoke_arguments_exit_zero_and_write_lifecycle_log(tmp_path: Path):
import subprocess, sys
result = subprocess.run([sys.executable, '-m', 'cbb_refresh_verify', '--smoke-test', '--data-root', str(tmp_path)], timeout=30)
assert result.returncode == 0
text = (tmp_path / "logs" / "application.log").read_text(encoding="utf-8")
assert "application_start" in text
assert "application_clean_shutdown" in text
assert "gui_smoke_window_created" in text
def test_module_entrypoint_propagates_main_exit_code():
import subprocess, sys
code = (
"import cbb_refresh_verify.application as a; a.main=lambda: 7; "
"import runpy; runpy.run_module('cbb_refresh_verify.__main__', run_name='__main__')"
)
result = subprocess.run([sys.executable, '-c', code], capture_output=True, text=True)
assert result.returncode == 7
def test_batch_cli_acquires_unc_lease_before_directory_scan(tmp_path, monkeypatch):
import cbb_refresh_verify.application as application
import cbb_refresh_verify.library_reader as library_reader
import cbb_refresh_verify.network_path as network_path
events = []
class Lease:
display_path = r'\\server\share\library'
mentor_path = tmp_path
drive = 'Z:'
remote_root = r'\\server\share'
created = True
def __enter__(self):
events.append('enter')
return self
def __exit__(self, *_args):
events.append('exit')
def close(self):
events.append('close')
class Library:
error = 'stop after path setup'
records = ()
monkeypatch.setattr(application, 'configure', lambda *_args: type('C', (), {
'root': tmp_path,
'logger': type('L', (), {'info': lambda *a, **k: None,
'warning': lambda *a, **k: None,
'exception': lambda *a, **k: None,
'handlers': ()})(),
})())
monkeypatch.setattr(network_path, 'LibraryPathLease', type('LP', (), {
'acquire': staticmethod(lambda path: (events.append(('acquire', path)) or Lease()))
}))
monkeypatch.setattr(network_path, 'select_library_file', lambda path: (
events.append(('select', path)) or path
))
# The command exits after the fake reader reports an empty/error library;
# ordering is the contract under test.
monkeypatch.setattr(library_reader, 'read_library_fast', lambda path, **kwargs: Library())
result = application.main(['--batch-lmc', r'\\server\share\library'])
assert result == 1
assert events[:3] == [('acquire', Path(r'\\server\share\library')), 'enter',
('select', tmp_path)]
def test_native_log_helper_mode_does_not_load_ui_or_mgcpcb(tmp_path, monkeypatch):
import json
import cbb_refresh_verify.application as application
request = tmp_path/'request.json'
pcb = tmp_path/'Work/PCB/test.pcb'
pcb.parent.mkdir(parents=True)
request.write_text(json.dumps({'root': str(tmp_path), 'pcb': str(pcb)}), encoding='utf-8')
monkeypatch.setattr(application, 'configure', lambda *_: (_ for _ in ()).throw(
AssertionError('log capture must not create a GUI/logger session')))
result = application.main(['--collect-failure-logs', str(request)])
assert result == 0
assert (tmp_path/'diagnostics/native-logs.json').is_file() assert (tmp_path/'diagnostics/native-logs.json').is_file()
+249
View File
@@ -0,0 +1,249 @@
"""An item failure must not strand a batch or masquerade as ICDB damage."""
from dataclasses import replace
from threading import Event
import pytest
from cbb_refresh_verify import management, operation_lifecycle, session_record
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult, run_batch
def test_bulk_admission_skips_live_observer_without_starting_or_cancelling(tmp_path, monkeypatch):
from test_live_observer_queue import observed
library, _ = observed(tmp_path, monkeypatch)
queue = NativeQueue()
context = BatchTaskContext(str(library))
calls = []
with pytest.raises(RuntimeError, match='NATIVE_SESSION_PENDING'):
queue.run(lambda: calls.append('unexpected'), context=context, skip_unavailable=True)
assert not calls and not queue.pending and not queue.active
assert not context.stop.is_set()
assert queue.run(lambda: 'other library', context=BatchTaskContext(str(tmp_path/'other.lmc')),
skip_unavailable=True) == 'other library'
assert not session_record.library_available(library, live_only=True)
@pytest.mark.parametrize('kind', ['verify', 'management'])
def test_pre_admission_busy_is_one_skip_not_a_retained_or_cancelled_batch(tmp_path, monkeypatch, kind):
from test_live_observer_queue import observed
library, state = observed(tmp_path, monkeypatch)
queue = NativeQueue()
calls = []
def item(req, action):
path = req.lmc_file if kind == 'verify' else req.library
context = BatchTaskContext(str(path))
try:
return queue.run(action, context=context, skip_unavailable=True)
finally:
# The original observer finishes between submitted targets.
state['status'] = 'RELEASED'
if kind == 'verify':
def execute(req):
calls.append(req.block_name)
return VerifyResult('PASS')
results = run_batch([VerifyRequest(library, name, tmp_path) for name in ('Busy', 'Good')],
verifier=execute, item_executor=item)
else:
def execute(req, **kwargs):
calls.append(req.name)
return management.ManagementResult(req.operation, req.library, req.name, req.partition,
req.source, req.auto_verify, 'complete', 'REMOVED', True)
monkeypatch.setattr(management, 'run_management', execute)
results = management.run_management_batch([
management.ManagementRequest('remove', library, name) for name in ('Busy', 'Good')],
item_executor=item)
assert [r.status for r in results] == ['SKIPPED', 'PASS' if kind == 'verify' else 'REMOVED']
assert all(r.safe_to_continue for r in results)
assert calls == ['Good']
assert 'NATIVE_SESSION_PENDING' in (results[0].stderr if kind == 'verify' else results[0].detail)
@pytest.mark.parametrize('released', [True, False])
def test_management_rechecks_original_owner_and_preserves_failure(tmp_path, monkeypatch, released):
library = tmp_path/'lib.lmc'
requests = [management.ManagementRequest('remove', library, name) for name in ('Bad', 'Next')]
failed = management.ManagementResult('remove', library, 'Bad', 'Logical-Physical', None,
True, 'complete', 'RECOVERY_REQUIRED', False, 'original failure', tmp_path/'result.json')
checks, calls = [], []
def recheck(lib, block, result, **kwargs):
assert lib == library and block == 'Bad' and result.name == 'Bad'
checks.append(block)
return replace(result, safe_to_continue=True) if released and len(checks) > 1 else result
def execute(req, **kwargs):
calls.append(req.name)
return failed if req.name == 'Bad' else replace(failed, name=req.name, status='REMOVED', safe_to_continue=True)
monkeypatch.setattr(operation_lifecycle, 'recheck_failed_release', recheck)
monkeypatch.setattr(management, 'run_management', execute)
results = management.run_management_batch(requests)
assert checks == ['Bad', 'Bad']
assert calls == (['Bad', 'Next'] if released else ['Bad'])
assert results[0].status == 'RECOVERY_REQUIRED' and results[0].detail == 'original failure'
assert results[0].safe_to_continue is released
if not released:
assert 'Bad' in results[1].detail and results[1].stage == 'admission'
def test_management_unexpected_item_exception_keeps_independent_targets(tmp_path, monkeypatch):
libraries = [tmp_path/'same.lmc', tmp_path/'same.lmc', tmp_path/'other.lmc']
requests = [management.ManagementRequest('remove', library, name)
for library, name in zip(libraries, ('Crash', 'Same', 'Other'))]
calls = []
def execute(req, **kwargs):
calls.append(req.name)
if req.name == 'Crash':
raise OSError('unexpected evidence disk failure')
return management.ManagementResult(req.operation, req.library, req.name, req.partition,
None, True, 'complete', 'REMOVED', True)
monkeypatch.setattr(management, 'run_management', execute)
results = management.run_management_batch(requests)
assert [r.status for r in results] == ['RECOVERY_REQUIRED', 'SKIPPED', 'REMOVED']
assert not results[0].safe_to_continue
assert 'BATCH_ITEM_EXCEPTION' in results[0].detail
assert calls == ['Crash', 'Other']
@pytest.mark.parametrize('released', [True, False])
def test_icdb_rechecks_failed_owner_before_next_target(qtbot, tmp_path, monkeypatch, released):
from cbb_refresh_verify.ui.icdb_check_task import IcdbCheckTask
library = tmp_path/'lib.lmc'
checks, calls = [], []
failed = VerifyResult('FAIL', stderr='original database load error', safe_to_continue=False,
evidence_path=tmp_path/'result.json', error_category='MENTOR_DATABASE_LOAD_FAILED')
def execute(req):
calls.append(req.block_name)
return failed if req.block_name == 'Bad' else VerifyResult('CHECKED')
def recheck(lib, block, result, **kwargs):
assert lib == library and block == 'Bad' and result is failed
checks.append(block)
return replace(result, safe_to_continue=True) if released and len(checks) > 1 else result
monkeypatch.setattr(operation_lifecycle, 'recheck_failed_release', recheck)
task = IcdbCheckTask([VerifyRequest(library, name, tmp_path) for name in ('Bad', 'Next')],
NativeQueue(), tmp_path/'reports', verifier=execute)
task.start()
qtbot.waitUntil(lambda: not task.active, timeout=5000)
assert checks == ['Bad', 'Bad']
assert calls == (['Bad', 'Next'] if released else ['Bad'])
assert task.results[0].status == 'FAIL' and task.results[0].safe_to_continue is released
if not released:
assert 'Bad' in task.results[1].stderr
assert task.results[1].error_category == 'PREVIOUS_SESSION_UNRELEASED'
def test_icdb_live_observer_finishes_batch_without_cancel_button(qtbot, tmp_path, monkeypatch):
from test_live_observer_queue import observed
from cbb_refresh_verify.ui.icdb_check_task import IcdbCheckTask
library, _ = observed(tmp_path, monkeypatch)
calls = []
task = IcdbCheckTask([VerifyRequest(library, name, tmp_path) for name in ('A', 'B')],
NativeQueue(), tmp_path/'reports',
verifier=lambda req: calls.append(req.block_name) or VerifyResult('CHECKED'))
task.start()
try:
qtbot.waitUntil(lambda: not task.active, timeout=1500)
assert [r.status for r in task.results] == ['SKIPPED', 'SKIPPED']
assert all(r.safe_to_continue and r.error_category == 'NATIVE_SESSION_PENDING' for r in task.results)
assert not calls and not task.stop.is_set()
finally:
task.cancel()
qtbot.waitUntil(lambda: not task.active, timeout=3000)
def test_cancel_has_priority_over_busy_admission(tmp_path, monkeypatch):
from test_live_observer_queue import observed
from cbb_refresh_verify.operation_queue import QueueCancelled
library, _ = observed(tmp_path, monkeypatch)
context = BatchTaskContext(str(library))
context.cancel()
with pytest.raises(QueueCancelled):
NativeQueue().run(lambda: pytest.fail('cancelled action dispatched'),
context=context, skip_unavailable=True)
def test_cancel_during_release_recheck_preserves_original_result(tmp_path):
stop = Event()
stop.set()
failed = VerifyResult('FAIL', safe_to_continue=False, evidence_path=tmp_path/'result.json')
result = operation_lifecycle.recheck_failed_release(tmp_path/'lib.lmc', 'Bad', failed, stop=stop)
assert result is failed
def test_broken_management_progress_sink_does_not_abort_completed_items(tmp_path, monkeypatch):
requests = [management.ManagementRequest('remove', tmp_path/'lib.lmc', name) for name in ('A', 'B')]
def execute(req, **kwargs):
return management.ManagementResult(req.operation, req.library, req.name, req.partition,
None, True, 'complete', 'REMOVED', True)
def disconnected(event):
raise RuntimeError('UI receiver deleted')
monkeypatch.setattr(management, 'run_management', execute)
results = management.run_management_batch(requests, progress=disconnected)
assert [r.status for r in results] == ['REMOVED', 'REMOVED']
def test_verify_ui_busy_admission_reports_each_skip_and_remains_usable(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
monkeypatch.setattr('cbb_refresh_verify.ui.main_window.VERIFY_RELEASE_WAIT_SECONDS', .1)
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda req: pytest.fail('live observer must prevent native launch'))
library = window.mentor_lmc_path or window.loaded_path
# Preserve the real admission/Qt paths; only emulate the cached native observer.
from types import SimpleNamespace
monkeypatch.setattr(session_record, '_retained_libraries', {'owned':{session_record._library_key(library)}})
monkeypatch.setattr(session_record, '_retained_results', {'owned':{'status':'ACTIVE'}})
monkeypatch.setattr(session_record, '_observers', {'owned':(SimpleNamespace(is_alive=lambda:True),None)})
window._run(['Beta', 'Gamma'])
try:
qtbot.waitUntil(lambda: not window.busy, timeout=2500)
assert window.search_edit.isEnabled()
reports = list((tmp_path/'reports').glob('batch-*.log'))
assert reports
text = reports[0].read_text(encoding='utf-8')
assert text.count('NATIVE_SESSION_PENDING') >= 2
assert 'CANCELLED' not in text and 'PREVIOUS_SESSION_UNRELEASED' not in text
assert window.status_label.text().startswith('已结束:')
finally:
window.stop.set()
window.native_queue.wake()
qtbot.waitUntil(lambda: not window.busy, timeout=3000)
@pytest.mark.parametrize('kind', ['backup', 'management'])
def test_dialog_busy_before_dispatch_never_claims_own_unreleased_session(qtbot, tmp_path, monkeypatch, kind):
from test_live_observer_queue import observed
from cbb_refresh_verify.ui import timed_prompt
from PySide6.QtWidgets import QMessageBox
library, _ = observed(tmp_path, monkeypatch)
monkeypatch.setattr(timed_prompt, 'question', lambda *a, **kw: QMessageBox.Yes)
results = []
if kind == 'backup':
from cbb_refresh_verify.ui.backup_recovery_dialog import BackupRecoveryDialog
dialog = BackupRecoveryDialog(('A',), lambda name: VerifyRequest(library, name, tmp_path),
recoverer=lambda *a, **kw: pytest.fail('blocked recovery dispatched'))
source=tmp_path/'A.prj'; source.touch()
dialog.source_edit.setText(str(source))
dialog.completed.connect(lambda name,result: results.append(result))
button=dialog.restore_button
else:
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
dialog = ManagementDialog([management.ManagementRequest('remove',library,'A')],
runner=lambda *a,**kw: pytest.fail('blocked management dispatched'))
dialog.completed.connect(results.extend)
button=dialog.execute_button
qtbot.addWidget(dialog)
dialog.native_queue=NativeQueue()
button.click()
qtbot.waitUntil(lambda: not dialog.busy, timeout=2500)
assert len(results)==1 and results[0].status=='SKIPPED' and results[0].safe_to_continue
def test_pre_admission_error_does_not_retain_a_path_lease(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.operation_queue import QueueUnavailable
window=load_window(qtbot,tmp_path,monkeypatch)
from types import SimpleNamespace
window.library_lease=SimpleNamespace()
retained=[]
monkeypatch.setattr(window,'_retain_path_lease',lambda *a,**kw: retained.append(a))
window._failed(QueueUnavailable('lib.lmc'))
window.library_lease=None
assert not retained
+20
View File
@@ -122,6 +122,26 @@ def test_persistent_loading_progress_keeps_deadline_and_never_closes(diagnostic,
assert Session.instances[-1].posted == [] assert Session.instances[-1].posted == []
def test_cancel_from_window_scan_wins_expired_open_deadline(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
signal = Path(job['root']).parent/'cancel-after-scan'
job['cancel_signal'] = str(signal)
clock = [0.0]
monkeypatch.setattr(diagnostic.time, 'monotonic', lambda: clock[0])
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
target = frame(job)
target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True})
def windows(pid):
signal.touch()
clock[0] = 10.0
return [target]
monkeypatch.setattr(diagnostic, '_windows', windows)
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'):
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
assert Session.instances[-1].posted == []
def test_diagnostic_waits_for_startup_forward_no_before_close(diagnostic, job, monkeypatch): def test_diagnostic_waits_for_startup_forward_no_before_close(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job); job['timeout'] = 1 write_logs(job); job['timeout'] = 1
+1
View File
@@ -166,6 +166,7 @@ def test_cli_unsafe_batch_preserves_created_drive(tmp_path, monkeypatch):
from cbb_refresh_verify import application from cbb_refresh_verify import application
backend = FakeWNet() backend = FakeWNet()
lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend) lease = LibraryPathLease.acquire(r'\\server\share\lib.lmc', backend=backend)
(tmp_path/'lib.lmc').write_bytes(b'library')
monkeypatch.setattr(LibraryPathLease, 'acquire', lambda path: lease) monkeypatch.setattr(LibraryPathLease, 'acquire', lambda path: lease)
monkeypatch.setattr('cbb_refresh_verify.network_path.select_library_file', lambda path: tmp_path/'lib.lmc') monkeypatch.setattr('cbb_refresh_verify.network_path.select_library_file', lambda path: tmp_path/'lib.lmc')
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests, **kw: [VerifyResult('FAIL', safe_to_continue=False)]) monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_batch', lambda requests, **kw: [VerifyResult('FAIL', safe_to_continue=False)])
+53
View File
@@ -371,3 +371,56 @@ def test_only_exact_empty_zero_area_childless_ie_infrastructure_is_benign(tmp_pa
entry = result['benign_auxiliary_windows'][0] entry = result['benign_auxiliary_windows'][0]
assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0] assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0]
assert entry['children'] == [] assert entry['children'] == []
@pytest.mark.parametrize('receipt', ['matching', 'late', 'different_operation', 'different_identity'])
def test_supervisor_no_lets_own_empty_pcb_close_with_address_remaining(tmp_path, monkeypatch, receipt):
import win32con
job, records, messages, _, visible = read_write_fixture(tmp_path, monkeypatch)
job['operation_id'] = 'verify-owned'
address = tmp_path/'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('existing address')
snapshot = failed_session._startup_snapshot(200, 12).to_record()
from cbb_refresh_verify import residual_sessions
monkeypatch.setattr(residual_sessions, '_force_ownership', lambda *_: {
'owner_sid': 'S-1-5-21-test', 'session_id': 1})
owner = {'pid': 12, 'owner_sid': 'S-1-5-21-test', 'session_id': 1,
'image': records[0][1], 'created_handle': 'reused' if receipt == 'different_identity' else 'original'}
(tmp_path/'pcb-open-user-choice.json').write_text(json.dumps(dict(
operation_id='another-operation' if receipt == 'different_operation' else job['operation_id'],
desktop=job['desktop'], project=job['project'], pcb=job['pcb'],
library=job['lmc_file'], choice='skip', snapshot=snapshot, owner={'target': owner})))
visible.remove(200)
def record_acknowledgement():
(tmp_path/'dialogs.jsonl').write_text(json.dumps(dict(
snapshot, action='user_confirmed_pcb_open', error_code='PCB_OPEN_SKIPPED',
accepted_control=[7]))+'\n')
if receipt == 'late':
from types import SimpleNamespace
elapsed = 0.0
def advance(seconds):
nonlocal elapsed
elapsed += seconds
if elapsed < 0.3:
record_acknowledgement()
monkeypatch.setattr(failed_session, 'time',
SimpleNamespace(monotonic=lambda: elapsed, sleep=advance))
else:
record_acknowledgement()
result = failed_session.close_failed_startup(
job, 12, timeout_seconds=0 if receipt == 'different_operation' else 1)
if receipt in {'different_operation', 'different_identity'}:
assert result['status'] == 'RETAINED' and records and not messages
return
assert result['status'] == 'CLOSED'
assert result['cancelled_prompt'] == 'read_write_access'
assert result['release']['addresses'] == [str(address)]
assert result['release']['resource_release_confirmed'] is False
assert messages == [(100, win32con.WM_CLOSE)]
assert not records and address.is_file()
+100 -1
View File
@@ -172,7 +172,7 @@ def test_catalog_union_keeps_registration_source_and_counts(qtbot, tmp_path, mon
load(window,qtbot) load(window,qtbot)
qtbot.waitUntil(entered.is_set) qtbot.waitUntil(entered.is_set)
assert '未知' in window.counts_label.text() assert '未知' in window.counts_label.text()
assert window.batch_button.isEnabled() assert not window.batch_button.isEnabled()
release.set() release.set()
qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name) qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name)
assert window._records_by_name['Orphan'].catalog_source == 'directory_only' assert window._records_by_name['Orphan'].catalog_source == 'directory_only'
@@ -649,3 +649,102 @@ def test_recovery_retry_rejects_old_external_progress_and_choice(qtbot,tmp_path,
assert choice.decision=='cancel' assert choice.decision=='cancel'
finally: finally:
release.set(); qtbot.waitUntil(lambda:not dialog.busy) release.set(); qtbot.waitUntil(lambda:not dialog.busy)
@pytest.mark.parametrize('cancel', [True, False])
def test_uncommitted_catalog_refresh_preserves_last_full_result(qtbot, tmp_path, monkeypatch, cancel):
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.ui import main_window as ui
reading, release = Event(), Event()
calls = []
snapshot = tmp_path/'status-refresh.jsonl'
def read_status(names, path, checkpoint_path=None, *, progress=None):
calls.append(names)
if checkpoint_path is not None:
checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
checkpoint_path.write_text('full scan' if len(calls) == 1 else 'partial scan', encoding='utf-8')
if len(calls) == 2:
reading.set()
release.wait(5)
return {name: 'READY' for name in names}
monkeypatch.setattr(ui, 'authoritative_status_map', read_status)
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
catalog_reader=lambda path, _: Catalog(path, 1, (CatalogEntry('A', 'Logical-Physical'),)))
try:
load(window, qtbot)
qtbot.waitUntil(lambda: window.ready_names == {'A'})
reports = []
monkeypatch.setattr(window, '_publish_check_statuses',
lambda library, statuses, lease: reports.append(dict(statuses)))
original_replace = Path.replace
def replace_file(path, target):
if target == snapshot:
raise PermissionError('snapshot is held')
return original_replace(path, target)
if not cancel:
monkeypatch.setattr(Path, 'replace', replace_file)
window.load_button.click()
qtbot.waitUntil(reading.is_set)
assert window.ready_names == {'A'}
assert not window.batch_button.isEnabled()
assert snapshot.read_text(encoding='utf-8') == 'full scan'
if cancel:
window.stop_button.click()
release.set()
qtbot.waitUntil(lambda: not any(job.kind == 'catalog' for job in window._jobs.values()))
assert ('已取消读取' if cancel else 'snapshot is held') in window.status_label.text()
assert reports == []
assert window.ready_names == {'A'}
assert snapshot.read_text(encoding='utf-8') == 'full scan'
window.status_refresher(('A',), Path('a.lmc'))
assert snapshot.read_text(encoding='utf-8') == 'full scan'
finally:
release.set()
window.pool.waitForDone(6000)
@pytest.mark.parametrize('cancelled', [False, True])
def test_external_catalog_owner_wait_retries_once_or_cancels(qtbot, tmp_path, monkeypatch, cancelled):
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.native_management import NativeOperationError
probing, released = Event(), Event()
calls = []
def read_catalog(path, evidence):
calls.append(evidence)
if len(calls) == 1:
raise NativeOperationError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行。', safe_to_continue=True)
return Catalog(path, 1, (CatalogEntry('A', 'Logical-Physical'),))
def owners(*args, **kwargs):
probing.set()
return [] if released.is_set() else [{'pid': 123}]
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', owners)
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
catalog_reader=read_catalog, status_refresher=lambda names, _: {name: 'READY' for name in names})
try:
load(window, qtbot)
qtbot.waitUntil(probing.is_set)
assert not window.native_queue.active
if cancelled:
window.stop_button.click()
released.set()
qtbot.waitUntil(lambda: not any(job.kind == 'catalog' for job in window._jobs.values()), timeout=4000)
assert len(calls) == (1 if cancelled else 2)
if cancelled:
assert '已取消读取' in window.status_label.text()
else:
assert calls[0] != calls[1]
assert window.ready_names == {'A'}
finally:
released.set()
window.pool.waitForDone(6000)
+40
View File
@@ -238,3 +238,43 @@ def test_catalog_native_wait_outlives_metadata_deadline(tmp_path, transport, mon
(evidence/'finish').touch() (evidence/'finish').touch()
finisher.join(6) finisher.join(6)
context.close(timeout_seconds=6) context.close(timeout_seconds=6)
@pytest.mark.parametrize('switch', [False, True])
def test_stop_reaches_active_catalog_adapter(qtbot, tmp_path, monkeypatch, transport, switch):
from types import SimpleNamespace
from cbb_refresh_verify.native_management import NativeManagementAdapter
Transport, workers = transport
original = Transport.__init__
def hold_until_signalled(self, command, *args, **kwargs):
Path(command[-1]).with_name('hold-handler').touch()
original(self, command, *args, **kwargs)
monkeypatch.setattr(Transport, '__init__', hold_until_signalled)
library = tmp_path/'library.lmc'
library.write_bytes(b'isolated')
adapter = NativeManagementAdapter(worker_factory=Transport)
window = window_for(qtbot, tmp_path/'ui', monkeypatch, catalog_reader=adapter.catalog)
mapping_calls = []
window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, display_path=path,
drive='', remote_root='', close=lambda: mapping_calls.append('close'),
retain_for_recovery=lambda: mapping_calls.append('retain'))
load(window, qtbot, str(library))
qtbot.waitUntil(lambda: bool(workers) and workers[0].path.with_name('handler-entered').exists())
worker = workers[0]
try:
if switch:
window.lmc_edit.setText(str(tmp_path/'different.lmc'))
else:
window.stop_button.click()
qtbot.waitUntil(lambda: worker.path.with_name('cancel-management.signal').exists(), timeout=3000)
qtbot.waitUntil(lambda: bool(mapping_calls), timeout=3000)
assert mapping_calls[0] == 'retain'
if not switch:
qtbot.waitUntil(lambda: '已取消读取中心库' in window.status_label.text(), timeout=3000)
assert not window.native_queue.active
assert worker.poll() is None
finally:
worker.path.with_name('finish').touch()
qtbot.waitUntil(lambda: worker.poll() is not None, timeout=5000)
+231
View File
@@ -0,0 +1,231 @@
"""Field #17: data failures finish their own cleanup before the next writer."""
import json
import time
from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
import pytest
from cbb_refresh_verify import failed_session, verify_runner
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
def test_database_load_question_declines_log_view_then_closes_empty_target(tmp_path, monkeypatch):
import win32con
from test_failed_startup import read_write_fixture
job, records, messages, names, _ = read_write_fixture(tmp_path, monkeypatch)
names[203] = ('Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed.\r\r'
'Do you wish to view the log file now?')
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'CLOSED', result
assert messages == [(202, win32con.BM_CLICK), (100, win32con.WM_CLOSE)]
assert not records
@pytest.mark.parametrize('text', [
'Problem encountered while opening one of the database files. Delete database?',
'Loading of the job has failed. Do you wish to repair it?',
])
def test_unknown_database_question_is_preserved(tmp_path, monkeypatch, text):
from test_failed_startup import read_write_fixture
job, records, messages, names, _ = read_write_fixture(tmp_path, monkeypatch)
names[203] = text
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'RETAINED' and records and not messages
def test_supervisor_acknowledged_failed_open_can_close_empty_shell_with_address(tmp_path, monkeypatch):
import win32con
from cbb_refresh_verify.dialog_models import WindowSnapshot, ControlSnapshot, DialogPhase
from test_failed_startup import startup_fixture
job, records, messages = startup_fixture(tmp_path, monkeypatch)
address = tmp_path/'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('original address')
popup = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB',
DialogPhase.PCB_STARTING, (
ControlSnapshot(201,6,'Button','Yes'), ControlSnapshot(202,7,'Button','No'),
ControlSnapshot(203,65535,'Static',
'Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed.\r\r'
'Do you wish to view the log file now?')))
(tmp_path/'dialogs.jsonl').write_text(json.dumps(dict(popup.to_record(),
action='acknowledge_fatal', error_code='MENTOR_DATABASE_LOAD_FAILED', accepted_control=[7]))+'\n')
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'CLOSED', result
assert messages == [(100,win32con.WM_CLOSE)]
assert not records and address.read_text() == 'original address'
@pytest.mark.parametrize('aliased', [False, True])
@pytest.mark.parametrize('first_status', ['FAIL', 'SKIPPED'])
def test_late_release_is_rechecked_before_later_same_library_item(tmp_path, monkeypatch, aliased, first_status):
library = tmp_path/'lib.lmc'
calls, checks = [], []
failed = verify_runner.VerifyResult(first_status, stderr='native operation declined', safe_to_continue=False,
evidence_path=tmp_path/'result.json',
error_category='PCB_OPEN_SKIPPED' if first_status == 'SKIPPED' else 'MENTOR_DATABASE_LOAD_FAILED')
def verify(request):
calls.append(request.block_name)
return failed if request.block_name == 'Bad' else verify_runner.VerifyResult('PASS')
def recheck(library, block, result, **kwargs):
checks.append(block)
return result if len(checks) == 1 else replace(result, safe_to_continue=True)
monkeypatch.setattr('cbb_refresh_verify.operation_lifecycle.recheck_failed_release', recheck)
if aliased:
monkeypatch.setattr('cbb_refresh_verify.operation_queue.request_library_keys',
lambda *args:{'display-path','mapped-path'})
results = verify_runner.run_batch([verify_runner.VerifyRequest(library, n, tmp_path)
for n in ('Bad','Good')], verifier=verify)
assert calls == ['Bad','Good']
assert [r.status for r in results] == [first_status,'PASS']
assert results[0].safe_to_continue
def test_slow_catalog_status_is_delivered_and_unknown_cannot_start_bulk(qtbot, tmp_path, monkeypatch):
from test_issue15_ui_integration import window_for
from cbb_refresh_verify.management import Catalog, CatalogEntry
from threading import Event
entered, release = Event(), Event()
def statuses(names, library):
entered.set()
assert release.wait(15)
return {name:'READY' for name in names}
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A','LP'),), directory_count=1),
catalog_reader=lambda p,e:Catalog(p,1,(CatalogEntry('A','Logical-Physical'),)),
status_refresher=statuses)
window.lmc_edit.setText('a.lmc')
window.load_library()
qtbot.waitUntil(entered.is_set)
try:
assert not window.batch_button.isEnabled()
assert window.backup_restore_button.isEnabled()
assert '待读取 1' in window.counts_label.text()
# Actual prior metadata cutoff; native IO is simulated, task/Qt delivery is real.
qtbot.wait(10300)
release.set()
qtbot.waitUntil(lambda:window.ready_names == {'A'}, timeout=3000)
assert '原生 1' in window.counts_label.text()
finally:
release.set()
window.pool.waitForDone(5000)
def test_successful_worker_does_not_report_retained_save(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
job, events, execute = exercise_worker(tmp_path, monkeypatch)
assert execute()['status'] == 'PASS'
assert not [e for e in events if e.get('stage') == 'save_result_retained']
@pytest.mark.parametrize('fresh', ['UNKNOWN', 'UNAVAILABLE', None])
def test_execution_rechecks_status_without_starting_unknown_target(qtbot, tmp_path, monkeypatch, fresh):
from test_issue15_ui_integration import window_for
from cbb_refresh_verify.management import Catalog, CatalogEntry
calls, reads = [], []
def statuses(names, library):
reads.append(tuple(names))
return {'A':'PENDING'} if len(reads) == 1 else ({} if fresh is None else {'A':fresh})
window = window_for(qtbot,tmp_path,monkeypatch,
reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),), directory_count=1),
catalog_reader=lambda p,e:Catalog(p,1,(CatalogEntry('A','Logical-Physical'),)),
status_refresher=statuses,
verifier=lambda request:(calls.append(request.block_name) or verify_runner.VerifyResult('PASS')))
window.lmc_edit.setText('a.lmc'); window.load_library()
qtbot.waitUntil(lambda:window._read_counts[1] == 1)
window._run(['A'])
qtbot.waitUntil(lambda:not window.busy)
assert calls == []
reports=list((tmp_path/'reports').glob('batch-*.log'))
assert reports and 'STATUS_UNCONFIRMED' in reports[0].read_text(encoding='utf-8')
@pytest.mark.parametrize('second_ready', [True,False])
def test_saved_closed_pending_commit_gets_only_one_followup(tmp_path, monkeypatch, second_ready):
root=tmp_path/'first';root.mkdir()
evidence=root/'result.json';evidence.write_text('{"status":"FAIL"}')
second=tmp_path/'second';second.mkdir()
second_evidence=second/'result.json';second_evidence.write_text('{}')
pending=verify_runner.VerifyResult('FAIL',safe_to_continue=True,evidence_path=evidence,
library_flag='NOT_GREEN',error_category='MENTOR_VERIFY_NOT_COMMITTED',error_stage='library_flag',
bridge_attempts=({'status':'PENDING','source':'IsVerifiedReuseBlock','raw_status':0},),
timings_seconds={'total':2.0},
write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',
resource_state='RELEASED',interrupted=False))
calls=[]
def serialized(request,**kwargs):
calls.append(request.block_name)
if len(calls)==1:return pending
return (verify_runner.VerifyResult('PASS',library_flag='GREEN',evidence_path=second_evidence,timings_seconds={'total':3.0})
if second_ready else replace(pending,evidence_path=second_evidence,timings_seconds={'total':3.0}))
monkeypatch.setattr(verify_runner,'_run_verify_serialized',serialized)
result=verify_runner._run_verify_task(verify_runner.VerifyRequest(tmp_path/'missing.lmc','Block',tmp_path))
assert calls == ['Block','Block']
assert result.status == ('PASS' if second_ready else 'FAIL')
assert result.timings_seconds['total']==5.0
assert json.loads(evidence.read_text()) == {'status':'FAIL'}
link=json.loads((root/'commit-followup.json').read_text())
assert link['status']==('READY' if second_ready else 'UNCONFIRMED')
@pytest.mark.parametrize('obstacle', ['unsafe','save_unknown','close_unknown','native_retained',
'helper_running','interrupted','database_failure','unknown_status','diagnostic','auto_repair','cancelled'])
def test_incomplete_or_failed_native_operation_never_gets_commit_followup(tmp_path,monkeypatch,obstacle):
from threading import Event
evidence=tmp_path/'result.json';evidence.write_text('{}')
facts=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',resource_state='RELEASED',interrupted=False)
if obstacle=='save_unknown':facts['save_state']='UNKNOWN'
if obstacle=='close_unknown':facts['close_state']='UNKNOWN'
if obstacle=='native_retained':facts['resource_state']='RETAINED'
if obstacle=='helper_running':facts['helper_state']='RUNNING'
if obstacle=='interrupted':facts['interrupted']=True
pending=verify_runner.VerifyResult('FAIL',safe_to_continue=obstacle!='unsafe',evidence_path=evidence,
library_flag='NOT_GREEN' if obstacle!='unknown_status' else 'UNKNOWN',
error_category='MENTOR_DATABASE_LOAD_FAILED' if obstacle=='database_failure' else 'MENTOR_VERIFY_NOT_COMMITTED',
error_stage='library_flag',bridge_attempts=({'status':'PENDING','source':'IsVerifiedReuseBlock','raw_status':0},),
write_outcome=facts)
stop=Event();calls=[]
def serialized(*args,**kwargs):
calls.append(1)
if obstacle=='cancelled':stop.set()
return pending
monkeypatch.setattr(verify_runner,'_run_verify_serialized',serialized)
verify_runner._run_verify_task(verify_runner.VerifyRequest(tmp_path/'missing.lmc','Block',tmp_path,
diagnostic_only=obstacle=='diagnostic',auto_repair=obstacle=='auto_repair'),stop=stop)
assert calls == [1]
assert not (tmp_path/'commit-followup.json').exists()
def test_cancel_after_followup_checkpoint_releases_completed_first_lease(tmp_path,monkeypatch):
from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled
from cbb_refresh_verify import library_lock
import win32con, win32file
library=tmp_path/'lib.lmc';library.write_bytes(b'isolated fixture')
evidence=tmp_path/'result.json';evidence.write_text('{}')
pending=verify_runner.VerifyResult('FAIL',safe_to_continue=True,evidence_path=evidence,
library_flag='NOT_GREEN',error_category='MENTOR_VERIFY_NOT_COMMITTED',error_stage='library_flag',
write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',resource_state='RELEASED',interrupted=False))
monkeypatch.setattr(library_lock,'recheck_previous_release',lambda *a,**k:None)
monkeypatch.setattr(verify_runner,'_run_verify_serialized',lambda *a,**k:pending)
context=BatchTaskContext(str(library))
original=Path.write_text
def write(path,*a,**k):
result=original(path,*a,**k)
if path.name=='commit-followup.json':context.cancel()
return result
monkeypatch.setattr(Path,'write_text',write)
try:
with pytest.raises(QueueCancelled):
context.run(lambda:verify_runner._run_verify_task(
verify_runner.VerifyRequest(library,'Block',tmp_path),stop=context.stop))
lock=library_lock.LibraryLock(library)
handle=win32file.CreateFile(str(lock.path),win32con.GENERIC_READ,0,None,win32con.OPEN_EXISTING,0,None)
handle.Close()
finally:
context.close(timeout_seconds=0)
with library_lock._guard:
owner=library_lock._owners.pop(library_lock.LibraryLock(library).key,None)
if owner:owner['handle'].Close()
+285
View File
@@ -0,0 +1,285 @@
from pathlib import Path
from types import SimpleNamespace
import pytest
from cbb_refresh_verify import native_management as native
from cbb_refresh_verify.batch_status import BatchStatusSession
from cbb_refresh_verify.status_bridge import BridgeResult
def test_status_scan_delivers_progress_after_each_record(tmp_path):
snapshots = []
bridge = SimpleNamespace(query=lambda *args, **kwargs: BridgeResult("READY", "test"))
lmc = tmp_path / 'library.lmc'
lmc.write_bytes(b'library')
checkpoint = tmp_path / 'pending.jsonl'
def progress(completed, total):
snapshots.append((completed, total, len(checkpoint.read_text('utf-8').splitlines())))
results = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint, progress=progress)
assert [record.status for record in results] == ['READY', 'READY']
assert snapshots == [(1, 2, 1), (2, 2, 2)]
@pytest.mark.parametrize('include_identity', [False, True])
def test_catalog_registration_only_skips_project_identities(tmp_path, monkeypatch, include_identity):
import win32com.client
from cbb_refresh_verify import mentor_adapter
lmc = tmp_path / 'lib.lmc'
lmc.touch()
project = tmp_path / 'ReusableBlocksLP/A/Work/A.prj'
project.parent.mkdir(parents=True)
project.touch()
hashed = []
monkeypatch.setattr(native, 'engineering_identity', lambda p: hashed.append(p) or {'identity': True})
partition = SimpleNamespace(Count=1,
Item=lambda _: SimpleNamespace(Name='A', PartitionName='Logical-Physical'))
library = SimpleNamespace(FullName=str(lmc), FlowType=1, Close=lambda: None,
Partitions=lambda _: SimpleNamespace(Count=1, Item=lambda _: partition))
app = SimpleNamespace(OpenLibrary=lambda _: library, Quit=lambda: None)
exe = tmp_path / 'lm/win32/bin/LibraryManager.exe'
no_owners = iter([[], [(123, str(exe), '', 0)]])
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: next(no_owners))
monkeypatch.setattr(native, '_current_desktop',
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: app)
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
'include_engineering_identity': include_identity, 'library': str(lmc),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
assert result['success']
assert hashed == ([project] if include_identity else [])
@pytest.mark.parametrize('scope', ['foreign', 'same', 'shared', 'unknown', 'switched', 'occupied'])
def test_catalog_distinguishes_foreign_and_conflicting_manager(tmp_path, monkeypatch, scope):
target = tmp_path/'target'/'lib.lmc'
outside = tmp_path/'outside'/'lib.lmc'
for lmc in (target, outside):
lmc.parent.mkdir()
lmc.touch()
if scope == 'shared':
from cbb_refresh_verify.icdb_ownership import shared_symbol_database
first = shared_symbol_database(target)/'icdb.dat'
second = shared_symbol_database(outside)/'icdb.dat'
first.parent.mkdir(parents=True)
second.parent.mkdir(parents=True)
first.touch()
second.hardlink_to(first)
lk = target if scope == 'same' else outside
actual = None if scope == 'unknown' else target if scope == 'switched' else lk
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: actual, raising=False)
owners = [(123, 'LibraryManager.exe', '' if scope == 'unknown' else f'LibraryManager.exe "{lk}"', 0)]
if scope == 'occupied':
def held(library):
raise OSError('shared database handle is occupied')
monkeypatch.setattr(native, '_probe_catalog_files', held)
if scope == 'foreign':
native._check_catalog_owners(target, owners)
else:
with pytest.raises(RuntimeError, match='LIBRARY_MANAGER_BUSY.*123'):
native._check_catalog_owners(target, owners)
def test_catalog_rejects_reused_foreign_com_proxy_without_mutating_it(tmp_path, monkeypatch):
import win32com.client
from cbb_refresh_verify import mentor_adapter
target = tmp_path/'target'/'lib.lmc'
other = tmp_path/'other'/'lib.lmc'
for lmc in (target, other):
lmc.parent.mkdir()
lmc.touch()
exe = tmp_path/'lm/win32/bin/LibraryManager.exe'
exe.parent.mkdir(parents=True)
exe.write_bytes(b'library manager')
monkeypatch.setitem(native._BINARY_PROOF, 'lm/win32/bin/LibraryManager.exe', native.hash_file(exe))
before = [(123, 'LibraryManager.exe', f'LibraryManager.exe "{other}"', 0)]
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: before)
monkeypatch.setattr(native, '_open_catalog_manager_library', lambda _: other, raising=False)
monkeypatch.setattr(native, '_current_desktop',
lambda: (SimpleNamespace(EnumDesktopWindows=lambda: []), 'CbbManagement_test'))
class Foreign:
def __setattr__(self, key, value):
pytest.fail(f'changed foreign LM property {key}')
def OpenLibrary(self, *_):
pytest.fail('opened target from a foreign LM')
def Quit(self):
pytest.fail('quit foreign LM')
monkeypatch.setattr(win32com.client, 'DispatchEx', lambda _: Foreign())
result = native._catalog_com({'operation': 'catalog', 'worker_role': 'catalog_readonly',
'include_engineering_identity': False, 'library': str(target),
'desktop': 'CbbManagement_test', 'mentor_home': str(tmp_path), 'supervisor_pid': __import__('os').getpid()}, tmp_path)
assert not result['success']
assert result['native_pids'] == []
assert result['no_new_manager'] is True
assert 'LIBRARY_MANAGER_BUSY' in result['detail']
def test_catalog_progress_and_pending_preview_are_visible(qtbot, tmp_path, monkeypatch):
from threading import Event
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.ui import main_window as ui
from test_issue15_ui_integration import load
checked, finish = Event(), Event()
library = tmp_path/'lib.lmc'
library.write_bytes(b'test catalog')
for name in ('A', 'B'):
(tmp_path/'ReusableBlocksLP'/name).mkdir(parents=True)
def status(names, path, checkpoint=None, *, progress=None):
if progress is not None:
progress(1, len(names))
checked.set()
assert finish.wait(5)
checkpoint.parent.mkdir(parents=True, exist_ok=True)
checkpoint.write_text('complete', encoding='utf-8')
return {name: 'READY' for name in names}
monkeypatch.setattr(ui, 'authoritative_status_map', status)
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *_: None)
window = ui.MainWindow(data_root=tmp_path/'data', catalog_reader=lambda path, _: Catalog(
path, 1, tuple(CatalogEntry(name, 'Logical-Physical') for name in ('A', 'B'))))
qtbot.addWidget(window)
window.show()
try:
load(window, qtbot, str(library))
qtbot.waitUntil(checked.is_set)
qtbot.waitUntil(lambda: '已核对 1/2' in window.status_label.text(), timeout=1000)
assert window.ready_names == set()
assert not window.icdb_repair_button.isEnabled()
assert not window.backup_restore_button.isEnabled()
assert not (tmp_path/'data'/'status-refresh.jsonl').exists()
finish.set()
qtbot.waitUntil(lambda: window.ready_names == {'A', 'B'})
finally:
finish.set()
window.pool.waitForDone(6000)
def test_timed_out_catalog_can_refresh_already_registered_status_only(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
from cbb_refresh_verify.ui import main_window as ui
from test_issue15_ui_integration import load, window_for
calls = []
still_active = []
def catalog(library, _):
calls.append(library)
if len(calls) > 1:
raise native.NativeOperationError('LIBRARY_MANAGER_BUSY: PID 123', safe_to_continue=True,
blocking_manager_pids=(123,))
return Catalog(library, 1, (CatalogEntry('A', 'Logical-Physical'),))
monkeypatch.setattr(ui, 'CATALOG_MANAGER_WAIT_SECONDS', 0, raising=False)
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'), CbbRecord('Ghost', 'LP')), directory_count=2),
catalog_reader=catalog, status_refresher=lambda names, _: (
still_active.append(tuple(names)) or {name: ('READY' if len(calls) == 1 else 'PENDING') for name in names}))
try:
load(window, qtbot)
qtbot.waitUntil(lambda: window.ready_names == {'A'})
window.load_button.click()
qtbot.waitUntil(lambda: window.load_button.text() == '重试读取')
assert window.ready_names == {'A'}
assert not window.batch_button.isEnabled()
window.catalog_status_button.click()
qtbot.waitUntil(lambda: window._records_by_name['A'].status == 'PENDING')
assert window._records_by_name['Ghost'].status == 'UNKNOWN'
assert not window.batch_button.isEnabled()
assert len(calls) == 2 and still_active == [('A',), ('A',)]
assert window.loaded_path is None
finally:
window.pool.waitForDone(6000)
def test_catalog_switch_retains_complete_snapshot_and_ignores_duplicate_reads(qtbot, tmp_path, monkeypatch):
from threading import Event
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.ui import main_window as ui
from test_issue15_ui_integration import load
paths = {name: tmp_path/name/'lib.lmc' for name in ('A', 'B')}
for name, library in paths.items():
(library.parent/'ReusableBlocksLP'/name).mkdir(parents=True)
library.write_bytes(b'catalog')
reading, allow_return = Event(), Event()
calls = []
def catalog(path, _):
calls.append(path.parent.name)
if path == paths['B']:
reading.set()
assert allow_return.wait(5)
return Catalog(path, 1, (CatalogEntry(path.parent.name, 'Logical-Physical'),))
def statuses(names, path, checkpoint=None, *, progress=None):
checkpoint.parent.mkdir(parents=True, exist_ok=True)
checkpoint.write_text(path.parent.name, encoding='utf-8')
return {name: 'READY' for name in names}
monkeypatch.setattr(ui, 'authoritative_status_map', statuses)
monkeypatch.setattr(ui, 'preflight_skip_reason', lambda *_: None)
window = ui.MainWindow(data_root=tmp_path/'data', catalog_reader=catalog)
qtbot.addWidget(window)
window.show()
try:
load(window, qtbot, str(paths['A']))
qtbot.waitUntil(lambda: window.ready_names == {'A'})
load(window, qtbot, str(paths['B']))
qtbot.waitUntil(reading.is_set)
window.load_button.click()
assert window.ready_names == {'A'}
assert str(paths['A']) in window.library_notice.text()
assert not window.batch_button.isEnabled()
allow_return.set()
qtbot.waitUntil(lambda: window.ready_names == {'B'})
assert calls == ['A', 'B']
assert (tmp_path/'data/status-refresh.jsonl').read_text('utf-8') == 'B'
finally:
allow_return.set()
window.pool.waitForDone(6000)
def test_catalog_read_submitted_during_restart_releases_then_reads(qtbot, tmp_path, monkeypatch):
from threading import Event
from cbb_refresh_verify import session_record
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
from test_issue15_ui_integration import load, window_for
released = Event()
calls = []
def catalog(library, evidence):
assert released.is_set()
calls.append(library)
return Catalog(library, 1, (CatalogEntry('A', 'Logical-Physical'),))
monkeypatch.setattr(session_record, '_live_library_available', lambda _: released.is_set())
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
catalog_reader=catalog, status_refresher=lambda names, _: {name: 'READY' for name in names})
try:
load(window, qtbot)
qtbot.waitUntil(lambda: '等待后台会话退出' in window.status_label.text())
assert calls == []
assert window.lmc_edit.isEnabled()
assert not window.batch_button.isEnabled()
released.set()
window.native_queue.wake()
qtbot.waitUntil(lambda: window.ready_names == {'A'})
assert len(calls) == 1
finally:
released.set()
window.native_queue.wake()
window.pool.waitForDone(6000)
+101
View File
@@ -0,0 +1,101 @@
from contextlib import contextmanager
import json
import pytest
from cbb_refresh_verify import verify_runner
@pytest.mark.parametrize('scenario', ['retry', 'pending', 'no-binding-change', 'still-occupied',
'before-save-only', 'other-engineering-error'])
def test_local_cell_library_failure_retries_once_only_after_bound_release(tmp_path, monkeypatch, scenario):
from cbb_refresh_verify import library_lock
library = tmp_path / 'lib.lmc'
library.write_bytes(b'isolated library')
work = tmp_path / 'ReusableBlocksLP/A/Work'
project = work / 'A.prj'
pcb = work / 'PCB/A.pcb'
config = pcb.with_name('pcb.prj')
layout = pcb.parent / 'Layout/LayoutDB.lyt'
cache = pcb.parent / 'Work/Layout_Temp'
prefs = cache / 'JobPrefsDB.jpf'
for path in (layout, prefs, work / 'database/icdb.dat'):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'original-' + path.name.encode('ascii'))
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "database"\n', encoding='utf-8')
pcb.write_text('KEY ProjectFile "../A.prj"\n', encoding='utf-8')
config.write_text('KEY CentralLibrary "../../../../lib.lmc"\n', encoding='utf-8')
(cache / 'CellDB.cel').write_bytes(b'old generated cell library')
first, second = tmp_path / 'first', tmp_path / 'second'
first.mkdir()
second.mkdir()
original = first / 'result.json'
original.write_text('{"status":"FAIL"}', encoding='utf-8')
new_evidence = second / 'result.json'
new_evidence.touch()
error = (f'Project Integration error: ERROR: Could not load Job Preferences DB [{prefs}] | '
'ERROR: Unable to create local Cell Library.')
if scenario == 'other-engineering-error':
error = 'Project Integration error: generic failure'
events = [
{'stage': 'central_library_path', 'status': 'MATCH' if scenario == 'no-binding-change' else 'UPDATED',
'path': str(config), 'target': str(library)},
{'stage': 'identity_verified', 'project': str(project), 'document': pcb.name},
{'stage': 'integration_error', 'detail': error},
]
if scenario == 'before-save-only':
events.append({'stage': 'save_start'})
(first / 'events.jsonl').write_text(''.join(json.dumps(e) + '\n' for e in events), encoding='utf-8')
job = dict(lmc_file=str(library), block_name='A', project=str(project), pcb=str(pcb),
operation_id='fixture-operation', root=str(first))
(first / 'request.json').write_text(json.dumps(job), encoding='utf-8')
if scenario != 'no-binding-change':
from cbb_refresh_verify.local_cell_library import capture_binding_change
capture_binding_change(job, config, lambda **_: None)
initial = verify_runner.VerifyResult('FAIL', stderr=error,
error_category=verify_runner.classify_failure_category(error), evidence_path=original,
safe_to_continue=True, timings_seconds={'total': 2.0})
@contextmanager
def prove(library_path, *, block_name, **_):
assert library_path == library and block_name == 'A'
if scenario == 'still-occupied':
raise library_lock.LibraryBusy('Occupied fixture')
yield {'blocked_resources': [], 'exclusive_files': [str(library), str(layout)], 'signatures': {}}
calls = []
def verify(request, **_):
calls.append(request.block_name)
if len(calls) == 1:
return initial
assert not cache.exists()
cache.mkdir()
prefs.write_bytes(b'rebuilt by Mentor')
if scenario == 'pending':
return verify_runner.VerifyResult('FAIL', error_stage='library_flag',
error_category='MENTOR_VERIFY_NOT_COMMITTED', library_flag='NOT_GREEN',
safe_to_continue=True, evidence_path=new_evidence,
write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',
resource_state='RELEASED',interrupted=False))
return verify_runner.VerifyResult('PASS', library_flag='GREEN', evidence_path=new_evidence,
safe_to_continue=True, timings_seconds={'total': 3.0})
monkeypatch.setattr(library_lock, '_prove_library_released', prove)
monkeypatch.setattr(library_lock, 'recheck_previous_release', lambda *_, **__: None)
monkeypatch.setattr(verify_runner, '_run_verify_serialized', verify)
result = verify_runner._run_verify_task(verify_runner.VerifyRequest(library, 'A', tmp_path))
assert original.read_text(encoding='utf-8') == '{"status":"FAIL"}'
assert layout.read_bytes() == b'original-LayoutDB.lyt'
if scenario in {'retry', 'pending'}:
assert calls == ['A', 'A']
receipt = json.loads((first / 'local-cell-library-retry.json').read_text(encoding='utf-8'))
assert prefs.read_bytes() == b'rebuilt by Mentor'
assert result.status == ('PASS' if scenario == 'retry' else 'FAIL')
assert receipt['initial_evidence'] == str(original)
assert receipt['retry_evidence'] == str(new_evidence)
assert (work.parent / receipt['preserved_name'] / 'JobPrefsDB.jpf').read_bytes() == b'original-JobPrefsDB.jpf'
else:
assert calls == ['A']
assert prefs.read_bytes() == b'original-JobPrefsDB.jpf'
+179
View File
@@ -0,0 +1,179 @@
"""Regression checks for read-only admission and cancel/retry handoff."""
from pathlib import Path
from threading import Event
import pytest
from cbb_refresh_verify import desktop_worker, library_lock, session_record
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, QueueUnavailable
def test_read_only_catalog_registers_without_reusing_retained_writer_lease(monkeypatch):
registrations = []
monkeypatch.setattr(library_lock, 'duplicate_worker_lease', lambda *a:
pytest.fail('read-only catalog must not duplicate a writer lease'))
monkeypatch.setattr(session_record, 'register_worker_session', lambda worker, job:
registrations.append(job))
worker = type('Worker', (), {'handle': object()})()
desktop_worker.DesktopWorker.bind_session(worker, dict(
operation='catalog', worker_role='catalog_readonly', library='target.lmc'))
assert registrations[0]['worker_lease_handle'] is None
def test_waiting_rerun_yields_queue_to_independent_library(monkeypatch):
from concurrent.futures import ThreadPoolExecutor
released, waiting = Event(), Event()
queue = NativeQueue()
monkeypatch.setattr(session_record, '_live_library_available',
lambda library: library != 'target.lmc' or released.is_set())
with ThreadPoolExecutor(1) as pool:
result = pool.submit(queue.run, lambda: 'target admitted',
context=BatchTaskContext('target.lmc'),
waiting=waiting.set, wait_for_release_seconds=2)
assert waiting.wait(1)
assert queue.run(lambda: 'independent admitted',
context=BatchTaskContext('other.lmc')) == 'independent admitted'
released.set()
queue.wake()
assert result.result(1) == 'target admitted'
def test_unreleased_retry_expires_before_action_starts(monkeypatch):
monkeypatch.setattr(session_record, '_live_library_available', lambda _: False)
monkeypatch.setattr(session_record, 'retained_session_states', lambda _: [
{'operation_id': 'cancelled-operation', 'block': 'OldBlock', 'path': 'original/session.json',
'blocked_resources': ['shared/icdb.dat']}])
with pytest.raises(QueueUnavailable) as caught:
NativeQueue().run(lambda: pytest.fail('unsafe native admission'),
context=BatchTaskContext('target.lmc'), wait_for_release_seconds=.02)
assert 'OldBlock' in str(caught.value)
assert 'shared/icdb.dat' in str(caught.value)
assert caught.value.sessions[0]['path'] == 'original/session.json'
def test_catalog_recovery_only_adopts_an_exact_exited_supervisor(tmp_path, monkeypatch):
import json
from cbb_refresh_verify import residual_sessions
path = tmp_path/'session.json'
library = tmp_path/'library.lmc'
identity = dict(pid=55, image='original.exe', created_handle='created', owner_sid='owner', session_id=1)
record = dict(operation_id='catalog-crash', operation='catalog', worker_role='catalog_readonly',
desktop='CbbManagement_recovery', library=str(library), block=None,
supervisor_identity=identity)
session_record.write_session_record(path, record)
job = dict(record, supervisor_pid=55, session_record_path=str(path))
(tmp_path/'request.json').write_text(json.dumps(job), encoding='utf-8')
monkeypatch.setattr(residual_sessions, '_recorded_process_exited', lambda found: found == identity)
assert residual_sessions.recoverable_orphan_session(path)
job['supervisor_identity'] = {**identity, 'pid': 56}
(tmp_path/'request.json').write_text(json.dumps(job), encoding='utf-8')
assert not residual_sessions.recoverable_orphan_session(path)
def test_idle_orphan_catalog_can_close_without_final_result(tmp_path, monkeypatch):
from test_owned_idle_cleanup import owned_fixture
from cbb_refresh_verify import residual_sessions
root, job, _, _, state = owned_fixture(tmp_path, monkeypatch, 'catalog')
(root/'result.json').unlink()
monkeypatch.setattr(residual_sessions, 'recoverable_orphan_session', lambda _: True, raising=False)
session_record.write_session_record(root/'worker-state.json',
dict(operation_id='owned', phase='NATIVE_CALL', processes=[dict(role='native', pid=12,
created_handle='native-created', image='D:/Mentor/LibraryManager.exe', owner_sid='owner', session_id=1)]))
assert not residual_sessions.finish_owned_idle_session(root/'session.json')
worker_state = session_record.read_session_record(root/'worker-state.json', evidence_root=root)
session_record.write_session_record(root/'worker-state.json', {**worker_state, 'phase': 'POSTCALL'})
assert residual_sessions.finish_owned_idle_session(root/'session.json')
assert state['posts'] == [(100, 12, 16)]
def test_recheck_archives_exited_catalog_only_after_fresh_proof(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
library = tmp_path/'lib.lmc'
library.touch()
session = dict(operation_id='finished-catalog', operation='catalog', library=str(library),
status='UNCONFIRMED', processes_exited=True, detail='待核对',
path=str(tmp_path/'history/session.json'), recorded_at='2026-11-23T00:00:00Z',
processes=[dict(role='native', pid=111)])
proven = set()
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda *_: {'library': str(library), 'sessions': []})
monkeypatch.setattr(session_record, 'discover_sessions',
lambda *a, **kw: [] if proven else [session, session.copy()])
monkeypatch.setattr(session_record, 'retained_session_states', lambda _: [])
monkeypatch.setattr(session_record, 'reconcile_session_record',
lambda path, **kw: proven.add(path) or {'status': 'RELEASED', 'release_proof': {'status': 'RELEASE_CONFIRMED'}})
archived = []
monkeypatch.setattr(session_record, 'record_session_release', lambda proof, rows: archived.extend(rows) or [])
dialog = ResidualReleaseDialog(library, tmp_path/'release-checks')
qtbot.addWidget(dialog)
qtbot.waitUntil(lambda: not dialog.busy)
assert not proven
assert dialog.runtime_label.text().count('PID 111') == 1
dialog.refresh_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert len(proven) == 1 and archived == [session] and not dialog.runtime_label.text()
@pytest.mark.parametrize(('phase', 'safe', 'exited', 'hidden'), [
('FINISHED', True, True, True),
('FINISHED', True, False, False),
('POSTCALL', True, True, False),
('UNCONFIRMED', False, True, False),
])
def test_discovery_hides_only_completed_read_only_catalog(tmp_path, monkeypatch, phase, safe, exited, hidden):
import json
record = tmp_path/'session.json'
library = tmp_path/'lib.lmc'
session_record.write_session_record(record, dict(operation_id='catalog-result',
operation='catalog', worker_role='catalog_readonly', library=str(library), block=None))
(tmp_path/'result.json').write_text(json.dumps({'safe_to_continue': safe}), encoding='utf-8')
monkeypatch.setattr(session_record, 'inspect_session_record', lambda *a, **kw: {
'status': 'UNCONFIRMED' if exited else 'ACTIVE', 'phase': phase,
'processes_exited': exited,
})
found = session_record.discover_sessions(tmp_path)
assert bool(found) == (not hidden)
@pytest.mark.parametrize('proved', [True, False])
def test_cancelled_prewrite_can_dismiss_exact_late_load_failure(qtbot, tmp_path, monkeypatch, proved):
import json
from contextlib import nullcontext
from types import SimpleNamespace
from test_owned_idle_cleanup import owned_fixture
from cbb_refresh_verify import failed_session, residual_sessions
root, job, result, windows, state = owned_fixture(tmp_path, monkeypatch)
result.update(status='CANCELLED', error_category='TASK_HANDOFF', write_outcome=None)
(root/'result.json').write_text(json.dumps(result), encoding='utf-8')
frame = windows[0]
frame['documents'] = [99]
windows.append(dict(hwnd=200, title='Expedition PCB', desktop=job['desktop'], children=[],
enabled=True, **{'class': '#32770'}))
baseline = {'started_ns': 123}
monkeypatch.setattr(failed_session, 'cancelled_prewrite_startup', lambda *a: baseline if proved else None)
monkeypatch.setattr(residual_sessions, '_window_desktop', lambda *a, **kw: nullcontext())
monkeypatch.setattr(failed_session, '_startup_snapshot', lambda *a: 'exact load failure')
monkeypatch.setattr(failed_session, '_cancel_target',
lambda _: ('database_load_log', SimpleNamespace(handle=201)))
def post(window, hwnd, pid, message):
state['posts'].append((hwnd, pid, message))
if hwnd == 201:
windows.pop()
frame['documents'].clear()
else:
state['native_alive'] = False
ticks = [0.]
monkeypatch.setattr(residual_sessions.time, 'monotonic', lambda: ticks[0])
monkeypatch.setattr(residual_sessions.time, 'sleep', lambda delay: ticks.__setitem__(0, ticks[0]+delay))
monkeypatch.setattr(residual_sessions, '_post_window_message', post)
original = (root/'result.json').read_bytes()
assert residual_sessions.finish_owned_idle_session(root/'session.json') is proved
assert state['posts'] == ([(201, 12, 245), (100, 12, 16)] if proved else [])
assert (root/'result.json').read_bytes() == original
+30
View File
@@ -28,3 +28,33 @@ def test_batch_rechecks_owned_failure_before_skipping_next_item(tmp_path,monkeyp
assert results[0].status=='FAIL' and results[0].stderr=='original failure' assert results[0].status=='FAIL' and results[0].stderr=='original failure'
assert results[0].safe_to_continue is released assert results[0].safe_to_continue is released
assert calls==(['A','B'] if released else ['A']) assert calls==(['A','B'] if released else ['A'])
def test_batch_rechecks_admission_after_timeout_and_real_release(tmp_path, monkeypatch):
from cbb_refresh_verify import session_record
from cbb_refresh_verify.operation_queue import QueueUnavailable
library = tmp_path/'first/lib.lmc'
independent = tmp_path/'second/lib.lmc'
occupied = True
admission_calls = []
def available(path):
return Path(path) != library or not occupied
def admit(request, action):
nonlocal occupied
admission_calls.append(request.block_name)
if not available(request.lmc_file):
raise QueueUnavailable(request.lmc_file, timed_out=True)
if request.block_name == 'B':
occupied = False
return action()
monkeypatch.setattr(session_record, '_live_library_available', available)
requests = [VerifyRequest(lmc, name, tmp_path/'evidence')
for name, lmc in [('A', library), ('A2', library), ('B', independent), ('C', library)]]
results = run_batch(requests, verifier=lambda _: VerifyResult('PASS'), item_executor=admit)
assert admission_calls == ['A', 'B', 'C']
assert [result.status for result in results] == ['SKIPPED', 'SKIPPED', 'PASS', 'PASS']
assert results[0].error_category == 'NATIVE_SESSION_PENDING'
+12
View File
@@ -593,3 +593,15 @@ def test_same_target_recovery_gate_preserves_release_and_batch_continues(setup,
adapter=adapter, idle_check=lambda *_: None) adapter=adapter, idle_check=lambda *_: None)
assert [result.status for result in results] == ['BLOCKED', 'UPLOADED'] assert [result.status for result in results] == ['BLOCKED', 'UPLOADED']
assert all(result.safe_to_continue for result in results) assert all(result.safe_to_continue for result in results)
@pytest.mark.parametrize('same_library', [True, False])
def test_release_scope_binds_native_shared_database_argument(tmp_path, same_library):
from cbb_refresh_verify.icdb_ownership import shared_symbol_database
from cbb_refresh_verify.library_lock import _owner_matches_scope
library = tmp_path/'Target/lib.lmc'
target = shared_symbol_database(library)
database = target if same_library else shared_symbol_database(tmp_path/'Foreign/lib.lmc')
owner = {'name': 'iCDBNetServer.exe', 'command': f'iCDBNetServer.exe -db "{database}"'}
assert _owner_matches_scope(owner, library, (target,)) is same_library
+1
View File
@@ -228,6 +228,7 @@ def test_confirmed_native_close_transfers_mapping_to_current_library(qtbot, tmp_
path_lease=old, process=SimpleNamespace(poll=lambda: 0)) path_lease=old, process=SimpleNamespace(poll=lambda: 0))
window._poll_native_backup(); qtbot.waitUntil(lambda: not window.busy) window._poll_native_backup(); qtbot.waitUntil(lambda: not window.busy)
assert window._native_backup_session is None assert window._native_backup_session is None
qtbot.waitUntil(lambda: window._lease_pending == 0)
assert backend.cancelled == [] and current.created assert backend.cancelled == [] and current.created
window.close() window.close()
qtbot.waitUntil(lambda: backend.cancelled == [current.drive]) qtbot.waitUntil(lambda: backend.cancelled == [current.drive])
+5 -1
View File
@@ -813,7 +813,11 @@ def test_malformed_native_success_never_authorizes_release(tmp_path, monkeypatch
assert result['safe_to_continue'] is False assert result['safe_to_continue'] is False
@pytest.mark.parametrize('key,value', MALFORMED_SUCCESS) @pytest.mark.parametrize('key,value', [
('minimal', None),
('project', '<other>/CBB.prj'),
('evidence.confirmed', False),
])
def test_malformed_native_success_never_reopens_or_counts_repaired(tmp_path, monkeypatch, key, value): def test_malformed_native_success_never_reopens_or_counts_repaired(tmp_path, monkeypatch, key, value):
from cbb_refresh_verify import verify_runner as runner, native_repair from cbb_refresh_verify import verify_runner as runner, native_repair
from cbb_refresh_verify.icdb_maintenance import maintenance_counts from cbb_refresh_verify.icdb_maintenance import maintenance_counts
+32
View File
@@ -40,3 +40,35 @@ def test_cancelled_paused_ticket_does_not_hold_later_work():
assert outcome==['cancelled','next'] assert outcome==['cancelled','next']
finally: finally:
stop.set();queue.wake();thread.join(2) stop.set();queue.wake();thread.join(2)
def test_saved_database_wait_yields_only_to_other_library_roots(tmp_path):
from concurrent.futures import ThreadPoolExecutor
from threading import Event
from cbb_refresh_verify.operation_queue import BatchTaskContext, allow_other_libraries
queue = NativeQueue()
waiting, released = Event(), Event()
same_directory_started = Event()
current = BatchTaskContext(str(tmp_path/'first/a.lmc'))
same_directory = BatchTaskContext(str(tmp_path/'first/b.lmc'))
independent = BatchTaskContext(str(tmp_path/'second/c.lmc'))
def saved():
with allow_other_libraries():
waiting.set()
assert released.wait(4)
return 'confirmed'
with ThreadPoolExecutor(max_workers=3) as threads:
first = threads.submit(queue.run, saved, context=current)
assert waiting.wait(2)
second = threads.submit(queue.run, same_directory_started.set, context=same_directory)
try:
third = threads.submit(queue.run, lambda: 'independent', context=independent)
assert third.result(timeout=2) == 'independent'
assert not same_directory_started.is_set()
finally:
released.set()
assert first.result(timeout=2) == 'confirmed'
second.result(timeout=2)
assert same_directory_started.is_set()
+282
View File
@@ -0,0 +1,282 @@
"""Finish a proved owned idle client, then prove resources independently."""
from contextlib import nullcontext
from dataclasses import replace
import json
from pathlib import Path
from threading import Event
import pytest
from cbb_refresh_verify import residual_sessions as residual, session_record as sessions
from cbb_refresh_verify import operation_lifecycle as lifecycle
from cbb_refresh_verify.verify_runner import VerifyResult
def owned_fixture(tmp_path, monkeypatch, kind='startup'):
import win32con, win32event
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
root=tmp_path/'evidence';root.mkdir()
operation='catalog' if kind=='catalog' else 'verify'
desktop=('CbbManagement_' if kind=='catalog' else 'CbbVerify_')+'owned'
job=dict(operation_id='owned',operation=operation,library=str(library),lmc_file=str(library),
block='Bad',root=str(root),desktop=desktop,interactive_input=False,
project=str(library.parent/'ReusableBlocksLP/Bad/Work/Bad.prj'),
pcb=str(library.parent/'ReusableBlocksLP/Bad/Work/PCB/Bad.pcb'),
session_record_path=str(root/'session.json'))
if kind=='catalog':job['worker_role']='catalog_readonly'
worker=dict(role='worker',pid=11,created_handle='worker-created',image='C:/Python/python.exe',
owner_sid='owner',session_id=1)
native=dict(role='native',pid=12,created_handle='native-created',
image='D:/Mentor/LibraryManager.exe' if kind=='catalog' else 'D:/Mentor/ExpeditionPCB.exe',
owner_sid='owner',session_id=1)
sessions.write_session_record(root/'session.json',dict(operation_id='owned',operation=operation,
library=str(library),block='Bad',desktop=desktop,processes=[worker]))
sessions.write_session_record(root/'worker-state.json',dict(operation_id='owned',phase='UNCONFIRMED',processes=[native]))
result=dict(status='FAIL',safe_to_continue=False,error_stage='PCB_STARTING',
error_category='MENTOR_DATABASE_LOAD_FAILED',block_name='Bad',evidence_path=str(root/'result.json'))
if kind=='saved':
result.update(error_stage='library_flag',error_category='MENTOR_VERIFY_NOT_COMMITTED',
write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',interrupted=False))
if kind=='catalog':result=dict(success=False,safe_to_continue=False,detail='catalog close failed')
(root/'request.json').write_text(json.dumps(job))
(root/'result.json').write_text(json.dumps(result))
windows=[dict(hwnd=100,**{'class':'Afx:main'},title='Library Manager' if kind=='catalog' else 'Expedition PCB',
desktop=desktop,enabled=True,documents=[],children=[])]
state=dict(worker_alive=False,native_alive=True,identity_changed=False,posts=[])
monkeypatch.setattr(residual,'_process_handle',lambda pid,**kw:nullcontext(pid))
monkeypatch.setattr(residual,'_handle_identity',lambda handle:
{k:(('replacement' if state['identity_changed'] else v) if k=='created_handle' else v)
for k,v in (worker if handle==11 else native).items() if k in ('created_handle','image')})
monkeypatch.setattr(residual,'_force_ownership',lambda *a:dict(force_user_confirmed=True,owner_sid='owner',session_id=1))
monkeypatch.setattr(residual,'_process_windows',lambda *a,**kw:{12:windows})
monkeypatch.setattr(sessions,'active_write_records',lambda library:[])
wait=win32event.WaitForSingleObject
monkeypatch.setattr(win32event,'WaitForSingleObject',lambda handle,ms:
(win32con.WAIT_TIMEOUT if state['worker_alive' if handle==11 else 'native_alive'] else win32con.WAIT_OBJECT_0)
if handle in (11,12) else wait(handle,ms))
def post(window, hwnd, pid, message):
record=sessions.read_session_record(root/'session.json',evidence_root=root)
assert record.get('owned_idle_cleanup'), 'intent must be durable before native action'
state['posts'].append((hwnd,pid,message))
state['native_alive']=False
monkeypatch.setattr(residual,'_post_window_message',post)
return root,job,result,windows,state
@pytest.mark.parametrize('kind',['startup','saved','catalog'])
def test_owned_idle_client_is_closed_once_without_changing_business_result(tmp_path,monkeypatch,kind):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch,kind)
before=(root/'result.json').read_bytes()
assert residual.finish_owned_idle_session(root/'session.json')
assert state['posts']==[(100,12,16)] and not state['native_alive']
residual.finish_owned_idle_session(root/'session.json')
assert state['posts']==[(100,12,16)]
assert (root/'result.json').read_bytes()==before
@pytest.mark.parametrize('obstacle',['worker_alive','identity_changed','documents','hidden_document','unknown',
'progress','desktop','request_identity','save_unknown','other_write','stopped','claim_io','window_race'])
def test_unproved_or_writing_client_is_never_automatically_closed(tmp_path,monkeypatch,obstacle):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch)
stop=Event()
if obstacle in ('worker_alive','identity_changed'):state[obstacle]=True
if obstacle=='documents':windows[0]['documents']=[55]
if obstacle=='hidden_document':windows[0]['children'].append(dict(hwnd=55,**{'class':'Afx:document'},visible=False))
if obstacle=='unknown':windows.append(dict(hwnd=200,**{'class':'#32770'},title='Unknown',enabled=True,desktop=job['desktop'],documents=[],children=[]))
if obstacle=='progress':windows[0]['children'].append(dict(hwnd=60,**{'class':'msctls_progress32'}))
if obstacle=='desktop':windows[0]['desktop']='Default'
if obstacle=='request_identity':
job['operation_id']='other';(root/'request.json').write_text(json.dumps(job))
if obstacle=='save_unknown':(root/'save.log').write_text('SAVE_START\n')
if obstacle=='other_write':monkeypatch.setattr(sessions,'active_write_records',lambda _: [dict(operation_id='other')])
if obstacle=='stopped':stop.set()
if obstacle=='claim_io':
monkeypatch.setattr(sessions,'write_session_record',lambda *a,**kw: (_ for _ in ()).throw(OSError('journal unavailable')))
if obstacle=='window_race':
original=sessions.write_session_record
def write(path,value):
original(path,value)
if value.get('owned_idle_cleanup'):windows[0]['documents']=[55]
monkeypatch.setattr(sessions,'write_session_record',write)
residual.finish_owned_idle_session(root/'session.json',stop=stop)
assert not state['posts'] and state['native_alive']
def test_late_release_actively_finishes_owned_idle_client_then_proves_shared_files(tmp_path,monkeypatch):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch)
monkeypatch.setattr(sessions,'inspect_session_record',lambda *a,**kw:
dict(status='ACTIVE' if state['native_alive'] else 'UNCONFIRMED'))
def release(library,evidence,**kw):
assert not state['native_alive'], 'resource proof must follow native cleanup'
return dict(status='RELEASE_CONFIRMED',lease_state='RELEASED',library=library,
blocked_resources=[],resource_scope=dict(scope_state='OBSERVED'))
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library',release)
failed=VerifyResult('FAIL',stderr='database load failed',safe_to_continue=False,
evidence_path=root/'result.json')
updated=lifecycle.recheck_failed_release(job['library'],'Bad',failed)
assert updated.status=='FAIL' and updated.safe_to_continue
assert state['posts']==[(100,12,16)]
def test_closed_client_does_not_imply_shared_database_released(tmp_path,monkeypatch):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch)
monkeypatch.setattr(sessions,'inspect_session_record',lambda *a,**kw:
dict(status='ACTIVE' if state['native_alive'] else 'UNCONFIRMED'))
from cbb_refresh_verify.library_lock import LibraryBusy
def release(*a,**kw):raise LibraryBusy('shared database still held by another client')
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library',release)
failed=VerifyResult('FAIL',safe_to_continue=False,evidence_path=root/'result.json')
updated=lifecycle.recheck_failed_release(job['library'],'Bad',failed)
assert not updated.safe_to_continue and updated.status=='FAIL'
assert state['posts']==[(100,12,16)]
attempt=json.loads((root/'late-release-attempt.json').read_text())
assert 'shared database' in attempt['detail']
def test_retained_verify_lease_does_not_expand_one_target_to_every_cbb(tmp_path,monkeypatch):
from cbb_refresh_verify import verify_runner as runner, library_lock as locks
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
other=library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
other.parent.mkdir(parents=True);other.write_text('unrelated occupied engineering database')
evidence=tmp_path/'evidence/result.json';evidence.parent.mkdir()
evidence.write_text('{}')
monkeypatch.setattr(runner,'_run_verify_serialized',lambda *a,**kw:
VerifyResult('FAIL',safe_to_continue=False,evidence_path=evidence))
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:[])
result=runner._run_verify_task(runner.VerifyRequest(library,'Bad',evidence.parent))
assert not result.safe_to_continue
try:
proof=locks.release_retained_library(library,tmp_path/'release',block_name='Bad')
assert proof['proof_scope']=='BLOCK' and proof['proof_block_name']=='Bad'
assert other.read_text()=='unrelated occupied engineering database'
finally:
with locks._guard:
owner=locks._owners.pop(locks.LibraryLock(library).key,None)
if owner:owner['handle'].Close()
@pytest.mark.parametrize('read_only',[False,True])
def test_background_observer_finishes_owned_idle_client_but_cold_observation_stays_read_only(tmp_path,monkeypatch,read_only):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch)
def reconcile(*a,**kw):
return dict(status='ACTIVE' if state['native_alive'] else 'RELEASED',operation_id='owned',
library=job['library'],block='Bad',release_proof=None)
monkeypatch.setattr(sessions,'_reconcile',reconcile)
stop=Event()
outcome=sessions.observe_retained_session(root/'session.json',evidence_root=root,
observe_only=read_only,stop=stop,progress=lambda value:stop.set())
assert outcome['status']==('ACTIVE' if read_only else 'RELEASED')
assert state['posts']==([] if read_only else [(100,12,16)])
def test_real_shared_database_handle_still_prevents_release_after_own_client_exits(tmp_path,monkeypatch):
import win32con,win32file
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch)
library=Path(job['library'])
shared=library.parent/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
shared.parent.mkdir(parents=True);shared.write_bytes(b'actual shared database fixture')
monkeypatch.setattr(sessions,'inspect_session_record',lambda *a,**kw:
dict(status='ACTIVE' if state['native_alive'] else 'UNCONFIRMED'))
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:[])
held=win32file.CreateFile(str(shared),win32con.GENERIC_READ,0,None,win32con.OPEN_EXISTING,0,None)
try:
failed=VerifyResult('FAIL',safe_to_continue=False,evidence_path=root/'result.json')
updated=lifecycle.recheck_failed_release(library,'Bad',failed)
assert state['posts']==[(100,12,16)] and not updated.safe_to_continue
attempt=json.loads((root/'late-release-attempt.json').read_text())
assert 'icdb.dat' in attempt['detail']
assert attempt['status']=='IN_USE' and attempt['blocked_resources']==[str(shared)]
finally:
held.Close()
@pytest.mark.parametrize('malformed',['request','result','write_outcome'])
def test_malformed_record_never_authorizes_or_crashes_cleanup(tmp_path,monkeypatch,malformed):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch,'saved')
if malformed=='write_outcome':
result['write_outcome']=['not facts'];(root/'result.json').write_text(json.dumps(result))
else:
(root/(malformed+'.json')).write_text('[]')
assert not residual.finish_owned_idle_session(root/'session.json')
assert not state['posts']
@pytest.mark.parametrize('changed',['result_block','result_path','state_after_claim'])
def test_wrong_result_or_changed_state_cannot_authorize_normal_close(tmp_path,monkeypatch,changed):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch,'saved')
if changed=='result_block':result['block_name']='Other'
if changed=='result_path':result['evidence_path']=str(tmp_path/'other/result.json')
(root/'result.json').write_text(json.dumps(result))
if changed=='state_after_claim':
write=sessions.write_session_record
def changed_state(path,record):
write(path,record)
if record.get('owned_idle_cleanup'):
previous=sessions.read_session_record(root/'worker-state.json',evidence_root=root)
write(root/'worker-state.json',{**previous,'phase':'NATIVE_CALL'})
monkeypatch.setattr(sessions,'write_session_record',changed_state)
assert not residual.finish_owned_idle_session(root/'session.json')
assert not state['posts']
@pytest.mark.parametrize('terminal', [True, False])
def test_save_handoff_uses_terminal_worker_receipt(tmp_path, monkeypatch, terminal):
root, _, result, _, state = owned_fixture(tmp_path, monkeypatch, 'saved')
facts = result['write_outcome']
result['write_outcome'] = dict(save_state='UNKNOWN', close_state='UNKNOWN',
helper_state='RUNNING', interrupted=False)
facts['save_close_confirmed'] = terminal
if not terminal:
facts['save_state'] = 'UNKNOWN'
state_path = root/'worker-state.json'
state_record = sessions.read_session_record(state_path, evidence_root=root)
state_record['processes'].append(dict(role='helper', pid=13, image='C:/Windows/cscript.exe',
created_handle='helper-created', owner_sid='owner', session_id=1))
sessions.write_session_record(state_path, {**state_record, 'phase': 'POSTCALL', 'write_outcome': facts})
import pywintypes
def open_process(pid, **kwargs):
if pid == 13:
raise pywintypes.error(87, 'OpenProcess', 'exited')
return nullcontext(pid)
monkeypatch.setattr(residual, '_process_handle', open_process)
result['status'] = 'CANCELLED'
(root/'result.json').write_text(json.dumps(result))
before = (root/'result.json').read_bytes()
assert residual.finish_owned_idle_session(root/'session.json') is terminal
assert bool(state['posts']) is terminal
assert (root/'result.json').read_bytes() == before
def test_crash_after_returned_save_can_close_only_with_matching_supervisor(tmp_path, monkeypatch):
import pywintypes
root, job, result, _, state = owned_fixture(tmp_path, monkeypatch, 'saved')
(root/'result.json').unlink()
journal = root/'session.json'
supervisor = dict(pid=14, image='C:/app/CbbRefreshVerify.exe', created_handle='parent-created',
owner_sid='owner', session_id=1)
session = sessions.read_session_record(journal, evidence_root=root)
sessions.write_session_record(journal, {**session, 'supervisor_identity': supervisor})
state_path = root/'worker-state.json'
journal_state = sessions.read_session_record(state_path, evidence_root=root)
helper = dict(role='helper', pid=13, image='C:/Windows/cscript.exe', created_handle='helper-created',
owner_sid='owner', session_id=1)
sessions.write_session_record(state_path, {**journal_state, 'phase': 'UNCONFIRMED',
'processes': [*journal_state['processes'], helper],
'write_outcome': {**result['write_outcome'], 'save_close_confirmed': True}})
def open_process(pid, **kwargs):
if pid in (13, 14):
raise pywintypes.error(87, 'OpenProcess', 'exited')
return nullcontext(pid)
monkeypatch.setattr(residual, '_process_handle', open_process)
request = root/'request.json'
job.update(supervisor_pid=14, supervisor_identity={**supervisor, 'created_handle': 'other'})
request.write_text(json.dumps(job), encoding='utf-8')
assert not residual.finish_owned_idle_session(journal)
job['supervisor_identity'] = supervisor
request.write_text(json.dumps(job), encoding='utf-8')
assert residual.finish_owned_idle_session(journal)
assert state['posts'] == [(100, 12, 16)]
assert not (root/'result.json').exists()
+30
View File
@@ -90,3 +90,33 @@ def test_full_snapshot_helper_does_not_filter_unknown_descendants(tmp_path, monk
assert len(queries) == 1 and 'WHERE' not in queries[0] assert len(queries) == 1 and 'WHERE' not in queries[0]
row = json.loads(job.with_name('result.json').read_text('utf-8'))['owners'][0] row = json.loads(job.with_name('result.json').read_text('utf-8'))['owners'][0]
assert row['name'] == 'custom-native-child.exe' and row['created'] == 'creation-time' assert row['name'] == 'custom-native-child.exe' and row['created'] == 'creation-time'
@pytest.mark.parametrize('contents', [None, b'broken-json', b'[]', b'\xff'])
def test_readonly_helper_quietly_rejects_unavailable_request(tmp_path, contents):
from cbb_refresh_verify.application import main
request = tmp_path/'request.json'
if contents is not None:
request.write_bytes(contents)
assert main(['--owner-probe', str(request)]) == 1
assert not request.with_name('result.json').exists()
def test_readonly_helper_quietly_exits_when_supervisor_removes_probe(tmp_path, monkeypatch):
from cbb_refresh_verify.owner_probe import owner_probe_main
from types import SimpleNamespace
import win32com.client
probe = tmp_path/'probe'
probe.mkdir()
request = probe/'request.json'
request.write_text('{"names":["ExpeditionPCB.exe"]}', encoding='utf-8')
def enumerate_then_clean(_):
request.unlink()
probe.rmdir()
return []
monkeypatch.setattr(win32com.client, 'GetObject', lambda _: SimpleNamespace(ExecQuery=enumerate_then_clean))
assert owner_probe_main(request) == 1
+16 -3
View File
@@ -14,7 +14,20 @@ def test_spec_packages_adaptive_dialog_rules_and_uia_modules():
assert 'pywinauto' in text assert 'pywinauto' in text
def test_spec_analysis_includes_pywin32_timezone_dynamic_import(): def test_spec_analysis_includes_pywin32_timezone_dynamic_import(tmp_path):
captured = _capture_spec_analysis(tmp_path)
assert 'win32timezone' in captured['hiddenimports']
def test_spec_copies_quick_start_next_to_executable(tmp_path):
target = tmp_path / 'CbbRefreshVerify-Background'
target.mkdir()
_capture_spec_analysis(target)
guide = (target / '使用说明.txt').read_text(encoding='utf-8')
assert 'CbbRefreshVerify.exe' in guide and '--data-root' in guide
def _capture_spec_analysis(target):
from types import SimpleNamespace from types import SimpleNamespace
captured = {} captured = {}
def analysis(*args, **kwargs): def analysis(*args, **kwargs):
@@ -23,6 +36,6 @@ def test_spec_analysis_includes_pywin32_timezone_dynamic_import():
path = Path('packaging/CbbRefreshVerify.spec') path = Path('packaging/CbbRefreshVerify.spec')
namespace = {'SPECPATH': str(path.parent.resolve()), 'Analysis': analysis, namespace = {'SPECPATH': str(path.parent.resolve()), 'Analysis': analysis,
'PYZ': lambda *a, **k: None, 'EXE': lambda *a, **k: None, 'PYZ': lambda *a, **k: None, 'EXE': lambda *a, **k: None,
'COLLECT': lambda *a, **k: None} 'COLLECT': lambda *a, **k: SimpleNamespace(name=str(target))}
exec(compile(path.read_text(encoding='utf-8'), str(path), 'exec'), namespace) exec(compile(path.read_text(encoding='utf-8'), str(path), 'exec'), namespace)
assert 'win32timezone' in captured['hiddenimports'] return captured
+313
View File
@@ -1,3 +1,4 @@
import json
from contextlib import nullcontext from contextlib import nullcontext
from types import SimpleNamespace from types import SimpleNamespace
from dataclasses import replace from dataclasses import replace
@@ -112,3 +113,315 @@ def test_readwrite_choice_rejects_replaced_native_button(tmp_path,monkeypatch):
changed=replace(original,controls=tuple(replace(c,handle=c.handle+1) if c.control_id==6 else c changed=replace(original,controls=tuple(replace(c,handle=c.handle+1) if c.control_id==6 else c
for c in original.controls)) for c in original.controls))
assert controller.handle(changed,(changed,),**kwargs).error_code=='DATABASE_RECOVERY_REQUIRED' assert controller.handle(changed,(changed,),**kwargs).error_code=='DATABASE_RECOVERY_REQUIRED'
@pytest.mark.parametrize('origin', ['user', 'timeout_default'])
@pytest.mark.parametrize('guard_error, control, code', [
(None, 6, ''),
(OSError('共享数据库被占用:SymbolLibs/icdb.dat'), 7, 'PCB_OPEN_SKIPPED'),
(TimeoutError('原生检查超时'), 7, 'PCB_OPEN_SKIPPED'),
])
def test_normal_readwrite_uses_same_resource_check(tmp_path, monkeypatch, origin, guard_error, control, code):
from contextlib import contextmanager
import json
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'owned'})
events = []
@contextmanager
def guard(*_, require_complete_proof=False):
assert require_complete_proof
events.append('probe')
if guard_error is not None:
raise guard_error
yield
events.append('released_probe_handles')
monkeypatch.setattr(consent, 'resource_guard', guard)
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
shown = []
def perform(_, action, phase):
clicked = action['target']['control_id']
events.append(clicked)
return SimpleNamespace(accepted_controls=(clicked,), error_code='', detail='', channel='win32_button_click')
kwargs = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, perform=perform)
controller.handle(snapshot(), (snapshot(),), **kwargs)
assert not events
shown[0].choose('continue', origin=origin)
result = controller.handle(snapshot(), (snapshot(),), **kwargs)
assert result.error_code == code
assert events == (['probe', 'released_probe_handles', control] if guard_error is None else ['probe', control])
if guard_error is not None:
assert str(guard_error) in result.detail
record = json.loads((tmp_path/'pcb-open-user-choice.json').read_text(encoding='utf-8'))
assert record['decision_origin'] == origin
assert record['choice'] == ('continue' if control == 6 else 'skip')
controller.handle(snapshot(), (snapshot(),), **kwargs)
assert events.count(control) == 1
def test_unattended_ordinary_dialog_defaults_to_checking_resources(qtbot):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
from cbb_refresh_verify.ui.pcb_open_dialog import PcbOpenDialog
choice = OpenChoice('A', 'lib.lmc', auto_confirm=True)
dialog = PcbOpenDialog(choice)
qtbot.addWidget(dialog)
assert dialog.defaultButton() is dialog.continue_button
dialog.skip_button.click()
assert choice.decision == 'skip'
assert choice.decision_origin == 'user'
def test_unattended_readwrite_checks_actual_shared_database_handle(tmp_path, monkeypatch):
import win32con
import win32file
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify import owner_probe
library = tmp_path/'lib.lmc'
work = tmp_path/'ReusableBlocksLP/A/Work'
project, pcb = work/'A.prj', work/'PCB/A.pcb'
shared = tmp_path/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
for path in (library, work/'database/icdb.dat', pcb.parent/'Layout/LayoutDB.lyt', shared):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'fixture')
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "database"\n')
pcb.write_text('KEY ProjectFile "../A.prj"\n')
owner = {'target': 'bound'}
monkeypatch.setattr(consent, 'validate_owner', lambda *_: owner)
monkeypatch.setattr(owner_probe, 'query_process_snapshot', lambda: [])
def run(attempt, expected_control):
evidence = tmp_path/attempt
evidence.mkdir()
controller = consent.OpenController(dict(root=str(evidence), block_name='A', lmc_file=str(library),
project=str(project), pcb=str(pcb), desktop='CbbVerify_test'), auto_confirm=True)
shown, actions = [], []
def perform(_, action, phase):
actions.append(action['target']['control_id'])
if expected_control == 6:
handle = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
handle.Close()
return SimpleNamespace(error_code='', accepted_controls=tuple(actions), detail='', channel='win32_button_click')
options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, perform=perform)
controller.handle(snapshot(), (snapshot(),), **options)
shown[0].choose('continue', origin='timeout_default')
result = controller.handle(snapshot(), (snapshot(),), **options)
assert actions == [expected_control], result.detail
return result, evidence
held = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
try:
skipped, evidence = run('occupied', 7)
assert skipped.error_code == 'PCB_OPEN_SKIPPED'
assert str(shared) in skipped.detail
assert not (evidence/'pcb-open-resource-proof.json').exists()
finally:
held.Close()
resumed, evidence = run('released', 6)
assert not resumed.error_code
assert (evidence/'pcb-open-resource-proof.json').is_file()
shared_address = shared.parent/'cdbsvr/sAddress.adr'
shared_address.parent.mkdir()
address_bytes = b'shared-server\n127.0.0.1\n192.168.0.6\n10001\n'
shared_address.write_bytes(address_bytes)
held = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
try:
skipped, _ = run('shared-address-occupied', 7)
assert skipped.error_code == 'PCB_OPEN_SKIPPED'
assert str(shared) in skipped.detail
finally:
held.Close()
unsupported, evidence = run('shared-address-verified-binding', 7)
assert unsupported.error_code == 'PCB_OPEN_SKIPPED'
assert 'SHARED_ICDB_INSPECTION_UNAVAILABLE' in unsupported.detail
denial = json.loads((evidence/'pcb-open-resource-denied.json').read_text(encoding='utf-8'))
assert denial['database'] == str(shared.parent)
assert denial['address'] == str(shared_address)
assert denial['exclusive_file_observed'] is True
assert shared_address.read_bytes() == address_bytes
shared_address.unlink()
from cbb_refresh_verify import native_repair
address = work/'database/cdbsvr/sAddress.adr'
address.parent.mkdir()
address.write_text('recorded address')
verdict = 'NOT_IN_USE'
inspected = []
def inspect(target, root, **kwargs):
assert kwargs['inspection_only'] is True
assert target.project == project and target.database == address.parent.parent
inspected.append(target.database)
output = (f'Loading project file [{project}].\nChecking if project is in use.\n'
+ ("Project is not in use. Full iCDB Project Backup's functionality is available.\n"
"Backup information loaded correctly." if verdict == 'NOT_IN_USE' else 'Project is in use.'))
return dict(status=verdict, repair_required=False, inspection_only=True,
repair_requested=False, native_pid=100, native_exit_code=0,
native_identity=dict(pid=100, created_handle=1, image='iCDBProjectBackup.exe',
owner_sid='test', session_id=1),
release={'native_exited': True}, project=str(project),
database=str(target.database), output=output)
monkeypatch.setattr(native_repair, 'run_native_repair', inspect)
unoccupied, _ = run('address-checked-unoccupied', 6)
assert not unoccupied.error_code and inspected == [address.parent.parent]
verdict = 'IN_USE'
occupied, _ = run('address-checked-occupied', 7)
assert occupied.error_code == 'PCB_OPEN_SKIPPED' and 'PCB_OPEN_DATABASE_IN_USE' in occupied.detail
assert inspected == [address.parent.parent]*2
assert address.read_text() == 'recorded address'
address.unlink()
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "../../../outside"\n')
unbound, _ = run('wrong-project-database', 7)
assert 'iCDBDir' in unbound.detail
def test_stop_during_receipt_never_sends_native_yes(tmp_path, monkeypatch):
from cbb_refresh_verify import management
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify.operation_queue import QueueCancelled
stopped = False
original = management._write_json
def write_choice(path, value):
nonlocal stopped
original(path, value)
stopped = True
def check_active():
if stopped:
raise QueueCancelled('cancelled')
monkeypatch.setattr(management, '_write_json', write_choice)
monkeypatch.setattr('cbb_refresh_verify.operation_queue.check_active', check_active)
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'bound'})
monkeypatch.setattr(consent, 'resource_guard', lambda *_, **__: nullcontext())
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
shown = []
options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append,
perform=lambda *_: pytest.fail('sent during cancellation'))
controller.handle(snapshot(), (snapshot(),), **options)
shown[0].choose('continue')
assert controller.handle(snapshot(), (snapshot(),), **options).error_code == 'USER_CANCELLED'
def test_headless_opt_in_checks_resources_without_presenting_dialog(tmp_path, monkeypatch):
import json
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'bound'})
checked = []
def guard(_, __, *, require_complete_proof):
checked.append(require_complete_proof)
return nullcontext()
monkeypatch.setattr(consent, 'resource_guard', guard)
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
actions = []
def perform(_, action, phase):
actions.append(action['target']['control_id'])
return SimpleNamespace(error_code='', accepted_controls=tuple(actions), detail='', channel='win32_button_click')
result = controller.handle(snapshot(), (snapshot(),), target_pid=20, launcher_pid=10, worker_pid=5,
show=None, perform=perform)
assert not result.error_code
assert checked == [True] and actions == [6]
receipt = json.loads((tmp_path/'pcb-open-user-choice.json').read_text(encoding='utf-8'))
assert receipt['decision_origin'] == 'headless_opt_in'
def test_shared_address_is_bound_to_shared_database_without_a_project_prj(tmp_path):
from cbb_refresh_verify.file_probe import _snapshot
library = tmp_path / 'lib.lmc'
library.write_bytes(b'fixture')
symbols = tmp_path / 'SymbolLibs'
database = symbols / '__ReusableBlocksSymb'
address = database / 'cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('fixture address')
(database / 'icdb.dat').write_bytes(b'fixture')
proof = _snapshot(library, (symbols,))
assert proof['inspection_targets'] == [{
'scope': 'shared_symbols', 'database': str(database), 'address': str(address)
}]
assert str(address) in proof['binding_files']
assert str(database / 'icdb.dat') in proof['exclusive_files']
def test_shared_address_with_matching_native_shutdown_allows_release_and_open(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock, owner_probe, pcb_open_consent
library = tmp_path/'library/lib.lmc'
work = library.parent/'ReusableBlocksLP/A/Work'
project, pcb = work/'A.prj', work/'PCB/A.pcb'
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb'
database = shared/'icdb.dat'
address = shared/'cdbsvr/sAddress.adr'
log = address.parent/'log/2026-11-24 10.51.10-16972/2026.11.24.txt'
for path in (library, work/'database/icdb.dat', pcb.parent/'Layout/LayoutDB.lyt', database, log):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'fixture')
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "database"\n')
pcb.write_text('KEY ProjectFile "../A.prj"\n')
guid = 'e3f4-cafd-6e7f-6e1b-f9bf-40b5-abf4-0b60-117c-d02d-bff6-3645'
adr = f'{guid}\n127.0.0.1\n10000\n1094\n2026-11-24 10.51.10-16972\n.\n'
address.write_text(adr)
lines = [
'iCDB Server ver.1.094, build:535943',
'Machine [LOCAL] User [operator] PID [16972]',
f'S: Project path [{shared}] on file system [NTFS]',
f'S: Server GUID [{guid}]',
'S: Wrote data to server address file',
'iCDB Server PI: Database closed',
f'Single file [{database}] closed with size [7 (0 kB)]',
f'AT: ERROR: Could not remove server address file [{address}]',
'S: STOP',
]
def write_log(events):
log.write_text('\n'.join(f'[2026.11.24 10:51:22] [0000m.11s.465ms] [0] {event}'
for event in events) + '\n')
write_log(lines)
monkeypatch.setattr(owner_probe, 'query_process_snapshot', lambda: [])
monkeypatch.setattr(owner_probe, 'query_owners', lambda *_: [])
release = library_lock.release_retained_library(library, tmp_path/'recovery', block_name='A')
assert release['status'] == 'RELEASE_CONFIRMED'
assert release['shared_shutdowns'][str(address)]['server_guid'] == guid
evidence = tmp_path/'open'
evidence.mkdir()
job = dict(root=str(evidence), lmc_file=str(library), block_name='A', project=str(project), pcb=str(pcb))
with pcb_open_consent.resource_guard(job, set(), require_complete_proof=True):
pass
proof = json.loads((evidence/'pcb-open-resource-proof.json').read_text('utf-8'))
assert proof['shared_shutdowns'] == release['shared_shutdowns']
assert address.read_text() == adr
assert database.read_bytes() == b'fixture'
import os
modified = log.stat().st_mtime_ns + 2_000_000_000
os.utime(database, ns=(modified, modified))
with pytest.raises(ValueError, match='SHARED_ICDB_INSPECTION_UNAVAILABLE'):
with pcb_open_consent.resource_guard(job, set(), require_complete_proof=True):
pytest.fail('an older server shutdown was accepted after a database change')
os.utime(database, ns=(modified, modified - 3_000_000_000))
write_log(lines[:-1]) # Database closed, but server shutdown is incomplete.
with pytest.raises(ValueError, match='SHARED_ICDB_INSPECTION_UNAVAILABLE'):
with pcb_open_consent.resource_guard(job, set(), require_complete_proof=True):
pytest.fail('incomplete native shutdown allowed read/write open')
+9
View File
@@ -1,4 +1,6 @@
from threading import Event from threading import Event
from types import SimpleNamespace
import time
import pytest import pytest
@@ -15,9 +17,15 @@ def test_real_recovery_handoff_preserves_A_lease_without_blocking_B_or_late_inst
request,original,source=recovery_files request,original,source=recovery_files
entered,release,done=Event(),Event(),Event();calls=[] entered,release,done=Event(),Event(),Event();calls=[]
context=BatchTaskContext(str(request.lmc_file),native_policy='external') context=BatchTaskContext(str(request.lmc_file),native_policy='external')
from cbb_refresh_verify import operation_queue
# Expire inactivity at the chosen stall, not during variable filesystem setup.
clock=[time.monotonic()]
monkeypatch.setattr(operation_queue,'time',SimpleNamespace(
monotonic=lambda:clock[0] if clock[0] is not None else time.monotonic()))
def hold(): def hold():
entered.set() entered.set()
if cancel:context.cancel() if cancel:context.cancel()
clock[0]=time.monotonic()+1
assert release.wait(5) assert release.wait(5)
def idle(*args): def idle(*args):
if boundary=='idle' and not entered.is_set():hold() if boundary=='idle' and not entered.is_set():hold()
@@ -43,6 +51,7 @@ def test_real_recovery_handoff_preserves_A_lease_without_blocking_B_or_late_inst
try: try:
with pytest.raises(TaskHandoff):context.run(action,timeout_seconds=.3) with pytest.raises(TaskHandoff):context.run(action,timeout_seconds=.3)
assert entered.is_set() assert entered.is_set()
clock[0]=None
with pytest.raises(LibraryBusy): with pytest.raises(LibraryBusy):
with LibraryLock(request.lmc_file):pytest.fail('A lease lost during stalled metadata') with LibraryLock(request.lmc_file):pytest.fail('A lease lost during stalled metadata')
def B(): def B():
+52
View File
@@ -158,3 +158,55 @@ def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, mo
monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw))) monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw)))
action.click() action.click()
assert calls == [(['Gamma'], {'maintenance': False, 'request_snapshot': original_remaining})] assert calls == [(['Gamma'], {'maintenance': False, 'request_snapshot': original_remaining})]
def test_orphaned_inflight_save_confirms_only_bound_prompt_after_three_seconds(tmp_path, monkeypatch):
from types import SimpleNamespace
from cbb_refresh_verify import desktop_worker, residual_sessions, session_record
desktop = 'CbbVerify_fixture'
job = {'interactive_input': False, 'desktop': desktop,
'operation_id': 'verify-fixture', 'session_record_path': str(tmp_path/'session.json')}
identity = {'role': 'native', 'pid': 75, 'created_handle': 'original',
'image': 'ExpeditionPCB.exe', 'owner_sid': 'sid', 'session_id': 1}
state = {'operation_id': job['operation_id'], 'phase': 'NATIVE_CALL', 'processes': [identity]}
actual = dict(identity)
known = {'hwnd': 1, 'title': 'Expedition PCB', 'desktop': desktop, 'class': '#32770',
'enabled': True, 'children': [
{'class': 'Static', 'text': 'Do you want to save the Reusable Block cell?'},
{'class': 'Button', 'id': 6, 'hwnd': 2, 'enabled': True},
{'class': 'Button', 'id': 7, 'hwnd': 3, 'enabled': True}]}
unrelated = {**known, 'hwnd': 9, 'desktop': 'Default'}
snapshots = SimpleNamespace(incomplete={})
snapshots.get = lambda *_: [unrelated, known]
clicks, events = [], []
monkeypatch.setattr(session_record, 'read_session_record', lambda *a, **k: state)
monkeypatch.setattr(session_record, 'process_identity', lambda pid: actual)
monkeypatch.setattr(residual_sessions, '_process_windows', lambda *_: snapshots)
monkeypatch.setattr(residual_sessions, '_post_window_message', lambda *args: clicks.append(args))
lost = False
monkeypatch.setattr(desktop_worker, 'supervisor_has_exited', lambda: lost, raising=False)
now = 10.0
prompt = residual_sessions.OrphanedVerifySavePrompt(job, 75, lambda **event: events.append(event),
clock=lambda: now)
prompt.poll(('SAVE_START',))
assert clicks == []
lost = True
prompt.poll(())
assert clicks == []
prompt.poll(('SAVE_START',))
now = 12.9
prompt.poll(('SAVE_START',))
assert clicks == []
now = 13.0
actual['created_handle'] = 'reused'
prompt.poll(('SAVE_START',))
assert clicks == []
actual['created_handle'] = 'original'
now = 14.0
prompt.poll(('SAVE_START',))
now = 17.0
prompt.poll(('SAVE_START',))
prompt.poll(('SAVE_START',))
assert [(args[0]['hwnd'], args[1], args[2]) for args in clicks] == [(1, 2, 75)]
assert events[0]['stage'] == 'orphaned_save_confirmed'
+35
View File
@@ -117,6 +117,7 @@ def batch_cli(tmp_path, monkeypatch):
def __enter__(self): return self def __enter__(self): return self
def __exit__(self, *_): pass def __exit__(self, *_): pass
def retain_for_recovery(self): retained.append(self.drive) def retain_for_recovery(self): retained.append(self.drive)
Lease.mentor_path.write_bytes(b'library')
monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease()) monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease())
monkeypatch.setattr(network, 'select_library_file', lambda path: path) monkeypatch.setattr(network, 'select_library_file', lambda path: path)
monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult(( monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult((
@@ -166,3 +167,37 @@ def test_retained_mapping_logs_context_and_confirmed_release_guidance(batch_cli,
assert 'Z:' in notice and r'\\server\share' in notice assert 'Z:' in notice and r'\\server\share' in notice
assert '释放残留会话' in notice and '确认' in notice assert '释放残留会话' in notice and '确认' in notice
assert 'net use' not in notice.lower() assert 'net use' not in notice.lower()
def test_batch_cli_can_enable_verified_pcb_open(batch_cli, monkeypatch):
app, runner, _, _, _ = batch_cli
received = []
def run(requests, **kwargs):
received.extend(request.auto_confirm_pcb_open for request in requests)
return [VerifyResult('PASS') for _ in requests]
monkeypatch.setattr(runner, 'run_batch', run)
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One']) == 0
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One', '--auto-confirm-pcb-open']) == 0
assert received == [False, True]
def test_batch_cli_uses_bounded_session_admission(batch_cli, monkeypatch):
from cbb_refresh_verify.operation_queue import NativeQueue, QueueUnavailable
app, runner, _, _, _ = batch_cli
calls = []
def admit(self, action, **kwargs):
calls.append(kwargs)
raise QueueUnavailable(kwargs['context'].library, timed_out=True)
monkeypatch.setattr(NativeQueue, 'run', admit)
def run(requests, **kwargs):
assert kwargs['context'].library == str(requests[0].lmc_file)
with pytest.raises(QueueUnavailable):
kwargs['item_executor'](requests[0], lambda: pytest.fail('unexpected write'))
return [VerifyResult('SKIPPED') for _ in requests]
monkeypatch.setattr(runner, 'run_batch', run)
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One', '--block', 'Two']) == 2
assert len(calls) == 1
assert calls[0]['wait_for_release_seconds'] == 120
+23 -1
View File
@@ -88,7 +88,7 @@ End Class
def run_helper(tmp_path, *, save_body='Save = True', close_body='Close = True', def run_helper(tmp_path, *, save_body='Save = True', close_body='Close = True',
is_saved='True', gated=False, cancelled=False): is_saved='True', gated=False, cancelled=False, transform=None):
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8') source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
classes = ''' classes = '''
Class FakePi Class FakePi
@@ -145,6 +145,8 @@ End Class
source = source.replace('Option Explicit', 'Option Explicit\nDim closedDoc\n' + classes) source = source.replace('Option Explicit', 'Option Explicit\nDim closedDoc\n' + classes)
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp') source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic') source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
if transform is not None:
source = transform(source)
harness = tmp_path/'facts.vbs' harness = tmp_path/'facts.vbs'
harness.write_text(source, encoding='ascii') harness.write_text(source, encoding='ascii')
cancel = tmp_path/'cancel.signal' cancel = tmp_path/'cancel.signal'
@@ -201,3 +203,23 @@ def test_unopened_gate_cancellation_exits_before_com(tmp_path):
assert 'TEST_SAVE_CALLED' not in result.stdout assert 'TEST_SAVE_CALLED' not in result.stdout
assert 'VALIDATE_START' not in result.stdout assert 'VALIDATE_START' not in result.stdout
assert result.returncode == 9 assert result.returncode == 9
def test_post_save_identity_failure_names_actual_and_expected_values(tmp_path):
result = run_helper(tmp_path, transform=lambda source:source.replace(
'ProjectFile = WScript.Arguments(0)',
'If afterSave Then\nProjectFile = "other.prj"\nElse\nProjectFile = WScript.Arguments(0)\nEnd If')
.replace('Dim closedDoc', 'Dim closedDoc, afterSave')
.replace('Save = True', 'afterSave = True\nSave = True'))
assert result.returncode == 8, result.stdout + result.stderr
assert 'POST_SAVE_IDENTITY|project=other.prj|expected=expected.prj|document=CBB.pcb|expected_document=CBB.pcb' in result.stdout
assert 'CLOSE_START' not in result.stdout
def test_post_save_transient_unsaved_state_retries_before_closing(tmp_path):
def transform(source):
return source.replace('Dim closedDoc', 'Dim closedDoc, savedCalls').replace(
'IsSaved = True', 'savedCalls = savedCalls + 1\nIsSaved = (savedCalls <> 2)')
result = run_helper(tmp_path, transform=transform)
assert result.returncode == 0, result.stdout + result.stderr
assert 'CLOSE_OK' in result.stdout
+83 -2
View File
@@ -47,7 +47,7 @@ def names(records):
def test_search_and_filters_use_cached_catalog_and_count_visible_states(qtbot, tmp_path, monkeypatch): def test_search_and_filters_use_cached_catalog_and_count_visible_states(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch) window = load_window(qtbot, tmp_path, monkeypatch)
window.reader = lambda _: pytest.fail('filter reread Mentor') window.reader = lambda _: pytest.fail('filter reread Mentor')
assert window.visible_counts() == {'visible': 5, 'ready': 2, 'error': 3} assert window.visible_counts() == {'visible': 5, 'ready': 2, 'error': 2}
expected = { expected = {
'ready': ['Alpha', 'Missing'], 'non_ready': ['Beta', 'Gamma', 'Delta'], 'ready': ['Alpha', 'Missing'], 'non_ready': ['Beta', 'Gamma', 'Delta'],
'pending': ['Beta'], 'errors': ['Gamma', 'Delta'], 'missing': ['Missing'], 'pending': ['Beta'], 'errors': ['Gamma', 'Delta'], 'missing': ['Missing'],
@@ -58,7 +58,7 @@ def test_search_and_filters_use_cached_catalog_and_count_visible_states(qtbot, t
window.status_filter.setCurrentIndex(window.status_filter.findData('all')) window.status_filter.setCurrentIndex(window.status_filter.findData('all'))
window.search_edit.setText(' ANALOG ') window.search_edit.setText(' ANALOG ')
assert names(window.visible_records()) == ['Gamma', 'Delta'] assert names(window.visible_records()) == ['Gamma', 'Delta']
assert window.visible_counts() == {'visible': 2, 'ready': 0, 'error': 2} assert window.visible_counts() == {'visible': 2, 'ready': 0, 'error': 1}
window.search_edit.setText('aLpH') window.search_edit.setText('aLpH')
assert names(window.visible_records()) == ['Alpha'] assert names(window.visible_records()) == ['Alpha']
assert '1' in window.counts_label.text() assert '1' in window.counts_label.text()
@@ -290,3 +290,84 @@ def test_large_catalog_local_filter_and_selection_remain_responsive(qtbot, tmp_p
print(f'catalog rows={size} load={loaded:.3f}s local_actions={elapsed:.3f}s') print(f'catalog rows={size} load={loaded:.3f}s local_actions={elapsed:.3f}s')
assert elapsed < 2.0 assert elapsed < 2.0
assert window.selected_records() == () assert window.selected_records() == ()
def test_double_click_shows_complete_skipped_reason(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QApplication, QDialog, QPlainTextEdit, QPushButton
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
reason = ('PCB_OPEN_SKIPPED: 检查未通过\n' +
'\n'.join(f'共享数据库占用记录 {index}' for index in range(30)) +
'\n完整路径 <library>/SymbolLibs/icdb.dat')
window._progress({'block': 'Beta', 'stage': 'SKIPPED', 'detail': reason})
row = window._row_by_name['Beta']
item = window.cbb_table.item(row, 3)
window.cbb_table.scrollToItem(item)
position = window.cbb_table.visualItemRect(item).center()
viewport = window.cbb_table.viewport()
assert viewport.rect().contains(position)
qtbot.mouseClick(viewport, Qt.LeftButton, pos=position)
qtbot.mouseDClick(viewport, Qt.LeftButton, pos=position)
dialogs = [dialog for dialog in window.findChildren(QDialog)
if dialog.isVisible() and '结果详情' in dialog.windowTitle()]
assert len(dialogs) == 1
dialog = dialogs[0]
text = dialog.findChild(QPlainTextEdit)
assert text.isReadOnly()
assert text.toPlainText() == reason
copy, = [button for button in dialog.findChildren(QPushButton) if button.text() == '复制全文']
qtbot.mouseClick(copy, Qt.LeftButton)
assert QApplication.clipboard().text() == reason
dialog.close()
@pytest.mark.parametrize('enabled', [False, True])
def test_pcb_open_option_is_bound_only_to_ordinary_verify(qtbot, tmp_path, monkeypatch, enabled):
requests = []
def verify(request):
requests.append(request)
return VerifyResult('SKIPPED')
window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify)
window.auto_confirm_pcb_open_check.setChecked(enabled)
assert window._request('Beta').auto_confirm_pcb_open is None
window._run(['Beta'])
qtbot.waitUntil(lambda: not window.busy)
assert len(requests) == 1
assert requests[0].auto_confirm_pcb_open is enabled
@pytest.mark.parametrize('prewrite', (True, False))
def test_prewrite_cancellation_can_resubmit_and_rechecks_ready(qtbot, tmp_path, monkeypatch, prewrite):
calls = []
reads = []
def verify(request):
calls.append(request.block_name)
window.stop.set()
return VerifyResult('CANCELLED', safe_to_continue=False, cancelled_before_write=prewrite)
def read(names, library):
reads.append(names)
return {'Beta': 'READY' if len(reads) > 1 else 'PENDING'}
window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify,
status_refresher=lambda *_: pytest.fail('cancelled batch started a status refresh'))
window.catalog_reader = object()
monkeypatch.setattr(window, '_execution_status_reader', lambda *_: read)
window.search_edit.setText('beta')
window.batch_button.click()
qtbot.waitUntil(lambda: not window.busy)
assert calls == ['Beta']
assert window.visible_records()[0].status == ('PENDING' if prewrite else 'UNKNOWN')
assert window.batch_button.isEnabled() == prewrite
if not prewrite:
return
window.batch_button.click()
qtbot.waitUntil(lambda: not window.busy)
assert reads == [('Beta',), ('Beta',)]
assert calls == ['Beta']
assert window.cbb_table.item(1, 3).text().startswith('SKIPPED:')
+20
View File
@@ -183,3 +183,23 @@ def test_window_close_tolerates_fake_and_deleted_dialog_pools(qtbot, tmp_path, m
window.show() window.show()
window.close() window.close()
qtbot.waitUntil(lambda: not window.isVisible()) qtbot.waitUntil(lambda: not window.isVisible())
def test_late_job_retains_mapping_after_window_destruction(qtbot, tmp_path):
import shiboken6
from cbb_refresh_verify.ui.main_window import MainWindow
window = MainWindow(reader=lambda _: None, data_root=tmp_path, authoritative_status=False)
lease, entered, release, closed, calls = slow_lease(get_ident())
job = window._new_job('verify', lease=lease)
window._shutdown_leases[id(lease)] = lease
window.library_lease = None
try:
shiboken6.delete(window)
window._finish_job(job)
qtbot.waitUntil(entered.is_set)
assert calls == ['retain']
assert not closed.is_set()
finally:
release.set()
+70
View File
@@ -1036,6 +1036,76 @@ def test_saved_closed_without_cert_uses_bridge_and_never_reexecutes_verify(
assert ordering[-1] == 'failure_logs' assert ordering[-1] == 'failure_logs'
@pytest.mark.parametrize('config_name', ['CBB1.prj', 'PCB/pcb.prj'])
def test_native_save_waits_for_scoped_database_sharing_violation(tmp_path, monkeypatch, config_name):
from cbb_refresh_verify import file_probe
import win32con
import win32file
work = fixture(tmp_path)
config_path = work/config_name
database = config_path.parent/'ActualDatabase/icdb.dat'
if config_path.exists():
with config_path.open('a', encoding='utf-8') as config:
config.write('\nKEY iCDBDir "ActualDatabase"\n')
else:
config_path.write_text('KEY iCDBDir "ActualDatabase"\n', encoding='utf-8-sig')
database.parent.mkdir()
database.touch()
shared = tmp_path/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
shared.parent.mkdir(parents=True)
shared.touch()
locked = win32file.CreateFile(str(database), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
progress = []
released = False
class FinishedWorker:
desktop = None
returncode = 0
def __init__(self, command, *_args, **kwargs):
root = Path(command[-1]).parent
(root/'outcome.json').write_text('{"status":"PASS"}', encoding='utf-8')
(root/'save.log').write_text(
'SAVE_START\nSAVE_OK\nIS_SAVED\nCLOSE_OK\nQUIT_OK\n', encoding='utf-8')
def poll(self):
return 0
def close(self):
pass
def observe(event):
nonlocal released
progress.append(event)
if event['stage'] == 'post_save_release_pending':
# Model the original case: PCB is gone, the database is still held.
assert event['blocked_resources'] == [str(database)]
locked.Close()
released = True
def read_status(*_args):
assert released, 'Native status read started before iCDB released the database'
return BridgeResult('READY', 'IsVerifiedReuseBlock', 1)
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', FinishedWorker)
monkeypatch.setattr('cbb_refresh_verify.verify_runner._cleanup_session_processes',
lambda *a, **kw: {'safe_to_continue': True, 'remaining_pids': []})
# Source-mode subprocess uses the same import root as the current test run.
monkeypatch.setenv('PYTHONPATH', str(Path(file_probe.__file__).parents[1]))
try:
result = run_verify(request(tmp_path), port_check=PORTS_OK, flag_reader=read_status, progress=observe)
finally:
if not released:
locked.Close()
assert result.status == 'PASS'
assert result.safe_to_continue
release = json.loads(result.evidence_path.with_name('session-release.json').read_text('utf-8'))
assert {str(shared), str(database)} <= set(release['database_release']['exclusive_files'])
assert sum(event['stage'] == 'post_save_release_pending' for event in progress) == 1
@pytest.mark.parametrize('detail, category', [ @pytest.mark.parametrize('detail, category', [
('PROJECT_INTEGRATION_FAILED: There were errors during packaging', 'MENTOR_PROJECT_INTEGRATION'), ('PROJECT_INTEGRATION_FAILED: There were errors during packaging', 'MENTOR_PROJECT_INTEGRATION'),
('DATABASE_LOAD_FAILED: DataBase Load is being terminated with 2 errors', 'MENTOR_DATABASE_LOAD_FAILED'), ('DATABASE_LOAD_FAILED: DataBase Load is being terminated with 2 errors', 'MENTOR_DATABASE_LOAD_FAILED'),