Compare commits
45
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3efeaed656 | ||
|
|
55cdf2b082 | ||
|
|
3bde847ff7 | ||
|
|
07eab61695 | ||
|
|
14cacb1d1c | ||
|
|
fa1f662e1d | ||
|
|
b4737b5102 | ||
|
|
8869093eb0 | ||
|
|
c1e259603a | ||
|
|
5e9509e573 | ||
|
|
906cfc06be | ||
|
|
32dcd80d1e | ||
|
|
8818fa9841 | ||
|
|
701e5cd3b4 | ||
|
|
7eafae417d | ||
|
|
a3f69de201 | ||
|
|
7cc65f78da | ||
|
|
845ae58690 | ||
|
|
d5d1a3deea | ||
|
|
a64636ba0d | ||
|
|
4402486baa | ||
|
|
de81bbf293 | ||
|
|
e0bb2438e8 | ||
|
|
fd50805380 | ||
|
|
eaff46e50e | ||
|
|
8bfa4eed34 | ||
|
|
f964ff347c | ||
|
|
2149e71b67 | ||
|
|
7c27f9604e | ||
|
|
87e10740f7 | ||
|
|
d40fa3a750 | ||
|
|
36ff964230 | ||
|
|
07206ce0d1 | ||
|
|
5b7e7bea2f | ||
|
|
eabf61c73b | ||
|
|
dbc685b9a5 | ||
|
|
cd7a5e0ca1 | ||
|
|
601dd7b6b2 | ||
|
|
8374cabe5c | ||
|
|
ddff6bd857 | ||
|
|
0440b2efbf | ||
|
|
b070837acb | ||
|
|
a1b38c242f | ||
|
|
efb8cae478 | ||
|
|
e4875b4eca |
No files matched your search
@@ -2,7 +2,9 @@
|
||||
|
||||
当前临时分支的备份策略(2026-11-03):应用不再自动备份中心库或 CBB 工程。新增、替换、移除、校验、ICDB 维护和恢复在执行前提示手动备份;请自行保留可用副本。导入暂存、恢复用隔离验证库和轻量操作证据仍会生成,Mentor 原生 Repair 自身的备份行为保持不变。详见[自动备份检查与调整](docs/releases/2026-11-03-manual-backup.md)。此条优先于下方历史版本的备份说明。
|
||||
|
||||
当前开发版本:**[0.2.4b2 生命周期候选](docs/releases/2026-11-06-runtime-lifecycle-candidate.md)(开发候选,待现场验收)**。ICDB 批量检查在后台逐项运行,普通校验、管理和恢复可排队;READY 工程在实际执行前再次排除。检查不自动 Repair、Restore 或选择历史版本,也不代表中心库 READY。
|
||||
当前测试版本:**[0.2.4b3](docs/releases/v0.2.4-beta.3.md)(待现场验收)**。ICDB 批量检查在后台逐项运行,普通校验、管理和恢复可排队;READY 工程在实际执行前再次排除。检查不自动 Repair、Restore 或选择历史版本,也不代表中心库 READY。
|
||||
|
||||
管理写入因无法完成占用确认而未执行,或恢复安装前选择跳过,结果为 `SKIPPED`;取消为 `CANCELLED`,与实际操作失败区分。文件身份核对失败保留“需要恢复”,后续独立 CBB 依据各自会话释放和写前检查决定是否继续,不自动重放失败目标。
|
||||
|
||||
停止、超时或应用失联只停止后续原生动作,不结束正在 Save/Close 的调用进程。普通停止等待 5 秒,可能正在写入时最多等待 120 秒后交给后台观察;这不是强制结束时限。保存结果、关闭结果和资源释放分别记录。相关库等待释放,独立库可以排队继续;界面、筛选和日志保持可用。重启只核对未完成会话,不重放管理写操作。legacy 状态读取只观察已打开且匹配库的 LM,不启动 LM 或回答弹窗;无法读取保持 UNKNOWN。
|
||||
|
||||
|
||||
@@ -15,6 +15,12 @@ python -m pytest -q
|
||||
python -m compileall -q src tests
|
||||
```
|
||||
|
||||
For an isolated checkout, set `$env:PYTHONPATH = (Resolve-Path ./src).Path` so
|
||||
test subprocesses import that checkout rather than another editable installation.
|
||||
The repository's `.gitattributes` preserves CRLF (`* -text`); use
|
||||
`git -c core.whitespace=cr-at-eol diff --check` to check whitespace in a clean
|
||||
clone without reporting the preserved CR bytes as trailing whitespace.
|
||||
|
||||
The source import was verified with 336 pytest cases. Tests use fake local files
|
||||
and replace the production Mentor COM/process boundary where required; they do
|
||||
not establish field success against a live network library.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CBB 检查、校验、管理与残留释放操作规程
|
||||
|
||||
适用开发版本:0.2.4b2。未完成现场验收,不自动发布或关闭工单。以下为当前规程,下方旧上传校验检查表保留为历史参考。
|
||||
适用测试版本:0.2.4b3。测试版发布不代表现场验收,不自动关闭工单。以下为当前规程,下方旧上传校验检查表保留为历史参考。
|
||||
|
||||
## 当前操作与队列
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
|
||||
## 历史记录、操作结果与报告
|
||||
|
||||
管理写入无法取得占用确认、或恢复安装前选择跳过时,记录 `SKIPPED`(已跳过 / 未执行);取消记录 `CANCELLED`。这两者不等于实际上传或恢复失败。文件核对失败仍记录“需要恢复”并禁止自动重放该目标;后续独立 CBB 在会话释放及自身写前检查通过后可继续。
|
||||
|
||||
校验和管理遇到历史释放记录时,先复核实际进程、地址、独占文件及导出副本。确认释放后归档记录再继续,不以历史 JSON 本身判定真实占用;同目标未完成写入仍需核对,不自动重放。释放证明在管理首次原生调用前写入检查点,并在结果中保留。
|
||||
|
||||
管理操作生成目标工程、库配置和共享依赖的写前/写后主要文件清单及新增、删除、修改差分;不增加自动全库备份,也不声称检查了其他 CBB 内容。报告不可用与原生操作失败分别记录;本任务已释放时可继续独立项。
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"created": "2026-11-16T14:36:55.137608+08:00",
|
||||
"base_commit": "e4875b4eca1bc487514d479df15f2a4ac92df5e3",
|
||||
"branch": "codex/unattended-prompt-defaults",
|
||||
"full_suite": {
|
||||
"path": "F:\\CbbUnattended-20261116\\full-final.xml",
|
||||
"sha256": "8717cf87707b525a17eb2a3a292677360eade0d374e7d6eb42a6c2d07209d520",
|
||||
"tests": 1937,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
},
|
||||
"red_original_no_timeout": {
|
||||
"path": "F:\\CbbUnattended-20261116\\red.xml",
|
||||
"sha256": "b0c46ca9c76ce41f9c9053ec94a08d416a3b18d775f3d9e3af1d469ac96b1225",
|
||||
"tests": 3,
|
||||
"failures": 3,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
},
|
||||
"button_and_prompt_integration": {
|
||||
"path": "F:\\CbbUnattended-20261116\\integration-final.xml",
|
||||
"sha256": "002f68c353fdf3a6e5eacfd2596df8b15f30a8a76ef3c262d2da3fc64e35a202",
|
||||
"tests": 100,
|
||||
"failures": 0,
|
||||
"errors": 0,
|
||||
"skipped": 0
|
||||
},
|
||||
"first_full_run": {
|
||||
"path": "F:\\CbbUnattended-20261116\\full-suite.xml",
|
||||
"sha256": "a6d2d5fe0d240ede5a90fff7b8f4c70635c12b82ef3423185c8ee975db17bf53",
|
||||
"tests": 1935,
|
||||
"failures": 6,
|
||||
"errors": 2,
|
||||
"skipped": 0
|
||||
},
|
||||
"first_full_run_explanation": "Four notification tests expected the old OK button; two recovery-summary paths recreated the Close button and invalidated countdown. Fixed redundant recreation and aligned notification clicks; failed evidence retained.",
|
||||
"static_api_trial": {
|
||||
"final_design": "Explicit QMessageBox object; no application event interception.",
|
||||
"rejected": "Static Qt question interception caused timer ownership/slot errors in experiments; rejected and replaced before final integration."
|
||||
},
|
||||
"default_timeout_ms": 3000,
|
||||
"defaults": {
|
||||
"submitted_verify_check_management_recovery": "confirm",
|
||||
"unknown_owner": "skip",
|
||||
"uncertain_pcb_readwrite": "skip",
|
||||
"version": "last_user_saved_if_enabled_else_cancel",
|
||||
"native_cancel": "confirm",
|
||||
"save_before_close": "save",
|
||||
"force_terminate": "cancel",
|
||||
"notification": "close"
|
||||
},
|
||||
"compileall_passed": true,
|
||||
"diff_check_passed": true,
|
||||
"independent_review": "Final read-only rereview found no remaining actionable issues.",
|
||||
"files_sha256": {
|
||||
"src/cbb_refresh_verify/application.py": "62b9b013563a216d020c8366cccb8f949b02afa72dc63c26940804441cc23057",
|
||||
"src/cbb_refresh_verify/backup_recovery.py": "1d7ef08ef53ca7a0971cdacb0908d9bb06d067b06dc2329fa58722ce9068921d",
|
||||
"src/cbb_refresh_verify/batch_status.py": "55a4007cf54491ca8e045a5bf86aa4353ac8437cca5a76cd79304962e3d3fa0a",
|
||||
"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": "27d751816552d215dd8ee9cd67941d824f7b4493120ead7c3f87e5eba5ec4a92",
|
||||
"src/cbb_refresh_verify/diagnostic_open.py": "d6c49ffe5a9969d95edbbc896d47a7e100f248380a287f99ba7bb8b92dbb3072",
|
||||
"src/cbb_refresh_verify/dialog_agent.py": "5acb6e5cf1350a7ca20a6fe480668435fac785835874f266881973010db6504b",
|
||||
"src/cbb_refresh_verify/dialog_models.py": "f68cee01d927b48364276d3c1f79e63ce8af231878db0b907d292780cfbafb56",
|
||||
"src/cbb_refresh_verify/dialog_probe.py": "d61f0c955c961980c9635940eefb9c7947c1fe90b4b6fd844720df41ddb0aa0e",
|
||||
"src/cbb_refresh_verify/dialog_rules.py": "3189b476f7ff4678b59212ed7b4081164e038a7cf7662cd895f9019cb3c1edc5",
|
||||
"src/cbb_refresh_verify/dialog_supervisor.py": "15c415c2d2e916f0b64ba04416164ff3b50996d70b22d3b4ac2226b5547ac247",
|
||||
"src/cbb_refresh_verify/failed_session.py": "7e6f7fa5ebcf2d49f00c5efc5f5d26412704b68e9122e476ac1f672009a98c09",
|
||||
"src/cbb_refresh_verify/icdb_maintenance.py": "e81d253d8b4d3e7c1000c45335a392c72b110748675c2c3324ebe524a7252e98",
|
||||
"src/cbb_refresh_verify/icdb_ownership.py": "7bf2342c1efa34a2ebcbf27964a40a490220f7146fbb6ef957b8d8dd1e511f03",
|
||||
"src/cbb_refresh_verify/icdb_recovery.py": "358c0e9a004f1e0b2127513286e1dffd94b0180a8b7314aa9655462f570b6360",
|
||||
"src/cbb_refresh_verify/integration.py": "f188856af69ba25e265988c51db7a6d4263326440d972ca78378b733b891c1ed",
|
||||
"src/cbb_refresh_verify/library_lock.py": "6836ec8ac21e788eb75326ff44cb31ad4bdfb5f381bd35cdf33e6b34c7fca89e",
|
||||
"src/cbb_refresh_verify/library_manager_verify.py": "71e16a8581ad44b646be78b480f9812d596a6d162b3eec03d078bf4ea4503195",
|
||||
"src/cbb_refresh_verify/library_reader.py": "d4007caa361edd467773e49f721e02671d5a9bcb30741769a57349850b12c438",
|
||||
"src/cbb_refresh_verify/maintenance_entry.py": "3b93c25f69d7a961facd8004e20e155a84cc18f06d57b741a9055786ed058990",
|
||||
"src/cbb_refresh_verify/management.py": "7ead9bfffeb44201e44f73d9f039590f091e9a456982f2110dca8ec3695f8803",
|
||||
"src/cbb_refresh_verify/management_transaction.py": "32c53caaead05d5db3a31d3e30721e65434e5837095dc0a7812f825603aa37a0",
|
||||
"src/cbb_refresh_verify/mentor_adapter.py": "1fc8c98d5508120e03bf001a42dd3e0da7b165eb18c90f1aed83147d17db8638",
|
||||
"src/cbb_refresh_verify/mentor_paths.py": "ba48c0003b3eacc88906497b2e43b299ca4536a9f7dae44bbacf6a6ec694c116",
|
||||
"src/cbb_refresh_verify/models.py": "9e8209a8b006df923f1d07ccab64bbcfe5d674c4fc5f5426bfbc9b11da4ee105",
|
||||
"src/cbb_refresh_verify/native_add_failures.py": "192202732423dc624c5548c75e80bb20973e5087c21d4798c9637f25b6de7e94",
|
||||
"src/cbb_refresh_verify/native_backup.py": "7276fa3d9298e85550151cf0c7191d84bd08a18a72df5d854a3c38f1a88b001d",
|
||||
"src/cbb_refresh_verify/native_engineering_identity.py": "8c0fc144707d68a9b85f6da50ef950f1f6e7fee248acbf34d19b707d51212be0",
|
||||
"src/cbb_refresh_verify/native_export_guard.py": "523cdf44db8e1665634feadba963ccf26777dc8942fb2eb604d2c30bbe92cbb6",
|
||||
"src/cbb_refresh_verify/native_management.py": "eb2ec311489eaf5deb06893a54a02469c9b2bb9baccbdd6563bae295aafcf363",
|
||||
"src/cbb_refresh_verify/native_occupancy.py": "7d686079d12217382adace6361cd343d977b91075e3b157cf410ca92d07ffc49",
|
||||
"src/cbb_refresh_verify/native_repair.py": "9f024dcb5e3a76369191033474fefd30787b6ae350c315f3cf38e92e5a1f3e98",
|
||||
"src/cbb_refresh_verify/native_repair_ui.py": "3eb2af181befea94af8b3b3131edff09589f340bcba777abbe3b67fd31b80393",
|
||||
"src/cbb_refresh_verify/network_path.py": "6b5b159502d42a46bf4ee26d5698fd2c6498b359088e2138eae46e9065b13c6f",
|
||||
"src/cbb_refresh_verify/operation_lifecycle.py": "3838c5a501711d16f578c45ebbc6f960872b0c3ba6bbda9a597f994ef746cef6",
|
||||
"src/cbb_refresh_verify/operation_queue.py": "a6932d8bc68ac436091f6d362557c66d274ec52d0f295a22f014a3396845c79f",
|
||||
"src/cbb_refresh_verify/owner_probe.py": "8dcfd60246cb2979db34d02e0a2d605c334b6f7e2666f22daa2f50c0408bc903",
|
||||
"src/cbb_refresh_verify/pcb_bridge.py": "2f6c2b09642100468814500569dbfc6695fc2a46b9a3b8333daa8e1530cdeef5",
|
||||
"src/cbb_refresh_verify/pcb_open_consent.py": "fd56dfe0b537408745127d80ea68cc59d3f333954af76bac7a7b324d66badc65",
|
||||
"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": "4ac500b33b209611d54eb496c6c30727ba159742d625431ceea84471a5fc3442",
|
||||
"src/cbb_refresh_verify/runtime_logging.py": "44ac25430a89c5ffc9e48e88c227e88052f4c815365e8556f67918f3edaba39e",
|
||||
"src/cbb_refresh_verify/runtime_timing.py": "c4ed4057b5000e0b86ccc7dd1fe2004d6e0dae29f397fec77b01ad41a81c6367",
|
||||
"src/cbb_refresh_verify/scoped_manifest.py": "9318bf0f929d23c18466a25d83a4a9903822093c123aae10510061788c6d0ab7",
|
||||
"src/cbb_refresh_verify/session_record.py": "2bc3cff365008864584138a4ff13538bb6b2f90d981e7d008a1300f9102c6e7e",
|
||||
"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": "3027ef7fc1ef6365ff36ae0c83389d869b92ffcd96985d10275bca4dc9483e3f",
|
||||
"src/cbb_refresh_verify/write_admission.py": "c5f879bd5cb70a5dedfc64349c8758bf370daa4240491addd2aecd344f3a935c",
|
||||
"src/cbb_refresh_verify/__init__.py": "75942b10cc5c09f19d5f31bedd0395361642336f52bc9e9872d8483e3b9882f9",
|
||||
"src/cbb_refresh_verify/__main__.py": "dc4be034a0e43d4b659a9300137c29a6a6b7a32b7eaef02b6dff9a88c41305c0",
|
||||
"src/cbb_refresh_verify/ui/backup_notice.py": "1a3fa5ac18a267907faf95f36d61b9f08bcbb939eef4d480dd06af1391a81599",
|
||||
"src/cbb_refresh_verify/ui/backup_recovery_dialog.py": "8a80f584347f3fdefc089169894712746fee85f079b029578f008d6aecec8d90",
|
||||
"src/cbb_refresh_verify/ui/icdb_check_task.py": "ade3bf414aa29b42f4c1535c613b2cacb2735f6abc7900e6da25999390a5891d",
|
||||
"src/cbb_refresh_verify/ui/main_window.py": "f72062cb3d97cbd38f6390b9483e0f3aab619dec0bb2292c02d32b7fc5cd84b9",
|
||||
"src/cbb_refresh_verify/ui/management_dialog.py": "57698f42112b120899dac26c40d2aafb4b5ba719660a302c0460361a7d50609a",
|
||||
"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": "a0bdcc091778d508c43a6af96bd6423b25cd029c92b6bcff22d459d09a030d06",
|
||||
"src/cbb_refresh_verify/ui/timed_prompt.py": "71db65febd0aff9117dcee42dde5151a7f13a3337794c77031cf5585f0397d97",
|
||||
"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",
|
||||
"tests/button_simulation.py": "3278868565853001103557d5f7ada42b11b05c03feb9032deed0327b6609de2b",
|
||||
"tests/test_abnormal_shutdown.py": "0abdeaf51e2ffc3f771e09aefa9ec647a72b7f64757c9f3851926fbd392cbbcd",
|
||||
"tests/test_all_buttons.py": "a075cfdf3223b754be351db54844f94a8538519c38a12b1b575ec483c544d57c",
|
||||
"tests/test_application.py": "bba12187fca6fee0f4f8862182bb40d939e2995016af2cdbb3fd756f6a99135d",
|
||||
"tests/test_automation_license.py": "45e9c75d0d3e1a76f997f7da4cc87b5eb1b05a4ea2356408725742eac8a09ffb",
|
||||
"tests/test_background_icdb.py": "df9bd9e8252e0dee4527dc6a740c0c33e76d1fb06a79b816cc15809d95716e44",
|
||||
"tests/test_background_queue_regressions.py": "132866bfccc9a7ac5cb234f97aaf6a290e2e4ef949f31e2f70b0f3eafeb99046",
|
||||
"tests/test_backup_recovery.py": "efd88c0c00440ac915b147c2e6dee8044ca805b03f90ab9f171cbde1db11cb9b",
|
||||
"tests/test_backup_recovery_dialog.py": "24a120e45dee151bc71a2e1a05345936c5063bf0f57a277af02ef3a6bfd753f9",
|
||||
"tests/test_batch_blockers.py": "4387293d3a5820fab630e3c5fe1b424f61ba6947773e5a61125d840433c5c62a",
|
||||
"tests/test_batch_item_yield.py": "ed4be6d1e854b18d054a75c92171cd46b6b64411c2f74e9a3caf31fba3c7366b",
|
||||
"tests/test_batch_status.py": "c1f9af0c7c6f3171b3726fb53346f480b13b8d9cd88111a9c12e2fae2392bbff",
|
||||
"tests/test_batch_status_faults.py": "314e890c9aee439c8a75b4dfd605685240c74f6212da975fd50526bd70b4a0ff",
|
||||
"tests/test_desktop_worker.py": "671d616f04a01d74508b328e3b6fc8f6c7191a91de0dcaa486aa98a3718353ff",
|
||||
"tests/test_diagnostic_open.py": "b44f8f7b171602ad2691ea2e064ac9fe94f2fabb9fcc2eb6760cc1dd365b9423",
|
||||
"tests/test_dialog_agent.py": "8c746e47d55637ca18d7cc998f324a0c2e0a5214dcfe8fcb6458c060619c211c",
|
||||
"tests/test_dialog_models.py": "6902cf5c292458340fb48241b34875e111a0113d706cd82775934a7f72bab7b9",
|
||||
"tests/test_dialog_probe.py": "55c98f6102957a27a96dcfd4f4bf3af499b5055225b77ef93b7b332dfd4ac472",
|
||||
"tests/test_dialog_rules.py": "96bf36493da770679e9207e96b3088ef7f471aea22e17c254f33326ffef0d7f9",
|
||||
"tests/test_dialog_startup_budget.py": "6f23c01836e4894ae82c3345a2383c4f8eb0517056c5b953c43100acd0fc3739",
|
||||
"tests/test_dialog_supervisor.py": "4c1b00050127a65b0a8cf1c7a94fd673431ea3f04b76033a463804d0468ad2d9",
|
||||
"tests/test_extended_safety.py": "7450816abba89aba1f4739f819f43631def82701fe07481279db2b3f3ed96cf6",
|
||||
"tests/test_external_owner_release.py": "675ddbab4a97e86febac3003b9083c259295534941aa0463488a5a1206cfaf92",
|
||||
"tests/test_failed_startup.py": "eca757ea46a4c0aa4fb0368ff53f26822af71612d251ecd87132686fe3c3794b",
|
||||
"tests/test_failure_lifecycle.py": "dfeac56744a44e6f4c7898516749ca478f53d7c7f08b3843a05ef7f448c469a7",
|
||||
"tests/test_icdb_address.py": "cbdc07e5043349c796a4ea1ce3d4989062094cd28929a9ef7d42c5ba75b77907",
|
||||
"tests/test_icdb_batch_check.py": "79b4a8d9576449bde64f06bfd4d30b82ce6fe93e055c238eb1f239e75b472579",
|
||||
"tests/test_icdb_open_check.py": "1f3750169755d0553bac3e0f8bec244038b84f9cd970e17c9f6eb67dee0e3dba",
|
||||
"tests/test_icdb_recovery.py": "298ddac4b79b4400efc99ff27c58ca49fffea1f401a31071451b2fdaca59036e",
|
||||
"tests/test_import_without_export_gate.py": "2f249412736cbe84f0c82db82403212739b7c53355f87cd053587ccdb722b175",
|
||||
"tests/test_incident_safety.py": "52f3ccb04db8971bf38628c2bd334d4fd79795e97de6538f6f66cb35f7123ece",
|
||||
"tests/test_independent_operations.py": "4ba5798df3346bce74c3703c158f1dce1d1ba14df748606fcaf900c8568753e0",
|
||||
"tests/test_integration.py": "9e9d30692607c889e1e3744a63c79c68e3af7d4c86804e0bcebe48e68765086c",
|
||||
"tests/test_late_release_continuation.py": "34c62a628cbc08f4e8b9a1919c13f17772a2d26d1996fae34a35f814725b00e2",
|
||||
"tests/test_library_lock.py": "3d65bd941faa441404045ce0140ea3ea5e58fb7d410b7b76bb9f03a9ea03d3af",
|
||||
"tests/test_library_reader.py": "b39a1dc9d99c2463b744141e3c3489cd49ac4a637e7835559a9c3fe9cbafbb58",
|
||||
"tests/test_lifecycle_supervision.py": "cfe29f1e73c6ef38d11e185e211b6e2fb60247f53a44e99dd1e2f8cf7a009faa",
|
||||
"tests/test_maintenance_diagnosis.py": "0849aef555475a03b061eacf499f261fb75f2e727f35dba3cbceafac92e2a638",
|
||||
"tests/test_maintenance_entry.py": "5ed3cda8e0c829fb2964e27f1bdc6fa8ee8dcde93ec63338959bf754b62d6a0b",
|
||||
"tests/test_maintenance_owner_scope.py": "7cf64dc7f2b126684dcac6e619cbd87eca3d85ec2fc1f70f057154679dad6026",
|
||||
"tests/test_maintenance_review.py": "ba807fd8c25c1b52cf2443d8bcf2f57539819715c0bc6c358d31d8542c2e7ce5",
|
||||
"tests/test_maintenance_startup_gate.py": "4f69d33218483a658b51b2012ae8bfa83aff8a787152a38b19dadc4c0d3ffe36",
|
||||
"tests/test_maintenance_ui.py": "9c604714b0742503dbd55b243161a01f4ae62fa0cae7c4cddec7a2b8c81d07ab",
|
||||
"tests/test_management.py": "cad0fb43eca9e7022a33a5e9ff0a408465b262fd304b146cdc85c28265f2e74f",
|
||||
"tests/test_management_diagnostics.py": "671a9d7c112ededbee332db9b6fbab786fb37e9367d992f902f3ab2c9f60880b",
|
||||
"tests/test_management_native_transaction.py": "7ca227aae6426c4d0d998edfd8620ec18905aaf212f0be20ceba97b1cde3a9a4",
|
||||
"tests/test_management_probe_guards.py": "ae9be3dbd7c6a616478b7d4ea3498c428ff94a985089fe798463c5cab456f151",
|
||||
"tests/test_management_retry_blockers.py": "124dbef291dbe331ba0c3e7de1665c910ea43e37b1563429b387f0f2233953ee",
|
||||
"tests/test_management_source.py": "16e608ed9c8b0aa81cf08d49f165a33a1403c4ea7f2a5be44e8cfc8cb49850ad",
|
||||
"tests/test_management_supervision.py": "2dcadd6551a94c52e5d4e74285959f10144a89c48af87e508abaea945652d1f6",
|
||||
"tests/test_management_ui.py": "3d02dd00f20227aba6eeff40b9c49e34c93f81b02a02370fb0fa6848a1981413",
|
||||
"tests/test_manual_backup_ui.py": "c1d3f7363a18ad3a690854d503199aa703c0a11ef937c933b025fd9b98083ed7",
|
||||
"tests/test_mentor_paths.py": "a05a91812a74b58e76f36d581216ee43969d2576b8a8e7d1cde3e301c52cf4c1",
|
||||
"tests/test_native_add_failures.py": "ceedd60e030628b1af149d08d16216d5f7158a63686729bb357c148da86fb0ec",
|
||||
"tests/test_native_backup.py": "43ec0c6b14b53864553feaf5d9fb498b37866f24edc486c0749160d3f803db5f",
|
||||
"tests/test_native_engineering_identity.py": "a1adcf6883a9b55c2c37d9f491faf40dd4928f4d8db675419fd288dd31552c69",
|
||||
"tests/test_native_export_guard.py": "f8ec4fa1058af55008e9628f79f2dc70b6e551f36815a812d10bfdf955cada51",
|
||||
"tests/test_native_inspection_release_regressions.py": "8f7bb0b2b641d437872f1dd1d0c2547c2522c81e3c0351c31a7125f751d91927",
|
||||
"tests/test_native_management.py": "badf33d4d00104c7e96e336777fb3e49690cc9db5ce1b071f98520aa5b6668f1",
|
||||
"tests/test_native_management_fields.py": "9917ca0910e19bd809c86d0120c652145261528ace33c3b805f5663442c4a973",
|
||||
"tests/test_native_occupancy.py": "56293dbe24bd3cd4f74cf8208e933faab7d737e5a5684a5d38838d063c3aef6d",
|
||||
"tests/test_native_repair.py": "113185ced72d8f4f4eafca99054d97fe80a504d1c6cc91aaf86f55cea1b7e138",
|
||||
"tests/test_navigation_tabs.py": "d7d5bbfc752f73c1b1d4615ffafc1266e772d96f3f3ba3d82c4b4baf678b292d",
|
||||
"tests/test_network_path.py": "f52624391ae78e9b913dace2b1a9a2875a5855f86dc9e12c324ef493e6c7817b",
|
||||
"tests/test_network_release_safety.py": "caef536d0a40b2eb848c1b8ab095ab374af247c03dd44acf8a70f0f500db6dac",
|
||||
"tests/test_operation_lifecycle.py": "c0ce6c86b73021a8b162ae9e67a10aeec8a27a98e382fd82e1449a451a9a8c3c",
|
||||
"tests/test_operation_queue.py": "8137528603f015695ed4d60a0c8fa8e7bf0a1c4659f8dc2a181291f5d500e6a1",
|
||||
"tests/test_owner_probe.py": "deb757e022980f11ef48e57a2fd002ee3e90ec647a4666a0c4d4427313b6f725",
|
||||
"tests/test_packaging.py": "87a6d04419775c0c5c806e0e569a48d7ef199a0bff8736b211443a1f471e7e8a",
|
||||
"tests/test_packaging_status_bridge.py": "cbfaeac070a1494a1d8609fc25e9a779a63354c8914b4c6c57fdc7c31b70d472",
|
||||
"tests/test_pcb_bridge.py": "527fb63147a203a2e9419da989aff600d3e461580989e39e8ede3a8cc57b901a",
|
||||
"tests/test_pcb_open_consent.py": "ec94b5b73790d7e0caf7140783e73e4a32a21b787f80a427e96fc7083f33535a",
|
||||
"tests/test_pcb_restore_prompt.py": "a005691d0296587e520e20c4430e9e55227d767c8e910e950a9f2e93aeccb2c7",
|
||||
"tests/test_pcb_version_choice.py": "0825c28333e4ed4f5a63847b6f5bb11143e922c7203d2770ce9c78fc8edec20f",
|
||||
"tests/test_post_repair_consent.py": "bf417b378255386dc97ad8efdf5003b0691aa5d69da9d9256aa367dc16a2d4bb",
|
||||
"tests/test_post_verify_diagnostics.py": "212857e56581998a3a3cd53635030b68a089fc4d630a8b0ee7ef3f137090dcc4",
|
||||
"tests/test_private_desktop_discovery.py": "5361493313ae6864e252cdb9f2c72e71b39264a1c022beb4cf0c04c143cdd91e",
|
||||
"tests/test_readonly_status_policy.py": "3ed40d7bdf2d3e6f70b38803b89a8b982336556444b45c6ba6b0a7c6df52a97f",
|
||||
"tests/test_reimport_recovery.py": "2c0ecf52cd6c393f572c11b5d998a78ef538f7a277668cdc329a03e267074650",
|
||||
"tests/test_residual_release_dialog.py": "1d5efa03cfe013770e2b81e1fcfb669142f5d6a07957110e56a3cc5eeb57c4a3",
|
||||
"tests/test_residual_sessions.py": "2c51ed1dc95a3afa7ebb24027963dfa9d13aba9c407e508e22ccc6e9f762dfeb",
|
||||
"tests/test_review313_residual_isolation.py": "52a8024ed4e2a7fed219fe46cacdf76fa971166feedd557206716ef7f6d3c914",
|
||||
"tests/test_review326_dispatch_and_receipts.py": "ce4d529246da1c4d53c3dec70ef49542165064404301dec3e32851df62492ecf",
|
||||
"tests/test_review326_queue_guidance.py": "305662f79251669685a618bdd35d524ef2b37eaece4428bb58ae4c5b65abb8ac",
|
||||
"tests/test_review345_ui_cli.py": "795e7e4f9bda8874c6a65a08863cab19f4adb3412287276ee2960588f0fd2fa8",
|
||||
"tests/test_review348_release_comparison.py": "ceccdb3d6f7bc6cb65562c059f13aa2bc5d89d98c6f64b0f11d9b943ebbde165",
|
||||
"tests/test_review381_queue_release.py": "e0d62424cbf70ec9573db78ede0a4c6534775399194eed4c6b28ba8d468307be",
|
||||
"tests/test_review391.py": "304d46d63af87ea4a9bca83834b77cc44c5c9addf7b0f3752431304ee612568c",
|
||||
"tests/test_review414_export_and_audit.py": "ec785c2656bed97de6c8467885f2ad0877b55ee872b02928744d399e8767d8a0",
|
||||
"tests/test_review414_open_and_queue.py": "db065207dacaccd0bd80af52c1f1edaf36a278e7cf2dce7c9b44bc51dd0e1cec",
|
||||
"tests/test_review414_write_admission.py": "732a3683c2e27331cd5a9645e062e22613f848cac1a12745744fe249b48a9ffe",
|
||||
"tests/test_review430.py": "7350f3883ddb9be48cc66fa7b0f612e1b45acf2298c80a7faa3da1f05d6d4c83",
|
||||
"tests/test_review_319.py": "831fd34d426abb4436b9132bfb7ed754994155a34ac60a59378dee0964b54d28",
|
||||
"tests/test_review_backend_followup.py": "2f3f51a72ecd05fc33c6b5a8dddaecfd12d2b50df423c87b4c18d1e52b2609bd",
|
||||
"tests/test_review_foreign_release_evidence.py": "cbf2af02418f6bd3ec720a7a7658cf97f06d1a6e12009fdff2a99f465711591e",
|
||||
"tests/test_review_management_ui_followup.py": "746602a84c3ba9cb041c5dd354b39d344355b71a3666b27a47eb9aee231e171c",
|
||||
"tests/test_review_release_followup.py": "8779bde7aaaf59ecf362990afe1d9e7ed4ecb1f6fd7653c08bffbdc296200837",
|
||||
"tests/test_runtime_timing.py": "7152cd8fedfe165e769dadc1238c347d9f4d3e93cd57f6ed991e14d959e720f7",
|
||||
"tests/test_safety.py": "ccf5febaf0a974d5e5357398a6946d3f121e07a6247c2f0dc5b71d86b39cac52",
|
||||
"tests/test_save_helper_identity.py": "178a68c4a9a8c618dad3d8393e816dd1d2a16aef8d1fb9984117fe9dc8d06add",
|
||||
"tests/test_save_helper_runtime.py": "00b092ec799da4bca424e1ee63a83bee783c81dbcdc20b7526fda8b45bb4b72a",
|
||||
"tests/test_scan_isolation.py": "cab02bfe55ed515f889d3fcba6e6880344f482cc3a78a072b543b7a871cf92ab",
|
||||
"tests/test_scoped_manifest.py": "fe9b2047d2c43812e851dd89ff250a2e5907dda89b3f5d9ae0a4dc4c5f452eac",
|
||||
"tests/test_session_record.py": "6b51b19adfb232275195da7ff1ba91a5ce5e296f9424a7a1a29fc67ecfdfb108",
|
||||
"tests/test_status_bridge.py": "fe1c0632d4d5fd5a1caf221903d4cfe38eda62aaa4298e3438735e31b8459ab2",
|
||||
"tests/test_status_bridge_server.py": "7d8cd72d69afae0f96ebbd9bb3be2ae3c222f01108e45ab51a09e54d4d8527cc",
|
||||
"tests/test_ui.py": "ec0aad6d58b81a42129709b4cbeda9e754be48c6107a5b12384f75170c983463",
|
||||
"tests/test_ui_batch_safety.py": "12a8d82d4aedbeee315a02a49ec0e9888547ad4abd63e181e7f392b2a39e26dc",
|
||||
"tests/test_ui_filters.py": "d542e3d6fbc8cff64229b31ea8d0ed14ae0fe0c2c03b6a6eefed2f57dfbe77c9",
|
||||
"tests/test_ui_lease_lifecycle.py": "18ea8af868373fa795a4911754be55068fe75833ce35579c1212fd7f4713f149",
|
||||
"tests/test_unattended_prompts.py": "9dff94c678af95b796dfc068bb478de720547dad0b341a63195ca97710f2c4af",
|
||||
"tests/test_verify_diagnostics.py": "b6431194e9f4c86a42110cac0d5f712c27b063f43b4ce820327aded81602908c",
|
||||
"tests/test_verify_probe.py": "aeb65b5bd2df14e8a8f3ba5501855b5946e6f8a22f0d26960c00ff1b0daea56b",
|
||||
"tests/test_verify_runner.py": "e58619f55873302c39129ce50e50fb25173a96ab309d975aa4f47f0bd3459fbb",
|
||||
"tests/test_verify_worker_stability.py": "eae03400c2e3c8a0bc339c8dc05d890403c6bfb4c6d70d0361bc1b882b47d618",
|
||||
"tests/support/runtime_lifecycle_frozen_boundaries.py": "bf98533a1c06ccf4453d20b3804323779719e697141b8dc64fa679960a979cfd",
|
||||
"tests/support/runtime_lifecycle_frozen_fixture.py": "b87761c06a300f0d93bce864d3d31e045f2135324b2a9a42f8682ccbff09ad22",
|
||||
"tests/support/runtime_lifecycle_frozen_smoke.py": "65b530d1e18b35918595eddc7cedeb31ff204cc785b1dc3c0d8c0b87f4aba0a5"
|
||||
},
|
||||
"production_logs_read": false,
|
||||
"mentor_started": false,
|
||||
"production_library_modified": false,
|
||||
"published": false,
|
||||
"automatic_icdb_repair": false,
|
||||
"limits": [
|
||||
"Only confirmation-message waiting is changed; global busy/queue/I-O locking design remains unresolved.",
|
||||
"Native write, real occupancy and exact process/window checks still govern continuation.",
|
||||
"Native Mentor unattended end-to-end, Windows 10 and cross-machine SMB not accepted.",
|
||||
"File selection and configuration forms require valid input; unknown native prompts are not guessed."
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
# 无人值守弹窗默认动作
|
||||
|
||||
从 beta.3 主分支 `e4875b4` 开始的本地修改。此记录不是云端发布公告。
|
||||
|
||||
## 之前修复为何仍有阻塞
|
||||
|
||||
此前以局部失败案例逐处增加保护,未完整验证各层的组合。界面 busy、原生队列、库租约、历史检查点和会话释放共同决定能否继续;释放动作还可能等待被阻塞的同一队列。
|
||||
“发生错误”“本任务仍占资源”“外部占用”“界面正在执行”几种状态未充分分开,导致恢复入口也被保护条件禁用。
|
||||
单项失败后继续的用例通过,只覆盖了可返回的失败;没有覆盖首次读库带锁、取消、换库、释放及关闭的完整闭环。
|
||||
|
||||
本轮只消除确认弹窗无限等待,并给出明确默认动作;全局队列及锁的结构问题仍需单独修复。
|
||||
|
||||
## 默认动作
|
||||
|
||||
所有下列消息框显示倒计时,在可见且无人选择时 3 秒后执行指定默认动作。
|
||||
手动选择、关闭窗口会停止本轮倒计时;不会在窗口消失后执行旧操作。
|
||||
|
||||
| 场景 | 默认动作 |
|
||||
| --- | --- |
|
||||
| 已点击执行的普通校验、ICDB 批量检查 | 确认开始 |
|
||||
| 已预览并提交的新增、替换、移除 | 确认执行;原有逐项检查及人工备份提示仍在 |
|
||||
| 已选择完整来源的备份恢复确认 | 确认执行;副本验证及安装前检查仍在 |
|
||||
| 已明确请求的原生取消 | 确认发出原生取消请求 |
|
||||
| 已进入释放流程的“关闭前保存” | 保存后关闭;不默认放弃未保存内容 |
|
||||
| 未知原生客户端占用确认 | 跳过本项,不给未知客户端授予写入许可,不取消整批 |
|
||||
| PCB 提示上次未正常关闭或仍被占用 | 跳过本项;实际释放成功后才能执行下一项 |
|
||||
| 原生历史版本选择 | 沿用用户此前明确偏好的“最后手动保存”;该候选不可用时取消本项,不改选自动保存 |
|
||||
| 强制结束客户端 | 取消,不自动强杀 |
|
||||
| 结果通知、原生详情通知 | 关闭;记录仍保留 |
|
||||
|
||||
选文件及填写来源等配置窗口需要有效输入,不猜测工程路径。
|
||||
未识别的原生弹窗不猜按钮,也不使用鼠标前台抢占。
|
||||
|
||||
## 证据与边界
|
||||
|
||||
OpenChoice / RestoreChoice 保留一次选择,新增 `decision_origin=user/timeout_default`;原生 PCB 选择记录与动作载荷写明来源。
|
||||
未知客户端超时默认跳过,不生成“用户已确认无人使用”的许可;逐项结果保留超时原因。
|
||||
所有原生身份、窗口按钮、地址记录、文件占用、保存和释放证明照常执行。
|
||||
倒计时不会解除真实资源占用,也不代表 ICDB 已修复或工程 READY。
|
||||
|
||||
测试包括实际等待 3 秒、人工提前改选、首选版本不可用、窗口隐藏/关闭后计时失效、一次性决策以及选择来源。
|
||||
测试不使用生产日志,不启动生产 Mentor 工程。
|
||||
|
||||
最终全量 1937 项、逐按钮及弹窗集成 100 项通过,编译及差异检查通过。
|
||||
首轮全量发现通知框重复创建标准按钮导致计时对象失效,已删除重复创建;首轮失败证据保留。
|
||||
完整散列和测试记录见 `2026-11-16-unattended-prompts-validation.json`。
|
||||
当前仅本地源码提交,没有重新冻结、推送或更新生产发布包。
|
||||
@@ -0,0 +1,132 @@
|
||||
# Issue 15 acceptance matrix
|
||||
|
||||
Refs #15. The final grouped review wave is implemented at `c1e2596` (B14). The complete suite passed **2,418 tests in 594.83 seconds**, actual exit code 0, with zero failures, errors or skips. Actual B13 ordinary Verify/Stop with automatic candidate-owned cleanup and cross-owner queued Versions passed; actual B13 CBB recovery passed source and target verification. B14 preserves explicit ordinary release promotion of an existing cold observer; that narrow change has source/real-process coverage and updated frozen checks. Native cases retain B13 identities. The final scoped independent review passed for 32dcd80..8869093: I1-I3 addressed; zero Critical/Important/Minor findings. This is a technical review, not field acceptance or merge/release approval.
|
||||
|
||||
## Executable bindings
|
||||
|
||||
Each case retains its actual executable hash. Rebuilds checked all packaged modules/resources and repeated the affected operation plus common frozen smoke; earlier passes are not relabelled as tests of the newest executable.
|
||||
|
||||
| Build | Code commit | Executable SHA-256 |
|
||||
|---|---|---|
|
||||
| B1 | eaff46e | `24201dac278ea91fbc7f1b50146a10e024d4c4bf0da14ec5ecbeedbac65104a0` |
|
||||
| B2 | fd50805 | `a75414653a399cfc76633cad25544d57749ab5a8b49ef227d0a0833f8828257f` |
|
||||
| B3 | e0bb243 | `aae0039bfcdcb21ea3d25156920a4124a510a10ac499049604550eddc2ab7645` |
|
||||
| B4 | de81bbf | `f87e403ee5a4891cff82649f5fef573cd304e5052aa3954faaaf43fd94b2ae88` |
|
||||
| B5 | 4402486 | `b52b8689dc66cfccbf94d578a23de3021fc6857933d9bea38b77038c3711d721` |
|
||||
| B6 | d5d1a3d | `f60e2eef44462f590ad81c94c0d2479cd017d519a7e176b34ee45258aae14690` |
|
||||
| B7 | 845ae58 | `dcdcd33e7909c8d1d3b616ef722734f630ea2f793e7bd162e7e8e722978baf9b` |
|
||||
| B8 | 7cc65f7 | `e1ba9e057d8147fcf451dd419d63660d507a29c96402b174f8824ed6a8ec159d` |
|
||||
| B9 | a3f69de | `bfd6c122724f71a2aac4748ed01336a9949aa753f9c58aca55db574668140083` |
|
||||
| B10 | 701e5cd | `a6271e4219a02123e301ed1e0ea3109e78307bf1f92574b4a5cacb70690695a4` |
|
||||
| B11 | 8818fa9 | `03452e39f394c3c63113aaa701f64bacf14e817ae3b4e194965f333ecc645b98` |
|
||||
| B12 | 906cfc0 | `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc` |
|
||||
| B13 | 5e9509e | `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` |
|
||||
| B14 | c1e2596 | `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c` |
|
||||
|
||||
B9 ZIP SHA-256: `4c589bae6bf7b68732cd7ebe373b2924016c71f6731fd661c1cd0fd848427438`. All 68 packaged modules and required assets/scripts/bridges/icons match the source; all 242 extracted files match the build. Its five pre-cancelled worker entry routes and common GUI/worker/owner-probe/dialog-agent smoke passed without launching Mentor. B8 is separately archived with ZIP SHA-256 `795010cc0b54b995eced859cac1513bf105092e484a44b1231955801deed879f`; B5 retains ZIP SHA-256 `176c7cda89c2a2706f969fa6dca513d2760615491aaf70c19fe7a0688abe471a`.
|
||||
|
||||
B10 ZIP SHA-256: `d4bd42416ea8d12a249ff1d9c8854eb76d2f81bb7ff869ff43dd92a331c647a0`; 68 modules/resources and 242 extracted files match, five pre-cancelled entries and common smoke passed. Only the residual-session module changed from B9. Earlier actual cases retain their original hashes.
|
||||
|
||||
B11 ZIP SHA-256: `34b3646b27afae22ec43a415ca19bbd32a91c0a4c941d37d6289c76cea9ca730`; the same module/resource/file checks, five cancelled entries and common smoke passed. Its only source-module change from B10 records each acknowledged Tip per cleanup intent. Immediate/delayed Tip states with/without prior Close passed focused source tests; no new actual Mentor Tip replay is claimed. The harmless real Win32 adapter probe belongs to the B10 source stage; its unchanged adapter preserves hidden MDI siblings and sends no action with an extra document.
|
||||
|
||||
B14 ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`; 68 modules/resources, 242 extracted files, five cancelled entries and common smoke passed. B13 actual native cases retain their original hashes. B12 failed late ordinary cancellation remains archived with its exact identity.
|
||||
|
||||
## Reported issues A–H
|
||||
|
||||
| Issue | Source verification | Actual frozen evidence and limits |
|
||||
|---|---|---|
|
||||
| A: cancellation leaves startup prompts/clients | Exact ownership, known prompts, cooperative cancellation, admission and shutdown coverage; late Tip after first Close, held identity, delayed launcher, no second Close, unknown/document/progress/write negatives; single legacy release intent and observer proof. | **REPRODUCED on B5:** Stop 0.797 s after registered PCB startup returned CANCELLED/safe=false with a late Tip and retained PCB/launcher. Manual Tip OK alone completed the existing close; that remains a failure. B8/B9 automatic release and B9 one-confirmation legacy release passed separately, as detailed below. |
|
||||
| B: another project's address blocks release | Scoped resources, exclusive Windows handles, fresh proofs and independent-item continuation. | B5 Release UI confirms zero active sessions and released library ownership. Earlier metadata handoffs and a separate bounded file-probe timeout remain failures; no native lock/address was manually deleted. |
|
||||
| C: Versions conflicts with the parent's lease | Parent/child handoff, worker admission and reopening tests. | B1 official Repair, manual backup, exact-version restore, backup verification and reopening succeeded on the selected copied project. Tool exit alone was not counted as successful repair/restore. |
|
||||
| D: historical records block unrelated/retried work | Legacy evidence is rechecked; a new confirmed operation requires fresh scoped release proof. | B3 corrected 8212 update succeeded in the same data root after the earlier failed operation. The original failed journal remained unchanged; later recovery and B operations continued. |
|
||||
| E: optional LM dispatch returns without starting PCB | Bounded dispatch observation, exact target binding and owned-LM cleanup. | The direct native route passed. The exact optional-LM dispatch failure is **NOT REPRODUCED**; Windows 10 is **NOT RUN**. |
|
||||
| F: Save finishes but library remains pending | Unique project/PCB binding, reference alignment and authoritative READY gate; Save/Close/exit/release are distinct. | B2 B-control first Verify remained PENDING and correctly failed; one explicit retry passed GREEN. B3 recovered 8212 source and installed target both passed GREEN. First-pass noncommit cause remains unconfirmed. |
|
||||
| G: copied database is inconsistent | Diagnostic routing, manual recovery entry and error precedence; automatic Repair stays disabled. | B1 healthy-control Repair passed. Original complete fault-bearing field snapshot is unavailable: **NOT REPRODUCED**. Constructed-copy result is reported separately below. |
|
||||
| H: selection/input/results/confirmation gaps | Real Qt controls, immutable requests, stale-view protection, one-shot defaults and large-table filters. | B1 basic controls/Add, B2 wrong-source rejection and concurrent view changes, B3 stop-after-current/recovery/removal/reimport, B4 restart without replay, and B5 diagnostic handoff/Release were exercised. Conditional controls are identified below. |
|
||||
|
||||
## Important native receipts
|
||||
|
||||
These identifiers locate retained local evidence; raw field files, private machine/user identifiers and production paths are not published.
|
||||
|
||||
| Build / operation | Receipt | Observed result |
|
||||
|---|---|---|
|
||||
| B1 duplicate A then independent B Add | management-c74c9a2b226e4df382be1447d2c9da95; management-4174be063d7843c69406e6610b4cc084 | Duplicate safely rejected; B UPLOADED with native registration/project/top/Layout confirmed. |
|
||||
| B1 manual Repair / backup / restore / verify | native-backup-ed65d2630b3c | Actual native success output; uniquely described archive and restore location checked. Archive SHA-256 `429195ff63fd76e3586a348357009e4638c06d2d2c27c38e5cdee63f6966d26a`. |
|
||||
| B1 Versions reopen | native-backup-de1ef77062a4 | Correct project/backup catalog; normal exit and release. |
|
||||
| B2 fresh-source diagnostic with external observation | icdb-check-455c02cfba8f / verify-d67aa6df8758 | CHECKED/safe; 261 read-only snapshots show Forward Annotation prompt disappearing and loading progress ending before Close. No manual native action. |
|
||||
| B2 B ordinary Verify | verify-491e77340ae2; verify-742c401bec4f | First FAIL/PENDING despite completed Save/Close/release; separate explicit retry PASS/GREEN with reusable-cell save confirmation. |
|
||||
| B3 8212 update and actual stop during Add | management-78e5a9b3f24b4353b778a540c6f67e56 | Stop clicked during exact registered LM NATIVE_CALL. Current item completed Add, authoritative readback and release: UPLOADED/safe. |
|
||||
| B3 CBB backup recovery | backup-restore-4c7aad5bd125 | Source verify-2c4769255397 and target verify-adad45363659 both PASS/GREEN; installed=true; old Work retained; both COMMITTED/CLOSED/EXITED/RELEASED. |
|
||||
| B3 B remove and reimport | management-c156db77b0c449a0b0e034891aeaacff; management-15a95455d14541e4a47a3b4b2126c8a7 | REMOVED with authoritative catalog absence, then UPLOADED from the independent source. Auto-verify off. |
|
||||
| B4 restart | restart-before-06 / restart-after-06 | Operation-root sets unchanged and no native process before explicit Read: no automatic replay. |
|
||||
| B5 diagnostic intent/ack/Close | icdb-check-8683e232ce83 / verify-755f3af6b650 | CHECKED/safe, 38.437 s; exact intent/ack/Close identity and nonce match; intent precedes Close by 0.125 s. |
|
||||
| B5 explicit Release | sessions-e4c27855ec69 | UI and durable RELEASE_CONFIRMED agree; zero active sessions, 7.704 s. Exact file-probe helper returned HELD and exited normally; read-only observation sent no target control action. |
|
||||
| B5 early native Stop — original failure | icdb-check-63f7ee04d30b / verify-719b874e0aaf | Actual Stop 0.797 s after PCB registration, before loaded readiness: CANCELLED at PCB_STARTING, 31.875 s, safe=false, native clients retained. 894 read-only snapshots showed the late Tip. Manual exact Tip OK allowed both clients to exit with no further Close, Save, annotation or force action. |
|
||||
| B6 early native Stop — loaded-target transition | icdb-check-762d0b790c2c / verify-67752f3332dd | Stop 0.813 s after PCB registration: Tip was automatically dismissed before any Close; target then loaded and showed Forward Annotation. CANCELLED/safe=false, 31.625 s; 892 read-only snapshots. Manual exact Forward No, then one normal target Close after progress ended, exited both clients without Save/annotation/force. This failure prompted the bounded cancelled-diagnostic loaded-target cleanup. |
|
||||
| B7 late exit after bounded cleanup | icdb-check-ac97c21a1863 / verify-0a4f641d37d3; sessions-98a1beebfb10 | Automatic one Close and late Tip dismissal; native exit followed the original deadline. Original CANCELLED/safe=false remained. A later manual Release obtained fresh proof, so this did not establish automatic observer release. |
|
||||
| B8 automatic cancellation and prequeued Versions | icdb-check-64348b7f55c5 / verify-505a4f09d4e7; native-backup-073e59195f9b | Versions queued after PCB registration and before Stop; UI terminal 7.125 s. Automatic Tip/Forward No/one Close, natural exit, existing observer RELEASE_CONFIRMED. Queued native client created 2.075 s after proof and catalog loaded. No Release click/manual diagnostic native action; original CANCELLED/safe=false retained. |
|
||||
| B5-to-B8 legacy release — incomplete workflow | icdb-check-17661d31889d / verify-4b7bc47b39f8; sessions-12c1715f5d7f, sessions-38ed41c344f8, sessions-2cca647d90da | Initial inspection handed off before a plan; Recheck succeeded. First confirmation declined Forward but did not close; second closed PCB/launcher while server remained; third obtained fresh proof. No manual native action, but multiple confirmations were required: not accepted as the intended final workflow. |
|
||||
| B9 automatic cancellation and prequeued Versions | icdb-check-b05147dc18bc / verify-3abaddb3e141; native-backup-005da267ebfe | Versions queued before Stop/handoff; UI terminal 6.672 s. Automatic Tip/Forward No/one Close; 307 read-only snapshots and kernel exit. Existing observer obtained fresh library RELEASE_CONFIRMED; queued native client created 1.684 s later and catalog loaded. Zero Release clicks/manual diagnostic native actions. Original CANCELLED/safe=false retained; backend duration 12.829 s is distinct from UI timing. |
|
||||
| B5-to-B9 legacy release — one confirmation | icdb-check-378044ad1122 / verify-d2acda2739c2; sessions-a5a9fe06b7c1 | Real B5 retained loaded target/Forward; old app normally exited. B9 initial inspection succeeded, one normal Confirm, zero Recheck/second confirmation/manual native actions. Forward disappeared after 3.562 s; 210 read-only snapshots show kernel exit. PCB, launcher and server RELEASED, fresh RELEASE_CONFIRMED at 22.634 s; UI agreed and Confirm disabled. Existing cold observer RELEASED; original cancellation result retained. |
|
||||
| B10 I3 setup — second pending item | management-f25df6a207ca4744ab4a0c23ddabb06c | Legitimate exact-name update from the existing healthy source, auto-verify off; UPLOADED/safe, native catalog/readback. Prepared two pending items without fabricated native failure. Selection made before final refresh was cleared; disabled Verify rejected the harness click; reselection afterward succeeded. |
|
||||
| B10 ordinary Stop — historical failure | verify-e464474b7bab; batch-20261117-105152-c3e162 | Actual Stop 0.547 s after PCB registration, no Save evidence: first CANCELLED/safe=false, 29.766 s; second SKIPPED with no native job. Later loaded Forward remained. Exact manual No, no-modal/no-progress check and one normal Close required; sessions-4aadbacb8a93 then fresh release. Not unattended PASS; ordinary cleanup does not have diagnostic-only authority. |
|
||||
| B10 actual Continue, no replay | button-watch-1794884270925407000; verify-f673ac48f600 | Existing summary's three-second Close elapsed before inspection. After main-window Release proof and normal dialog close, production code recreated Continue. Actual button click started only the previously skipped second item, which passed GREEN/safe. First terminal result predates the click and no first-item job was replayed. No in-process method/result injection. |
|
||||
| B10 actual result Release | button-watch-1794884430968047900; verify-4f959f61fbc4 | One bounded same-scenario timing repeat caught actual result Release and opened its residual plan. Ordinary Stop again retained Forward, 32.844 s; this remains a failure. Exact manual No/normal Close, no Save/force; sessions-6bfdf0a26476 fresh release. |
|
||||
| B5-to-B10 affected legacy release | icdb-check-92a3c92f6d6c / verify-9f3856153c79; sessions-82cc60b6eacb | Initial inspection succeeded; one Confirm, zero Recheck/manual native actions. Forward disappeared +6.5 s; 278 read-only samples/kernel exit. Intermediate PARTIAL then fresh RELEASE_CONFIRMED +35.387 s under the same intent; all three clients and existing observer RELEASED, UI agreed. Original CANCELLED/safe=false preserved. Entry was loaded Forward; actual Tip replay is not claimed. |
|
||||
| B12 ordinary Stop — late loaded failure | verify-642171759614 | UI terminal 7.797 s; loaded Forward at 34.406 s after original cleanup deadline. Manual exact No/normal Close required. Failed-run cleanup only; original CANCELLED/safe=false preserved. |
|
||||
| B13 ordinary Stop / cross-owner queue | verify-71aee0603183; native-backup-b63e7f708fd5 | Actual candidate worker No/one Close before first 30 s deadline; late kernel exit and fresh candidate/independent proofs. UI terminal 7.375 s; real Versions creation 5.220 s after candidate proof and 1.506 s after independent proof, catalog loaded. No Release/manual ordinary native action. Retained-phase No/Close branch not replayed in Mentor. |
|
||||
| B13 CBB backup recovery | backup-restore-3f98efb14448; source verify-06c8149375e6; target verify-f902921f2440 | Both PASS/GREEN/safe and COMMITTED/CLOSED/EXITED/RELEASED, installed=true; old Work retained, all 366 original source files unchanged, no native intervention. |
|
||||
|
||||
The B2 diagnostic run supports the implemented sole-handler No sequence through observed windows and verified code; there is no separate startup button acknowledgement event. The hidden-owner-chain save branch did not recur on corrected native runs and remains covered by regression tests plus the original captured chain. The original failed diagnostic required manual cleanup and a native crash acknowledgement; that crash was **NOT REPRODUCED** in the subsequent bounded runs.
|
||||
|
||||
## Buttons and misuse scenarios
|
||||
|
||||
| Controls / scenario | Source coverage | Frozen coverage |
|
||||
|---|---|---|
|
||||
| Tabs, advanced options, optional LM checkbox, runtime log toggle | Actual source UI and Qt tests | B1 actual navigation/toggles. |
|
||||
| Library chooser Open/Cancel and Read CBB | Actual chooser/catalog; invalid-input tests | B1 chooser cancellation and catalog; B3 removal/reimport catalog; B4/B5 explicit reload. |
|
||||
| Select visible, Clear, filter/hidden selection | Actual UI and 381/3,000-row Qt checks | B1/B2 actual controls and view changes; immutable original operation retained. |
|
||||
| Verify selected / visible non-READY | Actual source native verification and Qt admission | B2 ordinary Verify; B3/B13 recovery target verification; B13 actual ordinary Stop and automatic release. READY exclusion remains enforced. |
|
||||
| ICDB batch confirmation No/Yes and stop | Actual source checks; Qt stop/continuation | B1/B2 confirmation cancellation and diagnostic runs; B5 acknowledged close; B8/B9 actual startup Stop and automatic queued continuation. Other cancellation timing remains conditional. |
|
||||
| Manual Repair Cancel/Confirm | Actual native healthy control | B1 native diagnostics/defragmentation; not field-fault recovery proof. |
|
||||
| Versions / create backup / restore Cancel/Confirm / verify / Close/reopen | Actual exact archive and location | B1 native tool operations and reopening. |
|
||||
| Add / source chooser / empty input / auto-verify / logs / No/default Yes | Actual source and Qt | B1 duplicate-plus-independent Add; B3 reimport. |
|
||||
| Same-name update / wrong source / reselection / No/default Yes | Actual source and Qt | B2 mismatch rejected before writing; B3 correct update. |
|
||||
| Remove / hidden source chooser / No/Yes / result | Actual source and Qt | B3 REMOVED and native catalog absence before reimport. |
|
||||
| CBB backup recovery / empty input / chooser Cancel / No/Yes | Actual source and Qt | B3 original controls/full sequence; B13 full serial metadata/source-validation/install/target-validation sequence. |
|
||||
| Management stop-after-current | Two-item Qt/real admission tests verify next item skipped, including failed readback and unknown release | B3 stop during native Add; mandatory current-item readback completed. |
|
||||
| Queued cancellation / active dialog close | Qt queue, close, hard-cancel and shutdown tests | B10 recovery dialog queued behind an owned diagnostic, Cancel queued clicked, UI CANCELLED/no native admission/no recovery job. Underlying diagnostic verify-96d285ffa450 completed CHECKED/safe. Earlier second management submission/active lower Close remained disabled. |
|
||||
| Residual sessions / Recheck / Confirm / Close | Qt exact scope, one-intent observer promotion and real Windows proofs | B5 zero-active-session release; B9 initial inspection and one-confirmation release of a real B5 cancelled session; previous failed/multiple confirmations retained. |
|
||||
| Native details / Save prompt / native Cancel / forced termination | Qt exact ownership/prompt and default-Cancel tests | Disabled with no matching active owned client. No forced native termination claimed. |
|
||||
| Conditional result recovery/release/resume buttons | Qt target binding, stale results and single continuation | B10 actual result Release and Continue/no-replay receipts above. B10 ordinary retained startup required manual cleanup; B13 automatic ordinary Stop acceptance is recorded separately below. Other fault-dependent recovery branches are not blanket passed. |
|
||||
| Three-second defaults / manual-vs-deadline / hidden or closed prompts | One-shot Qt timer tests | Actual management/recovery No and timed Yes; full timing competition covered in Qt. |
|
||||
| Double submission / result remaining open / view changes / restart | Qt and Windows lifecycle tests | Active execute controls disabled; modeless dialogs and view changes observed; B4 no replay. |
|
||||
| Open logs/evidence / shell errors | Qt dispatch and error reporting | B10 actual Open logs/Open exception clicks opened exact application logs and verify-e464474b7bab folders; complete private Explorer breadcrumbs recorded. Only the two task-created Explorer windows normally closed. No shell-error case is claimed. |
|
||||
|
||||
One B1 harness edit targeted the library textbox while a modeless dialog changed control indices. The immutable original-library operation still completed and the changed view was invalidated. This is retained as a harness/misuse event, not a product search failure.
|
||||
|
||||
## Final-wave evidence and limits
|
||||
|
||||
B14 EXE SHA-256: `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c`. ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`. All 68 packaged product modules/resources and all 242 extracted files match source/build. Five pre-cancelled frozen routes and common GUI/worker/owner-probe/dialog-agent smoke passed. Full-suite log SHA-256: `d9c57b7998e02154fb703f0fe2ba1f37f73dc4687d116c4b6efc0e5ad7e5c30e`; JUnit SHA-256: `4303cc123e90689103cc4135e483ac936b04a052067e952a1861ae167c7811ea`. Native clients and writer/management mutexes were idle before and after the full suite.
|
||||
|
||||
B13 (`5e9509e`) retains EXE `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` and ZIP `7a1da94e05b85873f791cde77907bdc280106768fbf84e5d89066ab8aa57a61b`. A final self-audit found that the new ordinary explicit-release branch bypassed existing cold-observer promotion. Its focused test failed before the two-line ordering correction at `c1e2596`; 110 related tests then passed in 21.96 seconds, including actual harmless worker exit, cold-observer promotion and queue proof. The in-progress B13 full suite was interrupted through its own execution session before editing, and is archived without a completion/JUnit claim. No additional native matrix was run for this narrow B14 delta.
|
||||
|
||||
The three review defects had retained RED evidence: actual MainWindow subprocess exit hung on stalled hash/copy/validation; real recovery callers held the unrelated native channel and could install after abandoned metadata; ordinary cancelled startup failed to clean a later loaded target. B13 related observer coverage passed 232 tests in 34.81 seconds, including an actual two-process mutex/file race between observer and explicit release plus a process restart. These race tests stub the native evidence/action boundary; they are not Mentor window tests.
|
||||
|
||||
B12 (`906cfc0`, EXE `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc`, ZIP `bbe68005469d8b6cf87726200ef85646e442de45d164ab2ac0aec23b51d0bd65`) retained a new failure: ordinary `verify-642171759614` returned its visible cancellation terminal state in 7.797 seconds, but Forward loaded at 34.406 seconds, after the worker cleanup budget. Exact manual No/normal Close was used solely to clear that failed run. A later independent queue-helper attempt was refused with sharing violation 32 before native creation while two releasing observers raced for the coordination lease. Both failures are archived and are not relabelled as B13 passes.
|
||||
|
||||
B13 ordinary `verify-71aee0603183` reached the visible terminal state in 7.375 seconds. Its candidate worker acknowledged Tip at 21.359 seconds, Forward No at 27.422 seconds and one Close at 28.750 seconds; native exit followed the original cleanup deadline. Read-only sampling confirmed kernel exit. The original result remains CANCELLED/safe=false. No Release click or manual ordinary native action occurred. The helper stayed observe-only until the actual candidate produced fresh RELEASED proof, then obtained its own independent fresh proof. Its prequeued real Versions client `native-backup-b63e7f708fd5` was created 5.220 seconds after the candidate proof and 1.506 seconds after the independent proof, loaded the backup catalog and closed normally. This is **cross-owner queue acceptance**, using source-hash-pinned production queue/observer/native-worker modules; it is not survival of work in the same app after global Stop. The candidate itself performed every ordinary No/Close action.
|
||||
|
||||
The B13 native run issued Close within the first worker budget, so the new retained-phase No/Close branch was **NOT REPLAYED in Mentor**. That branch has source guard, real process race/restart and existing real Win32 adapter evidence. No repeated cold-start attempts were used to manufacture a slower launch.
|
||||
|
||||
B13 actual recovery `backup-restore-3f98efb14448` used the current pending original target and healthy independent source A. Its isolated source and installed target both returned PASS/GREEN/safe; native save/close/release completed without intervention. The old Work directory is retained and all 366 original source files are unchanged. The 27,689-file complete validation library copy progressed through the serial metadata path without a false inactivity handoff.
|
||||
|
||||
Separate frozen metadata-exit harness EXE SHA-256: `7490be1988d823944307510f7cfd22c85cf8570c7c25f6ee60d97f542bb72753`. All 68 packaged product modules equal final B14. A disposable I/O stall at each of hash/copy/validation exercised actual MainWindow close and interpreter exit before releasing the stall; no late dispatch occurred and partial copies were retained. This uses an acceptance-only entry, **not stall injection into the candidate EXE**. The earlier B12/B13 harnesses and all RED/setup attempts remain archived.
|
||||
|
||||
The original complete fault-bearing field snapshot remains unavailable (**NOT REPRODUCED**); the constructed partial copy remains **COPY_BLOCKED** and was never opened. Windows 10 and production SMB remain **NOT RUN**. The earlier first-pass B-control PENDING result and explicit retry remain separate outcomes. No merge, publication or issue closure is performed.
|
||||
|
||||
## Constructed copy and remaining limits
|
||||
|
||||
Constructed-copy experiment: **COPY_BLOCKED; inconsistency NOT REPRODUCED** (1 attempt, maximum 3). The healthy control passed normal native Verify. On a separate disposable copy, the documented native property write and stock Save actually ran; ordinary Work copying encountered Windows sharing violation 32 at the 113th attempted file, database/icdb.dat, after 0.470 seconds. The source still completed Save/Close and authoritative PASS/GREEN with released resources. The partial clone was never opened and no native Repair claim is made for it. This fault-creation instrumentation did not modify the frozen product and does not reproduce the original field incident.
|
||||
|
||||
The original field inconsistency remains **NOT REPRODUCED**. Windows 10 and production SMB/network behavior are **NOT RUN**. Initial B-control PENDING results, diagnostic/manual-cleanup failures, metadata handoffs and the bounded file-probe timeout remain visible in the evidence. This report does not authorize merging, release publication or issue closure.
|
||||
@@ -0,0 +1,114 @@
|
||||
# Issue 15 runtime and recovery candidate
|
||||
|
||||
Refs #15. This candidate records local Windows 11 acceptance and its limits; it is not a published release or field-acceptance approval.
|
||||
|
||||
The final grouped review wave is implemented at `c1e2596` (B14). The complete suite passed **2,418 tests in 594.83 seconds**, actual exit code 0, with zero failures, errors or skips. Actual B13 ordinary Verify/Stop with automatic candidate-owned cleanup and cross-owner queued Versions passed; actual B13 CBB recovery passed source and target verification. B14 preserves explicit ordinary release promotion of an existing cold observer; that narrow change has source/real-process coverage and updated frozen checks. Native cases retain B13 identities. The final scoped independent review passed for 32dcd80..8869093: I1-I3 addressed; zero Critical/Important/Minor findings. This is a technical review, not field acceptance or merge/release approval.
|
||||
|
||||
The PR base is main at e4875b4. The branch also includes the previously approved efb8cae three-second confirmation defaults.
|
||||
|
||||
The change separates native task execution, client exit, coordination-lease release, data recovery and eligibility for the next write. A completed independent item no longer inherits another project's address or a stale historical blocker. Unknown ownership still requires fresh proof; the application does not delete native address or lock files.
|
||||
|
||||
## Final grouped review fixes
|
||||
|
||||
- Ordinary pre-document cancellation now requires positive supervisor and worker no-write events, a bound prelaunch log baseline, and exact worker/process/project/private-desktop identity. Potentially mutating supervisor actions and integration admission revoke this authority before dispatch. Proven no-write startup uses one 30-second cleanup budget and the existing five-second UI handoff; unproved ordinary cleanup and active-write waiting retain their existing policies. Ordinary global Stop still cancels its own queue.
|
||||
- A late loaded ordinary target may enter one separate retained cleanup phase only after its original worker/helpers have exited and fresh complete loaded evidence is available. The existing observer persists the intent and absolute 30-second deadline in the existing session record before any action, under the existing native management mutex. Duplicate observers, explicit release and process restart cannot start it again. Prior No/Tip acknowledgements and the sole Close remain deduplicated. Unknown or multiple documents, changed identities and active writes authorize no action. Cleanup return never establishes release or successful verification; queued writes still use fresh scoped resource proof.
|
||||
- Manifest hashing/copy/validation now run serially on the existing bounded daemon task. Nested executors no longer keep the Python interpreter alive after real MainWindow closure during stalled metadata I/O. Completed work renews inactivity; cancellation prevents late dispatch and incomplete copies remain available as evidence.
|
||||
- Backup recovery no longer holds the global native mutex during abandonable metadata work. It retains the exact library lease and completed-work fences. Only the short pair of Work renames, rollback and installed-state update is protected from abandonment; the task registry guard is never held over filesystem operations. Cancellation after that pair cannot start target verification. An OS rename that itself never returns cannot be safely interrupted; the implementation preserves ownership rather than claiming cancellation completed.
|
||||
|
||||
## Implementation
|
||||
|
||||
- Resource release uses exact project/database/library scope and observed process identity. Read-only file probes retain exclusive handles through release commitment. Legacy receipts are rechecked; a proof for one block cannot close another block's session.
|
||||
- Each UI operation owns its immutable requests, cancellation signal and view revision. Queued work and late callbacks cannot write into a replacement library view. Native writes stay serial; registered worker handles and event admission protect shutdown handoff.
|
||||
- Fast directory discovery and authoritative native catalog/status reconciliation are separate. Directory-only records are not treated as native entries. READY items remain available for management and are excluded from ordinary verification/maintenance admission.
|
||||
- Manual Repair and version history open the official tool for the exact selected project/database, including recovery-required projects. The application does not submit Repair automatically or treat tool closure as successful recovery or READY.
|
||||
- Results and management/recovery/release dialogs remain nonmodal. Three-second defaults preserve one-shot manual priority; unknown occupancy skips, exit saves, and forced termination defaults to cancellation.
|
||||
- Native acceptance exposed two premature timeouts: successful catalog completion after the metadata deadline, and a progressing complete-library manifest exceeding that deadline. Catalog commit/wait now uses the existing read-only native channel; successful metadata work renews inactivity without changing stalled-I/O limits or native transaction behavior.
|
||||
- A transient incomplete native-window scan is retried within the original open/close deadlines. Partial snapshots never authorize a control action. Persistent incomplete observation, unknown prompts and identity mismatches still fail closed.
|
||||
- Same-name update validates the resolved source project name before native removal. A mismatched source remains selectable in the dialog for correction; the UI preview performs no filesystem resolution. The native Add dialog fields are reread immediately before submission.
|
||||
- Save/Close may close the exact owned Project Integration panel only when all four complete statuses say no changes are pending and the unique Close control is enabled. Native inconsistency/error evidence takes precedence; partial, foreign or pending panels do not authorize closure.
|
||||
- A new explicitly confirmed recovery attempt can proceed after a fresh release proof for the exact library and block is recorded under that new operation. Old failed journals remain unchanged; default requests, cached proofs and proofs for another target cannot authorize a retry.
|
||||
- Hidden native worker failures now write compatible result records and tracebacks before exiting. Admission and entered-worker failures remain distinct, existing save evidence is preserved, and exceptions never establish release. This prevents a cancelled frozen worker from blocking on the packaging runtime's error dialog.
|
||||
- Completed release and occupancy checks now renew the existing metadata inactivity clock. Cancellation and abandoned calls cannot be revived; active native transactions keep their existing continuation rules. This fixes a frozen Add that expired across a successful seven-second release proof followed by two successful occupancy checks before any native write.
|
||||
- Diagnostic opening waits for an enabled target frame with no visible loading progress. After fresh project/PID evidence, its sole handler declines the exact owned Forward Annotation prompt. A close intent containing the current operation, target identity and nonce requires an exact supervisor acknowledgement after any in-flight dialog poll. The worker then rechecks readiness, prompts, native errors and cancellation before posting Close; acknowledgement consumes the original 30-second close budget. Ordinary Verify retains its own confirmation policy. A nested save prompt is accepted only through the captured, bounded chain of same-process, same-desktop, hidden disabled Expedition dialogs to the exact frame.
|
||||
- The management dialog's stop-after-current button and active-window close request now stop the batch at the next item boundary. The current item completes its native writes, required directory readback and result bookkeeping. A queued batch can still be cancelled before admission. Global cancellation, shutdown, process identity checks and worker admission remain separate. Real acceptance exposed the former hard-cancel signal interrupting the readback after successful Remove/Add.
|
||||
- Explicit release renews metadata inactivity after completed process snapshots, owner checks, held-file proofs and durable evidence steps. Multiple successful checks can finish without a false UI handoff; a single stalled step still times out. A late or cancelled proof cannot remove the coordination checkpoint or close the retained lease after its context has been abandoned.
|
||||
- Actual early Stop reproduced a late Tip arriving after the one normal empty-frame Close. Startup cleanup now retains the original process handle and, within the original timeout, can dismiss that exact known Tip after rechecking the private desktop, empty frame, complete windows and lack of progress/documents/unknown prompts. When Close already hid the frame, only the Tip's direct hidden, disabled owner is inspected; hidden MDI documents also veto the action. The deadline and release Stop signal are rechecked immediately before clicking. It never posts another Close. Normal residual release shares this guarded acknowledgement for already-retained sessions, then waits for exit without forced termination or another Close. PCB exit, launcher exit and resource release remain separate requirements.
|
||||
- A second actual cancellation race loaded the target after Tip dismissal, while COM/document admission had already stopped. Cancelled diagnostic startup now uses the existing fresh native path/PID logs and exact target MDI identity to decline Forward Annotation and finish one normal Close. Only exact owned No actions are allowed; unknown siblings, foreign identities, visible progress and writes remain protected. The supervisor completes its last poll before creating the cancellation signal, so cleanup is the sole prompt actor and does not wait for a normal-close acknowledgement. Its diagnostic 30-second cleanup budget starts once; an empty-to-loaded transition does not reset it. Cleanup never establishes CHECKED, READY or successful verification.
|
||||
- Diagnostic cancellation yields to the existing registered observer after a bounded five-second wait; ordinary write waiting is unchanged. If the worker exits before its native clients, the same observer keeps ownership until client exit and fresh scoped release proof. Queue admission waits only for an actual initializing or live observer, so historical caches and unrelated libraries cannot create a permanent wait. The original cancellation result remains historical evidence. Report completion writes only unique application evidence files and can finish while native cleanup continues.
|
||||
- Normal residual release can recover an older cancelled diagnostic startup using its complete existing registration, terminal worker, exact current native identity/command/private desktop/MDI and absence of Save evidence. That authority permits cleanup only; a missing prelaunch log baseline is never fabricated or treated as successful opening validation. The action rechecks binding immediately before each No or Close and respects a previously recorded close. Partial, foreign, active-write or ambiguous evidence remains blocked.
|
||||
- One normal Release confirmation gives that proven legacy diagnostic cleanup one 30-second budget, including the known transition after Forward No. It runs in the existing read-only native phase, then the existing registered observer can obtain fresh release proof after late exit without another confirmation. Observer promotion requires the same operation and current Windows user/session; cleanup requires exactly one target MDI document. Ordinary close remains three seconds and ordinary native-write waiting remains unchanged. Pure residual inspection uses metadata-only admission so it remains available during native finalization.
|
||||
|
||||
## Evidence retained locally
|
||||
|
||||
Task 1's durable findings are consolidated here rather than tracking orchestration scratch files. Its final scoped backend coverage was 420 tests after review fixes; those tests cover real Windows exclusive/duplicated handles, scoped receipt trust, cancellation and unknown export ownership. They do not establish real Mentor behavior. Subsequent task evidence and all failed attempts remain in the local acceptance evidence archive; raw field data, process snapshots, host/user identifiers and production paths are not included in this repository report.
|
||||
|
||||
The initial Task 5 full run had 2,111 passes and one obsolete internal test entry. The test now uses the dedicated catalog-only handler while retaining the original mapping-order assertions. A separate regression reproduced child Python importing another editable checkout; test-session configuration now preserves the active worktree in inherited PYTHONPATH without changing machine configuration.
|
||||
|
||||
## Native acceptance recorded so far
|
||||
|
||||
All native operations use complete, hash-verified local copies with main/PCB/database references bound to the selected copied library. Source and frozen runs use independent copies.
|
||||
|
||||
| Source scenario | Observed outcome |
|
||||
|---|---|
|
||||
| Native catalog | Four original registered entries and authoritative READY statuses confirmed; fast discovery alone was not accepted. |
|
||||
| Batch add with first-item name conflict | Existing name rejected safely; independent next source added and confirmed through native catalog/readback. Auto-verify was disabled; the new item remained pending. |
|
||||
| Manual Repair | Official confirmation cancelled without submission, then explicitly confirmed on the healthy added control. Native diagnostics/defragmentation completed; the native tool also reported a missing optional project file. This is not a reproduced field inconsistency. |
|
||||
| Manual backup and native restore | A uniquely described manual version was created; exact archive identity and restore location checked. Cancel and committed restore exercised; native restore and backup verification reported success. |
|
||||
| Versions reopening | Exact restored project reopened successfully; normal close exited with release confirmed. Tool closure alone did not claim repair/restore validation. |
|
||||
| ICDB check after restore | Initial observation-timeout failure retained; corrected same-button rerun returned CHECKED and safe resource release. It did not claim READY. |
|
||||
| Release observations | No active clients remained; zero active sessions were reported released while old observation records were cleared. Conditional native save/cancel/force controls remained disabled. |
|
||||
| Wrong-source same-name update | Earlier attempt exposed a missing name check and retained recovery-required evidence. The corrected UI rejects that source before submission and permits reselection. An audit of 21 major files in three unrelated blocks found no changes. |
|
||||
| Corrected update after recovery | Exact-name source restored the missing target. A new confirmed update in the original application data root succeeded with a fresh scoped release proof; the old recovery-required journal was preserved. |
|
||||
| Ordinary verification | Recovered target reached PASS/GREEN with native save committed, document closed, helper exited and resources released, without manual intervention. An earlier different target required manual native panel closure and remains classified as manual intervention. |
|
||||
| CBB backup recovery | Actual dialog empty-input rejection, chooser cancellation and No/Yes confirmation were exercised. The isolated source validation and installed target verification both passed with GREEN; the old Work directory was retained. No manual native intervention was needed. |
|
||||
| Automatic Project Integration panel close | The B control's first Verify automatically closed the completed panel and finished Save/Close/release, but authoritative status stayed PENDING and was correctly reported as FAIL. One explicitly requested fresh Verify then confirmed the native reusable-cell save and reached PASS/GREEN. The exact first-pass noncommit cause remains unconfirmed. |
|
||||
|
||||
The first full regression after these changes recorded 2,144 passes and eight fixture failures. Three tests still edited the old project filename, four lifecycle cases used an outdated control-helper signature, and one independent-item test reused a differently named source. The fixture updates preserve the original identity and lifecycle assertions. After the hidden-worker correction and isolation of simulated clients between tests, the full run at that stage passed **2,175 tests in 522.52 seconds**, exit code 0. The previous full regression at code commit 4402486 passed **2,246 tests in 572.82 seconds**, with zero failures, errors or skips and exit code 0. One earlier run was cooperatively interrupted after 2,151 passes when old test doubles contaminated the new entry tests; its stack and interrupted result are retained separately. Compilation and diff checks also passed.
|
||||
|
||||
The previous complete regression at code commit a3f69de passed **2,351 tests in 497.58 seconds**, exit code 0, with zero failures, errors or skips. Log SHA-256: `aa820f1202becd30ee220c8e660fcde0e063d9ed874023ab3487108aedae214d`; JUnit SHA-256: `7d951ad853978e58aabaa481656c15b8610f01fdf9d64f67af0585dda9bc3bbe`. Actual native applications were normally closed and the writer/management mutexes were idle before and after this run.
|
||||
|
||||
The previous candidate B9 is built from code commit a3f69de. All 68 packaged modules, assets, bridge programs, scripts and icon images match; all 242 ZIP-extracted files match the build. Executable SHA-256: `bfd6c122724f71a2aac4748ed01336a9949aa753f9c58aca55db574668140083`. ZIP SHA-256: `4c589bae6bf7b68732cd7ebe373b2924016c71f6731fd661c1cd0fd848427438`. Five actual pre-cancelled frozen entry routes exited without acknowledgement or termination and wrote the expected results. Common GUI, worker, owner-probe and dialog-agent smoke passed.
|
||||
|
||||
B9 repeated the two affected native cases. Versions was queued after exact diagnostic PCB registration and before Stop. The UI reached its cancellation terminal state in 6.672 seconds; the original result remains CANCELLED/safe=false. Automatic guarded Tip/Forward No/Close cleanup and the existing observer produced fresh library release proof; the queued Versions native client started 1.684 seconds after that proof and loaded its backup catalog. No Release click or manual diagnostic native action occurred. Separately, B5 produced a real cancelled, loaded-target legacy session. B9's initial inspection succeeded and one normal Release confirmation released the PCB, launcher and database server with fresh RELEASE_CONFIRMED proof in 22.634 seconds. The UI agreed and disabled Confirm; no Recheck, second confirmation, manual native action, Save, annotation or forced termination occurred. The old cancellation result was retained. The earlier B8 legacy path required multiple confirmations and is preserved as an incomplete workflow, not a final pass.
|
||||
|
||||
The [acceptance matrix](2026-11-17-issue15-acceptance-matrix.md) records each native case against its actual executable hash. Earlier successful cases remain bound to their original builds; they are not relabelled as new-build tests. The constructed-copy experiment ended with Windows sharing violation 32 at database/icdb.dat during native Save. Its source passed GREEN and released normally; the incomplete clone was never opened. The B5 early Stop returned CANCELLED with retained PCB/launcher and safe_to_continue=false; manual Tip OK alone completed the pending Close. That failure is preserved. The late-Tip fix and its new native acceptance are recorded separately.
|
||||
|
||||
## Limits
|
||||
|
||||
Review round 1 corrected two legacy-cleanup defects. The real residual snapshot adapter now retains hidden MDI document siblings before the exact-one-document guard, and a Tip without any previous Close returns to guarded loaded-target observation within the same deadline. A Tip after an actual Close retains wait-only behavior. The focused regressions first reproduced both failures, then 134 related tests passed; an independent harmless real Win32 window probe confirmed hidden-sibling no-action and the single-document normal Close path. This probe is not Mentor acceptance.
|
||||
|
||||
A delayed Tip dismissal regression then exposed repeated OK posts in the new continuation path. A separate set of Tip handles now limits acknowledgement to once per cleanup intent while retaining the original deadline and Forward handling. Final related coverage passed 180 tests in 29.43 seconds. The first round-1 full run retained 2,355 passes and one failed UI-reopen fixture: it claimed its worker had exited while registering the still-live pytest PID, so the real cold observer correctly blocked admission. The fixture now launches a harmless real worker, exercises actual mutex admission refusal, waits for real process exit and retains the original receipt/reopen assertions; its focused run passed. No product queue bypass or UI timeout increase was introduced.
|
||||
|
||||
B10 is built from `701e5cd`, with EXE SHA-256 `a6271e4219a02123e301ed1e0ea3109e78307bf1f92574b4a5cacb70690695a4` and ZIP SHA-256 `d4bd42416ea8d12a249ff1d9c8854eb76d2f81bb7ff869ff43dd92a331c647a0`. All 68 modules/resources and 242 extracted files match; five cancelled frozen entry routes and common smoke passed. Actual B5-to-B10 legacy diagnostic recovery used one confirmation, zero Rechecks/manual native actions, and reached fresh RELEASE_CONFIRMED after an intermediate PARTIAL; final receipt at 35.387 seconds and the UI agreed. This actual native case entered at loaded Forward; both Tip states are covered by focused regression, not claimed as newly replayed Mentor Tip states.
|
||||
|
||||
The final round-1 candidate B11 is built from `8818fa9`: EXE SHA-256 `03452e39f394c3c63113aaa701f64bacf14e817ae3b4e194965f333ecc645b98`, ZIP SHA-256 `34b3646b27afae22ec43a415ca19bbd32a91c0a4c941d37d6289c76cea9ca730`. Module/resource equality, all 242 extracted files, five cancelled frozen entries and common smoke passed. Only the residual-session module changed from B10 to add per-intent Tip acknowledgement tracking. B10 native/button receipts remain bound to B10; B11 delayed Tip behavior has source regression coverage, not a new actual Mentor Tip replay.
|
||||
|
||||
The final round-1 complete suite at `8818fa9` passed **2,358 tests in 451.34 seconds**, exit code 0, with zero failures, errors or skips. Log SHA-256: `5544f2e17f84a74e67faa81403a0b13679728c432ab269f2f5050cfe42103831`; JUnit SHA-256: `8e734b1f6298d368b1b059019e419b687c5284c472ad04a999f0b73e2254cd16`. Compilation/diff checks and the post-suite native-process/writer/management idle checks passed. The earlier failing run and test-harness setup failures remain archived.
|
||||
|
||||
The missing frozen controls were exercised on B10: Open logs and Open exception evidence opened the exact current application folders, verified by private-desktop Explorer breadcrumbs; queued CBB recovery was cancelled before admission and created no recovery job; result Release opened the correct residual plan; Continue started only the second previously skipped item, which passed GREEN, without replaying the terminal first item. The first result summary elapsed under its existing three-second Close default. After ordinary main-window Release and normal dialog closure, production code recreated the Continue summary; the observer clicked that actual enabled control without injecting results or calling application methods. One bounded repeat captured result Release within the default window.
|
||||
|
||||
That B10 button exercise exposed the **historical ordinary-verification cancellation defect**: Stop 0.547 seconds after first PCB registration, before any Save, returned CANCELLED/safe=false at PCB_STARTING; the target later loaded Forward Annotation and remained alive. The B10 automatic loaded-startup cleanup required diagnostic-only authority, so it did not clean this ordinary case. Exact manual Forward No and one normal Close after no-modal/no-progress checks were required before fresh release. The bounded result-button repeat reproduced the same retained state. These are failures of unattended ordinary cancellation, not successful automatic cleanup or protected active-Save cases, and remain preserved as failures; the grouped fix and B13 acceptance are recorded below.
|
||||
|
||||
The exact complete fault-bearing field snapshot is unavailable, so the original field inconsistency remains **NOT REPRODUCED**. Any bounded constructed live-copy experiment is reported separately. Windows 10 and production network/SMB behavior are **NOT RUN**. No merge, published release or issue closure is authorized by this candidate report.
|
||||
|
||||
One local B control required a second explicit verification after an initial completed native Save/Close left it PENDING. Both results are retained; automatic retries were not added and the initial failure is not counted as a pass.
|
||||
|
||||
## Final-wave evidence and limits
|
||||
|
||||
B14 EXE SHA-256: `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c`. ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`. All 68 packaged product modules/resources and all 242 extracted files match source/build. Five pre-cancelled frozen routes and common GUI/worker/owner-probe/dialog-agent smoke passed. Full-suite log SHA-256: `d9c57b7998e02154fb703f0fe2ba1f37f73dc4687d116c4b6efc0e5ad7e5c30e`; JUnit SHA-256: `4303cc123e90689103cc4135e483ac936b04a052067e952a1861ae167c7811ea`. Native clients and writer/management mutexes were idle before and after the full suite.
|
||||
|
||||
B13 (`5e9509e`) retains EXE `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` and ZIP `7a1da94e05b85873f791cde77907bdc280106768fbf84e5d89066ab8aa57a61b`. A final self-audit found that the new ordinary explicit-release branch bypassed existing cold-observer promotion. Its focused test failed before the two-line ordering correction at `c1e2596`; 110 related tests then passed in 21.96 seconds, including actual harmless worker exit, cold-observer promotion and queue proof. The in-progress B13 full suite was interrupted through its own execution session before editing, and is archived without a completion/JUnit claim. No additional native matrix was run for this narrow B14 delta.
|
||||
|
||||
The three review defects had retained RED evidence: actual MainWindow subprocess exit hung on stalled hash/copy/validation; real recovery callers held the unrelated native channel and could install after abandoned metadata; ordinary cancelled startup failed to clean a later loaded target. B13 related observer coverage passed 232 tests in 34.81 seconds, including an actual two-process mutex/file race between observer and explicit release plus a process restart. These race tests stub the native evidence/action boundary; they are not Mentor window tests.
|
||||
|
||||
B12 (`906cfc0`, EXE `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc`, ZIP `bbe68005469d8b6cf87726200ef85646e442de45d164ab2ac0aec23b51d0bd65`) retained a new failure: ordinary `verify-642171759614` returned its visible cancellation terminal state in 7.797 seconds, but Forward loaded at 34.406 seconds, after the worker cleanup budget. Exact manual No/normal Close was used solely to clear that failed run. A later independent queue-helper attempt was refused with sharing violation 32 before native creation while two releasing observers raced for the coordination lease. Both failures are archived and are not relabelled as B13 passes.
|
||||
|
||||
B13 ordinary `verify-71aee0603183` reached the visible terminal state in 7.375 seconds. Its candidate worker acknowledged Tip at 21.359 seconds, Forward No at 27.422 seconds and one Close at 28.750 seconds; native exit followed the original cleanup deadline. Read-only sampling confirmed kernel exit. The original result remains CANCELLED/safe=false. No Release click or manual ordinary native action occurred. The helper stayed observe-only until the actual candidate produced fresh RELEASED proof, then obtained its own independent fresh proof. Its prequeued real Versions client `native-backup-b63e7f708fd5` was created 5.220 seconds after the candidate proof and 1.506 seconds after the independent proof, loaded the backup catalog and closed normally. This is **cross-owner queue acceptance**, using source-hash-pinned production queue/observer/native-worker modules; it is not survival of work in the same app after global Stop. The candidate itself performed every ordinary No/Close action.
|
||||
|
||||
The B13 native run issued Close within the first worker budget, so the new retained-phase No/Close branch was **NOT REPLAYED in Mentor**. That branch has source guard, real process race/restart and existing real Win32 adapter evidence. No repeated cold-start attempts were used to manufacture a slower launch.
|
||||
|
||||
B13 actual recovery `backup-restore-3f98efb14448` used the current pending original target and healthy independent source A. Its isolated source and installed target both returned PASS/GREEN/safe; native save/close/release completed without intervention. The old Work directory is retained and all 366 original source files are unchanged. The 27,689-file complete validation library copy progressed through the serial metadata path without a false inactivity handoff.
|
||||
|
||||
Separate frozen metadata-exit harness EXE SHA-256: `7490be1988d823944307510f7cfd22c85cf8570c7c25f6ee60d97f542bb72753`. All 68 packaged product modules equal final B14. A disposable I/O stall at each of hash/copy/validation exercised actual MainWindow close and interpreter exit before releasing the stall; no late dispatch occurred and partial copies were retained. This uses an acceptance-only entry, **not stall injection into the candidate EXE**. The earlier B12/B13 harnesses and all RED/setup attempts remain archived.
|
||||
|
||||
The original complete fault-bearing field snapshot remains unavailable (**NOT REPRODUCED**); the constructed partial copy remains **COPY_BLOCKED** and was never opened. Windows 10 and production SMB remain **NOT RUN**. The earlier first-pass B-control PENDING result and explicit retry remain separate outcomes. No merge, publication or issue closure is performed.
|
||||
@@ -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,38 @@
|
||||
# PR 16 small review follow-up
|
||||
|
||||
Refs #15. Follow-up to review comment 446 on `b4737b5`; this does not authorize
|
||||
merging, release publication or issue closure.
|
||||
|
||||
- Verify now propagates a registered `TaskHandoff` instead of recording it as a
|
||||
close error and continuing a second native cleanup. It preserves the cancelled
|
||||
or failed result as evidence before returning cleanup ownership to the observer.
|
||||
- Repair runs local worker cleanup even when observer registration or handoff
|
||||
raises. A live native worker retains its existing observer-owned handles;
|
||||
`DesktopWorker.close()` does not terminate it or claim resources are released.
|
||||
- Starting an ICDB check binds the fallback Stop signal to the task's actual
|
||||
context. The normal global Stop and per-task cancellation policies are unchanged.
|
||||
- Native Versions/Repair errors now explain that the main PRJ must contain exactly
|
||||
one nonempty `iCDBDir` using a project-local relative path. Absolute paths,
|
||||
including absolute paths inside Work, and multiple entries remain unsupported.
|
||||
No PRJ is rewritten and no native tool is launched for rejected input.
|
||||
|
||||
The previously approved three-second defaults remain: submitted execution
|
||||
continues; unknown ownership/read-write confirmation skips; version selection
|
||||
uses the last manual save; exit saves; force termination defaults to cancellation.
|
||||
This follow-up does not add or change those product decisions.
|
||||
|
||||
## Validation
|
||||
|
||||
The unchanged targeted baseline passed 31 tests. New behavior regressions first
|
||||
recorded four failures and four passes; after the fixes all eight passed.
|
||||
Related Verify, Repair, native-entry, observer, ICDB/UI and shutdown regressions
|
||||
passed **363 tests in 157.24 seconds**, exit code 0.
|
||||
Compilation and whitespace checks also passed. Independent scoped review found
|
||||
zero Critical, Important or Minor issues in the follow-up fixes.
|
||||
|
||||
These are source tests with real task contexts and Qt controls; native process
|
||||
boundaries are replaced where the tests require them. This follow-up does not
|
||||
claim a new full-suite run, rebuilt frozen package, or actual Mentor acceptance.
|
||||
The earlier 2,418-test full run and B14 package still belong to source `c1e2596`.
|
||||
Original field inconsistency, the retained-phase native replay, Windows 10 and
|
||||
production SMB acceptance remain outstanding as documented in the main matrix.
|
||||
@@ -0,0 +1,34 @@
|
||||
# CBB 刷新校验 v0.2.4-beta.4
|
||||
|
||||
Refs #15。延续测试版发行,供隔离副本和现场进一步验证。
|
||||
|
||||
## 本版改动
|
||||
|
||||
- 分开任务执行、原生客户端退出、资源释放及数据待恢复状态,减少旧记录和无关工程导致的误阻塞。
|
||||
- 普通校验启动阶段取消时,只有完整未写入证明和准确归属才能处理已知提示并安全收尾;原结果保留为取消,不改成 READY。
|
||||
- 已登记观察者可以持久化接管一次迟到启动的安全收尾;不循环重新打开或自动重放写操作。
|
||||
- 文件哈希、复制、校验不再因嵌套线程池阻止程序退出。恢复准备不长期持有全局原生通道,迟到任务不能继续安装。
|
||||
- 修正交接异常传递、Repair 本地资源清理、ICDB 停止信号绑定,以及管理窗口销毁后的迟到结果回调。
|
||||
- 保留当前图标、三个菜单、READY 操作范围及手动备份政策。版本/Repair 对绝对或多条 iCDBDir 的拒绝原因现在明确显示,不自动修改工程引用。
|
||||
- 沿用已确认的 3 秒默认策略;未知占用和读写确认默认跳过,强制终止默认取消。真实原生写入仍受保护。
|
||||
|
||||
## 发布验证
|
||||
|
||||
本次源码全量 **2,428 项通过,659.54 秒,退出码 0**;JUnit 零失败、零错误、零跳过。
|
||||
管理窗口销毁后的成功/失败回调先复现失败,再通过实际 Qt 信号测试验证修复。
|
||||
生命周期模拟测试隔离无关的机器 WMI/文件探测延迟,真实占用、独占句柄、资源证明和原生写入保护测试继续保留。
|
||||
新增发布改动经独立限定复核,无 Critical、Important 或 Minor 遗留项。
|
||||
|
||||
Windows 包使用合并后的 main 提交构建并上传云端;仓库当前未配置云端打包工作流。
|
||||
最终源码提交、冻结模块/资源及图标核对、冻结冒烟和 ZIP 校验结果见发行附件
|
||||
`release-info.json`、`release-smoke.json` 和 `SHA256SUMS.txt`。
|
||||
发布前因 C 盘耗尽中断的一轮,以及后续失败/修订的测试记录均保留,不计为通过。
|
||||
|
||||
## 使用与范围
|
||||
|
||||
完整解压 Windows ZIP,运行 `CbbRefreshVerify-Background/CbbRefreshVerify.exe`,保留 `_internal`。
|
||||
库写操作前按提示手动备份。程序回滚不能撤销已经完成的中心库写入。
|
||||
|
||||
自动 ICDB Repair 仍关闭。原现场不一致故障未完整复现;独立接管阶段的原生 No/Close 重放、Windows 10、生产 SMB 尚未验收。
|
||||
此前 B13 实际普通取消、后续原生调度与备份恢复的通过记录保留其原始源码/包版本,不能算成本发行包的原生重跑。
|
||||
发布测试版不关闭工单 #15,也不代表这些现场边界已经解决。
|
||||
@@ -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,21 @@
|
||||
# CBB 刷新校验 v0.2.4-beta.3
|
||||
|
||||
本测试版整合 PR #14:普通 CBB 导入与可选导出诊断解耦、写前未知会话确认、PCB 打开句柄顺序修复、任务绑定中心库,以及审查评论 414/430 的修复。
|
||||
|
||||
- 无效来源、可选 Verify 失败不再阻止已释放的独立条目继续。上传完成、校验通过和 READY 分开报告。
|
||||
- 无法取得写入确认、或恢复安装前跳过,记录为 SKIPPED;取消为 CANCELLED,保留具体原因。
|
||||
- 文件身份采集失败仍为 RECOVERY_REQUIRED;由独立的原生退出和资源证据决定后续资格,禁止自动重放该目标。
|
||||
- 无未知原生客户端时只探测一轮;等待用户确认后仍重新检查进程和资源。
|
||||
- 保留三个横向菜单和当前图标,不自动备份整个中心库;写操作前仍需人工备份。
|
||||
|
||||
下载 Windows ZIP 后完整解压,运行 `CbbRefreshVerify-Background/CbbRefreshVerify.exe`,保留同目录 `_internal`。
|
||||
发布程序由 Windows 主机从合入后的 main 构建并上传云端;不标记为云端 Windows runner 构建。
|
||||
发行附件的 `release-info.json`、`release-smoke.json` 和 `SHA256SUMS.txt` 记录实际提交、验证结果及文件散列。
|
||||
|
||||
导入确认原生注册、名称/分区、工程关联、允许的顶层块及 Layout,未证明原理图语义等价。
|
||||
UPLOADED 不等于 READY;完整 Verify 独立可选。已有其他 LibraryManager 时原生入口仍拒绝,需正常关闭相关会话再继续。
|
||||
|
||||
自动 ICDB Repair 仍关闭。EDIF 崩溃根因、Windows 10、跨机器 SMB 和现场服务器会话失联修复仍未验收;
|
||||
测试版发布不代表这些问题已解决,不自动关闭工单。
|
||||
|
||||
回滚程序时完整解压此前发布包并在关闭新客户端后使用;程序回滚不撤销已完成的中心库写入,工程恢复须依据逐项证据和人工备份。
|
||||
@@ -0,0 +1,79 @@
|
||||
# 工单 #15 实测问题全量修复实施计划
|
||||
|
||||
**Goal:** 消除误阻塞,打通手动修复与版本管理,逐项验证工单全部实测问题。
|
||||
**Architecture:** 复用会话记录、串行队列和原生适配器;区分任务执行、客户端退出、协调租约释放、数据待恢复及下一项写入资格。范围不明时只隔离受影响资源,不冻结界面或无关库。
|
||||
**Tech Stack:** Python 3.12、PySide6、pywin32、Mentor EE7.9.5,不新增依赖。
|
||||
**Spec:** 用户在聊天中批准的五节计划;证据及确认/待确认边界见 `F:/CbbIssue15-20261116/analysis.md`。
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 基线 efb8cae,独立分支 codex/issue15-runtime-unblock;保留原脏工作区。
|
||||
- 自动 ICDB Repair 继续关闭。明确不一致时报告并跳过,提供实际可用的手动 Repair/历史恢复入口。独立项继续。
|
||||
- 普通校验确认工程唯一归属后,将主 PRJ 和 PCB PRJ 对齐所选中心库,保留原文件证据;ICDB 检查不修改引用。
|
||||
- READY 不进入校验/维护;管理允许 READY。原生写入串行,同名更新 Remove→Add 不被打断。
|
||||
- 手动备份政策;不新增自动整库备份。不手删原生锁/地址,不杀用户程序,不抢前台鼠标。
|
||||
- 默认确认 3 秒:已提交执行继续;未知占用/PCB 读写确认跳过项;历史版本最后手动保存;退出前保存;强制终止取消。人工优先、仅生效一次。
|
||||
- VerifyRequest/VerifyResult 与旧记录兼容。未知旧记录重新核对,不直接采信旧证明。
|
||||
- 先失败复现再最小修复,阶段验证后单独提交。源码回归不冒充冻结包或现场原生验收。
|
||||
- 验收只用隔离完整副本;不改生产库。未复现原故障必须明确。不得自动合并发布或关闭工单。
|
||||
|
||||
## Task 1: 会话资源范围、锁与释放证明
|
||||
|
||||
Owned areas: library_lock/session_record/icdb_ownership/operation_lifecycle/residual_sessions/owner_probe and a bounded file-probe helper/CLI if needed; associated tests. Coordinate shared changes through controller.
|
||||
|
||||
- [ ] 先新增行为回归并见证失败:A 退出而 B 有地址;未知检查点+明确其他工程进程;父句柄保留后子进程获取;迟到观察不能清除新任务;慢 A 探测不挡 B 内存/租约检查。
|
||||
- [ ] 在现有会话和释放证明中增补可选 lease_state/resource_scope/blocked_resources/data_recovery_required,记录目标工程、数据库、实际共享依赖和操作身份;旧记录缺范围重新核对。
|
||||
- [ ] 分开客户端退出、协调租约释放和数据恢复;已退出任务不因为其他块地址永久占有自己的句柄。不将文件存在/PID文本/地址年龄/端点不可达当作权威占用或可写证明。
|
||||
- [ ] release_residual_sessions 传递准确范围;观察项不进入关闭目标、不增加主动释放计数。未知检查点也按实际资源判断,不要求全部 Mentor 进程退出。
|
||||
- [ ] 地址不手动删除;有地址且需判定的目标复用 inspection-only 原生判定。真实目标占用/未返回共享写入依旧保护,健康工程不跑额外 ICDB 扫描。
|
||||
- [ ] 全局锁只保护快照/提交;进程/文件/网络探测移出锁,提交前核对 lease/operation 身份。
|
||||
- [ ] 有阻塞风险的只读文件探测放独立 helper,默认单次最多10秒,支持停止;只能终止纯探测 helper。需要持有证明句柄跨提交时使用握手保持保护,不引入无保护 TOCTOU。
|
||||
- [ ] 相关旧回归及真实 Windows 句柄/父子进程试验通过,写阶段记录并提交。
|
||||
|
||||
## Task 2: 取消、超时、退出与批次继续
|
||||
|
||||
Owned areas: failed_session/verify_runner/desktop_worker/operation_queue and lifecycle integration/tests. UI adoption delegated to Task 4.
|
||||
|
||||
- [ ] 失败用例覆盖晚到每日提示、读写确认、历史版本取消、PCB先退/启动器后退、COM无文档、慢探测、失败后独立项继续、取消后的新任务。
|
||||
- [ ] 正常执行和失败启动收尾复用已知弹窗识别。精确绑定创建身份、工程、私有桌面;未知弹窗不猜按钮。取消收尾最多30秒返回终态或交给独立观察。
|
||||
- [ ] 现有队列增补每批不可变任务上下文(operation_id、library/aliases、targets/resources、stop、state),停止事件不跨任务复用;原生写保持串行,事务不能在Remove与Add间让出。
|
||||
- [ ] 仅资源相关项受保护;安全业务失败继续,未确认范围的后续项记录跳过并结束汇总,不无限等待。回调绑定任务身份,不覆盖新库。
|
||||
- [ ] 准备有界关闭接口:30秒内完成或把原生事务交给有证据监督,禁止线程池析构/文件探测导致无限等。启动和交接记录保障重启可见,不重放写操作。
|
||||
- [ ] 运行覆盖测试并提交;向 Task 4 明确队列状态、停止和关闭接口。
|
||||
|
||||
## Task 3: 版本管理、手动 Repair、工程身份和原生错误
|
||||
|
||||
Owned areas: native_backup/mentor_adapter/library_manager_verify/verify diagnostics/maintenance_entry/native occupancy; may amend runner stage integration after Task 2.
|
||||
|
||||
- [ ] 先写失败测试:版本 worker 前的父保留租约、子启动/登记失败、无备份、关闭再打开、主/PCB引用不同、旧日志不作新诊断、菜单返回但没PCB。
|
||||
- [ ] 版本启动前复核本任务历史租约;使用已有登记/启动门控,先持久登记身份再开原生工具,执行方持实际租约,失败给明确归属与恢复路径。
|
||||
- [ ] 提供绑定准确PRJ/数据库的原生 Repair 入口,保留版本与备份UI;自动Repair关闭。不得绕过活跃事务;数据待恢复本身不得禁用手动恢复入口。
|
||||
- [ ] 普通校验以同一工程归属确认统一两层PRJ,保留编码/原字节;诊断不修改。重新核对实际打开身份。
|
||||
- [ ] 从本轮增量日志提取副本不一致/ICDB/失联及目标DB;只报告“发现问题、未修复”,独立项继续。
|
||||
- [ ] LM派发观察上限min(45秒,用户超时),有PCB再进入正常启动计时;无PCB快速失败并正常收尾,默认不启用前台鼠标替代。
|
||||
- [ ] 保存成功、关闭、资源释放、权威READY独立记录。仍PENDING不得记通过;历史恢复是版本待核对,原生窗口关闭不冒充Repair成功。
|
||||
- [ ] 相关回归与可用的隔离原生路径通过,记录后提交。
|
||||
|
||||
## Task 4: UI、输入、计数与无人值守集成
|
||||
|
||||
Owned areas: ui/main_window/child dialogs/library_reader/models/application settings and queue adoption; associated tests.
|
||||
|
||||
- [ ] 先复现排队禁用全界面、首次读库无法取消、迟到跨库回调、模态结果、证据按钮条件错误、坏库输入和计数问题。
|
||||
- [ ] 接 Task2 上下文,每任务独立停止/回调。排队不置全局不可操作;搜索筛选、换库、证据、取消排队、释放可用。原生操作排队,重复提交同一快照不重复执行。
|
||||
- [ ] 读库失败保留旧表并标失效,禁止旧表写;快速显示目录结果,原生目录复核后台入队。目录发现/原生记录/缺工程分别计数,未复核显示未知。
|
||||
- [ ] 空文件、错误后缀、锁路径是目录、权限失败输出稳定分类;快速读不自称验证了原生格式。
|
||||
- [ ] 结果QMessageBox显式NonModal、3秒默认关闭,失败/取消有证据即可打开;日志入口打开logs。记忆上次成功读取路径,启动仅回填不自动执行。
|
||||
- [ ] 版本/Repair按钮绑定一个可见非READY目标,不能以未校验或数据待恢复直接禁用;真实资源冲突有简短原因。
|
||||
- [ ] 全面复核选择/清空/隐藏项、READY资格、状态刷新、每个条件按钮。现有3秒策略完整集成,人工抢先选择/窗口隐藏/计时竞态不得重复动作。
|
||||
- [ ] 关闭接Task2有界交接;UI只留必要操作/错误,不写开发说明。
|
||||
- [ ] 全部相关Qt测试和381/3000项响应检查通过,记录后提交。
|
||||
|
||||
## Task 5: 全量回归、真实冻结包验收与PR
|
||||
|
||||
- [ ] 全量pytest、compileall、diff检查、模块/资源/PE图标与冻结包一致性;每次失败保留,修订后重验相应范围。
|
||||
- [ ] 逐按钮清单覆盖主窗口、管理、恢复、原生版本/Repair、释放及所有条件按钮;源码Qt与最终冻结包分别执行。
|
||||
- [ ] 非规则点击覆盖双击执行、取消重试、检查中排队/换库、隐藏勾选、结果框存在、关闭原生窗口、3秒边界竞争和主程序退出重启。
|
||||
- [ ] 真实Windows进程/文件锁覆盖无持有LOCK、父子冲突、外部无关进程、真实目标独占句柄、地址残留和慢/失败查询。不能修改或终止其他任务。
|
||||
- [ ] Mentor真实独立副本验证普通校验READY、ICDB批检后独立继续、手动Repair、版本回退后重开、批量新增/同名更新/移除/恢复;原生失败单独列明,不用模拟替代。
|
||||
- [ ] 不一致故障必须对应实际原生特征;没有现场一致副本则标未复现,不拿格式损坏替代。Win10/生产网络未测明确保留。
|
||||
- [ ] 候选包、逐问题/逐按钮验收表、新PR。未经现场验收不自动合并发布、不关工单。
|
||||
@@ -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`,保留现场原始故障与冻结包验收缺口。
|
||||
+1
-1
@@ -3,7 +3,7 @@ requires = ["setuptools>=84.1.0"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
[project]
|
||||
name = "cbb-refresh-verify"
|
||||
version = "0.2.4b2"
|
||||
version = "0.2.4b5"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
|
||||
|
||||
|
||||
@@ -1 +1 @@
|
||||
__version__ = "0.2.4b2"
|
||||
__version__ = "0.2.4b5"
|
||||
@@ -72,11 +72,71 @@ def _positive_int(value):
|
||||
return number
|
||||
|
||||
|
||||
def _native_worker_entry(mode, request):
|
||||
"""Contain hidden-worker failures so a frozen bootloader cannot show a modal error."""
|
||||
import contextlib
|
||||
import json
|
||||
import traceback
|
||||
from .desktop_worker import run_native_worker
|
||||
state = {'worker_entered': False}
|
||||
result_name = {'verify': 'outcome.json', 'repair': 'repair-result.json'}.get(mode, 'result.json')
|
||||
try:
|
||||
with request.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
||||
if mode == 'native-backup':
|
||||
from .native_backup import run_native_backup_worker
|
||||
return run_native_backup_worker(request, admission_state=state)
|
||||
if mode == 'management':
|
||||
from .native_management import catalog_worker_main, management_worker_main
|
||||
job = json.loads(request.read_text(encoding='utf-8'))
|
||||
action = catalog_worker_main if job.get('worker_role') == 'catalog_readonly' else management_worker_main
|
||||
elif mode == 'repair':
|
||||
from .native_repair_ui import repair_worker_main
|
||||
action = repair_worker_main
|
||||
else:
|
||||
from .mentor_adapter import worker_main
|
||||
action = worker_main
|
||||
return run_native_worker(action, request, admission_state=state)
|
||||
except Exception as error:
|
||||
trace = traceback.format_exc()
|
||||
entered = state['worker_entered']
|
||||
reason = str(error)
|
||||
cancelled = not entered and reason.startswith('WORKER_CANCELLED:')
|
||||
detail = ('VERIFY_CANCELLED: ' if mode == 'verify' and cancelled else '') + reason
|
||||
path = request.with_name(result_name)
|
||||
try:
|
||||
result = json.loads(path.read_text(encoding='utf-8'))
|
||||
if not isinstance(result, dict): result = {}
|
||||
except (OSError, ValueError):
|
||||
result = {}
|
||||
if mode == 'verify':
|
||||
result.update(status='CANCELLED' if cancelled else 'FAIL', stderr=detail,
|
||||
error_stage='worker' if entered else 'admission', safe_to_continue=False)
|
||||
else:
|
||||
result.update(success=False, status='FAILED', detail=detail, safe_to_continue=False)
|
||||
failure = dict(stage='worker' if entered else 'admission', reason=reason,
|
||||
worker_entered=entered, native_started=None if entered or mode == 'native-backup' else False,
|
||||
safe_to_continue=False)
|
||||
# An exception is never a release proof, and existing Save/Close evidence is retained.
|
||||
for output, value in ((path, result), (request.with_name('worker-failure.json'), failure)):
|
||||
try:
|
||||
output.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
except OSError:
|
||||
pass
|
||||
try:
|
||||
with request.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||
log.write(trace)
|
||||
except OSError:
|
||||
pass
|
||||
return 2 if mode == 'management' else 1
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--file-probe', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--native-backup-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--management-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||
@@ -89,18 +149,18 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||
if args.file_probe:
|
||||
from .file_probe import file_probe_main
|
||||
return file_probe_main(args.file_probe)
|
||||
if args.owner_probe:
|
||||
from .owner_probe import owner_probe_main
|
||||
return owner_probe_main(args.owner_probe)
|
||||
if args.native_backup_worker:
|
||||
from .native_backup import native_backup_worker_main
|
||||
return native_backup_worker_main(args.native_backup_worker)
|
||||
return _native_worker_entry('native-backup', args.native_backup_worker)
|
||||
if args.management_worker:
|
||||
from .native_management import management_worker_main
|
||||
return management_worker_main(args.management_worker)
|
||||
return _native_worker_entry('management', args.management_worker)
|
||||
if args.repair_worker:
|
||||
from .native_repair_ui import repair_worker_main
|
||||
return repair_worker_main(args.repair_worker)
|
||||
return _native_worker_entry('repair', args.repair_worker)
|
||||
if args.collect_failure_logs:
|
||||
from .verify_diagnostics import failure_logs_main
|
||||
return failure_logs_main(args.collect_failure_logs)
|
||||
@@ -108,11 +168,7 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
from .dialog_agent import dialog_agent_main
|
||||
return dialog_agent_main(args.dialog_agent)
|
||||
if args.verify_worker:
|
||||
from .mentor_adapter import worker_main
|
||||
import contextlib
|
||||
with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
||||
return worker_main(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")
|
||||
try:
|
||||
if args.batch_lmc:
|
||||
|
||||
@@ -33,6 +33,7 @@ def _idle_check(library, project, pcb, *, confirmation=None, evidence=None, bloc
|
||||
from .icdb_ownership import database_directories, unreleased_addresses
|
||||
from contextlib import ExitStack
|
||||
import win32con, win32file
|
||||
from .operation_queue import note_metadata_progress
|
||||
directories = database_directories(library, project, pcb)
|
||||
scope = (Path(project).parent, *directories)
|
||||
def owners():
|
||||
@@ -61,6 +62,7 @@ def _idle_check(library, project, pcb, *, confirmation=None, evidence=None, bloc
|
||||
unknown = owners()
|
||||
resources() # Never hold exclusive probe handles while waiting for a user.
|
||||
if not unknown:
|
||||
note_metadata_progress()
|
||||
return
|
||||
if confirmation is None:
|
||||
from .write_admission import WriteAdmissionDeclined
|
||||
@@ -71,6 +73,7 @@ def _idle_check(library, project, pcb, *, confirmation=None, evidence=None, bloc
|
||||
if unknown and not confirmation.confirmed(library, unknown):
|
||||
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 占用确认后出现新的未知进程,请重新检查。')
|
||||
resources()
|
||||
note_metadata_progress()
|
||||
|
||||
|
||||
def _native_scope_match(command, *, roots=(), files=()):
|
||||
@@ -161,7 +164,7 @@ def _align_library(project, pcb, library):
|
||||
|
||||
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None, version_prompt=None,stop=None):
|
||||
"""Validate in copies before changing Work; preserve all recovery evidence."""
|
||||
import pythoncom, win32con, win32event
|
||||
from .operation_queue import check_active, local_commit, note_metadata_progress, QueueCancelled
|
||||
from .network_path import absolute_preserving_drive
|
||||
from .verify_runner import run_verify, read_library_flag_if_available
|
||||
verifier = verifier or run_verify
|
||||
@@ -184,11 +187,16 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
return VerifyResult('BLOCKED', stderr='恢复记录目录不能位于备份工程内。')
|
||||
if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent):
|
||||
return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。')
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
library_lock = None
|
||||
release_confirmed = True
|
||||
installed = False
|
||||
def check():
|
||||
check_active()
|
||||
if stop is not None and stop.is_set():
|
||||
raise QueueCancelled('恢复已取消,未提交后续操作。')
|
||||
def completed():
|
||||
check()
|
||||
note_metadata_progress()
|
||||
record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source),
|
||||
'library': str(library), 'block': request.block_name, 'installed': False,
|
||||
'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'}
|
||||
@@ -213,23 +221,25 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
try:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
return VerifyResult('BLOCKED', stderr='已有 CBB 任务运行,请等待结束。', safe_to_continue=False)
|
||||
check()
|
||||
from .library_lock import LibraryLock
|
||||
library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed)
|
||||
library_lock.__enter__()
|
||||
if source.is_relative_to(library_root):
|
||||
raise ValueError('请选择目标中心库之外的独立备份工程。')
|
||||
project, pcb = preflight(replace(request, lmc_file=library))
|
||||
completed()
|
||||
source_pcb = _source_check(source, request.block_name, project)
|
||||
completed()
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
idle_check(library, project, pcb)
|
||||
completed()
|
||||
idle_check(library, source, source_pcb)
|
||||
completed()
|
||||
validation_base.mkdir(parents=True, exist_ok=True)
|
||||
library_size = sum(info.st_size for info in _scan(library_root).values() if stat.S_ISREG(info.st_mode))
|
||||
source_size = sum(info.st_size for info in _scan(source.parent).values() if stat.S_ISREG(info.st_mode))
|
||||
completed()
|
||||
same_drive = root.anchor.casefold() == validation_dir.anchor.casefold()
|
||||
required = (library_size + source_size * 2) if same_drive else 0
|
||||
if (shutil.disk_usage(root).free < required
|
||||
@@ -241,6 +251,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
library_scope = ManifestScope.library(request.block_name, library.name)
|
||||
original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope,
|
||||
progress=copy_progress('prepare_source', '正在准备验证库:'))
|
||||
completed()
|
||||
(root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
|
||||
staged_library = validation_dir/library.name
|
||||
staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work'
|
||||
@@ -249,8 +260,10 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
if not resolved_work.is_relative_to(validation_dir.resolve()):
|
||||
raise ValueError('验证副本工程路径越界。')
|
||||
shutil.rmtree(resolved_work)
|
||||
completed()
|
||||
source_manifest = _copy_verified(source.parent, staged_work,
|
||||
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
|
||||
completed()
|
||||
(root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
|
||||
staged_project = staged_work/source.name
|
||||
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
|
||||
@@ -260,41 +273,55 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='',
|
||||
native_lm_verify=False, interactive_input=False)
|
||||
preflight(validation)
|
||||
completed()
|
||||
emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
|
||||
check()
|
||||
release_confirmed = False
|
||||
choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {}
|
||||
if stop is not None:choice_options['stop']=stop
|
||||
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
|
||||
release_confirmed = source_result.safe_to_continue
|
||||
record['source_validation'] = asdict(source_result)
|
||||
completed()
|
||||
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
|
||||
or not source_result.safe_to_continue):
|
||||
return save(replace(source_result, status='FAIL', stderr=
|
||||
'备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail)))
|
||||
idle_check(library, project, pcb)
|
||||
completed()
|
||||
idle_check(staged_library, staged_project, staged_pcb)
|
||||
completed()
|
||||
token = root.name.removeprefix('backup-restore-')
|
||||
work = project.parent.resolve()
|
||||
incoming = work.with_name('Work.restore-' + token)
|
||||
retained = work.with_name('Work.before-restore-' + token)
|
||||
_copy_verified(staged_work, incoming,
|
||||
progress=copy_progress('prepare_source', '正在准备恢复工程:'))
|
||||
completed()
|
||||
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
|
||||
completed()
|
||||
idle_check(library, source, source_pcb)
|
||||
completed()
|
||||
if _manifest(source.parent) != source_manifest:
|
||||
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
|
||||
completed()
|
||||
if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest:
|
||||
raise ValueError('目标中心库在验证期间发生变化,停止恢复。')
|
||||
completed()
|
||||
emit('install', '备份已通过验证,正在保留原工程并恢复…')
|
||||
work.rename(retained)
|
||||
try:
|
||||
incoming.rename(work)
|
||||
except Exception:
|
||||
retained.rename(work)
|
||||
raise
|
||||
installed = True
|
||||
record['retained_work'] = str(retained)
|
||||
check()
|
||||
with local_commit():
|
||||
work.rename(retained)
|
||||
try:
|
||||
incoming.rename(work)
|
||||
except Exception:
|
||||
retained.rename(work)
|
||||
raise
|
||||
installed = True
|
||||
record['retained_work'] = str(retained)
|
||||
completed()
|
||||
emit('verify_target', '正在重新打开恢复后的目标工程并校验…')
|
||||
check()
|
||||
release_confirmed = False
|
||||
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
|
||||
auto_repair=False, native_lm_verify=False, interactive_input=False),
|
||||
@@ -317,7 +344,4 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
|
||||
if library_lock is not None:
|
||||
library_lock.__exit__(None, None, None)
|
||||
finally:
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
uninitialize_com(initialized)
|
||||
@@ -16,6 +16,225 @@ _automation_clients = []
|
||||
_automation_clients_lock = threading.Lock()
|
||||
_supervisor_lost = threading.Event()
|
||||
_native_phases = {}
|
||||
WRITER_MUTEX = r'Local\CbbRefreshVerify795NativeWriter'
|
||||
|
||||
|
||||
def assert_native_writer_idle():
|
||||
mutex = win32event.CreateMutex(None, False, WRITER_MUTEX)
|
||||
acquired = False
|
||||
try:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
raise RuntimeError('NATIVE_WRITER_ACTIVE: 原生事务尚未返回,未启动新的写入。')
|
||||
finally:
|
||||
if acquired: win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
|
||||
|
||||
class _RegisteredWriter:
|
||||
def __init__(self, handle):
|
||||
import win32api
|
||||
current = win32api.GetCurrentProcess()
|
||||
self.handle = win32api.DuplicateHandle(current, handle, current, 0, False,
|
||||
win32con.DUPLICATE_SAME_ACCESS)
|
||||
self.returncode = None
|
||||
|
||||
def poll(self):
|
||||
if self.returncode is None and win32event.WaitForSingleObject(self.handle, 0) == win32con.WAIT_OBJECT_0:
|
||||
self.returncode = win32process.GetExitCodeProcess(self.handle)
|
||||
self.handle.Close()
|
||||
return self.returncode
|
||||
|
||||
|
||||
def register_native_writer(process):
|
||||
handle = getattr(process, 'handle', None) or getattr(process, '_handle', None)
|
||||
registered = _RegisteredWriter(handle) if handle is not None else process
|
||||
with _automation_clients_lock:
|
||||
_automation_clients.append(registered)
|
||||
return process
|
||||
|
||||
|
||||
class _PendingNativeOperation:
|
||||
"""One asynchronously submitted operation, including its native descendants."""
|
||||
def __init__(self, job, identities):
|
||||
import win32api
|
||||
from .residual_sessions import _handle_identity, _force_ownership
|
||||
from .session_record import IDENTITY_KEYS
|
||||
self.record = job
|
||||
self.job = win32job.CreateJobObject(None, '') # Deliberately no kill-on-close.
|
||||
self.owners = {}
|
||||
self.recorded = set()
|
||||
self.completed = False
|
||||
self.exited = False
|
||||
self.lock = threading.Lock()
|
||||
try:
|
||||
for identity in identities:
|
||||
pid = identity['pid']
|
||||
handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000 |
|
||||
win32con.PROCESS_SET_QUOTA | win32con.PROCESS_TERMINATE, False, pid)
|
||||
try:
|
||||
actual = dict(pid=pid, **_handle_identity(handle), **_force_ownership(handle, pid))
|
||||
if any(actual[key] != identity.get(key) for key in IDENTITY_KEYS):
|
||||
raise RuntimeError('NATIVE_OPERATION_IDENTITY_CHANGED')
|
||||
win32job.AssignProcessToJobObject(self.job, handle)
|
||||
self.owners[pid] = _RegisteredWriter(handle)
|
||||
self.recorded.add(pid)
|
||||
finally:
|
||||
handle.Close()
|
||||
except Exception:
|
||||
self._close()
|
||||
raise # Admission failure is not permission to post Add without protection.
|
||||
|
||||
def _close(self):
|
||||
for owner in self.owners.values():
|
||||
if owner.returncode is None:
|
||||
owner.handle.Close()
|
||||
self.job.Close()
|
||||
self.exited = True
|
||||
|
||||
def complete(self):
|
||||
with self.lock:
|
||||
self.completed = True # Only an exact native acknowledgement settles the operation.
|
||||
|
||||
def poll(self):
|
||||
with self.lock:
|
||||
return self._poll()
|
||||
|
||||
def _poll(self):
|
||||
if self.exited:
|
||||
return 0
|
||||
pids = set(win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList))
|
||||
fresh = pids-self.recorded
|
||||
if fresh:
|
||||
from .session_record import update_worker_state
|
||||
from .residual_sessions import _process_handle, _handle_identity, _force_ownership
|
||||
identities = []
|
||||
for pid in fresh:
|
||||
with _process_handle(pid) as handle:
|
||||
if not win32job.IsProcessInJob(handle, self.job):
|
||||
continue # The snapshot PID may have been reused outside this job.
|
||||
identities.append(('native', dict(pid=pid, **_handle_identity(handle),
|
||||
**_force_ownership(handle, pid))))
|
||||
if identities and update_worker_state(self.record, 'UNCONFIRMED', observed_identities=identities):
|
||||
self.recorded.update(identity['pid'] for _, identity in identities)
|
||||
# An acknowledged Add does not retain an otherwise idle LM shell.
|
||||
# Descendants still need observed exit; PID reuse cannot imitate an owner.
|
||||
idle = {pid for pid, owner in self.owners.items() if owner.poll() is None} if self.completed else set()
|
||||
if not pids-idle:
|
||||
self._close()
|
||||
return 0
|
||||
return None
|
||||
|
||||
|
||||
def register_pending_native_operation(job, pids):
|
||||
from .session_record import read_session_record, update_worker_state
|
||||
pids = set(pids)
|
||||
if not pids:
|
||||
raise RuntimeError('NATIVE_OPERATION_OWNER_REQUIRED')
|
||||
# Retain the creation/image/owner identity in the existing bound journal
|
||||
# before asynchronous dispatch, so a restarted UI can validate controls.
|
||||
update_worker_state(job, 'POSTCALL', identities=[('native', pid) for pid in pids], required=True)
|
||||
path = Path(job['session_record_path']).with_name('worker-state.json')
|
||||
record = read_session_record(path, evidence_root=path.parent)
|
||||
identities = [p for p in record.get('processes', ()) if p['pid'] in pids and p.get('role') == 'native']
|
||||
if record['operation_id'] != job['operation_id'] or {p['pid'] for p in identities} != pids:
|
||||
raise RuntimeError('NATIVE_OPERATION_OWNER_UNCONFIRMED')
|
||||
operation = _PendingNativeOperation(job, identities)
|
||||
with _automation_clients_lock:
|
||||
_automation_clients.append(operation)
|
||||
return operation
|
||||
|
||||
|
||||
@contextmanager
|
||||
def worker_native_channel(*, lease_handle=None, inspection_only=False):
|
||||
"""The native worker, not its disposable supervisor, owns write exclusion."""
|
||||
import win32api
|
||||
mutex = win32event.CreateMutex(None, False, WRITER_MUTEX)
|
||||
acquired = False
|
||||
try:
|
||||
if inspection_only is not True:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
raise RuntimeError('NATIVE_WRITER_ACTIVE: 原生事务尚未返回。')
|
||||
yield
|
||||
finally:
|
||||
if acquired:
|
||||
# Only registered Save/Close/Repair clients extend the boundary;
|
||||
# an idle PCB shell or a business failure is not a pending write.
|
||||
warned = False
|
||||
while True:
|
||||
with _automation_clients_lock:
|
||||
clients = tuple(_automation_clients)
|
||||
try:
|
||||
released = all(client.poll() is not None for client in clients)
|
||||
except Exception:
|
||||
released = False
|
||||
if not warned:
|
||||
logging.getLogger(__name__).warning('Native writer exit is unconfirmed', exc_info=True)
|
||||
warned = True
|
||||
if released:
|
||||
break
|
||||
threading.Event().wait(.1)
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
if lease_handle is not None:
|
||||
win32api.CloseHandle(int(lease_handle))
|
||||
|
||||
|
||||
def run_native_worker(action, request_path, *, admission_state=None):
|
||||
"""Wait for durable parent admission before acquiring the worker barrier."""
|
||||
import json
|
||||
import time
|
||||
job = json.loads(Path(request_path).read_text(encoding='utf-8'))
|
||||
gate = Path(job['start_gate']) if job.get('start_gate') else None
|
||||
if gate is not None:
|
||||
deadline = time.monotonic()+30
|
||||
while not gate.is_file():
|
||||
if (job.get('cancel_signal') and Path(job['cancel_signal']).exists()
|
||||
or time.monotonic() >= deadline):
|
||||
raise RuntimeError('WORKER_CANCELLED: 未取得启动许可。')
|
||||
threading.Event().wait(.05)
|
||||
lease_handle = None
|
||||
record = None
|
||||
if job.get('session_record_path'):
|
||||
from .session_record import read_session_record, process_identity, IDENTITY_KEYS
|
||||
path = Path(job['session_record_path'])
|
||||
record = read_session_record(path, evidence_root=path.parent)
|
||||
identity = process_identity(os.getpid())
|
||||
if (record['operation_id'] != job['operation_id']
|
||||
or any(record.get(key) != job.get(key) for key in (
|
||||
'operation', 'library', 'block', 'desktop', 'worker_role', 'start_gate_protocol', 'start_gate'))
|
||||
or not any(p.get('role') == 'worker' and all(p.get(k) == identity[k] for k in IDENTITY_KEYS)
|
||||
for p in record.get('processes', ()))):
|
||||
raise RuntimeError('WORKER_ADMISSION_IDENTITY_CHANGED')
|
||||
lease_handle = record.get('worker_lease_handle')
|
||||
if job.get('start_gate_protocol') == 'event-v1':
|
||||
import win32api
|
||||
handle = record.get('worker_start_handle') if record else None
|
||||
if not handle:
|
||||
raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少启动事件。')
|
||||
try:
|
||||
deadline = time.monotonic()+30
|
||||
while win32event.WaitForSingleObject(int(handle), 50) != win32con.WAIT_OBJECT_0:
|
||||
if (job.get('cancel_signal') and Path(job['cancel_signal']).exists()
|
||||
or time.monotonic() >= deadline):
|
||||
raise RuntimeError('WORKER_CANCELLED: 启动事件未提交。')
|
||||
finally:
|
||||
win32api.CloseHandle(int(handle))
|
||||
if job.get('worker_role') == 'catalog_readonly':
|
||||
from .native_management import catalog_worker_main
|
||||
if action is not catalog_worker_main or job.get('operation') != 'catalog':
|
||||
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||
inspection = (action.__module__ == 'cbb_refresh_verify.native_repair_ui'
|
||||
and action.__name__ == 'repair_worker_main' and job.get('inspection_only') is True)
|
||||
with worker_native_channel(lease_handle=lease_handle, inspection_only=inspection):
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('WORKER_CANCELLED: 已取消原生启动。')
|
||||
if admission_state is not None:
|
||||
admission_state['worker_entered'] = True
|
||||
return action(request_path)
|
||||
|
||||
|
||||
def _phase_pending(phase):
|
||||
@@ -56,6 +275,8 @@ def _record_write_pending(record_path, operation_id=None):
|
||||
def launch_save_helper(command, *, start_gate=None, identity_path=None, operation_id=None, **kwargs):
|
||||
"""Register the save client atomically with respect to supervisor loss."""
|
||||
with _automation_clients_lock:
|
||||
from .operation_queue import check_active
|
||||
check_active()
|
||||
if _supervisor_lost.is_set():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 监督器已退出,未启动新的保存客户端')
|
||||
helper = subprocess.Popen(command, **kwargs)
|
||||
@@ -115,9 +336,12 @@ def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=
|
||||
pending = _record_write_pending(session_record_path, operation_id)
|
||||
# The same gate blocks new calls/helpers after loss. A stale
|
||||
# POSTCALL on disk cannot override an active in-memory call.
|
||||
if (pending is False and _phase_pending(_native_phases.get(operation_id)) is False
|
||||
and all(helper.poll() is not None for helper in _automation_clients)):
|
||||
os._exit(75) # This Python worker only; native children remain untouched.
|
||||
returned = pending is False and _phase_pending(_native_phases.get(operation_id)) is False
|
||||
clients = tuple(_automation_clients)
|
||||
# Polling can publish a job descendant's exact identity. Never
|
||||
# hold the client registry lock while that journal is updated.
|
||||
if returned and all(helper.poll() is not None for helper in clients):
|
||||
os._exit(75) # This Python worker only; native children remain untouched.
|
||||
threading.Event().wait(.2)
|
||||
finally:
|
||||
parent.Close()
|
||||
@@ -160,6 +384,8 @@ class DesktopWorker:
|
||||
startup = win32process.STARTUPINFO()
|
||||
# subprocess.STARTUPINFO does NOT pass lpDesktop to CreateProcess.
|
||||
startup.lpDesktop = startup_desktop_name(name, interactive_input=self.interactive_input)
|
||||
from .operation_queue import check_active
|
||||
check_active()
|
||||
self.handle, thread, self.pid, _ = win32process.CreateProcess(
|
||||
command[0], subprocess.list2cmdline(command), None, None, False,
|
||||
win32con.CREATE_NO_WINDOW, None, None, startup)
|
||||
@@ -199,6 +425,8 @@ class DesktopWorker:
|
||||
raise
|
||||
|
||||
def start_companion(self, command):
|
||||
from .operation_queue import check_active
|
||||
check_active()
|
||||
startup = win32process.STARTUPINFO()
|
||||
startup.lpDesktop = startup_desktop_name(
|
||||
self.name, interactive_input=getattr(self, 'interactive_input', False))
|
||||
@@ -283,7 +511,10 @@ class DesktopWorker:
|
||||
|
||||
def bind_session(self, job):
|
||||
from .session_record import register_worker_session
|
||||
register_worker_session(self, job)
|
||||
from .library_lock import duplicate_worker_lease
|
||||
lease = (None if job.get('inspection_only') is True else
|
||||
duplicate_worker_lease(job['library'], self.handle))
|
||||
register_worker_session(self, {**job, 'worker_lease_handle': lease})
|
||||
|
||||
def native_write_pending(self):
|
||||
return _record_write_pending(getattr(self, 'session_record_path', None))
|
||||
|
||||
@@ -9,6 +9,7 @@ import ctypes
|
||||
from ctypes import wintypes
|
||||
import heapq
|
||||
import hashlib
|
||||
import json
|
||||
import ntpath
|
||||
import os
|
||||
from pathlib import Path
|
||||
@@ -138,16 +139,21 @@ def _load_evidence(job, pcb_pid, baseline, *, require_autosave=True):
|
||||
return None
|
||||
|
||||
|
||||
def _target_frame(windows, name):
|
||||
def _target_frame(windows, name, *, require_ready=True):
|
||||
matches = []
|
||||
for window in windows:
|
||||
if not window['class'].casefold().startswith('afx:') or not window.get('enabled', True):
|
||||
if not window['class'].casefold().startswith('afx:'):
|
||||
continue
|
||||
if require_ready and (not window.get('enabled', True) or any(
|
||||
child['class'].casefold() == 'msctls_progress32' and child.get('visible', False)
|
||||
for child in window['children'])):
|
||||
continue
|
||||
if not window['text'].casefold().startswith('expedition pcb') or f'[{name}]'.casefold() not in window['text'].casefold():
|
||||
continue
|
||||
mdi = {child['hwnd'] for child in window['children'] if child['class'].casefold() == 'mdiclient'}
|
||||
if any(child.get('parent') in mdi and child['text'].casefold() == name.casefold()
|
||||
and child['class'].casefold().startswith('afx:') for child in window['children']):
|
||||
documents = [child for child in window['children'] if child.get('parent') in mdi
|
||||
and child['class'].casefold().startswith('afx:')]
|
||||
if len(documents) == 1 and documents[0]['text'].casefold() == name.casefold():
|
||||
matches.append(window)
|
||||
return matches[0] if len(matches) == 1 else None
|
||||
|
||||
@@ -170,6 +176,23 @@ def _windows(pid):
|
||||
# Custom controls may have no cached text; missing evidence fails closed.
|
||||
user.GetWindowTextW(hwnd, buffer, len(buffer))
|
||||
return buffer.value
|
||||
def owner_chain(hwnd):
|
||||
import win32service
|
||||
desktop = win32service.GetUserObjectInformation(win32service.GetThreadDesktop(
|
||||
win32api.GetCurrentThreadId()), 2)
|
||||
chain, seen = [], {hwnd}
|
||||
for _ in range(8):
|
||||
hwnd = int(win32gui.GetWindow(hwnd, 4) or 0)
|
||||
if not hwnd or hwnd in seen: break
|
||||
seen.add(hwnd)
|
||||
thread, owner_pid = win32process.GetWindowThreadProcessId(hwnd)
|
||||
same_desktop = win32service.GetUserObjectInformation(win32service.GetThreadDesktop(thread), 2) == desktop
|
||||
chain.append({'hwnd': hwnd, 'pid': owner_pid, 'class': win32gui.GetClassName(hwnd),
|
||||
'text': text(hwnd), 'visible': bool(win32gui.IsWindowVisible(hwnd)),
|
||||
'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'same_desktop': same_desktop,
|
||||
'owner': int(win32gui.GetWindow(hwnd, 4) or 0)})
|
||||
if owner_pid != pid or not same_desktop or chain[-1]['visible']: break
|
||||
return chain
|
||||
result = []
|
||||
seen = 0
|
||||
def collect(hwnd, _):
|
||||
@@ -191,10 +214,10 @@ def _windows(pid):
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: too many controls')
|
||||
child_cls = win32gui.GetClassName(ch)
|
||||
if (cls == '#32770' or cls.casefold() == 'internet explorer_hidden'
|
||||
or child_cls.casefold() == 'mdiclient' or child_cls.casefold().startswith('afx:')):
|
||||
or child_cls.casefold() in ('mdiclient', 'msctls_progress32') or child_cls.casefold().startswith('afx:')):
|
||||
children.append({'hwnd': ch, 'class': child_cls, 'text': text(ch),
|
||||
'id': win32gui.GetDlgCtrlID(ch), 'parent': win32gui.GetParent(ch),
|
||||
'enabled': bool(win32gui.IsWindowEnabled(ch))})
|
||||
'enabled': bool(win32gui.IsWindowEnabled(ch)), 'visible': bool(win32gui.IsWindowVisible(ch))})
|
||||
return True
|
||||
if cls == '#32770' or cls.casefold().startswith('afx:') or cls.casefold() == 'internet explorer_hidden':
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
@@ -205,7 +228,8 @@ def _windows(pid):
|
||||
return True
|
||||
result.append({'hwnd': hwnd, 'pid': pid, 'class': cls, 'text': caption,
|
||||
'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'children': children,
|
||||
'owner': int(win32gui.GetWindow(hwnd, 4) or 0)})
|
||||
'owner': int(win32gui.GetWindow(hwnd, 4) or 0),
|
||||
'owner_chain': owner_chain(hwnd) if cls == '#32770' else []})
|
||||
return True
|
||||
win32api.SetLastError(0)
|
||||
try:
|
||||
@@ -261,6 +285,50 @@ def _cancel(job):
|
||||
raise RuntimeError('VERIFY_CANCELLED: native opening check cancelled')
|
||||
|
||||
|
||||
def _request_close_handoff(job, pcb_pid, frame, session, emit, deadline):
|
||||
from uuid import uuid4
|
||||
intent = dict(pcb_pid=int(pcb_pid), hwnd=frame['hwnd'], operation_id=job['operation_id'],
|
||||
desktop=job['desktop'], project=job['project'], pcb=job['pcb'], close_id=uuid4().hex)
|
||||
ack = Path(job['root'])/'diagnostic-close-ack.json'
|
||||
emit(stage='diagnostic_close_requested', **intent)
|
||||
def read_ack():
|
||||
try:
|
||||
with ack.open(encoding='utf-8') as stream:
|
||||
return json.loads(stream.read(8192))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
while True:
|
||||
_cancel(job)
|
||||
remaining = deadline-time.monotonic()
|
||||
if remaining <= 0 or not session.pcb_alive():
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: supervisor handoff not acknowledged')
|
||||
try:
|
||||
acknowledged = _bounded_call(read_ack, min(2, remaining))
|
||||
except TimeoutError as error:
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: supervisor acknowledgement read timed out') from error
|
||||
if acknowledged == intent:
|
||||
return intent
|
||||
time.sleep(min(.1, max(0, deadline-time.monotonic())))
|
||||
|
||||
|
||||
def _owned_by_frame(window, frame):
|
||||
if frame is None or window['pid'] != frame['pid']: return False
|
||||
if window.get('owner') == frame['hwnd']: return True
|
||||
chain = window.get('owner_chain', ())
|
||||
expected, seen = window.get('owner'), {window['hwnd']}
|
||||
if not chain or len(chain) > 8: return False
|
||||
for index, owner in enumerate(chain):
|
||||
if (owner['hwnd'] != expected or owner['hwnd'] in seen or owner['pid'] != frame['pid']
|
||||
or owner.get('same_desktop') is not True): return False
|
||||
seen.add(owner['hwnd'])
|
||||
if owner['hwnd'] == frame['hwnd']:
|
||||
return (index == len(chain)-1 and owner['class'] == frame['class'] and owner['text'] == frame['text'])
|
||||
if (owner['class'] != '#32770' or owner['text'] != 'Expedition PCB'
|
||||
or owner['visible'] or owner['enabled']): return False
|
||||
expected = owner['owner']
|
||||
return False
|
||||
|
||||
|
||||
def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked=None, pcb_name=''):
|
||||
for window in windows:
|
||||
known_titles = {'expedition pcb', 'expedition pcb - reusable block'}
|
||||
@@ -276,14 +344,21 @@ def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked
|
||||
and child['text'].strip().casefold() == f'Save changes to {pcb_name}?'.casefold()
|
||||
for child in window['children'])
|
||||
and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} == {2, 6, 7})
|
||||
if closing and window.get('owner') == frame['hwnd'] and (standard_save or 'do you want to save the reusable block cell' in text):
|
||||
forward = (window['class'] == '#32770' and window['text'] == 'Expedition PCB'
|
||||
and any(child['class'].casefold() == 'static' and child.get('id') == 6172
|
||||
and ' '.join(child['text'].split()) == 'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'
|
||||
for child in window['children'])
|
||||
and {child.get('id') for child in window['children'] if child['class'].casefold() == 'button'} in ({6,7}, {6,7,6171}))
|
||||
if _owned_by_frame(window, frame) and (forward or closing and (standard_save or 'do you want to save the reusable block cell' in text)):
|
||||
targets = [child for child in window['children'] if child['class'].casefold() == 'button'
|
||||
and child.get('id') == 7 and child['text'].replace('&', '').strip().casefold() in {'no', '否(n)', '否'}
|
||||
and child.get('enabled', True)]
|
||||
if len(targets) == 1:
|
||||
if session is None: return True
|
||||
if window['hwnd'] not in clicked:
|
||||
session.post(targets[0]['hwnd'], 0xF5)
|
||||
clicked.add(window['hwnd'])
|
||||
if not closing: return True
|
||||
continue
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt preserved; '
|
||||
f"pid={window['pid']} hwnd={window['hwnd']} class={window['class']!r} "
|
||||
@@ -291,6 +366,68 @@ def _pending_prompt(windows, *, closing=False, frame=None, session=None, clicked
|
||||
return False
|
||||
|
||||
|
||||
def cancelled_startup_step(job, pcb_pid, state, *, closed_frame, deadline, post, emit,
|
||||
read_windows=None, identity_check=None):
|
||||
"""Finish only the owned no-write diagnostic startup; never establish PASS.
|
||||
|
||||
Cancellation already ended supervisor polling. Cleanup is its sole prompt
|
||||
actor and uses the caller's original deadline and single-close state.
|
||||
"""
|
||||
from types import SimpleNamespace
|
||||
read_windows = read_windows or (lambda: _windows(pcb_pid))
|
||||
windows = read_windows()
|
||||
if any(window['pid'] != pcb_pid for window in windows):
|
||||
raise RuntimeError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
current = _target_frame(windows, Path(job['pcb']).stem, require_ready=False)
|
||||
frame = current
|
||||
if frame is None and closed_frame is not None:
|
||||
frame = state.get('frame')
|
||||
if frame is None:
|
||||
return closed_frame, False
|
||||
old = state.get('frame')
|
||||
if old is not None and any(frame[k] != old[k] for k in ('hwnd', 'pid', 'class', 'text')):
|
||||
raise RuntimeError('STARTUP_DOCUMENT_CHANGED')
|
||||
if closed_frame is not None and frame['hwnd'] != closed_frame:
|
||||
raise RuntimeError('STARTUP_DOCUMENT_CHANGED')
|
||||
if old is None:
|
||||
# Explicit legacy cleanup supplies already checked registration. It is
|
||||
# revalidated immediately before every action, never used as open proof.
|
||||
confirmed = (identity_check is not None or
|
||||
_load_evidence(job, pcb_pid, job['diagnostic_log_baseline'], require_autosave=False) is not None)
|
||||
if not confirmed:
|
||||
return closed_frame, False
|
||||
state['frame'] = frame
|
||||
# Validate every window before allowing a known No. An unknown sibling
|
||||
# must not be hidden by the first recognized modal in enumeration order.
|
||||
try:
|
||||
for window in windows:
|
||||
_pending_prompt([window], closing=closed_frame is not None, frame=frame,
|
||||
pcb_name=Path(job['pcb']).name)
|
||||
except RuntimeError as error:
|
||||
if str(error).startswith('DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown native prompt'):
|
||||
return closed_frame, False
|
||||
raise
|
||||
actions = []
|
||||
def act(hwnd, message):
|
||||
if read_windows() != windows:
|
||||
raise RuntimeError('STARTUP_WINDOW_CHANGED: native snapshot changed before action')
|
||||
if identity_check is not None and not identity_check():
|
||||
raise RuntimeError('STARTUP_IDENTITY_UNCONFIRMED: registered cleanup binding changed')
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError('STARTUP_CLEANUP_TIMEOUT: original cleanup deadline reached')
|
||||
post(hwnd, message)
|
||||
actions.append((hwnd, message))
|
||||
if message == 0xF5:
|
||||
emit(stage='startup_prompt_no', pcb_pid=pcb_pid, hwnd=hwnd, control_id=7)
|
||||
pending = _pending_prompt(windows, closing=closed_frame is not None, frame=frame,
|
||||
session=SimpleNamespace(post=act), clicked=state['clicked'], pcb_name=Path(job['pcb']).name)
|
||||
if (closed_frame is None and not pending
|
||||
and _target_frame(windows, Path(job['pcb']).stem) is not None):
|
||||
act(frame['hwnd'], 0x10)
|
||||
closed_frame = frame['hwnd']
|
||||
return closed_frame, bool(actions)
|
||||
|
||||
|
||||
def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=None) -> dict:
|
||||
"""Prove this launch opened its native document, close it, and prove exit.
|
||||
|
||||
@@ -301,8 +438,23 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No
|
||||
if not isinstance(baseline, dict) or 'started_ns' not in baseline or 'files' not in baseline:
|
||||
raise RuntimeError('DIAGNOSTIC_BASELINE_REQUIRED: snapshot before native launch')
|
||||
session = _NativeSession(job, int(pcb_pid), launcher_process)
|
||||
def scan(deadline, *, closing=False):
|
||||
while True:
|
||||
if not closing:
|
||||
_cancel(job)
|
||||
try:
|
||||
return _windows(int(pcb_pid))
|
||||
except RuntimeError as error:
|
||||
if str(error) != 'DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s':
|
||||
raise
|
||||
# Discard the incomplete snapshot; no control action may use it.
|
||||
emit(stage='diagnostic_window_retry', detail=str(error))
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(min(.1, max(0, deadline-time.monotonic())))
|
||||
try:
|
||||
deadline = time.monotonic() + max(.01, float(job['timeout']))
|
||||
startup_clicked = set()
|
||||
while True:
|
||||
_cancel(job)
|
||||
error = _read_bounded(error_reader) if error_reader else None
|
||||
@@ -310,38 +462,45 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No
|
||||
raise RuntimeError(str(error))
|
||||
if not session.pcb_alive():
|
||||
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence')
|
||||
windows = _windows(int(pcb_pid))
|
||||
windows = scan(deadline)
|
||||
_cancel(job)
|
||||
if any(window['pid'] != int(pcb_pid) for window in windows):
|
||||
raise RuntimeError('DIAGNOSTIC_PID_MISMATCH')
|
||||
frame = _target_frame(windows, Path(job['pcb']).stem)
|
||||
frame = _target_frame(windows, Path(job['pcb']).stem, require_ready=False)
|
||||
# Startup splash/control windows are transient. Unknown windows
|
||||
# veto closing only once the target actually has loaded evidence.
|
||||
pending = (_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
|
||||
if frame is not None else True)
|
||||
evidence = (_load_evidence(job, int(pcb_pid), baseline, require_autosave=False)
|
||||
if frame is not None and not pending else None)
|
||||
if evidence is not None:
|
||||
if frame is not None else None)
|
||||
pending = (_pending_prompt(windows, frame=frame, session=session if evidence else None,
|
||||
clicked=startup_clicked, pcb_name=Path(job['pcb']).name) if frame is not None else True)
|
||||
if evidence is not None and not pending and _target_frame(windows, Path(job['pcb']).stem) is not None:
|
||||
emit(stage='diagnostic_native_loaded_candidate', **evidence)
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: current target MDI/path/PID logs missing')
|
||||
time.sleep(.1)
|
||||
# Re-read the exact PID/frame before the sole close request.
|
||||
_cancel(job)
|
||||
windows = _windows(int(pcb_pid))
|
||||
_pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
|
||||
current = _target_frame(windows, Path(job['pcb']).stem)
|
||||
if current is None or current['hwnd'] != frame['hwnd']:
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target frame changed')
|
||||
session.post(frame['hwnd'], 0x10)
|
||||
emit(stage='diagnostic_wm_close', pcb_pid=int(pcb_pid), hwnd=frame['hwnd'])
|
||||
# Finish any in-flight supervisor poll before WM_CLOSE can create a prompt.
|
||||
close_deadline = time.monotonic() + 30
|
||||
intent = _request_close_handoff(job, pcb_pid, frame, session, emit, close_deadline)
|
||||
# Re-read the exact PID/frame after acknowledgement and before the sole close.
|
||||
_cancel(job)
|
||||
error = _read_bounded(error_reader) if error_reader else None
|
||||
if error: raise RuntimeError(str(error))
|
||||
windows = scan(close_deadline)
|
||||
pending = _pending_prompt(windows, frame=frame, pcb_name=Path(job['pcb']).name)
|
||||
current = _target_frame(windows, Path(job['pcb']).stem)
|
||||
if (pending or time.monotonic() >= close_deadline or current is None
|
||||
or any(current[key] != frame[key] for key in ('hwnd', 'pid', 'class', 'text'))):
|
||||
raise RuntimeError('DIAGNOSTIC_CLOSE_UNCONFIRMED: target frame changed')
|
||||
_cancel(job)
|
||||
session.post(frame['hwnd'], 0x10)
|
||||
emit(stage='diagnostic_wm_close', **intent)
|
||||
clicked = set()
|
||||
last_pending = ''
|
||||
while session.pcb_alive() or session.launcher_alive():
|
||||
# Cancellation stops future work; an accepted normal close must
|
||||
# still finish before its queue slot can be safely released.
|
||||
windows = _windows(int(pcb_pid)) if session.pcb_alive() else []
|
||||
windows = scan(close_deadline, closing=True) if session.pcb_alive() else []
|
||||
previous_clicks = set(clicked)
|
||||
pending_error = None
|
||||
try:
|
||||
|
||||
@@ -238,11 +238,16 @@ class WindowProbe:
|
||||
process_name = ""
|
||||
controls = tuple(self._win32_control(child) for child in self._children(hwnd))
|
||||
diagnostics = []
|
||||
try:
|
||||
uia_records = _bounded_call(lambda: self.uia.controls(hwnd), self.uia_timeout_seconds)
|
||||
controls = self._merge_controls(controls, uia_records)
|
||||
except Exception as error:
|
||||
diagnostics.append(f"UIA_ERROR: {error}")
|
||||
native_panel = (process_name.casefold() == 'expeditionpcb.exe'
|
||||
and phase in (DialogPhase.SAVE, DialogPhase.CLOSE)
|
||||
and gui.GetClassName(hwnd) == '#32770' and gui.GetWindowText(hwnd) == 'Project Integration')
|
||||
# This native panel's exact control IDs/text are sufficient; its UIA tree can stall Save.
|
||||
if not native_panel:
|
||||
try:
|
||||
uia_records = _bounded_call(lambda: self.uia.controls(hwnd), self.uia_timeout_seconds)
|
||||
controls = self._merge_controls(controls, uia_records)
|
||||
except Exception as error:
|
||||
diagnostics.append(f"UIA_ERROR: {error}")
|
||||
owner = 0
|
||||
try:
|
||||
owner = int(gui.GetWindow(hwnd, 4) or 0) # GW_OWNER
|
||||
|
||||
@@ -116,7 +116,7 @@ def _read_document(path: Path) -> list[dict[str, Any]]:
|
||||
return rules
|
||||
|
||||
|
||||
def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[DialogRule, ...]:
|
||||
def load_rules(default_path: Path, override_path: Path | None = None, *, diagnostic_only=False) -> tuple[DialogRule, ...]:
|
||||
ordered: list[str] = []
|
||||
raw_by_id: dict[str, dict[str, Any]] = {}
|
||||
for raw in _read_document(default_path):
|
||||
@@ -137,7 +137,12 @@ def load_rules(default_path: Path, override_path: Path | None = None) -> tuple[D
|
||||
else:
|
||||
ordered.append(rule_id)
|
||||
raw_by_id[rule_id] = dict(override)
|
||||
return tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered)
|
||||
rules = tuple(_parse_rule(raw_by_id[rule_id]) for rule_id in ordered)
|
||||
if diagnostic_only:
|
||||
# The process-bound diagnostic checker declines this prompt after proving the loaded project.
|
||||
rules = tuple(replace(rule, category='OBSERVE_PROGRESS', action='', channels=(), target=())
|
||||
if rule.rule_id == 'forward-annotation-confirm' else rule for rule in rules)
|
||||
return rules
|
||||
|
||||
|
||||
def _semantic_text(snapshot: WindowSnapshot) -> str:
|
||||
@@ -253,6 +258,22 @@ def decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecisio
|
||||
channels=('win32_button_click', 'uia_invoke'),
|
||||
target=(('control_id', 7),), postcondition='window_gone',
|
||||
error_code='MENTOR_DATABASE_LOAD_FAILED', detail=' | '.join(snapshot.texts))
|
||||
if (snapshot.title == 'Project Integration' and snapshot.phase in (DialogPhase.SAVE, DialogPhase.CLOSE)
|
||||
and snapshot.process_name.casefold() == 'expeditionpcb.exe' and snapshot.process_role == 'pcb'
|
||||
and snapshot.window_class == '#32770' and snapshot.owner_hwnd and not snapshot.diagnostics
|
||||
and not re.search(r'\b(?:errors?|failed|inconsistent)\b', combined)):
|
||||
idle = {1033: 'No connectivity changes to be forward annotated',
|
||||
1032: 'No pending schematic CES changes to load into PCB',
|
||||
1035: 'No pending PCB changes to be back annotated',
|
||||
1034: 'No pending CES changes to load into PCB'}
|
||||
complete = all(len(matches := [c for c in snapshot.controls if c.control_id == identifier]) == 1
|
||||
and matches[0].class_name == 'Static' and matches[0].name == text for identifier, text in idle.items())
|
||||
close = [c for c in snapshot.controls if c.control_id == 2]
|
||||
if (complete and len(close) == 1 and close[0].class_name == 'Button'
|
||||
and close[0].name.replace('&', '') == 'Close' and close[0].enabled):
|
||||
return RuleDecision(rule_id='completed-integration-panel', category='SAFE_CONFIRM',
|
||||
action='close_completed_integration', channels=('win32_button_click',),
|
||||
target=(('control_id', 2),), postcondition='window_gone')
|
||||
matches = [rule for rule in rules if _matches(rule, snapshot, include_phase=True)]
|
||||
if matches:
|
||||
best_priority = max(rule.priority for rule in matches)
|
||||
|
||||
@@ -100,9 +100,10 @@ class DialogBackend(Protocol):
|
||||
class AgentDialogBackend:
|
||||
"""Adapt the private-desktop JSONL client to the supervisor backend."""
|
||||
|
||||
def __init__(self, client, *, pids=None) -> None:
|
||||
def __init__(self, client, *, pids=None, before_action=None) -> None:
|
||||
self.client = client
|
||||
self.pids = pids
|
||||
self.before_action = before_action
|
||||
|
||||
def observe(self, phase: DialogPhase):
|
||||
if self.pids is None:
|
||||
@@ -111,6 +112,7 @@ class AgentDialogBackend:
|
||||
return tuple(w for w in self.client.observe(phase, pids=pids) if w.pid in pids)
|
||||
|
||||
def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult:
|
||||
if self.before_action is not None:self.before_action(snapshot,action)
|
||||
return self.client.perform(
|
||||
hwnd=snapshot.hwnd,
|
||||
fingerprint=stable_fingerprint(snapshot),
|
||||
@@ -123,7 +125,7 @@ class Win32DialogBackend:
|
||||
"""Observe and act on dialogs without moving focus, cursor, or desktop."""
|
||||
|
||||
def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None,
|
||||
win32con=None) -> None:
|
||||
win32con=None, before_action=None) -> None:
|
||||
if win32gui is None:
|
||||
import win32gui as win32gui_module
|
||||
win32gui = win32gui_module
|
||||
@@ -138,6 +140,7 @@ class Win32DialogBackend:
|
||||
self.win32gui = win32gui
|
||||
self.win32process = win32process
|
||||
self.win32con = win32con
|
||||
self.before_action = before_action
|
||||
|
||||
def _allowed_pids(self) -> set[int]:
|
||||
values = self.pids() if callable(self.pids) else self.pids
|
||||
@@ -256,6 +259,7 @@ class Win32DialogBackend:
|
||||
return control.control_id
|
||||
|
||||
def perform(self, snapshot: DialogSnapshot, action: str) -> tuple[int, ...]:
|
||||
if self.before_action is not None:self.before_action(snapshot,action)
|
||||
buttons = self._buttons(snapshot)
|
||||
positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load",
|
||||
"是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载")
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Close only an idle document whose native identity was already established."""
|
||||
import json
|
||||
from contextlib import ExitStack
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
@@ -43,6 +44,18 @@ def _cancel_target(snapshot):
|
||||
from .dialog_rules import pcb_version_choice
|
||||
if exact_prompt(snapshot):
|
||||
return 'read_write_access', next(c for c in snapshot.controls if c.control_id == 7)
|
||||
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:
|
||||
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]
|
||||
@@ -53,24 +66,104 @@ def _cancel_target(snapshot):
|
||||
return None
|
||||
|
||||
|
||||
def _tip_target(snapshot):
|
||||
from .dialog_agent import DialogActionExecutor
|
||||
if snapshot.title != 'Tip of the Day' or snapshot.window_class != '#32770':
|
||||
return None
|
||||
target = DialogActionExecutor._target(snapshot, {'control_id': 1})
|
||||
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 cancelled_prewrite_startup(job, pcb_pid=None):
|
||||
"""Positive ordinary pre-document cancellation proof; absence of Save is insufficient."""
|
||||
from .session_record import IDENTITY_KEYS, read_session_record
|
||||
try:
|
||||
if (job.get('diagnostic_only') is not False or job.get('interactive_input')
|
||||
or job.get('native_lm_verify') or job.get('post_repair_consent')
|
||||
or job.get('operation') != 'verify' or not job.get('operation_id')
|
||||
or not job.get('desktop', '').startswith('CbbVerify_')):
|
||||
return None
|
||||
root=Path(job['root'])
|
||||
if not Path(job['cancel_signal']).is_file() or (root/'save.log').exists():return None
|
||||
path=root/'events.jsonl'
|
||||
if path.stat().st_size>1024*1024:return None
|
||||
events=[json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()]
|
||||
if any(str(e.get('stage','')).startswith(('save','integration','validate','failure_close'))
|
||||
or e.get('stage') in ('startup_write_admitted','startup_supervisor_write_possible','identity_verified')
|
||||
for e in events):return None
|
||||
stages=('startup_supervisor_no_write','startup_prewrite_ready','startup_cancelled_prewrite')
|
||||
selected=[]
|
||||
for stage in stages:
|
||||
matches=[(i,e) for i,e in enumerate(events) if e.get('stage')==stage]
|
||||
if len(matches)!=1:return None
|
||||
selected.append(matches[0])
|
||||
if [i for i,_ in selected]!=sorted(i for i,_ in selected):return None
|
||||
binding={k:job[k] for k in ('operation_id','project','pcb','desktop')}
|
||||
if any(any(e.get(k)!=v for k,v in binding.items()) for _,e in selected):return None
|
||||
ready,cancelled=selected[1][1],selected[2][1]
|
||||
pid=cancelled.get('pcb_pid')
|
||||
if (not pid or pcb_pid is not None and pid!=pcb_pid
|
||||
or cancelled.get('identity_verified') is not False or cancelled.get('write_admitted') is not False):return None
|
||||
if not any(e.get('stage')=='pcb_worker_started' and e.get('pcb_pid')==pid
|
||||
for e in events[selected[1][0]+1:selected[2][0]]):return None
|
||||
session=read_session_record(Path(job['session_record_path']),evidence_root=root)
|
||||
workers=[p for p in session.get('processes',()) if p.get('role')=='worker']
|
||||
if (session.get('operation_id')!=job['operation_id'] or session.get('desktop')!=job['desktop']
|
||||
or session.get('library')!=job['library'] or len(workers)!=1
|
||||
or not set(IDENTITY_KEYS)<=ready.get('worker_identity',{}).keys()
|
||||
or any(ready.get('worker_identity',{}).get(k)!=workers[0].get(k) for k in IDENTITY_KEYS)):return None
|
||||
baseline=ready.get('baseline')
|
||||
if not isinstance(baseline,dict) or not {'started_ns','files'}<=baseline.keys():return None
|
||||
return baseline
|
||||
except (OSError,ValueError,KeyError,TypeError):
|
||||
return None
|
||||
|
||||
|
||||
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
|
||||
timeout_seconds=20, launcher_process=None):
|
||||
timeout_seconds=None, launcher_process=None):
|
||||
"""Normally close our empty PCB after a diagnosed database startup failure.
|
||||
|
||||
No COM attach: the global ROT can name another session. Only the exact
|
||||
read/write question is declined; no ownership is taken or version restored.
|
||||
Unknown windows and documents are retained. WM_CLOSE is cooperative.
|
||||
"""
|
||||
import win32api, win32con, win32gui, win32process
|
||||
import win32api, win32con, win32gui, win32process, win32event
|
||||
from .mentor_adapter import _process_details
|
||||
from .native_repair_ui import _current_desktop_name
|
||||
from .icdb_ownership import unreleased_addresses
|
||||
from . import residual_sessions
|
||||
root = Path(job['root'])
|
||||
result = {'status': 'RETAINED', 'pcb_pid': pcb_pid}
|
||||
result['release'] = {'pcb_exited': False, 'launcher_exited': launcher_process is None,
|
||||
'safe_to_continue': False}
|
||||
if launcher_process is not None:
|
||||
result['launcher_pid'] = launcher_process.pid
|
||||
handles = ExitStack()
|
||||
try:
|
||||
desktop = job.get('desktop', '')
|
||||
if (job.get('interactive_input') or not desktop.startswith('CbbVerify_')
|
||||
@@ -79,14 +172,45 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
if not pcb_pid or pcb_pid in baseline_pids:
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
expected = os.path.normcase(os.path.abspath(job['pcb']))
|
||||
cancelled_diagnostic = (job.get('diagnostic_only') is True
|
||||
and bool(job.get('cancel_signal')) and Path(job['cancel_signal']).exists()
|
||||
and isinstance(job.get('diagnostic_log_baseline'), dict)
|
||||
and {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys()
|
||||
and not (root/'save.log').exists())
|
||||
ordinary_baseline=cancelled_prewrite_startup(job,pcb_pid)
|
||||
cancelled_prewrite=ordinary_baseline is not None
|
||||
# Diagnostic close already owns a 30-second cleanup budget. Start it
|
||||
# once here; the empty-to-loaded transition never resets that deadline.
|
||||
if timeout_seconds is None:
|
||||
timeout_seconds = 30 if cancelled_diagnostic or cancelled_prewrite else 20
|
||||
deadline = time.monotonic() + max(0, timeout_seconds)
|
||||
sent = False
|
||||
declined_hwnd = None
|
||||
declined_kind = None
|
||||
cancelled_open = False
|
||||
cancelled_open = _database_log_declined(root, pcb_pid)
|
||||
dismissed_tips = set()
|
||||
close_handle = None
|
||||
close_identity = None
|
||||
close_frame = None
|
||||
diagnostic_state = {'clicked': set()}
|
||||
def cleanup_post(hwnd, message):
|
||||
if (time.monotonic() >= deadline or _current_desktop_name() != desktop
|
||||
or cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline
|
||||
or win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_TIMEOUT
|
||||
or residual_sessions._handle_identity(close_handle) != close_identity
|
||||
or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid):
|
||||
raise ValueError('STARTUP_ACTION_UNCONFIRMED')
|
||||
win32gui.PostMessage(hwnd, message, 0, 0)
|
||||
while True:
|
||||
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
|
||||
if not records:
|
||||
if (close_handle is not None
|
||||
and win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_OBJECT_0):
|
||||
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 原进程句柄尚未确认退出'
|
||||
if time.monotonic() >= deadline:
|
||||
break
|
||||
time.sleep(.2)
|
||||
continue
|
||||
if declined_hwnd is not None:
|
||||
cancelled_open = True
|
||||
result['cancelled_prompt'] = declined_kind
|
||||
@@ -111,6 +235,34 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
or '-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
if cancelled_diagnostic or cancelled_prewrite:
|
||||
if time.monotonic() >= deadline:
|
||||
result['detail']='STARTUP_CLEANUP_TIMEOUT: original cleanup deadline reached'
|
||||
break
|
||||
if cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline:
|
||||
raise ValueError('STARTUP_IDENTITY_UNCONFIRMED: pre-write phase proof changed')
|
||||
if (cancelled_diagnostic or cancelled_prewrite) and time.monotonic() < deadline:
|
||||
if close_handle is None:
|
||||
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
|
||||
close_identity = residual_sessions._handle_identity(close_handle)
|
||||
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
from .diagnostic_open import cancelled_startup_step
|
||||
def ordinary_identity():
|
||||
from .diagnostic_open import _load_evidence
|
||||
return (cancelled_prewrite_startup(job,pcb_pid)==ordinary_baseline
|
||||
and _load_evidence(job,pcb_pid,ordinary_baseline,require_autosave=False) is not None)
|
||||
closed, acted = cancelled_startup_step(job, pcb_pid, diagnostic_state,
|
||||
closed_frame=close_frame, deadline=deadline, post=cleanup_post, emit=emit,
|
||||
identity_check=ordinary_identity if cancelled_prewrite else None)
|
||||
if closed is not None and not sent:
|
||||
sent, close_frame = True, closed
|
||||
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=closed,
|
||||
document_identity='native_path_pid_logs',
|
||||
cleanup='cancelled_prewrite' if cancelled_prewrite else 'cancelled_diagnostic')
|
||||
if acted:
|
||||
continue
|
||||
if not sent:
|
||||
windows = []
|
||||
def observe(hwnd, _):
|
||||
if (win32process.GetWindowThreadProcessId(hwnd)[1] == pcb_pid
|
||||
@@ -121,6 +273,27 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
if declined_hwnd is not None and declined_hwnd not in windows:
|
||||
cancelled_open = True
|
||||
result['cancelled_prompt'] = declined_kind
|
||||
dismissed = False
|
||||
for hwnd in windows:
|
||||
if hwnd in dismissed_tips or win32gui.GetClassName(hwnd) != '#32770':
|
||||
continue
|
||||
snapshot = _startup_snapshot(hwnd, pcb_pid)
|
||||
target = _tip_target(snapshot)
|
||||
if target is None:
|
||||
continue
|
||||
current = _startup_snapshot(hwnd, pcb_pid)
|
||||
if current != snapshot or _tip_target(current) != target:
|
||||
raise ValueError('STARTUP_TIP_CHANGED')
|
||||
if cancelled_diagnostic or cancelled_prewrite:
|
||||
cleanup_post(target.handle,win32con.BM_CLICK)
|
||||
else:
|
||||
win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0)
|
||||
dismissed_tips.add(hwnd)
|
||||
dismissed = True
|
||||
emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=hwnd)
|
||||
break
|
||||
if dismissed:
|
||||
continue # Prove the Tip disappeared; it does not prove a cancelled open.
|
||||
if declined_hwnd is None:
|
||||
for hwnd in windows:
|
||||
if win32gui.GetClassName(hwnd) != '#32770':
|
||||
@@ -134,7 +307,10 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
if _cancel_target(current) != target or current != snapshot:
|
||||
raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED')
|
||||
declined_kind, cancel = target
|
||||
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
|
||||
if cancelled_diagnostic or cancelled_prewrite:
|
||||
cleanup_post(cancel.handle,win32con.BM_CLICK)
|
||||
else:
|
||||
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
|
||||
declined_hwnd = hwnd
|
||||
emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd,
|
||||
control_id=cancel.control_id, prompt=declined_kind)
|
||||
@@ -173,15 +349,38 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
win32gui.EnumChildWindows(main[0], child, None)
|
||||
addresses = unreleased_addresses(job['lmc_file'], job['project'], job['pcb'])
|
||||
if len(main) == 1 and not unknown and not documents and (cancelled_open or not addresses):
|
||||
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
|
||||
if close_handle is None:
|
||||
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
|
||||
close_identity = residual_sessions._handle_identity(close_handle)
|
||||
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
|
||||
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
|
||||
if cancelled_diagnostic or cancelled_prewrite:
|
||||
cleanup_post(main[0],win32con.WM_CLOSE)
|
||||
else:
|
||||
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
|
||||
close_frame = main[0]
|
||||
sent = True
|
||||
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
|
||||
# Observe exit even when the caller requested no extra wait.
|
||||
continue
|
||||
result['detail'] = 'STARTUP_IDLE_UNCONFIRMED: 等待空闲窗口和数据库释放'
|
||||
# After the single owned WM_CLOSE, WMI may lose the executable/
|
||||
# command fields before removing the PID. Only observe exit here;
|
||||
# never issue another close or treat missing fields as release.
|
||||
# WMI fields can disappear during teardown. The held identity binds
|
||||
# any late Tip action to the original process, never a reused PID.
|
||||
if sent and time.monotonic() < deadline:
|
||||
if _current_desktop_name() != desktop:
|
||||
raise ValueError('STARTUP_DESKTOP_UNCONFIRMED')
|
||||
snapshot = residual_sessions._process_windows({pcb_pid})
|
||||
windows = snapshot.get(pcb_pid, [])
|
||||
if all(w.get('desktop') == desktop for w in windows):
|
||||
dismissed = residual_sessions._dismiss_startup_tip(
|
||||
dict(pid=pcb_pid, name='ExpeditionPCB.exe', scope_confirmed=True, startup_frame=close_frame,
|
||||
**close_identity), close_handle, windows,
|
||||
incomplete=residual_sessions._window_error(snapshot, pcb_pid),
|
||||
dismissed=dismissed_tips, deadline=deadline)
|
||||
if dismissed is not None:
|
||||
dismissed_tips.add(dismissed)
|
||||
emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=dismissed)
|
||||
continue
|
||||
if time.monotonic() >= deadline:
|
||||
if sent:
|
||||
result['detail'] = 'STARTUP_EXIT_UNCONFIRMED: 已请求正常关闭,但 PCB 尚未退出'
|
||||
@@ -189,6 +388,8 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
|
||||
time.sleep(.2)
|
||||
except Exception as error:
|
||||
result['detail'] = str(error)
|
||||
finally:
|
||||
handles.close()
|
||||
(root/'startup-close.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
emit(stage='startup_close_result', **result)
|
||||
return result
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Bound read-only filesystem probes; keep proof handles alive through commit."""
|
||||
from contextlib import contextmanager, ExitStack
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
@contextmanager
|
||||
def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None):
|
||||
"""Only this pure probe may be terminated. stdin EOF releases its handles."""
|
||||
with tempfile.TemporaryDirectory(prefix='cbb-file-probe-') as folder:
|
||||
job = Path(folder)/'request.json'
|
||||
token = uuid4().hex
|
||||
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')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--file-probe', str(job)]
|
||||
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
try:
|
||||
deadline = time.monotonic()+max(.1, min(10, timeout_seconds))
|
||||
result_path = job.with_name('result.json')
|
||||
while not result_path.exists():
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('FILE_PROBE_CANCELLED')
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError('FILE_PROBE_TIMEOUT: 文件占用检查超时,未证明释放')
|
||||
if process.poll() is not None:
|
||||
raise OSError('FILE_PROBE_UNCONFIRMED: 文件探测未返回证据')
|
||||
time.sleep(.02)
|
||||
if stop is not None and stop.is_set():
|
||||
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:
|
||||
error = OSError('FILE_PROBE_UNCONFIRMED: '+str(record.get('error', '探测身份或句柄失效')))
|
||||
error.winerror = record.get('winerror')
|
||||
error.blocked_resources = record.get('blocked_resources', [])
|
||||
raise error
|
||||
# Duplicate the already-open handles before acknowledging the probe.
|
||||
# Its exit can never create a gap in the parent's commit protection.
|
||||
import win32api, win32con
|
||||
with ExitStack() as protection:
|
||||
child = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE, False, process.pid)
|
||||
protection.callback(child.Close)
|
||||
if len(record['handles']) != len(record['exclusive_files'])+len(record['binding_files']):
|
||||
raise OSError('FILE_PROBE_UNCONFIRMED: 证明句柄数量不符')
|
||||
for handle in record['handles']:
|
||||
owned = win32api.DuplicateHandle(child, handle, win32api.GetCurrentProcess(),
|
||||
0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||
protection.callback(owned.Close)
|
||||
yield {k: v for k, v in record.items() if k != 'handles'}
|
||||
finally:
|
||||
process.stdin.close()
|
||||
try:
|
||||
process.wait(.5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.terminate() # This executable only scans and opens read handles.
|
||||
process.wait(3)
|
||||
|
||||
|
||||
def _snapshot(library, roots):
|
||||
from .scoped_manifest import scan_tree
|
||||
entries = {library: library.lstat()}
|
||||
for root in roots:
|
||||
if root.exists():
|
||||
entries.update(scan_tree(root))
|
||||
native = sorted(path for path, info in entries.items() if stat.S_ISREG(info.st_mode)
|
||||
and (path == library or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')))
|
||||
if library not in native:
|
||||
raise ValueError('目标库身份缺失')
|
||||
addresses = sorted(path for path in entries if path.name.casefold() == 'saddress.adr')
|
||||
targets, signatures = [], {}
|
||||
for address in addresses:
|
||||
data = address.read_bytes()
|
||||
signatures[str(address)] = hashlib.sha256(data).hexdigest()
|
||||
database = address.parent.parent
|
||||
matches = []
|
||||
for project in database.parent.glob('*.prj'):
|
||||
if project not in entries or project.stat().st_size > 1024*1024:
|
||||
continue
|
||||
from .backup_recovery import _project_text
|
||||
text = _project_text(project)
|
||||
references = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"', text, re.M)
|
||||
if len(references) == 1 and (project.parent/references[0]).resolve() == database:
|
||||
matches.append(project)
|
||||
if len(matches) != 1 or database/'icdb.dat' not in native:
|
||||
raise ValueError(f'地址未绑定唯一工程数据库,需人工核对:{address}')
|
||||
targets.append({'project': str(matches[0]), 'database': str(database)})
|
||||
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],
|
||||
'inspection_targets': targets, 'signatures': signatures, 'binding_files': sorted(signatures),
|
||||
'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'),
|
||||
'shared_dependencies': sorted(str(p.parent) for p in native
|
||||
if p.is_relative_to(library.parent/'SymbolLibs') and p.name.casefold() == 'icdb.dat'),
|
||||
'databases': sorted({str(p.parent) for p in native if p.name.casefold() == 'icdb.dat'})}}
|
||||
|
||||
|
||||
def file_probe_main(job):
|
||||
"""No native launch, writes, repair, address deletion or process termination."""
|
||||
import win32con, win32file
|
||||
job = Path(job)
|
||||
request = json.loads(job.read_text('utf-8'))
|
||||
result = {'token': request['token'], 'status': 'UNCONFIRMED'}
|
||||
opening = None
|
||||
try:
|
||||
def checked_path(value):
|
||||
path = Path(value).absolute()
|
||||
for part in (path, *path.parents):
|
||||
try:
|
||||
info = part.lstat()
|
||||
except FileNotFoundError:
|
||||
continue
|
||||
if info.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||
raise ValueError(f'资源范围含重解析点:{part}')
|
||||
return path.resolve()
|
||||
library = checked_path(request['library'])
|
||||
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):
|
||||
raise ValueError('文件探测范围不属于所选库')
|
||||
snapshot = _snapshot(library, roots)
|
||||
with ExitStack() as stack:
|
||||
handles = []
|
||||
for path in snapshot['exclusive_files']:
|
||||
opening = path
|
||||
handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
handles.append(int(handle))
|
||||
for path in snapshot['binding_files']:
|
||||
opening = path
|
||||
handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ,
|
||||
None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
handles.append(int(handle))
|
||||
opening = None
|
||||
if _snapshot(library, roots) != snapshot:
|
||||
raise ValueError('占用检查期间资源集合变化')
|
||||
pending = job.with_name('result.pending')
|
||||
pending.write_text(json.dumps({**result, **snapshot, 'status': 'HELD', 'handles': handles}), 'utf-8')
|
||||
pending.replace(job.with_name('result.json'))
|
||||
sys.stdin.buffer.read(1) # Parent keeps stdin open until its commit finishes.
|
||||
return 0
|
||||
except Exception as error:
|
||||
pending = job.with_name('result.pending')
|
||||
blocked = [opening] if opening and getattr(error, 'winerror', None) in (32,33) else []
|
||||
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'))
|
||||
return 1
|
||||
@@ -2,6 +2,19 @@
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def session_resource_scope(job):
|
||||
"""Persist declared targets; only fresh proof promotes them to observed scope."""
|
||||
library = Path(job['library'])
|
||||
project, pcb = job.get('project'), job.get('pcb')
|
||||
projects = [str(Path(project))] if project else []
|
||||
databases = [str(Path(p).parent/'database') for p in (project, pcb) if p]
|
||||
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb'
|
||||
return {'scope_state': 'DECLARED' if project else 'RECHECK_REQUIRED',
|
||||
'library': str(library), 'operation_id': job.get('operation_id'),
|
||||
'block_name': job.get('block'), 'projects': projects,
|
||||
'databases': list(dict.fromkeys(databases)), 'shared_dependencies': [str(shared)]}
|
||||
|
||||
|
||||
def database_directories(lmc_file, project, pcb):
|
||||
return tuple(dict.fromkeys((
|
||||
Path(project).parent/'database',
|
||||
@@ -14,3 +27,20 @@ def unreleased_addresses(lmc_file, project, pcb):
|
||||
return [str(path/'cdbsvr/sAddress.adr')
|
||||
for path in database_directories(lmc_file, project, pcb)
|
||||
if (path/'cdbsvr/sAddress.adr').exists()]
|
||||
|
||||
|
||||
def inspect_release_addresses(snapshot, *, stop=None):
|
||||
"""An address is a reason for native inspection, never an occupancy verdict."""
|
||||
import tempfile
|
||||
from .native_repair import RepairTarget, run_native_repair
|
||||
from .native_occupancy import confirmed_inspection
|
||||
from .library_lock import LibraryBusy
|
||||
results = []
|
||||
for item in snapshot['inspection_targets']:
|
||||
target = RepairTarget(Path(item['project']), Path(item['database']))
|
||||
root = Path(tempfile.mkdtemp(prefix='cbb-release-inspection-'))
|
||||
result = run_native_repair(target, root, inspection_only=True, stop=stop)
|
||||
if not confirmed_inspection(target, result) or result['status'] != 'NOT_IN_USE':
|
||||
raise LibraryBusy(f'目标数据库未确认释放:{target.database};检查证据:{root}')
|
||||
results.append(result)
|
||||
return results
|
||||
@@ -8,7 +8,7 @@ import re
|
||||
ERROR_CODE = 'ICDB_REPAIR_REQUIRED'
|
||||
LOG_LIMIT = 128 * 1024
|
||||
RECOVERY_ACTION = (
|
||||
'停止批次并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,'
|
||||
'停止受影响工程的写入并确认原服务器及其他客户端已正常关闭;保留完整一致副本后,'
|
||||
"使用同版本 iCDB Project Backup 的 Repair project 检查并修复正确目标。"
|
||||
'共享符号库问题需核对中心库,不能只修复单个 CBB 的 Work 工程。'
|
||||
'不要删除 sAddress.adr/锁文件;修复后重新打开、校验并确认权威 READY。'
|
||||
@@ -16,6 +16,9 @@ RECOVERY_ACTION = (
|
||||
_SESSION_LOSS = re.compile(
|
||||
r'\bthe\s+last\s+server\s+session\s+on\s+different\s+server\s+machine\s+'
|
||||
r'lost\s+the\s+connection\s+to\s+the\s+database\b', re.IGNORECASE)
|
||||
_INCONSISTENT = re.compile(
|
||||
r"Project database \[([^\]\r\n]+)\] is inconsistent\. It has been manually copied while the iCDB Server was running\.\s*"
|
||||
r"Please use iCDB Project Backup 'Repair project' functionality to fix this issue\.", re.I)
|
||||
|
||||
_ICDB_MESSAGE = re.compile(r'(?<![A-Za-z0-9_])icdb(?![A-Za-z0-9_.\\/])', re.I)
|
||||
_FAILURE_MESSAGE = re.compile(
|
||||
@@ -78,11 +81,25 @@ def parse_session_loss(text):
|
||||
return record
|
||||
|
||||
|
||||
def parse_recovery_request(text):
|
||||
record = parse_session_loss(text)
|
||||
if record is not None:
|
||||
return record
|
||||
match = _INCONSISTENT.search(str(text or ''))
|
||||
if match is not None:
|
||||
shared = 'symbollibs' in ntpath.normpath(match[1]).casefold().split('\\')
|
||||
return {'error_code': ERROR_CODE, 'kind': 'database_inconsistent',
|
||||
'native_message': match[0], 'database_path': match[1], 'scope': 'central_library' if shared else 'project',
|
||||
'machine': '', 'session': ''}
|
||||
return None
|
||||
|
||||
|
||||
def recovery_detail(record):
|
||||
target = ('中心库共享符号数据库' if record['scope'] == 'central_library' else
|
||||
'工程数据库' if record['scope'] == 'project' else '报错中指定的数据库')
|
||||
reason = '数据库副本不一致' if record.get('kind') == 'database_inconsistent' else '上次服务器会话失联'
|
||||
return (
|
||||
f"{ERROR_CODE}: {target}的上次服务器会话失联。\n"
|
||||
f"{ERROR_CODE}: {target}{reason};发现问题,未修复。\n"
|
||||
f"{record['native_message']}\n"
|
||||
f'{RECOVERY_ACTION}'
|
||||
)
|
||||
@@ -100,7 +117,8 @@ def snapshot_log(path):
|
||||
return {'size': size, 'tail_sha256': hashlib.sha256(tail).hexdigest(),
|
||||
'truncated': size > LOG_LIMIT,
|
||||
'icdb_errors': [' '.join(message.split()) for message in _icdb_error_paragraphs(decode_log(tail))],
|
||||
'session_losses': losses}
|
||||
'session_losses': losses,
|
||||
'inconsistent_databases': [match[1] for match in _INCONSISTENT.finditer(decode_log(tail))]}
|
||||
except FileNotFoundError:
|
||||
return {'size': 0, 'tail_sha256': hashlib.sha256(b'').hexdigest(), 'icdb_errors': []}
|
||||
except OSError as error:
|
||||
@@ -161,6 +179,12 @@ def read_log_failure(path, baseline):
|
||||
historical = baseline.get('session_losses', []) if baseline else []
|
||||
recovery = next((record for record in _session_losses(text)
|
||||
if appended or _session_identity(record) not in historical), None)
|
||||
if recovery is None:
|
||||
old = baseline.get('inconsistent_databases') if baseline else None
|
||||
match = next((match for match in _INCONSISTENT.finditer(text)
|
||||
if appended or old is not None and match[1] not in old), None)
|
||||
if match is not None:
|
||||
recovery = parse_recovery_request(match[0])
|
||||
return text, recovery
|
||||
|
||||
|
||||
|
||||
@@ -11,6 +11,28 @@ from uuid import uuid4
|
||||
|
||||
_guard = threading.RLock()
|
||||
_owners = {}
|
||||
_library_guards = {}
|
||||
|
||||
|
||||
def _library_guard(key):
|
||||
"""Serialize one lease without making slow resource probes global."""
|
||||
with _guard:
|
||||
return _library_guards.setdefault(key, threading.RLock())
|
||||
|
||||
|
||||
def duplicate_worker_lease(library, process_handle):
|
||||
"""Keep the exact admitted exclusive file object alive across parent exit."""
|
||||
import win32api, win32con
|
||||
lease = LibraryLock(library)
|
||||
with _library_guard(lease.key):
|
||||
owner = _owners.get(lease.key)
|
||||
if owner is None:
|
||||
return None
|
||||
if owner['thread'] != threading.get_ident() or owner['retained'] or not owner['depth']:
|
||||
raise LibraryBusy('不能将其他任务的库锁交给工作进程。')
|
||||
remote = win32api.DuplicateHandle(win32api.GetCurrentProcess(), owner['handle'],
|
||||
process_handle, 0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||
return remote.Detach() # This handle belongs to the target process only.
|
||||
|
||||
|
||||
class LibraryBusy(OSError):
|
||||
@@ -82,10 +104,10 @@ def has_retained_library(library):
|
||||
return bool(owner and owner['retained'])
|
||||
|
||||
|
||||
def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None):
|
||||
def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None, stop=None):
|
||||
"""Historical records trigger fresh proof, never process termination or repair."""
|
||||
if not required:
|
||||
with _guard:
|
||||
with _library_guard(LibraryLock(library).key):
|
||||
owner = _owners.get(LibraryLock(library).key)
|
||||
marker = blocker_path(library)
|
||||
record = checkpoint_record(marker)
|
||||
@@ -108,10 +130,13 @@ def recheck_previous_release(library, evidence_dir, *, block_name=None, required
|
||||
logging.getLogger(__name__).warning('Release progress observer failed', exc_info=True)
|
||||
notify('previous_release_check', detail='正在复核历史记录对应的实际占用')
|
||||
try:
|
||||
proof = release_retained_library(library, evidence_dir, block_name=block_name)
|
||||
options = {'stop': stop} if stop is not None else {}
|
||||
proof = release_retained_library(library, evidence_dir, block_name=block_name, **options)
|
||||
except Exception as error:
|
||||
notify('previous_release_unconfirmed', detail=str(error))
|
||||
raise
|
||||
from .operation_queue import note_metadata_progress
|
||||
note_metadata_progress()
|
||||
notify('previous_release_confirmed', release_proof=proof,
|
||||
detail='已确认会话释放并归档历史记录;这不表示历史数据已恢复')
|
||||
return proof
|
||||
@@ -128,9 +153,14 @@ def _persist_blocker(library, status='OWNER_RELEASE_UNCONFIRMED', *, lease_id, b
|
||||
export_record['block_name'] = block_name
|
||||
elif previous and previous['lease_id'] == lease_id and 'block_name' in previous:
|
||||
export_record['block_name'] = previous['block_name']
|
||||
from .icdb_ownership import session_resource_scope
|
||||
scope = (previous.get('resource_scope') if previous and previous['lease_id'] == lease_id else None)
|
||||
scope = scope or session_resource_scope({'library': library, 'block': export_record.get('block_name')})
|
||||
with pending.open('w', encoding='utf-8') as stream:
|
||||
json.dump({**export_record, 'protocol': 'cbb-refresh-verify-library-lease', 'version': 1,
|
||||
'lease_id': lease_id, 'library': str(library), 'status': status,
|
||||
'lease_state': 'ACTIVE' if status == 'OPERATION_IN_PROGRESS' else 'RETAINED',
|
||||
'resource_scope': scope, 'blocked_resources': [], 'data_recovery_required': None,
|
||||
'machine': socket.gethostname(),
|
||||
'supervisor_created': win32process.GetProcessTimes(win32api.GetCurrentProcess())['CreationTime'].isoformat(),
|
||||
'pid': os.getpid(), 'time': datetime.now(timezone.utc).isoformat()}, stream)
|
||||
@@ -159,7 +189,7 @@ class LibraryLock:
|
||||
return lease
|
||||
|
||||
def __enter__(self):
|
||||
with _guard:
|
||||
with _library_guard(self.key):
|
||||
owner = _owners.get(self.key)
|
||||
if owner and owner['retained'] and owner['depth'] == 0 and owner.get('release_probe'):
|
||||
try:
|
||||
@@ -180,7 +210,7 @@ class LibraryLock:
|
||||
if self.maintenance_guard is not None:
|
||||
return _enter_maintenance(self)
|
||||
import win32con, win32file
|
||||
with _guard:
|
||||
with _library_guard(self.key):
|
||||
owner = _owners.get(self.key)
|
||||
if owner:
|
||||
if owner['thread'] != threading.get_ident() or owner['retained']:
|
||||
@@ -246,7 +276,7 @@ class LibraryLock:
|
||||
self.maintenance_mutex = None
|
||||
|
||||
def _exit_owned(self):
|
||||
with _guard:
|
||||
with _library_guard(self.key):
|
||||
if not self.entered:
|
||||
return
|
||||
owner = _owners[self.key]
|
||||
@@ -394,15 +424,13 @@ def _owner_is_blocking(item, library, roots):
|
||||
|
||||
def _enter_maintenance(lease):
|
||||
"""Transfer only a valid known lease, after project admission under lock."""
|
||||
import win32con, win32event, win32file
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
import win32con, win32file
|
||||
from .operation_queue import check_active
|
||||
handle = None
|
||||
existing = None
|
||||
try:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired: raise LibraryBusy('已有 CBB 操作运行,维护不能接续')
|
||||
with _guard:
|
||||
check_active()
|
||||
with _library_guard(lease.key):
|
||||
marker = blocker_path(lease.library)
|
||||
if marker.with_suffix('.pending').exists():
|
||||
raise LibraryBusy('未完成检查点写入,不能自动接续')
|
||||
@@ -436,6 +464,7 @@ def _enter_maintenance(lease):
|
||||
with saved.open('xb') as stream:
|
||||
stream.write(old); stream.flush(); os.fsync(stream.fileno())
|
||||
if saved.read_bytes() != old: raise OSError('原检查点归档校验失败')
|
||||
check_active()
|
||||
lease_id = uuid4().hex
|
||||
_persist_blocker(lease.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
|
||||
_owners[lease.key] = {'thread': threading.get_ident(), 'depth': 1, 'handle': handle,
|
||||
@@ -443,19 +472,16 @@ def _enter_maintenance(lease):
|
||||
'release_probe': lease.safe_to_release, 'block_name': None}
|
||||
lease.maintenance_proof = proof
|
||||
lease.entered = True
|
||||
lease.maintenance_mutex = mutex
|
||||
return lease
|
||||
except Exception:
|
||||
if handle is not None and existing is None: handle.Close()
|
||||
if acquired: win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
raise
|
||||
|
||||
|
||||
def owned_snapshot(path):
|
||||
"""Read only a lease held by this thread, never reopen an exclusive file."""
|
||||
import win32con, win32file
|
||||
with _guard:
|
||||
with _library_guard(_key(path)):
|
||||
owner = _owners.get(_key(path))
|
||||
if not owner or owner['thread'] != threading.get_ident() or owner['retained']:
|
||||
return None
|
||||
@@ -470,19 +496,17 @@ def owned_snapshot(path):
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoint=False):
|
||||
def _prove_library_released(library, block_name=None, *, block_names=(), allow_unknown_checkpoint=False, stop=None):
|
||||
"""Hold all native database read handles during explicit lease release."""
|
||||
import stat
|
||||
import win32con, win32file
|
||||
from .operation_queue import note_metadata_progress
|
||||
from .owner_probe import query_owners
|
||||
from .scoped_manifest import scan_tree
|
||||
from .native_management import _retained_workers
|
||||
from .native_export_guard import assert_retained_exports_idle, prove_export_copies_released
|
||||
from .native_engineering_identity import _OWNER_NAMES
|
||||
library = Path(library).resolve()
|
||||
assert_retained_exports_idle(library)
|
||||
if any(worker.poll() is None and (allow_unknown_checkpoint
|
||||
or not getattr(worker, 'cbb_library', None) or _key(worker.cbb_library) == _key(library))
|
||||
if any(worker.poll() is None and (not getattr(worker, 'cbb_library', None)
|
||||
or _key(worker.cbb_library) == _key(library))
|
||||
for worker in _retained_workers):
|
||||
raise LibraryBusy('原生管理工作进程尚未返回,不能解除协调阻止。')
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
@@ -492,12 +516,17 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
|
||||
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe',
|
||||
'cscript.exe', 'wscript.exe', 'python.exe', 'pythonw.exe',
|
||||
'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
|
||||
scope_root = (Path(library).resolve().parent/'ReusableBlocksLP'/block_name/'Work').resolve() if block_name else None
|
||||
blocks = tuple(dict.fromkeys(block_names or ((block_name,) if block_name else ())))
|
||||
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks):
|
||||
raise ValueError('释放检查的工程名称无效')
|
||||
scope_roots = tuple(library.parent/'ReusableBlocksLP'/name/'Work' for name in blocks)
|
||||
shared_root = Path(library).resolve().parent/'SymbolLibs'
|
||||
if allow_unknown_checkpoint and scope_root is not None:
|
||||
if allow_unknown_checkpoint and scope_roots:
|
||||
raise LibraryBusy('未知检查点必须执行完整库释放证明。')
|
||||
observed = []
|
||||
def check_owners():
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('已停止释放检查')
|
||||
owners = []
|
||||
observed.clear()
|
||||
from .session_record import active_write_records
|
||||
@@ -506,12 +535,11 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
|
||||
for item in query_owners(names):
|
||||
if item['pid'] == os.getpid():
|
||||
continue
|
||||
if not allow_unknown_checkpoint:
|
||||
roots = (scope_root, shared_root) if scope_root is not None else (Path(library).parent,)
|
||||
if not _owner_is_blocking(item, library, roots):
|
||||
if _owner_matches_scope(item, library, roots) is None:
|
||||
observed.append(item)
|
||||
continue
|
||||
roots = (*scope_roots, shared_root) if scope_roots else (library.parent,)
|
||||
if not _owner_is_blocking(item, library, roots):
|
||||
if _owner_matches_scope(item, library, roots) is None:
|
||||
observed.append(item)
|
||||
continue
|
||||
automation = item['name'].casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
|
||||
command = item['command'].casefold()
|
||||
if not automation or not command or any(flag in command for flag in (
|
||||
@@ -519,68 +547,82 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
|
||||
owners.append(item)
|
||||
if owners:
|
||||
raise LibraryBusy(f'原生进程仍存在,不能解除协调阻止:{owners}')
|
||||
note_metadata_progress()
|
||||
return owners
|
||||
check_owners()
|
||||
if scope_root is None:
|
||||
entries = scan_tree(Path(library).parent)
|
||||
else:
|
||||
entries = {Path(library): Path(library).lstat()}
|
||||
for root in (scope_root, shared_root):
|
||||
if root.exists():
|
||||
entries.update(scan_tree(root))
|
||||
addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr'
|
||||
and (scope_root is None or path.is_relative_to(scope_root)
|
||||
or path.is_relative_to(shared_root))]
|
||||
if addresses:
|
||||
raise LibraryBusy(f'库中仍有数据库地址记录,不能自动解除:{addresses}')
|
||||
# scan_tree already rejects links; only native candidates need file opens.
|
||||
native = [path for path, metadata in entries.items() if stat.S_ISREG(metadata.st_mode) and (
|
||||
path == library
|
||||
or (path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')
|
||||
and (scope_root is None or path.is_relative_to(scope_root)
|
||||
or path.is_relative_to(shared_root))))]
|
||||
if library not in native:
|
||||
raise LibraryBusy('目标库身份缺失,不能解除协调阻止。')
|
||||
from .file_probe import hold_release_files
|
||||
roots = (*scope_roots, shared_root) if scope_roots else None
|
||||
inspections = []
|
||||
with ExitStack() as stack:
|
||||
try:
|
||||
files = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||
except OSError as error:
|
||||
blocked = LibraryBusy(str(error))
|
||||
blocked.winerror = getattr(error, 'winerror', None)
|
||||
blocked.blocked_resources = getattr(error, 'blocked_resources', [])
|
||||
raise blocked from error
|
||||
note_metadata_progress()
|
||||
if files['addresses']:
|
||||
# Native inspection needs the database; reacquire proof handles
|
||||
# and compare the exact address/project binding before commit.
|
||||
stack.close()
|
||||
from .icdb_ownership import inspect_release_addresses
|
||||
# Checkpoint I/O is per-library; only native inspection owns
|
||||
# the host channel. The sidecar still excludes other writers.
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('已停止释放检查')
|
||||
inspections = inspect_release_addresses(files, stop=stop)
|
||||
try:
|
||||
current = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||
except OSError as error:
|
||||
blocked = LibraryBusy(str(error))
|
||||
blocked.winerror = getattr(error, 'winerror', None)
|
||||
blocked.blocked_resources = getattr(error, 'blocked_resources', [])
|
||||
raise blocked from error
|
||||
if any(current[key] != files[key] for key in (
|
||||
'exclusive_files', 'addresses', 'signatures', 'inspection_targets')):
|
||||
raise LibraryBusy('原生检查期间资源范围或地址身份变化。')
|
||||
files = current
|
||||
note_metadata_progress()
|
||||
export_proof = (prove_export_copies_released(library, allow_unknown_checkpoint=True)
|
||||
if allow_unknown_checkpoint else prove_export_copies_released(library))
|
||||
export_copies = stack.enter_context(export_proof)
|
||||
for path in native:
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
owners = check_owners()
|
||||
yield {'native_owners': owners, 'observed_owners': list(observed),
|
||||
'addresses': addresses, 'export_copies': export_copies,
|
||||
'unknown_checkpoint_recovery': allow_unknown_checkpoint,
|
||||
'exclusive_files': [str(path) for path in native]}
|
||||
yield {**{k: v for k, v in files.items() if k not in ('status', 'token')},
|
||||
'native_owners': owners, 'observed_owners': list(observed),
|
||||
'export_copies': export_copies, 'native_inspections': inspections,
|
||||
'data_recovery_required': any(item['repair_required'] for item in inspections) if inspections else None,
|
||||
'data_recovery_resources': [item['database'] for item in inspections if item['repair_required']],
|
||||
'unknown_checkpoint_recovery': allow_unknown_checkpoint}
|
||||
|
||||
finally:
|
||||
uninitialize_com(initialized)
|
||||
|
||||
|
||||
def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
def release_retained_library(library, evidence_dir, *, block_name=None, block_names=(), stop=None):
|
||||
"""Reconcile historical leases after fresh owner/address/access proof.
|
||||
|
||||
The upload sidecar is never deleted. This acknowledges process release,
|
||||
not the correctness of a partially changed library or its recovery state.
|
||||
"""
|
||||
import win32con, win32event, win32file
|
||||
import win32con, win32file
|
||||
from .operation_queue import note_metadata_progress
|
||||
library = Path(library).resolve(strict=True)
|
||||
from .session_record import (retained_session_snapshot, acknowledge_library_release,
|
||||
reconciled_retained_sessions)
|
||||
retained = retained_session_snapshot(library)
|
||||
requested_blocks = tuple(dict.fromkeys(block_names or ((block_name,) if block_name else ())))
|
||||
if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in requested_blocks):
|
||||
raise ValueError('释放检查的工程名称无效')
|
||||
evidence = Path(evidence_dir).resolve()
|
||||
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
|
||||
raise ValueError('释放检查证据必须位于目标库之外。')
|
||||
lease = LibraryLock(library)
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
external = None
|
||||
try:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
raise LibraryBusy('另一个 CBB 操作仍在运行。')
|
||||
with _guard:
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('已停止释放检查')
|
||||
with _library_guard(lease.key):
|
||||
owner = _owners.get(lease.key)
|
||||
if owner and (not owner['retained'] or owner['depth']):
|
||||
raise LibraryBusy('本应用操作仍在使用库锁。')
|
||||
@@ -598,8 +640,10 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
before = {path: path.read_bytes() if path.exists() else None for path in checkpoints}
|
||||
unknown = any(data is not None and checkpoint_record(path) is None for path, data in before.items())
|
||||
records = [checkpoint_record(path) for path, data in before.items() if data is not None]
|
||||
scoped = (block_name if block_name and all(record and record.get('block_name') == block_name
|
||||
for record in records) and (owner is None or owner.get('block_name') == block_name) else None)
|
||||
scoped_blocks = (requested_blocks if requested_blocks and all(record
|
||||
and record.get('block_name') in requested_blocks for record in records)
|
||||
and (owner is None or owner.get('block_name') in requested_blocks) else ())
|
||||
scoped = scoped_blocks[0] if len(scoped_blocks) == 1 else None
|
||||
reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None,
|
||||
**{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}}
|
||||
for path, data in before.items() if data is not None
|
||||
@@ -610,28 +654,49 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
'status': 'OWNER_RELEASE_UNCONFIRMED'})
|
||||
foreign = sorted({item['block_name'] for item in reconciled
|
||||
if block_name and item.get('block_name') and item['block_name'] != block_name})
|
||||
proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True) if unknown else
|
||||
_prove_library_released(library, block_name=scoped)
|
||||
if scoped else _prove_library_released(library))
|
||||
options = {'stop': stop} if stop is not None else {}
|
||||
if len(scoped_blocks) > 1:
|
||||
options['block_names'] = scoped_blocks
|
||||
proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True, **options) if unknown else
|
||||
_prove_library_released(library, block_name=scoped, **options)
|
||||
if scoped else _prove_library_released(library, **options))
|
||||
with proof_context as proof:
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('已停止释放检查')
|
||||
with _guard:
|
||||
if _owners.get(lease.key) is not owner:
|
||||
raise LibraryBusy('释放检查期间租约身份变化,保留当前任务。')
|
||||
if unknown and proof.get('unknown_checkpoint_recovery') is not True:
|
||||
raise LibraryBusy('未知检查点缺少完整库释放证明,保留原文件。')
|
||||
if any((path.read_bytes() if path.exists() else None) != data for path, data in before.items()):
|
||||
raise LibraryBusy('释放检查期间协调检查点变化,保留原文件。')
|
||||
root = evidence/('release-' + uuid4().hex)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
reconciled_sessions = reconciled_retained_sessions(retained, block_name=scoped)
|
||||
matching_retained = ({path: value for path, value in retained.items()
|
||||
if value[1] in scoped_blocks} if scoped_blocks else retained)
|
||||
reconciled_sessions = reconciled_retained_sessions(matching_retained, block_name=scoped)
|
||||
reconciled_blocks = sorted({item['block_name'] for item in (*reconciled, *reconciled_sessions)
|
||||
if item.get('block_name')})
|
||||
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
|
||||
'requested_block_name': block_name, 'proof_scope': 'BLOCK' if scoped else 'LIBRARY',
|
||||
'proof_block_name': scoped, 'reconciled_checkpoints': reconciled,
|
||||
'requested_block_name': block_name, 'requested_block_names': list(requested_blocks),
|
||||
'proof_scope': 'BLOCK' if scoped else 'BLOCKS' if scoped_blocks else 'LIBRARY',
|
||||
'proof_block_name': scoped, 'proof_block_names': list(scoped_blocks),
|
||||
'reconciled_checkpoints': reconciled,
|
||||
'reconciled_foreign_blockers': sorted(set(foreign) | {
|
||||
block for block in reconciled_blocks if block_name and block != block_name}),
|
||||
'reconciled_blocks': reconciled_blocks, 'reconciled_sessions': reconciled_sessions,
|
||||
'unknown_checkpoint_archived': unknown,
|
||||
'lease_state': 'RELEASED', 'blocked_resources': [],
|
||||
'data_recovery_required': proof.get('data_recovery_required', None),
|
||||
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
|
||||
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
record['resource_scope'] = {**proof.get('resource_scope', {}),
|
||||
'scope_state': 'OBSERVED', 'library': str(library), 'block_name': scoped,
|
||||
'block_names': list(scoped_blocks),
|
||||
'lease_id': owner['lease_id'] if owner else None,
|
||||
'operation_ids': [item['operation_id'] for item in reconciled_sessions]}
|
||||
pending = {**record, 'status': 'RELEASE_PENDING', 'lease_state': 'PENDING'}
|
||||
(root/'release.json').write_text(json.dumps(pending, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
note_metadata_progress()
|
||||
for index, checkpoint in enumerate(checkpoints):
|
||||
if checkpoint.exists():
|
||||
data = checkpoint.read_bytes()
|
||||
@@ -639,15 +704,16 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
archived.write_bytes(data)
|
||||
if archived.read_bytes() != data:
|
||||
raise OSError('阻止记录归档校验失败,保持库锁。')
|
||||
note_metadata_progress()
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('已停止释放检查')
|
||||
checkpoint.unlink() # Checkpoint JSON only; never .lock.
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
del _owners[lease.key]
|
||||
acknowledge_library_release(record, retained, block_name=scoped)
|
||||
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
acknowledge_library_release(record, matching_retained, block_name=scoped)
|
||||
return record
|
||||
finally:
|
||||
if external is not None:
|
||||
external.Close()
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
@@ -203,20 +203,22 @@ def filesystem_status_map(library: Path, names):
|
||||
return {name: details['status'] for name, details in filesystem_evidence_map(library, names).items()}
|
||||
|
||||
def read_library_fast(path: Path, *, status_reader=None):
|
||||
"""List CBBs from ReusableBlocksLP without touching COM or the .lmc.
|
||||
|
||||
Useful when Library Manager is unavailable or already running: the folder
|
||||
is the same source the LM tree shows, and an optional status_reader can
|
||||
supply each item's flag without a full COM session.
|
||||
"""
|
||||
"""Discover directories; this does not validate native format/registration."""
|
||||
try:
|
||||
path = Path(path)
|
||||
if path.suffix.casefold() != '.lmc':
|
||||
return LibraryReadResult((), 'INPUT_SUFFIX: 请选择 .lmc 中心库文件。')
|
||||
if not path.is_file():
|
||||
return LibraryReadResult((), f'中心库不存在: {path}')
|
||||
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'
|
||||
if not folder.is_dir():
|
||||
return LibraryReadResult((), f'缺少 ReusableBlocksLP 目录: {folder}')
|
||||
entries = [entry for entry in folder.iterdir() if entry.is_dir()]
|
||||
if folder.exists() and not folder.is_dir():
|
||||
return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}')
|
||||
entries = [entry for entry in folder.iterdir() if entry.is_dir()] if folder.is_dir() else []
|
||||
names = tuple(sorted((entry.name for entry in entries), key=str.casefold))
|
||||
statuses = {}
|
||||
if status_reader is not None and names:
|
||||
@@ -240,8 +242,11 @@ def read_library_fast(path: Path, *, status_reader=None):
|
||||
status = str(statuses.get(entry.name, 'UNKNOWN') or 'UNKNOWN')
|
||||
if status not in {'READY', 'PENDING', 'UNKNOWN', 'UNAVAILABLE', 'ERROR', 'TIMEOUT'}:
|
||||
status = 'UNKNOWN'
|
||||
records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status))
|
||||
return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name)))
|
||||
records.append(CbbRecord(entry.name, 'Reusable Blocks', status=status,
|
||||
catalog_source='directory', status_source='status_reader' if status_reader else 'unknown'))
|
||||
return LibraryReadResult(tuple(sorted(records, key=lambda item: item.name)), directory_count=len(entries))
|
||||
except PermissionError as error:
|
||||
return LibraryReadResult((), f'INPUT_PERMISSION: 无权读取中心库: {error}')
|
||||
except Exception as error:
|
||||
return LibraryReadResult((), str(error))
|
||||
|
||||
|
||||
@@ -19,22 +19,25 @@ def assert_native_idle(target=None):
|
||||
from .native_export_guard import assert_retained_exports_idle
|
||||
from .native_engineering_identity import _OWNER_NAMES
|
||||
from .library_lock import _key, _owner_matches_scope
|
||||
library = None
|
||||
library = Path(target.library) if target is not None and getattr(target, 'library', None) else None
|
||||
roots = ()
|
||||
if target is not None:
|
||||
from .backup_recovery import _project_text
|
||||
roots = (Path(target.project).parent, Path(target.database))
|
||||
try:
|
||||
lines = re.findall(r'^KEY CentralLibrary\b[^\r\n]*', _project_text(target.project), re.M)
|
||||
references = [re.fullmatch(r'KEY CentralLibrary "([^"\r\n]+)"\s*', line) for line in lines]
|
||||
if not references or any(match is None for match in references):
|
||||
raise ValueError('CentralLibrary references are missing or invalid.')
|
||||
libraries = {(Path(target.project).parent/match[1]).resolve(strict=True) for match in references}
|
||||
if len(libraries) == 1 and all(path.suffix.casefold() == '.lmc' and path.is_file() for path in libraries):
|
||||
library = libraries.pop()
|
||||
roots += (library.parent/'SymbolLibs',)
|
||||
except (OSError, ValueError):
|
||||
pass # Missing/ambiguous original references cannot narrow retained ownership.
|
||||
if library is not None:
|
||||
roots += (library.parent/'SymbolLibs',)
|
||||
else:
|
||||
try:
|
||||
lines = re.findall(r'^KEY CentralLibrary\b[^\r\n]*', _project_text(target.project), re.M)
|
||||
references = [re.fullmatch(r'KEY CentralLibrary "([^"\r\n]+)"\s*', line) for line in lines]
|
||||
if not references or any(match is None for match in references):
|
||||
raise ValueError('CentralLibrary references are missing or invalid.')
|
||||
libraries = {(Path(target.project).parent/match[1]).resolve(strict=True) for match in references}
|
||||
if len(libraries) == 1 and all(path.suffix.casefold() == '.lmc' and path.is_file() for path in libraries):
|
||||
library = libraries.pop()
|
||||
roots += (library.parent/'SymbolLibs',)
|
||||
except (OSError, ValueError):
|
||||
pass # Missing/ambiguous original references cannot narrow retained ownership.
|
||||
assert_retained_exports_idle(library)
|
||||
if any(worker.poll() is None and (library is None or not getattr(worker, 'cbb_library', None)
|
||||
or _key(worker.cbb_library) == _key(library)) for worker in _retained_workers):
|
||||
|
||||
@@ -171,9 +171,11 @@ def _may_have_mutated(record):
|
||||
|
||||
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None, version_prompt=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
|
||||
import win32con, win32event
|
||||
from contextlib import ExitStack
|
||||
from .operation_queue import check_active, native_channel, task_stop, remember_result
|
||||
stop = task_stop(stop)
|
||||
import pythoncom
|
||||
if adapter is None:
|
||||
from .native_management import NativeManagementAdapter
|
||||
@@ -190,8 +192,6 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
history = []
|
||||
mutated = uploaded = removed = False
|
||||
owner_safe = True
|
||||
mutex = None
|
||||
acquired = False
|
||||
release_proof = None
|
||||
original = None
|
||||
change_report = None
|
||||
@@ -199,12 +199,13 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
nonlocal owner_safe
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('MANAGEMENT_CANCELLED: 已停止后续原生操作')
|
||||
owner_safe = False
|
||||
try:
|
||||
result = callback(*args)
|
||||
except Exception as error:
|
||||
owner_safe = getattr(error, 'safe_to_continue', False) is True
|
||||
raise
|
||||
with native_channel():
|
||||
owner_safe = False
|
||||
try:
|
||||
result = callback(*args)
|
||||
except Exception as error:
|
||||
owner_safe = getattr(error, 'safe_to_continue', False) is True
|
||||
raise
|
||||
owner_safe = result.safe_to_continue
|
||||
return result
|
||||
def checkpoint(next_stage, **details):
|
||||
@@ -215,14 +216,18 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
_write_json(report, {**asdict(request), 'stage': stage, 'status': 'RUNNING',
|
||||
'safe_to_continue': False, 'history': history, 'backup_policy': 'manual'})
|
||||
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):
|
||||
nonlocal change_report
|
||||
remember_result(ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report))
|
||||
if mutated and original is not None and change_report is None:
|
||||
change_report = {'status': 'UNCONFIRMED', 'scope': original['scope'],
|
||||
**comparison_rules(scope),
|
||||
'unrelated_cbb_content_checked': False,
|
||||
'detail': '原生会话尚未释放,未读取写后内容'}
|
||||
remember_result(ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report))
|
||||
if safe:
|
||||
try:
|
||||
after = build_exclusive_library_manifest(library_root, scope=scope, progress=progress)
|
||||
@@ -244,12 +249,13 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
detail = (detail+'\n'+change_report['detail']).strip()
|
||||
result = ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||
request.source, request.auto_verify, 'complete', status, safe, detail, report, release_proof, change_report)
|
||||
remember_result(result)
|
||||
if report:
|
||||
try:
|
||||
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
|
||||
except OSError as error:
|
||||
result = replace(result, detail=f'{detail}\n操作记录写入失败:{error}'.strip())
|
||||
return result
|
||||
return remember_result(result)
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
try:
|
||||
@@ -283,6 +289,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
if request.operation in ('add', 'update'):
|
||||
if request.source is None:
|
||||
raise ValueError('新增/更新需要完整来源工程。')
|
||||
if hasattr(adapter, 'validate_source'):
|
||||
adapter.validate_source(request)
|
||||
source, pcb, top = source_project(request.source, request.top_level_block)
|
||||
if (source.parent.is_relative_to(library_root) or library_root.is_relative_to(source.parent)
|
||||
or evidence.is_relative_to(source.parent)
|
||||
@@ -292,24 +300,30 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
report = root/'checkpoint.json'
|
||||
checkpoint('release_check')
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
return finish('BLOCKED', '已有 CBB 校验/管理/恢复任务运行;本次未启动。')
|
||||
from .library_lock import recheck_previous_release
|
||||
release_proof = recheck_previous_release(library, root/'previous-release', block_name=request.name,
|
||||
required=request.check_previous_release or bool(unfinished_target
|
||||
and unfinished_target.get('safe_to_continue') is not True), progress=progress)
|
||||
and unfinished_target.get('safe_to_continue') is not True), progress=progress, stop=stop)
|
||||
if release_proof is not None:
|
||||
checkpoint('release_check', release_proof=release_proof)
|
||||
if unfinished_target:
|
||||
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished_target["evidence_path"]}')
|
||||
from .session_record import _proof_covers_session
|
||||
fresh = (request.check_previous_release and isinstance(release_proof, dict)
|
||||
and _proof_covers_session(release_proof, {'library': str(library), 'block': request.name})
|
||||
and bool(release_proof.get('evidence_path'))
|
||||
and Path(release_proof['evidence_path']).resolve().is_relative_to((root/'previous-release').resolve())
|
||||
and Path(release_proof['evidence_path']).is_file())
|
||||
if not fresh:
|
||||
return finish('BLOCKED', f'存在未完成/需恢复任务,禁止自动重放:{unfinished_target["evidence_path"]}')
|
||||
checkpoint('release_check', confirmed_new_request=True,
|
||||
previous_failed_operation=unfinished_target['evidence_path'])
|
||||
if hasattr(adapter, 'bind_library_mapping'):
|
||||
adapter.bind_library_mapping(request.mapped_drive, request.mapped_remote_root)
|
||||
if hasattr(adapter,'bind_write_admission'):
|
||||
adapter.bind_write_admission(write_admission if native_idle_check else None)
|
||||
check_active()
|
||||
with LibraryLock(library, block_name=request.name, safe_to_release=lambda: owner_safe or (
|
||||
callable(getattr(adapter, 'release_confirmed', None)) and adapter.release_confirmed(library))):
|
||||
callable(getattr(adapter, 'release_confirmed', None)) and adapter.release_confirmed(library))), ExitStack() as native_stack:
|
||||
work = library.parent/'ReusableBlocksLP'/request.name/'Work'
|
||||
target_project, target_pcb = work/(request.name+'.prj'), work/'PCB/pcb.pcb'
|
||||
if request.operation != 'add':
|
||||
@@ -324,7 +338,6 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
if source:
|
||||
idle_check(library, source, pcb)
|
||||
checkpoint('catalog_before')
|
||||
owner_safe = False
|
||||
before = invoke(adapter.catalog, library, root/'before')
|
||||
owner_safe = before.safe_to_continue
|
||||
if not owner_safe or Path(before.library).resolve() != canonical_library or before.flow != 1:
|
||||
@@ -366,6 +379,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
if request.operation in ('remove', 'update'):
|
||||
if stop is not None and stop.is_set():
|
||||
return finish('CANCELLED', '已取消,未开始移除', owner_safe)
|
||||
native_stack.enter_context(native_channel())
|
||||
checkpoint('native_remove')
|
||||
mutated = True; owner_safe = False
|
||||
native = invoke(adapter.remove, request, root/'remove')
|
||||
@@ -385,6 +399,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
if stop is not None and stop.is_set():
|
||||
return finish('RECOVERY_REQUIRED' if mutated else 'CANCELLED',
|
||||
'已停止后续导入;已发生的原生变更需要核对', owner_safe)
|
||||
if not removed:
|
||||
native_stack.enter_context(native_channel())
|
||||
checkpoint('native_add')
|
||||
mutated = True; owner_safe = False
|
||||
native = invoke(adapter.add, staged, root/'add')
|
||||
@@ -413,6 +429,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或工程关联未确认一致。\n'+native.detail, owner_safe)
|
||||
uploaded = True
|
||||
checkpoint('uploaded')
|
||||
native_stack.close()
|
||||
if not request.auto_verify:
|
||||
return finish('UPLOADED', '上传已确认;本批次未启用自动校验。\n'+native.detail)
|
||||
# Adapter catalog cannot return until its exact native owner exits.
|
||||
@@ -442,52 +459,82 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
|
||||
status = 'BLOCKED'
|
||||
return finish(status, str(error), owner_safe)
|
||||
finally:
|
||||
if mutex is not None:
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
uninitialize_com(initialized)
|
||||
|
||||
|
||||
def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, **kwargs):
|
||||
def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, context=None, **kwargs):
|
||||
from threading import Event
|
||||
from .write_admission import WriteAdmission
|
||||
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()
|
||||
if context is not None:
|
||||
stop = stop if stop is not None else context.stop
|
||||
progress = context.guard_callback(progress) if progress else None
|
||||
if stop is None:
|
||||
stop = Event()
|
||||
kwargs.setdefault('write_admission',WriteAdmission(prompt=kwargs.get('version_prompt'),stop=stop))
|
||||
results = []
|
||||
retained_libraries = set()
|
||||
retained_libraries = {}
|
||||
cancelled = False
|
||||
for request in requests:
|
||||
if stop is not None and stop.is_set():
|
||||
break
|
||||
key = str(request.library).casefold()
|
||||
if key in retained_libraries:
|
||||
keys = request_library_keys(request, context)
|
||||
stopped = (cancelled or stop.is_set() or context is not None
|
||||
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):
|
||||
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,
|
||||
request.source, request.auto_verify, 'complete', 'SKIPPED', True,
|
||||
'同库原生会话尚未释放,未启动新的写入')
|
||||
request.source, request.auto_verify, 'admission', 'SKIPPED', True,
|
||||
'队列已停止,未操作此 CBB' if stopped else
|
||||
f'PREVIOUS_SESSION_UNRELEASED: 前项 {previous.name} 的同库会话尚未释放,当前项未启动。')
|
||||
results.append(result)
|
||||
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
|
||||
def action():
|
||||
result = run_management(request, progress=progress, stop=stop, **kwargs)
|
||||
remember_result(result)
|
||||
if not result.safe_to_continue:
|
||||
from .operation_lifecycle import recheck_failed_release
|
||||
result = recheck_failed_release(request.library, request.name, result)
|
||||
result = recheck_failed_release(request.library, request.name, result, stop=stop)
|
||||
return result
|
||||
from .operation_queue import QueueCancelled
|
||||
try:
|
||||
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:
|
||||
results.append(ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||
request.source, request.auto_verify, 'complete', 'CANCELLED', True, str(error)))
|
||||
break
|
||||
known = error.result if isinstance(error, TaskHandoff) else None
|
||||
if isinstance(known, ManagementResult):
|
||||
result = replace(known, safe_to_continue=False,
|
||||
status='RECOVERY_REQUIRED' if known.status in ('PASS', 'UPLOADED', 'UPLOADED_VERIFIED', 'REMOVED')
|
||||
else known.status,
|
||||
release_proof=dict(status='RELEASE_PENDING', lease_state='PENDING',
|
||||
resource_scope=error.scope, previous_release_proof=known.release_proof))
|
||||
else:
|
||||
result = ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||
request.source, request.auto_verify, 'complete',
|
||||
'TIMEOUT' if isinstance(error, TaskHandoff) and not error.cancelled else 'CANCELLED',
|
||||
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)
|
||||
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 '')})
|
||||
if not result.safe_to_continue:
|
||||
retained_libraries.add(key)
|
||||
retained_libraries.update({key:(request, len(results)-1) for key in keys})
|
||||
if result.status == 'CANCELLED':
|
||||
break
|
||||
cancelled = True
|
||||
return results
|
||||
@@ -25,9 +25,9 @@ def fixture_authority(root, library, token):
|
||||
|
||||
|
||||
def current_lease(library):
|
||||
from .library_lock import LibraryLock, _guard, _owners, blocker_path, checkpoint_record
|
||||
from .library_lock import LibraryLock, _library_guard, _owners, blocker_path, checkpoint_record
|
||||
lease = LibraryLock(library)
|
||||
with _guard:
|
||||
with _library_guard(lease.key):
|
||||
owner = _owners.get(lease.key)
|
||||
guard = checkpoint_record(blocker_path(library))
|
||||
if (owner is None or owner['retained'] or owner['thread'] != threading.get_ident()
|
||||
|
||||
@@ -68,6 +68,10 @@ def pcb_startup_timeout_seconds(timeout_seconds):
|
||||
return max(60.0, float(timeout_seconds))
|
||||
|
||||
|
||||
def lm_dispatch_timeout_seconds(timeout_seconds):
|
||||
return max(.1, min(45.0, float(timeout_seconds)))
|
||||
|
||||
|
||||
def same_path(first, second):
|
||||
return os.path.normcase(os.path.abspath(str(first))) == os.path.normcase(os.path.abspath(str(second)))
|
||||
|
||||
@@ -680,6 +684,11 @@ def execute_job(job, emit):
|
||||
launcher_process = None
|
||||
completed = False
|
||||
identity_verified = False
|
||||
write_admitted = False
|
||||
prewrite_eligible = (job.get('diagnostic_only') is False and not job.get('native_lm_verify')
|
||||
and not job.get('post_repair_consent') and not job.get('interactive_input')
|
||||
and all(job.get(k) for k in ('operation_id','session_record_path','desktop')))
|
||||
startup_binding={k:job.get(k) for k in ('operation_id','project','pcb','desktop')}
|
||||
diagnostic_close_attempted = False
|
||||
helper = None
|
||||
app = doc = pi = None
|
||||
@@ -698,12 +707,15 @@ def execute_job(job, emit):
|
||||
from .diagnostic_open import snapshot_diagnostic_logs
|
||||
job['diagnostic_log_baseline'] = snapshot_diagnostic_logs(job)
|
||||
else:
|
||||
ensure_pcb_central_library(
|
||||
job['pcb'],
|
||||
job['lmc_file'],
|
||||
evidence_dir=Path(root) / 'diagnostics',
|
||||
emit=emit,
|
||||
)
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])):
|
||||
ensure_project_central_library(config, job['lmc_file'],
|
||||
evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit)
|
||||
if prewrite_eligible:
|
||||
from .diagnostic_open import snapshot_diagnostic_logs
|
||||
from .session_record import process_identity
|
||||
emit(stage='startup_prewrite_ready',baseline=snapshot_diagnostic_logs(job),
|
||||
worker_identity=process_identity(os.getpid()),**startup_binding)
|
||||
emit(
|
||||
stage='verify_mode',
|
||||
mode=('library_manager_native' if bool(job.get('native_lm_verify', False))
|
||||
@@ -716,12 +728,13 @@ def execute_job(job, emit):
|
||||
pcb_started_ns = time.time_ns()
|
||||
if bool(job.get('native_lm_verify', False)):
|
||||
from .library_manager_verify import launch_library_verify
|
||||
dispatch_deadline = time.monotonic()+lm_dispatch_timeout_seconds(job['timeout'])
|
||||
emit(stage='lm_launch', library=job['lmc_file'], block=job['block_name'])
|
||||
lm_session = launch_library_verify(
|
||||
job['lmc_file'],
|
||||
job['block_name'],
|
||||
emit,
|
||||
time.monotonic() + pcb_startup_timeout_seconds(job['timeout']),
|
||||
dispatch_deadline,
|
||||
mentor_bin=job.get('mentor_bin'),
|
||||
interactive_input=bool(job.get('interactive_input', False)),
|
||||
)
|
||||
@@ -737,8 +750,8 @@ def execute_job(job, emit):
|
||||
worker_parent_pid = int(launcher_process.pid)
|
||||
emit(stage='pcb_launcher_started', launcher_pid=worker_parent_pid,
|
||||
command=list(command), strategy='reusable_circuit_direct')
|
||||
pcb_deadline = reset_verify_activity_deadline(
|
||||
0.0, time.monotonic(), timeout_seconds=pcb_startup_timeout_seconds(job['timeout']))
|
||||
pcb_deadline = (dispatch_deadline if job.get('native_lm_verify') else
|
||||
time.monotonic()+pcb_startup_timeout_seconds(job['timeout']))
|
||||
while time.monotonic() < pcb_deadline:
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: PCB 启动期间收到停止请求')
|
||||
@@ -771,6 +784,8 @@ def execute_job(job, emit):
|
||||
break
|
||||
time.sleep(.2)
|
||||
if worker_pid is None:
|
||||
if job.get('native_lm_verify'):
|
||||
raise RuntimeError('VERIFY_DISPATCH_FAILED: LM 菜单返回但未观察到目标 PCB,未执行校验')
|
||||
raise RuntimeError('ReusableCircuit common 启动后未观察到 wg PCB 子进程')
|
||||
if job.get('diagnostic_only'):
|
||||
# Global PCB COM can wait on another design's modal window.
|
||||
@@ -805,6 +820,10 @@ def execute_job(job, emit):
|
||||
# the old, working path acquires the token inside the SysWOW64
|
||||
# cscript save helper below. The PCB UI license dialog has already
|
||||
# been handled by the private-desktop supervisor.
|
||||
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
|
||||
raise RuntimeError('VERIFY_CANCELLED: 未开始工程集成')
|
||||
write_admitted = True
|
||||
if prewrite_eligible:emit(stage='startup_write_admitted',**startup_binding)
|
||||
refresh_integration(
|
||||
pi,
|
||||
emit=emit,
|
||||
@@ -892,7 +911,7 @@ def execute_job(job, emit):
|
||||
pass
|
||||
if helper is not None and helper.poll() is None:
|
||||
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.
|
||||
emit(stage='save_result_retained', detail='保存或关闭结果不完整,保留原生会话供核对')
|
||||
elif diagnostic_close_attempted:
|
||||
@@ -910,6 +929,10 @@ def execute_job(job, emit):
|
||||
elif not completed and worker_pid is not None:
|
||||
try:
|
||||
from .failed_session import close_failed_startup
|
||||
if (prewrite_eligible and not write_admitted and not identity_verified
|
||||
and job.get('cancel_signal') and Path(job['cancel_signal']).exists()):
|
||||
emit(stage='startup_cancelled_prewrite',pcb_pid=worker_pid,
|
||||
identity_verified=False,write_admitted=False,**startup_binding)
|
||||
failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit,
|
||||
launcher_process=launcher_process)
|
||||
if failed_close.get('status') == 'CLOSED' and lm_session is not None:
|
||||
@@ -926,6 +949,8 @@ def execute_job(job, emit):
|
||||
)
|
||||
if completed and lm_session is not None:
|
||||
lm_session.close()
|
||||
elif worker_pid is None and lm_session is not None:
|
||||
lm_session.close() # No PCB was dispatched; close only this owned LM.
|
||||
|
||||
|
||||
def cleanup_verify_processes(lm_pid, worker_pid, worker_parent_pid=None, *,
|
||||
|
||||
@@ -7,8 +7,15 @@ class CbbRecord:
|
||||
partition_name: str
|
||||
logical_type: str = "LP"
|
||||
status: str = "UNKNOWN"
|
||||
catalog_source: str = "provided"
|
||||
status_source: str = "provided"
|
||||
missing_reason: str = ""
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LibraryReadResult:
|
||||
records: tuple[CbbRecord, ...]
|
||||
error: str | None = None
|
||||
directory_count: int | None = None
|
||||
native_count: int | None = None
|
||||
missing_project_count: int | None = None
|
||||
catalog_verified: bool = False
|
||||
@@ -1,7 +1,11 @@
|
||||
"""Open the official backup UI; version selection and writes stay native."""
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
from pathlib import PureWindowsPath
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -39,6 +43,36 @@ def native_backup_project(library, block):
|
||||
return project
|
||||
|
||||
|
||||
def native_backup_target(request, *, mode='versions', target_database=None):
|
||||
"""Bind the official tool without requiring an openable/healthy PCB."""
|
||||
from .backup_recovery import _project_text
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
if mode not in ('versions', 'repair'):
|
||||
raise ValueError('NATIVE_TARGET_MODE_INVALID')
|
||||
project = native_backup_project(request.lmc_file, request.block_name)
|
||||
candidates = (project,)
|
||||
if target_database is not None:
|
||||
pcbs = list((project.parent/'PCB').glob('*.pcb'))
|
||||
if len(pcbs) != 1:
|
||||
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 无法唯一绑定 PCB 工程')
|
||||
candidates = maintenance_project_files(project, pcbs[0])
|
||||
matches = []
|
||||
for config in candidates:
|
||||
values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"\s*$', _project_text(config), re.M)
|
||||
if len(values) != 1 or not values[0] or PureWindowsPath(values[0]).root or PureWindowsPath(values[0]).drive:
|
||||
if config == project or target_database is None:
|
||||
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 主 PRJ 的 iCDBDir 必须唯一且为工程内相对路径,不支持绝对路径或多条记录')
|
||||
continue
|
||||
database = (config.parent/values[0]).resolve()
|
||||
if not database.is_relative_to(project.parent.resolve()):
|
||||
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 数据库不在当前工程内')
|
||||
if target_database is None or database == Path(target_database).resolve():
|
||||
matches.append((config, database))
|
||||
if len(matches) != 1:
|
||||
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 诊断数据库未绑定唯一工程 PRJ')
|
||||
return matches[0]
|
||||
|
||||
|
||||
@dataclass
|
||||
class NativeBackupSession:
|
||||
process: object
|
||||
@@ -46,10 +80,18 @@ class NativeBackupSession:
|
||||
library: Path
|
||||
block: str
|
||||
path_lease: object = None
|
||||
mode: str = 'versions'
|
||||
project: Path | None = None
|
||||
database: Path | None = None
|
||||
session_record_path: Path | None = None
|
||||
operation_id: str | None = None
|
||||
|
||||
|
||||
def launch_native_backup(request):
|
||||
project = native_backup_project(request.lmc_file, request.block_name)
|
||||
def launch_native_backup(request, *, mode='versions', target_database=None):
|
||||
from .library_lock import recheck_previous_release
|
||||
from .session_record import register_worker_session
|
||||
from .operation_queue import check_active, native_channel, task_stop, commit_worker_start
|
||||
project, database = native_backup_target(request, mode=mode, target_database=target_database)
|
||||
native_backup_executable(request.mentor_bin)
|
||||
root = Path(request.evidence_dir).resolve()/('native-backup-'+uuid4().hex[:12])
|
||||
library_root = Path(request.lmc_file).resolve().parent
|
||||
@@ -57,17 +99,55 @@ def launch_native_backup(request):
|
||||
raise ValueError('运行记录目录需位于中心库之外。')
|
||||
root.mkdir(parents=True)
|
||||
job = root/'request.json'
|
||||
job.write_text(json.dumps({'library': str(request.lmc_file), 'block': request.block_name,
|
||||
'project': str(project), 'mentor_bin': request.mentor_bin}, ensure_ascii=False), 'utf-8')
|
||||
recheck_previous_release(request.lmc_file, root/'previous-release',
|
||||
block_name=request.block_name, stop=task_stop(None))
|
||||
record = {'library': str(request.lmc_file), 'block': request.block_name,
|
||||
'project': str(project), 'database': str(database), 'mode': mode,
|
||||
'project_sha256': hashlib.sha256(project.read_bytes()).hexdigest(),
|
||||
'target_database': str(target_database) if target_database is not None else None,
|
||||
'mentor_bin': request.mentor_bin, 'automatic_repair': False,
|
||||
'operation': 'native_backup', 'operation_id': root.name,
|
||||
'session_record_path': str(root/'session.json'), 'start_gate': str(root/'start-worker.signal'),
|
||||
'start_gate_protocol': 'event-v1',
|
||||
'cancel_signal': str(root/'cancel-worker.signal'), 'supervisor_pid': os.getpid(), 'desktop': None}
|
||||
job.write_text(json.dumps(record, ensure_ascii=False), 'utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify'])+['--native-backup-worker', str(job)]
|
||||
process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name)
|
||||
try:
|
||||
check_active()
|
||||
process = subprocess.Popen(command, creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
register_worker_session(process, record)
|
||||
with native_channel():
|
||||
check_active()
|
||||
commit_worker_start(process, record)
|
||||
except BaseException:
|
||||
Path(record['cancel_signal']).touch() # The unadmitted child exits without native launch.
|
||||
raise
|
||||
return NativeBackupSession(process, job, Path(request.lmc_file), request.block_name,
|
||||
mode=mode, project=project, database=database, session_record_path=Path(record['session_record_path']),
|
||||
operation_id=record['operation_id'])
|
||||
|
||||
|
||||
class _BackupJobWriter:
|
||||
"""Independent Job handle keeps future descendants inside the writer boundary."""
|
||||
def __init__(self, job):
|
||||
import win32api, win32con
|
||||
current = win32api.GetCurrentProcess()
|
||||
self.job = win32api.DuplicateHandle(current, job, current, 0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||
|
||||
def poll(self):
|
||||
import win32job
|
||||
if self.job is None:
|
||||
return 0
|
||||
if win32job.QueryInformationJobObject(self.job, win32job.JobObjectBasicProcessIdList):
|
||||
return None
|
||||
self.job.Close(); self.job = None
|
||||
return 0
|
||||
|
||||
|
||||
class _NativeBackupProcess:
|
||||
"""Track this visible tool and its descendants without killing on close."""
|
||||
def __init__(self, command, cwd):
|
||||
def __init__(self, command, cwd, *, before_resume=None):
|
||||
import win32con, win32job, win32process
|
||||
self.job = win32job.CreateJobObject(None, '')
|
||||
startup = win32process.STARTUPINFO()
|
||||
@@ -80,6 +160,8 @@ class _NativeBackupProcess:
|
||||
raise
|
||||
try:
|
||||
win32job.AssignProcessToJobObject(self.job, self.handle)
|
||||
if before_resume is not None:
|
||||
before_resume(self)
|
||||
win32process.ResumeThread(thread)
|
||||
except Exception:
|
||||
# No native code has run while suspended; there can be no DB write.
|
||||
@@ -102,11 +184,54 @@ class _NativeBackupProcess:
|
||||
self.handle.Close(); self.job.Close()
|
||||
|
||||
|
||||
def run_native_backup_worker(job, *, admission_state=None):
|
||||
"""Publish admission refusal only when this exact worker never entered native work."""
|
||||
from .desktop_worker import run_native_worker
|
||||
from .management import _write_json
|
||||
from .session_record import IDENTITY_KEYS, process_identity, read_session_record
|
||||
job = Path(job)
|
||||
entered = False
|
||||
request = json.loads(job.read_text('utf-8'))
|
||||
identity = process_identity(os.getpid())
|
||||
def registered():
|
||||
try:
|
||||
path = Path(request['session_record_path'])
|
||||
session = read_session_record(path, evidence_root=job.parent)
|
||||
return (session['operation_id'] == request['operation_id']
|
||||
and session.get('operation') == 'native_backup'
|
||||
and session.get('library') == request['library'] and session.get('block') == request['block']
|
||||
and request.get('project') in session.get('resource_scope', {}).get('projects', ())
|
||||
and any(all(process.get(key) == identity[key] for key in IDENTITY_KEYS)
|
||||
for process in session.get('processes', ()) if process.get('role') == 'worker'))
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
return False # Unknown registration never establishes a safe terminal result.
|
||||
def execute(path):
|
||||
nonlocal entered
|
||||
if not registered():
|
||||
raise ValueError('NATIVE_BACKUP_ADMISSION_UNCONFIRMED: 当前工程与工作进程未登记')
|
||||
entered = True
|
||||
return native_backup_worker_main(path)
|
||||
try:
|
||||
return run_native_worker(execute, job, admission_state=admission_state)
|
||||
except Exception as error:
|
||||
bound = registered()
|
||||
_write_json(job.with_name('result.json'), {'status': 'FAILED', 'detail': str(error),
|
||||
'operation_id': request.get('operation_id'), 'worker_identity': identity,
|
||||
'library': request.get('library'), 'block': request.get('block'),
|
||||
'mode': request.get('mode', 'versions'), 'project': request.get('project'),
|
||||
'database': request.get('database'), 'worker_entered': entered,
|
||||
'native_started': None if entered else False,
|
||||
'safe_to_continue': bound and not entered, 'restore_confirmed': False,
|
||||
'repair_confirmed': False, 'validation_passed': False, 'automatic_repair': False})
|
||||
return 1
|
||||
|
||||
|
||||
def native_backup_worker_main(job, *, process_factory=None):
|
||||
from .library_lock import LibraryLock
|
||||
from .management import _write_json
|
||||
job = Path(job)
|
||||
result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False}
|
||||
result = {'status': 'FAILED', 'safe_to_continue': True, 'restore_confirmed': False,
|
||||
'repair_confirmed': False, 'validation_passed': False, 'automatic_repair': False}
|
||||
native = None
|
||||
def write_evidence(name, value):
|
||||
try:
|
||||
@@ -117,14 +242,34 @@ def native_backup_worker_main(job, *, process_factory=None):
|
||||
try:
|
||||
record = json.loads(job.read_text('utf-8'))
|
||||
library, block = Path(record['library']), record['block']
|
||||
result.update(library=str(library), block=block)
|
||||
project = native_backup_project(library, block)
|
||||
result.update(library=str(library), block=block, operation_id=record.get('operation_id'))
|
||||
from types import SimpleNamespace
|
||||
mode = record.get('mode', 'versions')
|
||||
project, database = native_backup_target(SimpleNamespace(lmc_file=library, block_name=block),
|
||||
mode=mode, target_database=record.get('target_database'))
|
||||
if project != Path(record['project']):
|
||||
raise ValueError('工程身份已变化,未打开原生工具。')
|
||||
if record.get('project_sha256') and hashlib.sha256(project.read_bytes()).hexdigest() != record['project_sha256']:
|
||||
raise ValueError('工程内容身份已变化,未打开原生工具。')
|
||||
if record.get('database') and database != Path(record['database']):
|
||||
raise ValueError('数据库身份已变化,未打开原生工具。')
|
||||
result.update(mode=mode, project=str(project), database=str(database),
|
||||
session_record_path=record.get('session_record_path'))
|
||||
executable = native_backup_executable(record.get('mentor_bin', ''))
|
||||
released = True
|
||||
with LibraryLock(library, checkpoint=False, safe_to_release=lambda: released):
|
||||
native = (process_factory or _NativeBackupProcess)([str(executable), '-p', str(project)], project.parent)
|
||||
with LibraryLock(library, checkpoint=bool(record.get('session_record_path')),
|
||||
block_name=block, safe_to_release=lambda: released):
|
||||
from .maintenance_entry import _assert_native_idle_for
|
||||
_assert_native_idle_for(SimpleNamespace(project=project, database=database, library=library))
|
||||
def admitted(process):
|
||||
from .session_record import update_worker_state
|
||||
from .desktop_worker import register_native_writer
|
||||
if record.get('session_record_path'):
|
||||
update_worker_state(record, 'NATIVE_CALL', identities=(('native', process.pid),), required=True)
|
||||
register_native_writer(_BackupJobWriter(process.job))
|
||||
command = [str(executable), '-p', str(project)] # User alone invokes Repair in the official UI.
|
||||
native = (process_factory(command, project.parent) if process_factory else
|
||||
_NativeBackupProcess(command, project.parent, before_resume=admitted))
|
||||
released = False
|
||||
result.update(status='OPEN', native_pid=native.pid, project=str(project), safe_to_continue=False)
|
||||
write_evidence('state.json', result)
|
||||
@@ -145,6 +290,7 @@ def native_backup_worker_main(job, *, process_factory=None):
|
||||
time.sleep(.25)
|
||||
released = True
|
||||
result.update(status='CLOSED', native_exit_code=exit_code, safe_to_continue=True)
|
||||
result['release'] = {'native_exited': True, 'remaining_pids': [], 'safe_to_continue': True}
|
||||
return 0 if result['native_exit_code'] == 0 else 1
|
||||
except Exception as error:
|
||||
result.update(status='FAILED', detail=str(error), safe_to_continue=native is None)
|
||||
|
||||
@@ -79,7 +79,7 @@ def assert_retained_exports_idle(library=None):
|
||||
|
||||
|
||||
def begin_export_analysis(library, root, project):
|
||||
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
|
||||
from .library_lock import LibraryLock, _library_guard, blocker_path, checkpoint_record, LibraryBusy
|
||||
from .management_transaction import current_lease
|
||||
library, root, project = Path(library).resolve(), Path(root).resolve(), Path(project).resolve()
|
||||
owner = current_lease(library)
|
||||
@@ -89,7 +89,7 @@ def begin_export_analysis(library, root, project):
|
||||
record = {'protocol': 'cbb-native-export-analysis', 'version': 1, 'token': uuid4().hex,
|
||||
'library': str(library), 'lease_id': owner['lease_id'], 'supervisor_pid': owner['supervisor_pid'],
|
||||
'analysis_root': str(root), 'project': str(project)}
|
||||
with _guard:
|
||||
with _library_guard(LibraryLock(library).key):
|
||||
marker = blocker_path(library)
|
||||
checkpoint = checkpoint_record(marker)
|
||||
if (checkpoint is None or checkpoint['lease_id'] != owner['lease_id']
|
||||
@@ -100,6 +100,77 @@ def begin_export_analysis(library, root, project):
|
||||
return record['token']
|
||||
|
||||
|
||||
def _external_export_library(process):
|
||||
"""Recover a live copy's owner; an outside path alone proves no association."""
|
||||
import ntpath
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
from .failed_session import _command_args
|
||||
from .backup_recovery import _native_scope_match
|
||||
from .native_engineering_identity import _process_birth
|
||||
def read(path):
|
||||
info = path.lstat()
|
||||
if info.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT or info.st_size > 1024*1024:
|
||||
raise ValueError('Untrusted export association')
|
||||
value = json.loads(path.read_text('utf-8'))
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError('Invalid export association')
|
||||
return value
|
||||
try:
|
||||
birth = _process_birth(process.get('created'))
|
||||
image = process.get('executable')
|
||||
if birth is None or not image or ntpath.basename(image).casefold() != process['name'].casefold():
|
||||
return None
|
||||
candidates = []
|
||||
for arg in _command_args(process.get('command', ''))[1:]:
|
||||
path = Path(arg.split('=', 1)[-1])
|
||||
if path.is_absolute() and (path.suffix.casefold() in ('.prj', '.pcb')
|
||||
or path.name.casefold() in ('database', 'icdb.dat')):
|
||||
candidates.append(path)
|
||||
associations = set()
|
||||
for path in candidates:
|
||||
project_root = next((p for p in (path, *path.parents) if p.name.casefold() == 'project'), None)
|
||||
if project_root is None or project_root.resolve() != project_root:
|
||||
return None
|
||||
root = project_root.parent
|
||||
owner = read(root/'export-owner.json')
|
||||
project, library = Path(owner['project']), Path(owner['library'])
|
||||
if (owner.get('protocol') != 'cbb-native-export-analysis' or owner.get('version') != 1
|
||||
or not re.fullmatch('[0-9a-f]{32}', str(owner.get('token', '')))
|
||||
or not re.fullmatch('[0-9a-f]{32}', str(owner.get('lease_id', '')))
|
||||
or type(owner.get('supervisor_pid')) is not int or owner['supervisor_pid'] <= 0
|
||||
or Path(owner['analysis_root']) != root or project.parent != project_root
|
||||
or project.suffix.casefold() != '.prj' or not project.is_file()
|
||||
or not library.is_absolute() or library.suffix.casefold() != '.lmc' or not library.is_file()
|
||||
or root.is_relative_to(library.parent) or library.parent.is_relative_to(root)
|
||||
or _native_scope_match(process['command'], roots=(project_root,)) is not True):
|
||||
return None
|
||||
matched = False
|
||||
for kind, executable in (('ascii', 'icdb2ascii.exe'), ('csv', 'icdb2csv.exe'), ('edif', 'edifexporter.exe')):
|
||||
evidence = root/(kind+'-process.json')
|
||||
if not evidence.exists():
|
||||
continue
|
||||
recorded = read(evidence)
|
||||
command = recorded.get('command')
|
||||
if (recorded.get('native_started') is not True or recorded.get('kind') != kind
|
||||
or not isinstance(command, list) or not command or not all(isinstance(v, str) for v in command)
|
||||
or ntpath.basename(command[0]).casefold() != executable
|
||||
or _native_scope_match(subprocess.list2cmdline(command), roots=(project_root,)) is not True):
|
||||
continue
|
||||
for identity in recorded.get('process_identities', []):
|
||||
if (identity.get('pid') == process['pid'] and _process_birth(identity.get('created')) == birth
|
||||
and identity.get('executable')
|
||||
and ntpath.normcase(identity['executable']) == ntpath.normcase(image)):
|
||||
matched = True
|
||||
if not matched:
|
||||
return None
|
||||
associations.add(library.resolve())
|
||||
return next(iter(associations)) if len(associations) == 1 else None
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError):
|
||||
return None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, unstarted_token=''):
|
||||
"""Fresh process and exclusive-copy proof, including after interpreter exit."""
|
||||
@@ -116,9 +187,12 @@ def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, uns
|
||||
raise LibraryBusy('Invalid library checkpoint cannot release export ownership.')
|
||||
# Only the explicit release path supplies full-library/native proof and
|
||||
# archives the unchanged metadata while its coordination handle is held.
|
||||
assert_retained_exports_idle()
|
||||
if any(p['name'].casefold() in _OWNER_NAMES for p in _process_snapshot()):
|
||||
raise LibraryBusy('Unknown export checkpoint still has a possible native identity owner.')
|
||||
for process in _process_snapshot():
|
||||
if process['name'].casefold() not in _OWNER_NAMES:
|
||||
continue
|
||||
associated_library = _external_export_library(process)
|
||||
if associated_library is None or associated_library == library:
|
||||
raise LibraryBusy('Unknown export checkpoint still has a possible native identity owner.')
|
||||
yield []
|
||||
return
|
||||
if checkpoint is None or 'export_analysis' not in checkpoint:
|
||||
@@ -208,8 +282,8 @@ def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, uns
|
||||
|
||||
|
||||
def finish_export_analysis(library, token, *, native_not_started=False):
|
||||
from .library_lock import _guard, blocker_path, checkpoint_record, LibraryBusy
|
||||
with _guard, prove_export_copies_released(library,
|
||||
from .library_lock import LibraryLock, _library_guard, blocker_path, checkpoint_record, LibraryBusy
|
||||
with _library_guard(LibraryLock(library).key), prove_export_copies_released(library,
|
||||
unstarted_token=token if native_not_started else ''):
|
||||
marker = blocker_path(library)
|
||||
checkpoint = checkpoint_record(marker)
|
||||
|
||||
@@ -53,9 +53,10 @@ def removal_output_ok(code, output, name, partition):
|
||||
+ r"' from partition '" + re.escape(partition) + r"'\.", output) is not None)
|
||||
|
||||
|
||||
def catalog_dialog_action(title, text):
|
||||
def catalog_dialog_action(title, text, *, read_only=False):
|
||||
value = (title + '\n' + text).casefold()
|
||||
if ('this central library must be updated' in value or 'select flow type' in value):
|
||||
if ('this central library must be updated' in value or 'select flow type' in value
|
||||
or read_only and ('save' in value or 'upgrade' in value)):
|
||||
return 'cancel'
|
||||
return 'observe'
|
||||
|
||||
@@ -222,6 +223,7 @@ class NativeManagementAdapter:
|
||||
from .session_record import process_identity
|
||||
job = {**job, 'cancel_signal': str(evidence/'cancel-management.signal'),
|
||||
'start_gate': str(evidence/'start-management.signal'),
|
||||
'start_gate_protocol': 'event-v1',
|
||||
'session_record_path': str(evidence/'session.json'), 'operation_id': uuid4().hex,
|
||||
'supervisor_pid': os.getpid(), 'supervisor_identity': process_identity(os.getpid()),
|
||||
'block': job.get('name')}
|
||||
@@ -242,12 +244,17 @@ class NativeManagementAdapter:
|
||||
worker.bind_cancellation(job['cancel_signal'])
|
||||
if hasattr(worker, 'bind_session'):
|
||||
worker.bind_session(job)
|
||||
Path(job['start_gate']).touch()
|
||||
while worker.poll() is None and time.monotonic() < deadline:
|
||||
if self.stop is not None and self.stop.is_set():
|
||||
Path(job['cancel_signal']).touch()
|
||||
break
|
||||
time.sleep(.1)
|
||||
from contextlib import nullcontext
|
||||
from .operation_queue import commit_worker_start, native_channel
|
||||
# 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()
|
||||
with channel:
|
||||
commit_worker_start(worker, job)
|
||||
while worker.poll() is None and time.monotonic() < deadline:
|
||||
if self.stop is not None and self.stop.is_set():
|
||||
Path(job['cancel_signal']).touch()
|
||||
break
|
||||
time.sleep(.1)
|
||||
if worker.poll() is None:
|
||||
# DesktopWorker.close() requests a kill without a cancellation file.
|
||||
# Keep this exact worker alive until its native call returns normally.
|
||||
@@ -275,7 +282,8 @@ class NativeManagementAdapter:
|
||||
worker.close()
|
||||
|
||||
def catalog(self, library, evidence):
|
||||
result = self._worker({'operation': 'catalog', 'library': str(absolute_preserving_drive(library))}, evidence)
|
||||
result = self._worker({'operation': 'catalog', 'worker_role': 'catalog_readonly',
|
||||
'library': str(absolute_preserving_drive(library))}, evidence)
|
||||
if not result.get('success') or not result.get('safe_to_continue'):
|
||||
raise NativeOperationError(result.get('detail', '原生目录复读未确认,禁止文件夹回退。'),
|
||||
safe_to_continue=result.get('safe_to_continue') is True)
|
||||
@@ -300,12 +308,31 @@ class NativeManagementAdapter:
|
||||
removal_input(request.name, request.partition)
|
||||
if request.partition != 'Logical-Physical' or catalog.flow != 1:
|
||||
raise ValueError('仅验证了 DxDesigner / Logical-Physical 管理操作。')
|
||||
self.validate_source(request)
|
||||
|
||||
def validate_source(self, request, *, probe_files=True):
|
||||
if request.operation not in ('add', 'update'):
|
||||
return
|
||||
if request.source is None:
|
||||
raise ValueError('请选择完整来源工程。')
|
||||
source = Path(request.source)
|
||||
if probe_files:
|
||||
source = source.resolve(strict=True)
|
||||
if source.suffix.casefold() != '.prj' or probe_files and not source.is_file():
|
||||
raise ValueError('请选择完整来源工程的 PRJ 文件。')
|
||||
if source.stem.casefold() != request.name.casefold():
|
||||
raise ValueError(f'SOURCE_NAME_MISMATCH: 来源工程名 {source.stem} 与目标 {request.name} 不一致;'
|
||||
'当前版本不支持改名,请重新选择同名 PRJ。')
|
||||
|
||||
def add(self, request, evidence):
|
||||
# Route readiness never grants production mutation authority.
|
||||
capability = self.capabilities()['add']
|
||||
if not capability.supported:
|
||||
return NativeOutcome(False, True, capability.reason, evidence_path=Path(evidence))
|
||||
try:
|
||||
self.validate_source(request)
|
||||
except (OSError, ValueError) as error:
|
||||
return NativeOutcome(False, True, str(error), evidence_path=Path(evidence))
|
||||
return self._add_transaction(request, Path(evidence))
|
||||
|
||||
def prepare_add_transaction(self, request, root, *, original_source):
|
||||
@@ -315,6 +342,7 @@ class NativeManagementAdapter:
|
||||
from .management import source_project
|
||||
from .backup_recovery import _align_library
|
||||
try:
|
||||
self.validate_source(request)
|
||||
if not self.capabilities()['add'].supported:
|
||||
raise ValueError(self.capabilities()['add'].reason)
|
||||
validate_native_copy_paths(request.source, request.library, request.name)
|
||||
@@ -442,6 +470,7 @@ class NativeManagementAdapter:
|
||||
return NativeOutcome(False, True, 'Native Add requires an existing staged PRJ source project.',
|
||||
evidence_path=evidence)
|
||||
try:
|
||||
self.validate_source(request)
|
||||
source_identity = engineering_identity(source)
|
||||
except (ValueError, OSError) as error:
|
||||
return NativeOutcome(False, True, f'Unable to read source engineering identity: {error}',
|
||||
@@ -686,11 +715,11 @@ def _dispatch_diagnostics(root, stage, app, library, *, paths=None):
|
||||
stream.write(json.dumps(record, ensure_ascii=False, default=str) + '\n')
|
||||
|
||||
|
||||
def _set_probe_field(hwnd, control_id, expected, root):
|
||||
"""Set/read a remote Edit with a one-second total message budget."""
|
||||
def _set_probe_field(hwnd, control_id, expected, root, *, read_only=False):
|
||||
"""Set/read or revalidate a remote Edit with a one-second total message budget."""
|
||||
from ctypes import wintypes
|
||||
record = {'control_id': control_id, 'hwnd': int(hwnd), 'expected': expected,
|
||||
'actual': None, 'matched': False}
|
||||
'actual': None, 'matched': False, 'read_only': read_only}
|
||||
deadline = time.monotonic() + 1.0
|
||||
try:
|
||||
user32 = ctypes.WinDLL('user32', use_last_error=True)
|
||||
@@ -707,9 +736,10 @@ def _set_probe_field(hwnd, control_id, expected, root):
|
||||
remaining, ctypes.byref(returned)):
|
||||
raise TimeoutError(f'原生字段消息超时或失败:{control_id}, Windows={ctypes.get_last_error()}')
|
||||
return returned.value
|
||||
text = ctypes.create_unicode_buffer(expected)
|
||||
if not message(0x000C, 0, text): # WM_SETTEXT
|
||||
raise RuntimeError(f'原生字段拒绝写入:{control_id}')
|
||||
if not read_only:
|
||||
text = ctypes.create_unicode_buffer(expected)
|
||||
if not message(0x000C, 0, text): # WM_SETTEXT
|
||||
raise RuntimeError(f'原生字段拒绝写入:{control_id}')
|
||||
buffer = ctypes.create_unicode_buffer(32768)
|
||||
copied = message(0x000D, len(buffer), buffer) # WM_GETTEXT, remote Edit marshalled by Windows.
|
||||
record['actual'] = buffer.value
|
||||
@@ -745,6 +775,9 @@ def _probe_add_dialog(app, job, desktop, owned_pids, root, *, library=None):
|
||||
import gc
|
||||
gc.collect() # Release UIA wrappers before closing native child dialogs.
|
||||
if not job.get('_native_add_pending'):
|
||||
writer = job.pop('_native_add_writer', None)
|
||||
if writer is not None:
|
||||
writer.complete()
|
||||
_close_probe_dialogs(desktop, owned_pids)
|
||||
|
||||
|
||||
@@ -840,6 +873,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
||||
if not hwnd or win32gui.GetClassName(hwnd) != 'Edit':
|
||||
raise RuntimeError(f'原生新增字段身份不匹配:{control}')
|
||||
_set_probe_field(hwnd, control, value, root)
|
||||
# Changing source/top fields can make Mentor derive a different name.
|
||||
for control, value in fields.items():
|
||||
_set_probe_field(win32gui.GetDlgItem(dialog, control), control, value, root, read_only=True)
|
||||
_write_json(root/'submitted-fields.json', fields)
|
||||
ok = win32gui.GetDlgItem(dialog, 1083)
|
||||
if not ok:
|
||||
@@ -851,9 +887,18 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
||||
_require_add_supervisor(job, root)
|
||||
from .session_record import dispatch_native, update_worker_state
|
||||
def submit_add():
|
||||
_require_add_supervisor(job, root) # Registration/journal I/O may have outlived cancellation.
|
||||
job['_native_add_pending'] = True
|
||||
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
|
||||
dispatch_native(job, submit_add, asynchronous=True, required=True)
|
||||
from .desktop_worker import register_pending_native_operation
|
||||
writer = register_pending_native_operation(job, owned_pids)
|
||||
job['_native_add_writer'] = writer
|
||||
try:
|
||||
dispatch_native(job, submit_add, asynchronous=True, required=True)
|
||||
except Exception:
|
||||
if not job.get('_native_add_pending'):
|
||||
writer.complete()
|
||||
raise
|
||||
success = None
|
||||
while time.monotonic() < deadline:
|
||||
pythoncom.PumpWaitingMessages()
|
||||
@@ -884,6 +929,7 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
|
||||
if not success:
|
||||
raise TimeoutError('未取得原生新增成功消息;保留副本与私有桌面证据。')
|
||||
job['_native_add_pending'] = False
|
||||
writer.complete()
|
||||
update_worker_state(job, 'POSTCALL')
|
||||
|
||||
|
||||
@@ -1056,6 +1102,8 @@ def _catalog_native(job, root):
|
||||
|
||||
|
||||
def _catalog_com(job, root):
|
||||
if job.get('worker_role') == 'catalog_readonly' and job.get('operation') != 'catalog':
|
||||
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||
import pythoncom, win32com.client, win32con, win32gui, win32process
|
||||
from .mentor_adapter import _process_details
|
||||
try:
|
||||
@@ -1089,7 +1137,7 @@ def _catalog_com(job, root):
|
||||
win32gui.EnumChildWindows(hwnd, lambda child, _: children.append(child), None)
|
||||
title = win32gui.GetWindowText(hwnd)
|
||||
text = '\n'.join(win32gui.GetWindowText(child) for child in children)
|
||||
if catalog_dialog_action(title, text) == 'cancel':
|
||||
if catalog_dialog_action(title, text, read_only=job.get('worker_role') == 'catalog_readonly') == 'cancel':
|
||||
if hwnd not in observed:
|
||||
observed.append(hwnd)
|
||||
refused.append({'title': title, 'text': text})
|
||||
@@ -1223,11 +1271,23 @@ def _catalog_com(job, root):
|
||||
return result
|
||||
|
||||
|
||||
def management_worker_main(request_path):
|
||||
def catalog_worker_main(request_path):
|
||||
"""A catalog-only entry: never allow this read role to select a write branch."""
|
||||
job = json.loads(Path(request_path).read_text(encoding='utf-8'))
|
||||
if job.get('operation') != 'catalog' or job.get('worker_role') != 'catalog_readonly':
|
||||
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||
return management_worker_main(request_path, catalog_readonly=True)
|
||||
|
||||
|
||||
def management_worker_main(request_path, *, catalog_readonly=False):
|
||||
"""Internal worker. Desktop identity and capability gates are rechecked here."""
|
||||
request_path = Path(request_path)
|
||||
root = request_path.parent
|
||||
job = json.loads(request_path.read_text(encoding='utf-8'))
|
||||
if job.get('worker_role') == 'catalog_readonly' and not catalog_readonly:
|
||||
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||
if catalog_readonly and (job.get('operation') != 'catalog' or job.get('worker_role') != 'catalog_readonly'):
|
||||
raise RuntimeError('WORKER_READONLY_ROLE_MISMATCH')
|
||||
result = {'success': False, 'safe_to_continue': True}
|
||||
try:
|
||||
_, desktop = _current_desktop()
|
||||
@@ -1285,6 +1345,8 @@ def management_worker_main(request_path):
|
||||
except (FileNotFoundError, PermissionError):
|
||||
result['safe_to_continue'] = True
|
||||
raise
|
||||
from .desktop_worker import register_native_writer
|
||||
register_native_writer(process)
|
||||
update_worker_state(job, 'NATIVE_CALL', identities=[('native', process.pid)], continuation=True)
|
||||
try:
|
||||
_write_json(root/'native-process.json', {'pid': process.pid, 'command': command})
|
||||
|
||||
@@ -264,21 +264,44 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
||||
job_path = root/'repair-request.json'
|
||||
cancel = root/'cancel-repair.signal'
|
||||
desktop = 'CbbRepair_'+uuid4().hex[:12]
|
||||
job_path.write_text(json.dumps({'project': str(target.project), 'database': str(target.database),
|
||||
from .operation_queue import current_context
|
||||
context = current_context()
|
||||
library = (maintenance_context or {}).get('library') or (context.library if context else str(target.project))
|
||||
job = {'project': str(target.project), 'database': str(target.database),
|
||||
'root': str(root), 'mentor_bin': str(mentor_bin or ''), 'timeout': timeout_seconds,
|
||||
'cancel_signal': str(cancel), 'supervisor_pid': os.getpid(), 'desktop': desktop,
|
||||
'maintenance_context': maintenance_context, 'inspection_only': inspection_only},
|
||||
ensure_ascii=False), encoding='utf-8')
|
||||
'maintenance_context': maintenance_context, 'inspection_only': inspection_only,
|
||||
'library': library, 'operation_id': root.name+'-'+uuid4().hex[:8],
|
||||
'operation': 'inspect' if inspection_only else 'repair',
|
||||
'block': (maintenance_context or {}).get('block'),
|
||||
'session_record_path': str(root/'session.json'), 'start_gate': str(root/'start-repair.signal')}
|
||||
job['start_gate_protocol'] = 'event-v1'
|
||||
job_path.write_text(json.dumps(job, ensure_ascii=False), encoding='utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--repair-worker', str(job_path)]
|
||||
from .operation_queue import task_stop
|
||||
return _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress, task_stop(stop), job)
|
||||
|
||||
|
||||
def _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress, stop, job):
|
||||
from .desktop_worker import DesktopWorker
|
||||
worker = DesktopWorker(command, desktop)
|
||||
worker.bind_cancellation(cancel)
|
||||
from .operation_queue import check_active, native_channel, commit_worker_start
|
||||
native = native_channel(inspection_only=job.get('inspection_only') is True)
|
||||
entered = False
|
||||
# Worker admission includes filesystem/ownership checks before the native
|
||||
# timeout begins. Bound that preparation separately; never extend on polls.
|
||||
deadline = time.monotonic()+60+max(1, float(timeout_seconds))+5
|
||||
event_count = 0
|
||||
cancelled = False
|
||||
try:
|
||||
if hasattr(worker, 'bind_session'):
|
||||
worker.bind_session(job)
|
||||
check_active()
|
||||
native.__enter__()
|
||||
entered = True
|
||||
commit_worker_start(worker, job)
|
||||
while worker.poll() is None and time.monotonic()<deadline:
|
||||
if not cancelled and stop is not None and stop.is_set():
|
||||
worker.request_stop()
|
||||
@@ -294,6 +317,9 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
||||
break
|
||||
event_count += 1
|
||||
time.sleep(.2)
|
||||
if worker.poll() is not None:
|
||||
native.__exit__(None, None, None)
|
||||
entered = False
|
||||
outcome = root/'repair-result.json'
|
||||
if worker.poll() is None or not outcome.is_file():
|
||||
worker.request_stop()
|
||||
@@ -306,5 +332,17 @@ def run_native_repair(target, root, *, mentor_bin='', timeout_seconds=300, progr
|
||||
if worker.returncode != 0 and result.get('status') in ('REPAIRED', 'NOT_IN_USE', 'IN_USE'):
|
||||
result['status'] = 'UNCONFIRMED'
|
||||
return {**result, 'evidence_path': str(root)}
|
||||
except BaseException:
|
||||
worker.request_stop()
|
||||
raise
|
||||
finally:
|
||||
worker.close()
|
||||
try:
|
||||
if entered:
|
||||
native.__exit__(None, None, None)
|
||||
if worker.poll() is None and getattr(worker, 'session_record_path', None):
|
||||
from .session_record import handoff_session
|
||||
from .operation_queue import hold_native_handoff
|
||||
handoff_session(worker.session_record_path, evidence_root=root, process=worker)
|
||||
hold_native_handoff(worker, worker.session_record_path)
|
||||
finally:
|
||||
worker.close()
|
||||
@@ -192,6 +192,10 @@ def _inspect_project(job, process, emit):
|
||||
result = {'status': 'UNCONFIRMED', 'project': str(project), 'database': str(database),
|
||||
'native_pid': process.pid, 'inspection_only': True, 'repair_requested': False,
|
||||
'repair_required': False, 'output': ''}
|
||||
if getattr(process, '_handle', None) is not None:
|
||||
from .residual_sessions import _handle_identity, _force_ownership
|
||||
result['native_identity'] = dict(pid=process.pid,
|
||||
**_handle_identity(process._handle), **_force_ownership(process._handle, process.pid))
|
||||
deadline = time.monotonic() + max(1, float(job['timeout']))
|
||||
closing = False
|
||||
last_state = None
|
||||
@@ -335,6 +339,8 @@ def repair_worker_main(job_path):
|
||||
if Path(job['cancel_signal']).exists():
|
||||
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
|
||||
process = subprocess.Popen([str(executable), '-p', str(project)], cwd=str(project.parent))
|
||||
from .desktop_worker import register_native_writer
|
||||
register_native_writer(process)
|
||||
result['native_started'] = True
|
||||
result['native_pid'] = process.pid
|
||||
emit(stage='native_started', pid=process.pid, project=str(project))
|
||||
|
||||
@@ -2,10 +2,19 @@
|
||||
from collections.abc import Sequence
|
||||
|
||||
|
||||
def recheck_failed_release(library, block, result):
|
||||
def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds=10):
|
||||
"""Refresh resource facts after a late exit; keep the original business failure."""
|
||||
if result.safe_to_continue or not result.evidence_path:
|
||||
return result
|
||||
from .operation_queue import BatchTaskContext, QueueCancelled, current_context, task_stop
|
||||
if current_context() is None:
|
||||
context = BatchTaskContext(library=str(library), targets=(block,))
|
||||
try:
|
||||
return context.run(lambda: recheck_failed_release(library, block, result, stop=stop),
|
||||
stop=stop, timeout_seconds=timeout_seconds)
|
||||
except QueueCancelled:
|
||||
return result
|
||||
stop = task_stop(stop)
|
||||
from pathlib import Path
|
||||
from dataclasses import replace
|
||||
import json
|
||||
@@ -19,7 +28,10 @@ def recheck_failed_release(library, block, result):
|
||||
if record.get('block') != block or Path(record.get('library', '')).resolve() != Path(library).resolve():
|
||||
return result
|
||||
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:
|
||||
record = json.loads(evidence.read_text('utf-8'))
|
||||
if (record.get('name') != block or record.get('operation') not in ('add', 'update', 'remove')
|
||||
@@ -33,18 +45,36 @@ def recheck_failed_release(library, block, result):
|
||||
if Path(owned.get('library', '')).resolve() != Path(library).resolve():
|
||||
return result
|
||||
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)
|
||||
if not bound:
|
||||
return result # A generic timeout without a bound owner is not an exit fact.
|
||||
proof = release_retained_library(library, evidence.parent/'late-release', block_name=block)
|
||||
if proof.get('status') != 'RELEASE_CONFIRMED' or Path(proof.get('library', '')).resolve() != Path(library).resolve():
|
||||
from .operation_queue import check_active
|
||||
check_active()
|
||||
proof = release_retained_library(library, evidence.parent/'late-release', block_name=block, stop=stop)
|
||||
scope = proof.get('resource_scope')
|
||||
if (proof.get('status') != 'RELEASE_CONFIRMED' or proof.get('lease_state') != 'RELEASED'
|
||||
or not isinstance(scope, dict) or scope.get('scope_state') != 'OBSERVED'
|
||||
or proof.get('blocked_resources') != []
|
||||
or Path(proof.get('library', '')).resolve() != Path(library).resolve()):
|
||||
return result
|
||||
check_active()
|
||||
evidence.with_name('late-release-result.json').write_text(json.dumps(dict(
|
||||
business_status=result.status, safe_to_continue=True, release_proof=proof),
|
||||
ensure_ascii=False, default=str, indent=2), 'utf-8')
|
||||
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
|
||||
|
||||
|
||||
|
||||
@@ -1,36 +1,464 @@
|
||||
"""Cooperative FIFO admission for this application's native operations."""
|
||||
from threading import Condition
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
import ntpath
|
||||
from threading import Condition, Event, RLock, Thread, local
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
class QueueCancelled(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class QueueUnavailable(RuntimeError):
|
||||
"""Admission failed before action dispatch; this task created no native session."""
|
||||
def __init__(self, library):
|
||||
self.library = str(library)
|
||||
super().__init__('NATIVE_SESSION_PENDING: '+self.library+
|
||||
' 的已登记会话仍在运行或初始化,当前项未启动。')
|
||||
|
||||
|
||||
class TaskHandoff(QueueCancelled):
|
||||
"""The call is still observable; this is never a release receipt."""
|
||||
def __init__(self, context, *, cancelled=False, result=None):
|
||||
self.operation_id = context.operation_id
|
||||
self.library = context.library
|
||||
self.cancelled = cancelled
|
||||
self.scope = context.scope
|
||||
self.result = result
|
||||
super().__init__('已交给后台观察;当前资源尚未确认释放。')
|
||||
|
||||
|
||||
class _StopSignal:
|
||||
def __init__(self):
|
||||
self._event = Event()
|
||||
|
||||
def set(self):
|
||||
with _tasks_guard:
|
||||
self._event.set()
|
||||
|
||||
def is_set(self):
|
||||
return self._event.is_set()
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return self._event.wait(timeout)
|
||||
|
||||
|
||||
_local = local()
|
||||
_tasks_guard = RLock()
|
||||
_calls = {}
|
||||
|
||||
|
||||
def _path_key(path):
|
||||
# Identity was bound by the caller; queue predicates must never resolve a share.
|
||||
return ntpath.normcase(ntpath.normpath(str(path)))
|
||||
|
||||
|
||||
def request_library_keys(request, context=None):
|
||||
library = str(getattr(request, 'lmc_file', getattr(request, 'library', '__injected_verifier_scope__')))
|
||||
keys = {_path_key(library)}
|
||||
drive, remote = getattr(request, 'mapped_drive', ''), getattr(request, 'mapped_remote_root', '')
|
||||
if drive and remote and ntpath.splitdrive(library)[0].casefold() == drive.rstrip('\\/').casefold():
|
||||
keys.add(_path_key(ntpath.join(remote, ntpath.splitdrive(library)[1].lstrip('\\/'))))
|
||||
if context is not None:
|
||||
aliases = {_path_key(v) for v in (context.library, *context.aliases)}
|
||||
if keys.intersection(aliases):
|
||||
keys.update(aliases)
|
||||
return keys
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class _Call:
|
||||
context: object
|
||||
external_stop: object = None
|
||||
metadata_only: bool = False
|
||||
done: Event = field(default_factory=Event)
|
||||
abandoned: bool = False
|
||||
native_depth: int = 0
|
||||
commit_depth: int = 0
|
||||
readonly_depth: int = 0
|
||||
supervised_depth: int = 0
|
||||
worker_sessions: list = field(default_factory=list)
|
||||
shutdown_handoff: bool = False
|
||||
native_handoff: str = ''
|
||||
handoff_cancelled: bool = False
|
||||
phase_started: float = field(default_factory=time.monotonic)
|
||||
result: object = None
|
||||
last_result: object = None
|
||||
error: BaseException | None = None
|
||||
|
||||
def is_set(self):
|
||||
return (self.abandoned or self.context.stop.is_set()
|
||||
or self.external_stop is not None and self.external_stop.is_set())
|
||||
|
||||
|
||||
def current_context():
|
||||
call = getattr(_local, 'call', None)
|
||||
return call.context if call is not None else None
|
||||
|
||||
|
||||
def task_stop(fallback=None):
|
||||
return getattr(_local, 'call', None) or fallback
|
||||
|
||||
|
||||
def check_active():
|
||||
call = getattr(_local, 'call', None)
|
||||
if call is not None and call.is_set():
|
||||
raise QueueCancelled('任务已取消,未提交新的原生操作。')
|
||||
|
||||
|
||||
def note_metadata_progress():
|
||||
"""Renew inactivity only after completed I/O; never revive an abandoned call."""
|
||||
call = getattr(_local, 'call', None)
|
||||
if call is not None:
|
||||
with _tasks_guard:
|
||||
if not call.native_depth:
|
||||
check_active()
|
||||
call.phase_started = time.monotonic()
|
||||
|
||||
|
||||
def remember_result(result):
|
||||
call = getattr(_local, 'call', None)
|
||||
if call is not None:
|
||||
with _tasks_guard:
|
||||
call.last_result = result
|
||||
return result
|
||||
|
||||
|
||||
def bind_supervised_worker(path, record):
|
||||
"""Called only after the common launcher has durably registered its worker."""
|
||||
call = getattr(_local, 'call', None)
|
||||
if call is not None:
|
||||
with _tasks_guard:
|
||||
call.worker_sessions.append(dict(path=str(path), operation_id=record['operation_id'],
|
||||
processes=record['processes'], worker_lease_handle=record.get('worker_lease_handle'),
|
||||
worker_protection=record.get('worker_protection'), resource_scope=record.get('resource_scope')))
|
||||
|
||||
|
||||
def check_worker_admission(job):
|
||||
check_active()
|
||||
call = getattr(_local, 'call', None)
|
||||
if (call is not None and call.readonly_depth and job.get('inspection_only') is not True
|
||||
and not (job.get('operation') == 'catalog' and job.get('worker_role') == 'catalog_readonly')):
|
||||
raise RuntimeError('NATIVE_ROLE_REQUIRED: 只读观察不能启动原生写入进程。')
|
||||
|
||||
|
||||
def commit_worker_start(worker, job):
|
||||
"""Prepare evidence outside the shutdown fence; only SetEvent grants admission."""
|
||||
from pathlib import Path
|
||||
import win32event
|
||||
try:
|
||||
check_worker_admission(job)
|
||||
event = getattr(worker, '_start_event', None)
|
||||
context = current_context()
|
||||
if context is not None and context.native_policy == 'external' and event is None:
|
||||
raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少已登记的启动事件。')
|
||||
if event is not None and worker._start_binding != (
|
||||
str(job['session_record_path']), job['operation_id'], job['start_gate']):
|
||||
raise RuntimeError('WORKER_ADMISSION_IDENTITY_CHANGED')
|
||||
Path(job['start_gate']).touch()
|
||||
with _tasks_guard:
|
||||
check_worker_admission(job)
|
||||
if event is not None:
|
||||
win32event.SetEvent(event)
|
||||
except BaseException:
|
||||
# A stalled evidence volume cannot delay shutdown or grant admission.
|
||||
if job.get('cancel_signal'):
|
||||
Path(job['cancel_signal']).touch()
|
||||
raise
|
||||
|
||||
|
||||
def hold_native_handoff(process, session_record_path):
|
||||
"""Yield parent admission to controls; the gated worker retains write exclusion.
|
||||
|
||||
The caller registers the exact worker observer first. Its writer barrier and
|
||||
inherited sidecar survive this supervisor, including while a user answers Save.
|
||||
"""
|
||||
call = getattr(_local, 'call', None)
|
||||
if call is not None:
|
||||
with _tasks_guard:
|
||||
call.handoff_cancelled = call.is_set()
|
||||
call.native_handoff = str(session_record_path)
|
||||
call.abandoned = True
|
||||
raise TaskHandoff(call.context, cancelled=call.handoff_cancelled, result=call.last_result)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def local_commit():
|
||||
"""Finish an admitted filesystem rename/rollback without native ownership claims."""
|
||||
call = getattr(_local, 'call', None)
|
||||
with _tasks_guard:
|
||||
check_active()
|
||||
if call is not None:
|
||||
if call.metadata_only or call.readonly_depth:
|
||||
raise RuntimeError('Read-only metadata cannot commit filesystem changes')
|
||||
call.commit_depth += 1
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if call is not None:
|
||||
with _tasks_guard:
|
||||
call.commit_depth -= 1
|
||||
call.phase_started = time.monotonic()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def native_phase(*, read_only=False, supervised=False):
|
||||
"""Never abandon a transaction between native writes (including Remove/Add)."""
|
||||
call = getattr(_local, 'call', None)
|
||||
if call is not None and call.metadata_only:
|
||||
raise RuntimeError('A metadata-only call cannot enter native work')
|
||||
if call is not None:
|
||||
if call.readonly_depth and not read_only:
|
||||
raise RuntimeError('NATIVE_ROLE_REQUIRED: 只读观察不能提交原生写入。')
|
||||
if not read_only and (call.context.native_policy == 'restricted'
|
||||
or call.context.native_policy == 'external' and not supervised):
|
||||
raise RuntimeError('NATIVE_ROLE_REQUIRED: 界面写入必须通过已登记的独立工作进程。')
|
||||
with _tasks_guard:
|
||||
check_active()
|
||||
if call is not None:
|
||||
call.native_depth += 1
|
||||
call.readonly_depth += int(read_only)
|
||||
call.supervised_depth += int(supervised)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if call is not None:
|
||||
with _tasks_guard:
|
||||
call.native_depth -= 1
|
||||
call.readonly_depth -= int(read_only)
|
||||
call.supervised_depth -= int(supervised)
|
||||
call.phase_started = time.monotonic()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def native_channel(*, inspection_only=False, read_only=False):
|
||||
"""Shared by Verify, Repair and backup native clients; reentrant per thread."""
|
||||
import win32con, win32event
|
||||
with native_phase(read_only=read_only or inspection_only, supervised=True):
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
try:
|
||||
check_active()
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
raise RuntimeError('NATIVE_CHANNEL_BUSY: 另一个原生操作仍在运行。')
|
||||
from .desktop_worker import assert_native_writer_idle
|
||||
if inspection_only is not True:
|
||||
assert_native_writer_idle()
|
||||
yield
|
||||
finally:
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BatchTaskContext:
|
||||
library: str
|
||||
aliases: tuple[str, ...] = ()
|
||||
targets: tuple[str, ...] = ()
|
||||
resources: tuple[str, ...] = ()
|
||||
operation_id: str = field(default_factory=lambda: uuid4().hex)
|
||||
stop: _StopSignal = field(default_factory=_StopSignal, repr=False, compare=False)
|
||||
_closed: Event = field(default_factory=Event, repr=False, compare=False)
|
||||
native_policy: str = field(default='legacy', kw_only=True)
|
||||
# Only queue/batch boundaries consume this; the current item retains hard-stop semantics.
|
||||
stop_after_current: _StopSignal = field(default_factory=_StopSignal, repr=False, compare=False, kw_only=True)
|
||||
|
||||
def __post_init__(self):
|
||||
if self.native_policy not in ('legacy', 'restricted', 'external'):
|
||||
raise ValueError('Unknown native task role')
|
||||
object.__setattr__(self, 'library', str(self.library))
|
||||
for name in ('aliases', 'targets', 'resources'):
|
||||
object.__setattr__(self, name, tuple(str(v) for v in getattr(self, name)))
|
||||
|
||||
@property
|
||||
def scope(self):
|
||||
return dict(scope_state='DECLARED', library=self.library, aliases=list(self.aliases),
|
||||
block_names=list(self.targets), resources=list(self.resources),
|
||||
operation_ids=[self.operation_id])
|
||||
|
||||
@property
|
||||
def state(self):
|
||||
return self.snapshot()['state']
|
||||
|
||||
def snapshot(self):
|
||||
with _tasks_guard:
|
||||
calls = [call for call in _calls.values() if call.context is self]
|
||||
pending = sum(not call.done.is_set() for call in calls)
|
||||
return dict(operation_id=self.operation_id, resource_scope=self.scope,
|
||||
state='CLOSED' if self._closed.is_set() else
|
||||
'CANCELLED' if self.stop.is_set() else
|
||||
'HANDED_OFF' if any(c.abandoned for c in calls) else
|
||||
'RUNNING' if pending else 'IDLE', pending=pending,
|
||||
pending_native=any(c.native_depth or c.commit_depth for c in calls))
|
||||
|
||||
def shutdown(self):
|
||||
"""Yield UI supervision, never a native worker's write/lease ownership.
|
||||
|
||||
External workers commit their kernel start event under this same fence.
|
||||
Registration and all filesystem preparation remain outside the fence.
|
||||
Legacy in-process transactions cannot opt in.
|
||||
"""
|
||||
with _tasks_guard:
|
||||
self._closed.set()
|
||||
self.cancel()
|
||||
calls = [c for c in _calls.values() if c.context is self and not c.done.is_set()]
|
||||
for call in calls:
|
||||
readonly = call.native_depth and call.readonly_depth == call.native_depth
|
||||
external = (self.native_policy == 'external' and
|
||||
call.supervised_depth == call.native_depth and
|
||||
all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only', 'catalog_readonly')
|
||||
for s in call.worker_sessions))
|
||||
if not call.commit_depth and (not call.native_depth or readonly or external):
|
||||
call.shutdown_handoff = call.abandoned = True
|
||||
return {**self.snapshot(), 'safe_to_continue': False,
|
||||
'shutdown_handoff': all(c.shutdown_handoff for c in calls),
|
||||
'worker_sessions': [s for c in calls for s in c.worker_sessions]}
|
||||
|
||||
def cancel(self):
|
||||
self.stop.set()
|
||||
|
||||
def check_active(self):
|
||||
if self.stop.is_set() or self._closed.is_set():
|
||||
raise QueueCancelled('任务已取消,未提交新的原生操作。')
|
||||
check_active()
|
||||
|
||||
def guard_callback(self, callback, *, current=None):
|
||||
call = getattr(_local, 'call', None)
|
||||
def guarded(*args, **kwargs):
|
||||
# Cancellation still gets its own terminal result; closing or an
|
||||
# abandoned invocation cannot update a newer task/library.
|
||||
if (not self._closed.is_set() and not (call and call.abandoned)
|
||||
and (current is None or current() is self)):
|
||||
return callback(*args, **kwargs)
|
||||
return guarded
|
||||
|
||||
def close(self, *, timeout_seconds=30):
|
||||
self._closed.set()
|
||||
self.cancel()
|
||||
deadline = time.monotonic() + min(30, max(0, timeout_seconds))
|
||||
with _tasks_guard:
|
||||
calls = [c for c in _calls.values() if c.context is self]
|
||||
for call in calls:
|
||||
call.done.wait(max(0, deadline-time.monotonic()))
|
||||
with _tasks_guard:
|
||||
for call in calls:
|
||||
if not call.done.is_set() and not call.native_depth and not call.commit_depth:
|
||||
call.abandoned = True
|
||||
return self.snapshot()
|
||||
|
||||
def run(self, action, *, stop=None, timeout_seconds=10, metadata_only=False):
|
||||
self.check_active()
|
||||
if current_context() is self:
|
||||
return action() # Preserve nested lease and mutex thread identity.
|
||||
aliases = {_path_key(v) for v in (self.library, *self.aliases)}
|
||||
call = _Call(self, stop, metadata_only=metadata_only)
|
||||
with _tasks_guard:
|
||||
if not metadata_only and self.native_policy != 'restricted' and any(c.abandoned and not c.metadata_only and aliases.intersection(
|
||||
_path_key(v) for v in (c.context.library, *c.context.aliases))
|
||||
for c in _calls.values()):
|
||||
raise TaskHandoff(self)
|
||||
_calls[id(call)] = call
|
||||
def execute():
|
||||
_local.call = call
|
||||
try:
|
||||
check_active()
|
||||
call.result = action()
|
||||
except BaseException as error:
|
||||
call.error = error
|
||||
finally:
|
||||
with _tasks_guard:
|
||||
call.done.set()
|
||||
_calls.pop(id(call), None)
|
||||
del _local.call
|
||||
Thread(target=execute, name='cbb-task-'+self.operation_id[:12], daemon=True).start()
|
||||
while not call.done.wait(.02):
|
||||
with _tasks_guard:
|
||||
if call.shutdown_handoff:
|
||||
raise TaskHandoff(self, cancelled=True, result=call.last_result)
|
||||
if call.native_handoff:
|
||||
cancelled = call.handoff_cancelled
|
||||
call.abandoned = True
|
||||
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
|
||||
elapsed = time.monotonic()-call.phase_started
|
||||
if not call.native_depth and not call.commit_depth and (call.abandoned or elapsed >= timeout_seconds):
|
||||
cancelled = call.is_set()
|
||||
call.abandoned = True
|
||||
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
|
||||
if call.error is not None:
|
||||
raise call.error
|
||||
return call.result
|
||||
|
||||
|
||||
class NativeQueue:
|
||||
def __init__(self):
|
||||
self.condition = Condition()
|
||||
self.pending = []
|
||||
self.active = False
|
||||
self.closed = False
|
||||
self.contexts = {}
|
||||
|
||||
def wake(self):
|
||||
with self.condition: self.condition.notify_all()
|
||||
|
||||
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None):
|
||||
ticket = object()
|
||||
def close(self, *, timeout_seconds=30):
|
||||
deadline = time.monotonic()+min(30, max(0, timeout_seconds))
|
||||
with self.condition:
|
||||
self.closed = True
|
||||
contexts = tuple(self.contexts.values())
|
||||
for context in contexts:
|
||||
context.cancel()
|
||||
self.condition.notify_all()
|
||||
return tuple(context.close(timeout_seconds=max(0, deadline-time.monotonic()))
|
||||
for context in contexts)
|
||||
|
||||
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None,
|
||||
context=None, timeout_seconds=10, skip_unavailable=False):
|
||||
def available_now():
|
||||
if not ready():
|
||||
return False
|
||||
if context is None:
|
||||
return True # Explicit recovery controls must still reach their retained clients.
|
||||
from .session_record import _live_library_available
|
||||
for path in (context.library, *context.aliases):
|
||||
if not _live_library_available(path):
|
||||
if skip_unavailable:
|
||||
raise QueueUnavailable(path)
|
||||
return False
|
||||
return True
|
||||
ticket = [object(), False]
|
||||
acquired, notified = False, False
|
||||
previous_state = None
|
||||
with self.condition: self.pending.append((ticket, ready))
|
||||
with self.condition:
|
||||
if self.closed:
|
||||
raise QueueCancelled('队列已关闭,未启动新的操作。')
|
||||
if context is not None:
|
||||
self.contexts[id(context)] = context
|
||||
self.pending.append(ticket)
|
||||
try:
|
||||
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.
|
||||
with self.condition:
|
||||
if 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())):
|
||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||
first = next((token for token, available in self.pending if available()), None)
|
||||
ticket[1] = bool(available)
|
||||
first = next((entry for entry in self.pending if entry[1]), None)
|
||||
if not self.active and first is ticket:
|
||||
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
||||
self.active = acquired = True
|
||||
else:
|
||||
self.condition.wait(.1)
|
||||
if acquired and not available_now():
|
||||
with self.condition:
|
||||
ticket[1] = self.active = acquired = False
|
||||
self.condition.notify_all()
|
||||
if not acquired and waiting is not None:
|
||||
try:
|
||||
current_state = wait_state() if wait_state is not None else None
|
||||
@@ -39,11 +467,12 @@ class NativeQueue:
|
||||
notified, previous_state = True, current_state
|
||||
except Exception:
|
||||
pass
|
||||
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()):
|
||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||
return action()
|
||||
return context.run(action, stop=stop, timeout_seconds=timeout_seconds) if context else action()
|
||||
finally:
|
||||
with self.condition:
|
||||
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
||||
self.pending = [entry for entry in self.pending if entry is not ticket]
|
||||
if acquired: self.active = False
|
||||
self.condition.notify_all()
|
||||
@@ -18,14 +18,16 @@ class OpenChoice:
|
||||
def __init__(self, block, library):
|
||||
self.block, self.library = block, library
|
||||
self.decision = None
|
||||
self.decision_origin = None
|
||||
self._lock = Lock()
|
||||
|
||||
def choose(self, decision):
|
||||
def choose(self, decision, *, origin='user'):
|
||||
if decision not in ('continue', 'skip', 'cancel'):
|
||||
raise ValueError('无效的打开工程选择')
|
||||
with self._lock:
|
||||
if self.decision is None:
|
||||
self.decision = decision
|
||||
self.decision_origin = origin
|
||||
|
||||
|
||||
def validate_owner(job, target_pid, launcher_pid, worker_pid):
|
||||
@@ -46,8 +48,14 @@ def validate_owner(job, target_pid, launcher_pid, worker_pid):
|
||||
|
||||
@contextmanager
|
||||
def resource_guard(job, allowed_pids):
|
||||
import win32con, win32file
|
||||
from .icdb_ownership import database_directories, unreleased_addresses
|
||||
import hashlib
|
||||
from .file_probe import hold_release_files
|
||||
from .maintenance_entry import maintenance_project_files
|
||||
from .native_repair import RepairTarget, run_native_repair
|
||||
from .native_occupancy import confirmed_inspection
|
||||
from .session_record import IDENTITY_KEYS
|
||||
from .operation_queue import task_stop
|
||||
from .management import _write_json
|
||||
from .owner_probe import query_process_snapshot
|
||||
from .library_lock import _owner_is_blocking
|
||||
from .verify_runner import preflight, VerifyRequest
|
||||
@@ -56,21 +64,48 @@ def resource_guard(job, allowed_pids):
|
||||
if project.resolve() != Path(job['project']).resolve() or pcb.resolve() != Path(job['pcb']).resolve():
|
||||
raise ValueError('PCB_OPEN_PROJECT_CHANGED')
|
||||
roots = (project.parent, library.parent/'SymbolLibs')
|
||||
configs = maintenance_project_files(project, pcb)
|
||||
def binding():
|
||||
return {str(path.resolve()): hashlib.sha256(path.read_bytes()).hexdigest() for path in (pcb, *configs)}
|
||||
original_binding = binding()
|
||||
def check():
|
||||
if unreleased_addresses(library, project, pcb):
|
||||
raise ValueError('目标仍有数据库地址记录,暂不能确认读写打开。')
|
||||
for row in query_process_snapshot():
|
||||
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
|
||||
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
|
||||
check()
|
||||
paths = [library, pcb.parent/'Layout/LayoutDB.lyt',
|
||||
*(d/'icdb.dat' for d in database_directories(library, project, pcb) if (d/'icdb.dat').is_file())]
|
||||
stop = task_stop(None)
|
||||
with ExitStack() as stack:
|
||||
for path in dict.fromkeys(paths):
|
||||
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
|
||||
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
|
||||
stack.callback(handle.Close)
|
||||
files = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||
inspections = []
|
||||
if files['addresses']:
|
||||
targets = files['inspection_targets']
|
||||
if any(Path(item['project']).resolve() not in {p.resolve() for p in configs} for item in targets):
|
||||
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置,需人工核对')
|
||||
stack.close() # Native inspection must access the DB; repeat exact proof afterwards.
|
||||
for index, item in enumerate(targets):
|
||||
target = RepairTarget(Path(item['project']), Path(item['database']))
|
||||
evidence = Path(job['root'])/('open-inspection-'+str(index))
|
||||
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)
|
||||
identity = result.get('native_identity') or {}
|
||||
if (not confirmed_inspection(target, result) or result['status'] != 'NOT_IN_USE'
|
||||
or identity.get('pid') != result.get('native_pid')
|
||||
or any(identity.get(key) is None for key in IDENTITY_KEYS)
|
||||
or not identity.get('image') or not identity.get('owner_sid')):
|
||||
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 原生检查未确认当前数据库未占用')
|
||||
inspections.append(result)
|
||||
current = stack.enter_context(hold_release_files(library, roots, stop=stop))
|
||||
if any(current[key] != files[key] for key in (
|
||||
'exclusive_files', 'binding_files', 'addresses', 'signatures', 'inspection_targets', 'resource_scope')):
|
||||
raise ValueError('PCB_OPEN_RESOURCE_CHANGED: 原生检查期间资源或地址身份变化')
|
||||
if binding() != original_binding:
|
||||
raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化')
|
||||
check()
|
||||
_write_json(Path(job['root'])/'pcb-open-resource-proof.json', {
|
||||
'operation_id': job.get('operation_id'), 'library': str(library),
|
||||
'project': str(project), 'pcb': str(pcb), 'binding': original_binding,
|
||||
'exclusive_files': files['exclusive_files'], 'addresses': files['addresses'],
|
||||
'native_inspections': inspections, 'repair_confirmed': False})
|
||||
yield
|
||||
|
||||
|
||||
@@ -106,9 +141,11 @@ class OpenController:
|
||||
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'],
|
||||
'target': {'control_id': control}, 'desktop': self.job['desktop'],
|
||||
'pid': target_pid, 'owner': owner, 'choice': self.choice.decision}
|
||||
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, project=self.job['project'], pcb=self.job['pcb'],
|
||||
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)
|
||||
@@ -128,8 +165,10 @@ class OpenController:
|
||||
error = 'PCB_OPEN_ANSWER_FAILED'
|
||||
if not error and control == 7:
|
||||
error = 'PCB_OPEN_SKIPPED' if self.choice.decision == 'skip' else 'USER_CANCELLED'
|
||||
skipped_detail = ('超时默认跳过本项。' if self.choice.decision_origin == 'timeout_default'
|
||||
else '用户跳过本项。')
|
||||
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
|
||||
error_code=error, detail=result.detail or ('用户跳过本项。' 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,
|
||||
action=action['action'], observed_snapshots=tuple(snapshots))
|
||||
except Exception as error:
|
||||
|
||||
@@ -13,14 +13,16 @@ class RestoreChoice:
|
||||
self.block, self.library = block, library
|
||||
self.candidates = tuple(dict(c) for c in candidates)
|
||||
self.decision = None
|
||||
self.decision_origin = None
|
||||
self._lock = Lock()
|
||||
|
||||
def choose(self, kind):
|
||||
def choose(self, kind, *, origin='user'):
|
||||
if kind != 'cancel' and not any(c['kind'] == kind and c['enabled'] for c in self.candidates):
|
||||
raise ValueError('Unknown or disabled PCB restoration version')
|
||||
with self._lock:
|
||||
if self.decision is None:
|
||||
self.decision = kind
|
||||
self.decision_origin = origin
|
||||
|
||||
|
||||
def _candidate_key(candidates):
|
||||
@@ -82,7 +84,11 @@ class RestoreController:
|
||||
if self.prompt.decision is None:
|
||||
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
|
||||
if self.prompt.decision == 'cancel':
|
||||
raise ValueError('用户取消 PCB 版本选择;未确认恢复,保留原生现场。')
|
||||
_write_json(Path(self.job['root'])/'pcb-version-user-choice.json', dict(
|
||||
project=self.job['project'], pcb=self.job['pcb'], choice='cancel',
|
||||
decision_origin=self.prompt.decision_origin, snapshot=snapshot.to_record()))
|
||||
reason = '超时默认取消' if self.prompt.decision_origin == 'timeout_default' else '用户取消'
|
||||
raise ValueError(reason+' PCB 版本选择;未确认恢复,保留原生现场。')
|
||||
selected = next(c for c in choice['candidates'] if c['kind'] == self.prompt.decision)
|
||||
if not selected['enabled']:
|
||||
raise ValueError('PCB_VERSION_DISABLED')
|
||||
@@ -99,12 +105,14 @@ class RestoreController:
|
||||
action = {'action': 'user_selected_pcb_version', 'channels': ['win32_button_click'],
|
||||
'target': {'control_id': control}, 'desktop': self.job['desktop'], 'pid': target_pid,
|
||||
'choice': selected['kind'], 'candidates': list(self.prompt.candidates)}
|
||||
action['decision_origin'] = self.prompt.decision_origin
|
||||
if self.owner is not None:
|
||||
action['owner'] = self.owner
|
||||
self.selection_sent = True
|
||||
self.confirm_sent = confirming
|
||||
self.sent_at = time.monotonic()
|
||||
record = {'project': self.job['project'], 'pcb': self.job['pcb'], 'choice': selected['kind'],
|
||||
'decision_origin': self.prompt.decision_origin,
|
||||
'date': selected['date'], 'historical_restore': True, 'confirm_sent': confirming,
|
||||
'snapshot': snapshot.to_record()}
|
||||
_write_json(Path(self.job['root'])/'pcb-version-user-choice.json', record)
|
||||
|
||||
@@ -252,7 +252,7 @@ def _post_window_message(window, hwnd, pid, message):
|
||||
win32gui.PostMessage(hwnd, message, 0, 0)
|
||||
|
||||
|
||||
def _process_windows(pids):
|
||||
def _process_windows(pids, *, include_hidden_documents=False):
|
||||
result = _WindowSnapshot(pids)
|
||||
if not pids: return result
|
||||
import win32api, win32con, win32gui, win32process
|
||||
@@ -271,10 +271,13 @@ def _process_windows(pids):
|
||||
kind = win32gui.GetClassName(handle)
|
||||
if kind == 'MDIClient' and win32gui.GetWindow(handle, win32con.GW_CHILD):
|
||||
documents.append(handle)
|
||||
if win32gui.IsWindowVisible(handle):
|
||||
visible = bool(win32gui.IsWindowVisible(handle))
|
||||
if visible or (include_hidden_documents and kind.casefold().startswith('afx:')
|
||||
and win32gui.GetClassName(win32gui.GetParent(handle)) == 'MDIClient'):
|
||||
children.append({'hwnd': int(handle), 'class': kind,
|
||||
'id': win32gui.GetDlgCtrlID(handle) & 0xffff,
|
||||
'text': win32gui.GetWindowText(handle), 'enabled': bool(win32gui.IsWindowEnabled(handle))})
|
||||
'text': win32gui.GetWindowText(handle), 'enabled': bool(win32gui.IsWindowEnabled(handle)),
|
||||
'visible': visible})
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd),
|
||||
@@ -482,6 +485,451 @@ def inspect_residual_sessions(library, *, block_names=()):
|
||||
'previous_records': previous}
|
||||
|
||||
|
||||
def _hidden_tip_owner(tip, pid):
|
||||
"""Read only the Tip's direct hidden frame, never arbitrary hidden windows."""
|
||||
import win32api, win32con, win32gui, win32process
|
||||
with _window_desktop(tip['desktop']) as desktop:
|
||||
hwnd = win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER)
|
||||
if (not hwnd or hwnd not in _desktop_windows(desktop)
|
||||
or win32process.GetWindowThreadProcessId(hwnd)[1] != pid
|
||||
or win32gui.IsWindowVisible(hwnd) or win32gui.IsWindowEnabled(hwnd)):
|
||||
return None
|
||||
kind, title = win32gui.GetClassName(hwnd), win32gui.GetWindowText(hwnd)
|
||||
if not kind.startswith('Afx:') or title.strip() not in (
|
||||
'Expedition PCB', 'Expedition PCB - Reusable Block'):
|
||||
return None
|
||||
children, documents = [], []
|
||||
def child(control, _):
|
||||
control_class = win32gui.GetClassName(control)
|
||||
if control_class.casefold() == 'msctls_progress32':
|
||||
children.append({'class': control_class})
|
||||
if control_class == 'MDIClient' and win32gui.GetWindow(control, win32con.GW_CHILD):
|
||||
documents.append(control)
|
||||
win32api.SetLastError(0)
|
||||
win32gui.EnumChildWindows(hwnd, child, None)
|
||||
return dict(hwnd=hwnd, title=title, **{'class': kind}, desktop=tip['desktop'],
|
||||
enabled=False, children=children, documents=documents)
|
||||
|
||||
|
||||
def _dismiss_startup_tip(row, handle, windows, *, incomplete=None, dismissed=(), deadline=None, stop=None):
|
||||
"""A non-writing startup Tip may finish an already pending normal close."""
|
||||
import win32con, win32event, win32gui
|
||||
from .failed_session import _startup_snapshot, _tip_target
|
||||
if (incomplete or row.get('scope_confirmed') is not True
|
||||
or row.get('name', '').casefold() != 'expeditionpcb.exe'
|
||||
or row.get('runtime_phase') in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED')
|
||||
or native_activity(row['name'], windows)['status'] != 'IDLE'):
|
||||
return None
|
||||
desktops = {w.get('desktop', '') for w in windows}
|
||||
if len(desktops) != 1 or not next(iter(desktops), '').startswith('CbbVerify_'):
|
||||
return None
|
||||
tips = [w for w in windows if w['class'] == '#32770' and w['title'] == 'Tip of the Day']
|
||||
if len(tips) != 1 or tips[0]['hwnd'] in dismissed:
|
||||
return None
|
||||
tip = tips[0]
|
||||
hidden_owner = None
|
||||
if not any(w['class'].startswith('Afx:') for w in windows):
|
||||
hidden_owner = _hidden_tip_owner(tip, row['pid'])
|
||||
# A disabled empty frame is expected behind a modal Tip. No document,
|
||||
# progress, other dialog, or arbitrary disabled application is admitted.
|
||||
rest = [dict(w, enabled=True) if w['class'].startswith('Afx:') else w
|
||||
for w in windows if w is not tip]
|
||||
if hidden_owner is not None:
|
||||
rest.append(dict(hidden_owner, enabled=True))
|
||||
main, _ = close_target(row['name'], rest)
|
||||
if (main is None or main.get('documents')
|
||||
or row.get('startup_frame', main['hwnd']) != main['hwnd']
|
||||
or main['title'].strip() not in (
|
||||
'Expedition PCB', 'Expedition PCB - Reusable Block')):
|
||||
return None
|
||||
buttons = [c for c in tip['children'] if c['class'] == 'Button' and c.get('id') == 1
|
||||
and c.get('enabled')]
|
||||
if len(buttons) != 1 or not tip['enabled']:
|
||||
return None
|
||||
if row.get('library'):
|
||||
from .session_record import active_write_records
|
||||
if active_write_records(row['library']):
|
||||
return None
|
||||
with _window_desktop(tip['desktop'], write=True):
|
||||
if win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER) != main['hwnd']:
|
||||
return None
|
||||
current = _startup_snapshot(tip['hwnd'], row['pid'])
|
||||
target = _tip_target(current)
|
||||
if (target is None or target.handle != buttons[0]['hwnd']
|
||||
or current.title != tip['title'] or current.window_class != tip['class']):
|
||||
return None
|
||||
fresh = _process_windows({row['pid']})
|
||||
if (_window_error(fresh, row['pid']) or fresh.get(row['pid']) != windows
|
||||
or win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_TIMEOUT
|
||||
or _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}
|
||||
or win32gui.GetWindow(tip['hwnd'], win32con.GW_OWNER) != main['hwnd']
|
||||
or hidden_owner is not None and _hidden_tip_owner(tip, row['pid']) != hidden_owner
|
||||
or _startup_snapshot(tip['hwnd'], row['pid']) != current):
|
||||
return None
|
||||
if (deadline is not None and time.monotonic() >= deadline
|
||||
or stop is not None and stop.is_set()):
|
||||
return None
|
||||
_post_window_message(tip, target.handle, row['pid'], win32con.BM_CLICK)
|
||||
return tip['hwnd']
|
||||
|
||||
|
||||
def _cancelled_diagnostic_record(row):
|
||||
"""Existing complete registration can authorize cleanup, never validation."""
|
||||
import stat
|
||||
import pywintypes, win32con, win32event
|
||||
from .session_record import _session, IDENTITY_KEYS, active_write_records
|
||||
from .failed_session import _command_args
|
||||
if row.get('scope_confirmed') is not True or row.get('name', '').casefold() != 'expeditionpcb.exe':
|
||||
return None
|
||||
def same(a, b):
|
||||
return os.path.normcase(os.path.abspath(str(a))) == os.path.normcase(os.path.abspath(str(b)))
|
||||
def read(path, *, lines=False):
|
||||
if path.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
|
||||
raise ValueError('STARTUP_RECORD_REPARSE_POINT')
|
||||
with path.open('rb') as stream:
|
||||
data = stream.read(1024*1024+1)
|
||||
if len(data) > 1024*1024:
|
||||
raise ValueError('STARTUP_RECORD_TOO_LARGE')
|
||||
return [json.loads(line) for line in data.splitlines()] if lines else json.loads(data)
|
||||
matches = []
|
||||
for record in row.get('session_records', ()):
|
||||
try:
|
||||
path = Path(record['path']); root = path.parent
|
||||
session, state, identities = _session(path, root)
|
||||
job, result = read(root/'request.json'), read(root/'result.json')
|
||||
operation = session['operation_id']
|
||||
scope = session.get('resource_scope', {})
|
||||
if (record.get('operation_id') != operation or job.get('operation_id') != operation
|
||||
or job.get('diagnostic_only') not in (True,False) or job.get('interactive_input') is not False
|
||||
or job.get('operation') != 'verify' or session.get('operation') != 'verify'
|
||||
or not all(same(value, row['library']) for value in (job['library'], job['lmc_file'], session['library']))
|
||||
or not same(job['root'], root) or not same(job['session_record_path'], path)
|
||||
or job.get('desktop') != session.get('desktop') or not job['desktop'].startswith('CbbVerify_')
|
||||
or scope.get('scope_state') != 'DECLARED' or scope.get('operation_id') != operation
|
||||
or not same(scope.get('library', ''), row['library'])
|
||||
or scope.get('projects') != [job['project']]
|
||||
or not Path(job['pcb']).is_relative_to(Path(job['project']).parent)
|
||||
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 result.get('status') != 'CANCELLED' or result.get('error_stage') != 'PCB_STARTING'
|
||||
or result.get('write_outcome', {}).get('save_state') != 'UNKNOWN'
|
||||
or state.get('phase') != 'UNCONFIRMED' or (root/'save.log').exists()):
|
||||
continue
|
||||
native = [p for p in identities if p.get('role') == 'native' and p['pid'] == row['pid']]
|
||||
workers = [p for p in identities if p.get('role') in ('worker', 'helper')]
|
||||
if (len(native) != 1 or not workers
|
||||
or any(native[0][k] != row.get(k) for k in IDENTITY_KEYS)
|
||||
or any(p.get('role') not in ('worker','helper','native','supervisor') for p in identities)):
|
||||
continue
|
||||
for worker in workers:
|
||||
try:
|
||||
with _process_handle(worker['pid']) as held:
|
||||
if win32event.WaitForSingleObject(held, 0) != win32con.WAIT_OBJECT_0:
|
||||
raise ValueError('STARTUP_WORKER_STILL_ACTIVE')
|
||||
except (OSError, pywintypes.error) as error:
|
||||
if getattr(error, 'winerror', None) != 87:
|
||||
raise
|
||||
args = _command_args(row['command'])
|
||||
if ('-reusablecircuit' not in [a.casefold() for a in args]
|
||||
or not any(same(a, job['pcb']) for a in args[1:])):
|
||||
continue
|
||||
events = read(root/'events.jsonl', lines=True)
|
||||
if (not any(e.get('stage') == 'pcb_worker_started' and e.get('pcb_pid') == row['pid'] for e in events)
|
||||
or not any(e.get('stage') == 'pcb_baseline' and row['pid'] not in e.get('pids', []) for e in events)
|
||||
or any(str(e.get('stage', '')).startswith(('save', 'integration', 'validate', 'failure_close'))
|
||||
or e.get('stage') == 'diagnostic_complete' for e in events)):
|
||||
continue
|
||||
closes = [e for e in events if e.get('stage') in ('startup_close_requested', 'diagnostic_wm_close')]
|
||||
if len(closes) > 1 or any(e.get('pcb_pid') != row['pid'] or not e.get('hwnd') for e in closes):
|
||||
continue
|
||||
if any(r.get('operation_id') != operation for r in active_write_records(row['library'])):
|
||||
continue
|
||||
if job.get('diagnostic_only') is False:
|
||||
from .failed_session import cancelled_prewrite_startup
|
||||
from .diagnostic_open import _load_evidence
|
||||
baseline=cancelled_prewrite_startup(job,row['pid'])
|
||||
if baseline is None or _load_evidence(job,row['pid'],baseline,require_autosave=False) is None:
|
||||
continue
|
||||
matches.append(dict(job=job, record_path=str(path), operation_id=operation,
|
||||
closed_frame=closes[0]['hwnd'] if closes else None,
|
||||
declined_buttons=[e['hwnd'] for e in events if e.get('stage')=='startup_prompt_no'
|
||||
and e.get('pcb_pid')==row['pid'] and e.get('control_id')==7 and e.get('hwnd')],
|
||||
dismissed_tips=[e['hwnd'] for e in events if e.get('stage')=='startup_tip_dismissed'
|
||||
and e.get('pcb_pid')==row['pid'] and e.get('hwnd')]))
|
||||
except (OSError, pywintypes.error, ValueError, KeyError, TypeError):
|
||||
continue
|
||||
return matches[0] if len(matches) == 1 else None
|
||||
|
||||
|
||||
def _legacy_diagnostic_windows(row):
|
||||
"""Adapt the existing complete private-desktop snapshot for diagnostic policy."""
|
||||
import win32con, win32gui
|
||||
snapshot = _process_windows({row['pid']}, include_hidden_documents=True)
|
||||
if _window_error(snapshot, row['pid']):
|
||||
raise ValueError('STARTUP_WINDOW_UNCONFIRMED')
|
||||
result = []
|
||||
for window in snapshot.get(row['pid'], []):
|
||||
if window.get('desktop') != row['cleanup_desktop']:
|
||||
raise ValueError('STARTUP_DESKTOP_UNCONFIRMED')
|
||||
benign = (not window['title'] and window['class'] in ('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator'))
|
||||
benign = benign or (window['class'] == 'Internet Explorer_Hidden' and not window['title']
|
||||
and not window['children'] and window.get('rect', [1,1,2,2])[:2] == window.get('rect', [1,1,2,2])[2:])
|
||||
if benign:
|
||||
continue
|
||||
with _window_desktop(window['desktop']):
|
||||
children = [dict(c, parent=win32gui.GetParent(c['hwnd'])) for c in window['children']]
|
||||
result.append(dict(hwnd=window['hwnd'], pid=row['pid'], **{'class':window['class']},
|
||||
text=window['title'], enabled=window['enabled'], children=children,
|
||||
owner=int(win32gui.GetWindow(window['hwnd'], win32con.GW_OWNER) or 0)))
|
||||
return result
|
||||
|
||||
|
||||
def _close_registered_startup(row, handle, proof, *, stop=None, deadline=None):
|
||||
import pywintypes, win32con, win32event
|
||||
from .diagnostic_open import cancelled_startup_step
|
||||
from .operation_queue import check_active
|
||||
job = proof['job']; bound = dict(row, cleanup_desktop=job['desktop'])
|
||||
if deadline is None:deadline = time.monotonic()+30
|
||||
def active_owner():
|
||||
check_active()
|
||||
if stop is not None and stop.is_set():
|
||||
return False
|
||||
owner = _force_ownership(handle,row['pid'])
|
||||
return (owner.get('force_user_confirmed') is True
|
||||
and win32event.WaitForSingleObject(handle,0) == win32con.WAIT_TIMEOUT
|
||||
and _handle_identity(handle) == {k:row.get(k) for k in ('created_handle','image')}
|
||||
and all(owner.get(k) == row.get(k) for k in ('owner_sid','session_id')))
|
||||
def confirmed():
|
||||
if not active_owner():return False
|
||||
fresh = next((p for p in query_process_snapshot() if p['pid'] == row['pid']), None)
|
||||
return (fresh is not None and all(fresh.get(k) == row.get(k) for k in ('created','command','executable','name'))
|
||||
and _cancelled_diagnostic_record(row) == proof)
|
||||
def post(hwnd, message):
|
||||
if not active_owner() or time.monotonic() >= deadline:
|
||||
raise ValueError('STARTUP_ACTION_UNCONFIRMED')
|
||||
_post_window_message({'desktop':job['desktop']}, hwnd, row['pid'], message)
|
||||
state = {'clicked':set()}; closed = proof['closed_frame']; dismissed_tips = set(proof.get('dismissed_tips',()))
|
||||
def read_bound_windows():
|
||||
windows=_legacy_diagnostic_windows(bound)
|
||||
for window in windows:
|
||||
if any(c['hwnd'] in proof.get('declined_buttons',()) for c in window['children']):
|
||||
state['clicked'].add(window['hwnd'])
|
||||
return windows
|
||||
try:
|
||||
while time.monotonic() < deadline:
|
||||
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
|
||||
return {'release_status':'RELEASED','detail':'已正常结束已取消的诊断启动'}
|
||||
if not active_owner():
|
||||
break
|
||||
snapshot = _process_windows({row['pid']})
|
||||
# Only this fully proved no-write operation may bypass its historical
|
||||
# UNCONFIRMED label; other operations were vetoed by the proof above.
|
||||
tip_row = {k:v for k,v in row.items() if k not in ('runtime_phase','library')}
|
||||
if closed is not None:
|
||||
tip_row['startup_frame'] = closed
|
||||
has_tip = any(w['title'] == 'Tip of the Day' for w in snapshot.get(row['pid'],[]))
|
||||
tip = (_dismiss_startup_tip(tip_row,handle,snapshot.get(row['pid'],[]),
|
||||
incomplete=_window_error(snapshot,row['pid']),dismissed=dismissed_tips,deadline=deadline,stop=stop)
|
||||
if has_tip and confirmed() else None)
|
||||
if tip is not None:
|
||||
dismissed_tips.add(tip)
|
||||
if closed is None:
|
||||
continue # Tip may precede loading; the same intent still owns its one Close.
|
||||
while time.monotonic() < deadline:
|
||||
if win32event.WaitForSingleObject(handle,100) == win32con.WAIT_OBJECT_0:
|
||||
return {'release_status':'RELEASED','detail':'已关闭启动提示并正常退出'}
|
||||
if stop is not None and stop.is_set():break
|
||||
break # Never stack another Close after a legacy Tip acknowledgement.
|
||||
try:
|
||||
closed,_ = cancelled_startup_step(job,row['pid'],state,closed_frame=closed,deadline=deadline,
|
||||
post=post,emit=lambda **event:None,read_windows=read_bound_windows,
|
||||
identity_check=confirmed)
|
||||
except RuntimeError as error:
|
||||
if not str(error).startswith('STARTUP_WINDOW_CHANGED:'):
|
||||
raise
|
||||
# No may remove a modal and enable the target while the next
|
||||
# snapshot is being read. Revalidate anew inside the same budget.
|
||||
time.sleep(.1)
|
||||
except (OSError, pywintypes.error, ValueError, RuntimeError) as error:
|
||||
return {'release_status':'WAITING','detail':str(error)}
|
||||
return {'release_status':'WAITING','detail':'已请求取消启动清理,等待原生退出后重新检查'}
|
||||
|
||||
|
||||
def _ordinary_startup_close(row, handle, proof, *, stop=None):
|
||||
"""One persisted retained phase, serialized with existing explicit release."""
|
||||
import win32con, win32event
|
||||
from .session_record import read_session_record, write_session_record
|
||||
from .operation_queue import native_phase
|
||||
waiting = {'release_status':'WAITING','detail':'取消启动清理已交接或原生执行通道忙,继续观察'}
|
||||
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 waiting
|
||||
path=Path(proof['record_path'])
|
||||
record=read_session_record(path,evidence_root=path.parent)
|
||||
if 'retained_startup_cleanup' in record or _cancelled_diagnostic_record(row)!=proof:return waiting
|
||||
# Complete loaded identity and every prompt are checked before consuming
|
||||
# the one-shot intent. Unknown/multiple documents remain observation-only.
|
||||
from .diagnostic_open import _target_frame, _pending_prompt
|
||||
windows=_legacy_diagnostic_windows(dict(row,cleanup_desktop=proof['job']['desktop']))
|
||||
frame=_target_frame(windows,Path(proof['job']['pcb']).stem,require_ready=False)
|
||||
if frame is None:return waiting
|
||||
for window in windows:
|
||||
_pending_prompt([window],closing=proof['closed_frame'] is not None,frame=frame,
|
||||
pcb_name=Path(proof['job']['pcb']).name)
|
||||
if _cancelled_diagnostic_record(row)!=proof or stop is not None and stop.is_set():return waiting
|
||||
deadline=time.monotonic()+30
|
||||
record['retained_startup_cleanup']=dict(operation_id=proof['operation_id'],
|
||||
pcb_pid=row['pid'],owner_pid=os.getpid(),state='CLAIMED',closed_frame=proof['closed_frame'],
|
||||
deadline_monotonic=deadline,identity={k:row[k] for k in ('created_handle','image','owner_sid','session_id')})
|
||||
write_session_record(path,record) # Durable before No/Close; never removed or retried.
|
||||
with native_phase(read_only=True):
|
||||
return _close_registered_startup(row,handle,proof,stop=stop,deadline=deadline)
|
||||
except (OSError,ValueError,RuntimeError):
|
||||
return waiting
|
||||
finally:
|
||||
if acquired:win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
|
||||
|
||||
def resume_cancelled_startup(path, *, stop=None):
|
||||
"""Observer-only entry for one late loaded, positively proved ordinary cancel."""
|
||||
from .session_record import _session
|
||||
from .failed_session import cancelled_prewrite_startup
|
||||
path=Path(path)
|
||||
try:
|
||||
session,state,identities=_session(path,path.parent)
|
||||
if 'retained_startup_cleanup' in session or stop is not None and stop.is_set():return False
|
||||
job=json.loads(path.with_name('request.json').read_text(encoding='utf-8'))
|
||||
if job.get('diagnostic_only') is not False:return False
|
||||
native=[p for p in identities if p.get('role')=='native'
|
||||
and Path(p['image']).name.casefold()=='expeditionpcb.exe']
|
||||
if len(native)!=1 or cancelled_prewrite_startup(job,native[0]['pid']) is None:return False
|
||||
plan=inspect_residual_sessions(session['library'],block_names=(session['block'],))
|
||||
rows=[r for r in plan['sessions'] if r['pid']==native[0]['pid']]
|
||||
if len(rows)!=1:return False
|
||||
row=dict(rows[0],session_records=[dict(path=str(path),operation_id=session['operation_id'])])
|
||||
proof=_cancelled_diagnostic_record(row)
|
||||
if proof is None:return False # Includes exact worker/helper exit and fresh loaded logs.
|
||||
_request_close(row,stop=stop)
|
||||
return True
|
||||
except (OSError,ValueError,KeyError,TypeError,RuntimeError):
|
||||
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, result = read('request.json'), read('result.json')
|
||||
if not isinstance(job, dict) or not isinstance(result, 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()
|
||||
or result.get('safe_to_continue') is not False): return False
|
||||
operation, desktop = job['operation'], job['desktop']
|
||||
if operation == 'verify':
|
||||
facts = result.get('write_outcome') or {}
|
||||
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())
|
||||
saved_closed = (isinstance(facts, dict) and facts.get('interrupted') is False
|
||||
and all(facts.get(k) == v for k,v in (
|
||||
('save_state','COMMITTED'),('close_state','CLOSED'),('helper_state','EXITED'))))
|
||||
if (not desktop.startswith('CbbVerify_') or job.get('interactive_input') is not False
|
||||
or 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()
|
||||
or Path(job.get('root','')).resolve() != path.parent.resolve()
|
||||
or job.get('lmc_file') != job['library'] or not (failed_open or saved_closed)): 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]
|
||||
if not same_client(): return False
|
||||
target = empty_target()
|
||||
if target 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'],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 empty_target() != target or read('request.json') != job
|
||||
or read('result.json') != result or stop is not None and stop.is_set()): return False
|
||||
with native_phase(read_only=True):
|
||||
_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):
|
||||
import win32con, win32event
|
||||
with _process_handle(row['pid']) as handle:
|
||||
@@ -494,6 +942,35 @@ def _request_close(row, *, stop=None):
|
||||
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
|
||||
if error:
|
||||
return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error}
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
if proof := _cancelled_diagnostic_record(row):
|
||||
owner = _force_ownership(handle,row['pid'])
|
||||
if (owner.get('force_user_confirmed') is not True
|
||||
or any(owner.get(k) != row.get(k) for k in ('owner_sid','session_id'))):
|
||||
return {'release_status':'WAITING','detail':'取消启动会话的用户或 Windows 会话未确认'}
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status':'CANCELLED','detail':'已停止释放'}
|
||||
from .session_record import handoff_session
|
||||
record_path = Path(proof['record_path'])
|
||||
handoff_session(record_path, evidence_root=record_path.parent, observe_only=False)
|
||||
if proof['job'].get('diagnostic_only') is False:
|
||||
return _ordinary_startup_close(row,handle,proof,stop=stop)
|
||||
from .operation_queue import native_phase
|
||||
# This confirmed no-write native cleanup has its own single bounded
|
||||
# budget; metadata inactivity must not abandon it between No and Close.
|
||||
with native_phase(read_only=True):
|
||||
return _close_registered_startup(row, handle, proof, stop=stop)
|
||||
if _dismiss_startup_tip(row, handle, windows, stop=stop) is not None:
|
||||
# Legacy startup cleanup may already have sent WM_CLOSE. Only wait
|
||||
# for it here; never stack another close behind this acknowledgement.
|
||||
deadline = time.monotonic()+3
|
||||
while time.monotonic() < deadline:
|
||||
if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0:
|
||||
return {'release_status': 'RELEASED', 'detail': '已关闭启动提示并正常退出'}
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
return {'release_status': 'WAITING', 'detail': '已关闭启动提示,等待原生退出后重新检查'}
|
||||
if row['name'].casefold() == 'expeditionpcb.exe':
|
||||
from .failed_session import _startup_snapshot, _cancel_target
|
||||
for window in windows:
|
||||
@@ -560,9 +1037,11 @@ def _force_close(row, *, stop=None):
|
||||
'detail': '已强制结束客户端,工程待检查,未执行修复' if exited else '已请求结束客户端,等待退出'}
|
||||
|
||||
|
||||
def _finish_library_release(library, evidence):
|
||||
def _finish_library_release(library, evidence, block_names=(), stop=None):
|
||||
from .library_lock import release_retained_library
|
||||
return release_retained_library(library, evidence)
|
||||
return release_retained_library(library, evidence,
|
||||
block_name=block_names[0] if len(block_names) == 1 else None,
|
||||
block_names=block_names, stop=stop)
|
||||
|
||||
|
||||
def _request_native_cancel(row, *, stop=None):
|
||||
@@ -622,6 +1101,7 @@ def release_targets_complete(rows):
|
||||
|
||||
|
||||
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
|
||||
from .operation_queue import note_metadata_progress
|
||||
library = Path(plan['library']).resolve()
|
||||
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
|
||||
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
|
||||
@@ -661,6 +1141,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
||||
result['consent_path'] = str(consent_path)
|
||||
try:
|
||||
fresh = {r['pid']: r for r in query_process_snapshot()}
|
||||
note_metadata_progress()
|
||||
blocks = plan.get('block_names', ())
|
||||
roots = (tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks)
|
||||
+ (library.parent/'SymbolLibs',)) if blocks else (library.parent,)
|
||||
@@ -691,6 +1172,9 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
||||
if not save():
|
||||
return result
|
||||
try:
|
||||
if not force and not cancel_native:
|
||||
row['session_records'] = [{k:r.get(k) for k in ('path','operation_id')}
|
||||
for r in plan.get('runtime_sessions', []) if r.get('path')]
|
||||
outcome = (_request_native_cancel(row, stop=stop) if cancel_native else
|
||||
(_force_close if force else _request_close)(row, stop=stop))
|
||||
except Exception as error:
|
||||
@@ -698,7 +1182,9 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
||||
row.update(outcome)
|
||||
if not save():
|
||||
return result # Preserve completed facts; stop further actions on storage failure.
|
||||
note_metadata_progress()
|
||||
after = {r['pid']: r for r in query_process_snapshot()}
|
||||
note_metadata_progress()
|
||||
remaining_windows = _process_windows({r['pid'] for r in result['sessions']
|
||||
if r['release_status'] == 'WAITING' and r['pid'] in after})
|
||||
for row in result['sessions']:
|
||||
@@ -713,7 +1199,8 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
||||
if row.get('force_user_confirmed') is True else None),
|
||||
native_activity=native_activity(row['name'], windows, incomplete=error))
|
||||
if release_targets_complete(result['sessions']) and not (stop and stop.is_set()):
|
||||
result['proof'] = _finish_library_release(library, root/'library-proof')
|
||||
result['proof'] = _finish_library_release(library, root/'library-proof',
|
||||
blocks, stop)
|
||||
proof = result['proof']
|
||||
if (proof.get('status') != 'RELEASE_CONFIRMED'
|
||||
or Path(proof.get('library', '')).resolve() != library):
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
Option Explicit
|
||||
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK, remaining
|
||||
Dim nativeError, nativeDescription
|
||||
Dim nativeError, nativeDescription, actualProject, actualDocument, expectedDocument, savedState
|
||||
WaitForStartGate
|
||||
CheckCancellation
|
||||
expected = WScript.Arguments(0)
|
||||
@@ -79,13 +79,25 @@ If Not stable Then
|
||||
WScript.Quit 7
|
||||
End If
|
||||
WScript.Echo "POST_SAVE_SYNCHRONIZED"
|
||||
On Error Resume Next
|
||||
operationOK = doc.IsSaved() And LCase(pi.ProjectFile) = LCase(expected)
|
||||
If WScript.Arguments.Count > 1 Then operationOK = operationOK And LCase(doc.Name) = LCase(WScript.Arguments(1))
|
||||
nativeError = Err.Number
|
||||
nativeDescription = Err.Description
|
||||
Err.Clear
|
||||
On Error GoTo 0
|
||||
expectedDocument = ""
|
||||
If WScript.Arguments.Count > 1 Then expectedDocument = WScript.Arguments(1)
|
||||
For attempt = 1 To 10
|
||||
On Error Resume Next
|
||||
savedState = doc.IsSaved()
|
||||
actualProject = pi.ProjectFile
|
||||
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
|
||||
WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|identity_or_saved_state_unconfirmed|" & nativeDescription
|
||||
WScript.Quit 8
|
||||
|
||||
@@ -4,7 +4,6 @@ Unknown engineering files are primary. Only explicit runtime, history and
|
||||
generated categories are ignored by semantic comparisons; they are still copied
|
||||
and their membership/size/mtime must remain stable throughout the snapshot.
|
||||
"""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from contextlib import ExitStack
|
||||
from dataclasses import asdict, dataclass
|
||||
import hashlib
|
||||
@@ -12,6 +11,7 @@ import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import stat
|
||||
from .operation_queue import note_metadata_progress
|
||||
|
||||
|
||||
MANIFEST_VERSION = 1
|
||||
@@ -207,6 +207,7 @@ def scan_tree(root, *, scope=None, exclude=None, check=None):
|
||||
if not (stat.S_ISDIR(metadata.st_mode) or stat.S_ISREG(metadata.st_mode)):
|
||||
raise ValueError(f'不支持的特殊文件:{entry.path}')
|
||||
entries[path] = metadata
|
||||
note_metadata_progress()
|
||||
if stat.S_ISDIR(metadata.st_mode):
|
||||
folders.append(path)
|
||||
return dict(sorted(entries.items()))
|
||||
@@ -250,12 +251,13 @@ def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_functi
|
||||
files = {}
|
||||
hashed_bytes = 0
|
||||
_emit(progress, 'hash', 0, 0, total_files=len(selected))
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
for count, (relative, item) in enumerate(pool.map(hashed, selected), 1):
|
||||
files[relative] = item
|
||||
hashed_bytes += item['size']
|
||||
if count % 256 == 0 or count == len(selected):
|
||||
_emit(progress, 'hash', count, hashed_bytes, total_files=len(selected))
|
||||
# Stay on the bounded task thread: executor workers are joined at interpreter exit.
|
||||
for count, (relative, item) in enumerate(map(hashed, selected), 1):
|
||||
note_metadata_progress()
|
||||
files[relative] = item
|
||||
hashed_bytes += item['size']
|
||||
if count % 256 == 0 or count == len(selected):
|
||||
_emit(progress, 'hash', count, hashed_bytes, total_files=len(selected))
|
||||
# Check primary membership and metadata again after every hash completed.
|
||||
# Runtime files can change/add/disappear without a semantic conflict.
|
||||
after = scan_tree(root, scope=scope, exclude=exclude)
|
||||
@@ -285,6 +287,7 @@ def build_exclusive_library_manifest(root, *, scope, progress=None):
|
||||
raise OSError(f'LIBRARY_DATABASE_IN_USE: 无法独占读取 {path}:{error}') from error
|
||||
handles[path] = handle
|
||||
stack.callback(handle.Close)
|
||||
note_metadata_progress()
|
||||
|
||||
def digest(path):
|
||||
if path not in handles:
|
||||
@@ -328,7 +331,7 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
|
||||
destination.mkdir(parents=True, exist_ok=False)
|
||||
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
|
||||
from .library_lock import owned_snapshot
|
||||
# Resolve ownership on the operation thread, before parallel copy workers.
|
||||
# Resolve ownership on the operation thread before copying.
|
||||
owned = {path: data for path in files
|
||||
if path.name.endswith('.cbb-upload.lock')
|
||||
and (data := owned_snapshot(path)) is not None}
|
||||
@@ -386,16 +389,16 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
|
||||
raise OSError(f'复制期间文件变化:{path}')
|
||||
return relative.as_posix(), digest, label
|
||||
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1):
|
||||
if label is not None:
|
||||
size = entries[source/relative].st_size
|
||||
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
|
||||
hashed_count += 1
|
||||
hashed_bytes += size
|
||||
if count % 256 == 0 or count == len(files):
|
||||
_emit(progress, 'copy', hashed_count, hashed_bytes,
|
||||
copied_files=count, total_files=len(files))
|
||||
for count, (relative, digest, label) in enumerate(map(copy_file, files), 1):
|
||||
note_metadata_progress()
|
||||
if label is not None:
|
||||
size = entries[source/relative].st_size
|
||||
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
|
||||
hashed_count += 1
|
||||
hashed_bytes += size
|
||||
if count % 256 == 0 or count == len(files):
|
||||
_emit(progress, 'copy', hashed_count, hashed_bytes,
|
||||
copied_files=count, total_files=len(files))
|
||||
|
||||
def validate_bytes(relative):
|
||||
item = record[relative]
|
||||
@@ -404,8 +407,9 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
|
||||
raise OSError(f'复制期间主要文件内容变化:{path}')
|
||||
if hash_function(destination/relative) != item['sha256']:
|
||||
raise OSError(f'复制内容校验失败:{path}')
|
||||
with ThreadPoolExecutor(max_workers=8) as pool:
|
||||
list(pool.map(validate_bytes, record))
|
||||
for relative in record:
|
||||
validate_bytes(relative)
|
||||
note_metadata_progress()
|
||||
if _metadata_record(source, scan_tree(source)) != expected_metadata:
|
||||
raise OSError(f'复制期间目录内容变化:{source}')
|
||||
if _metadata_record(destination, scan_tree(destination)) != expected_metadata:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Bounded, observation-only journal for native calls that outlive a task."""
|
||||
"""Bounded registration and observation for native calls that outlive a task."""
|
||||
from contextlib import ExitStack
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
@@ -22,13 +22,30 @@ def _library_key(library):
|
||||
return os.path.normcase(os.path.normpath(str(library)))
|
||||
|
||||
|
||||
def library_available(library):
|
||||
def library_available(library, *, live_only=False):
|
||||
"""Cached queue predicate: no file, process or network queries."""
|
||||
if live_only:
|
||||
return _live_library_available(library)
|
||||
key = _library_key(library)
|
||||
with _observer_guard:
|
||||
return not any(key in aliases for aliases in _retained_libraries.values())
|
||||
|
||||
|
||||
def _live_library_available(library):
|
||||
"""Ignore stale retention, but wait for an actual registered observer."""
|
||||
key = _library_key(library)
|
||||
with _observer_guard:
|
||||
for path, aliases in _retained_libraries.items():
|
||||
observer = _observers.get(path)
|
||||
if key not in aliases or observer is None or not observer[0].is_alive():
|
||||
continue
|
||||
state = _retained_results.get(path, {})
|
||||
if (state.get('observer_initializing') is True or state.get('status') == 'ACTIVE'
|
||||
or state.get('owned_worker_alive') is True):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def retained_session_snapshot(library):
|
||||
key = _library_key(library)
|
||||
with _observer_guard:
|
||||
@@ -67,6 +84,25 @@ def acknowledge_library_release(proof, snapshot, *, block_name=None):
|
||||
_retained_results.pop(path, None)
|
||||
|
||||
|
||||
def _proof_covers_session(proof, session):
|
||||
"""A receipt may acknowledge only resources actually covered by its proof."""
|
||||
scope = proof.get('resource_scope')
|
||||
library = session.get('library')
|
||||
if (proof.get('status') != 'RELEASE_CONFIRMED' or proof.get('lease_state') != 'RELEASED'
|
||||
or not isinstance(scope, dict) or scope.get('scope_state') != 'OBSERVED'
|
||||
or not library or _library_key(proof.get('library', '')) != _library_key(library)
|
||||
or _library_key(scope.get('library', '')) != _library_key(library)):
|
||||
return False
|
||||
if proof.get('proof_scope') == 'LIBRARY':
|
||||
return not scope.get('block_names') and not proof.get('proof_block_names')
|
||||
blocks = proof.get('proof_block_names')
|
||||
observed = scope.get('block_names')
|
||||
if (proof.get('proof_scope') not in ('BLOCK', 'BLOCKS') or not isinstance(blocks, list)
|
||||
or not blocks or not isinstance(observed, list) or blocks != observed):
|
||||
return False
|
||||
return bool(session.get('block') and session['block'] in blocks)
|
||||
|
||||
|
||||
def record_session_release(proof, records):
|
||||
"""Persist a past proof only for the pre-proof operation, never replay it."""
|
||||
errors = []
|
||||
@@ -78,7 +114,8 @@ def record_session_release(proof, records):
|
||||
path = Path(record['path'])
|
||||
session = read_session_record(path, evidence_root=path.parent)
|
||||
if (session['operation_id'] != record.get('operation_id')
|
||||
or Path(session['library']).resolve() != library):
|
||||
or Path(session['library']).resolve() != library
|
||||
or not _proof_covers_session(proof, session)):
|
||||
continue
|
||||
write_session_record(path.with_name('observation-release-'+uuid4().hex+'.json'), {
|
||||
'operation_id': session['operation_id'], 'library': str(library),
|
||||
@@ -108,14 +145,47 @@ def library_wait_reason(library):
|
||||
def register_worker_session(worker, job):
|
||||
"""The launcher must persist identity before opening the worker's gate."""
|
||||
path = Path(job['session_record_path'])
|
||||
write_session_record(path, {k: job.get(k) for k in (
|
||||
'operation_id', 'operation', 'library', 'block', 'desktop', 'cancel_signal')}
|
||||
| {'processes': [{'role': 'worker', **process_identity(worker.pid)}]})
|
||||
from .operation_queue import check_worker_admission, current_context, bind_supervised_worker
|
||||
check_worker_admission(job)
|
||||
context = current_context()
|
||||
protection = ('duplicated_lease' if job.get('worker_lease_handle') else
|
||||
'worker_owned_lease' if job.get('operation') == 'native_backup' else
|
||||
'inspection_only' if job.get('inspection_only') is True else
|
||||
'catalog_readonly' if job.get('worker_role') == 'catalog_readonly'
|
||||
and job.get('operation') == 'catalog' else None)
|
||||
if context is not None and context.native_policy == 'external':
|
||||
if protection is None or worker.pid == os.getpid():
|
||||
raise RuntimeError('WORKER_OWNERSHIP_REQUIRED: 原生写入未登记独立进程和租约。')
|
||||
from .icdb_ownership import session_resource_scope
|
||||
record = ({k: job.get(k) for k in (
|
||||
'operation_id', 'operation', 'library', 'block', 'desktop', 'cancel_signal', 'worker_lease_handle',
|
||||
'worker_role', 'start_gate_protocol', 'start_gate')}
|
||||
| {'processes': [{'role': 'worker', **process_identity(worker.pid)}],
|
||||
'lease_state': 'ACTIVE', 'resource_scope': session_resource_scope(job),
|
||||
'worker_protection': protection, 'task_operation_id': context.operation_id if context else None,
|
||||
'blocked_resources': [], 'data_recovery_required': None})
|
||||
if job.get('start_gate_protocol') == 'event-v1':
|
||||
import win32api, win32con, win32event
|
||||
event = win32event.CreateEvent(None, True, False, None)
|
||||
process = getattr(worker, 'handle', None) or getattr(worker, '_handle', None)
|
||||
if process is None:
|
||||
raise RuntimeError('WORKER_ADMISSION_UNCONFIRMED: 缺少工作进程句柄。')
|
||||
# Use the launch handle, never a reopened PID. The child's event survives
|
||||
# supervisor exit even before Python startup or journal reads finish.
|
||||
remote = win32api.DuplicateHandle(win32api.GetCurrentProcess(), event,
|
||||
process, 0, False, win32con.DUPLICATE_SAME_ACCESS)
|
||||
record['worker_start_handle'] = remote.Detach()
|
||||
worker._start_event = event
|
||||
worker._start_binding = (str(path), job['operation_id'], job['start_gate'])
|
||||
write_session_record(path, record)
|
||||
bind_supervised_worker(path, record)
|
||||
worker.session_record_path = path
|
||||
worker.cbb_library = job['library']
|
||||
check_worker_admission(job) # A slow registration must not open a gate after UI shutdown.
|
||||
|
||||
|
||||
def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False, continuation=False):
|
||||
def update_worker_state(job, phase, *, identities=(), observed_identities=(), write_outcome=None,
|
||||
required=False, continuation=False):
|
||||
"""required controls I/O; only existing same-phase calls may continue recording after supervisor loss."""
|
||||
if not job.get('session_record_path'):
|
||||
if required:
|
||||
@@ -132,6 +202,12 @@ def update_worker_state(job, phase, *, identities=(), write_outcome=None, requir
|
||||
for role, pid in identities:
|
||||
if pid and not any(p['pid'] == pid for p in state['processes']):
|
||||
state['processes'].append({'role': role, **process_identity(pid)})
|
||||
# Callers supply these only after validating an open handle's exact
|
||||
# job membership; do not reopen a snapshot PID during publication.
|
||||
for role, identity in observed_identities:
|
||||
bound = {key: identity[key] for key in IDENTITY_KEYS}
|
||||
if not any(all(p.get(key) == value for key, value in bound.items()) for p in state['processes']):
|
||||
state['processes'].append({'role': role, **bound})
|
||||
state['phase'] = phase
|
||||
if write_outcome is not None:
|
||||
state['write_outcome'] = write_outcome
|
||||
@@ -230,7 +306,13 @@ def _result(status, detail='', *, session=None, state=None, proof=None):
|
||||
return {'status': status, 'detail': detail, 'library': (session or {}).get('library'),
|
||||
'block': (session or {}).get('block'),
|
||||
'operation_id': (session or {}).get('operation_id'),
|
||||
'phase': (state or {}).get('phase', 'UNCONFIRMED'), 'release_proof': proof}
|
||||
'phase': (state or {}).get('phase', 'UNCONFIRMED'), 'release_proof': proof,
|
||||
'lease_state': (proof or {}).get('lease_state', 'ACTIVE' if status == 'ACTIVE' else 'UNCONFIRMED'),
|
||||
'resource_scope': (proof or {}).get('resource_scope') or (session or {}).get('resource_scope')
|
||||
or {'scope_state': 'RECHECK_REQUIRED'},
|
||||
'blocked_resources': (proof or {}).get('blocked_resources', (session or {}).get('blocked_resources', [])),
|
||||
'data_recovery_required': (proof or {}).get('data_recovery_required',
|
||||
(session or {}).get('data_recovery_required'))}
|
||||
|
||||
|
||||
def _reconcile(path, root, handles, stack, *, release=True):
|
||||
@@ -305,15 +387,17 @@ def inspect_session_record(path, *, evidence_root):
|
||||
def observe_retained_session(path, *, evidence_root, stop=None, progress=None, process=None,
|
||||
observe_only=False):
|
||||
stop = stop if stop is not None else threading.Event()
|
||||
read_only = observe_only if callable(observe_only) else lambda: observe_only
|
||||
observation = Path(path).with_name('observation-' + uuid4().hex + '.json')
|
||||
with ExitStack() as stack:
|
||||
handles = {}
|
||||
while True:
|
||||
observation_only = read_only()
|
||||
try:
|
||||
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observe_only)
|
||||
result = _reconcile(Path(path), Path(evidence_root), handles, stack, release=not observation_only)
|
||||
except Exception as error:
|
||||
result = _result('UNCONFIRMED', str(error))
|
||||
if (not observe_only and process is not None and process.poll() is not None
|
||||
if (not observation_only and process is not None and process.poll() is not None
|
||||
and getattr(process, 'cbb_library', None)):
|
||||
try:
|
||||
from .library_lock import release_retained_library
|
||||
@@ -323,7 +407,16 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
|
||||
session={'library': str(process.cbb_library)}, proof=proof)
|
||||
except Exception:
|
||||
pass
|
||||
if result['status'] == 'IDENTITY_CHANGED' and not observe_only:
|
||||
if result['status'] == 'ACTIVE' and not observation_only and not stop.is_set():
|
||||
try:
|
||||
from .residual_sessions import resume_cancelled_startup, finish_owned_idle_session
|
||||
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
|
||||
# and independently prove the resource release as usual.
|
||||
result = _reconcile(Path(path), Path(evidence_root), handles, stack)
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning('Retained startup cleanup unavailable', exc_info=True)
|
||||
if result['status'] == 'IDENTITY_CHANGED' and not observation_only:
|
||||
try:
|
||||
from .library_lock import release_retained_library
|
||||
proof = release_retained_library(result['library'], Path(path).parent/'release-proof')
|
||||
@@ -331,6 +424,10 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
|
||||
result = {**result, 'status': 'RELEASED', 'identity_changed': True, 'release_proof': proof}
|
||||
except Exception as error:
|
||||
result['detail'] += f';资源释放待确认:{error}'
|
||||
try:
|
||||
result['owned_worker_alive'] = process is not None and process.poll() is None
|
||||
except Exception:
|
||||
result['owned_worker_alive'] = False
|
||||
try:
|
||||
write_session_record(observation, {**result, 'operation_id': result['operation_id'] or 'unknown'})
|
||||
except (OSError, ValueError):
|
||||
@@ -341,7 +438,7 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
|
||||
except Exception:
|
||||
logging.getLogger(__name__).warning('Observation callback failed', exc_info=True)
|
||||
if (result['status'] == 'RELEASED' or stop.is_set()
|
||||
or observe_only and result['status'] != 'ACTIVE'):
|
||||
or read_only() and result['status'] != 'ACTIVE'):
|
||||
return result
|
||||
if not handles and process is not None and process.poll() is None:
|
||||
stop.wait(1)
|
||||
@@ -363,33 +460,49 @@ def handoff_session(path, *, evidence_root, process=None, progress=None, stop=No
|
||||
aliases = {_library_key(library), _library_key(Path(library).resolve())} if library else set()
|
||||
with _observer_guard:
|
||||
if key in _observers:
|
||||
if (observe_only is False and session.get('operation_id')
|
||||
and _retained_results.get(key, {}).get('operation_id') == session['operation_id']):
|
||||
_retained_results[key]['release_operation_id'] = session['operation_id']
|
||||
return
|
||||
_retained_libraries[key] = aliases
|
||||
_retained_results[key] = {'status': 'UNCONFIRMED', 'phase': 'UNCONFIRMED',
|
||||
'library': str(library) if library else None, 'block': session.get('block'),
|
||||
'detail': '正在核对残留会话', 'operation_id': session.get('operation_id')}
|
||||
'detail': '正在核对残留会话', 'operation_id': session.get('operation_id'),
|
||||
'observer_initializing': True}
|
||||
def notify(value):
|
||||
with _observer_guard:
|
||||
if _retained_libraries.get(key) is aliases:
|
||||
previous = _retained_results[key]
|
||||
_retained_results[key] = {**previous, **value,
|
||||
'observer_initializing': False,
|
||||
'library': value.get('library') or previous['library'],
|
||||
'operation_id': value.get('operation_id') or previous['operation_id'],
|
||||
'block': value.get('block') or previous['block']}
|
||||
if progress is not None:
|
||||
progress(value)
|
||||
def observation_only():
|
||||
if not observe_only:
|
||||
return False
|
||||
with _observer_guard:
|
||||
value = _retained_results.get(key, {})
|
||||
return not (session.get('operation_id') and _retained_libraries.get(key) is aliases
|
||||
and value.get('operation_id') == session.get('operation_id')
|
||||
and value.get('release_operation_id') == session.get('operation_id'))
|
||||
def observe():
|
||||
result = None
|
||||
try:
|
||||
result = observe_retained_session(path, evidence_root=evidence_root, progress=notify,
|
||||
stop=stop, process=process, observe_only=observe_only)
|
||||
stop=stop, process=process, observe_only=observation_only)
|
||||
if process is not None and process.poll() is not None:
|
||||
process.close()
|
||||
return result
|
||||
finally:
|
||||
with _observer_guard:
|
||||
_observers.pop(key, None)
|
||||
if result and result['status'] == 'RELEASED':
|
||||
if _observers.get(key, (None,))[0] is threading.current_thread():
|
||||
_observers.pop(key, None)
|
||||
if (result and result['status'] == 'RELEASED'
|
||||
and _retained_libraries.get(key) is aliases
|
||||
and _retained_results.get(key, {}).get('operation_id') == session.get('operation_id')):
|
||||
_retained_libraries.pop(key, None)
|
||||
_retained_results.pop(key, None)
|
||||
thread = threading.Thread(target=observe, name='retained-native-session', daemon=True)
|
||||
@@ -420,9 +533,14 @@ def discover_sessions(evidence_root, *, library=None):
|
||||
if not (name.startswith('observation-') and name.endswith('.json')):
|
||||
continue
|
||||
observation = read_session_record(Path(folder)/name, evidence_root=root)
|
||||
proof = observation.get('release_proof') or {}
|
||||
proof = proof if isinstance(proof, dict) else {}
|
||||
session_scope = value.get('resource_scope')
|
||||
if observation['operation_id'] == value['operation_id'] and (
|
||||
observation.get('status') == 'RELEASED' and observation.get('release_proof')
|
||||
observation.get('status') == 'RELEASED'
|
||||
and _proof_covers_session(proof, value)
|
||||
or observation.get('status') == 'FINISHED'
|
||||
and isinstance(session_scope, dict) and session_scope.get('scope_state') == 'DECLARED'
|
||||
and observation.get('native_release_confirmed') is True
|
||||
and observation.get('worker_exited') is True):
|
||||
completed = True
|
||||
|
||||
@@ -2,12 +2,14 @@
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
|
||||
from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout,
|
||||
QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox)
|
||||
|
||||
from .workers import ServiceWorker
|
||||
from .backup_notice import MANUAL_BACKUP_NOTICE
|
||||
from . import timed_prompt
|
||||
from ..operation_queue import BatchTaskContext
|
||||
|
||||
|
||||
class RecoverySignals(QObject):
|
||||
@@ -27,13 +29,17 @@ class BackupRecoveryDialog(QDialog):
|
||||
self.recoverer = recoverer
|
||||
self.native_queue = None
|
||||
self.stop = Event()
|
||||
self.context = None
|
||||
self.ui_job = None
|
||||
self.admit = None
|
||||
self.setWindowModality(Qt.NonModal)
|
||||
self.busy = False
|
||||
self.pool = QThreadPool(self)
|
||||
self.pool.setMaxThreadCount(1)
|
||||
self.signals = RecoverySignals(self)
|
||||
self.signals.progress.connect(self._progress)
|
||||
if parent is not None and hasattr(parent, '_show_version_choice'):
|
||||
self.signals.choice.connect(parent._show_version_choice)
|
||||
self._choice_handler = getattr(parent, '_show_version_choice', None)
|
||||
self.signals.choice.connect(self._choice)
|
||||
self.block_combo = QComboBox()
|
||||
self.block_combo.addItems(list(names))
|
||||
self.source_edit = QLineEdit()
|
||||
@@ -46,7 +52,7 @@ class BackupRecoveryDialog(QDialog):
|
||||
self.close_button.clicked.connect(self.reject)
|
||||
self.cancel_queue_button = QPushButton('取消排队')
|
||||
self.cancel_queue_button.setEnabled(False)
|
||||
self.cancel_queue_button.clicked.connect(self.stop.set)
|
||||
self.cancel_queue_button.clicked.connect(lambda:self.stop.set())
|
||||
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。')
|
||||
self.status_label.setWordWrap(True)
|
||||
layout = QFormLayout(self)
|
||||
@@ -88,42 +94,73 @@ class BackupRecoveryDialog(QDialog):
|
||||
except Exception as error:
|
||||
self.status_label.setText(str(error))
|
||||
return
|
||||
if QMessageBox.question(self, '确认从备份恢复',
|
||||
if timed_prompt.question(self, '确认从备份恢复',
|
||||
f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{request.lmc_file}\nCBB:{name}\n来源:{source}'
|
||||
'\n\n将创建用于校验的隔离库副本,校验通过后替换目标工程。确认继续?',
|
||||
QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes:
|
||||
QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) != QMessageBox.Yes:
|
||||
return
|
||||
if self.admit is not None and not self.admit((request, source)):
|
||||
self.status_label.setText('相同任务已提交,未重复执行。')
|
||||
return
|
||||
self.busy = True
|
||||
self.stop.clear()
|
||||
self.context = BatchTaskContext(str(request.lmc_file), targets=(name,), native_policy='external')
|
||||
context = self.context
|
||||
self.stop = context.stop
|
||||
self._set_enabled(False)
|
||||
self.status_label.setText('正在准备恢复…')
|
||||
self.started.emit(name)
|
||||
def execute():
|
||||
options = {'version_prompt': self.signals.choice.emit,'stop':self.stop} if self.recoverer is None else {}
|
||||
action = lambda: recoverer(request, source, progress=self.signals.progress.emit, **options)
|
||||
if self.native_queue is None: return action()
|
||||
from ..operation_queue import QueueCancelled
|
||||
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)
|
||||
if self.native_queue is None: return context.run(action)
|
||||
from ..operation_queue import QueueCancelled, QueueUnavailable
|
||||
def restore():
|
||||
self.signals.progress.emit({'stage': 'queue_acquired'})
|
||||
self._emit(context, 'progress',{'stage': 'queue_acquired'})
|
||||
return action()
|
||||
try:
|
||||
return self.native_queue.run(restore, stop=self.stop, waiting=lambda: self.signals.progress.emit(
|
||||
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': '已排队,等待当前检查结束'}))
|
||||
except QueueCancelled as error:
|
||||
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:
|
||||
from ..operation_queue import TaskHandoff
|
||||
from ..verify_runner import VerifyResult, _handoff_verify_result
|
||||
if isinstance(error, TaskHandoff): return _handoff_verify_result(error)
|
||||
return VerifyResult('CANCELLED', stderr=str(error))
|
||||
self.worker = ServiceWorker(execute)
|
||||
self.worker.signals.succeeded.connect(lambda result: self._result(name, result))
|
||||
self.worker.signals.failed.connect(lambda error: self._failed(name, error))
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
self.worker.signals.succeeded.connect(context.guard_callback(lambda result: self._result(name, result), current=lambda:self.context))
|
||||
self.worker.signals.failed.connect(context.guard_callback(lambda error: self._failed(name, error), current=lambda:self.context))
|
||||
self.worker.signals.finished.connect(lambda:self._finished() if self.context is context else None)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _emit(self, context, signal, value):
|
||||
if context is not self.context or not self.busy or signal == 'choice' and context.stop.is_set():
|
||||
if signal == 'choice': value.choose('cancel')
|
||||
return
|
||||
try:
|
||||
delivered = context.guard_callback(lambda:getattr(self.signals, signal).emit((context,value)) or True)()
|
||||
if not delivered and signal == 'choice': value.choose('cancel')
|
||||
except RuntimeError:
|
||||
if signal == 'choice': value.choose('cancel')
|
||||
|
||||
def _choice(self, payload):
|
||||
context, choice = payload
|
||||
if context is not self.context or not self.busy or context.stop.is_set() or self._choice_handler is None:
|
||||
choice.choose('cancel')
|
||||
return
|
||||
self._choice_handler((self.ui_job,choice) if self.ui_job else choice)
|
||||
|
||||
def _set_enabled(self, enabled):
|
||||
for widget in (self.block_combo, self.source_edit, self.browse_button,
|
||||
self.restore_button, self.close_button):
|
||||
widget.setEnabled(enabled)
|
||||
|
||||
def _progress(self, event):
|
||||
if isinstance(event, tuple):
|
||||
context, event = event
|
||||
if context is not self.context or not self.busy: return
|
||||
if isinstance(event, dict):
|
||||
if event.get('stage') in ('waiting_native_slot', 'queue_acquired'):
|
||||
self.cancel_queue_button.setEnabled(event['stage'] == 'waiting_native_slot')
|
||||
@@ -159,6 +196,7 @@ class BackupRecoveryDialog(QDialog):
|
||||
|
||||
def closeEvent(self, event):
|
||||
if self.busy:
|
||||
self.stop.set()
|
||||
event.ignore()
|
||||
else:
|
||||
super().closeEvent(event)
|
||||
@@ -1,8 +1,7 @@
|
||||
"""A check batch owns its snapshot and yields the native queue after each CBB."""
|
||||
from threading import Event
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal
|
||||
from .workers import ServiceWorker
|
||||
from ..operation_queue import QueueCancelled
|
||||
from ..operation_queue import QueueCancelled, QueueUnavailable, BatchTaskContext, request_library_keys
|
||||
from ..verify_runner import VerifyResult, run_verify, write_batch_report
|
||||
from ..icdb_maintenance import write_maintenance_report
|
||||
|
||||
@@ -12,14 +11,18 @@ class IcdbCheckTask(QObject):
|
||||
item_done = Signal(str, object)
|
||||
finished = Signal(object)
|
||||
|
||||
def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None):
|
||||
def __init__(self, requests, queue, report_root, *, verifier=None, path_lease=None, parent=None, status_reader=None, choice_prompt=None):
|
||||
super().__init__(parent)
|
||||
self.requests = tuple(requests)
|
||||
self.queue, self.report_root = queue, report_root
|
||||
self.path_lease = path_lease
|
||||
self.verifier = verifier or (lambda req: run_verify(req, progress=self.event.emit, stop=self.stop))
|
||||
self.context = BatchTaskContext(str(self.requests[0].lmc_file),
|
||||
targets=tuple(r.block_name for r in self.requests), native_policy='external')
|
||||
self.status_reader = status_reader
|
||||
self.verifier = verifier or (lambda req: run_verify(req, progress=self._emit_event,
|
||||
stop=self.stop, version_prompt=choice_prompt))
|
||||
self.results = []
|
||||
self.stop = Event()
|
||||
self.stop = self.context.stop
|
||||
self.active = False
|
||||
self.paused = False
|
||||
self.invalidated = set()
|
||||
@@ -27,9 +30,15 @@ class IcdbCheckTask(QObject):
|
||||
self.running = False
|
||||
self.report = None
|
||||
self.report_error = ''
|
||||
self.retained_libraries = set()
|
||||
self.retained_libraries = {}
|
||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
||||
|
||||
def _emit_event(self, event):
|
||||
try:
|
||||
self.context.guard_callback(self.event.emit)(event)
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
def start(self):
|
||||
self.active = True
|
||||
self._next()
|
||||
@@ -57,9 +66,6 @@ class IcdbCheckTask(QObject):
|
||||
if self.stop.is_set():
|
||||
self.results.extend(VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
||||
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):
|
||||
self._report(); return
|
||||
if self.paused: return
|
||||
@@ -67,24 +73,48 @@ class IcdbCheckTask(QObject):
|
||||
def check():
|
||||
from ..session_record import library_available, library_wait_reason
|
||||
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():
|
||||
if self.status_reader is not None:
|
||||
statuses = self.status_reader((request.block_name,), request.lmc_file)
|
||||
self.update_statuses(statuses)
|
||||
if statuses.get(request.block_name) == 'NOT_REGISTERED':
|
||||
return VerifyResult('SKIPPED', stderr='仅发现目录,原生目录未登记此 CBB。')
|
||||
if request.block_name in self.ready_names:
|
||||
return VerifyResult('SKIPPED', stderr='工程已为 READY,跳过 ICDB 检查。')
|
||||
if request.block_name in self.invalidated:
|
||||
return VerifyResult('SKIPPED', stderr='目标已有后续管理操作,请重新检查。')
|
||||
self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name})
|
||||
self._emit_event({'stage': 'icdb_check_start', 'block': request.block_name})
|
||||
result = self.verifier(request)
|
||||
if not result.safe_to_continue:
|
||||
from ..operation_lifecycle import recheck_failed_release
|
||||
result = recheck_failed_release(request.lmc_file, request.block_name, result)
|
||||
return result
|
||||
return self.queue.run(execute, stop=self.stop,
|
||||
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)),
|
||||
ready=lambda: not self.paused and library_available(request.lmc_file),
|
||||
waiting=lambda: self.event.emit({'stage': 'waiting_native_slot', 'block': request.block_name,
|
||||
ready=lambda: not self.paused,
|
||||
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),
|
||||
'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:
|
||||
from ..operation_queue import TaskHandoff
|
||||
from ..verify_runner import _handoff_verify_result
|
||||
if isinstance(error, TaskHandoff): return _handoff_verify_result(error)
|
||||
return VerifyResult('CANCELLED', stderr=str(error))
|
||||
except Exception as error:
|
||||
return VerifyResult('FAIL', stderr=str(error), safe_to_continue=False,
|
||||
@@ -99,7 +129,8 @@ class IcdbCheckTask(QObject):
|
||||
request = self.requests[len(self.results)]
|
||||
name = request.block_name
|
||||
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)
|
||||
if result.status in ('CANCELLED', 'QUEUE_STOP'): self.stop.set()
|
||||
self.item_done.emit(name, result)
|
||||
@@ -117,7 +148,12 @@ class IcdbCheckTask(QObject):
|
||||
return report, ''
|
||||
except Exception as error:
|
||||
return None, str(error)
|
||||
self.worker = ServiceWorker(write)
|
||||
def bounded_write():
|
||||
try:
|
||||
return BatchTaskContext(str(self.requests[0].lmc_file)).run(write, metadata_only=True)
|
||||
except Exception as error:
|
||||
return None, str(error)
|
||||
self.worker = ServiceWorker(bounded_write)
|
||||
self.worker.signals.succeeded.connect(self._report_ready)
|
||||
self.worker.signals.finished.connect(self._complete)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,15 +1,17 @@
|
||||
"""Explicit preview and asynchronous, checkpointed CBB management batch."""
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
|
||||
from PySide6.QtWidgets import (QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLabel,
|
||||
QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout)
|
||||
from shiboken6 import isValid
|
||||
|
||||
from .workers import ServiceWorker
|
||||
from .backup_notice import MANUAL_BACKUP_NOTICE
|
||||
from . import timed_prompt
|
||||
from ..management import run_management_batch
|
||||
from ..operation_queue import BatchTaskContext
|
||||
|
||||
RESULT_LABELS = {
|
||||
'REMOVED': '已移除', 'UPLOADED': '已上传 / 未自动校验',
|
||||
@@ -58,12 +60,16 @@ class ManagementDialog(QDialog):
|
||||
evidence_dir=self.template.evidence_dir.parent/'reimport-recovery', **kwargs)
|
||||
self.busy = False
|
||||
self.executed = False
|
||||
self.stop = Event()
|
||||
self.context = BatchTaskContext(str(self.template.library), native_policy='external')
|
||||
self.stop = self.context.stop
|
||||
self.ui_job = None
|
||||
self.admit = None
|
||||
self.setWindowModality(Qt.NonModal)
|
||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
|
||||
self.signals = ManagementSignals(self)
|
||||
self.signals.progress.connect(self._progress)
|
||||
if parent is not None and hasattr(parent, '_show_version_choice'):
|
||||
self.signals.choice.connect(parent._show_version_choice)
|
||||
self._choice_handler = getattr(parent, '_show_version_choice', None)
|
||||
self.signals.choice.connect(self._choice)
|
||||
self.setWindowTitle({'add': '新增 CBB', 'update': '同名更新 CBB', 'remove': '移除 CBB'}[self.operation])
|
||||
self.resize(850, 450)
|
||||
self.table = QTableWidget(0, 4)
|
||||
@@ -95,7 +101,7 @@ class ManagementDialog(QDialog):
|
||||
self.execute_button = QPushButton('预览并确认执行…')
|
||||
self.execute_button.clicked.connect(self._execute)
|
||||
self.stop_button = QPushButton('当前项结束后停止'); self.stop_button.setEnabled(False)
|
||||
self.stop_button.clicked.connect(self.stop.set)
|
||||
self.stop_button.clicked.connect(lambda:self.context.stop_after_current.set())
|
||||
self.close_button = QPushButton('关闭'); self.close_button.clicked.connect(self.reject)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addWidget(QLabel(f'目标库:{self.template.library}'))
|
||||
@@ -151,10 +157,13 @@ class ManagementDialog(QDialog):
|
||||
try:
|
||||
if not requests:
|
||||
raise ValueError('请先选择来源工程。')
|
||||
if hasattr(self.adapter, 'validate_source'):
|
||||
for request in requests:
|
||||
self.adapter.validate_source(request, probe_files=False)
|
||||
# Per-item input errors belong in batch results, so valid rows still run.
|
||||
if len({(r.partition.casefold(), r.name.casefold()) for r in requests}) != len(requests):
|
||||
raise ValueError('批次包含重复目标名称。')
|
||||
except ValueError as error:
|
||||
except (OSError, ValueError) as error:
|
||||
self.status_label.setText(str(error)); return
|
||||
preview = '\n'.join(f'{r.partition} / {r.name}' + (f' ← {r.source}' if r.source else '') for r in requests)
|
||||
description = ('同名更新会原生移除并重新导入;导入失败需要使用手动备份恢复。' if self.operation == 'update'
|
||||
@@ -163,50 +172,79 @@ class ManagementDialog(QDialog):
|
||||
if self.recovery_from:
|
||||
description = ('将用所选副本替换这些 CBB。操作会先移除原条目,再导入副本;'
|
||||
'导入失败时需要用备份恢复。请确认副本版本。')
|
||||
answer = QMessageBox.question(self, '确认管理操作',
|
||||
answer = timed_prompt.question(self, '确认管理操作',
|
||||
f'{MANUAL_BACKUP_NOTICE}\n{description}\n\n目标库:{self.template.library}\n{preview}\n\n'
|
||||
'确认继续执行?', QMessageBox.Yes | QMessageBox.No,
|
||||
QMessageBox.No)
|
||||
QMessageBox.Yes)
|
||||
if answer != QMessageBox.Yes:
|
||||
return
|
||||
requests = [replace(request, check_previous_release=True) for request in requests]
|
||||
if self.admit is not None and not self.admit(tuple(requests)):
|
||||
self.status_label.setText('相同任务已提交,未重复执行。')
|
||||
return
|
||||
self.context = BatchTaskContext(str(self.template.library), targets=tuple(r.name for r in requests), native_policy='external')
|
||||
context = self.context
|
||||
self.stop = context.stop
|
||||
self.busy = True; self.executed = True
|
||||
self._enabled(False)
|
||||
self.before_execute.emit([r.name for r in requests])
|
||||
def execute():
|
||||
choices={'version_prompt':self.signals.choice.emit} if self.runner is run_management_batch or self.recovery_from else {}
|
||||
action = lambda: self.runner(requests, adapter=self.adapter, stop=self.stop,
|
||||
progress=self.signals.progress.emit,**choices)
|
||||
if self.native_queue is None: return action()
|
||||
from ..operation_queue import QueueCancelled
|
||||
choices={'version_prompt':lambda choice:self._emit(context, 'choice',choice)} if self.runner is run_management_batch or self.recovery_from else {}
|
||||
action = lambda: self.runner(requests, adapter=self.adapter, stop=context.stop,
|
||||
progress=lambda event:self._emit(context, 'progress',event),**choices)
|
||||
if self.native_queue is None: return context.run(action)
|
||||
from ..operation_queue import QueueCancelled, QueueUnavailable
|
||||
from ..session_record import library_available, library_wait_reason
|
||||
try:
|
||||
if self.runner is run_management_batch:
|
||||
def item(request, action):
|
||||
return self.native_queue.run(action, stop=self.stop,
|
||||
ready=lambda: library_available(request.library),
|
||||
return self.native_queue.run(action, stop=context.stop, context=context, skip_unavailable=True,
|
||||
wait_state=lambda: library_wait_reason(request.library),
|
||||
waiting=lambda: self.signals.progress.emit({'stage': 'waiting_native_slot',
|
||||
waiting=lambda: self._emit(context, 'progress',{'stage': 'waiting_native_slot',
|
||||
'retained': not library_available(request.library),
|
||||
'detail': library_wait_reason(request.library) or '已排队,等待当前原生操作结束'}))
|
||||
return self.runner(requests, adapter=self.adapter, stop=self.stop,
|
||||
progress=self.signals.progress.emit, item_executor=item,
|
||||
version_prompt=self.signals.choice.emit)
|
||||
return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit(
|
||||
return self.runner(requests, adapter=self.adapter, stop=context.stop,
|
||||
progress=lambda event:self._emit(context, 'progress',event), item_executor=item,
|
||||
version_prompt=lambda choice:self._emit(context, 'choice',choice), context=context)
|
||||
return self.native_queue.run(action, stop=context.stop, context=context, skip_unavailable=True, waiting=lambda: self._emit(context, 'progress',
|
||||
{'stage': 'waiting_native_slot',
|
||||
'retained': not library_available(self.template.library),
|
||||
'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}),
|
||||
ready=lambda: library_available(self.template.library),
|
||||
wait_state=lambda: library_wait_reason(self.template.library))
|
||||
except QueueCancelled as error:
|
||||
except QueueUnavailable as error:
|
||||
from ..management import ManagementResult
|
||||
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
|
||||
'complete', 'BLOCKED', True, str(error)) for r in requests]
|
||||
'admission', 'SKIPPED', True, str(error)) for r in requests]
|
||||
except QueueCancelled as error:
|
||||
from ..operation_queue import TaskHandoff
|
||||
from ..management import ManagementResult
|
||||
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
|
||||
'complete', 'RECOVERY_REQUIRED' if isinstance(error,TaskHandoff) else 'CANCELLED',
|
||||
not isinstance(error,TaskHandoff), str(error)) for r in requests]
|
||||
self.worker = ServiceWorker(execute)
|
||||
self.worker.signals.succeeded.connect(self._result)
|
||||
self.worker.signals.failed.connect(self._failed)
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
current = lambda: self.context if isValid(self) else None
|
||||
self.worker.signals.succeeded.connect(context.guard_callback(self._result, current=current))
|
||||
self.worker.signals.failed.connect(context.guard_callback(self._failed, current=current))
|
||||
self.worker.signals.finished.connect(lambda:self._finished() if current() is context else None)
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _emit(self, context, signal, value):
|
||||
if context is not self.context or not self.busy or signal == 'choice' and context.stop.is_set():
|
||||
if signal == 'choice': value.choose('cancel')
|
||||
return
|
||||
try:
|
||||
delivered = context.guard_callback(lambda:getattr(self.signals, signal).emit((context,value)) or True)()
|
||||
if not delivered and signal == 'choice': value.choose('cancel')
|
||||
except RuntimeError:
|
||||
if signal == 'choice': value.choose('cancel')
|
||||
|
||||
def _choice(self, payload):
|
||||
context, choice = payload
|
||||
if context is not self.context or not self.busy or context.stop.is_set() or self._choice_handler is None:
|
||||
choice.choose('cancel')
|
||||
return
|
||||
self._choice_handler((self.ui_job,choice) if self.ui_job else choice)
|
||||
|
||||
def _enabled(self, enabled):
|
||||
for widget in (self.table, self.sources_button, self.auto_verify, self.close_button):
|
||||
widget.setEnabled(enabled)
|
||||
@@ -214,6 +252,9 @@ class ManagementDialog(QDialog):
|
||||
self.stop_button.setEnabled(not enabled)
|
||||
|
||||
def _progress(self, event):
|
||||
if isinstance(event, tuple):
|
||||
context, event = event
|
||||
if context is not self.context or not self.busy: return
|
||||
stage = str(event.get('stage', ''))
|
||||
self.release_wait_button.setVisible(stage == 'waiting_native_slot' and bool(event.get('retained')))
|
||||
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}'
|
||||
@@ -270,6 +311,6 @@ class ManagementDialog(QDialog):
|
||||
|
||||
def closeEvent(self, event):
|
||||
if self.busy:
|
||||
self.stop.set(); event.ignore()
|
||||
self.context.stop_after_current.set(); event.ignore()
|
||||
else:
|
||||
super().closeEvent(event)
|
||||
@@ -1,4 +1,5 @@
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from .timed_prompt import arm_default
|
||||
|
||||
|
||||
class PcbOpenDialog(QMessageBox):
|
||||
@@ -13,9 +14,11 @@ class PcbOpenDialog(QMessageBox):
|
||||
self.continue_button = self.addButton('确认无人使用,继续打开', QMessageBox.ActionRole)
|
||||
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
|
||||
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
|
||||
self.setDefaultButton(self.cancel_button)
|
||||
self.setDefaultButton(self.skip_button)
|
||||
self.setEscapeButton(self.cancel_button)
|
||||
self.setModal(True)
|
||||
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'))
|
||||
self.finished.connect(lambda _: choice.choose('cancel'))
|
||||
arm_default(self, self.skip_button)
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Show the native version dates without preselecting a recovery version."""
|
||||
"""Prefer the authorized last manually saved version after a visible countdown."""
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from .timed_prompt import arm_default
|
||||
|
||||
|
||||
class PcbRestoreDialog(QMessageBox):
|
||||
@@ -14,7 +15,7 @@ class PcbRestoreDialog(QMessageBox):
|
||||
'原生程序检测到上次异常退出,需要选择 PCB 恢复版本。\n'
|
||||
f'最后手动保存:{manual["date"]}\n自动保存:{auto["date"]}\n\n'
|
||||
'选择历史版本可能丢失此版本之后的修改。选择后继续校验、保存和状态确认;恢复版本仍需核对。'
|
||||
'\n取消将停止本项并保留原生现场,不自动选取版本。')
|
||||
'\n默认选择最后手动保存;该版本不可用时取消本项。')
|
||||
self.manual_button = self.addButton(f'最后手动保存({manual["date"]})', QMessageBox.ActionRole)
|
||||
self.auto_button = self.addButton(f'自动保存({auto["date"]})', QMessageBox.ActionRole)
|
||||
self.manual_button.setEnabled(manual['enabled'])
|
||||
@@ -25,7 +26,9 @@ class PcbRestoreDialog(QMessageBox):
|
||||
self.buttonClicked.connect(self._chosen)
|
||||
self.finished.connect(lambda _: choice.choose('cancel'))
|
||||
self.setModal(True)
|
||||
arm_default(self, self.manual_button if manual['enabled'] else self.cancel_button)
|
||||
|
||||
def _chosen(self, button):
|
||||
self.choice.choose('last_user_saved' if button is self.manual_button else
|
||||
'autosave' if button is self.auto_button else 'cancel')
|
||||
'autosave' if button is self.auto_button else 'cancel',
|
||||
origin=self.property('selectionOrigin') or 'user')
|
||||
@@ -2,11 +2,14 @@
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
from PySide6.QtCore import QThreadPool, Signal
|
||||
from PySide6.QtCore import QThreadPool, Signal, Qt
|
||||
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
|
||||
|
||||
from .workers import ServiceWorker
|
||||
from .timed_prompt import arm_default
|
||||
from . import timed_prompt
|
||||
from ..operation_queue import BatchTaskContext
|
||||
from ..residual_sessions import force_block_reason, release_targets_complete
|
||||
|
||||
|
||||
@@ -22,10 +25,12 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.release_finalizer = None
|
||||
self.busy = False
|
||||
self.stop = Event()
|
||||
self.context = None
|
||||
self._workers = set()
|
||||
self._refresh_after = False
|
||||
self.pool = QThreadPool(self)
|
||||
self.setWindowTitle('释放残留会话')
|
||||
self.setModal(True)
|
||||
self.setWindowModality(Qt.NonModal)
|
||||
self.resize(1040, 400)
|
||||
layout = QVBoxLayout(self)
|
||||
self.message = QLabel('正在检查当前库关联的会话…')
|
||||
@@ -63,7 +68,9 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.table.itemSelectionChanged.connect(self._update_prompt)
|
||||
self.refresh()
|
||||
|
||||
def _start(self, action, completed):
|
||||
def _start(self, action, completed, *, metadata_only=False):
|
||||
context = BatchTaskContext(str(self.library))
|
||||
self.context, self.stop = context, context.stop
|
||||
self.busy = True
|
||||
self.confirm_button.setEnabled(False)
|
||||
self.refresh_button.setEnabled(False)
|
||||
@@ -71,10 +78,12 @@ class ResidualReleaseDialog(QDialog):
|
||||
self.force_button.setEnabled(False)
|
||||
self.cancel_native_button.setEnabled(False)
|
||||
self.close_button.setText('停止释放')
|
||||
self.worker = ServiceWorker(action)
|
||||
self.worker.signals.succeeded.connect(completed)
|
||||
self.worker.signals.failed.connect(lambda error: self.message.setText(str(error)))
|
||||
self.worker.signals.finished.connect(self._finished)
|
||||
self.worker = ServiceWorker(lambda:context.run(action, metadata_only=metadata_only))
|
||||
worker = self.worker
|
||||
self._workers.add(worker)
|
||||
self.worker.signals.succeeded.connect(context.guard_callback(completed, current=lambda:self.context))
|
||||
self.worker.signals.failed.connect(context.guard_callback(lambda error: self.message.setText(str(error)), current=lambda:self.context))
|
||||
self.worker.signals.finished.connect(lambda:(self._workers.discard(worker), self._finished() if self.context is context else None))
|
||||
self.pool.start(self.worker)
|
||||
|
||||
def _finished(self):
|
||||
@@ -128,6 +137,9 @@ class ResidualReleaseDialog(QDialog):
|
||||
details.extend(c.get('text', '') for c in window.get('children', [])
|
||||
if c.get('class') == 'Static')
|
||||
box.setDetailedText('\n'.join(details))
|
||||
box.setWindowModality(Qt.NonModal)
|
||||
box.setStandardButtons(QMessageBox.Close)
|
||||
arm_default(box, box.button(QMessageBox.Close))
|
||||
box.show()
|
||||
|
||||
def cancel_native(self):
|
||||
@@ -136,13 +148,13 @@ class ResidualReleaseDialog(QDialog):
|
||||
if row < 0: return
|
||||
session = self.plan['sessions'][row]
|
||||
if not session.get('cancel_prompt'): return
|
||||
answer = QMessageBox.question(self, '请求原生取消',
|
||||
answer = timed_prompt.question(self, '请求原生取消',
|
||||
f'请求 {session["name"]} (PID {session["pid"]}) 当前显示的取消按钮?\n'
|
||||
'取消后的工程状态仍需核对;不会强制结束进程。',
|
||||
QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
|
||||
QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
|
||||
if answer != QMessageBox.Yes: return
|
||||
from cbb_refresh_verify.residual_sessions import request_native_cancel
|
||||
self.before_release.emit(); self.stop.clear()
|
||||
self.before_release.emit(); self.stop = Event()
|
||||
def execute():
|
||||
action = lambda: self._finalize_release_result(
|
||||
request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop))
|
||||
@@ -187,9 +199,9 @@ class ResidualReleaseDialog(QDialog):
|
||||
session = self.plan['sessions'][row]
|
||||
prompt = session.get('prompt')
|
||||
if not prompt: return
|
||||
choice = QMessageBox.question(self, '关闭工程前保存', prompt['text']+
|
||||
choice = timed_prompt.question(self, '关闭工程前保存', prompt['text']+
|
||||
'\n\n是:保存后关闭;否:放弃未保存更改;取消:保留会话。',
|
||||
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Cancel)
|
||||
QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel, QMessageBox.Yes)
|
||||
code = {QMessageBox.Yes: 6, QMessageBox.No: 7, QMessageBox.Cancel: 2}[choice]
|
||||
from cbb_refresh_verify.residual_sessions import answer_save_question
|
||||
self._start(lambda: answer_save_question(session, code),
|
||||
@@ -226,14 +238,14 @@ class ResidualReleaseDialog(QDialog):
|
||||
states.update({str(Path(row['path']).absolute()).casefold(): row for row in
|
||||
discover_sessions(self.evidence_dir.parent, library=library)})
|
||||
return {**plan, 'runtime_sessions': list(states.values())}
|
||||
self._start(inspect, ready)
|
||||
self._start(inspect, ready, metadata_only=True)
|
||||
|
||||
def force_release(self):
|
||||
if self.busy or not self.plan or not self.plan['sessions']: return
|
||||
targets = [r for r in self.plan['sessions'] if not force_block_reason(r)]
|
||||
if not targets: return
|
||||
names = '\n'.join(f'{r.get("project", "")} — {r["name"]} (PID {r["pid"]})' for r in targets)
|
||||
answer = QMessageBox.warning(self, '强制结束客户端',
|
||||
answer = timed_prompt.warning(self, '强制结束客户端',
|
||||
'仅强制结束以下客户端。客户端中其他已打开工程也会退出;未保存的更改会丢失,正在写入的工程可能需要恢复。'
|
||||
'\n数据库服务器和归属未知的进程不会被强制结束。\n\n'+names+
|
||||
'\n\n仍要结束这些进程吗?', QMessageBox.Yes | QMessageBox.Cancel, QMessageBox.Cancel)
|
||||
@@ -242,7 +254,7 @@ class ResidualReleaseDialog(QDialog):
|
||||
def confirm_release(self, checked=False, *, force=False):
|
||||
if self.busy or self.plan is None: return
|
||||
from cbb_refresh_verify.library_lock import release_residual_sessions
|
||||
self.stop.clear()
|
||||
self.stop = Event()
|
||||
plan = self.plan
|
||||
self.before_release.emit()
|
||||
self.message.setText('正在逐项释放,请稍候…')
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Visible, one-shot defaults for confirmation prompts in unattended batches."""
|
||||
from math import ceil
|
||||
import logging
|
||||
|
||||
from PySide6.QtCore import QElapsedTimer, QEvent, QObject, QTimer, Slot
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
|
||||
DEFAULT_TIMEOUT_MS = 3000
|
||||
|
||||
|
||||
class _Countdown(QObject):
|
||||
def __init__(self, box, button):
|
||||
super().__init__(box)
|
||||
self.box, self.button = box, button
|
||||
self.label = button.text()
|
||||
self.duration = DEFAULT_TIMEOUT_MS
|
||||
self.elapsed = QElapsedTimer()
|
||||
self.timer = QTimer(self)
|
||||
self.timer.setInterval(50)
|
||||
self.timer.timeout.connect(self.tick)
|
||||
self.done = False
|
||||
box.setDefaultButton(button)
|
||||
box.buttonClicked.connect(self.stop)
|
||||
box.finished.connect(self.stop)
|
||||
box.installEventFilter(self)
|
||||
if box.isVisible():
|
||||
self.start()
|
||||
|
||||
@Slot()
|
||||
def start(self):
|
||||
if self.done:
|
||||
return
|
||||
self.elapsed.start()
|
||||
self.timer.start()
|
||||
self.button.setText(f'{self.label}({ceil(self.duration / 1000)} 秒)')
|
||||
|
||||
def eventFilter(self, watched, event):
|
||||
if event.type() == QEvent.Show:
|
||||
self.start()
|
||||
elif event.type() in (QEvent.Hide, QEvent.Close):
|
||||
self.timer.stop()
|
||||
return False
|
||||
|
||||
@Slot()
|
||||
def stop(self):
|
||||
self.done = True
|
||||
self.timer.stop()
|
||||
from shiboken6 import isValid
|
||||
if isValid(self.button): self.button.setText(self.label)
|
||||
|
||||
@Slot()
|
||||
def tick(self):
|
||||
if self.done or not self.box.isVisible():
|
||||
self.timer.stop()
|
||||
return
|
||||
remaining = self.duration - self.elapsed.elapsed()
|
||||
if remaining > 0:
|
||||
self.button.setText(f'{self.label}({ceil(remaining / 1000)} 秒)')
|
||||
return
|
||||
self.timer.stop()
|
||||
self.done = True
|
||||
if not self.button.isEnabled():
|
||||
self.box.setProperty('selectionOrigin', 'timeout_default')
|
||||
self.box.reject()
|
||||
return
|
||||
self.box.setProperty('selectionOrigin', 'timeout_default')
|
||||
self.button.click()
|
||||
|
||||
|
||||
def arm_default(box, button):
|
||||
countdown = _Countdown(box, button)
|
||||
box._default_countdown = countdown
|
||||
return countdown
|
||||
|
||||
|
||||
def _ask(icon, parent, title, text, buttons, default):
|
||||
box = QMessageBox(icon, title, text, buttons, parent)
|
||||
arm_default(box, box.button(default))
|
||||
try:
|
||||
result = QMessageBox.StandardButton(box.exec())
|
||||
owner = parent
|
||||
while owner is not None and getattr(owner, 'logging_context', None) is None:
|
||||
owner = owner.parentWidget()
|
||||
context = getattr(owner, 'logging_context', None)
|
||||
logger = context.logger if context is not None else logging.getLogger('cbb_refresh_verify')
|
||||
logger.info('prompt_decision title=%s result=%s origin=%s', title, result.name,
|
||||
box.property('selectionOrigin') or 'user')
|
||||
return result
|
||||
finally:
|
||||
box.deleteLater()
|
||||
|
||||
|
||||
def question(parent, title, text, buttons, default):
|
||||
return _ask(QMessageBox.Question, parent, title, text, buttons, default)
|
||||
|
||||
|
||||
def warning(parent, title, text, buttons, default):
|
||||
return _ask(QMessageBox.Warning, parent, title, text, buttons, default)
|
||||
@@ -1,4 +1,5 @@
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from .timed_prompt import arm_default
|
||||
|
||||
|
||||
class WriteOwnerDialog(QMessageBox):
|
||||
@@ -15,9 +16,11 @@ class WriteOwnerDialog(QMessageBox):
|
||||
self.continue_button = self.addButton('已确认未使用此库,继续', QMessageBox.ActionRole)
|
||||
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
|
||||
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
|
||||
self.setDefaultButton(self.cancel_button)
|
||||
self.setDefaultButton(self.skip_button)
|
||||
self.setEscapeButton(self.cancel_button)
|
||||
self.setModal(True)
|
||||
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'))
|
||||
self.finished.connect(lambda _: choice.choose('cancel'))
|
||||
arm_default(self, self.skip_button)
|
||||
@@ -230,7 +230,7 @@ def _run_process(command, timeout_seconds, cwd, *, evidence_root=None):
|
||||
return run_content_check(command, timeout_seconds, cwd, evidence_root=evidence_root)
|
||||
|
||||
|
||||
def _stop_worker(process, *, timeout=5):
|
||||
def _stop_worker(process, *, timeout=5, wait_for_native_write=True):
|
||||
"""Request stop without interrupting a possibly unreturned native call."""
|
||||
try:
|
||||
if hasattr(process, 'request_stop'):
|
||||
@@ -243,7 +243,8 @@ def _stop_worker(process, *, timeout=5):
|
||||
process.wait(timeout=timeout)
|
||||
except Exception:
|
||||
pending = getattr(process, 'native_write_pending', lambda: False)()
|
||||
if pending is not False and not getattr(process, '_stop_wait_complete', False):
|
||||
wait_required = wait_for_native_write() if callable(wait_for_native_write) else wait_for_native_write
|
||||
if wait_required and pending is not False and not getattr(process, '_stop_wait_complete', False):
|
||||
from .defaults import NATIVE_WRITE_STOP_WAIT_SECONDS
|
||||
try:
|
||||
process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout))
|
||||
@@ -412,6 +413,42 @@ def phase_for_event(event, current=None):
|
||||
return mapping.get(stage, current or DialogPhase.PCB_STARTING)
|
||||
|
||||
|
||||
def _diagnostic_close_event(job, event, target_pid):
|
||||
close_id = event.get('close_id')
|
||||
return (job.get('diagnostic_only') is True and event.get('stage') == 'diagnostic_close_requested'
|
||||
and target_pid is not None and event.get('pcb_pid') == target_pid
|
||||
and type(event.get('hwnd')) is int and event['hwnd'] > 0
|
||||
and isinstance(close_id, str) and len(close_id) == 32 and all(c in '0123456789abcdef' for c in close_id)
|
||||
and bool(job.get('operation_id')) and event.get('operation_id') == job['operation_id']
|
||||
and all(job.get(key) and event.get(key) == job[key] for key in ('project', 'pcb', 'desktop')))
|
||||
|
||||
|
||||
def _acknowledge_diagnostic_close(job, event, stop):
|
||||
from .operation_queue import check_active
|
||||
check_active()
|
||||
if stop is not None and stop.is_set() or Path(job['cancel_signal']).exists():
|
||||
raise InterruptedError('VERIFY_CANCELLED: diagnostic handoff cancelled')
|
||||
ack = Path(job['root'])/'diagnostic-close-ack.json'
|
||||
pending = ack.with_suffix('.pending')
|
||||
pending.write_text(json.dumps({key: event[key] for key in
|
||||
('pcb_pid', 'hwnd', 'operation_id', 'desktop', 'project', 'pcb', 'close_id')}), encoding='utf-8')
|
||||
check_active()
|
||||
if stop is not None and stop.is_set() or Path(job['cancel_signal']).exists():
|
||||
raise InterruptedError('VERIFY_CANCELLED: diagnostic handoff cancelled')
|
||||
pending.replace(ack)
|
||||
|
||||
|
||||
def _close_intent_after_poll(job, events, offset, target_pid):
|
||||
if not job.get('diagnostic_only') or not events.exists(): return None
|
||||
with events.open(encoding='utf-8') as stream:
|
||||
stream.seek(offset)
|
||||
for line in stream:
|
||||
try: event = json.loads(line)
|
||||
except json.JSONDecodeError: break
|
||||
if _diagnostic_close_event(job, event, target_pid): return event
|
||||
return None
|
||||
|
||||
|
||||
def classify_verify_dispatch(*, verify_invoked, invoke_returned, target_pid, observation):
|
||||
"""Classify a returned Verify command that never started its PCB.
|
||||
|
||||
@@ -545,14 +582,59 @@ def _cleanup_session_processes(root, *, lm_pid, target_pid, pcb, pcb_baseline, l
|
||||
|
||||
|
||||
def run_verify(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||
dialog_supervisor_factory=None, version_prompt=None, stop=None):
|
||||
# Cover contents checking, native work and final state reads with one
|
||||
# session-wide mutex. The worker-stage lock below is reentrant on Windows.
|
||||
import win32event, win32con
|
||||
dialog_supervisor_factory=None, version_prompt=None, stop=None, context=None,
|
||||
admission_timeout_seconds=10):
|
||||
from .operation_queue import BatchTaskContext, TaskHandoff, current_context, task_stop
|
||||
if stop is not None and stop.is_set() or context is not None and context.stop.is_set():
|
||||
return VerifyResult('CANCELLED', stderr='已取消,未启动原生操作。', safe_to_continue=True)
|
||||
options = dict(progress=progress, flag_reader=flag_reader, process_runner=process_runner,
|
||||
port_check=port_check, dialog_supervisor_factory=dialog_supervisor_factory,
|
||||
version_prompt=version_prompt)
|
||||
bound = current_context()
|
||||
if bound is None:
|
||||
# Management may call Verify while holding a same-thread lease. Do not
|
||||
# transfer that transaction to a different thread.
|
||||
import threading
|
||||
from .library_lock import _guard, _owners
|
||||
with _guard:
|
||||
nested = any(v['thread'] == threading.get_ident() and v['depth'] > 0
|
||||
for v in _owners.values())
|
||||
if not nested:
|
||||
from .operation_queue import request_library_keys
|
||||
bound = context or BatchTaskContext(library=str(request.lmc_file),
|
||||
aliases=tuple(sorted(request_library_keys(request))), targets=(request.block_name,))
|
||||
try:
|
||||
return bound.run(lambda: run_verify(request, stop=stop, **options),
|
||||
stop=stop, timeout_seconds=admission_timeout_seconds)
|
||||
except TaskHandoff as error:
|
||||
result = _handoff_verify_result(error)
|
||||
_notify_progress(bound.guard_callback(progress) if progress else None,
|
||||
dict(stage='task_handoff', operation_id=bound.operation_id,
|
||||
library=bound.library, status=result.status, resource_scope=error.scope))
|
||||
return result
|
||||
if bound is not None and progress is not None:
|
||||
options['progress'] = bound.guard_callback(progress)
|
||||
return _run_verify_task(request, stop=task_stop(stop), **options)
|
||||
|
||||
|
||||
def _handoff_verify_result(error):
|
||||
known = error.result if isinstance(error.result, VerifyResult) else None
|
||||
result = known or VerifyResult('CANCELLED' if error.cancelled else 'TIMEOUT')
|
||||
return replace(result, status='FAIL' if result.status == 'PASS' else result.status,
|
||||
stderr=result.stderr or str(error), safe_to_continue=False,
|
||||
error_stage=result.error_stage or 'admission_or_finalization',
|
||||
error_category=result.error_category or 'TASK_HANDOFF',
|
||||
release_proof=dict(lease_state='PENDING', resource_scope=error.scope,
|
||||
blocked_resources=error.scope.get('resources', [])))
|
||||
|
||||
|
||||
def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner=None, port_check=None,
|
||||
dialog_supervisor_factory=None, version_prompt=None, stop=None):
|
||||
# Admission/finalization keep only the library lease. Native launch paths
|
||||
# acquire the host channel after slow metadata has returned.
|
||||
from .operation_queue import check_active
|
||||
from .com_runtime import initialize_com, uninitialize_com
|
||||
initialized = initialize_com()
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
library_lock = None
|
||||
previous_release = None
|
||||
release_confirmed = True
|
||||
@@ -563,11 +645,7 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
from .library_lock import _supervisor_alive
|
||||
return bool(remaining_clients) and not any(_supervisor_alive(pid) for pid in remaining_clients)
|
||||
try:
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
if not acquired:
|
||||
return VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行,请等待结束。',
|
||||
safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY')
|
||||
check_active()
|
||||
if request.maintenance:
|
||||
from .maintenance_entry import run_icdb_check
|
||||
return run_icdb_check(request, progress=progress, stop=stop)
|
||||
@@ -576,10 +654,13 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
if Path(request.lmc_file).is_file():
|
||||
try:
|
||||
previous_release = recheck_previous_release(request.lmc_file,
|
||||
Path(request.evidence_dir)/'previous-release', block_name=request.block_name, progress=progress)
|
||||
library_lock = LibraryLock(request.lmc_file, checkpoint=False,
|
||||
Path(request.evidence_dir)/'previous-release', block_name=request.block_name,
|
||||
progress=progress, stop=stop)
|
||||
check_active()
|
||||
library_lock = LibraryLock(request.lmc_file, checkpoint=False, block_name=request.block_name,
|
||||
safe_to_release=clients_released)
|
||||
library_lock.__enter__()
|
||||
check_active()
|
||||
except LibraryBusy as error:
|
||||
return VerifyResult('FAIL', stderr=str(error), error_category='LIBRARY_IN_USE')
|
||||
except (OSError, ValueError, RuntimeError, pywintypes.error) as error:
|
||||
@@ -589,6 +670,46 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
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)
|
||||
facts = result.write_outcome or {}
|
||||
if (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'}
|
||||
and result.error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
and result.evidence_path):
|
||||
@@ -691,14 +812,12 @@ def run_verify(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
if library_lock is not None:
|
||||
library_lock.__exit__(None, None, None)
|
||||
finally:
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
uninitialize_com(initialized)
|
||||
|
||||
|
||||
def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_runner=None,
|
||||
port_check=None, dialog_supervisor_factory=None, version_prompt=None, stop=None):
|
||||
from .operation_queue import remember_result
|
||||
timing = RunTimings()
|
||||
result = _run_verify(request, timing=timing, progress=progress, flag_reader=flag_reader,
|
||||
process_runner=process_runner, port_check=port_check,
|
||||
@@ -722,6 +841,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
result = replace(result, status='FAIL', stderr='原生会话或自动化客户端尚未退出。')
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
remember_result(result)
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP', 'CANCELLED'} and result.evidence_path:
|
||||
job_path = result.evidence_path.with_name('request.json')
|
||||
if job_path.is_file():
|
||||
@@ -735,13 +855,13 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
finally:
|
||||
timing.end('failure_diagnostics')
|
||||
if result.status not in {'PASS', 'SKIPPED', 'QUEUE_STOP'}:
|
||||
from .icdb_recovery import ERROR_CODE, RECOVERY_ACTION, parse_session_loss, recovery_detail
|
||||
recovery = parse_session_loss(result.stderr)
|
||||
from .icdb_recovery import ERROR_CODE, RECOVERY_ACTION, parse_recovery_request, recovery_detail
|
||||
recovery = parse_recovery_request(result.stderr)
|
||||
if recovery is None and result.evidence_path:
|
||||
try:
|
||||
saved = json.loads(result.evidence_path.with_name('diagnostics').joinpath(
|
||||
'icdb-recovery.json').read_text('utf-8'))
|
||||
recovery = parse_session_loss(saved.get('native_message', ''))
|
||||
recovery = parse_recovery_request(saved.get('native_message', ''))
|
||||
except (OSError, ValueError, AttributeError):
|
||||
pass
|
||||
if recovery or ERROR_CODE.casefold() in result.stderr.casefold():
|
||||
@@ -764,6 +884,7 @@ def _run_verify_serialized(request, *, progress=None, flag_reader=None, process_
|
||||
if result.status not in {"PASS", "SKIPPED"} else ""),
|
||||
error_stage=(result.error_stage or (unfinished[-1] if unfinished else 'execution')
|
||||
if result.status not in {"PASS", "SKIPPED"} else ""))
|
||||
remember_result(result)
|
||||
if result.evidence_path:
|
||||
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
|
||||
_write_optional_evidence(result.evidence_path.with_name('performance.json'), {
|
||||
@@ -819,7 +940,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
except Exception:
|
||||
# Cleanup must never hide or change the verification result.
|
||||
pass
|
||||
return replace(result, evidence_path=result_path)
|
||||
from .operation_queue import remember_result
|
||||
return remember_result(replace(result, evidence_path=result_path))
|
||||
|
||||
if stop is not None and stop.is_set():
|
||||
return finish(VerifyResult('CANCELLED', stderr='已取消,未启动校验。'))
|
||||
@@ -843,7 +965,9 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'detail': ' '.join(command)})
|
||||
timing.begin('content_check')
|
||||
try:
|
||||
exit_code, stdout, stderr, timed_out = runner(command, request.timeout_seconds, Path(request.lmc_file).parent)
|
||||
from .operation_queue import native_channel
|
||||
with native_channel(read_only=True):
|
||||
exit_code, stdout, stderr, timed_out = runner(command, request.timeout_seconds, Path(request.lmc_file).parent)
|
||||
finally:
|
||||
timing.end('content_check')
|
||||
combined = '\n'.join(part for part in (stdout, stderr) if part)
|
||||
@@ -886,7 +1010,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'cancel_signal': str(root/'cancel-worker.signal'),
|
||||
'start_gate': str(root/'start-worker.signal')}
|
||||
job.update(operation_id=root.name, operation='verify', library=str(request.lmc_file),
|
||||
block=request.block_name, session_record_path=str(root/'session.json'))
|
||||
block=request.block_name, session_record_path=str(root/'session.json'), start_gate_protocol='event-v1')
|
||||
from .session_record import process_identity
|
||||
job['supervisor_identity'] = process_identity(os.getpid())
|
||||
consent = None
|
||||
@@ -902,11 +1026,22 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
except Exception as error:
|
||||
return finish(VerifyResult('FAIL', stderr=str(error)))
|
||||
events = root/'events.jsonl'
|
||||
prewrite_eligible = not (request.diagnostic_only or request.interactive_input or request.native_lm_verify or consent)
|
||||
def startup_phase(stage,**facts):
|
||||
record={k:job[k] for k in ('operation_id','project','pcb','desktop')}
|
||||
with events.open('a',encoding='utf-8') as stream:
|
||||
stream.write(json.dumps(dict(stage=stage,**record,**facts))+'\n')
|
||||
def before_dialog_action(snapshot,action):
|
||||
name=action.get('action') if isinstance(action,dict) else action
|
||||
if name not in ('dismiss_tip','accept_license','decline_database_log'):
|
||||
startup_phase('startup_supervisor_write_possible',action=name,pid=snapshot.pid,hwnd=snapshot.hwnd)
|
||||
offset = 0
|
||||
target_pid = None
|
||||
diagnostic_closing = False
|
||||
launcher_pid = None
|
||||
lm_pid = None
|
||||
verify_invoked = False
|
||||
lm_dispatch_deadline = None
|
||||
invoke_returned = False
|
||||
pcb_baseline = set()
|
||||
last_observation = 0.0
|
||||
@@ -915,17 +1050,21 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
from .desktop_worker import DesktopWorker
|
||||
from .dialog_supervisor import AgentDialogBackend, DialogSupervisor, Win32DialogBackend
|
||||
from .dialog_models import DialogPhase
|
||||
import win32event, win32con
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
lock_status = win32event.WaitForSingleObject(mutex, 0)
|
||||
if lock_status not in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED):
|
||||
mutex.Close()
|
||||
return finish(VerifyResult('BLOCKED', stderr='已有 CBB 校验任务运行;本次未启动。',
|
||||
safe_to_continue=True, error_category='NATIVE_CHANNEL_BUSY'))
|
||||
from .operation_queue import TaskHandoff, check_active, native_channel
|
||||
check_active()
|
||||
worker_launch_attempted = False
|
||||
native = native_channel()
|
||||
phase_entered = False
|
||||
def end_native_phase():
|
||||
nonlocal phase_entered
|
||||
if phase_entered:
|
||||
native.__exit__(None, None, None)
|
||||
phase_entered = False
|
||||
try:
|
||||
if prewrite_eligible:startup_phase('startup_supervisor_no_write')
|
||||
timing.begin('worker_setup')
|
||||
with (root/'worker.log').open('w', encoding='utf-8') as log:
|
||||
check_active()
|
||||
worker_launch_attempted = True
|
||||
if request.interactive_input:
|
||||
process = DesktopWorker(
|
||||
@@ -949,14 +1088,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
from .dialog_rules import default_rules_path, load_rules
|
||||
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop)
|
||||
dialog_supervisor = DialogSupervisor(
|
||||
AgentDialogBackend(dialog_agent, pids=lambda: {
|
||||
AgentDialogBackend(dialog_agent, before_action=before_dialog_action if prewrite_eligible else None, pids=lambda: {
|
||||
int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}),
|
||||
rules=load_rules(default_rules_path()),
|
||||
rules=load_rules(default_rules_path(), diagnostic_only=request.diagnostic_only),
|
||||
)
|
||||
else:
|
||||
dialog_supervisor = DialogSupervisor(Win32DialogBackend(
|
||||
lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
|
||||
desktop=process.desktop,
|
||||
desktop=process.desktop,before_action=before_dialog_action if prewrite_eligible else None,
|
||||
))
|
||||
else:
|
||||
dialog_supervisor = dialog_supervisor_factory(
|
||||
@@ -965,7 +1104,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
)
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('VERIFY_CANCELLED: 启动已取消,未启动 PCB')
|
||||
Path(job['start_gate']).touch()
|
||||
check_active()
|
||||
try:
|
||||
native.__enter__()
|
||||
phase_entered = True
|
||||
except RuntimeError as error:
|
||||
return finish(VerifyResult('BLOCKED', stderr=str(error), safe_to_continue=False,
|
||||
error_category='NATIVE_CHANNEL_BUSY'))
|
||||
from .operation_queue import commit_worker_start
|
||||
commit_worker_start(process, job)
|
||||
while process.poll() is None:
|
||||
if stop is not None and stop.is_set():
|
||||
save_markers = timing._save_markers
|
||||
@@ -974,7 +1121,9 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'已请求停止,等待当前原生操作返回')
|
||||
_notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name,
|
||||
'detail': detail})
|
||||
_stop_worker(process)
|
||||
from .failed_session import cancelled_prewrite_startup
|
||||
_stop_worker(process, wait_for_native_write=False if request.diagnostic_only else
|
||||
lambda:cancelled_prewrite_startup(job,target_pid) is None)
|
||||
return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
|
||||
safe_to_continue=False, error_stage=phase.value))
|
||||
if events.exists():
|
||||
@@ -986,10 +1135,16 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
except json.JSONDecodeError:
|
||||
break
|
||||
timing.record(event)
|
||||
if _diagnostic_close_event(job, event, target_pid):
|
||||
_acknowledge_diagnostic_close(job, event, stop)
|
||||
diagnostic_closing = True
|
||||
if event.get('pcb_pid'): target_pid = event['pcb_pid']
|
||||
if event.get('launcher_pid'): launcher_pid = event['launcher_pid']
|
||||
if event.get('lm_pid'): lm_pid = event['lm_pid']
|
||||
stage = event.get('stage')
|
||||
if stage == 'lm_launch' and lm_dispatch_deadline is None:
|
||||
from .mentor_adapter import lm_dispatch_timeout_seconds
|
||||
lm_dispatch_deadline = (event.get('monotonic_seconds') or time.monotonic()) + lm_dispatch_timeout_seconds(request.timeout_seconds)
|
||||
if stage == 'verify_invoke': verify_invoked = True
|
||||
if stage == 'verify_invoke_returned': invoke_returned = True
|
||||
if stage == 'pcb_baseline': pcb_baseline = set(event.get('pids', ()))
|
||||
@@ -1021,7 +1176,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
except Exception as error:
|
||||
observation = {'error': str(error)}
|
||||
last_post_verify_observation = observation
|
||||
if dialog_agent is not None and target_pid is None:
|
||||
if diagnostic_closing:
|
||||
# The exact diagnostic worker owns its bounded close/No sequence.
|
||||
from .dialog_supervisor import DialogPollResult
|
||||
dialog_result = DialogPollResult(activity=False)
|
||||
elif dialog_agent is not None and target_pid is None:
|
||||
# The Library Manager Verify route starts its own window
|
||||
# before it launches Expedition PCB. Do not feed that
|
||||
# large MFC main window to the PCB dialog probe; it can
|
||||
@@ -1039,6 +1198,13 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
dialog_result = dialog_supervisor.poll()
|
||||
else:
|
||||
dialog_result = dialog_supervisor.poll()
|
||||
if not diagnostic_closing:
|
||||
intent = _close_intent_after_poll(job, events, offset, target_pid)
|
||||
if intent is not None:
|
||||
_acknowledge_diagnostic_close(job, intent, stop)
|
||||
diagnostic_closing = True
|
||||
from .dialog_supervisor import DialogPollResult
|
||||
dialog_result = DialogPollResult(activity=False)
|
||||
if (version_prompt is not None and consent is None and dialog_agent is not None
|
||||
and not request.diagnostic_only and not request.native_lm_verify
|
||||
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
|
||||
@@ -1107,7 +1273,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
error_stage=phase.value,
|
||||
safe_to_continue=False,
|
||||
))
|
||||
if deadline.expired():
|
||||
if deadline.expired() or (lm_dispatch_deadline is not None and target_pid is None
|
||||
and time.monotonic() >= lm_dispatch_deadline):
|
||||
_write_failure_windows(root, latest_snapshots)
|
||||
# Stop automation without killing PCB/iCDB during a write.
|
||||
_write_process_tree(root, process, target_pid)
|
||||
@@ -1123,7 +1290,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
target_pid=target_pid,
|
||||
observation=last_post_verify_observation,
|
||||
)
|
||||
_stop_worker(process)
|
||||
_stop_worker(process, wait_for_native_write=not request.diagnostic_only)
|
||||
if dispatch_failure is not None:
|
||||
status, detail = dispatch_failure
|
||||
if progress:
|
||||
@@ -1136,6 +1303,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
return finish(VerifyResult(status, stderr=detail, safe_to_continue=False))
|
||||
return finish(VerifyResult('TIMEOUT', stderr='操作超时,当前项未完成。', error_stage=phase.value, safe_to_continue=False))
|
||||
time.sleep(.2)
|
||||
end_native_phase() # Exact worker exit precedes all optional outcome/evidence I/O.
|
||||
worker_result = root/'outcome.json'
|
||||
if not worker_result.exists():
|
||||
return finish(VerifyResult('FAIL', stderr=f'执行器异常退出 ({process.returncode}),见 worker.log', safe_to_continue=False))
|
||||
@@ -1145,7 +1313,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
result = VerifyResult(**outcome)
|
||||
except Exception as error:
|
||||
if 'process' in locals() and process.poll() is None:
|
||||
_stop_worker(process)
|
||||
_stop_worker(process, wait_for_native_write=not request.diagnostic_only)
|
||||
launch_release = getattr(error, 'worker_launch_release', None) if 'process' not in locals() else None
|
||||
if not worker_launch_attempted:
|
||||
launch_release = {'process_created': False, 'worker_exited': True,
|
||||
@@ -1164,7 +1332,12 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
finally:
|
||||
close_errors = []
|
||||
worker_exited = False
|
||||
observer_started = False
|
||||
automation_release = {'safe_to_continue': False}
|
||||
if 'process' not in locals() or process.poll() is not None or getattr(process, 'session_record_path', None):
|
||||
# A gated worker owns its writer barrier and inherited sidecar.
|
||||
# Parent admission must not block controls needed for its exit.
|
||||
end_native_phase()
|
||||
if 'dialog_agent' in locals() and dialog_agent is not None:
|
||||
try:
|
||||
dialog_agent.close()
|
||||
@@ -1174,20 +1347,27 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
try:
|
||||
worker_exited = process.poll() is not None
|
||||
if not worker_exited:
|
||||
worker_exited = _stop_worker(process)
|
||||
worker_exited = _stop_worker(process, wait_for_native_write=not request.diagnostic_only)
|
||||
if hasattr(process, 'automation_release_state'):
|
||||
automation_release = process.automation_release_state()
|
||||
else:
|
||||
automation_release = {'safe_to_continue': worker_exited, 'remaining_pids': []}
|
||||
if worker_exited:
|
||||
process.close()
|
||||
elif getattr(process, 'session_record_path', None):
|
||||
if not worker_exited and getattr(process, 'session_record_path', None):
|
||||
from .session_record import handoff_session
|
||||
handoff_session(process.session_record_path, evidence_root=root,
|
||||
process=process, progress=lambda state: _notify_progress(progress,
|
||||
{'stage': 'session_observation', 'block': request.block_name, **state}))
|
||||
observer_started = True
|
||||
_notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name,
|
||||
'detail': '已转后台观察,可查看状态'})
|
||||
from .operation_queue import hold_native_handoff
|
||||
hold_native_handoff(process, process.session_record_path)
|
||||
except TaskHandoff as error:
|
||||
handoff_result = _handoff_verify_result(error)
|
||||
if handoff_result.evidence_path:
|
||||
_write_optional_evidence(handoff_result.evidence_path,
|
||||
{'block_name': request.block_name, **asdict(handoff_result)})
|
||||
raise
|
||||
except Exception as error:
|
||||
close_errors.append(str(error))
|
||||
if 'process' in locals():
|
||||
@@ -1232,6 +1412,25 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'automation_release': automation_release, 'worker_exited': worker_exited}
|
||||
release_result['remaining_pids'] = sorted(set(release_result.get('remaining_pids', []))
|
||||
| set(automation_release.get('remaining_pids', [])))
|
||||
if worker_exited:
|
||||
try:
|
||||
if (release_result.get('safe_to_continue') is not True
|
||||
and getattr(process, 'session_record_path', None)):
|
||||
if not observer_started:
|
||||
from .session_record import handoff_session
|
||||
# Retain the exact worker handle until registered
|
||||
# native clients exit and the observer obtains proof.
|
||||
handoff_session(process.session_record_path, evidence_root=root,
|
||||
process=process, progress=lambda state: _notify_progress(progress,
|
||||
{'stage': 'session_observation', 'block': request.block_name, **state}))
|
||||
observer_started = True
|
||||
_notify_progress(progress, {'stage': 'session_handoff', 'block': request.block_name,
|
||||
'detail': '工作进程已退出,原生会话继续后台观察'})
|
||||
else:
|
||||
process.close()
|
||||
except Exception as error:
|
||||
release_result = {**release_result, 'safe_to_continue': False,
|
||||
'close_errors': [*close_errors, str(error)]}
|
||||
try:
|
||||
from .operation_lifecycle import classify_save_state
|
||||
save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines()
|
||||
@@ -1279,8 +1478,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
end_native_phase()
|
||||
|
||||
if result.status == 'PASS' and not request.diagnostic_only:
|
||||
timing.begin('library_flag')
|
||||
@@ -1290,9 +1488,10 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
if progress:
|
||||
_notify_progress(progress, {'stage': 'library_flag_probe', 'block': request.block_name, **record})
|
||||
try:
|
||||
probe = read_library_flag_with_retry(
|
||||
flag_reader or read_library_flag_if_available, Path(request.lmc_file),
|
||||
request.block_name, on_attempt=record_attempt)
|
||||
with native_channel(read_only=True):
|
||||
probe = read_library_flag_with_retry(
|
||||
flag_reader or read_library_flag_if_available, Path(request.lmc_file),
|
||||
request.block_name, on_attempt=record_attempt)
|
||||
result = apply_post_verify_status(result, probe)
|
||||
result = replace(result, bridge_attempts=tuple(bridge_records))
|
||||
_write_optional_evidence(root/'bridge-status.json', bridge_records)
|
||||
@@ -1304,39 +1503,62 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
return finish(result)
|
||||
|
||||
|
||||
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None):
|
||||
"""Run serially and stop when database/session safety is unconfirmed."""
|
||||
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None,
|
||||
context=None):
|
||||
"""Run serially; isolate failures and skip writes to resources still retained."""
|
||||
if max_workers != 1:
|
||||
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
|
||||
if context is not None:
|
||||
stop = stop if stop is not None else context.stop
|
||||
progress = context.guard_callback(progress) if progress is not None else None
|
||||
if verifier is None:
|
||||
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available, stop=stop) # noqa: E731
|
||||
verifier = lambda request: run_verify(request, flag_reader=read_library_flag_if_available,
|
||||
stop=stop, context=context) # noqa: E731
|
||||
results = []
|
||||
queue_stop = False
|
||||
retained_libraries = set()
|
||||
retained_libraries = {}
|
||||
for request in requests:
|
||||
library_key = str(getattr(request, 'lmc_file', '__injected_verifier_scope__')).casefold()
|
||||
if queue_stop or (stop is not None and stop.is_set()):
|
||||
from .operation_queue import request_library_keys
|
||||
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}
|
||||
if (queue_stop or stop is not None and stop.is_set()
|
||||
or context is not None and context.stop.is_set()):
|
||||
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
||||
elif library_key in retained_libraries:
|
||||
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入')
|
||||
elif library_keys.intersection(retained_libraries):
|
||||
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)} 的同库会话尚未释放,当前项未启动。')
|
||||
else:
|
||||
try:
|
||||
def execute():
|
||||
result = verifier(request)
|
||||
if not result.safe_to_continue:
|
||||
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, stop=stop)
|
||||
return result
|
||||
result = item_executor(request, execute) if item_executor is not None else execute()
|
||||
except Exception as error:
|
||||
from .operation_queue import QueueCancelled
|
||||
from .operation_queue import QueueCancelled, QueueUnavailable, TaskHandoff
|
||||
# An unexpected exception cannot establish database safety.
|
||||
result = VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
|
||||
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled))
|
||||
result = (VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
|
||||
error_stage='admission') if isinstance(error, QueueUnavailable) else
|
||||
_handoff_verify_result(error) if isinstance(error, TaskHandoff) else
|
||||
VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
|
||||
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled)))
|
||||
results.append(result)
|
||||
# Never start another writer after an unconfirmed native shutdown.
|
||||
if not result.safe_to_continue:
|
||||
retained_libraries.add(library_key)
|
||||
retained_libraries.update({key:(request, len(results)-1) for key in library_keys})
|
||||
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'}
|
||||
if queue_stop and stop is not None:
|
||||
stop.set()
|
||||
|
||||
@@ -63,7 +63,9 @@ class WriteAdmission:
|
||||
if decision != 'continue':
|
||||
if decision == 'cancel' and self.stop is not None:
|
||||
self.stop.set()
|
||||
raise WriteAdmissionDeclined(decision)
|
||||
detail = ('确认等待超时默认跳过本项,未授予未知进程写入许可。'
|
||||
if decision == 'skip' and choice.decision_origin == 'timeout_default' else None)
|
||||
raise WriteAdmissionDeclined(decision, detail)
|
||||
current, _ = self._identities(owners)
|
||||
if not set(current).issubset(identities):
|
||||
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 确认期间进程身份已变化,请重新检查。')
|
||||
@@ -73,5 +75,6 @@ class WriteAdmission:
|
||||
_write_json(root/('write-owner-consent-'+uuid4().hex+'.json'), dict(
|
||||
intent='user_confirmed_unknown_clients_do_not_use_target_library', library=str(Path(library).resolve()),
|
||||
block=block, scope='current_batch_library', owners=rows, choice='continue',
|
||||
decision_origin=choice.decision_origin,
|
||||
proves_native_ownership=False, requires_fresh_resource_checks=True))
|
||||
self._grants.setdefault(key, set()).update(current)
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Keep subprocess imports on the worktree being tested."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def pytest_configure():
|
||||
source = str(Path(__file__).resolve().parents[1] / 'src')
|
||||
existing = os.environ.get('PYTHONPATH', '').split(os.pathsep)
|
||||
os.environ['PYTHONPATH'] = os.pathsep.join(
|
||||
[source, *(entry for entry in existing if entry and entry != source)])
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Run the real Add dispatch with harmless process and Win32/UIA boundaries."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
from pytest import MonkeyPatch
|
||||
|
||||
from cbb_refresh_verify import desktop_worker, native_management as native
|
||||
from cbb_refresh_verify.session_record import update_worker_state
|
||||
|
||||
|
||||
def run(job_path):
|
||||
job = json.loads(Path(job_path).read_text(encoding='utf-8'))
|
||||
root = Path(job['root'])
|
||||
signals = root.parent
|
||||
mode = job['test_mode']
|
||||
lm_script = '''import subprocess,sys,time
|
||||
from pathlib import Path
|
||||
root=Path(sys.argv[1])
|
||||
input()
|
||||
if sys.argv[2] == 'pending':
|
||||
code='import sys,time; from pathlib import Path; p=Path(sys.argv[1]); '+\
|
||||
'\\nwhile not p.exists(): time.sleep(.02)'
|
||||
child=subprocess.Popen([sys.executable,'-c',code,str(root/'native-done')])
|
||||
(root/'descendant-pid').write_text(str(child.pid))
|
||||
while not (root/'lm-exit').exists(): time.sleep(.02)
|
||||
'''
|
||||
lm = subprocess.Popen([sys.executable, '-c', lm_script, str(signals), mode], stdin=subprocess.PIPE, text=True)
|
||||
(signals/'lm-pid').write_text(str(lm.pid))
|
||||
update_worker_state(job, 'POSTCALL', identities=[('native', lm.pid)], required=True)
|
||||
desktop_worker.start_supervisor_watchdog(job['supervisor_pid'], cancel_path=job['cancel_signal'],
|
||||
session_record_path=job['session_record_path'], operation_id=job['operation_id'],
|
||||
supervisor_identity=job['supervisor_identity'])
|
||||
state = {'new': False, 'posted': False, 'closed': False}
|
||||
patch = MonkeyPatch()
|
||||
import win32gui, win32process
|
||||
if mode == 'assignment-failed':
|
||||
def deny_job(*args):
|
||||
raise OSError('exact native job admission denied')
|
||||
patch.setattr(desktop_worker.win32job, 'AssignProcessToJobObject', deny_job)
|
||||
if mode == 'cancel-after-registration':
|
||||
assign = desktop_worker.win32job.AssignProcessToJobObject
|
||||
def cancel_after_assign(*args):
|
||||
result = assign(*args)
|
||||
(root/'cancel-native-add.signal').touch()
|
||||
return result
|
||||
patch.setattr(desktop_worker.win32job, 'AssignProcessToJobObject', cancel_after_assign)
|
||||
tab = SimpleNamespace(window_text=lambda: 'Logical - Physical', is_selected=lambda: True)
|
||||
patch.setitem(sys.modules, 'pywinauto', SimpleNamespace(Desktop=lambda **kw: SimpleNamespace(
|
||||
window=lambda **kw: SimpleNamespace(descendants=lambda **kw: [tab]))))
|
||||
patch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (1, lm.pid))
|
||||
patch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
|
||||
patch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
|
||||
patch.setattr(win32gui, 'GetWindowText', lambda h: {
|
||||
100: 'Reusable Blocks', 200: 'New Reusable Block', 300: 'Native result',
|
||||
301: 'New Logical-Physical Reuse Block was successfully added.'}.get(int(h), ''))
|
||||
patch.setattr(win32gui, 'GetDlgItem', lambda h, c:
|
||||
110 if h == 100 and c == 1066 else 112 if h == 100 else 210 if c == 1083 else 302 if h == 300 else c+1000)
|
||||
patch.setattr(win32gui, 'GetClassName', lambda _: 'Edit')
|
||||
patch.setattr(win32gui, 'IsWindow', lambda _: not state['closed'])
|
||||
patch.setattr(win32gui, 'EnumChildWindows', lambda h, fn, arg:
|
||||
fn(301, arg) if h == 300 and mode == 'acknowledged' else None)
|
||||
# Only the external native text-control setter is substituted.
|
||||
patch.setattr(native, '_set_probe_field', lambda hwnd, control, value, root, *, read_only=False: None)
|
||||
def post(hwnd, *args):
|
||||
if hwnd == 110: state['new'] = True
|
||||
if hwnd == 210:
|
||||
state['posted'] = True
|
||||
lm.stdin.write('Add\n')
|
||||
lm.stdin.flush()
|
||||
(signals/'add-dispatched').touch()
|
||||
if hwnd == 112: state['closed'] = True
|
||||
patch.setattr(win32gui, 'PostMessage', post)
|
||||
def windows():
|
||||
if state['closed']: return []
|
||||
return ([100, 200, 300] if state['posted'] and mode == 'acknowledged' else
|
||||
[100, 200] if state['new'] else [100])
|
||||
desktop = SimpleNamespace(EnumDesktopWindows=windows)
|
||||
try:
|
||||
native._probe_add_dialog(SimpleNamespace(OnReusableBlocksEditor=lambda: None),
|
||||
job, desktop, {lm.pid}, root)
|
||||
result = {'success': True, 'safe_to_continue': False}
|
||||
except (TimeoutError, OSError, RuntimeError) as error:
|
||||
result = {'success': False, 'safe_to_continue': False, 'detail': str(error)}
|
||||
finally:
|
||||
patch.undo()
|
||||
(root/'result.json').write_text(json.dumps(result))
|
||||
update_worker_state(job, 'UNCONFIRMED')
|
||||
(signals/'add-unwound').touch()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
desktop_worker.run_native_worker(run, Path(sys.argv[1]))
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Real application close while one disposable metadata boundary is held."""
|
||||
from pathlib import Path
|
||||
import sys,time
|
||||
|
||||
from PySide6.QtCore import QTimer
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from cbb_refresh_verify import scoped_manifest as manifest
|
||||
from cbb_refresh_verify.operation_queue import check_active
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
|
||||
root=Path(sys.argv[1]);mode=sys.argv[2]
|
||||
source=root/'source';source.mkdir()
|
||||
(source/('one.log' if mode=='copy' else 'one.dat')).write_bytes(b'isolated fixture')
|
||||
def held():
|
||||
(root/'entered').touch()
|
||||
while not (root/'release').exists():time.sleep(.02)
|
||||
def hash_file(path):
|
||||
held()
|
||||
return manifest.hash_file(path)
|
||||
if mode=='copy':
|
||||
original=manifest.shutil.copy2
|
||||
def copy_file(*args,**kwargs):
|
||||
held()
|
||||
return original(*args,**kwargs)
|
||||
manifest.shutil.copy2=copy_file
|
||||
def action():
|
||||
if mode=='hash':manifest.build_manifest(source,hash_function=hash_file)
|
||||
else:manifest.copy_verified(source,root/'partial-copy',hash_function=hash_file)
|
||||
check_active()
|
||||
(root/'late-dispatch').touch()
|
||||
app=QApplication([])
|
||||
window=MainWindow(reader=lambda _:None,data_root=root/'data');window.show()
|
||||
job=window._new_job('management',library=root/'library.lmc')
|
||||
window._start(action,lambda _:None,queued=False,job=job)
|
||||
def close_when_entered():
|
||||
if (root/'entered').exists():window.close()
|
||||
else:QTimer.singleShot(20,close_when_entered)
|
||||
QTimer.singleShot(20,close_when_entered)
|
||||
code=app.exec()
|
||||
(root/'main-returning').touch()
|
||||
raise SystemExit(code)
|
||||
@@ -9,6 +9,7 @@ from uuid import uuid4
|
||||
workspace = Path(sys.argv[1]).resolve()
|
||||
bundle_root = Path(sys.argv[2]).resolve()
|
||||
sys.path.insert(0, str(workspace/'src'))
|
||||
from cbb_refresh_verify import __version__
|
||||
exe = bundle_root/'dist/CbbRefreshVerify-Background/CbbRefreshVerify.exe'
|
||||
root = bundle_root/('smoke-' + uuid4().hex[:8])
|
||||
root.mkdir()
|
||||
@@ -64,7 +65,7 @@ finally:
|
||||
from PyInstaller.archive.readers import ZlibArchiveReader
|
||||
pyz = bundle_root/'build/CbbRefreshVerify/PYZ-00.pyz'
|
||||
code = ZlibArchiveReader(str(pyz)).extract('cbb_refresh_verify')
|
||||
assert '0.2.4b2' in code.co_consts
|
||||
assert __version__ in code.co_consts
|
||||
toc = ast.literal_eval((bundle_root/'build/CbbRefreshVerify/Analysis-00.toc').read_text('utf-8'))
|
||||
stack, rows = [toc], []
|
||||
while stack:
|
||||
@@ -77,6 +78,6 @@ while stack:
|
||||
stack.extend(value)
|
||||
assert rows and all(Path(row[1]).is_relative_to(workspace/'src') for row in rows)
|
||||
results['module_origins'] = {'status': 'passed', 'module_count': len(rows), 'source_root': str(workspace/'src')}
|
||||
results['version'] = '0.2.4b2'
|
||||
results['version'] = __version__
|
||||
(root/'result.json').write_text(json.dumps(results, ensure_ascii=False, indent=2), 'utf-8')
|
||||
print(json.dumps({'evidence': str(root/'result.json'), **results}, ensure_ascii=False), flush=True)
|
||||
@@ -130,7 +130,7 @@ def test_main_logs_and_evidence_buttons_open_the_correct_paths(controls, qtbot):
|
||||
w.recovery_path = evidence
|
||||
w.recovery_button.setEnabled(True)
|
||||
press(qtbot, w.recovery_button)
|
||||
assert controls.opened == [w.data_root, evidence]
|
||||
assert controls.opened == [w.data_root/'logs', evidence]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('attribute', ['selected_batch_button', 'batch_button', 'icdb_repair_button'])
|
||||
@@ -152,7 +152,7 @@ def test_main_check_buttons_have_real_confirm_and_cancel_paths(controls, qtbot,
|
||||
assert details is not None
|
||||
press(qtbot, details)
|
||||
assert summary.findChild(QTextEdit).isVisible()
|
||||
press(qtbot, summary.button(QMessageBox.Ok))
|
||||
press(qtbot, summary.button(QMessageBox.Close))
|
||||
assert not isValid(summary) or not summary.isVisible()
|
||||
|
||||
|
||||
@@ -280,7 +280,7 @@ def test_management_confirm_cancel_execute_stop_and_repeated_click(controls, qtb
|
||||
qtbot.mouseClick(dialog.close_button, Qt.LeftButton)
|
||||
assert len(calls) == 1 and dialog.isVisible()
|
||||
press(qtbot, dialog.stop_button)
|
||||
assert dialog.stop.is_set()
|
||||
assert dialog.context.stop_after_current.is_set() and not dialog.stop.is_set()
|
||||
finally:
|
||||
finish.set()
|
||||
qtbot.waitUntil(lambda: not dialog.busy)
|
||||
@@ -411,7 +411,7 @@ def test_residual_refresh_details_confirm_and_close(residual, qtbot):
|
||||
expand = next(b for b in details.findChildren(QPushButton) if 'Details' in b.text())
|
||||
press(qtbot, expand)
|
||||
assert details.findChild(QTextEdit).isVisible()
|
||||
press(qtbot, details.button(QMessageBox.Ok))
|
||||
press(qtbot, details.button(QMessageBox.Close))
|
||||
press(qtbot, d.confirm_button)
|
||||
qtbot.waitUntil(lambda: not d.busy)
|
||||
assert len(residual.releases) == 1 and residual.releases[0]['force'] is False
|
||||
|
||||
@@ -69,9 +69,10 @@ def test_completed_old_library_result_does_not_release_new_library(qtbot, tmp_pa
|
||||
qtbot.waitUntil(lambda: not window._icdb_active())
|
||||
summary = window.icdb_summary
|
||||
window.lmc_edit.setText('other.lmc')
|
||||
message = window.status_label.text()
|
||||
next(button for button in summary.buttons() if '释放' in button.text()).click()
|
||||
assert getattr(window, 'release_dialog', None) is None
|
||||
assert '切' in window.status_label.text()
|
||||
assert window.status_label.text() == message
|
||||
|
||||
|
||||
def test_later_management_invalidates_old_recovery_offer(qtbot, tmp_path, monkeypatch):
|
||||
@@ -109,4 +110,4 @@ def test_check_release_action_tracks_busy_and_retained_queue(qtbot, tmp_path, mo
|
||||
assert opened == [{'queued': True}]
|
||||
window.busy = False
|
||||
window._update()
|
||||
assert action.isEnabled()
|
||||
assert not action.isEnabled(), 'A dismissed one-shot result cannot be reactivated'
|
||||
@@ -1,3 +1,4 @@
|
||||
from cbb_refresh_verify.ui import timed_prompt
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
@@ -8,7 +9,7 @@ import pytest
|
||||
@pytest.fixture(autouse=True)
|
||||
def accept_manual_backup_reminder(monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: QMessageBox.Yes)
|
||||
|
||||
|
||||
def test_backup_dialog_requires_a_project_and_passes_selected_target(qtbot, tmp_path):
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
"""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
|
||||
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
|
||||
@@ -71,7 +71,7 @@ def test_verify_failure_recheck_finishes_before_yielding_native_queue(qtbot,tmp_
|
||||
try:return action()
|
||||
finally:active.pop()
|
||||
return run
|
||||
def recheck(library,block,result):
|
||||
def recheck(library,block,result,**kwargs):
|
||||
seen.append(bool(active))
|
||||
return replace(result,safe_to_continue=True)
|
||||
monkeypatch.setattr(window,'_queued_action',queued)
|
||||
@@ -92,7 +92,7 @@ def test_management_failure_recheck_finishes_before_yielding_native_queue(tmp_pa
|
||||
active.append(True)
|
||||
try:return action()
|
||||
finally:active.pop()
|
||||
def recheck(library,block,result):
|
||||
def recheck(library,block,result,**kwargs):
|
||||
seen.append(bool(active))
|
||||
return replace(result,safe_to_continue=True)
|
||||
monkeypatch.setattr(operation_lifecycle,'recheck_failed_release',recheck)
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, TaskHandoff, hold_native_handoff
|
||||
from cbb_refresh_verify.ui.icdb_check_task import IcdbCheckTask
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
from test_verify_runner import fixture, request
|
||||
|
||||
|
||||
def test_cancelled_diagnostic_report_survives_ongoing_handoff_finalization(qtbot,tmp_path):
|
||||
fixture(tmp_path)
|
||||
req=request(tmp_path,diagnostic_only=True)
|
||||
context=BatchTaskContext(str(req.lmc_file),native_policy='external')
|
||||
entered,finish=Event(),Event()
|
||||
def finalize():
|
||||
try:
|
||||
hold_native_handoff(None,tmp_path/'session.json')
|
||||
except TaskHandoff:
|
||||
entered.set()
|
||||
assert finish.wait(5)
|
||||
try:
|
||||
with pytest.raises(TaskHandoff):context.run(finalize)
|
||||
assert entered.is_set()
|
||||
task=IcdbCheckTask([req],NativeQueue(),tmp_path/'reports')
|
||||
task.active=True
|
||||
task.results=[VerifyResult('CANCELLED',safe_to_continue=False,stderr='已转后台观察')]
|
||||
task._report()
|
||||
qtbot.waitUntil(lambda:not task.active,timeout=3000)
|
||||
assert task.report is not None and task.report.exists(),task.report_error
|
||||
assert not task.report_error and task.results[0].status=='CANCELLED'
|
||||
finally:
|
||||
finish.set()
|
||||
context.close(timeout_seconds=2)
|
||||
@@ -0,0 +1,178 @@
|
||||
"""Cancellation may race native loading after COM/document admission stopped."""
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import diagnostic_open, failed_session, residual_sessions
|
||||
from cbb_refresh_verify.dialog_models import ControlSnapshot, DialogPhase, WindowSnapshot
|
||||
from test_failed_startup import startup_fixture
|
||||
from test_diagnostic_open import write_logs
|
||||
|
||||
|
||||
def loaded_fixture(tmp_path, monkeypatch, *, empty_close_first=False, obstacle=''):
|
||||
import win32con, win32gui
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
job.update(project=str(tmp_path/'IP101GR/IP101GR.prj'), pcb=str(tmp_path/'IP101GR/PCB/IP101GR.pcb'),
|
||||
diagnostic_only=True, cancel_signal=str(tmp_path/'cancel.signal'))
|
||||
Path(job['pcb']).parent.mkdir(parents=True)
|
||||
Path(job['pcb']).touch(); Path(job['cancel_signal']).touch()
|
||||
records[0] = (12, records[0][1], f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)
|
||||
job['diagnostic_log_baseline'] = diagnostic_open.snapshot_diagnostic_logs(job)
|
||||
write_logs(job, pid=99 if obstacle == 'foreign_log_pid' else 12, foreign=obstacle == 'foreign_log_path')
|
||||
if obstacle == 'stale_logs': job['diagnostic_log_baseline'] = diagnostic_open.snapshot_diagnostic_logs(job)
|
||||
if obstacle == 'write': (tmp_path/'save.log').write_text('save entered')
|
||||
if obstacle == 'ordinary': job['diagnostic_only'] = False
|
||||
if obstacle == 'not_cancelled': Path(job['cancel_signal']).unlink()
|
||||
state = dict(ticks=0., tip=not empty_close_first, declined=False, closing=False)
|
||||
clock = SimpleNamespace(monotonic=lambda:state['ticks'],
|
||||
sleep=lambda seconds:state.__setitem__('ticks', state['ticks']+seconds))
|
||||
monkeypatch.setattr(failed_session, 'time', clock)
|
||||
monkeypatch.setattr(diagnostic_open, 'time', clock)
|
||||
target = dict(hwnd=100, pid=12, **{'class':'Afx:main'},
|
||||
text='Expedition PCB - Reusable Block - [IP101GR]', enabled=False,
|
||||
children=[dict(hwnd=101, **{'class':'MDIClient'}, text='', parent=100),
|
||||
dict(hwnd=102, **{'class':'Afx:document'}, text='IP101GR', parent=101)])
|
||||
if obstacle == 'foreign_mdi': target['children'][1]['text'] = 'Other'
|
||||
forward = dict(hwnd=200, pid=12, **{'class':'#32770'}, text='Expedition PCB', owner=100,
|
||||
children=[dict(hwnd=30, **{'class':'Static'}, id=6172,
|
||||
text='New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'),
|
||||
dict(hwnd=31, **{'class':'Button'}, id=7, text='&No', enabled=True),
|
||||
dict(hwnd=32, **{'class':'Button'}, id=6, text='&Yes', enabled=True)])
|
||||
if obstacle == 'foreign_prompt': forward['owner'] = 999
|
||||
if obstacle == 'unknown': forward['text'] = 'Unknown action'
|
||||
def windows(pid):
|
||||
if state['tip'] or empty_close_first and not state['closing']: return []
|
||||
frame = deepcopy(target)
|
||||
frame['enabled'] = state['declined']
|
||||
if not state['declined'] or obstacle == 'progress':
|
||||
frame['children'].append(dict(hwnd=103, **{'class':'msctls_progress32'}, text='', visible=True))
|
||||
return [frame] + ([] if state['declined'] else [deepcopy(forward)])
|
||||
monkeypatch.setattr(diagnostic_open, '_windows', windows)
|
||||
monkeypatch.setattr(diagnostic_open, '_request_close_handoff', lambda *a, **kw:
|
||||
pytest.fail('cancelled supervisor must not be asked for a normal admission ack'))
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn,arg:
|
||||
[fn(h,arg) for h in ((200,) if state['tip'] else (100,200))])
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', lambda h:'#32770' if h == 200 else 'Afx:main')
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', lambda h:
|
||||
'Expedition PCB' if empty_close_first and not state['closing'] else target['text'])
|
||||
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda h: h != 200 or state['tip'] or not empty_close_first)
|
||||
tip = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Tip of the Day',
|
||||
DialogPhase.PCB_STARTING,(ControlSnapshot(201,1,'Button','OK',enabled=True),))
|
||||
unknown = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB',
|
||||
DialogPhase.PCB_STARTING,())
|
||||
monkeypatch.setattr(failed_session, '_startup_snapshot', lambda *a:tip if state['tip'] else unknown)
|
||||
def post(hwnd, message, *_):
|
||||
messages.append((hwnd,message))
|
||||
if hwnd == 201: state['tip'] = False
|
||||
elif hwnd == 31:
|
||||
state['declined'] = True
|
||||
if state['closing']: records.clear()
|
||||
elif hwnd == 100 and message == win32con.WM_CLOSE:
|
||||
state['closing'] = True
|
||||
if state['declined']: records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
return job, records, messages, state
|
||||
|
||||
|
||||
@pytest.mark.parametrize('empty_close_first', [False, True])
|
||||
def test_cancelled_diagnostic_tip_to_loaded_forward_no_closes_once_without_ack(tmp_path, monkeypatch, empty_close_first):
|
||||
job, records, messages, state = loaded_fixture(tmp_path, monkeypatch, empty_close_first=empty_close_first)
|
||||
events = []
|
||||
result = failed_session.close_failed_startup(job,12,timeout_seconds=1,
|
||||
emit=lambda **event:events.append(event))
|
||||
assert result['status'] == 'CLOSED' and result['release']['safe_to_continue']
|
||||
assert messages == ([(100,16),(31,245)] if empty_close_first else [(201,245),(31,245),(100,16)])
|
||||
assert not records and Path(job['cancel_signal']).exists()
|
||||
assert not any(e.get('stage') in ('diagnostic_complete','diagnostic_native_open_confirmed','save_start') for e in events)
|
||||
assert sum(e['stage']=='startup_close_requested' for e in events)==1
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['foreign_log_pid','foreign_log_path','stale_logs','foreign_mdi',
|
||||
'foreign_prompt','unknown','progress','write','ordinary','not_cancelled'])
|
||||
def test_cancelled_loaded_cleanup_cannot_override_identity_write_or_unknown_guards(tmp_path, monkeypatch, obstacle):
|
||||
job, records, messages, state = loaded_fixture(tmp_path, monkeypatch, obstacle=obstacle)
|
||||
result = failed_session.close_failed_startup(job,12,timeout_seconds=.5)
|
||||
assert result['status']=='RETAINED' and records
|
||||
assert messages == ([(201,245),(31,245)] if obstacle=='progress' else [(201,245)])
|
||||
|
||||
|
||||
def test_cancelled_diagnostic_keeps_one_thirty_second_cleanup_budget(tmp_path, monkeypatch):
|
||||
job, records, messages, state = loaded_fixture(tmp_path,monkeypatch,obstacle='progress')
|
||||
result = failed_session.close_failed_startup(job,12)
|
||||
assert result['status']=='RETAINED' and records
|
||||
assert 30 <= state['ticks'] <= 30.2
|
||||
assert messages==[(201,245),(31,245)]
|
||||
|
||||
|
||||
def test_unknown_sibling_vetoes_known_forward_no(tmp_path,monkeypatch):
|
||||
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
||||
original=diagnostic_open._windows
|
||||
def windows(pid):
|
||||
values=original(pid)
|
||||
return values+[dict(hwnd=999,pid=12,**{'class':'#32770'},text='Unknown action',children=[])] if values else values
|
||||
monkeypatch.setattr(diagnostic_open,'_windows',windows)
|
||||
result=failed_session.close_failed_startup(job,12,timeout_seconds=.5)
|
||||
assert result['status']=='RETAINED' and records
|
||||
assert messages==[(201,245)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename',['IP101GR.pcb','Foreign.pcb'])
|
||||
def test_cancelled_loaded_close_only_declines_exact_owned_save_question(tmp_path,monkeypatch,filename):
|
||||
import win32gui
|
||||
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
||||
original_windows=diagnostic_open._windows
|
||||
def windows(pid):
|
||||
if not state['closing']:return original_windows(pid)
|
||||
return [dict(hwnd=400,pid=12,**{'class':'#32770'},text='Expedition PCB',owner=100,
|
||||
children=[dict(hwnd=40,**{'class':'Static'},text=f'Save changes to {filename}?'),
|
||||
dict(hwnd=41,**{'class':'Button'},id=7,text='No',enabled=True),
|
||||
dict(hwnd=42,**{'class':'Button'},id=6,text='Yes',enabled=True),
|
||||
dict(hwnd=43,**{'class':'Button'},id=2,text='Cancel',enabled=True)])]
|
||||
monkeypatch.setattr(diagnostic_open,'_windows',windows)
|
||||
original_post=win32gui.PostMessage
|
||||
def post(hwnd,message,*args):
|
||||
if hwnd==100:
|
||||
messages.append((hwnd,message));state['closing']=True
|
||||
elif hwnd==41:
|
||||
messages.append((hwnd,message));records.clear()
|
||||
else:original_post(hwnd,message,*args)
|
||||
monkeypatch.setattr(win32gui,'PostMessage',post)
|
||||
result=failed_session.close_failed_startup(job,12,timeout_seconds=1)
|
||||
assert result['status']==('CLOSED' if filename=='IP101GR.pcb' else 'RETAINED')
|
||||
assert messages==[(201,245),(31,245),(100,16)]+([(41,245)] if filename=='IP101GR.pcb' else [])
|
||||
|
||||
|
||||
def test_supervisor_finishes_inflight_poll_before_signalling_cleanup_and_never_polls_again(tmp_path,monkeypatch):
|
||||
import json
|
||||
from threading import Event
|
||||
from cbb_refresh_verify import desktop_worker
|
||||
from cbb_refresh_verify.verify_runner import run_verify
|
||||
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
|
||||
from test_verify_runner import fixture, request, PORTS_OK
|
||||
fixture(tmp_path); stop=Event(); state={'polling':False,'polls':0,'cleanup':False}
|
||||
class Worker:
|
||||
desktop=None;pid=700;companion_pids=[];returncode=None
|
||||
def __init__(self,command,name):
|
||||
self.name=name
|
||||
state['path']=Path(command[-1]);state['job']=json.loads(state['path'].read_text())
|
||||
state['path'].with_name('events.jsonl').write_text(json.dumps(dict(stage='pcb_worker_started',pcb_pid=901))+'\n')
|
||||
def poll(self):return self.returncode
|
||||
def request_stop(self):
|
||||
assert not state['polling'] and state['polls']==1
|
||||
Path(state['job']['cancel_signal']).touch()
|
||||
def wait(self,timeout=5):
|
||||
assert Path(state['job']['cancel_signal']).exists() and not state['polling']
|
||||
state['cleanup']=True;self.returncode=1;return 1
|
||||
def close(self):pass
|
||||
class Supervisor:
|
||||
def poll(self,*args):
|
||||
assert not state['cleanup'] and not Path(state['job']['cancel_signal']).exists()
|
||||
state['polling']=True;state['polls']+=1;stop.set();state['polling']=False
|
||||
return DialogPollResult()
|
||||
monkeypatch.setattr(desktop_worker,'DesktopWorker',Worker)
|
||||
result=run_verify(request(tmp_path,diagnostic_only=True),port_check=PORTS_OK,stop=stop,
|
||||
dialog_supervisor_factory=lambda **kw:Supervisor())
|
||||
assert result.status=='CANCELLED' and state['cleanup'] and state['polls']==1
|
||||
assert not state['path'].with_name('diagnostic-close-ack.json').exists()
|
||||
@@ -0,0 +1,198 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import failed_session,session_record,diagnostic_open
|
||||
from test_cancelled_loaded_startup import loaded_fixture
|
||||
|
||||
|
||||
def ordinary_proof(job,root,baseline,*,worker=None,pid=12):
|
||||
worker=worker or dict(pid=11,created_handle='worker-created',image='C:/App/python.exe',owner_sid='current',session_id=1)
|
||||
job.update(diagnostic_only=False,operation='verify',operation_id=job.get('operation_id','verify-ordinary'),
|
||||
library=job['lmc_file'],session_record_path=str(root/'session.json'),interactive_input=False)
|
||||
job.pop('diagnostic_log_baseline',None)
|
||||
session_record.write_session_record(root/'session.json',dict(operation_id=job['operation_id'],operation='verify',
|
||||
library=job['library'],block=job.get('block',job.get('block_name')),desktop=job['desktop'],cancel_signal=job['cancel_signal'],processes=[dict(role='worker',**worker)],
|
||||
resource_scope=dict(scope_state='DECLARED',library=job['library'],operation_id=job['operation_id'],projects=[job['project']])))
|
||||
binding={k:job[k] for k in ('operation_id','project','pcb','desktop')}
|
||||
events=[dict(stage='startup_supervisor_no_write',**binding),
|
||||
dict(stage='startup_prewrite_ready',worker_identity=worker,baseline=baseline,**binding),
|
||||
dict(stage='pcb_baseline',pids=[]),dict(stage='pcb_worker_started',pcb_pid=pid),
|
||||
dict(stage='startup_cancelled_prewrite',pcb_pid=pid,identity_verified=False,write_admitted=False,**binding)]
|
||||
(root/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
|
||||
return events
|
||||
|
||||
|
||||
@pytest.mark.parametrize('prior_close',[False,True])
|
||||
def test_proved_ordinary_cancel_finishes_tip_to_loaded_without_annotation_or_second_close(tmp_path,monkeypatch,prior_close):
|
||||
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,empty_close_first=prior_close)
|
||||
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
|
||||
result=failed_session.close_failed_startup(job,12,timeout_seconds=1)
|
||||
assert result['status']=='CLOSED' and not records
|
||||
assert messages==([(100,16),(31,245)] if prior_close else [(201,245),(31,245),(100,16)])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle',['missing_ready','missing_cancel_phase','supervisor_write','worker_write',
|
||||
'missing_supervisor','missing_baseline','foreign_worker','foreign_target','save','missing_cancel','interactive','native_lm'])
|
||||
def test_ordinary_cleanup_requires_positive_bound_no_write_evidence(tmp_path,monkeypatch,obstacle):
|
||||
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
||||
events=ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
|
||||
if obstacle=='missing_ready':events=[e for e in events if e['stage']!='startup_prewrite_ready']
|
||||
if obstacle=='missing_cancel_phase':events=[e for e in events if e['stage']!='startup_cancelled_prewrite']
|
||||
if obstacle=='missing_supervisor':events=events[1:]
|
||||
if obstacle=='supervisor_write':events.append(dict(stage='startup_supervisor_write_possible'))
|
||||
if obstacle=='worker_write':events.append(dict(stage='startup_write_admitted'))
|
||||
if obstacle=='missing_baseline':events[1].pop('baseline')
|
||||
if obstacle=='foreign_worker':events[1]['worker_identity']['created_handle']='other'
|
||||
if obstacle=='foreign_target':events[-1]['pcb']='C:/foreign.pcb'
|
||||
if obstacle=='save':(tmp_path/'save.log').write_text('SAVE_ENTERED')
|
||||
if obstacle=='missing_cancel':Path(job['cancel_signal']).unlink()
|
||||
if obstacle=='interactive':job['interactive_input']=True
|
||||
if obstacle=='native_lm':job['native_lm_verify']=True
|
||||
(tmp_path/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
|
||||
result=failed_session.close_failed_startup(job,12,timeout_seconds=.3)
|
||||
assert result['status']=='RETAINED' and records
|
||||
assert not any(h==31 or m==16 for h,m in messages)
|
||||
|
||||
|
||||
def test_worker_publishes_bound_baseline_before_launch_and_revokes_before_integration(tmp_path,monkeypatch):
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
from cbb_refresh_verify import mentor_adapter,integration
|
||||
job,events,execute=exercise_worker(tmp_path,monkeypatch)
|
||||
job.update(operation_id='op',operation='verify',library=job['lmc_file'],desktop='CbbVerify_test',
|
||||
session_record_path=str(Path(job['root'])/'session.json'),diagnostic_only=False)
|
||||
launch=mentor_adapter.launch_pcb_process
|
||||
def start(*args):
|
||||
assert any(e['stage']=='startup_prewrite_ready' and 'baseline' in e for e in events)
|
||||
return launch(*args)
|
||||
def write(*args,**kwargs):
|
||||
assert any(e['stage']=='startup_write_admitted' for e in events)
|
||||
monkeypatch.setattr(mentor_adapter,'launch_pcb_process',start)
|
||||
monkeypatch.setattr(integration,'refresh_integration',write)
|
||||
assert execute()['status']=='PASS'
|
||||
|
||||
|
||||
def test_cancelled_worker_records_positive_prewrite_phase_before_startup_cleanup(tmp_path,monkeypatch):
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
from cbb_refresh_verify import pcb_bridge
|
||||
job,events,execute=exercise_worker(tmp_path,monkeypatch)
|
||||
job.update(operation_id='op',operation='verify',library=job['lmc_file'],desktop='CbbVerify_test',
|
||||
session_record_path=str(Path(job['root'])/'session.json'),diagnostic_only=False,
|
||||
cancel_signal=str(tmp_path/'cancel.signal'))
|
||||
def cancel(*args,**kwargs):
|
||||
Path(job['cancel_signal']).touch();raise RuntimeError('VERIFY_CANCELLED')
|
||||
monkeypatch.setattr(pcb_bridge,'wait_for_target_document',cancel)
|
||||
observed=[]
|
||||
def cleanup(*args,**kwargs):observed.extend(events);return {'status':'RETAINED'}
|
||||
monkeypatch.setattr(failed_session,'close_failed_startup',cleanup)
|
||||
with pytest.raises(RuntimeError,match='VERIFY_CANCELLED'):execute()
|
||||
assert any(e['stage']=='startup_cancelled_prewrite' and e['write_admitted'] is False
|
||||
and e['identity_verified'] is False for e in observed)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('journal_fails',[False,True])
|
||||
def test_dialog_backend_records_write_revocation_before_action(journal_fails):
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify.dialog_supervisor import Win32DialogBackend,DialogSnapshot,DialogControl
|
||||
calls=[]
|
||||
gui=SimpleNamespace(PostMessage=lambda *args:calls.append('native'))
|
||||
backend=Win32DialogBackend((),win32gui=gui,win32process=object(),win32con=SimpleNamespace(BM_CLICK=245))
|
||||
def before(snapshot,action):
|
||||
calls.append('journal')
|
||||
if journal_fails:raise OSError('cannot record phase')
|
||||
backend.before_action=before
|
||||
snapshot=DialogSnapshot(100,12,'Expedition PCB',(DialogControl(101,6,'Button','Yes',True),))
|
||||
if journal_fails:
|
||||
with pytest.raises(OSError):backend.perform(snapshot,'confirm_forward_annotation')
|
||||
assert calls==['journal']
|
||||
else:
|
||||
backend.perform(snapshot,'confirm_forward_annotation');assert calls==['journal','native']
|
||||
|
||||
|
||||
def test_positive_ordinary_cancel_phase_yields_after_initial_wait(tmp_path,monkeypatch):
|
||||
from test_cancelled_session_handoff import worker_fixture
|
||||
state,stop,run=worker_fixture(tmp_path,monkeypatch)
|
||||
# The real worker publishes its cancellation fact during the first wait.
|
||||
from cbb_refresh_verify import desktop_worker
|
||||
Worker=desktop_worker.DesktopWorker;wait=Worker.wait
|
||||
def complete_proof(worker,timeout=5):
|
||||
job=state['job']
|
||||
baseline={'started_ns':1,'files':{}}
|
||||
ordinary_proof(job,state['path'].parent,baseline,pid=901,
|
||||
worker=dict(pid=700,created_handle='worker',image='C:/App/python.exe',owner_sid='current',session_id=1))
|
||||
return wait(worker,timeout)
|
||||
monkeypatch.setattr(Worker,'wait',complete_proof)
|
||||
assert run(False).status=='CANCELLED'
|
||||
assert state['waits']==[5]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('proof_present',[True,False])
|
||||
def test_normal_release_of_ordinary_retained_startup_requires_new_complete_prewrite_proof(tmp_path,monkeypatch,proof_present):
|
||||
from test_registered_startup_release import registered_fixture
|
||||
from cbb_refresh_verify import residual_sessions
|
||||
load=diagnostic_open._load_evidence
|
||||
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch)
|
||||
monkeypatch.setattr(diagnostic_open,'_load_evidence',load)
|
||||
job['diagnostic_only']=False
|
||||
if proof_present:ordinary_proof(job,tmp_path,state['prelaunch_baseline'])
|
||||
(tmp_path/'request.json').write_text(json.dumps(job))
|
||||
result=residual_sessions._request_close(row)
|
||||
assert result['release_status']==('RELEASED' if proof_present else 'WAITING'),result
|
||||
assert messages==([(31,245),(100,16)] if proof_present else [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle',['unknown','hidden_document','progress','foreign_log_pid','foreign_log_path','revoked'])
|
||||
def test_ordinary_cleanup_keeps_native_window_write_and_identity_vetoes(tmp_path,monkeypatch,obstacle):
|
||||
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,
|
||||
obstacle=obstacle if obstacle in ('unknown','progress','foreign_log_pid','foreign_log_path') else '')
|
||||
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
|
||||
read=diagnostic_open._windows
|
||||
def windows(pid):
|
||||
values=read(pid)
|
||||
if values and obstacle=='hidden_document':
|
||||
values[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101,visible=False))
|
||||
if state['declined'] and obstacle=='revoked':
|
||||
with (tmp_path/'events.jsonl').open('a') as stream:stream.write(json.dumps(dict(stage='startup_write_admitted'))+'\n')
|
||||
return values
|
||||
monkeypatch.setattr(diagnostic_open,'_windows',windows)
|
||||
result=failed_session.close_failed_startup(job,12,timeout_seconds=.5)
|
||||
assert result['status']=='RETAINED' and records
|
||||
assert not any(message==16 for _,message in messages)
|
||||
assert messages==[(201,245)]+([(31,245)] if obstacle in ('progress','revoked') else [])
|
||||
|
||||
|
||||
def test_proved_cancelled_startup_cannot_ack_tip_after_absolute_deadline(tmp_path,monkeypatch):
|
||||
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
|
||||
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
|
||||
assert failed_session.close_failed_startup(job,12,timeout_seconds=0)['status']=='RETAINED'
|
||||
assert not messages and records
|
||||
|
||||
|
||||
def test_agent_backend_cannot_dispatch_before_phase_journal():
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify.dialog_supervisor import AgentDialogBackend
|
||||
from cbb_refresh_verify.dialog_models import WindowSnapshot,DialogPhase
|
||||
calls=[]
|
||||
backend=AgentDialogBackend(SimpleNamespace(perform=lambda **kwargs:calls.append('native')),
|
||||
before_action=lambda *args:calls.append('journal'))
|
||||
snapshot=WindowSnapshot(100,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB',DialogPhase.PCB_STARTING,())
|
||||
backend.perform(snapshot,{'action':'confirm_forward_annotation'},DialogPhase.PCB_STARTING)
|
||||
assert calls==['journal','native']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('action',['tip','empty_close'])
|
||||
def test_startup_deadline_is_rechecked_after_window_read_before_post(tmp_path,monkeypatch,action):
|
||||
import win32gui
|
||||
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch,empty_close_first=action=='empty_close')
|
||||
ordinary_proof(job,tmp_path,job['diagnostic_log_baseline'])
|
||||
if action=='tip':
|
||||
snapshot=failed_session._startup_snapshot
|
||||
def read(*args):
|
||||
value=snapshot(*args);state['ticks']=2;return value
|
||||
monkeypatch.setattr(failed_session,'_startup_snapshot',read)
|
||||
else:
|
||||
def children(*args):state['ticks']=2
|
||||
monkeypatch.setattr(win32gui,'EnumChildWindows',children)
|
||||
assert failed_session.close_failed_startup(job,12,timeout_seconds=1)['status']=='RETAINED'
|
||||
assert not messages
|
||||
@@ -0,0 +1,154 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import desktop_worker, session_record, verify_runner as runner
|
||||
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
|
||||
from test_verify_runner import fixture, request, PORTS_OK
|
||||
|
||||
|
||||
def worker_fixture(tmp_path, monkeypatch, *, exited=False):
|
||||
fixture(tmp_path)
|
||||
state = dict(waits=[], closed=False, observers=[], polling=False, polls=0)
|
||||
stop = Event()
|
||||
class Worker:
|
||||
desktop=None; pid=700; companion_pids=[]; returncode=1 if exited else None
|
||||
def __init__(self, command, name):
|
||||
self.name=name
|
||||
path=Path(command[-1]); state.update(path=path,job=json.loads(path.read_text()),worker=self)
|
||||
self.session_record_path=path.with_name('session.json')
|
||||
session_record.write_session_record(self.session_record_path, dict(
|
||||
operation_id=state['job']['operation_id'],library=state['job']['library'],
|
||||
block=state['job']['block']))
|
||||
path.with_name('events.jsonl').write_text(json.dumps(dict(stage='pcb_worker_started',pcb_pid=901))+'\n')
|
||||
path.with_name('outcome.json').write_text(json.dumps(dict(status='CANCELLED',safe_to_continue=False)))
|
||||
def poll(self):return self.returncode
|
||||
def request_stop(self):
|
||||
assert not state['polling']
|
||||
Path(state['job']['cancel_signal']).touch()
|
||||
def native_write_pending(self):return True
|
||||
def wait(self,timeout=5):
|
||||
state['waits'].append(timeout)
|
||||
if timeout <= 5:raise TimeoutError('native startup still closing')
|
||||
self.returncode=1;return 1
|
||||
def automation_release_state(self):return {'safe_to_continue':self.poll() is not None,'remaining_pids':[]}
|
||||
def close(self):state['closed']=True
|
||||
class Supervisor:
|
||||
def poll(self,*args):
|
||||
assert not state['observers']
|
||||
state['polling']=True;state['polls']+=1;stop.set();state['polling']=False
|
||||
return DialogPollResult()
|
||||
monkeypatch.setattr(desktop_worker,'DesktopWorker',Worker)
|
||||
monkeypatch.setattr(runner,'_cleanup_session_processes',lambda *a,**kw:
|
||||
{'safe_to_continue':False,'remaining_pids':[901]})
|
||||
monkeypatch.setattr(session_record,'handoff_session',lambda path,**kw:
|
||||
state['observers'].append((path,kw,state['closed'])))
|
||||
# Keep the task runner deterministic while exercising real supervisor ownership decisions.
|
||||
monkeypatch.setattr('cbb_refresh_verify.operation_queue.hold_native_handoff',lambda *a:None)
|
||||
return state,stop,lambda diagnostic:runner.run_verify(request(tmp_path,diagnostic_only=diagnostic),
|
||||
port_check=PORTS_OK,stop=stop,dialog_supervisor_factory=lambda **kw:Supervisor())
|
||||
|
||||
|
||||
@pytest.mark.parametrize('diagnostic',[True,False])
|
||||
def test_diagnostic_cancel_yields_after_five_seconds_but_write_wait_is_unchanged(tmp_path,monkeypatch,diagnostic):
|
||||
state,stop,run=worker_fixture(tmp_path,monkeypatch)
|
||||
assert run(diagnostic).status=='CANCELLED'
|
||||
assert state['waits']==([5] if diagnostic else [5,115])
|
||||
assert state['observers'] and state['observers'][0][1]['process'] is state['worker']
|
||||
assert not state['observers'][0][2] and not state['closed']
|
||||
assert state['polls']==1
|
||||
|
||||
|
||||
def test_exited_worker_with_live_native_clients_keeps_ownership_for_observer(tmp_path,monkeypatch):
|
||||
state,stop,run=worker_fixture(tmp_path,monkeypatch,exited=True)
|
||||
result=run(True)
|
||||
assert result.status=='CANCELLED' and not result.safe_to_continue
|
||||
assert len(state['observers'])==1, 'worker exit must not orphan the still-live registered native client'
|
||||
path,options,already_closed=state['observers'][0]
|
||||
assert path==state['worker'].session_record_path
|
||||
assert options['process'] is state['worker'] and not already_closed and not state['closed']
|
||||
original=json.loads(state['path'].with_name('result.json').read_text())
|
||||
assert original['status']=='CANCELLED' and not original['safe_to_continue']
|
||||
|
||||
|
||||
def test_failed_observer_registration_preserves_original_cancelled_result_and_handle(tmp_path,monkeypatch):
|
||||
state,stop,run=worker_fixture(tmp_path,monkeypatch,exited=True)
|
||||
def fail(*args,**kwargs):raise OSError('observation journal unavailable')
|
||||
monkeypatch.setattr(session_record,'handoff_session',fail)
|
||||
result=run(True)
|
||||
assert result.status=='CANCELLED' and not result.safe_to_continue
|
||||
assert not state['closed']
|
||||
|
||||
|
||||
def test_missing_operation_identity_cannot_promote_cold_observation(tmp_path,monkeypatch):
|
||||
from types import SimpleNamespace
|
||||
path=tmp_path/'session.json';path.write_text('{invalid')
|
||||
entered,finish=Event(),Event();modes=[]
|
||||
def observe(*args,**kwargs):
|
||||
mode=kwargs['observe_only'];modes.append(mode() if callable(mode) else mode)
|
||||
entered.set();assert finish.wait(3)
|
||||
return dict(status='UNCONFIRMED',operation_id=None)
|
||||
monkeypatch.setattr(session_record,'observe_retained_session',observe)
|
||||
owner=SimpleNamespace(cbb_library=str(tmp_path/'lib.lmc'),poll=lambda:0,close=lambda:None)
|
||||
thread=None
|
||||
try:
|
||||
session_record.handoff_session(path,evidence_root=tmp_path,process=owner,observe_only=True)
|
||||
assert entered.wait(2)
|
||||
thread=session_record._observers[str(path.absolute()).casefold()][0]
|
||||
assert modes==[True]
|
||||
finally:
|
||||
finish.set()
|
||||
if thread:thread.join(3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cold_observer',[False,True])
|
||||
def test_natural_native_exit_gets_fresh_release_and_admits_waiting_scope_without_click(tmp_path,monkeypatch,cold_observer):
|
||||
import subprocess,sys,time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from types import SimpleNamespace
|
||||
from cbb_refresh_verify import library_lock
|
||||
from cbb_refresh_verify.operation_queue import NativeQueue,BatchTaskContext
|
||||
from test_issue15_resource_release import library_file,cleanup
|
||||
library=library_file(tmp_path)
|
||||
gate=tmp_path/'native-exit'
|
||||
native=subprocess.Popen([sys.executable,'-c',
|
||||
'from pathlib import Path; import time,sys\nwhile not Path(sys.argv[1]).exists(): time.sleep(.02)',str(gate)])
|
||||
evidence=tmp_path/'evidence';evidence.mkdir();path=evidence/'session.json'
|
||||
session_record.write_session_record(path,dict(operation_id='cancelled-owned',operation='verify',
|
||||
library=str(library),block='A',processes=[dict(role='native',**session_record.process_identity(native.pid))]))
|
||||
original=evidence/'result.json';original.write_text('{"status":"CANCELLED","safe_to_continue":false}')
|
||||
before=original.read_bytes()
|
||||
with library_lock.LibraryLock(library,block_name='A',safe_to_release=lambda:False) as lease:pass
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *a,**kw:[])
|
||||
active=Event();stop=Event();closed=[]
|
||||
owner=SimpleNamespace(pid=700,poll=lambda:0,close=lambda:closed.append(native.poll()))
|
||||
thread=None
|
||||
try:
|
||||
session_record.handoff_session(path,evidence_root=evidence,process=owner,stop=stop,observe_only=cold_observer,
|
||||
progress=lambda state:active.set() if state['status']=='ACTIVE' else None)
|
||||
assert active.wait(3) and not closed
|
||||
key=str(path.absolute()).casefold()
|
||||
thread=session_record._observers[key][0]
|
||||
if cold_observer:
|
||||
session_record.handoff_session(path,evidence_root=evidence,observe_only=False)
|
||||
assert session_record._observers[key][0] is thread
|
||||
assert not session_record.library_available(library)
|
||||
queue=NativeQueue()
|
||||
def admitted():
|
||||
with library_lock.LibraryLock(library,checkpoint=False):return 'fresh admission'
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
future=pool.submit(queue.run,admitted,context=BatchTaskContext(str(library)),stop=stop)
|
||||
time.sleep(.15);assert not future.done()
|
||||
gate.touch();native.wait(5)
|
||||
assert future.result(8)=='fresh admission'
|
||||
thread.join(3)
|
||||
assert not thread.is_alive() and closed==[0]
|
||||
observations=[json.loads(p.read_text()) for p in evidence.glob('observation-*.json')]
|
||||
assert any(o.get('status')=='RELEASED' and o['release_proof']['proof_block_name']=='A' for o in observations)
|
||||
assert original.read_bytes()==before
|
||||
finally:
|
||||
gate.touch();native.wait(5);stop.set()
|
||||
if thread:thread.join(3)
|
||||
cleanup(lease)
|
||||
@@ -115,7 +115,28 @@ def test_reader_never_creates_a_desktop_or_process(monkeypatch, tmp_path, reader
|
||||
import win32service
|
||||
import win32process
|
||||
import cbb_refresh_verify.mentor_adapter as module
|
||||
from pywinauto import Desktop
|
||||
import sys
|
||||
import pythoncom
|
||||
if 'pywinauto' not in sys.modules:
|
||||
# Match the real worker's STA apartment. pywinauto's first import probes
|
||||
# MTA and may report its fallback; validate that exact diagnostic only.
|
||||
import warnings
|
||||
pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED)
|
||||
try:
|
||||
with warnings.catch_warnings(record=True) as diagnostics:
|
||||
warnings.simplefilter('always')
|
||||
from pywinauto import Desktop
|
||||
for diagnostic in diagnostics:
|
||||
if diagnostic.category is UserWarning and str(diagnostic.message) in (
|
||||
'Revert to STA COM threading mode', 'Apply externally defined coinit_flags: 2'):
|
||||
assert sys.coinit_flags == pythoncom.COINIT_APARTMENTTHREADED
|
||||
else:
|
||||
warnings.warn_explicit(diagnostic.message, diagnostic.category,
|
||||
diagnostic.filename, diagnostic.lineno)
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
else:
|
||||
from pywinauto import Desktop
|
||||
monkeypatch.setattr(Desktop, 'windows', lambda *_: [])
|
||||
|
||||
closed = []
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from test_verify_runner import fixture, request, PORTS_OK
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['', 'no_event', 'wrong_pid', 'wrong_operation', 'wrong_project', 'wrong_desktop', 'ordinary'])
|
||||
def test_only_current_diagnostic_close_leaves_prompt_actions_to_checker(tmp_path, monkeypatch, fault):
|
||||
from cbb_refresh_verify import desktop_worker
|
||||
from cbb_refresh_verify.verify_runner import run_verify
|
||||
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
|
||||
fixture(tmp_path); polls = []
|
||||
class Worker:
|
||||
desktop = None
|
||||
pid = 700
|
||||
companion_pids = []
|
||||
returncode = None
|
||||
count = 0
|
||||
def __init__(self, command, name):
|
||||
self.name = name
|
||||
path = Path(command[-1]); job = json.loads(path.read_text())
|
||||
event = dict(stage='diagnostic_close_requested', close_id='b'*32, pcb_pid=901, hwnd=900,
|
||||
operation_id=job['operation_id'], desktop=job['desktop'], project=job['project'], pcb=job['pcb'])
|
||||
for condition, key, value in [('wrong_pid','pcb_pid',999),('wrong_operation','operation_id','foreign'),
|
||||
('wrong_project','project','foreign.prj'),('wrong_desktop','desktop','Default')]:
|
||||
if fault == condition: event[key] = value
|
||||
events = [dict(stage='pcb_worker_started', pcb_pid=901)]
|
||||
if fault != 'no_event': events.append(event)
|
||||
path.with_name('events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
|
||||
path.with_name('outcome.json').write_text(json.dumps({'status':'FAIL','safe_to_continue':False,
|
||||
'stderr':'DIAGNOSTIC_CLOSE_UNCONFIRMED: unknown prompt retained'}))
|
||||
def poll(self):
|
||||
self.count += 1
|
||||
if self.count > 2: self.returncode = 1
|
||||
return self.returncode
|
||||
def close(self): pass
|
||||
def wait(self, timeout=5): self.returncode = 1; return 1
|
||||
class Supervisor:
|
||||
def poll(self, *args):
|
||||
polls.append(True)
|
||||
return DialogPollResult(error_code='UNKNOWN_DIALOG', detail='competing save prompt')
|
||||
monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker)
|
||||
result = run_verify(request(tmp_path, diagnostic_only=fault!='ordinary'), port_check=PORTS_OK,
|
||||
dialog_supervisor_factory=lambda **kwargs:Supervisor())
|
||||
assert result.status == 'FAIL'
|
||||
assert json.loads(result.evidence_path.with_name('outcome.json').read_text())['safe_to_continue'] is False
|
||||
if not fault:
|
||||
assert polls == []
|
||||
assert 'DIAGNOSTIC_CLOSE_UNCONFIRMED' in result.stderr
|
||||
else:
|
||||
assert polls and 'UNKNOWN_DIALOG' in result.stderr
|
||||
@@ -0,0 +1,136 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from test_verify_runner import fixture, request, PORTS_OK
|
||||
from test_diagnostic_open import job, write_logs, frame, Session
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['', 'foreign_operation', 'ordinary', 'missing_nonce'])
|
||||
def test_close_handoff_arriving_during_poll_prevents_competing_abort(tmp_path, monkeypatch, fault):
|
||||
from cbb_refresh_verify import desktop_worker
|
||||
from cbb_refresh_verify.verify_runner import run_verify
|
||||
from cbb_refresh_verify.dialog_supervisor import DialogPollResult
|
||||
fixture(tmp_path); state = {}
|
||||
class Worker:
|
||||
desktop = None; pid = 700; companion_pids = []; returncode = None; count = 0
|
||||
def __init__(self, command, name):
|
||||
self.name = name
|
||||
path = Path(command[-1]); state.update(path=path, job=json.loads(path.read_text()))
|
||||
path.with_name('events.jsonl').write_text(json.dumps(dict(stage='pcb_worker_started', pcb_pid=901))+'\n')
|
||||
path.with_name('outcome.json').write_text(json.dumps(dict(status='FAIL', safe_to_continue=False,
|
||||
stderr='DIAGNOSTIC_CLOSE_UNCONFIRMED: checker retained unknown prompt')))
|
||||
def poll(self):
|
||||
self.count += 1
|
||||
if self.count > 2: self.returncode = 1
|
||||
return self.returncode
|
||||
def close(self): pass
|
||||
def wait(self, timeout=5): self.returncode = 1; return 1
|
||||
class Supervisor:
|
||||
def poll(self, *args):
|
||||
j = state['job']
|
||||
event = dict(stage='diagnostic_close_requested', close_id='a'*32, pcb_pid=901, hwnd=900,
|
||||
operation_id=j['operation_id'], desktop=j['desktop'], project=j['project'], pcb=j['pcb'])
|
||||
if fault == 'foreign_operation': event['operation_id'] = 'foreign'
|
||||
if fault == 'missing_nonce': event.pop('close_id')
|
||||
with state['path'].with_name('events.jsonl').open('a') as stream:
|
||||
stream.write(json.dumps(event)+'\n')
|
||||
return DialogPollResult(error_code='UNKNOWN_DIALOG', detail='in-flight competing save prompt')
|
||||
monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker)
|
||||
result = run_verify(request(tmp_path, diagnostic_only=fault!='ordinary'), port_check=PORTS_OK,
|
||||
dialog_supervisor_factory=lambda **kw: Supervisor())
|
||||
assert result.status == 'FAIL'
|
||||
ack = state['path'].with_name('diagnostic-close-ack.json')
|
||||
if fault:
|
||||
assert 'UNKNOWN_DIALOG' in result.stderr and not ack.exists()
|
||||
else:
|
||||
assert 'DIAGNOSTIC_CLOSE_UNCONFIRMED' in result.stderr
|
||||
assert 'UNKNOWN_DIALOG' not in result.stderr
|
||||
assert json.loads(ack.read_text())['close_id'] == 'a'*32
|
||||
|
||||
|
||||
def test_checker_never_posts_close_before_bound_supervisor_ack(job, monkeypatch):
|
||||
from cbb_refresh_verify import diagnostic_open as diagnostic
|
||||
job['operation_id'] = 'verify-protocol'
|
||||
Path(job['root']).mkdir(exist_ok=True)
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job); events = []
|
||||
ack = Path(job['root'])/'diagnostic-close-ack.json'
|
||||
class AcknowledgedSession(Session):
|
||||
def post(self, hwnd, message):
|
||||
assert ack.exists(), 'WM_CLOSE raced ahead of supervisor ownership acknowledgement'
|
||||
assert events[-1]['stage'] == 'diagnostic_close_requested'
|
||||
super().post(hwnd, message)
|
||||
def emit(**event):
|
||||
events.append(event)
|
||||
if event['stage'] == 'diagnostic_close_requested':
|
||||
ack.write_text(json.dumps({k:v for k,v in event.items() if k != 'stage'}))
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', AcknowledgedSession)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)] if Session.instances[-1].alive else [])
|
||||
assert diagnostic.check_target_window(job, 42, emit=emit, error_reader=lambda: None)['status'] == 'PASS'
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['missing', 'stale_nonce', 'foreign_pid', 'foreign_project',
|
||||
'foreign_desktop', 'cancel_wait', 'cancel_ack', 'late_ack'])
|
||||
def test_missing_stale_cancelled_or_late_ack_preserves_native(job, monkeypatch, fault):
|
||||
from cbb_refresh_verify import diagnostic_open as diagnostic
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
offset = [0]; clock = time.monotonic
|
||||
cancel = Path(job['root'])/'cancel.signal'; job['cancel_signal'] = str(cancel)
|
||||
def wait(_):
|
||||
if fault == 'cancel_wait': cancel.touch()
|
||||
else: offset[0] += 31
|
||||
monkeypatch.setattr(diagnostic, 'time', SimpleNamespace(monotonic=lambda:clock()+offset[0], sleep=wait))
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
monkeypatch.setattr(diagnostic, '_windows', lambda pid: [frame(job)])
|
||||
def emit(**event):
|
||||
if event['stage'] != 'diagnostic_close_requested': return
|
||||
if fault in ('missing', 'cancel_wait'): return
|
||||
ack = {k:v for k,v in event.items() if k != 'stage'}
|
||||
for condition,key,value in [('stale_nonce','close_id','0'*32),('foreign_pid','pcb_pid',99),
|
||||
('foreign_project','project','foreign'),('foreign_desktop','desktop','Default')]:
|
||||
if fault == condition: ack[key] = value
|
||||
(Path(job['root'])/'diagnostic-close-ack.json').write_text(json.dumps(ack))
|
||||
if fault == 'cancel_ack': cancel.touch()
|
||||
if fault == 'late_ack': offset[0] += 31
|
||||
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED' if fault.startswith('cancel') else 'DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||
diagnostic.check_target_window(job,42,emit=emit,error_reader=lambda:None)
|
||||
assert Session.instances[-1].alive and Session.instances[-1].posted == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['progress', 'disabled', 'hwnd', 'pid', 'unknown', 'forward', 'native_error', 'cancel_recheck'])
|
||||
def test_ready_frame_and_prompt_are_revalidated_after_ack(job, monkeypatch, change):
|
||||
from cbb_refresh_verify import diagnostic_open as diagnostic
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job); acknowledged = []
|
||||
job['cancel_signal'] = str(Path(job['root'])/'cancel.signal')
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
def windows(pid):
|
||||
target = frame(job); rows = [target]
|
||||
if not acknowledged: return rows
|
||||
if change == 'progress': target['children'].append({'class':'msctls_progress32','visible':True})
|
||||
if change == 'disabled': target['enabled'] = False
|
||||
if change == 'hwnd': target['hwnd'] = 99
|
||||
if change == 'pid': target['pid'] = 99
|
||||
if change == 'cancel_recheck': Path(job['cancel_signal']).touch()
|
||||
if change == 'unknown': rows.append({'hwnd':20,'pid':42,'class':'#32770','text':'Unknown','children':[]})
|
||||
if change == 'forward': rows.append({'hwnd':20,'pid':42,'class':'#32770','text':'Expedition PCB','owner':10,
|
||||
'children':[{'class':'Static','id':6172,'text':'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'},
|
||||
{'hwnd':21,'class':'Button','id':7,'text':'No'}, {'hwnd':22,'class':'Button','id':6,'text':'Yes'}]})
|
||||
return rows
|
||||
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||
def emit(**event):
|
||||
if event['stage'] == 'diagnostic_close_requested':
|
||||
(Path(job['root'])/'diagnostic-close-ack.json').write_text(json.dumps({k:v for k,v in event.items() if k!='stage'}))
|
||||
acknowledged.append(True)
|
||||
def error():
|
||||
return 'ICDB_INCONSISTENT: fresh error after handoff' if change == 'native_error' and acknowledged else None
|
||||
expected = {'native_error':'ICDB_INCONSISTENT', 'cancel_recheck':'VERIFY_CANCELLED'}.get(change, 'DIAGNOSTIC_CLOSE_UNCONFIRMED')
|
||||
with pytest.raises(RuntimeError, match=expected):
|
||||
diagnostic.check_target_window(job,42,emit=emit,error_reader=error)
|
||||
assert acknowledged and Session.instances[-1].posted == []
|
||||
@@ -1,14 +1,25 @@
|
||||
import importlib
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def diagnostic():
|
||||
def diagnostic(monkeypatch):
|
||||
assert importlib.util.find_spec('cbb_refresh_verify.diagnostic_open') is not None, 'diagnostic open module is missing'
|
||||
return importlib.import_module('cbb_refresh_verify.diagnostic_open')
|
||||
module = importlib.import_module('cbb_refresh_verify.diagnostic_open')
|
||||
check = module.check_target_window
|
||||
def acknowledged(job, pid, *, emit, **kwargs):
|
||||
def parent(**event):
|
||||
emit(**event)
|
||||
if event['stage'] == 'diagnostic_close_requested':
|
||||
(Path(job['root'])/'diagnostic-close-ack.json').write_text(json.dumps(
|
||||
{key:value for key,value in event.items() if key != 'stage'}))
|
||||
return check(job, pid, emit=parent, **kwargs)
|
||||
monkeypatch.setattr(module, 'check_target_window', acknowledged)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -17,8 +28,9 @@ def job(tmp_path):
|
||||
pcb = project / 'PCB/IP101GR.pcb'
|
||||
pcb.parent.mkdir(parents=True)
|
||||
pcb.write_bytes(b'pcb')
|
||||
(tmp_path/'evidence').mkdir()
|
||||
return {'project': str(project / 'IP101GR.prj'), 'pcb': str(pcb), 'root': str(tmp_path / 'evidence'),
|
||||
'desktop': 'CbbDiagnosticTest', 'timeout': .03}
|
||||
'desktop': 'CbbDiagnosticTest', 'operation_id': 'verify-fixture', 'timeout': .03}
|
||||
|
||||
|
||||
def write_logs(job, *, pid=42, foreign=False, success=True):
|
||||
@@ -83,6 +95,78 @@ def test_target_title_without_target_mdi_does_not_pass(diagnostic, job):
|
||||
assert diagnostic._target_frame([window], Path(job['pcb']).stem) is None
|
||||
|
||||
|
||||
def test_visible_loading_progress_is_not_ready_for_diagnostic_close(diagnostic, job):
|
||||
window = frame(job)
|
||||
progress = {'hwnd': 13, 'class': 'msctls_progress32', 'text': '', 'visible': True}
|
||||
window['children'].append(progress)
|
||||
assert diagnostic._target_frame([window], 'IP101GR') is None
|
||||
progress['visible'] = False
|
||||
assert diagnostic._target_frame([window], 'IP101GR') == window
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cancel', [False, True])
|
||||
def test_persistent_loading_progress_keeps_deadline_and_never_closes(diagnostic, job, monkeypatch, cancel):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
signal = Path(job['root']).parent/'cancel-progress'
|
||||
job['cancel_signal'] = str(signal)
|
||||
target = frame(job)
|
||||
target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True})
|
||||
def windows(pid):
|
||||
if cancel: signal.touch()
|
||||
return [target]
|
||||
monkeypatch.setattr(diagnostic,'_NativeSession',Session)
|
||||
monkeypatch.setattr(diagnostic,'_windows',windows)
|
||||
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED' if cancel else 'DIAGNOSTIC_OPEN_UNCONFIRMED'):
|
||||
diagnostic.check_target_window(job,42,emit=lambda **event:None,error_reader=lambda:None)
|
||||
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):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job); job['timeout'] = 1
|
||||
class ForwardSession(Session):
|
||||
declined = False
|
||||
def post(self, hwnd, message):
|
||||
self.posted.append((hwnd,message))
|
||||
if hwnd == 31: self.declined = True
|
||||
else: self.alive = False
|
||||
def windows(pid):
|
||||
state = Session.instances[-1]
|
||||
target = frame(job)
|
||||
if state.declined: return [target] if state.alive else []
|
||||
target['enabled'] = False
|
||||
target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True})
|
||||
return [target, {'hwnd':20,'pid':42,'class':'#32770','text':'Expedition PCB','owner':10,
|
||||
'children':[{'hwnd':30,'class':'Static','id':6172,'text':'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'},
|
||||
{'hwnd':31,'class':'Button','id':7,'text':'&No','enabled':True},
|
||||
{'hwnd':32,'class':'Button','id':6,'text':'&Yes','enabled':True}]}]
|
||||
monkeypatch.setattr(diagnostic,'_NativeSession',ForwardSession)
|
||||
monkeypatch.setattr(diagnostic,'_windows',windows)
|
||||
assert diagnostic.check_target_window(job,42,emit=lambda **event:None,error_reader=lambda:None)['status']=='PASS'
|
||||
assert Session.instances[-1].posted == [(31,0xF5),(10,0x10)]
|
||||
|
||||
|
||||
class Session:
|
||||
instances = []
|
||||
def __init__(self, job, pid, launcher):
|
||||
@@ -127,6 +211,87 @@ def test_success_posts_one_exact_close_and_reports_only_open_check(diagnostic, j
|
||||
assert Session.instances[-1].closed
|
||||
|
||||
|
||||
@pytest.mark.parametrize('incomplete_scan', [1, 2, 3])
|
||||
def test_transient_incomplete_scan_is_retried_without_acting_on_partial_windows(diagnostic, job, monkeypatch, incomplete_scan):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
job['timeout'] = 1
|
||||
write_logs(job)
|
||||
class ClosingSession(Session):
|
||||
closing = False
|
||||
def post(self, hwnd, message):
|
||||
self.posted.append((hwnd, message))
|
||||
self.closing = True
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', ClosingSession)
|
||||
scans = []
|
||||
def windows(pid):
|
||||
scans.append(True)
|
||||
if len(scans) == incomplete_scan:
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s')
|
||||
if Session.instances[-1].closing:
|
||||
Session.instances[-1].alive = False
|
||||
return []
|
||||
return [frame(job)]
|
||||
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||
events = []
|
||||
result = diagnostic.check_target_window(job, 42, emit=lambda **event:events.append(event), error_reader=lambda:None)
|
||||
assert result['status'] == 'PASS'
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
assert any(e['stage'] == 'diagnostic_window_retry' for e in events)
|
||||
|
||||
|
||||
def test_incomplete_scans_keep_original_open_deadline_and_never_close(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
calls = []
|
||||
def windows(pid):
|
||||
calls.append(True)
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s')
|
||||
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_WINDOW_LIMIT'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event:None, error_reader=lambda:None)
|
||||
assert len(calls) <= 3
|
||||
assert Session.instances[-1].posted == []
|
||||
|
||||
|
||||
def test_cancel_during_incomplete_scan_stops_retry_without_close(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
job['timeout'] = 10
|
||||
cancel = Path(job['root']).parent/'cancel-scan'
|
||||
job['cancel_signal'] = str(cancel)
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
|
||||
calls = []
|
||||
def windows(pid):
|
||||
calls.append(True)
|
||||
cancel.touch()
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s')
|
||||
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 len(calls) == 1 and Session.instances[-1].posted == []
|
||||
|
||||
|
||||
def test_incomplete_close_scan_cannot_extend_thirty_second_deadline(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
clock, offset = diagnostic.time.monotonic, [0]
|
||||
monkeypatch.setattr(diagnostic.time, 'monotonic', lambda:clock()+offset[0])
|
||||
class ClosingSession(Session):
|
||||
closing = False
|
||||
def post(self, hwnd, message):
|
||||
self.posted.append((hwnd, message))
|
||||
self.closing = True
|
||||
monkeypatch.setattr(diagnostic, '_NativeSession', ClosingSession)
|
||||
def windows(pid):
|
||||
if Session.instances[-1].closing:
|
||||
offset[0] = 31
|
||||
raise RuntimeError('DIAGNOSTIC_WINDOW_LIMIT: window scan exceeded 0.2s')
|
||||
return [frame(job)]
|
||||
monkeypatch.setattr(diagnostic, '_windows', windows)
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_WINDOW_LIMIT'):
|
||||
diagnostic.check_target_window(job, 42, emit=lambda **event:None, error_reader=lambda:None)
|
||||
assert Session.instances[-1].posted == [(10, 0x10)]
|
||||
|
||||
|
||||
def test_transient_startup_window_cannot_abort_before_target_is_loaded(diagnostic, job, monkeypatch):
|
||||
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
|
||||
write_logs(job)
|
||||
@@ -336,3 +501,37 @@ def test_recycled_window_from_another_pid_never_receives_close(diagnostic, monke
|
||||
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda hwnd: (1, 99))
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_STALE_WINDOW'):
|
||||
session.post(10, 0x10)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault', ['', 'foreign_pid', 'cycle', 'other_frame', 'visible', 'enabled', 'class', 'title', 'desktop', 'incomplete', 'filename'])
|
||||
def test_diagnostic_save_accepts_only_complete_hidden_owner_chain(diagnostic, job, fault):
|
||||
target = frame(job)
|
||||
owner = {'hwnd': 15, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
|
||||
'owner': 10, 'visible': False, 'enabled': False, 'same_desktop': True}
|
||||
end = {**target, 'same_desktop': True}
|
||||
window = {'hwnd': 20, 'pid': 42, 'class': '#32770', 'text': 'Expedition PCB',
|
||||
'owner': 15, 'owner_chain': [owner, end], 'children': [
|
||||
{'hwnd': 30, 'class': 'Static', 'text': 'Save changes to IP101GR.pcb?', 'id': -1},
|
||||
{'hwnd': 31, 'class': 'Button', 'text': '否(&N)', 'id': 7},
|
||||
{'hwnd': 32, 'class': 'Button', 'text': '是(&Y)', 'id': 6},
|
||||
{'hwnd': 33, 'class': 'Button', 'text': '取消', 'id': 2}]}
|
||||
if fault == 'foreign_pid': owner['pid'] = 99
|
||||
if fault == 'cycle': owner['owner'] = 15
|
||||
if fault == 'other_frame': end['hwnd'] = 99
|
||||
if fault == 'visible': owner['visible'] = True
|
||||
if fault == 'enabled': owner['enabled'] = True
|
||||
if fault == 'class': owner['class'] = 'VendorDialog'
|
||||
if fault == 'title': owner['text'] = 'Unknown recovery'
|
||||
if fault == 'desktop': owner['same_desktop'] = False
|
||||
if fault == 'incomplete': window['owner_chain'] = [owner]
|
||||
if fault == 'filename': window['children'][0]['text'] = 'Save changes to Foreign.pcb?'
|
||||
session = Session(job, 42, None)
|
||||
action = lambda:diagnostic._pending_prompt([window], closing=True, frame=target,
|
||||
session=session, clicked=set(), pcb_name='IP101GR.pcb')
|
||||
if not fault:
|
||||
assert action() is False
|
||||
assert session.posted == [(31, 0xF5)]
|
||||
else:
|
||||
with pytest.raises(RuntimeError, match='DIAGNOSTIC_CLOSE_UNCONFIRMED'):
|
||||
action()
|
||||
assert session.posted == []
|
||||
@@ -179,3 +179,13 @@ def test_probe_skips_project_integration_panel_during_com_phase():
|
||||
snapshots = make_probe(gui, (10,)).capture(DialogPhase.PROJECT_INTEGRATION)
|
||||
|
||||
assert snapshots == ()
|
||||
|
||||
|
||||
def test_save_integration_panel_uses_complete_win32_controls_without_huge_uia_tree():
|
||||
gui=FakeGui({10:{'class_name':'#32770','text':'Project Integration','owner':99},
|
||||
11:{'class_name':'Button','text':'&Close','control_id':2}},children={10:(11,)})
|
||||
probe=make_probe(gui,(10,),FakeUia(error=AssertionError('unnecessary large UIA panel scan')))
|
||||
probe.process_name_reader=lambda _: 'ExpeditionPCB.exe'
|
||||
snapshot=probe.capture(DialogPhase.SAVE,pids={1010})[0]
|
||||
assert snapshot.controls[0].control_id==2
|
||||
assert snapshot.diagnostics==()
|
||||
@@ -15,6 +15,15 @@ from cbb_refresh_verify.dialog_rules import (
|
||||
ASSETS = Path(__file__).resolve().parents[1] / "src" / "cbb_refresh_verify" / "assets"
|
||||
|
||||
|
||||
def test_diagnostic_forward_prompt_is_observed_while_ordinary_verify_still_confirms():
|
||||
text = 'New changes are ready for Forward Annotation. Do you want to Forward Annotate now?'
|
||||
snapshot = prompt(text)
|
||||
ordinary = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json'))
|
||||
diagnostic = decide(snapshot, load_rules(ASSETS/'dialog_rules.v1.json', diagnostic_only=True))
|
||||
assert ordinary.action == 'confirm_forward_annotation'
|
||||
assert diagnostic.category == 'OBSERVE_PROGRESS' and not diagnostic.action
|
||||
|
||||
|
||||
def prompt(text, *, phase=DialogPhase.PCB_STARTING, window_class="#32770",
|
||||
control_types=("Text", "Button")):
|
||||
controls = tuple(
|
||||
@@ -244,3 +253,41 @@ def test_database_open_failure_is_classified_and_declines_log_view():
|
||||
assert decision.category == 'FATAL_ACK'
|
||||
assert decision.error_code == 'MENTOR_DATABASE_LOAD_FAILED'
|
||||
assert dict(decision.target)['control_id'] == 7 # IDNO, never launch another log viewer
|
||||
|
||||
|
||||
def completed_integration_panel():
|
||||
texts={1033:'No connectivity changes to be forward annotated',
|
||||
1032:'No pending schematic CES changes to load into PCB',
|
||||
1035:'No pending PCB changes to be back annotated',
|
||||
1034:'No pending CES changes to load into PCB'}
|
||||
return WindowSnapshot(hwnd=10,pid=20,process_name='ExpeditionPCB.exe',process_role='pcb',
|
||||
window_class='#32770',title='Project Integration',phase=DialogPhase.SAVE,owner_hwnd=99,
|
||||
controls=(ControlSnapshot(handle=12,control_id=2,class_name='Button',name='&Close'),
|
||||
*(ControlSnapshot(handle=i,control_id=i,class_name='Static',name=text) for i,text in texts.items())))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('phase',[DialogPhase.SAVE,DialogPhase.CLOSE])
|
||||
def test_completed_integration_panel_only_closes_its_exact_close_control(phase):
|
||||
from dataclasses import replace
|
||||
decision=decide(replace(completed_integration_panel(),phase=phase),load_rules(ASSETS/'dialog_rules.v1.json'))
|
||||
assert decision.action=='close_completed_integration'
|
||||
assert decision.channels==('win32_button_click',)
|
||||
assert dict(decision.target)=={'control_id':2}
|
||||
assert decision.postcondition=='window_gone' and not decision.error_code
|
||||
|
||||
|
||||
@pytest.mark.parametrize('fault',['pending','missing','duplicate','partial','foreign','unowned','disabled','early','error'])
|
||||
def test_integration_panel_without_complete_owned_idle_proof_never_closes(fault):
|
||||
from dataclasses import replace
|
||||
panel=completed_integration_panel()
|
||||
if fault=='pending': panel=replace(panel,controls=(*panel.controls[:-1],replace(panel.controls[-1],name='CES changes are pending')))
|
||||
elif fault=='missing': panel=replace(panel,controls=panel.controls[:-1])
|
||||
elif fault=='duplicate': panel=replace(panel,controls=(*panel.controls,panel.controls[-1]))
|
||||
elif fault=='partial': panel=replace(panel,diagnostics=('WINDOW_ENUM_INCOMPLETE',))
|
||||
elif fault=='foreign': panel=replace(panel,process_name='Unrelated.exe',process_role='unknown')
|
||||
elif fault=='unowned': panel=replace(panel,owner_hwnd=0)
|
||||
elif fault=='disabled': panel=replace(panel,controls=(replace(panel.controls[0],enabled=False),*panel.controls[1:]))
|
||||
elif fault=='early': panel=replace(panel,phase=DialogPhase.DOCUMENT_ATTACH)
|
||||
elif fault=='error': panel=replace(panel,controls=(*panel.controls,
|
||||
ControlSnapshot(handle=500,control_id=500,class_name='Static',name='There were errors during Project Integration.')))
|
||||
assert decide(panel,load_rules(ASSETS/'dialog_rules.v1.json')).action!='close_completed_integration'
|
||||
@@ -54,7 +54,7 @@ def test_preflight_rejects_pcb_junction_outside_current_block(tmp_path):
|
||||
preflight(VerifyRequest(library, 'CBB', tmp_path/'evidence'))
|
||||
|
||||
|
||||
def test_serial_guard_covers_preflight_and_content_check(tmp_path, monkeypatch):
|
||||
def test_nonnative_preparation_leaves_real_host_channel_available(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import verify_runner as runner
|
||||
entered, release = Event(), Event()
|
||||
calls, results = [], []
|
||||
@@ -70,14 +70,14 @@ def test_serial_guard_covers_preflight_and_content_check(tmp_path, monkeypatch):
|
||||
thread.start()
|
||||
assert entered.wait(3)
|
||||
try:
|
||||
second = runner.run_verify(VerifyRequest(tmp_path/'lib.lmc', 'second', tmp_path/'evidence'))
|
||||
assert second.status == 'BLOCKED'
|
||||
assert second.safe_to_continue
|
||||
assert second.error_category == 'NATIVE_CHANNEL_BUSY'
|
||||
from cbb_refresh_verify.operation_queue import native_channel
|
||||
with native_channel():
|
||||
pass
|
||||
assert calls == ['first']
|
||||
finally:
|
||||
release.set()
|
||||
thread.join(6)
|
||||
assert results[0].status == 'PASS'
|
||||
|
||||
|
||||
def test_recovery_retains_temporary_network_mapping():
|
||||
|
||||
@@ -7,8 +7,9 @@ from cbb_refresh_verify import failed_session, mentor_adapter
|
||||
|
||||
|
||||
def startup_fixture(tmp_path, monkeypatch):
|
||||
import win32gui, win32process
|
||||
from cbb_refresh_verify import native_repair_ui
|
||||
from contextlib import nullcontext
|
||||
import win32gui, win32process, win32event, win32con
|
||||
from cbb_refresh_verify import native_repair_ui, residual_sessions
|
||||
job = {'root': str(tmp_path), 'pcb': str(tmp_path/'PCB/CBB.pcb'),
|
||||
'project': str(tmp_path/'CBB.prj'), 'lmc_file': str(tmp_path/'lib.lmc'),
|
||||
'desktop': 'CbbVerify_test'}
|
||||
@@ -20,6 +21,12 @@ def startup_fixture(tmp_path, monkeypatch):
|
||||
records = [(12, r'C:\Mentor\wg\ExpeditionPCB.exe',
|
||||
f'ExpeditionPCB.exe "{job["pcb"]}" -ReusableCircuit', 11)]
|
||||
monkeypatch.setattr(mentor_adapter, '_process_details', lambda _: list(records))
|
||||
monkeypatch.setattr(residual_sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
|
||||
monkeypatch.setattr(residual_sessions, '_handle_identity', lambda h:
|
||||
{'created_handle': 'original', 'image': r'C:\Mentor\wg\ExpeditionPCB.exe'})
|
||||
monkeypatch.setattr(residual_sessions, '_process_windows', lambda pids: {12: []})
|
||||
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *a:
|
||||
win32con.WAIT_TIMEOUT if records else win32con.WAIT_OBJECT_0)
|
||||
monkeypatch.setattr(native_repair_ui, '_current_desktop_name', lambda: 'CbbVerify_test')
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: fn(100, arg))
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
from threading import Event,Thread
|
||||
|
||||
from cbb_refresh_verify.operation_queue import QueueCancelled
|
||||
from test_issue15_ui_integration import window_for
|
||||
|
||||
|
||||
def test_actual_global_stop_button_cancels_running_and_same_app_queued_jobs(qtbot,tmp_path,monkeypatch):
|
||||
window=window_for(qtbot,tmp_path,monkeypatch)
|
||||
first=window._new_job('verify',library=tmp_path/'lib.lmc')
|
||||
second=window._new_job('native_session',library=tmp_path/'lib.lmc')
|
||||
entered,release,waiting,done=Event(),Event(),Event(),Event();calls=[];errors=[]
|
||||
def current():
|
||||
calls.append('first');entered.set();release.wait(3)
|
||||
def run_first():
|
||||
try:window.native_queue.run(current,context=first.context,stop=first.context.stop)
|
||||
except QueueCancelled:pass
|
||||
def queued():
|
||||
try:window.native_queue.run(lambda:calls.append('second'),context=second.context,
|
||||
stop=second.context.stop,waiting=waiting.set)
|
||||
except QueueCancelled as error:errors.append(error)
|
||||
finally:done.set()
|
||||
a=Thread(target=run_first);b=Thread(target=queued)
|
||||
a.start();assert entered.wait(2);b.start()
|
||||
try:
|
||||
qtbot.waitUntil(waiting.is_set);window._update()
|
||||
assert window.stop_button.isEnabled()
|
||||
window.stop_button.click()
|
||||
qtbot.waitUntil(done.is_set)
|
||||
assert first.context.stop.is_set() and second.context.stop.is_set()
|
||||
assert calls==['first'] and len(errors)==1
|
||||
finally:
|
||||
release.set();a.join(3);b.join(3)
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Batch ICDB checks open diagnostically without dispatching Repair."""
|
||||
from cbb_refresh_verify.ui import timed_prompt
|
||||
from dataclasses import replace
|
||||
import json
|
||||
|
||||
@@ -93,7 +94,7 @@ def test_ui_check_summary_reports_findings_and_never_claims_repair(qtbot, tmp_pa
|
||||
verifier=lambda req: (requests.append(req) or VerifyResult('FAIL',
|
||||
error_category='ICDB_REPAIR_REQUIRED', stderr='发现 ICDB 问题,未执行修复。')),
|
||||
status_refresher=lambda names, _: {name: 'PENDING' for name in names})
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes))
|
||||
monkeypatch.setattr(timed_prompt, 'question', lambda *a, **k: (prompts.append(a[2]) or QMessageBox.Yes))
|
||||
window.search_edit.setText('Beta')
|
||||
window.icdb_repair_button.click(); qtbot.waitUntil(lambda: not window._icdb_active())
|
||||
assert requests[0].maintenance and not requests[0].auto_repair
|
||||
|
||||
@@ -277,7 +277,8 @@ def test_contents_session_loss_records_each_item_without_launching_pcb_or_repair
|
||||
assert results[1].error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
|
||||
|
||||
def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch):
|
||||
@pytest.mark.parametrize('fault', ['session_loss', 'inconsistent'])
|
||||
def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, monkeypatch, fault):
|
||||
from test_verify_runner import fixture, request
|
||||
from cbb_refresh_verify.icdb_recovery import snapshot_log
|
||||
from cbb_refresh_verify.verify_diagnostics import failure_logs_main
|
||||
@@ -292,7 +293,8 @@ def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, mon
|
||||
(root/'diagnostics').mkdir()
|
||||
(root/'diagnostics/startup-log-baseline.json').write_text(json.dumps({
|
||||
'source': str(log), 'baseline': snapshot_log(log)}), encoding='utf-8')
|
||||
log.write_text(ERROR, encoding='utf-8')
|
||||
from test_issue15_native_entry import inconsistency
|
||||
log.write_text(ERROR if fault == 'session_loss' else inconsistency(work/'database'), encoding='utf-8')
|
||||
(root/'outcome.json').write_text(json.dumps({
|
||||
'status': 'FAIL', 'stderr': 'MENTOR_DATABASE_LOAD_FAILED: opening failed',
|
||||
'safe_to_continue': False}), encoding='utf-8')
|
||||
@@ -305,7 +307,11 @@ def test_supervisor_enriches_generic_failure_from_fresh_native_log(tmp_path, mon
|
||||
assert result.error_category == 'ICDB_REPAIR_REQUIRED'
|
||||
assert result.safe_to_continue is True
|
||||
assert 'opening failed' in result.stderr
|
||||
assert '200091-CBB' in result.stderr
|
||||
assert '__ReusableBlocksSymb' in result.stderr
|
||||
assert '2026-10-24 08.22.29-10308' in result.stderr
|
||||
if fault == 'session_loss':
|
||||
assert '200091-CBB' in result.stderr
|
||||
assert '__ReusableBlocksSymb' in result.stderr
|
||||
assert '2026-10-24 08.22.29-10308' in result.stderr
|
||||
else:
|
||||
assert str(work/'database') in result.stderr
|
||||
assert '未修复' in result.stderr
|
||||
assert json.loads(result.evidence_path.read_text('utf-8'))['error_category'] == 'ICDB_REPAIR_REQUIRED'
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Normal imports must not depend on optional schematic export tools."""
|
||||
from cbb_refresh_verify.ui import timed_prompt
|
||||
from dataclasses import replace
|
||||
import json
|
||||
|
||||
@@ -57,7 +58,7 @@ def test_bad_source_row_does_not_prevent_valid_rows_from_starting(qtbot, tmp_pat
|
||||
r.auto_verify, 'complete', 'UPLOAD_FAILED' if r.name == 'Missing' else 'UPLOADED',
|
||||
True, 'per-item result') for r in requests]
|
||||
dialog = ManagementDialog(rows, runner=runner); qtbot.addWidget(dialog)
|
||||
monkeypatch.setattr(QMessageBox, 'question', lambda *_a, **_kw: QMessageBox.Yes)
|
||||
monkeypatch.setattr(timed_prompt, 'question', lambda *_a, **_kw: QMessageBox.Yes)
|
||||
dialog.execute_button.click()
|
||||
qtbot.waitUntil(lambda: bool(seen) and not dialog.busy)
|
||||
assert [r.name for r in seen] == ['Missing', 'Good']
|
||||
@@ -96,7 +97,7 @@ def test_native_project_normalization_is_a_recorded_difference_not_import_failur
|
||||
def worker(adapter, job, evidence):
|
||||
result = original_worker(adapter, job, evidence)
|
||||
if job['operation'] == 'add' and result.get('success'):
|
||||
project = request.library.parent/'ReusableBlocksLP/Block/Work/Source.prj'
|
||||
project = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj'
|
||||
with project.open('a') as stream:
|
||||
stream.write('SECTION VBPCBIndicators\nKEY VBPCBForwardAnno "0"\nKEY CADBackAnno "0"\nENDSECTION\n')
|
||||
return result
|
||||
@@ -105,7 +106,7 @@ def test_native_project_normalization_is_a_recorded_difference_not_import_failur
|
||||
assert result.status == 'UPLOADED' and result.safe_to_continue, result.detail
|
||||
comparison = json.loads((result.evidence_path.parent/'add/identity-comparison.json').read_text())
|
||||
assert comparison['identity_matches'] and not comparison['assets_match']
|
||||
assert 'Source.prj' in comparison['asset_differences']['modified']
|
||||
assert 'Block.prj' in comparison['asset_differences']['modified']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('registered_top,expected', [('Block', 'UPLOADED'), ('Foreign', 'RECOVERY_REQUIRED')])
|
||||
@@ -116,7 +117,7 @@ def test_native_top_block_may_match_registration_name_but_not_an_unrelated_name(
|
||||
def worker(adapter, job, evidence):
|
||||
result = original_worker(adapter, job, evidence)
|
||||
if job['operation'] == 'add' and result.get('success'):
|
||||
project = request.library.parent/'ReusableBlocksLP/Block/Work/Source.prj'
|
||||
project = request.library.parent/'ReusableBlocksLP/Block/Work/Block.prj'
|
||||
project.write_text(project.read_text().replace('KEY RootBlock "Top"', f'KEY RootBlock "{registered_top}"'))
|
||||
return result
|
||||
monkeypatch.setattr(native.NativeManagementAdapter, '_worker', worker)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""A fresh confirmed operation may recover data; historical requests never replay."""
|
||||
from dataclasses import replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from test_management import setup, execute
|
||||
|
||||
|
||||
@pytest.mark.parametrize('proof_case', ['fresh','none','wrong_library','wrong_block','cached','live_writer'])
|
||||
def test_confirmed_retry_requires_fresh_exact_resource_proof(setup,monkeypatch,proof_case):
|
||||
request,adapter,source=setup
|
||||
old=request.evidence_dir/'old';old.mkdir(parents=True)
|
||||
record={'operation':'update','library':str(request.library),'name':'Block','stage':'complete',
|
||||
'status':'RECOVERY_REQUIRED','safe_to_continue':True,'history':[{'stage':'native_add'}]}
|
||||
path=old/'checkpoint.json';path.write_text(json.dumps(record));before=path.read_bytes()
|
||||
observed=[]
|
||||
def proof(library,evidence,*,block_name,required,**kw):
|
||||
observed.append((library,evidence,block_name,required))
|
||||
if proof_case=='live_writer':raise RuntimeError('NATIVE_WRITER_ACTIVE')
|
||||
if proof_case=='none':return None
|
||||
target=library if proof_case!='wrong_library' else library.with_name('other.lmc')
|
||||
block=block_name if proof_case!='wrong_block' else 'Other'
|
||||
receipt=(old if proof_case=='cached' else evidence/'fresh')/'release.json'
|
||||
receipt.parent.mkdir(parents=True,exist_ok=True)
|
||||
result={'status':'RELEASE_CONFIRMED','lease_state':'RELEASED','library':str(target),
|
||||
'proof_scope':'BLOCK','proof_block_names':[block],
|
||||
'resource_scope':{'scope_state':'OBSERVED','library':str(target),'block_names':[block]},
|
||||
'evidence_path':str(receipt)}
|
||||
receipt.write_text(json.dumps(result));return result
|
||||
monkeypatch.setattr('cbb_refresh_verify.library_lock.recheck_previous_release',proof)
|
||||
result=execute(replace(request,operation='update',source=source,auto_verify=False,check_previous_release=True),adapter)
|
||||
assert observed and observed[0][2:]==('Block',True)
|
||||
assert path.read_bytes()==before
|
||||
if proof_case=='fresh':
|
||||
assert result.status=='UPLOADED' and result.safe_to_continue
|
||||
assert adapter.calls[0]=='remove' and adapter.calls[1][0]=='add'
|
||||
else:
|
||||
assert result.status=='BLOCKED' and adapter.calls==[]
|
||||
|
||||
|
||||
def test_old_request_without_current_confirmation_remains_blocked(setup,monkeypatch):
|
||||
request,adapter,source=setup
|
||||
old=request.evidence_dir/'old';old.mkdir(parents=True)
|
||||
(old/'checkpoint.json').write_text(json.dumps({'library':str(request.library),'name':'Block',
|
||||
'stage':'complete','status':'RECOVERY_REQUIRED','safe_to_continue':True,'history':[{'stage':'native_add'}]}))
|
||||
result=execute(replace(request,operation='update',source=source,auto_verify=False),adapter)
|
||||
assert result.status=='BLOCKED' and adapter.calls==[]
|
||||
|
||||
|
||||
def test_ui_adds_fresh_recheck_only_after_current_yes(qtbot,tmp_path,monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from cbb_refresh_verify.management import ManagementRequest,ManagementResult
|
||||
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||
from cbb_refresh_verify.ui import timed_prompt
|
||||
request=ManagementRequest('remove',tmp_path/'lib.lmc','Block')
|
||||
captured=[]
|
||||
def runner(requests,**kw):
|
||||
captured.extend(requests)
|
||||
return [ManagementResult('remove',request.library,'Block','Logical-Physical',None,False,'complete','REMOVED',True)]
|
||||
dialog=ManagementDialog([request],runner=runner);qtbot.addWidget(dialog);dialog.show()
|
||||
answer=[QMessageBox.No]
|
||||
monkeypatch.setattr(timed_prompt,'question',lambda *a,**k:answer[0])
|
||||
dialog._execute();assert not captured and not dialog.requests()[0].check_previous_release
|
||||
answer[0]=QMessageBox.Yes;dialog._execute()
|
||||
qtbot.waitUntil(lambda:not dialog.busy)
|
||||
assert len(captured)==1 and captured[0].check_previous_release
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Large advancing manifests stay usable; a stalled member still hands off."""
|
||||
from threading import Event
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, check_active
|
||||
from cbb_refresh_verify.scoped_manifest import build_manifest, hash_file
|
||||
|
||||
|
||||
def test_advancing_manifest_outlives_aggregate_metadata_deadline(tmp_path, monkeypatch):
|
||||
for i in range(768):
|
||||
(tmp_path/f'part-{i:04}.dat').write_bytes(str(i).encode())
|
||||
clock, offset = time.monotonic, [0]
|
||||
monkeypatch.setattr(time, 'monotonic', lambda:clock()+offset[0])
|
||||
def progress(event):
|
||||
if event['hashed_files']:
|
||||
offset[0] += 8
|
||||
time.sleep(.06) # Let the actual context waiter observe each advancing batch.
|
||||
context = BatchTaskContext(str(tmp_path/'library.lmc'), native_policy='external')
|
||||
try:
|
||||
result = context.run(lambda:build_manifest(tmp_path, progress=progress), timeout_seconds=10)
|
||||
assert len(result['files']) == 768
|
||||
assert offset[0] == 24
|
||||
finally:
|
||||
context.close(timeout_seconds=2)
|
||||
|
||||
|
||||
def test_stalled_manifest_member_cannot_resume_into_native_write(tmp_path):
|
||||
(tmp_path/'one.dat').write_bytes(b'content')
|
||||
entered, release = Event(), Event()
|
||||
writes = []
|
||||
def stalled(path):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return hash_file(path)
|
||||
def action():
|
||||
build_manifest(tmp_path, hash_function=stalled)
|
||||
check_active()
|
||||
writes.append('native')
|
||||
context = BatchTaskContext(str(tmp_path/'library.lmc'), native_policy='external')
|
||||
try:
|
||||
with pytest.raises(TaskHandoff):
|
||||
context.run(action, timeout_seconds=.1)
|
||||
assert entered.is_set()
|
||||
release.set()
|
||||
context.close(timeout_seconds=2)
|
||||
assert writes == []
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
|
||||
def test_manifest_progress_does_not_interrupt_admitted_native_continuation(tmp_path):
|
||||
from cbb_refresh_verify.operation_queue import native_phase
|
||||
(tmp_path/'one.dat').write_bytes(b'content')
|
||||
context = BatchTaskContext(str(tmp_path/'library.lmc'))
|
||||
effects = []
|
||||
def transaction():
|
||||
with native_phase():
|
||||
effects.append('Remove')
|
||||
context.cancel()
|
||||
assert len(build_manifest(tmp_path)['files']) == 1
|
||||
effects.append('Add')
|
||||
context.run(transaction)
|
||||
assert effects == ['Remove', 'Add']
|
||||
|
||||
|
||||
def test_completed_release_and_idle_checks_outlive_aggregate_deadline(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import library_lock, owner_probe
|
||||
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
clock, offset = time.monotonic, [0]
|
||||
monkeypatch.setattr(time, 'monotonic', lambda:clock()+offset[0])
|
||||
def released(*args, **kwargs):
|
||||
offset[0] += 7
|
||||
return {'status': 'RELEASE_CONFIRMED'}
|
||||
def owners(names):
|
||||
offset[0] += 4
|
||||
time.sleep(.06)
|
||||
return []
|
||||
monkeypatch.setattr(library_lock, 'release_retained_library', released)
|
||||
monkeypatch.setattr(owner_probe, 'query_owners', owners)
|
||||
context = BatchTaskContext(str(library), native_policy='external')
|
||||
def prepare():
|
||||
library_lock.recheck_previous_release(library, tmp_path/'evidence', required=True)
|
||||
for name in ('target', 'source'):
|
||||
_idle_check(library, tmp_path/name/'main.prj', tmp_path/name/'PCB/main.pcb')
|
||||
check_active()
|
||||
return 'ready for native dispatch'
|
||||
try:
|
||||
assert context.run(prepare, timeout_seconds=10) == 'ready for native dispatch'
|
||||
assert offset[0] == 15
|
||||
finally:
|
||||
context.close(timeout_seconds=2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cancel', [False, True])
|
||||
def test_completed_idle_check_cannot_revive_stalled_or_cancelled_work(tmp_path, monkeypatch, cancel):
|
||||
from cbb_refresh_verify import owner_probe
|
||||
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||
from cbb_refresh_verify.operation_queue import QueueCancelled
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
release = Event(); writes = []
|
||||
context = BatchTaskContext(str(library), native_policy='external')
|
||||
def owners(names):
|
||||
if cancel: context.cancel()
|
||||
else: assert release.wait(3)
|
||||
return []
|
||||
monkeypatch.setattr(owner_probe, 'query_owners', owners)
|
||||
def prepare():
|
||||
_idle_check(library, tmp_path/'main.prj', tmp_path/'PCB/main.pcb')
|
||||
writes.append('dispatch')
|
||||
try:
|
||||
with pytest.raises(QueueCancelled):
|
||||
context.run(prepare, timeout_seconds=.1)
|
||||
release.set(); context.close(timeout_seconds=2)
|
||||
assert writes == []
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
|
||||
def test_successful_idle_check_does_not_abort_admitted_native_continuation(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import owner_probe
|
||||
from cbb_refresh_verify.backup_recovery import _idle_check
|
||||
from cbb_refresh_verify.operation_queue import native_phase
|
||||
library = tmp_path/'library.lmc'; library.touch()
|
||||
monkeypatch.setattr(owner_probe, 'query_owners', lambda names: [])
|
||||
context = BatchTaskContext(str(library)); writes = []
|
||||
def transaction():
|
||||
with native_phase():
|
||||
writes.append('Remove'); context.cancel()
|
||||
_idle_check(library, tmp_path/'main.prj', tmp_path/'PCB/main.pcb')
|
||||
writes.append('Add')
|
||||
context.run(transaction)
|
||||
assert writes == ['Remove', 'Add']
|
||||
@@ -0,0 +1,38 @@
|
||||
from threading import Event
|
||||
import pytest
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, native_phase
|
||||
|
||||
|
||||
def test_metadata_can_refresh_while_abandoned_native_scope_stays_protected():
|
||||
entered, release = Event(), Event()
|
||||
old = BatchTaskContext('a.lmc')
|
||||
def stalled():
|
||||
entered.set(); release.wait(3)
|
||||
try:
|
||||
with pytest.raises(TaskHandoff): old.run(stalled, timeout_seconds=.01)
|
||||
assert entered.is_set()
|
||||
new = BatchTaskContext('a.lmc')
|
||||
assert new.run(lambda: 'metadata', metadata_only=True) == 'metadata'
|
||||
with pytest.raises(TaskHandoff): new.run(lambda: 'native')
|
||||
finally:
|
||||
release.set(); old.close(timeout_seconds=1)
|
||||
|
||||
|
||||
def test_metadata_cannot_escalate_into_native_phase():
|
||||
context = BatchTaskContext('a.lmc')
|
||||
def escalate():
|
||||
with native_phase():
|
||||
pytest.fail('metadata admitted native action')
|
||||
with pytest.raises(RuntimeError, match='metadata'):
|
||||
context.run(escalate, metadata_only=True)
|
||||
|
||||
|
||||
def test_abandoned_metadata_does_not_block_next_native_admission():
|
||||
release = Event()
|
||||
old = BatchTaskContext('a.lmc')
|
||||
try:
|
||||
with pytest.raises(TaskHandoff):
|
||||
old.run(lambda: release.wait(3), timeout_seconds=.01, metadata_only=True)
|
||||
assert BatchTaskContext('a.lmc').run(lambda: 'admitted') == 'admitted'
|
||||
finally:
|
||||
release.set(); old.close(timeout_seconds=1)
|
||||
@@ -0,0 +1,407 @@
|
||||
"""Issue 15 recovery entry regressions. Native boundaries never launch Mentor."""
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_real_owner_probe(monkeypatch):
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: [])
|
||||
|
||||
|
||||
def test_ordinary_worker_aligns_both_bound_projects_and_retains_each_original(tmp_path, monkeypatch):
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
from cbb_refresh_verify import mentor_adapter as adapter
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
main = Path(job['project']); aux = Path(job['pcb']).parent/'pcb.prj'
|
||||
original_main = b'KEY CentralLibrary "old-main.lmc"\r\n#\x81\x40\r\n'
|
||||
original_aux = b'\xff\xfe'+ 'KEY CentralLibrary "old-pcb.lmc"\r\n'.encode('utf-16-le')
|
||||
main.write_bytes(original_main); aux.write_bytes(original_aux)
|
||||
assert execute()['status'] == 'PASS'
|
||||
from cbb_refresh_verify.backup_recovery import _project_text
|
||||
for path in (main, aux):
|
||||
import re
|
||||
reference = re.search(r'KEY CentralLibrary "([^"]+)"', _project_text(path))[1]
|
||||
assert (path.parent/reference).resolve() == Path(job['lmc_file']).resolve()
|
||||
saved = [p.read_bytes() for p in (Path(job['root'])/'diagnostics').rglob('*.before-central-library')]
|
||||
assert original_main in saved and original_aux in saved
|
||||
|
||||
|
||||
def test_ordinary_legacy_binding_never_rewrites_template(tmp_path, monkeypatch):
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
job, _, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
main = Path(job['project']); pcb = Path(job['pcb'])
|
||||
main.write_text('KEY CentralLibrary "old.lmc"\n')
|
||||
pcb.write_text('KEY ProjectFile "../CBB.prj"\n')
|
||||
template = pcb.parent/'template.prj'; template.write_text('KEY CentralLibrary "do-not-touch.lmc"\n')
|
||||
original = template.read_bytes()
|
||||
assert execute()['status'] == 'PASS'
|
||||
assert template.read_bytes() == original
|
||||
assert 'old.lmc' not in main.read_text()
|
||||
|
||||
|
||||
def inconsistency(database):
|
||||
return (f'Project database [{database}] is inconsistent. It has been manually copied while the iCDB Server was running. '
|
||||
"Please use iCDB Project Backup 'Repair project' functionality to fix this issue.")
|
||||
|
||||
|
||||
def test_current_inconsistency_has_structured_database_and_old_error_is_not_reused(tmp_path):
|
||||
from cbb_refresh_verify import icdb_recovery as recovery, mentor_adapter as adapter
|
||||
source = tmp_path/'LogFiles/PCBLogFile.txt'; source.parent.mkdir()
|
||||
db = tmp_path/'database'; message = inconsistency(db)
|
||||
source.write_text(message+'\n')
|
||||
baseline = recovery.snapshot_log(source)
|
||||
assert recovery.read_log_failure(source, baseline)[1] is None
|
||||
source.write_text('new header\n'+message+'\n')
|
||||
assert recovery.read_log_failure(source, baseline)[1] is None
|
||||
baseline = recovery.snapshot_log(source)
|
||||
with source.open('a') as stream: stream.write(message+'\n')
|
||||
text, record = recovery.read_log_failure(source, baseline)
|
||||
assert record['database_path'] == str(db) and record['scope'] == 'project'
|
||||
assert record['kind'] == 'database_inconsistent'
|
||||
detail = adapter.pcb_log_reports_missing_server(tmp_path/'CBB.pcb', offset=baseline)
|
||||
assert 'ICDB_REPAIR_REQUIRED' in detail and str(db) in detail and '未修复' in detail
|
||||
|
||||
|
||||
def test_manual_repair_selects_diagnosed_bound_database_without_layout_or_healthy_header(tmp_path):
|
||||
from test_native_backup import project_fixture
|
||||
from cbb_refresh_verify import native_backup as native
|
||||
request, main = project_fixture(tmp_path)
|
||||
pcb = main.parent/'PCB/Block.pcb'; pcb.parent.mkdir()
|
||||
pcb.write_text('KEY ProjectFile "../Block.prj"\n')
|
||||
aux = pcb.parent/'pcb.prj'; aux.write_text('KEY iCDBDir "database"\n')
|
||||
for prj in (main, aux):
|
||||
(prj.parent/'database').mkdir(); (prj.parent/'database/icdb.dat').write_bytes(b'not-a-healthy-header')
|
||||
assert native.native_backup_target(request, mode='repair')[0] == main
|
||||
assert native.native_backup_target(request, mode='repair', target_database=aux.parent/'database')[0] == aux
|
||||
with pytest.raises(ValueError, match='TARGET'):
|
||||
native.native_backup_target(request, mode='repair', target_database=tmp_path/'foreign')
|
||||
|
||||
|
||||
def test_versions_launcher_rechecks_parent_retained_lease_and_persists_before_gate(tmp_path, monkeypatch):
|
||||
import subprocess, sys
|
||||
from test_native_backup import project_fixture
|
||||
from cbb_refresh_verify import native_backup as native, library_lock, session_record
|
||||
request, project = project_fixture(tmp_path)
|
||||
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe')
|
||||
calls = []
|
||||
monkeypatch.setattr(library_lock, 'recheck_previous_release', lambda *a, **k: calls.append('recheck'))
|
||||
monkeypatch.setattr(session_record, 'process_identity', lambda pid: dict(pid=pid, created='now', executable='python', owner='test'))
|
||||
child = subprocess.Popen([sys.executable,'-c','input()'],stdin=subprocess.PIPE,text=True)
|
||||
def spawn(command, **kw):
|
||||
job = json.loads(Path(command[-1]).read_text())
|
||||
assert calls == ['recheck'] and not Path(job['start_gate']).exists()
|
||||
calls.append('spawn')
|
||||
return child
|
||||
monkeypatch.setattr(native.subprocess, 'Popen', spawn)
|
||||
try:
|
||||
session = native.launch_native_backup(request, mode='repair')
|
||||
finally:
|
||||
child.communicate('\n',timeout=5)
|
||||
record = json.loads(session.job.read_text())
|
||||
assert Path(record['start_gate']).is_file()
|
||||
assert Path(record['session_record_path']).is_file()
|
||||
assert session.mode == 'repair' and session.database == project.parent/'database'
|
||||
assert session.operation_id == record['operation_id']
|
||||
assert record['automatic_repair'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['spawn', 'registration'])
|
||||
def test_backup_failure_leaves_start_gate_closed(tmp_path, monkeypatch, failure):
|
||||
from test_native_backup import project_fixture
|
||||
from cbb_refresh_verify import native_backup as native, session_record
|
||||
request, _ = project_fixture(tmp_path)
|
||||
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe')
|
||||
def spawn(*a, **k):
|
||||
if failure == 'spawn': raise OSError('start failed')
|
||||
return SimpleNamespace(pid=123, poll=lambda: None)
|
||||
monkeypatch.setattr(native.subprocess, 'Popen', spawn)
|
||||
monkeypatch.setattr(session_record, 'register_worker_session', lambda *a: (_ for _ in ()).throw(OSError('register failed')))
|
||||
with pytest.raises(OSError): native.launch_native_backup(request)
|
||||
job = next(request.evidence_dir.glob('native-backup-*/request.json'))
|
||||
record = json.loads(job.read_text())
|
||||
assert not Path(record['start_gate']).exists()
|
||||
assert Path(record['cancel_signal']).exists()
|
||||
|
||||
|
||||
def test_changed_prj_bytes_refused_before_recovery_tool_dispatch(tmp_path, monkeypatch):
|
||||
import hashlib
|
||||
from test_native_backup import project_fixture
|
||||
from cbb_refresh_verify import native_backup as native
|
||||
request, project = project_fixture(tmp_path)
|
||||
job = tmp_path/'request.json'
|
||||
record = dict(library=str(request.lmc_file), block=request.block_name, project=str(project),
|
||||
project_sha256=hashlib.sha256(project.read_bytes()).hexdigest())
|
||||
job.write_text(json.dumps(record))
|
||||
project.write_text(project.read_text()+'# changed identity\n')
|
||||
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe')
|
||||
assert native.native_backup_worker_main(job, process_factory=lambda *a: pytest.fail('changed PRJ dispatched')) == 1
|
||||
assert '身份' in json.loads(job.with_name('result.json').read_text('utf-8'))['detail']
|
||||
|
||||
|
||||
def test_real_parent_retained_sidecar_is_reconciled_before_child_acquires_it_and_reopens(tmp_path, monkeypatch):
|
||||
import subprocess, sys
|
||||
from test_native_backup import project_fixture
|
||||
from cbb_refresh_verify import native_backup as native, library_lock as locks
|
||||
from cbb_refresh_verify.file_probe import hold_release_files
|
||||
request, _ = project_fixture(tmp_path)
|
||||
with locks.LibraryLock(request.lmc_file, safe_to_release=lambda: False, block_name='Block') as retained:
|
||||
pass
|
||||
@contextmanager
|
||||
def proof(library, **kwargs):
|
||||
with hold_release_files(library, (library.parent/'ReusableBlocksLP/Block/Work',)) as files:
|
||||
yield {**files, 'native_owners': []}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', proof)
|
||||
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'not-launched.exe')
|
||||
popen = subprocess.Popen
|
||||
script = (
|
||||
'import json,sys\nfrom pathlib import Path\n'
|
||||
'from cbb_refresh_verify.desktop_worker import run_native_worker\n'
|
||||
'from cbb_refresh_verify.library_lock import LibraryLock\n'
|
||||
'def action(path):\n'
|
||||
' j=json.loads(Path(path).read_text())\n'
|
||||
' with LibraryLock(j["library"],checkpoint=False):\n'
|
||||
' Path(path).with_name("child-acquired").write_text("owned")\n'
|
||||
' return 0\n'
|
||||
'raise SystemExit(run_native_worker(action,sys.argv[1]))\n')
|
||||
def spawn(command, **kwargs):
|
||||
if '--native-backup-worker' in command:
|
||||
assert not locks.has_retained_library(request.lmc_file)
|
||||
return popen([sys.executable, '-c', script, command[-1]], **kwargs)
|
||||
return popen(command, **kwargs)
|
||||
monkeypatch.setattr(native.subprocess, 'Popen', spawn)
|
||||
try:
|
||||
for mode in ('versions', 'repair'):
|
||||
session = native.launch_native_backup(request, mode=mode)
|
||||
assert session.process.wait(10) == 0
|
||||
assert session.job.with_name('child-acquired').read_text() == 'owned'
|
||||
assert retained.path.is_file()
|
||||
finally:
|
||||
owner = locks._owners.pop(retained.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_native_registration_failure_never_resumes_suspended_child(tmp_path):
|
||||
import sys
|
||||
from cbb_refresh_verify.native_backup import _NativeBackupProcess
|
||||
marker = tmp_path/'must-not-run'
|
||||
def refuse(process): raise OSError('required identity journal failed')
|
||||
with pytest.raises(OSError, match='journal'):
|
||||
_NativeBackupProcess([sys.executable, '-c', f'from pathlib import Path;Path({str(marker)!r}).touch()'],
|
||||
tmp_path, before_resume=refuse)
|
||||
assert not marker.exists()
|
||||
|
||||
|
||||
def test_independent_backup_job_registration_retains_descendants_after_caller_handles_close(tmp_path):
|
||||
import sys, time
|
||||
from cbb_refresh_verify.native_backup import _NativeBackupProcess, _BackupJobWriter
|
||||
script = tmp_path/'parent.py'; marker = tmp_path/'child.pid'
|
||||
script.write_text('import subprocess,sys,time\nfrom pathlib import Path\n'
|
||||
'p=subprocess.Popen([sys.executable,"-c","import time;time.sleep(1)"])\n'
|
||||
f'Path({str(marker)!r}).write_text(str(p.pid))\ntime.sleep(.1)\n')
|
||||
process = _NativeBackupProcess([sys.executable, str(script)], tmp_path)
|
||||
registered = _BackupJobWriter(process.job)
|
||||
try:
|
||||
deadline = time.monotonic()+5
|
||||
while process.poll() is None and time.monotonic()<deadline: time.sleep(.02)
|
||||
assert marker.exists() and process.poll() == 0
|
||||
process.close()
|
||||
assert registered.poll() is None
|
||||
while registered.poll() is None and time.monotonic()<deadline: time.sleep(.02)
|
||||
assert registered.poll() == 0
|
||||
finally:
|
||||
if registered.job is not None: registered.job.Close()
|
||||
|
||||
|
||||
def test_common_admission_refusal_publishes_bound_receipt_and_ui_can_reopen(qtbot, tmp_path, monkeypatch):
|
||||
import subprocess,sys
|
||||
from threading import Event, Thread
|
||||
from test_native_backup import project_fixture
|
||||
from test_ui_filters import load_window
|
||||
from cbb_refresh_verify import native_backup as native, desktop_worker
|
||||
request, _ = project_fixture(tmp_path)
|
||||
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe')
|
||||
# A cold observer reads kernel identity: poll=exited on pytest's live PID
|
||||
# cannot represent a released worker. Use a real, harmless refused child.
|
||||
invoke = tmp_path/'invoke-refusal.signal'
|
||||
child = tmp_path/'refused_worker.py'
|
||||
child.write_text('import sys,time\nfrom pathlib import Path\n'
|
||||
f'gate=Path({str(invoke)!r})\ndeadline=time.monotonic()+10\n'
|
||||
'while not gate.exists() and time.monotonic()<deadline:time.sleep(.01)\n'
|
||||
'assert gate.exists()\n'
|
||||
'from cbb_refresh_verify import native_backup\n'
|
||||
'def forbidden(*args):raise AssertionError("refused action entered")\n'
|
||||
'native_backup.native_backup_worker_main=forbidden\n'
|
||||
'from cbb_refresh_verify.application import main\n'
|
||||
'raise SystemExit(main(["--native-backup-worker",sys.argv[1]]))\n')
|
||||
popen = subprocess.Popen
|
||||
with monkeypatch.context() as launch:
|
||||
launch.setattr(native.subprocess, 'Popen', lambda command, **kwargs:
|
||||
popen([sys.executable,str(child),command[-1]], **kwargs))
|
||||
session = native.launch_native_backup(request)
|
||||
entered, release = Event(), Event()
|
||||
monkeypatch.setattr(desktop_worker, '_automation_clients', [])
|
||||
def held_writer():
|
||||
with desktop_worker.worker_native_channel():
|
||||
entered.set(); release.wait(10)
|
||||
holder = Thread(target=held_writer); holder.start()
|
||||
assert entered.wait(2)
|
||||
try:
|
||||
invoke.touch()
|
||||
assert session.process.wait(timeout=8) == 1
|
||||
finally:
|
||||
release.set(); holder.join(3)
|
||||
record = json.loads(session.job.with_name('result.json').read_text('utf-8'))
|
||||
assert record['safe_to_continue'] is True and record['native_started'] is False
|
||||
assert record['operation_id'] == json.loads(session.job.read_text('utf-8'))['operation_id']
|
||||
assert record['worker_identity']['pid'] == session.process.pid != os.getpid()
|
||||
launched = []
|
||||
window = load_window(qtbot, tmp_path, monkeypatch,
|
||||
native_backup_launcher=lambda req: (launched.append(req) or session),
|
||||
status_refresher=lambda names, _: {name:'UNKNOWN' for name in names})
|
||||
# Deliver the receipt to its actual library view; a foreign view must not
|
||||
# receive an old session's status label after Task 4's callback isolation.
|
||||
window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, display_path=path,
|
||||
drive='', remote_root='', close=lambda:None, retain_for_recovery=lambda:None)
|
||||
window.lmc_edit.setText(str(session.library)); window.load_library()
|
||||
qtbot.waitUntil(lambda:not window.busy)
|
||||
session.block = 'Beta'; record['block'] = 'Beta'
|
||||
session.job.with_name('result.json').write_text(json.dumps(record), encoding='utf-8')
|
||||
window._native_backup_session = session
|
||||
window._poll_native_backup(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert window._native_backup_session is None
|
||||
assert 'NATIVE_WRITER_ACTIVE' in window.status_label.text()
|
||||
window.search_edit.setText('Beta'); window.select_visible_button.click()
|
||||
window.open_native_backup(); qtbot.waitUntil(lambda: not window.busy)
|
||||
assert len(launched) == 1
|
||||
window._native_backup_session = None # The test adapter has no live native client.
|
||||
|
||||
|
||||
def test_unbound_admission_refusal_cannot_claim_release(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import native_backup as native, desktop_worker
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps(dict(library=str(tmp_path/'lib.lmc'), block='A', operation_id='foreign',
|
||||
session_record_path=str(tmp_path/'session.json'), project=str(tmp_path/'A.prj'))))
|
||||
monkeypatch.setattr(desktop_worker, 'run_native_worker', lambda *a, admission_state=None: (_ for _ in ()).throw(RuntimeError('refused')))
|
||||
assert native.run_native_backup_worker(job) == 1
|
||||
result = json.loads(job.with_name('result.json').read_text('utf-8'))
|
||||
assert result['safe_to_continue'] is False
|
||||
|
||||
|
||||
def test_legacy_unregistered_backup_job_cannot_enter_native_action(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import native_backup as native, desktop_worker
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps(dict(library=str(tmp_path/'lib.lmc'), block='A', project=str(tmp_path/'A.prj'))))
|
||||
monkeypatch.setattr(desktop_worker, '_automation_clients', [])
|
||||
monkeypatch.setattr(native, 'native_backup_worker_main', lambda *a: pytest.fail('unregistered action entered'))
|
||||
assert native.run_native_backup_worker(job) == 1
|
||||
assert json.loads(job.with_name('result.json').read_text('utf-8'))['safe_to_continue'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('owner_scope', ['target', 'unrelated'])
|
||||
def test_recovery_entry_scopes_external_ownership_before_launch(tmp_path, monkeypatch, owner_scope):
|
||||
from test_native_backup import project_fixture
|
||||
from cbb_refresh_verify import native_backup as native, owner_probe
|
||||
request, project = project_fixture(tmp_path)
|
||||
job = tmp_path/'request.json'
|
||||
job.write_text(json.dumps(dict(library=str(request.lmc_file), block=request.block_name,
|
||||
project=str(project), mode='repair')))
|
||||
monkeypatch.setattr(native, 'native_backup_executable', lambda *_: tmp_path/'native.exe')
|
||||
external = project if owner_scope == 'target' else tmp_path/'other/Work/other.prj'
|
||||
monkeypatch.setattr(owner_probe, 'query_owners', lambda names: [dict(pid=99999,
|
||||
name='ExpeditionPCB.exe', command=f'ExpeditionPCB.exe "{external}"', executable='ExpeditionPCB.exe')])
|
||||
def process(*args):
|
||||
if owner_scope == 'target': pytest.fail('external target owner bypassed')
|
||||
return SimpleNamespace(pid=456, poll=lambda: 0, session_pids=lambda: [], close=lambda: None)
|
||||
assert native.native_backup_worker_main(job, process_factory=process) == (1 if owner_scope == 'target' else 0)
|
||||
result = json.loads(job.with_name('result.json').read_text('utf-8'))
|
||||
assert result['safe_to_continue'] is True
|
||||
if owner_scope == 'target': assert 'OWNER_ACTIVE' in result['detail']
|
||||
else: assert result['status'] == 'CLOSED'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('user_timeout', [5, 600])
|
||||
def test_lm_menu_return_without_pcb_uses_dispatch_budget_and_closes_lm(tmp_path, monkeypatch, user_timeout):
|
||||
from test_verify_worker_stability import exercise_worker
|
||||
from cbb_refresh_verify import mentor_adapter as adapter, library_manager_verify as lm
|
||||
job, events, execute = exercise_worker(tmp_path, monkeypatch)
|
||||
job['native_lm_verify'] = True; job['timeout'] = user_timeout
|
||||
(Path(job['pcb']).parent/'pcb.prj').write_text('KEY CentralLibrary "old.lmc"\n')
|
||||
clock = [0.0]; closed = []
|
||||
monkeypatch.setattr(adapter.time, 'monotonic', lambda: clock[0])
|
||||
monkeypatch.setattr(adapter.time, 'sleep', lambda seconds: clock.__setitem__(0, clock[0]+seconds))
|
||||
monkeypatch.setattr(adapter, 'select_reusable_circuit_worker', lambda *a, **k: None)
|
||||
def launch(*args, **kw):
|
||||
assert args[3] <= min(45, user_timeout)
|
||||
return SimpleNamespace(process=SimpleNamespace(pid=123), close=lambda: closed.append(True))
|
||||
monkeypatch.setattr(lm, 'launch_library_verify', launch)
|
||||
with pytest.raises(RuntimeError, match='VERIFY_DISPATCH_FAILED'): execute()
|
||||
assert clock[0] <= min(45, user_timeout)+1 and closed == [True]
|
||||
|
||||
|
||||
def test_inconsistency_preserves_shared_database_scope():
|
||||
from cbb_refresh_verify.icdb_recovery import parse_recovery_request
|
||||
database = r'C:\\library\\SymbolLibs\\__ReusableBlocksSymb'
|
||||
assert parse_recovery_request(inconsistency(database))['scope'] == 'central_library'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('case', ['not_in_use', 'repair_required', 'in_use', 'unconfirmed', 'wrong_target',
|
||||
'no_identity', 'changed_address', 'changed_project', 'shared_address', 'exclusive'])
|
||||
def test_explicit_continue_requires_exact_fresh_native_and_exclusive_proof(tmp_path, monkeypatch, case):
|
||||
from test_native_repair import target_fixture
|
||||
from test_native_occupancy import output
|
||||
from cbb_refresh_verify import pcb_open_consent as consent, native_repair, owner_probe, session_record
|
||||
from cbb_refresh_verify.verify_runner import preflight
|
||||
request, _, target = target_fixture(tmp_path)
|
||||
request.evidence_dir.mkdir()
|
||||
project, pcb = preflight(request)
|
||||
project.write_text('KEY PCBDesignPath "PCB/actual.pcb"\nKEY iCDBDir "database"\n')
|
||||
pcb.write_text('KEY ProjectFile "../'+project.name+'"\n')
|
||||
address = target.database/'cdbsvr/sAddress.adr'; address.parent.mkdir(); address.write_bytes(b'unchanged address')
|
||||
if case == 'shared_address':
|
||||
shared = request.lmc_file.parent/'SymbolLibs/__ReusableBlocksSymb/cdbsvr/sAddress.adr'
|
||||
shared.parent.mkdir(parents=True); shared.write_bytes(b'unknown shared owner')
|
||||
monkeypatch.setattr(owner_probe, 'query_process_snapshot', lambda: [])
|
||||
calls = []
|
||||
def inspect(inspected, root, **kwargs):
|
||||
assert kwargs['inspection_only'] is True
|
||||
calls.append(inspected)
|
||||
record = dict(status='NOT_IN_USE', project=str(target.project), database=str(target.database),
|
||||
native_pid=os.getpid(), native_identity=session_record.process_identity(os.getpid()),
|
||||
inspection_only=True, repair_requested=False, repair_required=case == 'repair_required',
|
||||
native_exit_code=0, release={'native_exited': True},
|
||||
output=output(target.project, target.database, fault=case == 'repair_required'))
|
||||
if case == 'in_use': record.update(status='IN_USE', output=output(target.project, target.database, busy=True))
|
||||
if case == 'unconfirmed': record.update(status='UNCONFIRMED', output='not known')
|
||||
if case == 'wrong_target': record['database'] = str(tmp_path/'foreign')
|
||||
if case == 'no_identity': record.pop('native_identity')
|
||||
if case == 'changed_address': address.write_bytes(b'new address')
|
||||
if case == 'changed_project': project.write_text('KEY iCDBDir "another-db"\n')
|
||||
return record
|
||||
monkeypatch.setattr(native_repair, 'run_native_repair', inspect)
|
||||
job = dict(root=str(request.evidence_dir), lmc_file=str(request.lmc_file),
|
||||
block_name=request.block_name, project=str(project), pcb=str(pcb), operation_id='current-open')
|
||||
held = None
|
||||
if case == 'exclusive':
|
||||
import win32con, win32file
|
||||
held = win32file.CreateFile(str(target.database/'icdb.dat'), win32con.GENERIC_READ,
|
||||
0, None, win32con.OPEN_EXISTING, 0, None)
|
||||
try:
|
||||
if case in ('not_in_use', 'repair_required'):
|
||||
with consent.resource_guard(job, {os.getpid()}): pass
|
||||
assert calls == [target]
|
||||
evidence = json.loads((request.evidence_dir/'pcb-open-resource-proof.json').read_text())
|
||||
assert evidence['operation_id'] == 'current-open'
|
||||
assert evidence['repair_confirmed'] is False
|
||||
else:
|
||||
with pytest.raises((ValueError, OSError)):
|
||||
with consent.resource_guard(job, {os.getpid()}): pass
|
||||
finally:
|
||||
if held is not None: held.Close()
|
||||
if case not in ('shared_address', 'exclusive'):
|
||||
assert calls == [target]
|
||||
if case != 'changed_address': assert address.read_bytes() == b'unchanged address'
|
||||
@@ -0,0 +1,69 @@
|
||||
"""EE7.9 imports by source PRJ name; reject rename before any native mutation."""
|
||||
from dataclasses import replace
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify.management import ManagementRequest, run_management
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
from test_management import project
|
||||
|
||||
|
||||
@pytest.mark.parametrize('operation', ['add', 'update'])
|
||||
def test_real_adapter_rejects_mismatched_source_before_native_catalog_or_remove(tmp_path, monkeypatch, operation):
|
||||
library=tmp_path/'library/mentor.lmc';library.parent.mkdir();library.write_bytes(b'unchanged library')
|
||||
target=project(library.parent/'ReusableBlocksLP/Block/Work','Block',b'unchanged target')
|
||||
source=project(tmp_path/'source','Other')
|
||||
adapter=NativeManagementAdapter()
|
||||
monkeypatch.setattr(adapter,'_binary_capability',lambda:'')
|
||||
calls=[]
|
||||
monkeypatch.setattr(adapter,'_worker',lambda *args:calls.append(args) or pytest.fail('native boundary reached'))
|
||||
request=ManagementRequest(operation,library,'Block',source=source,evidence_dir=tmp_path/'evidence')
|
||||
result=run_management(request,adapter=adapter,idle_check=lambda *_:None)
|
||||
assert result.safe_to_continue and 'SOURCE_NAME_MISMATCH' in result.detail
|
||||
assert calls == []
|
||||
assert library.read_bytes()==b'unchanged library'
|
||||
assert (target.parent/'database/icdb.dat').read_bytes()==b'unchanged target'
|
||||
|
||||
|
||||
def test_source_name_check_uses_windows_case_insensitive_identity(tmp_path):
|
||||
source=project(tmp_path/'source','BLOCK')
|
||||
request=ManagementRequest('update',tmp_path/'library.lmc','Block',source=source)
|
||||
NativeManagementAdapter().validate_source(request)
|
||||
|
||||
|
||||
def test_management_preview_reports_mismatch_and_allows_rechoose(qtbot,tmp_path,monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||
from cbb_refresh_verify.ui import timed_prompt
|
||||
wrong=project(tmp_path/'wrong','Other');right=project(tmp_path/'right','Block')
|
||||
request=ManagementRequest('update',tmp_path/'library.lmc','Block',source=wrong)
|
||||
dialog=ManagementDialog([request],adapter=NativeManagementAdapter())
|
||||
qtbot.addWidget(dialog);dialog.show()
|
||||
questions=[]
|
||||
monkeypatch.setattr(timed_prompt,'question',lambda *a,**k:questions.append(a) or QMessageBox.No)
|
||||
dialog.execute_button.click()
|
||||
assert 'SOURCE_NAME_MISMATCH' in dialog.status_label.text()
|
||||
assert not questions and dialog.execute_button.isEnabled()
|
||||
dialog.table.item(0,2).setText(str(right))
|
||||
dialog.execute_button.click()
|
||||
assert len(questions)==1 and not dialog.busy
|
||||
|
||||
|
||||
def test_source_name_preview_does_not_resolve_files_on_gui_thread(qtbot,tmp_path,monkeypatch):
|
||||
from pathlib import Path
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
|
||||
from cbb_refresh_verify.ui import timed_prompt
|
||||
source=project(tmp_path/'source','Block')
|
||||
request=ManagementRequest('update',tmp_path/'library.lmc','Block',source=source)
|
||||
dialog=ManagementDialog([request],adapter=NativeManagementAdapter())
|
||||
qtbot.addWidget(dialog);dialog.show()
|
||||
original=Path.resolve
|
||||
def resolve(path,*args,**kw):
|
||||
assert path!=source,'GUI preview touched potentially stalled source metadata'
|
||||
return original(path,*args,**kw)
|
||||
monkeypatch.setattr(Path,'resolve',resolve)
|
||||
questions=[]
|
||||
monkeypatch.setattr(timed_prompt,'question',lambda *a,**k:questions.append(a) or QMessageBox.No)
|
||||
dialog._execute()
|
||||
assert len(questions)==1
|
||||
@@ -0,0 +1,72 @@
|
||||
"""A durable receipt cannot expand the scope of its resource proof."""
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import library_lock as locks, residual_sessions, session_record as sessions
|
||||
|
||||
|
||||
@pytest.mark.parametrize('selected', [('A',), ('A', 'C')])
|
||||
def test_scoped_release_receipt_leaves_unselected_journal_discoverable(tmp_path, monkeypatch, selected):
|
||||
library = tmp_path/'library/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
address = library.parent/'ReusableBlocksLP/B/Work/database/cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_bytes(b'unselected B owner')
|
||||
history = tmp_path/'history'
|
||||
records = []
|
||||
for block in ('A', 'B', 'C'):
|
||||
path = history/block/'session.json'
|
||||
path.parent.mkdir(parents=True)
|
||||
value = dict(operation_id='op-'+block, library=str(library), block=block, processes=[])
|
||||
sessions.write_session_record(path, value)
|
||||
records.append({**value, 'path': str(path)})
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
monkeypatch.setattr(residual_sessions, 'query_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(residual_sessions, '_process_windows', lambda _: {})
|
||||
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
try:
|
||||
result = residual_sessions.release_residual_sessions(dict(library=str(library),
|
||||
block_names=list(selected), sessions=[], runtime_sessions=records), tmp_path/'evidence')
|
||||
assert result['status'] == 'RELEASE_CONFIRMED', result.get('detail')
|
||||
assert not list((history/'B').glob('observation-release-*.json'))
|
||||
assert address.read_bytes() == b'unselected B owner'
|
||||
monkeypatch.setattr(sessions, '_retained_libraries', {})
|
||||
monkeypatch.setattr(sessions, '_retained_results', {})
|
||||
found = sessions.discover_sessions(history, library=library)
|
||||
assert {row['block'] for row in found} == {'A', 'B', 'C'}-set(selected)
|
||||
finally:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('proof_scope,selected', [('BLOCK', ['A']), ('BLOCKS', ['A', 'C'])])
|
||||
def test_discovery_rejects_existing_receipt_for_uncovered_operation(tmp_path, monkeypatch, proof_scope, selected):
|
||||
library = tmp_path/'lib.lmc'
|
||||
library.touch()
|
||||
value = dict(operation_id='op-B', library=str(library), block='B', processes=[])
|
||||
sessions.write_session_record(tmp_path/'session.json', value)
|
||||
proof = dict(status='RELEASE_CONFIRMED', lease_state='RELEASED', library=str(library),
|
||||
proof_scope=proof_scope, proof_block_names=selected,
|
||||
proof_block_name=selected[0] if len(selected) == 1 else None,
|
||||
resource_scope=dict(scope_state='OBSERVED', library=str(library), block_names=selected))
|
||||
# Reproduce a receipt written by the prior implementation, then restart discovery.
|
||||
sessions.write_session_record(tmp_path/'observation-release-old.json',
|
||||
dict(operation_id='op-B', library=str(library), status='RELEASED', release_proof=proof))
|
||||
monkeypatch.setattr(sessions, '_retained_libraries', {})
|
||||
monkeypatch.setattr(sessions, '_retained_results', {})
|
||||
found = sessions.discover_sessions(tmp_path, library=library)
|
||||
assert len(found) == 1 and found[0]['operation_id'] == 'op-B'
|
||||
|
||||
|
||||
def test_receipt_writer_keeps_replaced_operation_unresolved(tmp_path):
|
||||
library = tmp_path/'lib.lmc'
|
||||
library.touch()
|
||||
path = tmp_path/'session.json'
|
||||
sessions.write_session_record(path, dict(operation_id='new', library=str(library), block='A', processes=[]))
|
||||
proof = dict(status='RELEASE_CONFIRMED', lease_state='RELEASED', library=str(library),
|
||||
proof_scope='BLOCK', proof_block_names=['A'], proof_block_name='A',
|
||||
resource_scope=dict(scope_state='OBSERVED', library=str(library), block_names=['A']))
|
||||
sessions.record_session_release(proof, [{'path': str(path), 'operation_id': 'old'}])
|
||||
assert not list(tmp_path.glob('observation-release-*.json'))
|
||||
@@ -0,0 +1,388 @@
|
||||
"""Resource release must not inherit another project's session or late evidence."""
|
||||
from contextlib import contextmanager
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import pytest
|
||||
import win32con
|
||||
import win32file
|
||||
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
from cbb_refresh_verify import residual_sessions, session_record
|
||||
|
||||
|
||||
def library_file(tmp_path, name='A'):
|
||||
path = tmp_path/name/'lib.lmc'
|
||||
path.parent.mkdir()
|
||||
path.touch()
|
||||
return path
|
||||
|
||||
|
||||
def cleanup(lease):
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
|
||||
|
||||
def test_residual_release_preserves_selected_scope_and_releases_parent_sidecar(tmp_path, monkeypatch):
|
||||
library = library_file(tmp_path)
|
||||
other = library.parent/'ReusableBlocksLP/B/Work/database/cdbsvr/sAddress.adr'
|
||||
other.parent.mkdir(parents=True)
|
||||
other.write_bytes(b'other native address')
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
monkeypatch.setattr(residual_sessions, 'query_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(residual_sessions, '_process_windows', lambda _: {})
|
||||
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
script = ('import sys; from cbb_refresh_verify.library_lock import LibraryLock; '
|
||||
'lease=LibraryLock(sys.argv[1],checkpoint=False); lease.__enter__(); lease.__exit__()')
|
||||
try:
|
||||
blocked = subprocess.run([sys.executable, '-c', script, str(library)], capture_output=True)
|
||||
assert blocked.returncode != 0
|
||||
result = residual_sessions.release_residual_sessions(
|
||||
{'library': str(library), 'block_names': ['A'], 'sessions': []}, tmp_path/'evidence')
|
||||
assert result['status'] == 'RELEASE_CONFIRMED', result.get('detail')
|
||||
assert result['proof']['proof_block_name'] == 'A'
|
||||
assert result['proof']['lease_state'] == 'RELEASED'
|
||||
assert other.read_bytes() == b'other native address'
|
||||
acquired = subprocess.run([sys.executable, '-c', script, str(library)], capture_output=True)
|
||||
assert acquired.returncode == 0, acquired.stderr
|
||||
assert lease.path.is_file()
|
||||
finally:
|
||||
cleanup(lease)
|
||||
|
||||
|
||||
def test_unknown_checkpoint_does_not_require_explicit_other_project_to_exit(tmp_path, monkeypatch):
|
||||
library = library_file(tmp_path)
|
||||
marker = locks.blocker_path(library)
|
||||
marker.write_bytes(b'{legacy unrecognized checkpoint')
|
||||
other = {'pid': 123456, 'name': 'ExpeditionPCB.exe',
|
||||
'command': f'ExpeditionPCB.exe "{tmp_path}/Other/board.prj"'}
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [other])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [])
|
||||
result = locks.release_retained_library(library, tmp_path/'evidence')
|
||||
assert result['status'] == 'RELEASE_CONFIRMED'
|
||||
assert result['unknown_checkpoint_archived'] is True
|
||||
assert result['data_recovery_confirmed'] is False
|
||||
|
||||
|
||||
def test_slow_release_of_a_does_not_block_b_cached_or_lease_checks(tmp_path, monkeypatch):
|
||||
a, b = library_file(tmp_path, 'A'), library_file(tmp_path, 'B')
|
||||
entered, finish = threading.Event(), threading.Event()
|
||||
with locks.LibraryLock(a, safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
@contextmanager
|
||||
def slow_proof(*args, **kwargs):
|
||||
entered.set()
|
||||
assert finish.wait(5)
|
||||
yield {'exclusive_files': [str(a)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', slow_proof)
|
||||
def inspect_b():
|
||||
assert not locks.has_retained_library(b)
|
||||
assert session_record.library_available(b)
|
||||
with locks.LibraryLock(b):
|
||||
return True
|
||||
with ThreadPoolExecutor(2) as pool:
|
||||
release = pool.submit(locks.release_retained_library, a, tmp_path/'evidence')
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
check = pool.submit(inspect_b)
|
||||
assert check.result(timeout=.5)
|
||||
finally:
|
||||
finish.set()
|
||||
release.result(5)
|
||||
cleanup(lease)
|
||||
|
||||
|
||||
def test_late_observer_cannot_clear_new_operation(tmp_path, monkeypatch):
|
||||
path = tmp_path/'session.json'
|
||||
library = tmp_path/'lib.lmc'
|
||||
session_record.write_session_record(path, {'operation_id': 'old', 'library': str(library)})
|
||||
key = str(path.absolute()).casefold()
|
||||
entered, finish = threading.Event(), threading.Event()
|
||||
def observe(*args, **kwargs):
|
||||
entered.set()
|
||||
assert finish.wait(3)
|
||||
return {'status': 'RELEASED', 'operation_id': 'old'}
|
||||
monkeypatch.setattr(session_record, 'observe_retained_session', observe)
|
||||
monkeypatch.setattr(session_record, '_observers', {})
|
||||
monkeypatch.setattr(session_record, '_retained_libraries', {})
|
||||
monkeypatch.setattr(session_record, '_retained_results', {})
|
||||
session_record.handoff_session(path, evidence_root=tmp_path)
|
||||
assert entered.wait(2)
|
||||
with session_record._observer_guard:
|
||||
thread = session_record._observers[key][0]
|
||||
session_record._retained_libraries[key] = {session_record._library_key(library)}
|
||||
session_record._retained_results[key] = {'operation_id': 'new', 'status': 'ACTIVE'}
|
||||
finish.set()
|
||||
thread.join(3)
|
||||
assert not session_record.library_available(library)
|
||||
assert session_record.retained_session_states(library)[0]['operation_id'] == 'new'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('repair_required', [False, True])
|
||||
def test_target_address_uses_native_inspection_and_keeps_recovery_separate(tmp_path, monkeypatch, repair_required):
|
||||
library = library_file(tmp_path)
|
||||
work = library.parent/'ReusableBlocksLP/A/Work'
|
||||
database = work/'database'
|
||||
address = database/'cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_bytes(b'native address retained')
|
||||
(database/'icdb.dat').write_bytes(b'database')
|
||||
project = work/'A.prj'
|
||||
project.write_text('KEY iCDBDir "database"\n')
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
def inspect(target, root, **kwargs):
|
||||
assert kwargs['inspection_only'] is True
|
||||
output = f'Loading project file [{project}].\nChecking if project is in use.\n'
|
||||
output += "Project is not in use. Full iCDB Project Backup's functionality is available.\n"
|
||||
if repair_required:
|
||||
output += (f'Project database [{database}] is inconsistent. It has been manually copied while '
|
||||
"the iCDB Server was running. Please use iCDB Project Backup 'Repair project' functionality to fix this issue.\n")
|
||||
output += 'Backup information loaded correctly.'
|
||||
return dict(status='NOT_IN_USE', repair_required=repair_required, inspection_only=True,
|
||||
repair_requested=False, native_pid=12345, native_exit_code=0,
|
||||
release={'native_exited': True}, project=str(project), database=str(database), output=output)
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_repair.run_native_repair', inspect)
|
||||
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
try:
|
||||
proof = locks.release_retained_library(library, tmp_path/'evidence', block_name='A')
|
||||
assert proof['lease_state'] == 'RELEASED'
|
||||
assert proof['data_recovery_required'] is repair_required
|
||||
assert proof['data_recovery_confirmed'] is False
|
||||
assert proof['resource_scope']['databases'] == [str(database)]
|
||||
assert address.read_bytes() == b'native address retained'
|
||||
assert not locks.has_retained_library(library)
|
||||
finally:
|
||||
cleanup(lease)
|
||||
|
||||
|
||||
def test_unknown_checkpoint_does_not_disown_export_server_from_path_alone(tmp_path, monkeypatch):
|
||||
library = library_file(tmp_path)
|
||||
locks.blocker_path(library).write_bytes(b'unknown')
|
||||
other = {'pid': 123456, 'name': 'icdbnetserver.exe',
|
||||
'command': f'icdbnetserver.exe -icdb "{tmp_path}/Other/database"'}
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [other])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [other])
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'evidence')
|
||||
|
||||
|
||||
def test_file_proof_holds_real_handle_until_context_exit(tmp_path):
|
||||
from cbb_refresh_verify import file_probe
|
||||
library = library_file(tmp_path)
|
||||
with file_probe.hold_release_files(library) as proof:
|
||||
assert proof['exclusive_files'] == [str(library)]
|
||||
with pytest.raises(Exception):
|
||||
handle = win32file.CreateFile(str(library), win32con.GENERIC_WRITE, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
handle.Close()
|
||||
handle = win32file.CreateFile(str(library), win32con.GENERIC_WRITE, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
handle.Close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('cancel', [False, True])
|
||||
def test_file_probe_timeout_or_stop_reaps_only_its_helper(tmp_path, monkeypatch, cancel):
|
||||
import time
|
||||
from cbb_refresh_verify import file_probe
|
||||
library = library_file(tmp_path)
|
||||
actual_popen = subprocess.Popen
|
||||
helpers = []
|
||||
def blocked_probe(command, **kwargs):
|
||||
child = actual_popen([sys.executable, '-c', 'import time; time.sleep(30)'], **kwargs)
|
||||
helpers.append(child)
|
||||
return child
|
||||
monkeypatch.setattr(file_probe.subprocess, 'Popen', blocked_probe)
|
||||
stop = threading.Event()
|
||||
if cancel:
|
||||
threading.Timer(.15, stop.set).start()
|
||||
started = time.monotonic()
|
||||
with pytest.raises((TimeoutError, InterruptedError)):
|
||||
with file_probe.hold_release_files(library, timeout_seconds=.3, stop=stop):
|
||||
pytest.fail('a stalled helper supplied release proof')
|
||||
assert time.monotonic()-started < 3
|
||||
assert helpers and helpers[0].poll() is not None
|
||||
|
||||
|
||||
def test_file_proof_survives_probe_exit_during_parent_commit(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import file_probe
|
||||
library = library_file(tmp_path)
|
||||
launch = subprocess.Popen
|
||||
helpers = []
|
||||
def capture(*args, **kwargs):
|
||||
child = launch(*args, **kwargs)
|
||||
helpers.append(child)
|
||||
return child
|
||||
monkeypatch.setattr(file_probe.subprocess, 'Popen', capture)
|
||||
with file_probe.hold_release_files(library):
|
||||
helpers[0].terminate()
|
||||
helpers[0].wait(3)
|
||||
with pytest.raises(Exception):
|
||||
handle = win32file.CreateFile(str(library), win32con.GENERIC_WRITE, 0, None,
|
||||
win32con.OPEN_EXISTING, 0, None)
|
||||
handle.Close()
|
||||
|
||||
|
||||
def test_worker_journal_records_declared_resource_scope_and_operation_identity(tmp_path):
|
||||
import os
|
||||
from types import SimpleNamespace
|
||||
library = library_file(tmp_path)
|
||||
project = library.parent/'ReusableBlocksLP/A/Work/A.prj'
|
||||
pcb = project.parent/'PCB/A.pcb'
|
||||
worker = SimpleNamespace(pid=os.getpid())
|
||||
path = tmp_path/'session.json'
|
||||
session_record.register_worker_session(worker, dict(session_record_path=str(path),
|
||||
operation_id='operation-123', operation='verify', library=str(library), block='A',
|
||||
project=str(project), pcb=str(pcb)))
|
||||
record = session_record.read_session_record(path, evidence_root=tmp_path)
|
||||
assert record['lease_state'] == 'ACTIVE'
|
||||
assert record['resource_scope']['operation_id'] == 'operation-123'
|
||||
assert record['resource_scope']['projects'] == [str(project)]
|
||||
assert str(pcb.parent/'database') in record['resource_scope']['databases']
|
||||
assert record['data_recovery_required'] is None
|
||||
|
||||
|
||||
def test_replacement_lease_cannot_be_cleared_by_earlier_probe(tmp_path, monkeypatch):
|
||||
library = library_file(tmp_path)
|
||||
with locks.LibraryLock(library, safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
marker = locks.blocker_path(library)
|
||||
original = marker.read_bytes()
|
||||
@contextmanager
|
||||
def replaced(*args, **kwargs):
|
||||
with locks._guard:
|
||||
locks._owners[lease.key] = {**locks._owners[lease.key], 'lease_id': 'b'*32}
|
||||
yield {'exclusive_files': [str(library)]}
|
||||
monkeypatch.setattr(locks, '_prove_library_released', replaced)
|
||||
try:
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'evidence')
|
||||
assert marker.read_bytes() == original
|
||||
assert locks._owners[lease.key]['lease_id'] == 'b'*32
|
||||
finally:
|
||||
cleanup(lease)
|
||||
|
||||
|
||||
def test_multiple_selected_projects_do_not_expand_release_to_unselected_c(tmp_path, monkeypatch):
|
||||
library = library_file(tmp_path)
|
||||
other = library.parent/'ReusableBlocksLP/C/Work/database/cdbsvr/sAddress.adr'
|
||||
other.parent.mkdir(parents=True)
|
||||
other.write_bytes(b'not selected')
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
monkeypatch.setattr(residual_sessions, 'query_process_snapshot', lambda: [])
|
||||
monkeypatch.setattr(residual_sessions, '_process_windows', lambda _: {})
|
||||
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
try:
|
||||
result = residual_sessions.release_residual_sessions(
|
||||
{'library': str(library), 'block_names': ['A', 'B'], 'sessions': []}, tmp_path/'evidence')
|
||||
assert result['status'] == 'RELEASE_CONFIRMED', result.get('detail')
|
||||
assert result['proof']['proof_block_names'] == ['A', 'B']
|
||||
assert other.read_bytes() == b'not selected'
|
||||
finally:
|
||||
cleanup(lease)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('verdict', ['IN_USE', 'UNCONFIRMED', 'NOT_EXITED'])
|
||||
def test_native_inspection_without_release_keeps_lease(tmp_path, monkeypatch, verdict):
|
||||
library = library_file(tmp_path)
|
||||
work = library.parent/'ReusableBlocksLP/A/Work'
|
||||
database = work/'database'
|
||||
address = database/'cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_bytes(b'keep native address')
|
||||
(database/'icdb.dat').touch()
|
||||
project = work/'A.prj'
|
||||
project.write_text('KEY iCDBDir "database"\n')
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
output = f'Loading project file [{project}].\nChecking if project is in use.\nProject is in use.'
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_repair.run_native_repair', lambda *a, **kw:
|
||||
dict(status=verdict, project=str(project), database=str(database), output=output,
|
||||
inspection_only=True, repair_requested=False, repair_required=False, native_pid=123,
|
||||
native_exit_code=0, release={'native_exited': verdict != 'NOT_EXITED'}))
|
||||
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
try:
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'evidence', block_name='A')
|
||||
assert locks.has_retained_library(library)
|
||||
assert address.read_bytes() == b'keep native address'
|
||||
finally:
|
||||
cleanup(lease)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('invalid_scope', [False, True])
|
||||
def test_legacy_release_receipt_without_resource_scope_is_rechecked(tmp_path, invalid_scope):
|
||||
library = library_file(tmp_path)
|
||||
session_record.write_session_record(tmp_path/'session.json',
|
||||
{'operation_id': 'legacy', 'library': str(library), 'processes': []})
|
||||
session_record.write_session_record(tmp_path/'observation-release-old.json',
|
||||
{'operation_id': 'legacy', 'status': 'RELEASED',
|
||||
'release_proof': {'status': 'RELEASE_CONFIRMED', 'library': str(library),
|
||||
**({'lease_state': 'RELEASED', 'resource_scope': None} if invalid_scope else {})}})
|
||||
found = session_record.discover_sessions(tmp_path)
|
||||
assert len(found) == 1
|
||||
assert found[0]['status'] == 'UNCONFIRMED'
|
||||
assert found[0]['resource_scope']['scope_state'] == 'RECHECK_REQUIRED'
|
||||
|
||||
|
||||
def test_stalled_transaction_checkpoint_does_not_block_other_library_memory(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify import management_transaction
|
||||
a, b = library_file(tmp_path, 'A'), library_file(tmp_path, 'B')
|
||||
entered, finish = threading.Event(), threading.Event()
|
||||
original = locks.checkpoint_record
|
||||
def checkpoint(path):
|
||||
if path == locks.blocker_path(a) and threading.current_thread().name.startswith('ThreadPool'):
|
||||
entered.set()
|
||||
assert finish.wait(5)
|
||||
return original(path)
|
||||
with locks.LibraryLock(a):
|
||||
monkeypatch.setattr(locks, 'checkpoint_record', checkpoint)
|
||||
with ThreadPoolExecutor(2) as pool:
|
||||
transaction = pool.submit(management_transaction.current_lease, a)
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
check = pool.submit(locks.has_retained_library, b)
|
||||
assert check.result(.5) is False
|
||||
finally:
|
||||
finish.set()
|
||||
with pytest.raises(ValueError): # This reader is not the lease's owning thread.
|
||||
transaction.result(3)
|
||||
|
||||
|
||||
def test_file_proof_holds_address_and_project_binding_against_changes(tmp_path):
|
||||
from cbb_refresh_verify import file_probe
|
||||
library = library_file(tmp_path)
|
||||
database = library.parent/'ReusableBlocksLP/A/Work/database'
|
||||
address = database/'cdbsvr/sAddress.adr'
|
||||
address.parent.mkdir(parents=True)
|
||||
address.write_bytes(b'address')
|
||||
(database/'icdb.dat').touch()
|
||||
project = database.parent/'A.prj'
|
||||
project.write_text('KEY iCDBDir "database"\n')
|
||||
with file_probe.hold_release_files(library):
|
||||
for path in (address, project):
|
||||
with pytest.raises(OSError):
|
||||
path.write_bytes(b'changed binding')
|
||||
assert address.read_bytes() == b'address'
|
||||
assert project.read_text() == 'KEY iCDBDir "database"\n'
|
||||
|
||||
|
||||
def test_file_probe_rejects_scope_junction_even_inside_same_library(tmp_path):
|
||||
import _winapi
|
||||
from cbb_refresh_verify import file_probe
|
||||
library = library_file(tmp_path)
|
||||
other = library.parent/'ReusableBlocksLP/B/Work'
|
||||
other.mkdir(parents=True)
|
||||
selected = library.parent/'ReusableBlocksLP/A/Work'
|
||||
selected.parent.mkdir(parents=True)
|
||||
_winapi.CreateJunction(str(other), str(selected))
|
||||
with pytest.raises(OSError):
|
||||
with file_probe.hold_release_files(library, (selected,)):
|
||||
pytest.fail('scope link silently changed the release target')
|
||||
@@ -0,0 +1,283 @@
|
||||
"""Actual process shutdown and captured native ownership regressions."""
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from test_issue15_ui_integration import window_for, load
|
||||
|
||||
|
||||
def test_close_retains_captured_mapping_while_native_supervisor_is_active(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.operation_queue import native_channel
|
||||
from cbb_refresh_verify.network_path import LibraryPathLease
|
||||
from test_network_path import FakeWNet
|
||||
window=window_for(qtbot,tmp_path,monkeypatch)
|
||||
load(window,qtbot)
|
||||
backend=FakeWNet()
|
||||
lease=LibraryPathLease.acquire(r'\\server\share\A\library.lmc',backend=backend)
|
||||
window.library_lease=lease; window.mentor_lmc_path=lease.mentor_path
|
||||
entered,release=Event(),Event()
|
||||
def action():
|
||||
with native_channel(): entered.set(); release.wait(5)
|
||||
job=window._new_job('verify',library=lease.mentor_path)
|
||||
window._start(action,lambda _:None,job=job)
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
try:
|
||||
window.close(); qtbot.wait(150)
|
||||
assert not lease._closed, 'active native owner lost its captured mapping'
|
||||
assert lease._retained_for_recovery
|
||||
finally:
|
||||
release.set(); qtbot.waitUntil(lambda:not window.isVisible())
|
||||
lease.release_after_recovery({'status':'RELEASE_CONFIRMED','library':str(lease.mentor_path)})
|
||||
lease.close()
|
||||
|
||||
|
||||
def test_old_release_proof_cleans_its_lease_without_updating_new_operation(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||
monkeypatch.setattr(ResidualReleaseDialog,'refresh',lambda self:None)
|
||||
cleaned=[]
|
||||
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases',
|
||||
lambda proof,**kw:cleaned.append((proof,kw)))
|
||||
window=window_for(qtbot,tmp_path,monkeypatch); load(window,qtbot)
|
||||
first,second=Event(),Event()
|
||||
window._start(lambda:first.wait(5),lambda _:None,queued=False)
|
||||
window.check_library_release(); panel=window.release_dialog
|
||||
first.set(); qtbot.waitUntil(lambda:not window.busy)
|
||||
window._start(lambda:second.wait(5),lambda _:None,queued=False)
|
||||
window.status_label.setText('NEW OPERATION STATUS')
|
||||
pending={'library':Path('a.lmc'),'names':['A'],'maintenance':False,'released':False}
|
||||
window._resume_batch=pending
|
||||
try:
|
||||
panel.released.emit({'status':'RELEASE_CONFIRMED','library':'a.lmc','evidence_path':'old-proof.json'})
|
||||
qtbot.waitUntil(lambda:bool(cleaned)); qtbot.waitUntil(lambda:window._lease_pending==0)
|
||||
assert window.status_label.text()=='NEW OPERATION STATUS'
|
||||
assert pending['released'] is False
|
||||
assert cleaned[0][0]['evidence_path']=='old-proof.json'
|
||||
finally:
|
||||
second.set(); qtbot.waitUntil(lambda:not window.busy); panel.close()
|
||||
|
||||
|
||||
def test_shutdown_role_rejects_unregistered_ui_write_before_its_body(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.operation_queue import native_phase
|
||||
window=window_for(qtbot,tmp_path,monkeypatch); load(window,qtbot)
|
||||
effects=[]
|
||||
def action():
|
||||
with native_phase(): effects.append('write')
|
||||
window._start(action,lambda _:None)
|
||||
qtbot.waitUntil(lambda:not window.busy)
|
||||
assert effects==[]
|
||||
assert 'NATIVE_ROLE_REQUIRED' in window.status_label.text()
|
||||
|
||||
|
||||
def test_readonly_native_phase_process_really_exits_while_observer_remains_pending(tmp_path):
|
||||
script=tmp_path/'readonly_app.py'
|
||||
script.write_text('''from threading import Event
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from PySide6.QtCore import QTimer
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.operation_queue import native_phase
|
||||
app=QApplication([])
|
||||
MainWindow._show_unfinished_management=lambda self:None
|
||||
w=MainWindow(reader=lambda _:None,data_root=Path(sys.argv[1])); w.show()
|
||||
def action():
|
||||
with native_phase(read_only=True):
|
||||
print('READONLY_PHASE_ACTIVE',flush=True)
|
||||
Event().wait(90)
|
||||
w._start(action,lambda _:None)
|
||||
QTimer.singleShot(250,w.close)
|
||||
app.exec()
|
||||
print('APP_RETURNED',flush=True)
|
||||
''',encoding='utf-8')
|
||||
process=subprocess.Popen([sys.executable,'-X','utf8',str(script),str(tmp_path/'data')],
|
||||
stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',
|
||||
env=dict(os.environ,QT_QPA_PLATFORM='offscreen'))
|
||||
try:
|
||||
stdout,stderr=process.communicate(timeout=8)
|
||||
assert process.returncode==0,stderr
|
||||
assert 'READONLY_PHASE_ACTIVE' in stdout and 'APP_RETURNED' in stdout
|
||||
finally:
|
||||
if process.poll() is None: process.kill(); process.communicate()
|
||||
|
||||
|
||||
def test_main_process_exit_hands_off_exact_worker_with_sidecar_and_writer_barrier(tmp_path):
|
||||
import win32api,win32con,win32event
|
||||
from cbb_refresh_verify.library_lock import LibraryLock, LibraryBusy
|
||||
from cbb_refresh_verify.operation_queue import native_channel
|
||||
library=tmp_path/'lib.lmc'; library.write_bytes(b'isolated metadata')
|
||||
child_script=tmp_path/'protected_child.py'
|
||||
child_script.write_text('''import sys,time,json,os
|
||||
from pathlib import Path
|
||||
from cbb_refresh_verify.desktop_worker import run_native_worker
|
||||
root=Path(sys.argv[1])
|
||||
def action(path):
|
||||
(root/'ready').write_text(str(os.getpid()))
|
||||
while not (root/'finish').exists(): time.sleep(.02)
|
||||
run_native_worker(action,root/'request.json')
|
||||
(root/'done').touch()
|
||||
''',encoding='utf-8')
|
||||
script=tmp_path/'owner_app.py'
|
||||
script.write_text('''import sys,time,subprocess,win32api,win32con,json
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from PySide6.QtCore import QTimer
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.operation_queue import native_channel,commit_worker_start
|
||||
from cbb_refresh_verify.library_lock import LibraryLock,duplicate_worker_lease
|
||||
from cbb_refresh_verify.session_record import register_worker_session
|
||||
root=Path(sys.argv[1]); library=root/'lib.lmc'
|
||||
app=QApplication([]); MainWindow._show_unfinished_management=lambda self:None
|
||||
w=MainWindow(reader=lambda _:None,data_root=root/'data'); w.show()
|
||||
def action():
|
||||
with LibraryLock(library,checkpoint=False), native_channel():
|
||||
record=dict(library=str(library),block='A',operation='verify',
|
||||
operation_id='protected-child',session_record_path=str(root/'session.json'),
|
||||
cancel_signal=str(root/'cancel'),start_gate=str(root/'gate'),start_gate_protocol='event-v1')
|
||||
(root/'request.json').write_text(json.dumps(record))
|
||||
child=subprocess.Popen([sys.executable,'-X','utf8',str(root/'protected_child.py'),str(root)],
|
||||
stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
handle=win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE,False,child.pid)
|
||||
try: lease=duplicate_worker_lease(library,handle)
|
||||
finally: handle.Close()
|
||||
register_worker_session(child,{**record,'worker_lease_handle':lease})
|
||||
commit_worker_start(child,record)
|
||||
Event().wait(90)
|
||||
job=w._new_job('verify',library=library,targets=('A',))
|
||||
w._start(action,lambda _:None,job=job)
|
||||
def close_ready():
|
||||
if (root/'ready').exists():
|
||||
print('PROTECTED_WRITER_ACTIVE',flush=True); w.close()
|
||||
else: QTimer.singleShot(20,close_ready)
|
||||
QTimer.singleShot(20,close_ready)
|
||||
app.exec(); print('APP_RETURNED',flush=True)
|
||||
''',encoding='utf-8')
|
||||
started=time.monotonic()
|
||||
process=subprocess.Popen([sys.executable,'-X','utf8',str(script),str(tmp_path)],
|
||||
stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',
|
||||
env=dict(os.environ,QT_QPA_PLATFORM='offscreen'))
|
||||
try:
|
||||
stdout,stderr=process.communicate(timeout=36)
|
||||
assert process.returncode==0,stderr
|
||||
assert 'PROTECTED_WRITER_ACTIVE' in stdout and 'APP_RETURNED' in stdout
|
||||
assert time.monotonic()-started<30
|
||||
record=json.loads((tmp_path/'session.json').read_text('utf-8'))
|
||||
pid=int((tmp_path/'ready').read_text())
|
||||
assert record['processes'][0]['pid']==pid and record['worker_lease_handle']
|
||||
assert record['start_gate_protocol']=='event-v1' and record['worker_start_handle']
|
||||
receipt=json.loads(next((tmp_path/'data'/'shutdown').glob('*.json')).read_text('utf-8'))
|
||||
assert receipt['safe_to_continue'] is False and receipt['status']=='UNCONFIRMED'
|
||||
bindings=[binding for scope in receipt['task_scopes'] for binding in scope['worker_sessions']]
|
||||
assert any(binding['operation_id']=='protected-child' and binding['path']==str(tmp_path/'session.json')
|
||||
and binding['worker_protection']=='duplicated_lease' for binding in bindings)
|
||||
assert record['task_operation_id'] in {scope['operation_id'] for scope in receipt['task_scopes']}
|
||||
handle=win32api.OpenProcess(win32con.SYNCHRONIZE,False,pid)
|
||||
try: assert win32event.WaitForSingleObject(handle,0)==win32con.WAIT_TIMEOUT
|
||||
finally: handle.Close()
|
||||
with pytest.raises(LibraryBusy):
|
||||
with LibraryLock(library,checkpoint=False): pass
|
||||
with pytest.raises(RuntimeError,match='NATIVE_WRITER_ACTIVE'):
|
||||
with native_channel(): pass
|
||||
finally:
|
||||
(tmp_path/'finish').touch()
|
||||
if process.poll() is None: process.kill(); process.communicate()
|
||||
deadline=time.monotonic()+5
|
||||
while (tmp_path/'ready').exists() and not (tmp_path/'done').exists() and time.monotonic()<deadline:
|
||||
time.sleep(.02)
|
||||
assert (tmp_path/'done').exists()
|
||||
with LibraryLock(library,checkpoint=False), native_channel(): pass
|
||||
|
||||
|
||||
def test_shutdown_during_registration_returns_waiter_and_never_opens_late_gate(tmp_path,monkeypatch):
|
||||
from threading import Thread
|
||||
import win32api,win32con
|
||||
from cbb_refresh_verify import session_record
|
||||
from cbb_refresh_verify.library_lock import LibraryLock,duplicate_worker_lease
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext,TaskHandoff,native_channel
|
||||
library=tmp_path/'lib.lmc'; library.write_bytes(b'isolated')
|
||||
context=BatchTaskContext(str(library),native_policy='external')
|
||||
entered,resume,returned=Event(),Event(),Event(); gates=[]; child=[]
|
||||
original=session_record.write_session_record
|
||||
def stalled(path,value):
|
||||
entered.set(); resume.wait(5); return original(path,value)
|
||||
monkeypatch.setattr(session_record,'write_session_record',stalled)
|
||||
def action():
|
||||
with LibraryLock(library,checkpoint=False), native_channel():
|
||||
process=subprocess.Popen([sys.executable,'-c','input()'],stdin=subprocess.PIPE,text=True)
|
||||
child.append(process)
|
||||
handle=win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE,False,process.pid)
|
||||
try: lease=duplicate_worker_lease(library,handle)
|
||||
finally: handle.Close()
|
||||
session_record.register_worker_session(process,dict(library=str(library),operation='verify',
|
||||
operation_id='registration',session_record_path=str(tmp_path/'session.json'),worker_lease_handle=lease))
|
||||
gates.append('late native dispatch')
|
||||
def run():
|
||||
try: context.run(action)
|
||||
except TaskHandoff: pass
|
||||
finally: returned.set()
|
||||
thread=Thread(target=run); thread.start(); assert entered.wait(2)
|
||||
try:
|
||||
state=context.shutdown()
|
||||
assert state['safe_to_continue'] is False and returned.wait(1)
|
||||
resume.set()
|
||||
deadline=time.monotonic()+3
|
||||
while context.snapshot()['pending'] and time.monotonic()<deadline: time.sleep(.01)
|
||||
assert not context.snapshot()['pending']
|
||||
assert gates==[]
|
||||
finally:
|
||||
resume.set(); thread.join(3)
|
||||
for process in child: process.communicate('\n',timeout=3)
|
||||
|
||||
|
||||
def test_readonly_observer_cannot_enter_a_mutating_phase(tmp_path):
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext,native_phase,native_channel
|
||||
effects=[]
|
||||
def action():
|
||||
with native_phase(read_only=True):
|
||||
with native_channel(): effects.append('write')
|
||||
with pytest.raises(RuntimeError,match='NATIVE_ROLE_REQUIRED'):
|
||||
BatchTaskContext(str(tmp_path/'lib.lmc'),native_policy='external').run(action)
|
||||
assert effects==[]
|
||||
|
||||
|
||||
def test_readonly_role_rejects_mutating_worker_at_common_registration(tmp_path):
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext,native_phase
|
||||
from cbb_refresh_verify.session_record import register_worker_session
|
||||
process=subprocess.Popen([sys.executable,'-c','input()'],stdin=subprocess.PIPE,text=True)
|
||||
effects=[]
|
||||
def action():
|
||||
with native_phase(read_only=True):
|
||||
register_worker_session(process,dict(library=str(tmp_path/'lib.lmc'),operation='remove',
|
||||
operation_id='forbidden',session_record_path=str(tmp_path/'session.json'),worker_lease_handle=1))
|
||||
effects.append('write gate')
|
||||
try:
|
||||
with pytest.raises(RuntimeError,match='NATIVE_ROLE_REQUIRED'):
|
||||
BatchTaskContext(str(tmp_path/'lib.lmc'),native_policy='external').run(action)
|
||||
assert effects==[]
|
||||
finally: process.communicate('\n',timeout=3)
|
||||
|
||||
|
||||
def test_shutdown_does_not_abandon_a_legacy_inprocess_mutation(tmp_path):
|
||||
from threading import Thread
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext,native_phase
|
||||
context=BatchTaskContext(str(tmp_path/'lib.lmc'))
|
||||
entered,release,returned=Event(),Event(),Event()
|
||||
def action():
|
||||
with native_phase(): entered.set(); release.wait(3)
|
||||
def run():
|
||||
try: context.run(action)
|
||||
finally: returned.set()
|
||||
thread=Thread(target=run); thread.start(); assert entered.wait(1)
|
||||
try:
|
||||
state=context.shutdown()
|
||||
assert state['pending_native'] and not state['shutdown_handoff']
|
||||
assert state['safe_to_continue'] is False and not returned.wait(.1)
|
||||
finally: release.set(); thread.join(3)
|
||||
assert returned.is_set()
|
||||
@@ -0,0 +1,737 @@
|
||||
"""Cancellation must release scheduling, never invent native release."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from threading import Event, Thread
|
||||
import time
|
||||
|
||||
import pytest
|
||||
import win32con
|
||||
import win32event
|
||||
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
from test_management import setup as management_setup
|
||||
|
||||
|
||||
@pytest.mark.parametrize('stage', ['read', 'archive'])
|
||||
def test_stalled_checkpoint_does_not_own_native_channel_or_commit_after_stop(tmp_path, monkeypatch, stage):
|
||||
library = tmp_path/'A/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
marker = locks.blocker_path(library)
|
||||
original = marker.read_bytes()
|
||||
entered, resume, stop = Event(), Event(), Event()
|
||||
read, write = Path.read_bytes, Path.write_bytes
|
||||
def read_bytes(path):
|
||||
if stage == 'read' and path == marker and not resume.is_set():
|
||||
entered.set()
|
||||
assert resume.wait(5)
|
||||
return read(path)
|
||||
def write_bytes(path, data):
|
||||
if stage == 'archive' and path.name.startswith('blocker-before-'):
|
||||
entered.set()
|
||||
assert resume.wait(5)
|
||||
return write(path, data)
|
||||
monkeypatch.setattr(Path, 'read_bytes', read_bytes)
|
||||
monkeypatch.setattr(Path, 'write_bytes', write_bytes)
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
task = pool.submit(locks.release_retained_library, library, tmp_path/'evidence', stop=stop)
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
try:
|
||||
assert entered.wait(3)
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) in (
|
||||
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
|
||||
assert acquired, 'checkpoint I/O retained the host native channel'
|
||||
if stage == 'archive':
|
||||
import json
|
||||
receipt = next((tmp_path/'evidence').rglob('release.json'))
|
||||
assert json.loads(receipt.read_text())['lease_state'] != 'RELEASED'
|
||||
stop.set()
|
||||
resume.set()
|
||||
with pytest.raises(InterruptedError):
|
||||
task.result(5)
|
||||
assert read(marker) == original
|
||||
assert locks.has_retained_library(library)
|
||||
finally:
|
||||
stop.set()
|
||||
resume.set()
|
||||
if acquired:
|
||||
win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
try:
|
||||
task.result(5)
|
||||
except InterruptedError:
|
||||
pass
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner:
|
||||
owner['handle'].Close()
|
||||
|
||||
|
||||
def test_task_context_is_frozen_pure_and_has_an_independent_monotonic_stop(tmp_path, monkeypatch):
|
||||
from dataclasses import FrozenInstanceError
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext
|
||||
monkeypatch.setattr(Path, 'resolve', lambda *a, **k: pytest.fail('context performed filesystem admission'))
|
||||
first = BatchTaskContext(library=str(tmp_path/'A.lmc'), aliases=('Z:/A.lmc',), targets=('A',))
|
||||
second = BatchTaskContext(library=str(tmp_path/'B.lmc'))
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
first.library = second.library
|
||||
first.cancel()
|
||||
assert first.stop.is_set() and not second.stop.is_set()
|
||||
assert not hasattr(first.stop, 'clear')
|
||||
received = []
|
||||
first.guard_callback(received.append)('CANCELLED')
|
||||
assert received == ['CANCELLED']
|
||||
first.close(timeout_seconds=0)
|
||||
first.guard_callback(received.append)('late')
|
||||
assert received == ['CANCELLED']
|
||||
|
||||
|
||||
def test_bounded_queue_handoff_preserves_scope_and_fences_late_native_launch(tmp_path):
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, TaskHandoff, native_phase
|
||||
queue = NativeQueue()
|
||||
first = BatchTaskContext(library=str(tmp_path/'A.lmc'), targets=('A',))
|
||||
second = BatchTaskContext(library=str(tmp_path/'B.lmc'), targets=('B',))
|
||||
entered, resume, finished = Event(), Event(), Event()
|
||||
effects = []
|
||||
def stalled():
|
||||
try:
|
||||
entered.set()
|
||||
assert resume.wait(3)
|
||||
with native_phase():
|
||||
effects.append('late native write')
|
||||
finally:
|
||||
finished.set()
|
||||
try:
|
||||
with pytest.raises(TaskHandoff) as error:
|
||||
queue.run(stalled, context=first, timeout_seconds=.05)
|
||||
assert entered.is_set() and error.value.library == first.library
|
||||
assert first.snapshot()['pending'] == 1
|
||||
assert queue.run(lambda: 'B ran', context=second) == 'B ran'
|
||||
resume.set()
|
||||
assert finished.wait(2)
|
||||
assert effects == []
|
||||
finally:
|
||||
resume.set()
|
||||
assert finished.wait(2)
|
||||
|
||||
|
||||
def test_native_phase_is_never_yielded_at_metadata_deadline(tmp_path):
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, native_phase
|
||||
queue = NativeQueue()
|
||||
context = BatchTaskContext(library=str(tmp_path/'A.lmc'))
|
||||
entered, resume, finished = Event(), Event(), Event()
|
||||
results = []
|
||||
def transaction():
|
||||
with native_phase():
|
||||
entered.set()
|
||||
assert resume.wait(3)
|
||||
return 'Remove and Add completed'
|
||||
def run():
|
||||
results.append(queue.run(transaction, context=context, timeout_seconds=.02))
|
||||
finished.set()
|
||||
thread = Thread(target=run)
|
||||
thread.start()
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
assert not finished.wait(.1)
|
||||
state = context.close(timeout_seconds=.02)
|
||||
assert state['pending_native'] and queue.active
|
||||
resume.set()
|
||||
assert finished.wait(2)
|
||||
assert results == ['Remove and Add completed']
|
||||
finally:
|
||||
resume.set()
|
||||
thread.join(2)
|
||||
|
||||
|
||||
def test_stalled_ready_predicate_does_not_hold_queue_condition():
|
||||
from cbb_refresh_verify.operation_queue import NativeQueue, QueueCancelled
|
||||
queue = NativeQueue()
|
||||
entered, resume, stop, completed = Event(), Event(), Event(), Event()
|
||||
effects = []
|
||||
def slow_ready():
|
||||
entered.set()
|
||||
assert resume.wait(3)
|
||||
return True
|
||||
def first():
|
||||
try:
|
||||
queue.run(lambda: effects.append('A'), ready=slow_ready, stop=stop)
|
||||
except QueueCancelled:
|
||||
pass
|
||||
thread = Thread(target=first)
|
||||
thread.start()
|
||||
second = Thread(target=lambda: (queue.run(lambda: effects.append('B')), completed.set()))
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
second.start()
|
||||
assert completed.wait(.5), 'one ready predicate froze every other queue ticket'
|
||||
stop.set()
|
||||
resume.set()
|
||||
thread.join(2)
|
||||
assert effects == ['B']
|
||||
finally:
|
||||
stop.set()
|
||||
resume.set()
|
||||
thread.join(3)
|
||||
second.join(3)
|
||||
|
||||
|
||||
def test_verify_admission_handoff_unblocks_b_and_never_launches_after_read_returns(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue
|
||||
from cbb_refresh_verify.verify_runner import VerifyRequest, run_verify
|
||||
import win32process
|
||||
library = tmp_path/'A/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
with locks.LibraryLock(library, block_name='A', safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
marker = locks.blocker_path(library)
|
||||
entered, resume, returned = Event(), Event(), Event()
|
||||
read = Path.read_text
|
||||
def withheld(path, *args, **kwargs):
|
||||
if path == marker:
|
||||
entered.set()
|
||||
assert resume.wait(3)
|
||||
returned.set()
|
||||
return read(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'read_text', withheld)
|
||||
monkeypatch.setattr(win32process, 'CreateProcess', lambda *a, **k: pytest.fail('late native launch'))
|
||||
context = BatchTaskContext(library=str(library), targets=('A',))
|
||||
events = []
|
||||
try:
|
||||
result = run_verify(VerifyRequest(library, 'A', tmp_path/'evidence'), context=context,
|
||||
admission_timeout_seconds=.05, progress=events.append)
|
||||
assert entered.is_set() and result.status == 'TIMEOUT'
|
||||
assert not result.safe_to_continue
|
||||
assert result.release_proof['resource_scope']['operation_ids'] == [context.operation_id]
|
||||
def unrelated():
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) == win32con.WAIT_OBJECT_0
|
||||
try:
|
||||
assert acquired
|
||||
return 'B completed'
|
||||
finally:
|
||||
if acquired: win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
assert NativeQueue().run(unrelated) == 'B completed'
|
||||
count = len(events)
|
||||
resume.set()
|
||||
assert returned.wait(2)
|
||||
limit = time.monotonic()+2
|
||||
while context.snapshot()['pending'] and time.monotonic() < limit:
|
||||
time.sleep(.01)
|
||||
assert context.snapshot()['pending'] == 0
|
||||
assert len(events) == count
|
||||
finally:
|
||||
resume.set()
|
||||
context.close(timeout_seconds=2)
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_native_time_does_not_consume_next_metadata_phase_budget(tmp_path):
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, native_phase
|
||||
context = BatchTaskContext(library=str(tmp_path/'A.lmc'))
|
||||
stages = []
|
||||
def action():
|
||||
with native_phase():
|
||||
time.sleep(.12)
|
||||
stages.append('saved')
|
||||
time.sleep(.02)
|
||||
with native_phase():
|
||||
stages.append('closed')
|
||||
return stages
|
||||
assert context.run(action, timeout_seconds=.06) == ['saved', 'closed']
|
||||
|
||||
|
||||
def test_native_channel_enforces_cross_thread_serialization_and_reentrancy():
|
||||
from cbb_refresh_verify.operation_queue import native_channel
|
||||
with native_channel():
|
||||
with native_channel():
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
def contend():
|
||||
with native_channel():
|
||||
pytest.fail('concurrent native writer admitted')
|
||||
with pytest.raises(RuntimeError, match='NATIVE_CHANNEL_BUSY'):
|
||||
pool.submit(contend).result(2)
|
||||
with native_channel():
|
||||
pass
|
||||
|
||||
|
||||
def test_maintenance_checkpoint_admission_does_not_hold_native_channel(tmp_path, monkeypatch):
|
||||
from contextlib import nullcontext
|
||||
library = tmp_path/'A/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
with locks.LibraryLock(library, safe_to_release=lambda: False) as retained:
|
||||
pass
|
||||
marker = locks.blocker_path(library)
|
||||
entered, resume = Event(), Event()
|
||||
original = Path.read_bytes
|
||||
def withheld(path):
|
||||
if path == marker and not resume.is_set():
|
||||
entered.set()
|
||||
assert resume.wait(3)
|
||||
return original(path)
|
||||
monkeypatch.setattr(Path, 'read_bytes', withheld)
|
||||
def admit():
|
||||
with locks.LibraryLock.for_maintenance(library, tmp_path/'archive', lambda: nullcontext({})):
|
||||
pass
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
task = pool.submit(admit)
|
||||
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
|
||||
acquired = False
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
acquired = win32event.WaitForSingleObject(mutex, 0) == win32con.WAIT_OBJECT_0
|
||||
assert acquired
|
||||
finally:
|
||||
if acquired: win32event.ReleaseMutex(mutex)
|
||||
mutex.Close()
|
||||
resume.set()
|
||||
task.result(5)
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(retained.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_native_handoff_keeps_worker_barrier_until_bound_process_returns(tmp_path):
|
||||
import subprocess
|
||||
import sys
|
||||
from cbb_refresh_verify.operation_queue import (
|
||||
BatchTaskContext, NativeQueue, TaskHandoff, hold_native_handoff, native_channel)
|
||||
from cbb_refresh_verify.session_record import write_session_record
|
||||
process = None
|
||||
context = BatchTaskContext(library=str(tmp_path/'A.lmc'))
|
||||
record = tmp_path/'session.json'
|
||||
queue = NativeQueue()
|
||||
effects = []
|
||||
def action():
|
||||
nonlocal process
|
||||
with native_channel():
|
||||
script = ('from cbb_refresh_verify.desktop_worker import worker_native_channel\n'
|
||||
'with worker_native_channel():\n print("ready",flush=True)\n input()\n')
|
||||
process = subprocess.Popen([sys.executable, '-c', script], stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, text=True)
|
||||
assert process.stdout.readline().strip() == 'ready'
|
||||
write_session_record(record, dict(operation_id=context.operation_id, library=context.library,
|
||||
worker_pid=process.pid))
|
||||
hold_native_handoff(process, record)
|
||||
with native_channel():
|
||||
effects.append('late mutation')
|
||||
try:
|
||||
with pytest.raises(TaskHandoff):
|
||||
queue.run(action, context=context)
|
||||
assert process.poll() is None
|
||||
assert not context.snapshot()['pending_native'] # Parent admission yielded to exact controls.
|
||||
assert queue.run(lambda: 'pure read') == 'pure read'
|
||||
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||
with native_channel():
|
||||
pytest.fail('writer overlapped handed-off native call')
|
||||
process.communicate('\n', timeout=3)
|
||||
limit = time.monotonic()+3
|
||||
while context.snapshot()['pending'] and time.monotonic() < limit:
|
||||
time.sleep(.01)
|
||||
assert context.snapshot()['pending'] == 0
|
||||
with native_channel():
|
||||
pass
|
||||
assert effects == []
|
||||
finally:
|
||||
if process is not None and process.poll() is None:
|
||||
process.communicate('\n', timeout=3)
|
||||
context.close(timeout_seconds=3)
|
||||
|
||||
|
||||
def test_worker_write_barrier_survives_supervisor_process_exit(tmp_path):
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from cbb_refresh_verify.operation_queue import native_channel
|
||||
ready, finish, done = (tmp_path/name for name in ('ready', 'finish', 'done'))
|
||||
child = '''import sys,time,os
|
||||
from pathlib import Path
|
||||
from cbb_refresh_verify.desktop_worker import worker_native_channel
|
||||
with worker_native_channel():
|
||||
Path(sys.argv[1]).write_text(str(os.getpid()))
|
||||
while not Path(sys.argv[2]).exists(): time.sleep(.02)
|
||||
Path(sys.argv[3]).touch()
|
||||
'''
|
||||
parent = '''import subprocess,sys,time,json
|
||||
from pathlib import Path
|
||||
subprocess.Popen([sys.executable,'-c',sys.argv[1],*sys.argv[2:]])
|
||||
deadline=time.monotonic()+4
|
||||
while not Path(sys.argv[2]).exists() and time.monotonic()<deadline: time.sleep(.02)
|
||||
raise SystemExit(0 if Path(sys.argv[2]).exists() else 2)
|
||||
'''
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', parent, child, str(ready), str(finish), str(done)])
|
||||
try:
|
||||
assert supervisor.wait(timeout=6) == 0
|
||||
assert ready.is_file() and not done.exists()
|
||||
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||
with native_channel():
|
||||
pytest.fail('restart admitted a second writer')
|
||||
finally:
|
||||
finish.touch()
|
||||
deadline = time.monotonic()+3
|
||||
while not done.exists() and time.monotonic()<deadline: time.sleep(.02)
|
||||
supervisor.wait(timeout=3)
|
||||
assert done.is_file()
|
||||
with native_channel():
|
||||
pass
|
||||
|
||||
|
||||
def test_exact_sidecar_handle_survives_parent_exit_until_worker_boundary(tmp_path):
|
||||
import subprocess
|
||||
import sys
|
||||
library = tmp_path/'A/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
ready, finish, done, handle = (tmp_path/name for name in ('ready', 'finish', 'done', 'handle'))
|
||||
child = '''import sys,time
|
||||
from pathlib import Path
|
||||
from cbb_refresh_verify.desktop_worker import worker_native_channel
|
||||
while not Path(sys.argv[4]).exists(): time.sleep(.02)
|
||||
with worker_native_channel(lease_handle=int(Path(sys.argv[4]).read_text())):
|
||||
Path(sys.argv[1]).touch()
|
||||
while not Path(sys.argv[2]).exists(): time.sleep(.02)
|
||||
Path(sys.argv[3]).touch()
|
||||
'''
|
||||
parent = '''import subprocess,sys,time,win32api,win32con
|
||||
from pathlib import Path
|
||||
from cbb_refresh_verify.library_lock import LibraryLock,duplicate_worker_lease
|
||||
with LibraryLock(sys.argv[1],checkpoint=False):
|
||||
child=subprocess.Popen([sys.executable,'-c',sys.argv[2],*sys.argv[3:]])
|
||||
process=win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE,False,child.pid)
|
||||
try: handle=duplicate_worker_lease(sys.argv[1],process)
|
||||
finally: process.Close()
|
||||
Path(sys.argv[6]).write_text(str(handle))
|
||||
deadline=time.monotonic()+4
|
||||
while not Path(sys.argv[3]).exists() and time.monotonic()<deadline: time.sleep(.02)
|
||||
assert Path(sys.argv[3]).exists()
|
||||
'''
|
||||
supervisor = subprocess.Popen([sys.executable, '-c', parent, str(library), child,
|
||||
str(ready), str(finish), str(done), str(handle)])
|
||||
try:
|
||||
assert supervisor.wait(timeout=6) == 0
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library, checkpoint=False):
|
||||
pytest.fail('uploader could replace a live worker library')
|
||||
finally:
|
||||
finish.touch()
|
||||
deadline = time.monotonic()+3
|
||||
while ready.exists() and not done.exists() and time.monotonic()<deadline: time.sleep(.02)
|
||||
supervisor.wait(timeout=3)
|
||||
assert done.is_file()
|
||||
with locks.LibraryLock(library, checkpoint=False):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.mark.parametrize('obstacle', ['', 'unknown_title', 'duplicate', 'changed'])
|
||||
def test_failed_startup_dismisses_only_exact_stable_owned_tip(tmp_path, monkeypatch, obstacle):
|
||||
import win32gui
|
||||
from test_failed_startup import startup_fixture
|
||||
from cbb_refresh_verify.failed_session import close_failed_startup
|
||||
job, records, messages = startup_fixture(tmp_path, monkeypatch)
|
||||
visible = {100, 200}
|
||||
reads = []
|
||||
classes = {100: 'Afx:main', 200: '#32770', 201: 'Button', 202: 'Button'}
|
||||
def title(hwnd):
|
||||
if hwnd == 100: return 'Expedition PCB'
|
||||
if hwnd == 200:
|
||||
reads.append(hwnd)
|
||||
return 'Unknown' if obstacle == 'unknown_title' or obstacle == 'changed' and len(reads)>1 else 'Tip of the Day'
|
||||
return 'OK'
|
||||
monkeypatch.setattr(win32gui, 'EnumWindows', lambda fn, arg: [fn(h, arg) for h in sorted(visible)])
|
||||
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda hwnd, fn, arg:
|
||||
[fn(h, arg) for h in ((201, 202) if obstacle == 'duplicate' else (201,))] if hwnd == 200 else None)
|
||||
monkeypatch.setattr(win32gui, 'GetClassName', classes.__getitem__)
|
||||
monkeypatch.setattr(win32gui, 'GetWindowText', title)
|
||||
monkeypatch.setattr(win32gui, 'GetDlgCtrlID', lambda hwnd: 1)
|
||||
def post(hwnd, message, wparam, lparam):
|
||||
messages.append((hwnd, message))
|
||||
if hwnd == 201: visible.remove(200)
|
||||
elif hwnd == 100: records.clear()
|
||||
monkeypatch.setattr(win32gui, 'PostMessage', post)
|
||||
result = close_failed_startup(job, 12, timeout_seconds=0)
|
||||
if obstacle:
|
||||
assert result['status'] == 'RETAINED' and not messages
|
||||
else:
|
||||
assert result['status'] == 'CLOSED'
|
||||
assert messages == [(201, win32con.BM_CLICK), (100, win32con.WM_CLOSE)]
|
||||
|
||||
|
||||
def test_late_release_recheck_is_bounded_and_keeps_business_failure(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.operation_lifecycle import recheck_failed_release
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
from cbb_refresh_verify.session_record import write_session_record
|
||||
library = tmp_path/'A/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
evidence = tmp_path/'evidence'
|
||||
evidence.mkdir()
|
||||
result = VerifyResult('FAIL', stderr='native business failure', safe_to_continue=False,
|
||||
evidence_path=evidence/'result.json')
|
||||
result.evidence_path.write_text('{}')
|
||||
record = evidence/'session.json'
|
||||
write_session_record(record, dict(operation_id='failed', library=str(library), block='A', processes=[]))
|
||||
entered, resume = Event(), Event()
|
||||
original = Path.open
|
||||
def withheld(path, *args, **kwargs):
|
||||
if path == record:
|
||||
entered.set()
|
||||
assert resume.wait(3)
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'open', withheld)
|
||||
try:
|
||||
started = time.monotonic()
|
||||
returned = recheck_failed_release(library, 'A', result, timeout_seconds=.05)
|
||||
assert time.monotonic()-started < .8
|
||||
assert entered.is_set() and returned is result
|
||||
assert returned.status == 'FAIL' and not returned.safe_to_continue
|
||||
finally:
|
||||
resume.set()
|
||||
|
||||
|
||||
def test_batch_context_cancel_records_all_remaining_items_and_new_batch_can_run(tmp_path):
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext
|
||||
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult, run_batch
|
||||
requests = [VerifyRequest(tmp_path/'lib.lmc', name, tmp_path/'evidence') for name in ('A', 'B', 'C')]
|
||||
first = BatchTaskContext(library=str(requests[0].lmc_file), targets=('A', 'B', 'C'))
|
||||
events = []
|
||||
def verify(request):
|
||||
first.cancel()
|
||||
return VerifyResult('CANCELLED')
|
||||
results = run_batch(requests, verifier=verify, context=first,
|
||||
progress=lambda name, result: events.append((name, result.status)))
|
||||
assert [r.status for r in results] == ['CANCELLED', 'SKIPPED', 'SKIPPED']
|
||||
assert events == [('A', 'CANCELLED'), ('B', 'SKIPPED'), ('C', 'SKIPPED')]
|
||||
second = BatchTaskContext(library=str(requests[0].lmc_file), targets=('A',))
|
||||
assert run_batch(requests[:1], verifier=lambda _: VerifyResult('PASS'), context=second)[0].status == 'PASS'
|
||||
|
||||
|
||||
def test_batch_retention_matches_normalized_library_alias_not_business_failure(tmp_path):
|
||||
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult, run_batch
|
||||
library = tmp_path/'A/lib.lmc'
|
||||
alias = tmp_path/'A/sub/../lib.lmc'
|
||||
requests = [VerifyRequest(path, block, tmp_path/'evidence') for path, block in (
|
||||
(library, 'A'), (alias, 'B'), (tmp_path/'B/lib.lmc', 'C'), (tmp_path/'B/lib.lmc', 'D'))]
|
||||
calls = []
|
||||
def verify(request):
|
||||
calls.append(request.block_name)
|
||||
return VerifyResult('FAIL', safe_to_continue=request.block_name != 'A')
|
||||
results = run_batch(requests, verifier=verify)
|
||||
assert calls == ['A', 'C', 'D']
|
||||
assert [r.status for r in results] == ['FAIL', 'SKIPPED', 'FAIL', 'FAIL']
|
||||
|
||||
|
||||
def test_queue_close_has_one_deadline_and_reports_pending_scope(tmp_path):
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue, TaskHandoff
|
||||
queue = NativeQueue()
|
||||
context = BatchTaskContext(library=str(tmp_path/'A.lmc'), aliases=('Z:/A.lmc',))
|
||||
entered, resume, finished = Event(), Event(), Event()
|
||||
def action():
|
||||
entered.set()
|
||||
resume.wait(3)
|
||||
def run():
|
||||
try:
|
||||
queue.run(action, context=context)
|
||||
except TaskHandoff:
|
||||
pass
|
||||
finally:
|
||||
finished.set()
|
||||
thread = Thread(target=run)
|
||||
thread.start()
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
started = time.monotonic()
|
||||
states = queue.close(timeout_seconds=.05)
|
||||
assert time.monotonic()-started < .5
|
||||
assert states[0]['resource_scope']['aliases'] == ['Z:/A.lmc']
|
||||
assert states[0]['pending'] == 1
|
||||
assert finished.wait(1)
|
||||
finally:
|
||||
resume.set()
|
||||
thread.join(2)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('native_policy', ['legacy', 'external'])
|
||||
def test_real_management_transaction_does_not_handoff_between_remove_and_add(management_setup, monkeypatch, native_policy):
|
||||
from dataclasses import replace
|
||||
from types import SimpleNamespace
|
||||
from test_management import execute
|
||||
from cbb_refresh_verify import operation_queue
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue
|
||||
request, adapter, source = management_setup
|
||||
offset = [0.0]
|
||||
real_clock = time.monotonic
|
||||
monkeypatch.setattr(operation_queue, 'time', SimpleNamespace(monotonic=lambda: real_clock()+offset[0]))
|
||||
original = adapter.remove
|
||||
def slow_remove(*args):
|
||||
result = original(*args)
|
||||
offset[0] += 100 # Native time exceeds admission budget without timing filesystem preparation.
|
||||
time.sleep(.08) # Let the real admission monitor observe the active native phase.
|
||||
return result
|
||||
adapter.remove = slow_remove # Native external boundary; transaction stays real.
|
||||
context = BatchTaskContext(library=str(request.library), targets=('Block',), native_policy=native_policy)
|
||||
result = NativeQueue().run(lambda: execute(replace(request, operation='update',
|
||||
source=source, auto_verify=False), adapter), context=context, timeout_seconds=10)
|
||||
assert result.status == 'UPLOADED'
|
||||
assert adapter.calls[0] == 'remove' and adapter.calls[1][0] == 'add'
|
||||
|
||||
|
||||
def test_busy_native_channel_before_dispatch_does_not_retain_management_library(management_setup):
|
||||
from test_management import execute
|
||||
from cbb_refresh_verify.operation_queue import native_channel
|
||||
request, adapter, _ = management_setup
|
||||
entered, resume = Event(), Event()
|
||||
def owner():
|
||||
with native_channel():
|
||||
entered.set()
|
||||
resume.wait(3)
|
||||
thread = Thread(target=owner)
|
||||
thread.start()
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
result = execute(request, adapter)
|
||||
assert result.safe_to_continue and not adapter.calls
|
||||
with locks.LibraryLock(request.library):
|
||||
pass
|
||||
finally:
|
||||
resume.set()
|
||||
thread.join(3)
|
||||
|
||||
|
||||
def test_only_explicit_repair_inspection_can_enter_while_worker_owns_writer_barrier(tmp_path):
|
||||
import json
|
||||
import os
|
||||
from cbb_refresh_verify.desktop_worker import worker_native_channel, run_native_worker
|
||||
from cbb_refresh_verify.operation_queue import native_channel
|
||||
from cbb_refresh_verify.native_repair_ui import repair_worker_main
|
||||
entered, resume = Event(), Event()
|
||||
def owner():
|
||||
with worker_native_channel():
|
||||
entered.set()
|
||||
resume.wait(3)
|
||||
thread = Thread(target=owner)
|
||||
thread.start()
|
||||
job = dict(root=str(tmp_path), project=str(tmp_path/'A.prj'), database=str(tmp_path/'database'),
|
||||
cancel_signal=str(tmp_path/'cancel'), supervisor_pid=os.getpid(), desktop='not-private')
|
||||
path = tmp_path/'repair-request.json'
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
with native_channel(inspection_only=True):
|
||||
pass
|
||||
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||
with native_channel():
|
||||
pass
|
||||
for mode in (False, 'true'):
|
||||
path.write_text(json.dumps({**job, 'inspection_only': mode}))
|
||||
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||
run_native_worker(repair_worker_main, path)
|
||||
path.write_text(json.dumps({**job, 'inspection_only': True}))
|
||||
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||
run_native_worker(lambda _: pytest.fail('arbitrary worker exempted'), path)
|
||||
assert run_native_worker(repair_worker_main, path) == 1
|
||||
result = json.loads((tmp_path/'repair-result.json').read_text())
|
||||
assert result['native_started'] is False
|
||||
assert 'REPAIR_PRIVATE_DESKTOP_REQUIRED' in result['detail']
|
||||
finally:
|
||||
resume.set()
|
||||
thread.join(3)
|
||||
|
||||
|
||||
def test_inspection_session_does_not_take_over_retained_writer_lease(tmp_path):
|
||||
import os
|
||||
import win32api
|
||||
from cbb_refresh_verify.desktop_worker import DesktopWorker
|
||||
library = tmp_path/'A/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
with locks.LibraryLock(library, safe_to_release=lambda: False) as lease:
|
||||
pass
|
||||
worker = object.__new__(DesktopWorker)
|
||||
worker.handle, worker.pid = win32api.GetCurrentProcess(), os.getpid()
|
||||
try:
|
||||
worker.bind_session(dict(operation_id='inspection', operation='inspect', inspection_only=True,
|
||||
library=str(library), project=str(tmp_path/'A.prj'), session_record_path=str(tmp_path/'session.json')))
|
||||
assert locks.has_retained_library(library)
|
||||
from cbb_refresh_verify.session_record import read_session_record
|
||||
record = read_session_record(tmp_path/'session.json', evidence_root=tmp_path)
|
||||
assert record['worker_lease_handle'] is None
|
||||
finally:
|
||||
with locks._guard:
|
||||
owner = locks._owners.pop(lease.key, None)
|
||||
if owner: owner['handle'].Close()
|
||||
|
||||
|
||||
def test_handoff_preserves_known_business_result_and_save_facts(tmp_path):
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, remember_result
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
context = BatchTaskContext(library=str(tmp_path/'A.lmc'))
|
||||
native_result = VerifyResult('FAIL', stderr='native failure after Save', safe_to_continue=False,
|
||||
write_outcome=dict(save_state='COMMITTED', close_state='UNKNOWN'))
|
||||
resume, done = Event(), Event()
|
||||
def finalize():
|
||||
remember_result(native_result)
|
||||
try:
|
||||
resume.wait(3)
|
||||
finally:
|
||||
done.set()
|
||||
try:
|
||||
with pytest.raises(TaskHandoff) as error:
|
||||
context.run(finalize, timeout_seconds=.05)
|
||||
assert error.value.result is native_result
|
||||
assert error.value.result.write_outcome['save_state'] == 'COMMITTED'
|
||||
assert error.value.result.status == 'FAIL'
|
||||
from cbb_refresh_verify.verify_runner import _handoff_verify_result
|
||||
returned = _handoff_verify_result(error.value)
|
||||
assert returned.status == 'FAIL' and returned.stderr == native_result.stderr
|
||||
assert returned.write_outcome == native_result.write_outcome and not returned.safe_to_continue
|
||||
error.value.result = VerifyResult('PASS', write_outcome=native_result.write_outcome)
|
||||
unfinished = _handoff_verify_result(error.value)
|
||||
assert unfinished.status == 'FAIL' and unfinished.library_flag == 'UNKNOWN'
|
||||
assert not unfinished.safe_to_continue
|
||||
finally:
|
||||
resume.set()
|
||||
assert done.wait(2)
|
||||
|
||||
|
||||
def test_registered_writer_owns_process_handle_after_callers_handle_closes(monkeypatch):
|
||||
import subprocess
|
||||
import sys
|
||||
from cbb_refresh_verify import desktop_worker
|
||||
monkeypatch.setattr(desktop_worker, '_automation_clients', [])
|
||||
process = subprocess.Popen([sys.executable, '-c', 'input()'], stdin=subprocess.PIPE, text=True)
|
||||
entered, done = Event(), Event()
|
||||
errors = []
|
||||
def run():
|
||||
try:
|
||||
with desktop_worker.worker_native_channel():
|
||||
desktop_worker.register_native_writer(process)
|
||||
process._handle.Close()
|
||||
entered.set()
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
finally:
|
||||
done.set()
|
||||
thread = Thread(target=run)
|
||||
thread.start()
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
assert not done.wait(.1), 'a closed caller handle released an unreturned writer'
|
||||
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||
desktop_worker.assert_native_writer_idle()
|
||||
finally:
|
||||
process.stdin.write('\n')
|
||||
process.stdin.flush()
|
||||
process.stdin.close()
|
||||
thread.join(3)
|
||||
# The duplicate's observed exit is authoritative; the original Popen
|
||||
# handle was deliberately invalidated, so do not poll it in __del__.
|
||||
process.returncode = 0
|
||||
assert done.is_set() and not errors
|
||||
@@ -0,0 +1,393 @@
|
||||
"""Real lifecycle regressions from the independent Task 2 review."""
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from threading import Event, Thread
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from test_management import setup as management_setup
|
||||
|
||||
|
||||
def wait_done(context):
|
||||
deadline = time.monotonic()+3
|
||||
while context.snapshot()['pending'] and time.monotonic()<deadline:
|
||||
time.sleep(.01)
|
||||
assert not context.snapshot()['pending']
|
||||
|
||||
|
||||
def test_management_result_survives_actual_late_release_read_handoff(management_setup, monkeypatch):
|
||||
from cbb_refresh_verify.management import run_management_batch
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, NativeQueue
|
||||
from cbb_refresh_verify.session_record import write_session_record
|
||||
request, adapter, _ = management_setup
|
||||
entered, resume = Event(), Event()
|
||||
session = []
|
||||
remove = adapter.remove
|
||||
def fail_remove(req, evidence):
|
||||
native = remove(req, evidence)
|
||||
path = evidence.parent/'session.json'
|
||||
write_session_record(path, dict(operation_id='failed-remove', library=str(req.library),
|
||||
block=req.name, processes=[]))
|
||||
session.append(path)
|
||||
return replace(native, success=False, safe_to_continue=False, detail='exact native removal failure')
|
||||
adapter.remove = fail_remove
|
||||
opening = Path.open
|
||||
def open_path(path, *args, **kwargs):
|
||||
if session and path == session[0] and args == ('rb',):
|
||||
entered.set()
|
||||
assert resume.wait(4)
|
||||
return opening(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'open', open_path)
|
||||
context = BatchTaskContext(library=str(request.library), targets=(request.name,))
|
||||
queue = NativeQueue()
|
||||
try:
|
||||
results = run_management_batch([request], adapter=adapter, idle_check=lambda *_: None,
|
||||
item_executor=lambda req, action: queue.run(action, context=context, timeout_seconds=1))
|
||||
assert entered.is_set()
|
||||
result = results[0]
|
||||
assert result.status == 'RECOVERY_REQUIRED'
|
||||
assert result.detail.startswith('exact native removal failure')
|
||||
assert result.evidence_path.is_file()
|
||||
assert result.change_report['status'] == 'UNCONFIRMED'
|
||||
assert result.release_proof['lease_state'] == 'PENDING'
|
||||
assert not result.safe_to_continue
|
||||
finally:
|
||||
resume.set()
|
||||
wait_done(context)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status,expected', [('UPLOAD_FAILED', 'UPLOAD_FAILED'), ('UPLOADED', 'RECOVERY_REQUIRED')])
|
||||
def test_management_batch_preserves_carried_handoff_result(management_setup, status, expected):
|
||||
from cbb_refresh_verify.management import ManagementResult, run_management_batch
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff
|
||||
request, _, _ = management_setup
|
||||
known = ManagementResult(request.operation, request.library, request.name, request.partition,
|
||||
request.source, request.auto_verify, 'complete', status, False, 'known native detail',
|
||||
request.evidence_dir/'checkpoint.json', change_report={'status': 'UNCONFIRMED'})
|
||||
context = BatchTaskContext(library=str(request.library))
|
||||
def executor(req, action):
|
||||
raise TaskHandoff(context, result=known)
|
||||
result = run_management_batch([request], item_executor=executor)[0]
|
||||
assert result.status == expected and result.detail == known.detail
|
||||
assert result.evidence_path == known.evidence_path and result.change_report == known.change_report
|
||||
assert result.release_proof['lease_state'] == 'PENDING' and not result.safe_to_continue
|
||||
|
||||
|
||||
def test_exited_verify_worker_outcome_read_is_bounded_and_releases_channel(tmp_path, monkeypatch):
|
||||
import json
|
||||
from test_verify_runner import fixture, request
|
||||
from cbb_refresh_verify.verify_runner import run_verify
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, native_channel
|
||||
fixture(tmp_path)
|
||||
entered, resume, completed, stop = Event(), Event(), Event(), Event()
|
||||
probes, results, errors = [], [], []
|
||||
class ExitedWorker:
|
||||
desktop = None
|
||||
returncode = 0
|
||||
def __init__(self, command, *args, **kwargs):
|
||||
root = Path(command[-1]).parent
|
||||
(root/'outcome.json').write_text(json.dumps(dict(status='PASS')))
|
||||
def poll(self): return 0
|
||||
def close(self): pass
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', ExitedWorker)
|
||||
# The fake worker has no native clients; cleanup probes are covered independently.
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner._cleanup_session_processes',
|
||||
lambda *args, **kwargs: {'safe_to_continue': True, 'remaining_pids': []})
|
||||
original = Path.read_text
|
||||
def read(path, *args, **kwargs):
|
||||
if path.name == 'outcome.json':
|
||||
entered.set()
|
||||
assert resume.wait(4)
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'read_text', read)
|
||||
context = BatchTaskContext(library=str(tmp_path/'lib.lmc'))
|
||||
def run():
|
||||
try:
|
||||
results.append(run_verify(request(tmp_path), stop=stop, context=context,
|
||||
admission_timeout_seconds=1, port_check=lambda: (True, ''),
|
||||
flag_reader=lambda *a: probes.append('late native status read')))
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
finally:
|
||||
completed.set()
|
||||
thread = Thread(target=run)
|
||||
thread.start()
|
||||
try:
|
||||
assert entered.wait(3), (results, errors)
|
||||
stop.set()
|
||||
assert completed.wait(1.5), 'exited worker metadata retained native phase'
|
||||
with native_channel():
|
||||
pass
|
||||
assert not errors and not results[0].safe_to_continue
|
||||
resume.set()
|
||||
wait_done(context)
|
||||
assert probes == []
|
||||
finally:
|
||||
resume.set()
|
||||
thread.join(4)
|
||||
wait_done(context)
|
||||
|
||||
|
||||
def test_repair_session_write_before_gate_is_bounded_without_host_channel(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.native_repair import run_native_repair, RepairTarget
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, native_channel
|
||||
from cbb_refresh_verify import session_record
|
||||
entered, resume, completed = Event(), Event(), Event()
|
||||
errors = []
|
||||
class GatedWorker:
|
||||
returncode = 0
|
||||
def __init__(self, command, *args, **kwargs): pass
|
||||
def bind_cancellation(self, path): pass
|
||||
def bind_session(self, job):
|
||||
session_record.write_session_record(Path(job['session_record_path']),
|
||||
{'operation_id': job['operation_id']})
|
||||
def poll(self): return 0
|
||||
def close(self): pass
|
||||
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', GatedWorker)
|
||||
original = Path.open
|
||||
def opening(path, *args, **kwargs):
|
||||
if path.name.startswith('session.json.') and path.suffix == '.pending':
|
||||
entered.set()
|
||||
assert resume.wait(4)
|
||||
return original(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'open', opening)
|
||||
context = BatchTaskContext(library=str(tmp_path/'A.lmc'))
|
||||
def run():
|
||||
try:
|
||||
context.run(lambda: run_native_repair(RepairTarget(tmp_path/'A.prj', tmp_path/'database'),
|
||||
tmp_path/'evidence'), timeout_seconds=.1)
|
||||
except Exception as error:
|
||||
errors.append(error)
|
||||
finally:
|
||||
completed.set()
|
||||
thread = Thread(target=run)
|
||||
thread.start()
|
||||
try:
|
||||
assert entered.wait(2)
|
||||
assert completed.wait(.8), 'Repair pre-gate journal retained native phase'
|
||||
with native_channel():
|
||||
pass
|
||||
assert len(errors) == 1 and isinstance(errors[0], TaskHandoff)
|
||||
resume.set()
|
||||
wait_done(context)
|
||||
assert not (tmp_path/'evidence/start-repair.signal').exists()
|
||||
finally:
|
||||
resume.set()
|
||||
thread.join(4)
|
||||
wait_done(context)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('control', ['save', 'cancel'])
|
||||
def test_handed_off_worker_accepts_exact_controls_but_excludes_new_writers(tmp_path, monkeypatch, control):
|
||||
import subprocess
|
||||
import sys
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff, native_channel, hold_native_handoff
|
||||
from cbb_refresh_verify import residual_sessions as sessions
|
||||
from cbb_refresh_verify.session_record import write_session_record
|
||||
library = tmp_path/'library/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
context = BatchTaskContext(library=str(library))
|
||||
child = []
|
||||
ready, answered = Event(), Event()
|
||||
errors = []
|
||||
script = ('from cbb_refresh_verify.desktop_worker import worker_native_channel\n'
|
||||
'with worker_native_channel():\n print("ready",flush=True)\n input()\n')
|
||||
def action():
|
||||
with native_channel():
|
||||
process = subprocess.Popen([sys.executable, '-c', script], stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, text=True)
|
||||
child.append(process)
|
||||
assert process.stdout.readline().strip() == 'ready'
|
||||
record = tmp_path/'session.json'
|
||||
write_session_record(record, dict(operation_id=context.operation_id, library=str(library)))
|
||||
ready.set()
|
||||
hold_native_handoff(process, record)
|
||||
controller = None
|
||||
try:
|
||||
with pytest.raises(TaskHandoff):
|
||||
context.run(action)
|
||||
assert ready.is_set() and child[0].poll() is None
|
||||
row = dict(pid=child[0].pid, name='iCDBProjectBackup.exe', created='exact-child',
|
||||
executable='C:/Mentor/iCDBProjectBackup.exe', command=f'backup -p "{library.parent}/A.prj"',
|
||||
scope_confirmed=True, cancel_prompt={'title': 'captured'})
|
||||
def answer(observed, *args, **kwargs):
|
||||
assert observed['pid'] == child[0].pid
|
||||
child[0].communicate('\n', timeout=3)
|
||||
answered.set()
|
||||
return {'release_status': 'RELEASED'}
|
||||
if control == 'save':
|
||||
monkeypatch.setattr(sessions, '_answer_save_question', answer)
|
||||
command = lambda: sessions.answer_save_question(row, 6)
|
||||
else:
|
||||
monkeypatch.setattr(sessions, '_request_native_cancel', answer)
|
||||
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [row] if child[0].poll() is None else [])
|
||||
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
|
||||
# Keep this real writer-barrier/control test independent of file-probe startup latency.
|
||||
monkeypatch.setattr(sessions, '_finish_library_release',
|
||||
lambda *args, **kwargs: {'status': 'RELEASE_CONFIRMED', 'library': str(library)})
|
||||
command = lambda: sessions.release_residual_sessions(dict(library=str(library), sessions=[row]),
|
||||
tmp_path/'controls', cancel_native=True)
|
||||
def control_call():
|
||||
try: command()
|
||||
except Exception as error: errors.append(error)
|
||||
# New writes still fail, but the exact corrective control can progress.
|
||||
with pytest.raises(RuntimeError):
|
||||
with native_channel():
|
||||
pytest.fail('overlapping new writer admitted')
|
||||
controller = Thread(target=control_call)
|
||||
controller.start()
|
||||
assert answered.wait(1), errors
|
||||
controller.join(5)
|
||||
assert not controller.is_alive() and not errors
|
||||
wait_done(context)
|
||||
with native_channel():
|
||||
pass
|
||||
finally:
|
||||
if child and child[0].poll() is None:
|
||||
child[0].communicate('\n', timeout=3)
|
||||
if controller is not None: controller.join(5)
|
||||
wait_done(context)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode', ['pending', 'acknowledged', 'assignment-failed', 'cancel-after-registration'])
|
||||
def test_real_async_add_unwind_and_parent_exit_keep_only_pending_writer_scope(tmp_path, mode):
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import win32api, win32con, win32event
|
||||
from test_management import project
|
||||
from cbb_refresh_verify import library_lock as locks
|
||||
from cbb_refresh_verify.operation_queue import native_channel
|
||||
library = tmp_path/'library/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
source = project(tmp_path/'source', name='Block')
|
||||
for path in (source, source.parent/'PCB/pcb.prj'):
|
||||
with path.open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'KEY CentralLibrary "{library}"\n')
|
||||
root = tmp_path/'native-add'
|
||||
root.mkdir()
|
||||
helper = Path(__file__).parent/'support/async_add_lifecycle_fixture.py'
|
||||
parent_script = '''import sys,json,time,subprocess,os,win32api,win32con
|
||||
from pathlib import Path
|
||||
from cbb_refresh_verify.library_lock import LibraryLock,duplicate_worker_lease
|
||||
from cbb_refresh_verify.session_record import register_worker_session,process_identity
|
||||
library,source,root,helper=map(Path,sys.argv[1:5])
|
||||
job=dict(operation='probe_create_add',library=str(library),source=str(source),root=str(root),name='Block',
|
||||
operation_id='actual-add',session_record_path=str(root/'session.json'),start_gate=str(root/'gate'),
|
||||
cancel_signal=str(root/'cancel'),supervisor_pid=os.getpid(),supervisor_identity=process_identity(os.getpid()),
|
||||
timeout_seconds=.3,test_mode=sys.argv[5])
|
||||
(root/'request.json').write_text(json.dumps(job))
|
||||
with LibraryLock(library,checkpoint=False):
|
||||
with (root/'worker-output.txt').open('w') as output:
|
||||
worker=subprocess.Popen([sys.executable,str(helper),str(root/'request.json')],stdout=output,stderr=output)
|
||||
(root.parent/'worker-pid').write_text(str(worker.pid))
|
||||
handle=win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE,False,worker.pid)
|
||||
try: inherited=duplicate_worker_lease(library,handle)
|
||||
finally: handle.Close()
|
||||
register_worker_session(worker,{**job,'worker_lease_handle':inherited})
|
||||
(root/'gate').touch()
|
||||
deadline=time.monotonic()+12
|
||||
while not (root.parent/'add-unwound').exists() and time.monotonic()<deadline: time.sleep(.02)
|
||||
assert (root.parent/'add-unwound').exists()
|
||||
'''
|
||||
parent = subprocess.Popen([sys.executable, '-c', parent_script, str(library), str(source), str(root), str(helper), mode])
|
||||
handles = []
|
||||
def open_pid_file(name):
|
||||
pid = int((tmp_path/name).read_text())
|
||||
handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, pid)
|
||||
handles.append(handle)
|
||||
return handle
|
||||
try:
|
||||
code = parent.wait(timeout=15)
|
||||
assert code == 0, (root/'worker-output.txt').read_text(errors='replace')
|
||||
if mode in ('assignment-failed', 'cancel-after-registration'):
|
||||
assert not (tmp_path/'add-dispatched').exists()
|
||||
detail = 'exact native job admission denied' if mode == 'assignment-failed' else 'NATIVE_ADD_CANCELLED'
|
||||
assert detail in (root/'result.json').read_text()
|
||||
with native_channel(): pass
|
||||
with locks.LibraryLock(library, checkpoint=False): pass
|
||||
return
|
||||
assert (tmp_path/'add-dispatched').exists()
|
||||
lm = open_pid_file('lm-pid')
|
||||
if mode == 'pending':
|
||||
worker = open_pid_file('worker-pid')
|
||||
from cbb_refresh_verify.session_record import read_session_record
|
||||
journal = read_session_record(root/'worker-state.json', evidence_root=root)
|
||||
identity = next(p for p in journal['processes'] if p['pid'] == int((tmp_path/'lm-pid').read_text()))
|
||||
assert identity['created_handle'] and identity['image'] and identity['owner_sid']
|
||||
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||
with native_channel(): pass
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library, checkpoint=False): pass
|
||||
(tmp_path/'lm-exit').touch()
|
||||
assert win32event.WaitForSingleObject(lm, 3000) == win32con.WAIT_OBJECT_0
|
||||
assert win32event.WaitForSingleObject(worker, 0) != win32con.WAIT_OBJECT_0
|
||||
deadline = time.monotonic()+2
|
||||
descendant = int((tmp_path/'descendant-pid').read_text())
|
||||
while time.monotonic()<deadline:
|
||||
journal = read_session_record(root/'worker-state.json', evidence_root=root)
|
||||
if any(p['pid'] == descendant for p in journal['processes']): break
|
||||
time.sleep(.02)
|
||||
assert any(p['pid'] == descendant and p['created_handle'] for p in journal['processes'])
|
||||
with pytest.raises(RuntimeError, match='NATIVE_WRITER_ACTIVE'):
|
||||
with native_channel(): pass
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
with locks.LibraryLock(library, checkpoint=False): pass
|
||||
(tmp_path/'native-done').touch()
|
||||
assert win32event.WaitForSingleObject(worker, 5000) == win32con.WAIT_OBJECT_0
|
||||
else:
|
||||
deadline = time.monotonic()+3
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
with native_channel(): pass
|
||||
break
|
||||
except RuntimeError:
|
||||
time.sleep(.02)
|
||||
with native_channel(): pass
|
||||
assert win32event.WaitForSingleObject(lm, 0) != win32con.WAIT_OBJECT_0, 'idle LM was killed'
|
||||
with locks.LibraryLock(library, checkpoint=False): pass
|
||||
finally:
|
||||
(tmp_path/'lm-exit').touch()
|
||||
(tmp_path/'native-done').touch()
|
||||
for handle in handles:
|
||||
win32event.WaitForSingleObject(handle, 5000)
|
||||
handle.Close()
|
||||
if (tmp_path/'worker-pid').exists():
|
||||
try:
|
||||
worker = open_pid_file('worker-pid')
|
||||
except Exception as error:
|
||||
if getattr(error, 'winerror', None) != 87: raise
|
||||
else:
|
||||
assert win32event.WaitForSingleObject(worker, 5000) == win32con.WAIT_OBJECT_0
|
||||
worker.Close()
|
||||
parent.wait(timeout=15)
|
||||
|
||||
|
||||
def test_add_descendant_snapshot_cannot_journal_an_unrelated_reused_pid(tmp_path, monkeypatch):
|
||||
import subprocess
|
||||
import sys
|
||||
from cbb_refresh_verify import desktop_worker
|
||||
from cbb_refresh_verify.session_record import write_session_record, read_session_record
|
||||
monkeypatch.setattr(desktop_worker, '_automation_clients', [])
|
||||
owner = subprocess.Popen([sys.executable, '-c', 'input()'], stdin=subprocess.PIPE, text=True)
|
||||
foreign = subprocess.Popen([sys.executable, '-c', 'input()'], stdin=subprocess.PIPE, text=True)
|
||||
operation = None
|
||||
query = desktop_worker.win32job.QueryInformationJobObject
|
||||
try:
|
||||
job = dict(operation_id='descendant-identity', session_record_path=str(tmp_path/'session.json'))
|
||||
write_session_record(tmp_path/'worker-state.json', dict(operation_id=job['operation_id'], processes=[]))
|
||||
operation = desktop_worker.register_pending_native_operation(job, {owner.pid})
|
||||
monkeypatch.setattr(desktop_worker.win32job, 'QueryInformationJobObject',
|
||||
lambda *args: [owner.pid, foreign.pid])
|
||||
assert operation.poll() is None
|
||||
journal = read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)
|
||||
assert not any(p['pid'] == foreign.pid for p in journal['processes'])
|
||||
finally:
|
||||
owner.communicate('\n', timeout=3)
|
||||
foreign.communicate('\n', timeout=3)
|
||||
monkeypatch.setattr(desktop_worker.win32job, 'QueryInformationJobObject', query)
|
||||
if operation is not None:
|
||||
assert operation.poll() == 0
|
||||
@@ -0,0 +1,651 @@
|
||||
"""Task-bound UI delivery and filesystem/native catalog separation."""
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from PySide6.QtCore import Qt
|
||||
|
||||
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
from cbb_refresh_verify.verify_runner import VerifyResult
|
||||
|
||||
|
||||
def window_for(qtbot, tmp_path, monkeypatch, *, reader=None, **kwargs):
|
||||
monkeypatch.setattr('cbb_refresh_verify.ui.main_window.preflight_skip_reason', lambda *_: None)
|
||||
def lease(path):
|
||||
return SimpleNamespace(mentor_path=path, display_path=path, drive='', remote_root='',
|
||||
close=lambda: None, retain_for_recovery=lambda: None)
|
||||
window = MainWindow(reader=reader or (lambda _: LibraryReadResult((CbbRecord('A', 'LP'),))),
|
||||
path_lease_factory=lease, data_root=tmp_path, **kwargs)
|
||||
qtbot.addWidget(window)
|
||||
window.show()
|
||||
return window
|
||||
|
||||
|
||||
def load(window, qtbot, path='a.lmc'):
|
||||
window.lmc_edit.setText(path)
|
||||
window.load_library()
|
||||
qtbot.waitUntil(lambda: not window.busy)
|
||||
|
||||
|
||||
def test_first_read_can_cancel_and_keeps_navigation_live(qtbot, tmp_path, monkeypatch):
|
||||
entered, release = Event(), Event()
|
||||
def reader(_):
|
||||
entered.set(); release.wait(5)
|
||||
return LibraryReadResult((CbbRecord('Late', 'LP'),))
|
||||
window = window_for(qtbot, tmp_path, monkeypatch, reader=reader)
|
||||
window.lmc_edit.setText('a.lmc'); window.load_library()
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
try:
|
||||
assert window.stop_button.isEnabled()
|
||||
assert window.lmc_edit.isEnabled() and window.load_button.isEnabled()
|
||||
window.stop_button.click()
|
||||
qtbot.waitUntil(lambda: not window.busy, timeout=2000)
|
||||
assert window.loaded_path is None
|
||||
finally:
|
||||
release.set(); window.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_failed_read_preserves_stale_table_without_write_eligibility(qtbot, tmp_path, monkeypatch):
|
||||
window = window_for(qtbot, tmp_path, monkeypatch)
|
||||
load(window, qtbot)
|
||||
window.reader = lambda _: LibraryReadResult((), 'INPUT_EMPTY: 空文件')
|
||||
load(window, qtbot, 'bad.lmc')
|
||||
assert window.cbb_table.rowCount() == 1
|
||||
assert window.loaded_path is None
|
||||
assert not window.batch_button.isEnabled()
|
||||
assert '失效' in window.library_notice.text()
|
||||
|
||||
|
||||
def test_successful_path_is_local_and_only_prefilled(qtbot, tmp_path, monkeypatch):
|
||||
window = window_for(qtbot, tmp_path, monkeypatch)
|
||||
load(window, qtbot, 'remember.lmc')
|
||||
calls = []
|
||||
other = window_for(qtbot, tmp_path, monkeypatch, reader=lambda p: calls.append(p))
|
||||
assert other.lmc_edit.text() == 'remember.lmc'
|
||||
assert not calls and other.loaded_path is None
|
||||
isolated = window_for(qtbot, tmp_path/'other', monkeypatch)
|
||||
assert isolated.lmc_edit.text() == ''
|
||||
|
||||
|
||||
def test_result_nonmodal_and_safe_cancel_evidence_and_logs(qtbot, tmp_path, monkeypatch):
|
||||
window = window_for(qtbot, tmp_path, monkeypatch)
|
||||
load(window, qtbot)
|
||||
evidence = tmp_path/'evidence'/'result.json'
|
||||
evidence.parent.mkdir(); evidence.write_text('{}')
|
||||
window._batch_done(([VerifyResult('CANCELLED', safe_to_continue=True, evidence_path=evidence)], None))
|
||||
assert window.summary.windowModality() == Qt.NonModal
|
||||
assert window.recovery_button.isEnabled()
|
||||
opened = []
|
||||
monkeypatch.setattr('os.startfile', opened.append)
|
||||
window.open_logs()
|
||||
assert Path(opened[-1]) == tmp_path/'logs'
|
||||
|
||||
|
||||
def test_read_does_not_wait_forever_on_old_retained_cache(qtbot, tmp_path, monkeypatch):
|
||||
calls = []
|
||||
monkeypatch.setattr('cbb_refresh_verify.session_record.library_available', lambda _: False)
|
||||
monkeypatch.setattr('cbb_refresh_verify.session_record.library_wait_reason', lambda _: 'old retained')
|
||||
window = window_for(qtbot, tmp_path, monkeypatch, reader=lambda p: (
|
||||
calls.append(p) or LibraryReadResult((CbbRecord('A', 'LP'),))))
|
||||
window.lmc_edit.setText('a.lmc'); window.load_library()
|
||||
try:
|
||||
qtbot.waitUntil(lambda: bool(calls), timeout=1500)
|
||||
finally:
|
||||
window.request_stop(); window.pool.waitForDone(3000)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('filename,content,category', [
|
||||
('wrong.txt', b'library', 'INPUT_SUFFIX'), ('empty.lmc', b'', 'INPUT_EMPTY')])
|
||||
def test_fast_read_rejects_invalid_input(tmp_path, filename, content, category):
|
||||
from cbb_refresh_verify.library_reader import read_library_fast
|
||||
path = tmp_path/filename; path.write_bytes(content)
|
||||
(tmp_path/'ReusableBlocksLP').mkdir()
|
||||
result = read_library_fast(path)
|
||||
assert result.error and category in result.error
|
||||
|
||||
|
||||
def test_fast_read_distinguishes_unknown_native_count(tmp_path):
|
||||
from cbb_refresh_verify.library_reader import read_library_fast
|
||||
path = tmp_path/'lib.lmc'; path.write_bytes(b'not-a-native-validation')
|
||||
(tmp_path/'ReusableBlocksLP'/'Orphan').mkdir(parents=True)
|
||||
result = read_library_fast(path)
|
||||
assert result.directory_count == 1 and result.native_count is None
|
||||
assert result.records[0].catalog_source == 'directory'
|
||||
assert result.records[0].status == 'UNKNOWN'
|
||||
|
||||
|
||||
def test_late_read_a_b_a_cannot_replace_newer_snapshot(qtbot, tmp_path, monkeypatch):
|
||||
entered, release = Event(), Event()
|
||||
count = 0
|
||||
def reader(path):
|
||||
nonlocal count
|
||||
count += 1
|
||||
if count == 1:
|
||||
entered.set(); release.wait(5)
|
||||
return LibraryReadResult((CbbRecord('Old', 'LP'),))
|
||||
return LibraryReadResult((CbbRecord('New', 'LP'),))
|
||||
window = window_for(qtbot, tmp_path, monkeypatch, reader=reader)
|
||||
window.lmc_edit.setText('a.lmc'); window.load_library()
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
try:
|
||||
window.lmc_edit.setText('b.lmc'); window.lmc_edit.setText('a.lmc')
|
||||
window.load_library()
|
||||
qtbot.waitUntil(lambda: window.loaded_path == 'a.lmc', timeout=2000)
|
||||
release.set(); qtbot.wait(100)
|
||||
assert tuple(window._records_by_name) == ('New',)
|
||||
finally:
|
||||
release.set(); window.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_batch_result_cannot_modify_reloaded_library_and_current_cancel_displays(qtbot, tmp_path, monkeypatch):
|
||||
entered, release = Event(), Event()
|
||||
def verify(_):
|
||||
entered.set(); release.wait(5)
|
||||
return VerifyResult('CANCELLED', stderr='old A cancelled')
|
||||
window = window_for(qtbot, tmp_path, monkeypatch, verifier=verify,
|
||||
status_refresher=lambda names, _: {name:'PENDING' for name in names})
|
||||
load(window, qtbot)
|
||||
try:
|
||||
window._run(['A']); qtbot.waitUntil(entered.is_set)
|
||||
load(window, qtbot, 'b.lmc'); load(window, qtbot, 'a.lmc')
|
||||
release.set(); qtbot.wait(200)
|
||||
assert 'old A cancelled' not in window.status_label.text()
|
||||
assert window.cbb_table.item(0,3).text() == '未检查'
|
||||
window._run(['A']); qtbot.waitUntil(lambda:not window.busy)
|
||||
assert '取消' in window.output.toPlainText() or 'CANCELLED' in window.output.toPlainText()
|
||||
finally:
|
||||
release.set(); window.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_catalog_union_keeps_registration_source_and_counts(qtbot, tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||
entered, release = Event(), Event()
|
||||
def catalog(path, evidence):
|
||||
entered.set(); release.wait(5)
|
||||
return Catalog(path,1,(CatalogEntry('A','Logical-Physical'),CatalogEntry('NativeOnly','Logical-Physical')))
|
||||
window = window_for(qtbot,tmp_path,monkeypatch, reader=lambda _:LibraryReadResult(
|
||||
(CbbRecord('A','LP',catalog_source='directory'), CbbRecord('Orphan','LP',catalog_source='directory')),
|
||||
directory_count=2), catalog_reader=catalog, status_refresher=lambda names,_:{name:'READY' for name in names})
|
||||
try:
|
||||
load(window,qtbot)
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
assert '未知' in window.counts_label.text()
|
||||
assert not window.batch_button.isEnabled()
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name)
|
||||
assert window._records_by_name['Orphan'].catalog_source == 'directory_only'
|
||||
assert window._records_by_name['NativeOnly'].catalog_source == 'native_only'
|
||||
assert window._records_by_name['A'].status_source == 'authoritative'
|
||||
assert '原生 2' in window.counts_label.text()
|
||||
finally:
|
||||
release.set(); window.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_execution_rechecks_ready_when_directory_snapshot_was_unknown(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.management import Catalog, CatalogEntry
|
||||
calls=[]
|
||||
window=window_for(qtbot,tmp_path,monkeypatch, verifier=lambda r:(calls.append(r.block_name) or VerifyResult('PASS')),
|
||||
catalog_reader=lambda p,e:Catalog(p,1,(CatalogEntry('A','Logical-Physical'),)),
|
||||
status_refresher=lambda names,_:{name:'READY' for name in names})
|
||||
load(window,qtbot)
|
||||
window._run(['A'])
|
||||
qtbot.waitUntil(lambda:not window.busy)
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_active_a_choice_defaults_after_switch_to_b(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.pcb_open_consent import OpenChoice
|
||||
from cbb_refresh_verify.ui import timed_prompt
|
||||
monkeypatch.setattr(timed_prompt,'DEFAULT_TIMEOUT_MS',80)
|
||||
window=window_for(qtbot,tmp_path,monkeypatch)
|
||||
load(window,qtbot)
|
||||
job=window._new_job('verify',targets=('A',))
|
||||
load(window,qtbot,'b.lmc')
|
||||
choice=OpenChoice('A',Path('a.lmc'))
|
||||
window._emit_job(job,'version_choice',choice)
|
||||
qtbot.waitUntil(lambda:choice.decision is not None)
|
||||
assert choice.decision == 'skip'
|
||||
window._finish_job(job)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('mode',['versions','repair'])
|
||||
def test_native_session_outlives_launcher_and_cleans_up_after_a_b_a(qtbot,tmp_path,monkeypatch,mode):
|
||||
import json
|
||||
exited=Event(); calls=[]
|
||||
job_file=tmp_path/'native'/'job.json'; job_file.parent.mkdir(); job_file.write_text('{}')
|
||||
def launcher(request, **options):
|
||||
calls.append(options.get('mode','versions'))
|
||||
return SimpleNamespace(process=SimpleNamespace(poll=lambda:0 if exited.is_set() else None),
|
||||
job=job_file,library=request.lmc_file,block=request.block_name,path_lease=None,operation_id='native-1')
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,native_backup_launcher=launcher,
|
||||
status_refresher=lambda names,_:{name:'PENDING' for name in names})
|
||||
load(window,qtbot); window.cbb_table.setCurrentCell(0,0)
|
||||
button=window.native_backup_button if mode=='versions' else window.native_repair_button
|
||||
button.click(); qtbot.waitUntil(lambda:window._native_backup_session is not None)
|
||||
qtbot.waitUntil(lambda:not window.busy)
|
||||
assert calls == [mode]
|
||||
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
|
||||
message=window.status_label.text()
|
||||
job_file.with_name('result.json').write_text(json.dumps(dict(operation_id='native-1',
|
||||
library='a.lmc',block='A',safe_to_continue=True,status='CLOSED')))
|
||||
exited.set(); window._poll_native_backup()
|
||||
qtbot.waitUntil(lambda:window._native_backup_session is None)
|
||||
assert window.status_label.text() == message
|
||||
window.cbb_table.setCurrentCell(0,0)
|
||||
assert window.native_backup_button.isEnabled()
|
||||
|
||||
|
||||
def test_close_during_first_read_finishes_and_late_emit_is_harmless(qtbot,tmp_path,monkeypatch):
|
||||
entered, release=Event(),Event()
|
||||
def reader(_):
|
||||
entered.set(); release.wait(5)
|
||||
return LibraryReadResult((CbbRecord('Late','LP'),))
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,reader=reader)
|
||||
window.lmc_edit.setText('a.lmc'); window.load_library(); qtbot.waitUntil(entered.is_set)
|
||||
job=window._current_job
|
||||
try:
|
||||
window.close()
|
||||
qtbot.waitUntil(lambda:not window.isVisible(),timeout=2000)
|
||||
window._emit_job(job,'event',{'stage':'late'})
|
||||
finally: release.set()
|
||||
|
||||
|
||||
def test_input_lock_directory_and_permissions_are_classified(tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.library_reader import read_library_fast
|
||||
path=tmp_path/'lib.lmc'; path.write_bytes(b'library')
|
||||
(tmp_path/'ReusableBlocksLP').mkdir(); path.with_suffix('.lock').mkdir()
|
||||
assert 'INPUT_LOCK_DIRECTORY' in read_library_fast(path).error
|
||||
original=Path.open
|
||||
def denied(self,*a,**k):
|
||||
if self == path: raise PermissionError('denied')
|
||||
return original(self,*a,**k)
|
||||
monkeypatch.setattr(Path,'open',denied)
|
||||
assert 'INPUT_PERMISSION' in read_library_fast(path).error
|
||||
|
||||
|
||||
def test_management_completion_after_switch_preserves_current_table(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.management import Capability, ManagementResult
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
|
||||
entered,release=Event(),Event()
|
||||
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
|
||||
load(window,qtbot); window.select_visible_button.click(); window.manage_cbb('remove')
|
||||
dialog=window.management_dialog
|
||||
def runner(requests,**kwargs):
|
||||
entered.set(); release.wait(5)
|
||||
r=requests[0]
|
||||
return [ManagementResult('remove',r.library,r.name,r.partition,None,False,'complete','REMOVED',True,'old remove')]
|
||||
dialog.runner=runner
|
||||
try:
|
||||
dialog.execute_button.click(); qtbot.waitUntil(entered.is_set)
|
||||
assert dialog.windowModality()==Qt.NonModal
|
||||
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
|
||||
message=window.status_label.text()
|
||||
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
|
||||
dialog.close(); qtbot.wait(100)
|
||||
assert window.status_label.text()==message
|
||||
assert window.cbb_table.item(0,3).text()=='未检查'
|
||||
finally: release.set(); dialog.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_recovery_dialog_binds_original_library_and_is_nonmodal(qtbot,tmp_path,monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
|
||||
entered,release=Event(),Event(); calls=[]
|
||||
window=window_for(qtbot,tmp_path,monkeypatch)
|
||||
load(window,qtbot); window.restore_backup(); dialog=window.backup_dialog
|
||||
source=tmp_path/'A.prj'; source.write_text('project')
|
||||
dialog.source_edit.setText(str(source))
|
||||
def recover(request,source,**kwargs):
|
||||
calls.append(request.lmc_file); entered.set(); release.wait(5)
|
||||
return VerifyResult('FAIL',stderr='old recovery',safe_to_continue=True)
|
||||
dialog.recoverer=recover
|
||||
try:
|
||||
assert dialog.windowModality()==Qt.NonModal
|
||||
load(window,qtbot,'b.lmc')
|
||||
dialog.restore_button.click(); qtbot.waitUntil(entered.is_set)
|
||||
message=window.status_label.text()
|
||||
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
|
||||
assert calls == [Path('a.lmc')]
|
||||
assert window.status_label.text()==message
|
||||
finally: release.set(); dialog.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_icdb_does_not_wait_on_stale_retained_and_late_result_is_scoped(qtbot,tmp_path,monkeypatch):
|
||||
entered,release=Event(),Event()
|
||||
monkeypatch.setattr('cbb_refresh_verify.session_record.library_available',lambda _:False)
|
||||
monkeypatch.setattr('cbb_refresh_verify.session_record.library_wait_reason',lambda _:'historical')
|
||||
def verify(_):
|
||||
entered.set(); release.wait(5)
|
||||
return VerifyResult('CHECKED',safe_to_continue=True)
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,verifier=verify)
|
||||
load(window,qtbot); window._start_icdb_check(['A'])
|
||||
try:
|
||||
qtbot.waitUntil(entered.is_set,timeout=1500)
|
||||
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
|
||||
message=window.status_label.text()
|
||||
release.set(); qtbot.waitUntil(lambda:not window._icdb_active())
|
||||
assert window.status_label.text()==message
|
||||
assert window.cbb_table.item(0,3).text()=='未检查'
|
||||
finally:
|
||||
release.set(); window._stop_icdb_check(); window.icdb_task.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_default_reentrant_tick_commits_one_choice(qtbot,monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from cbb_refresh_verify.ui.timed_prompt import arm_default
|
||||
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',50)
|
||||
box=QMessageBox(); qtbot.addWidget(box); box.setStandardButtons(QMessageBox.Yes|QMessageBox.No)
|
||||
choices=[]
|
||||
def clicked(button):
|
||||
choices.append(button)
|
||||
if len(choices)==1: countdown.tick()
|
||||
box.buttonClicked.connect(clicked)
|
||||
countdown=arm_default(box,box.button(QMessageBox.Yes))
|
||||
box.show(); qtbot.wait(120)
|
||||
assert len(choices) == 1
|
||||
|
||||
|
||||
def test_release_dialog_is_available_during_task_and_stale_receipt_keeps_view(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||
monkeypatch.setattr(ResidualReleaseDialog,'refresh',lambda self:None)
|
||||
released=[]
|
||||
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases',lambda proof,**kw:released.append(proof))
|
||||
window=window_for(qtbot,tmp_path,monkeypatch)
|
||||
load(window,qtbot); window.busy=True; window._update()
|
||||
window.release_library_button.click()
|
||||
dialog=window.release_dialog
|
||||
assert dialog.isVisible() and dialog.windowModality()==Qt.NonModal
|
||||
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc'); message=window.status_label.text()
|
||||
dialog.released.emit(dict(status='RELEASE_CONFIRMED',library='a.lmc',evidence_path='proof.json'))
|
||||
qtbot.waitUntil(lambda:bool(released))
|
||||
dialog.close(); qtbot.wait(100)
|
||||
assert window.status_label.text()==message
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind',['read','lease'])
|
||||
def test_source_process_exits_after_stalled_bookkeeping(tmp_path,kind):
|
||||
import subprocess,sys,os,time
|
||||
script=tmp_path/'close_app.py'
|
||||
script.write_text('''from threading import Event
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from PySide6.QtWidgets import QApplication
|
||||
from PySide6.QtCore import QTimer
|
||||
from cbb_refresh_verify.ui.main_window import MainWindow
|
||||
app=QApplication([])
|
||||
MainWindow._show_unfinished_management=lambda self:None
|
||||
block=Event()
|
||||
w=MainWindow(reader=lambda _:block.wait(90),data_root=Path(sys.argv[2]))
|
||||
w.show()
|
||||
if sys.argv[1]=='read':
|
||||
w.lmc_edit.setText('stalled.lmc'); w.load_library()
|
||||
else: w._lease_action(lambda:block.wait(90))
|
||||
QTimer.singleShot(150,w.close)
|
||||
app.exec()
|
||||
print('APP_RETURNED',flush=True)
|
||||
''',encoding='utf-8')
|
||||
env=dict(os.environ,QT_QPA_PLATFORM='offscreen')
|
||||
started=__import__('time').monotonic()
|
||||
process=subprocess.Popen([sys.executable,'-X','utf8',str(script),kind,str(tmp_path/'data')],
|
||||
stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,encoding='utf-8',env=env)
|
||||
try:
|
||||
stdout,stderr=process.communicate(timeout=8)
|
||||
assert process.returncode==0,stderr
|
||||
assert 'APP_RETURNED' in stdout
|
||||
assert time.monotonic()-started < 8
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill(); process.communicate()
|
||||
|
||||
|
||||
def test_old_library_mapping_cleanup_does_not_keep_new_library_busy(qtbot,tmp_path,monkeypatch):
|
||||
entered,release=Event(),Event(); calls=[]
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,verifier=lambda r:(calls.append(r.lmc_file) or VerifyResult('PASS')),
|
||||
status_refresher=lambda names,_:{name:'PENDING' for name in names})
|
||||
load(window,qtbot)
|
||||
def cleanup(): entered.set(); release.wait(5)
|
||||
window._lease_action(cleanup,hold_busy=True)
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
try:
|
||||
window.lmc_edit.setText('b.lmc'); window.load_library()
|
||||
qtbot.waitUntil(lambda:window.loaded_path=='b.lmc' and not window.busy,timeout=1000)
|
||||
window._run(['A'])
|
||||
qtbot.waitUntil(lambda:bool(calls),timeout=1000)
|
||||
assert calls == [Path('b.lmc')]
|
||||
finally:
|
||||
release.set(); qtbot.waitUntil(lambda:window._lease_pending==0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind',['recovery','management'])
|
||||
def test_dialog_handoff_is_not_claimed_as_safe_cancellation(qtbot,tmp_path,monkeypatch,kind):
|
||||
from cbb_refresh_verify.operation_queue import TaskHandoff,BatchTaskContext
|
||||
from cbb_refresh_verify.management import Capability
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
|
||||
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
|
||||
load(window,qtbot); results=[]
|
||||
def handed_off(*a,**k): raise TaskHandoff(BatchTaskContext('a.lmc'))
|
||||
if kind=='recovery':
|
||||
window.restore_backup(); dialog=window.backup_dialog
|
||||
source=tmp_path/'A.prj'; source.write_text('project'); dialog.source_edit.setText(str(source))
|
||||
dialog.recoverer=handed_off
|
||||
dialog.completed.connect(lambda name,result:results.append(result))
|
||||
dialog.restore_button.click()
|
||||
else:
|
||||
window.select_visible_button.click(); window.manage_cbb('remove'); dialog=window.management_dialog
|
||||
dialog.runner=handed_off
|
||||
dialog.completed.connect(results.extend)
|
||||
dialog.execute_button.click()
|
||||
qtbot.waitUntil(lambda:bool(results))
|
||||
assert results[0].safe_to_continue is False
|
||||
|
||||
|
||||
def test_real_startup_observer_delivery_after_destroy_is_ignored(qtbot,tmp_path,monkeypatch):
|
||||
callbacks=[]
|
||||
monkeypatch.setattr('cbb_refresh_verify.management.unfinished_operations',lambda _:[])
|
||||
monkeypatch.setattr('cbb_refresh_verify.session_record.discover_sessions',lambda _:[dict(
|
||||
status='ACTIVE',path='owned-session.json',block='A',phase='NATIVE_CALL',detail='running')])
|
||||
monkeypatch.setattr('cbb_refresh_verify.session_record.handoff_session',lambda *a,**kw:callbacks.append(kw['progress']))
|
||||
# This test explicitly destroys the QObject, so pytest-qt must not retain it
|
||||
# for its normal close-at-teardown fixture.
|
||||
window=MainWindow(reader=lambda _:LibraryReadResult(()),data_root=tmp_path)
|
||||
window.show()
|
||||
qtbot.waitUntil(lambda:bool(callbacks))
|
||||
window.close(); qtbot.waitUntil(lambda:not window.isVisible())
|
||||
import shiboken6
|
||||
shiboken6.delete(window)
|
||||
callbacks[0]({'library':'a.lmc','status':'RELEASED'})
|
||||
|
||||
|
||||
def test_running_a_emits_real_choice_after_reading_b(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.pcb_open_consent import OpenChoice
|
||||
entered,continue_a,answered=Event(),Event(),Event(); choices=[]
|
||||
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',80)
|
||||
def verify(request,*,version_prompt,**kwargs):
|
||||
entered.set(); continue_a.wait(5)
|
||||
choice=OpenChoice(request.block_name,request.lmc_file); choices.append(choice)
|
||||
version_prompt(choice)
|
||||
for _ in range(100):
|
||||
if choice.decision is not None: answered.set(); break
|
||||
Event().wait(.02)
|
||||
return VerifyResult('SKIPPED',safe_to_continue=True)
|
||||
monkeypatch.setattr('cbb_refresh_verify.verify_runner.run_verify',verify)
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
|
||||
load(window,qtbot); window._run(['A']); qtbot.waitUntil(entered.is_set)
|
||||
try:
|
||||
load(window,qtbot,'b.lmc'); message=window.status_label.text()
|
||||
continue_a.set(); qtbot.waitUntil(answered.is_set)
|
||||
assert choices[0].decision=='skip' and choices[0].library==Path('a.lmc')
|
||||
assert window.status_label.text()==message
|
||||
finally: continue_a.set(); window.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_second_management_dialog_cannot_submit_same_active_snapshot(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.management import Capability
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
|
||||
entered,release=Event(),Event(); calls=[]
|
||||
adapter=SimpleNamespace(capabilities=lambda:{op:Capability(True,'available') for op in ('add','update','remove')})
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,management_adapter=adapter)
|
||||
def runner(requests,**kwargs):
|
||||
calls.append(requests[0].name); entered.set(); release.wait(5); return []
|
||||
load(window,qtbot); window.select_visible_button.click(); window.manage_cbb('remove')
|
||||
first=window.management_dialog; first.runner=runner; first.execute_button.click()
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
try:
|
||||
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
|
||||
window.select_visible_button.click(); window.manage_cbb('remove')
|
||||
second=window.management_dialog; second.runner=runner; second.execute_button.click()
|
||||
assert not second.busy
|
||||
assert '重复' in second.status_label.text()
|
||||
release.set(); qtbot.waitUntil(lambda:not first.busy)
|
||||
assert calls==['A']
|
||||
finally: release.set(); first.pool.waitForDone(6000)
|
||||
|
||||
|
||||
def test_manual_repair_uses_current_diagnostic_database(qtbot,tmp_path,monkeypatch):
|
||||
import json
|
||||
evidence=tmp_path/'run'/'result.json'; evidence.parent.mkdir(); evidence.write_text('{}')
|
||||
diagnostic=evidence.parent/'diagnostics'/'icdb-recovery.json'; diagnostic.parent.mkdir()
|
||||
database=tmp_path/'actual-project'/'database'
|
||||
diagnostic.write_text(json.dumps({'database_path':str(database),'scope':'project'}))
|
||||
calls=[]
|
||||
def launcher(request,**kwargs):
|
||||
calls.append(kwargs)
|
||||
return SimpleNamespace(process=SimpleNamespace(poll=lambda:None),job=evidence,
|
||||
library=request.lmc_file,block=request.block_name,path_lease=None)
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,native_backup_launcher=launcher,
|
||||
verifier=lambda _:VerifyResult('FAIL',safe_to_continue=True,evidence_path=evidence,error_category='ICDB_REPAIR_REQUIRED'),
|
||||
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
|
||||
load(window,qtbot); window._run(['A']); qtbot.waitUntil(lambda:not window.busy)
|
||||
window.cbb_table.setCurrentCell(0,0); window.native_repair_button.click()
|
||||
qtbot.waitUntil(lambda:bool(calls))
|
||||
assert calls[0]['target_database']==str(database)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('maintenance',[False,True])
|
||||
def test_directory_only_submission_is_not_treated_as_native_registration(qtbot,tmp_path,monkeypatch,maintenance):
|
||||
from cbb_refresh_verify.management import Catalog
|
||||
calls=[]
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,
|
||||
verifier=lambda req:(calls.append(req.block_name) or VerifyResult('PASS')),
|
||||
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
|
||||
load(window,qtbot)
|
||||
# The snapshot was already selectable while the native catalog was unknown.
|
||||
window.catalog_reader=lambda path,evidence:Catalog(path,1,())
|
||||
window._run(['A'],maintenance=maintenance)
|
||||
qtbot.waitUntil(lambda:not window.busy and not window._icdb_active())
|
||||
assert calls == []
|
||||
|
||||
|
||||
def test_missing_all_project_directories_still_allows_native_catalog_reconciliation(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.management import Catalog,CatalogEntry
|
||||
path=tmp_path/'lib.lmc'; path.write_bytes(b'library metadata')
|
||||
window=MainWindow(data_root=tmp_path/'data',
|
||||
catalog_reader=lambda library,evidence:Catalog(library,1,(CatalogEntry('NativeOnly','Logical-Physical'),)),
|
||||
status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
|
||||
qtbot.addWidget(window); window.show()
|
||||
load(window,qtbot,str(path))
|
||||
qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name)
|
||||
assert window._records_by_name['NativeOnly'].catalog_source=='native_only'
|
||||
assert window._read_counts==(0,1,1)
|
||||
|
||||
|
||||
def test_failed_native_entry_resumes_captured_check_after_view_switch(qtbot,tmp_path,monkeypatch):
|
||||
entered,release=Event(),Event(); calls=[]
|
||||
def verify(request):
|
||||
calls.append(request.block_name)
|
||||
if len(calls)==1: entered.set(); release.wait(5)
|
||||
return VerifyResult('CHECKED',safe_to_continue=True)
|
||||
def failed(*a,**k): raise RuntimeError('entry refused')
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),CbbRecord('Next','LP'))),
|
||||
verifier=verify,native_backup_launcher=failed)
|
||||
load(window,qtbot); window._start_icdb_check(['A','Next']); qtbot.waitUntil(entered.is_set)
|
||||
task=window.icdb_task
|
||||
try:
|
||||
window.cbb_table.setCurrentCell(0,0); window.native_backup_button.click()
|
||||
assert task.paused
|
||||
load(window,qtbot,'b.lmc'); message=window.status_label.text()
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda:len(calls)==2,timeout=2000)
|
||||
assert window.status_label.text()==message
|
||||
finally:
|
||||
release.set(); task.cancel(); qtbot.waitUntil(lambda:not task.active)
|
||||
|
||||
|
||||
def test_old_release_panel_never_cancels_replacement_check(qtbot,tmp_path,monkeypatch):
|
||||
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
|
||||
monkeypatch.setattr(ResidualReleaseDialog,'refresh',lambda self:None)
|
||||
entered=Event(); window=None
|
||||
def verify(_):
|
||||
task=window.icdb_task; entered.set(); task.stop.wait(5)
|
||||
return VerifyResult('CANCELLED',safe_to_continue=True)
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,verifier=verify)
|
||||
load(window,qtbot); window._start_icdb_check(['A']); qtbot.waitUntil(entered.is_set)
|
||||
old=window.icdb_task
|
||||
window.release_library_button.click(); dialog=window.release_dialog
|
||||
old.cancel(); qtbot.waitUntil(lambda:not old.active)
|
||||
entered.clear(); load(window,qtbot,'b.lmc'); window._start_icdb_check(['A'])
|
||||
qtbot.waitUntil(entered.is_set); newer=window.icdb_task
|
||||
try:
|
||||
dialog.before_release.emit()
|
||||
assert not newer.stop.is_set()
|
||||
finally:
|
||||
newer.cancel(); qtbot.waitUntil(lambda:not newer.active)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('switch_view',[True,False])
|
||||
def test_summary_actions_keep_original_revision_and_resume_configuration(qtbot,tmp_path,monkeypatch,switch_view):
|
||||
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.DEFAULT_TIMEOUT_MS',10000)
|
||||
monkeypatch.setattr('cbb_refresh_verify.operation_lifecycle.recheck_failed_release',lambda library,name,result,**kw:result)
|
||||
requests=[]; release_clicks=[]
|
||||
def verify(request):
|
||||
requests.append(request)
|
||||
return VerifyResult('FAIL' if request.block_name=='A' else 'PASS',safe_to_continue=request.block_name!='A')
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),CbbRecord('Next','LP'))),
|
||||
verifier=verify,status_refresher=lambda names,_:{name:'PENDING' for name in names})
|
||||
monkeypatch.setattr(window,'check_library_release',lambda *a,**k:release_clicks.append(True))
|
||||
load(window,qtbot); original_timeout=window.timeout_spin.value(); window._run(['A','Next'])
|
||||
qtbot.waitUntil(lambda:not window.busy)
|
||||
old_release,old_resume=window._residual_release_action,window._resume_batch_action
|
||||
window._resume_batch['released']=True; window._update()
|
||||
if switch_view:
|
||||
load(window,qtbot,'b.lmc'); load(window,qtbot,'a.lmc')
|
||||
old_release.click(); old_resume.click(); qtbot.wait(100)
|
||||
assert release_clicks==[] and len(requests)==1
|
||||
else:
|
||||
window.timeout_spin.setValue(45)
|
||||
old_resume.click(); qtbot.waitUntil(lambda:not window.busy)
|
||||
assert len(requests)==2 and requests[-1].block_name=='Next'
|
||||
assert requests[-1].timeout_seconds==original_timeout
|
||||
|
||||
|
||||
def test_recovery_retry_rejects_old_external_progress_and_choice(qtbot,tmp_path,monkeypatch):
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from cbb_refresh_verify.pcb_open_consent import OpenChoice
|
||||
monkeypatch.setattr('cbb_refresh_verify.ui.timed_prompt.question',lambda *a,**k:QMessageBox.Yes)
|
||||
callbacks=[]; entered,release=Event(),Event()
|
||||
def recover(*args,progress,version_prompt,stop):
|
||||
callbacks.append((progress,version_prompt))
|
||||
if len(callbacks)==2: entered.set(); release.wait(5)
|
||||
return VerifyResult('CANCELLED',safe_to_continue=True)
|
||||
monkeypatch.setattr('cbb_refresh_verify.backup_recovery.recover_from_backup',recover)
|
||||
window=window_for(qtbot,tmp_path,monkeypatch,status_refresher=lambda names,_:{name:'UNKNOWN' for name in names})
|
||||
load(window,qtbot); window.restore_backup(); dialog=window.backup_dialog
|
||||
source=tmp_path/'A.prj'; source.write_text('project'); dialog.source_edit.setText(str(source))
|
||||
dialog.restore_button.click(); qtbot.waitUntil(lambda:not dialog.busy and not window.busy)
|
||||
try:
|
||||
dialog.restore_button.click(); qtbot.waitUntil(entered.is_set)
|
||||
message=dialog.status_label.text()
|
||||
callbacks[0][0]({'detail':'old external observer'})
|
||||
choice=OpenChoice('A',Path('a.lmc')); callbacks[0][1](choice)
|
||||
qtbot.wait(50)
|
||||
assert dialog.status_label.text()==message
|
||||
assert choice.decision=='cancel'
|
||||
finally:
|
||||
release.set(); qtbot.waitUntil(lambda:not dialog.busy)
|
||||
@@ -0,0 +1,72 @@
|
||||
"""A corrupt checkpoint cannot disown its independent identity-export copy."""
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from cbb_refresh_verify import library_lock as locks, native_export_guard as exports
|
||||
|
||||
|
||||
def external_copy(tmp_path, monkeypatch, *, associated, process_name, invalid=None):
|
||||
library = tmp_path/'library/lib.lmc'
|
||||
library.parent.mkdir()
|
||||
library.touch()
|
||||
other = tmp_path/'other/lib.lmc'
|
||||
other.parent.mkdir()
|
||||
other.touch()
|
||||
root = tmp_path/'evidence/identity'
|
||||
(root/'project/database').mkdir(parents=True)
|
||||
project = root/'project/Source.prj'
|
||||
# Source-library references may differ from the transaction's owner library.
|
||||
project.write_text(f'KEY CentralLibrary "{other if associated else library}"\n', 'utf-8')
|
||||
(root/'project/database/icdb.dat').touch()
|
||||
owner_library = library if associated else other
|
||||
with locks.LibraryLock(owner_library) as lease:
|
||||
exports.begin_export_analysis(owner_library, root, project)
|
||||
# Restart removes process-local retained ownership, but independent evidence remains.
|
||||
locks._owners.pop(lease.key)['handle'].Close()
|
||||
locks.blocker_path(library).write_bytes(b'{truncated checkpoint')
|
||||
process = dict(pid=123456, parent=98765, name=process_name,
|
||||
executable='C:/Mentor/'+process_name, created='20261116120000.000000+480',
|
||||
command=(f'icdb2ascii.exe -project="{project}"' if process_name == 'icdb2ascii.exe'
|
||||
else f'icdbnetserver.exe -icdb "{project.parent}/database"'))
|
||||
record = dict(command=['C:/Mentor/icdb2ascii.exe', '-project='+str(project)], kind='ascii',
|
||||
success=False, safe_to_continue=False, native_started=True,
|
||||
pid=process['pid'] if process_name == 'icdb2ascii.exe' else 98765,
|
||||
observed_pids=[process['pid']], root_created='2026-11-16T04:00:00+00:00',
|
||||
process_identities=[{k: process[k] for k in ('pid', 'created', 'executable')}])
|
||||
if invalid == 'identity':
|
||||
record['process_identities'][0]['created'] = '20261115120000.000000+480'
|
||||
(root/'ascii-process.json').write_text(json.dumps(record), 'utf-8')
|
||||
if invalid == 'missing_owner':
|
||||
(root/'export-owner.json').unlink()
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._retained_exports', [])
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [process])
|
||||
monkeypatch.setattr('cbb_refresh_verify.native_engineering_identity._process_snapshot', lambda: [process])
|
||||
return library, root
|
||||
|
||||
|
||||
@pytest.mark.parametrize('process_name', ['icdb2ascii.exe', 'icdbnetserver.exe'])
|
||||
@pytest.mark.parametrize('associated', [True, False])
|
||||
def test_corrupt_checkpoint_requires_independent_export_association(tmp_path, monkeypatch, process_name, associated):
|
||||
library, root = external_copy(tmp_path, monkeypatch,
|
||||
associated=associated, process_name=process_name)
|
||||
marker = locks.blocker_path(library)
|
||||
before = marker.read_bytes()
|
||||
if associated:
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'release')
|
||||
assert marker.read_bytes() == before
|
||||
else:
|
||||
proof = locks.release_retained_library(library, tmp_path/'release')
|
||||
assert proof['status'] == 'RELEASE_CONFIRMED'
|
||||
assert (root/'export-owner.json').is_file()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('invalid', ['missing_owner', 'identity'])
|
||||
def test_unproven_other_export_remains_unknown(tmp_path, monkeypatch, invalid):
|
||||
library, _ = external_copy(tmp_path, monkeypatch,
|
||||
associated=False, process_name='icdbnetserver.exe', invalid=invalid)
|
||||
before = locks.blocker_path(library).read_bytes()
|
||||
with pytest.raises(locks.LibraryBusy):
|
||||
locks.release_retained_library(library, tmp_path/'release')
|
||||
assert locks.blocker_path(library).read_bytes() == before
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Real producer/binding/worker admission, using only harmless Python children."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from threading import Event
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from test_issue15_ui_integration import window_for, load
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def transport(tmp_path):
|
||||
from cbb_refresh_verify.desktop_worker import DesktopWorker
|
||||
script = tmp_path/'harmless_worker.py'
|
||||
script.write_text('''import json,sys,time
|
||||
from pathlib import Path
|
||||
from cbb_refresh_verify.desktop_worker import run_native_worker
|
||||
from cbb_refresh_verify import native_management as management
|
||||
path=Path(sys.argv[1]); job=json.loads(path.read_text('utf-8')); root=path.parent
|
||||
def harmless(path):
|
||||
(root/'handler-entered').touch()
|
||||
while (root/'hold-handler').exists() and not (root/'finish').exists(): time.sleep(.01)
|
||||
(root/'result.json').write_text(json.dumps(dict(success=True,safe_to_continue=True,
|
||||
library=job['library'],flow=1,entries=[dict(name='A',partition='Logical-Physical',engineering_identity={})])))
|
||||
return 0
|
||||
if job['operation']=='catalog':
|
||||
management._current_desktop=lambda:(None,job['desktop'])
|
||||
def catalog(job,root):
|
||||
harmless(path)
|
||||
return json.loads((root/'result.json').read_text())
|
||||
management._catalog_native=catalog
|
||||
from cbb_refresh_verify.application import main
|
||||
execute=lambda:main(['--management-worker',str(path)])
|
||||
else: execute=lambda:run_native_worker(harmless,path)
|
||||
try: execute()
|
||||
except Exception as error: (root/'rejected').write_text(str(error),encoding='utf-8')
|
||||
''', encoding='utf-8')
|
||||
workers = []
|
||||
spawn = subprocess.Popen
|
||||
class Transport:
|
||||
bind_cancellation = DesktopWorker.bind_cancellation
|
||||
bind_session = DesktopWorker.bind_session
|
||||
request_stop = DesktopWorker.request_stop
|
||||
desktop = None
|
||||
def __init__(self, command, *args, **kwargs):
|
||||
self.path = Path(command[-1])
|
||||
self.process = spawn([sys.executable, str(script), str(self.path)])
|
||||
self.pid, self.handle = self.process.pid, self.process._handle
|
||||
workers.append(self)
|
||||
def poll(self): return self.process.poll()
|
||||
def wait(self, timeout=5): return self.process.wait(timeout)
|
||||
def close(self): self.process.wait(timeout=5)
|
||||
yield Transport, workers
|
||||
for worker in workers:
|
||||
worker.path.with_name('finish').touch()
|
||||
if worker.poll() is None:
|
||||
Path(json.loads(worker.path.read_text('utf-8'))['cancel_signal']).touch()
|
||||
worker.wait(6)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('entry', ['initial', 'verify', 'icdb'])
|
||||
def test_real_catalog_adapter_enters_initial_and_execution_reads(qtbot, tmp_path, monkeypatch, transport, entry):
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext
|
||||
Transport, workers = transport
|
||||
adapter = NativeManagementAdapter(worker_factory=Transport)
|
||||
window = window_for(qtbot, tmp_path/'ui', monkeypatch,
|
||||
catalog_reader=adapter.catalog, status_refresher=lambda names, _: {name:'PENDING' for name in names})
|
||||
library = tmp_path/'library.lmc'; library.write_bytes(b'isolated')
|
||||
if entry == 'initial':
|
||||
load(window, qtbot, str(library))
|
||||
qtbot.waitUntil(lambda: not any(j.kind=='catalog' and j.active for j in window._jobs.values()), timeout=6000)
|
||||
assert window._records_by_name['A'].catalog_source == 'both', window.status_label.text()
|
||||
else:
|
||||
context = BatchTaskContext(str(library), native_policy='external')
|
||||
reader = window._execution_status_reader(entry, None)
|
||||
assert context.run(lambda: reader(('A', 'Missing'), library)) == {'A':'PENDING','Missing':'NOT_REGISTERED'}
|
||||
assert len(workers) == 1
|
||||
record = json.loads(workers[0].path.with_name('session.json').read_text('utf-8'))
|
||||
assert record['worker_protection'] == 'catalog_readonly'
|
||||
assert record['worker_lease_handle'] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pause', ['after_bind', 'final_preparation'])
|
||||
def test_shutdown_wins_after_real_binding_and_returns_ui_waiter(qtbot, tmp_path, monkeypatch, transport, pause):
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
Transport, workers = transport
|
||||
entered, resume = Event(), Event()
|
||||
original_bind, original_touch = Transport.bind_session, Path.touch
|
||||
if pause == 'after_bind':
|
||||
def bind(self, job):
|
||||
original_bind(self, job); entered.set(); assert resume.wait(6)
|
||||
Transport.bind_session = bind
|
||||
else:
|
||||
def touch(path, *args, **kwargs):
|
||||
if path.name == 'start-management.signal':
|
||||
entered.set(); assert resume.wait(6)
|
||||
return original_touch(path, *args, **kwargs)
|
||||
monkeypatch.setattr(Path, 'touch', touch)
|
||||
library = tmp_path/'lib.lmc'; library.write_bytes(b'isolated')
|
||||
adapter = NativeManagementAdapter(worker_factory=Transport)
|
||||
window = window_for(qtbot, tmp_path/'ui', monkeypatch)
|
||||
job = window._new_job('verify', library=library)
|
||||
def action():
|
||||
with LibraryLock(library, checkpoint=False):
|
||||
return adapter._worker(dict(operation='remove',library=str(library)),tmp_path/'operation')
|
||||
window._start(action, lambda _:None, job=job)
|
||||
qtbot.waitUntil(entered.is_set, timeout=4000)
|
||||
try:
|
||||
state = job.context.shutdown()
|
||||
assert state['shutdown_handoff']
|
||||
qtbot.waitUntil(lambda: not window.busy, timeout=1000)
|
||||
resume.set()
|
||||
qtbot.waitUntil(lambda: not job.context.snapshot()['pending'], timeout=4000)
|
||||
qtbot.waitUntil(lambda: workers[0].poll() is not None, timeout=4000)
|
||||
assert not (tmp_path/'operation'/'handler-entered').exists()
|
||||
finally:
|
||||
resume.set()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('route', ['verify', 'backup', 'repair'])
|
||||
@pytest.mark.parametrize('pause', ['after_bind', 'final_preparation'])
|
||||
def test_other_real_producers_share_final_admission_fence(qtbot,tmp_path,monkeypatch,transport,route,pause):
|
||||
from cbb_refresh_verify import desktop_worker, native_backup, native_repair, session_record
|
||||
from cbb_refresh_verify.library_lock import LibraryLock
|
||||
from cbb_refresh_verify.verify_runner import run_verify
|
||||
from test_verify_runner import fixture, request, PORTS_OK
|
||||
from test_native_repair import target_fixture
|
||||
Transport, workers = transport
|
||||
entered, resume = Event(), Event()
|
||||
original_bind, original_register, original_touch = Transport.bind_session, session_record.register_worker_session, Path.touch
|
||||
if pause == 'after_bind':
|
||||
def bind(self, job):
|
||||
original_bind(self, job); entered.set(); assert resume.wait(8)
|
||||
Transport.bind_session = bind
|
||||
if route == 'backup':
|
||||
def register(worker,job):
|
||||
original_register(worker,job); entered.set(); assert resume.wait(8)
|
||||
monkeypatch.setattr(session_record,'register_worker_session',register)
|
||||
else:
|
||||
def touch(path,*args,**kwargs):
|
||||
if path.name in ('start-worker.signal','start-repair.signal'):
|
||||
entered.set(); assert resume.wait(8)
|
||||
return original_touch(path,*args,**kwargs)
|
||||
monkeypatch.setattr(Path,'touch',touch)
|
||||
monkeypatch.setattr(desktop_worker,'DesktopWorker',Transport)
|
||||
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:[])
|
||||
if route == 'repair':
|
||||
req,_,target = target_fixture(tmp_path)
|
||||
def action():
|
||||
with LibraryLock(req.lmc_file,checkpoint=False):
|
||||
return native_repair.run_native_repair(target,tmp_path/'repair',maintenance_context={'library':str(req.lmc_file)})
|
||||
elif route == 'backup':
|
||||
from test_native_backup import project_fixture
|
||||
req,_ = project_fixture(tmp_path)
|
||||
monkeypatch.setattr(native_backup,'native_backup_executable',lambda *_:tmp_path/'unused.exe')
|
||||
monkeypatch.setattr(native_backup.subprocess,'Popen',Transport)
|
||||
action=lambda:native_backup.launch_native_backup(req)
|
||||
else:
|
||||
fixture(tmp_path); req=request(tmp_path)
|
||||
action=lambda:run_verify(req,port_check=PORTS_OK)
|
||||
window=window_for(qtbot,tmp_path/'ui',monkeypatch)
|
||||
job=window._new_job('verify',library=req.lmc_file)
|
||||
window._start(action,lambda _:None,job=job)
|
||||
try:
|
||||
qtbot.waitUntil(entered.is_set,timeout=6000)
|
||||
assert job.context.shutdown()['shutdown_handoff']
|
||||
qtbot.waitUntil(lambda:not window.busy,timeout=1500)
|
||||
resume.set()
|
||||
qtbot.waitUntil(lambda:not job.context.snapshot()['pending'],timeout=6000)
|
||||
qtbot.waitUntil(lambda:workers[0].poll() is not None,timeout=4000)
|
||||
assert not workers[0].path.with_name('handler-entered').exists()
|
||||
finally:
|
||||
resume.set()
|
||||
|
||||
|
||||
def test_catalog_read_role_requires_the_actual_readonly_worker_action(tmp_path):
|
||||
from cbb_refresh_verify.desktop_worker import run_native_worker
|
||||
from cbb_refresh_verify.native_management import catalog_worker_main,management_worker_main,_catalog_com,catalog_dialog_action
|
||||
from cbb_refresh_verify.session_record import register_worker_session
|
||||
from types import SimpleNamespace
|
||||
path=tmp_path/'request.json'
|
||||
job=dict(operation='catalog',worker_role='catalog_readonly',operation_id='read',
|
||||
library=str(tmp_path/'lib.lmc'),session_record_path=str(tmp_path/'session.json'))
|
||||
path.write_text(json.dumps(job))
|
||||
register_worker_session(SimpleNamespace(pid=os.getpid()),job)
|
||||
effects=[]
|
||||
def impostor(path): effects.append('write')
|
||||
with pytest.raises(RuntimeError,match='WORKER_READONLY_ROLE_MISMATCH'):
|
||||
run_native_worker(impostor,path)
|
||||
with pytest.raises(RuntimeError,match='WORKER_READONLY_ROLE_MISMATCH'):
|
||||
management_worker_main(path)
|
||||
job['operation']='add';path.write_text(json.dumps(job))
|
||||
with pytest.raises(RuntimeError,match='WORKER_READONLY_ROLE_MISMATCH'):
|
||||
catalog_worker_main(path)
|
||||
with pytest.raises(RuntimeError,match='WORKER_READONLY_ROLE_MISMATCH'):
|
||||
_catalog_com(job,tmp_path)
|
||||
assert effects==[]
|
||||
assert catalog_dialog_action('Library Manager','Would you like to save?',read_only=True)=='cancel'
|
||||
assert catalog_dialog_action('Upgrade library','Continue?',read_only=True)=='cancel'
|
||||
|
||||
|
||||
def test_catalog_native_wait_outlives_metadata_deadline(tmp_path, transport, monkeypatch):
|
||||
from threading import Thread
|
||||
from cbb_refresh_verify.native_management import NativeManagementAdapter
|
||||
from cbb_refresh_verify.operation_queue import BatchTaskContext
|
||||
Transport, workers = transport
|
||||
evidence = tmp_path/'slow-catalog'
|
||||
original = Transport.__init__
|
||||
def start(self, command, *args, **kwargs):
|
||||
Path(command[-1]).with_name('hold-handler').touch()
|
||||
original(self, command, *args, **kwargs)
|
||||
Transport.__init__ = start
|
||||
clock = time.monotonic
|
||||
offset = [0]
|
||||
monkeypatch.setattr(time, 'monotonic', lambda: clock()+offset[0])
|
||||
def complete():
|
||||
deadline = clock()+5
|
||||
while not (evidence/'handler-entered').exists() and clock()<deadline:
|
||||
time.sleep(.01)
|
||||
offset[0] = 20 # Only the admitted native wait crosses the metadata deadline.
|
||||
time.sleep(.15)
|
||||
(evidence/'finish').touch()
|
||||
finisher = Thread(target=complete)
|
||||
finisher.start()
|
||||
context = BatchTaskContext(str(tmp_path/'library.lmc'), native_policy='external')
|
||||
try:
|
||||
result = context.run(lambda: NativeManagementAdapter(worker_factory=Transport).catalog(
|
||||
tmp_path/'library.lmc', evidence), timeout_seconds=10)
|
||||
assert [entry.name for entry in result.entries] == ['A']
|
||||
assert result.safe_to_continue
|
||||
finally:
|
||||
(evidence/'finish').touch()
|
||||
finisher.join(6)
|
||||
context.close(timeout_seconds=6)
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user