Compare commits

...
Author SHA1 Message Date
阿白叔 7c239e123b fix: address PCB access review in CLI and desktop 2026-11-23 12:10:30 +08:00
阿白叔 2d6acc1180 fix: show complete CBB result details 2026-11-23 09:08:19 +08:00
阿白叔 86837155ea fix: preserve catalog state and verify PCB write access 2026-11-20 23:24:47 +08:00
阿白叔 3efeaed656 chore: set version to 0.2.4b5 2026-11-20 16:50:48 +08:00
阿白叔 55cdf2b082 fix: finish owned idle sessions before proving resource release 2026-11-19 11:14:49 +08:00
阿白叔 3bde847ff7 fix: skip unavailable items and isolate batch failures 2026-11-19 10:06:04 +08:00
阿白叔 07eab61695 fix: complete issue17 cleanup and bounded native verification 2026-11-18 19:13:49 +08:00
阿白叔 14cacb1d1c release: prepare v0.2.4-beta.4 and guard late management signals
Ignore queued management completion after its Qt receiver is destroyed. Isolate unrelated WMI and file-proof latency in simulated lifecycle tests while retaining real occupancy and writer-barrier coverage. Validation: 2428 tests passed, compile and whitespace checks passed, scoped review clean. Field ICDB inconsistency and Windows 10/production SMB remain unaccepted.
2026-11-18 10:13:55 +08:00
阿白叔 fa1f662e1d fix: preserve handoff cleanup and ICDB cancellation bindings 2026-11-18 09:05:22 +08:00
阿白叔 b4737b5102 docs: record final issue15 scoped review acceptance 2026-11-17 14:09:15 +08:00
阿白叔 8869093eb0 docs: record final issue 15 fix-wave acceptance and limits 2026-11-17 13:55:20 +08:00
阿白叔 c1e259603a fix: preserve observer promotion for ordinary release 2026-11-17 13:37:36 +08:00
阿白叔 5e9509e573 fix: hand off late cancelled startup cleanup once 2026-11-17 13:13:24 +08:00
阿白叔 906cfc06be fix: prove prewrite cancellation and bound recovery metadata lifetime 2026-11-17 12:45:59 +08:00
64 changed files with 3901 additions and 201 deletions

No files matched your search

+8
View File
@@ -193,6 +193,14 @@ Windows 版本判断以 Build 为准:`22000` 及以上归为 Win11,`10240–
GUI 中状态为 `绿色 / Ready` 的条目不能勾选、也不会进入批量队列。 GUI 中状态为 `绿色 / Ready` 的条目不能勾选、也不会进入批量队列。
### PCB 读写确认
桌面普通校验默认在读写确认弹窗无人应答 3 秒后核验占用。可在高级设置取消勾选「无人应答时自动核验 PCB 读写占用」,本次启动的后续批次便会在无人应答时跳过该项。手动选择继续也会核验占用。
命令行使用 `--batch-lmc` 时,加 `--auto-confirm-pcb-open` 可对已识别的读写确认执行同样的核验。带此参数的无界面运行发现该弹窗后立即开始检查。版本选择和 ICDB 维护分别使用各自的入口。
程序核对当前工程、LMC、布局和共享数据库。出现身份不符、实际占用、无法绑定的地址记录、绝对或不唯一的 iCDBDir,以及需要维护的库时,报告会记录具体原因。双击表格备注可查看并复制全文。
### 批量状态桥(只读、默认启用) ### 批量状态桥(只读、默认启用)
`tools/status_bridge/bin/CbbStatusBridge32.exe` 是与 Mentor EE 7.9 x86/MFC ABI `tools/status_bridge/bin/CbbStatusBridge32.exe` 是与 Mentor EE 7.9 x86/MFC ABI
@@ -1,6 +1,6 @@
# Issue 15 acceptance matrix # Issue 15 acceptance matrix
Refs #15. The round-1 complete suite at `8818fa9` passed **2,358 tests in 451.34 seconds**, exit code 0, with zero failures, errors or skips. B9 automatic release/prequeued Versions and B10 legacy release/conditional buttons retain their actual build identities. Ordinary Verify early cancellation still retains a later loaded Forward prompt and is an open blocker. Source Qt/Windows tests, source native runs and frozen native runs are separate evidence classes. 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 ## Executable bindings
@@ -19,6 +19,9 @@ Each case retains its actual executable hash. Rebuilds checked all packaged modu
| B9 | a3f69de | `bfd6c122724f71a2aac4748ed01336a9949aa753f9c58aca55db574668140083` | | B9 | a3f69de | `bfd6c122724f71a2aac4748ed01336a9949aa753f9c58aca55db574668140083` |
| B10 | 701e5cd | `a6271e4219a02123e301ed1e0ea3109e78307bf1f92574b4a5cacb70690695a4` | | B10 | 701e5cd | `a6271e4219a02123e301ed1e0ea3109e78307bf1f92574b4a5cacb70690695a4` |
| B11 | 8818fa9 | `03452e39f394c3c63113aaa701f64bacf14e817ae3b4e194965f333ecc645b98` | | 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`. 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`.
@@ -26,6 +29,8 @@ B10 ZIP SHA-256: `d4bd42416ea8d12a249ff1d9c8854eb76d2f81bb7ff869ff43dd92a331c647
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. 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 ## Reported issues A–H
| Issue | Source verification | Actual frozen evidence and limits | | Issue | Source verification | Actual frozen evidence and limits |
@@ -64,10 +69,13 @@ These identifiers locate retained local evidence; raw field files, private machi
| 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. | | 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. | | 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 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 — open defect | 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 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 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. | | 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. | | 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. 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.
@@ -78,25 +86,45 @@ The B2 diagnostic run supports the implemented sole-handler No sequence through
| Tabs, advanced options, optional LM checkbox, runtime log toggle | Actual source UI and Qt tests | B1 actual navigation/toggles. | | 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. | | 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. | | 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 recovery target verification. READY exclusion remains enforced. | | 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. | | 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. | | 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. | | 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. | | 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. | | 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. | | 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 full source-validation/install/target-validation sequence. | | 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. | | 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. | | 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. | | 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. | | 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. Ordinary retained startup required manual native cleanup and remains an open defect. Other fault-dependent recovery branches are not blanket passed. | | 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. | | 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. | | 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. | | 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. 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 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. 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.
@@ -2,10 +2,19 @@
Refs #15. This candidate records local Windows 11 acceptance and its limits; it is not a published release or field-acceptance approval. 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 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. 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 ## 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. - 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.
@@ -78,8 +87,28 @@ The final round-1 complete suite at `8818fa9` passed **2,358 tests in 451.34 sec
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. 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 button exercise exposed an **open 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 current automatic loaded-startup cleanup requires 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 for the whole-branch fix/review round. 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. 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. 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.
+34
View File
@@ -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,13 @@
# 工单 #19 审查后续验证
## 合入与发布
PR #18 的目标为 main,PR #20 叠在 PR #18 的分支上。计划先合入 #18,再将 #20 的变更合入 main。发版前在 main 核对两轮改动和测试证据,从最终提交构建新测试版。现有 beta.5 标签对应提交 `3efeaed`。其中不含 PR #20 的目录扫描、读写确认和完整备注改动。
## 占用验证
- 在 Windows 上保留实际文件探测,分别验证共享数据库由独占句柄持有和释放后的选择。另用存在地址记录的工作目录覆盖原生只读检查的调度、正反回执解析和再次探测。该用例替换 Mentor 回执来源。
- 在隔离工程 1GPHY_RTL8211F 上,以之前捕获的项目地址记录调用实际 Mentor Project Backup。原生结果为 `NOT_IN_USE`、`repair_required=true`、`inspection_only=true`、`repair_requested=false`,退出码 0。程序拒绝自动继续。工程地址、工程数据库和共享符号数据库的哈希保持一致,原生检查进程已退出。原始回执 SHA-256 为 `22812c4423bc06fedce4eb9c89ee17e1fe10452fde76aff02ae0380a4505d1d6`。
- 批次回归核对前项保持 SKIPPED,释放复核成功后实际调度同库下一项。工单原先的 5 个工程、364 项生产库及 Win10/SMB 仍待现场复验。
最终全量 Python 测试 2,526 项通过,用时 366.39 秒,退出码 0。编译和差异检查通过。本轮未复现审查机的文件探测挂起。
@@ -0,0 +1,18 @@
# 工单 #17:失败项收尾与后续任务准入
按用户“开始修复,并实际验证收尾闭环”的授权实施。沿用 2026-11-18 工单附件分析;不改 ICDB 自动 Repair、READY 跳过策略和原生 Verify 路线。
1. 以工单精确数据库加载失败问题补回归:直接遇到“是否查看日志”、监督器先行点否、空 PCB 关闭、未知弹窗保留。
2. 修复成功 worker 误报保留会话;保存后分别记录工程路径、文档名、IsSaved,短暂状态有界重试,不放宽身份/Close/READY 条件。
3. 目录完整状态查询采用足够且有界的任务预算;UNKNOWN 独立显示,不进入生产批量校验;目录结束后刷新取消按钮状态。
4. 批次在后续同库项前复核先前未释放项,释放成功后清除其全部路径别名,原失败不改为 PASS。真实未释放仍不可强行写入;不同库继续独立。
5. 实测使用既有隔离验证库的全量一致副本,记录来源、完整复制哈希及工程引用重绑定。健康项先通过原生同名更新成为 PENDING;只在本次副本制造打开故障。通过实际应用按钮运行故障批次、再次运行批次,检查真实原生启动、Save/Close、READY、精确 PID 退出、协调句柄和会话记录,不以模拟或原本 READY 的跳过代替通过。
6. 全量测试和编译检查,记录源码身份、实际步骤及未通过边界。保留工单打开,不自动合并或发行。
工单附件将“任何收尾失败都继续写下一块”与“基础设施错误十次熔断”并列。本次优先消除可自动完成的失败收尾及过期阻塞,不以强杀未知写入或伪造 RELEASED 达成队列继续。
实测补充:首次原生同名导入后,健康控制项完成 Save/Close/退出、三次权威 PENDING/raw=0,未生成 Cert;同一应用显式再次校验触发原生“保存复用块”确认并达到 READY/raw=1。保留首轮失败,不把它重记为通过。
据此新增有界提交补完:仅普通校验得到 MENTOR_VERIFY_NOT_COMMITTED,且 COMMITTED/CLOSED/EXITED/RELEASED、未中断、权威 NOT_GREEN 时,记录检查点后最多再执行一次完整原生校验。它会再次打开工程并执行原生写入,**不是只读状态重查**。不适用于数据库打开失败、未知保存/关闭/释放、诊断、自动 Repair 或 Repair 确认流程。第二次仍不为 READY 就保留失败,不循环。两轮证据关联、累计耗时,首轮证据不覆盖;取消后不进入第二轮,补完前取消也必须释放已完成首轮的协调句柄。自动链路仍需实际按钮验收,显式重跑成功本身不算通过。
最终源码按钮验收已记录:故障项 FAIL 安全释放后下一项 PASS;同一应用下一批首轮 PENDING 后自动一次补完为 READY。未强杀、删除原生锁或手动释放。进程/独占文件核对通过;完整边界与证据见 `docs/releases/2026-11-18-issue17-cleanup-validation.md`,保留现场原始故障与冻结包验收缺口。
+1 -1
View File
@@ -3,7 +3,7 @@ requires = ["setuptools>=84.1.0"]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
[project] [project]
name = "cbb-refresh-verify" name = "cbb-refresh-verify"
version = "0.2.4b3" version = "0.2.4b5"
requires-python = ">=3.12,<3.13" requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"] dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<0.7", "Pillow>=13.0.0,<14"]
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.2.4b3" __version__ = "0.2.4b5"
+4 -1
View File
@@ -143,6 +143,8 @@ def main(argv: Sequence[str] | None = None) -> int:
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS) parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS) parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS) parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
parser.add_argument('--auto-confirm-pcb-open', action='store_true',
help='With --batch-lmc, continue through the known PCB prompt after checking resource access')
parser.add_argument('--limit', type=_positive_int, help='Maximum requested CBB names for --batch-lmc (default: all)') parser.add_argument('--limit', type=_positive_int, help='Maximum requested CBB names for --batch-lmc (default: all)')
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS) parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS) parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
@@ -203,7 +205,8 @@ def main(argv: Sequence[str] | None = None) -> int:
mentor_bin=args.mentor_bin, logging_context=context, mentor_bin=args.mentor_bin, logging_context=context,
mapped_drive=lease.drive, mapped_drive=lease.drive,
mapped_remote_root=lease.remote_root, mapped_remote_root=lease.remote_root,
native_lm_verify=native_lm_verify_enabled()) native_lm_verify=native_lm_verify_enabled(),
auto_confirm_pcb_open=args.auto_confirm_pcb_open)
for name in names] for name in names]
def retain_mapping(reason): def retain_mapping(reason):
lease.retain_for_recovery() lease.retain_for_recovery()
+31 -10
View File
@@ -164,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): 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.""" """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 .network_path import absolute_preserving_drive
from .verify_runner import run_verify, read_library_flag_if_available from .verify_runner import run_verify, read_library_flag_if_available
verifier = verifier or run_verify verifier = verifier or run_verify
@@ -187,11 +187,16 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
return VerifyResult('BLOCKED', stderr='恢复记录目录不能位于备份工程内。') return VerifyResult('BLOCKED', stderr='恢复记录目录不能位于备份工程内。')
if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent): if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent):
return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。') return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。')
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
library_lock = None library_lock = None
release_confirmed = True release_confirmed = True
installed = False 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), record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source),
'library': str(library), 'block': request.block_name, 'installed': False, 'library': str(library), 'block': request.block_name, 'installed': False,
'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'} 'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'}
@@ -216,23 +221,25 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
from .com_runtime import initialize_com, uninitialize_com from .com_runtime import initialize_com, uninitialize_com
initialized = initialize_com() initialized = initialize_com()
try: try:
acquired = win32event.WaitForSingleObject(mutex, 0) in ( check()
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
return VerifyResult('BLOCKED', stderr='已有 CBB 任务运行,请等待结束。', safe_to_continue=False)
from .library_lock import LibraryLock from .library_lock import LibraryLock
library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed) library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed)
library_lock.__enter__() library_lock.__enter__()
if source.is_relative_to(library_root): if source.is_relative_to(library_root):
raise ValueError('请选择目标中心库之外的独立备份工程。') raise ValueError('请选择目标中心库之外的独立备份工程。')
project, pcb = preflight(replace(request, lmc_file=library)) project, pcb = preflight(replace(request, lmc_file=library))
completed()
source_pcb = _source_check(source, request.block_name, project) source_pcb = _source_check(source, request.block_name, project)
completed()
root.mkdir(parents=True, exist_ok=False) root.mkdir(parents=True, exist_ok=False)
idle_check(library, project, pcb) idle_check(library, project, pcb)
completed()
idle_check(library, source, source_pcb) idle_check(library, source, source_pcb)
completed()
validation_base.mkdir(parents=True, exist_ok=True) 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)) 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)) 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() same_drive = root.anchor.casefold() == validation_dir.anchor.casefold()
required = (library_size + source_size * 2) if same_drive else 0 required = (library_size + source_size * 2) if same_drive else 0
if (shutil.disk_usage(root).free < required if (shutil.disk_usage(root).free < required
@@ -244,6 +251,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
library_scope = ManifestScope.library(request.block_name, library.name) library_scope = ManifestScope.library(request.block_name, library.name)
original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope, original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope,
progress=copy_progress('prepare_source', '正在准备验证库:')) progress=copy_progress('prepare_source', '正在准备验证库:'))
completed()
(root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8') (root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
staged_library = validation_dir/library.name staged_library = validation_dir/library.name
staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work' staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work'
@@ -252,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()): if not resolved_work.is_relative_to(validation_dir.resolve()):
raise ValueError('验证副本工程路径越界。') raise ValueError('验证副本工程路径越界。')
shutil.rmtree(resolved_work) shutil.rmtree(resolved_work)
completed()
source_manifest = _copy_verified(source.parent, staged_work, source_manifest = _copy_verified(source.parent, staged_work,
progress=copy_progress('prepare_source', '正在准备备份验证工程:')) progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
completed()
(root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8') (root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
staged_project = staged_work/source.name staged_project = staged_work/source.name
staged_pcb = staged_work/source_pcb.relative_to(source.parent) staged_pcb = staged_work/source_pcb.relative_to(source.parent)
@@ -263,32 +273,44 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='', auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='',
native_lm_verify=False, interactive_input=False) native_lm_verify=False, interactive_input=False)
preflight(validation) preflight(validation)
completed()
emit('validate_source', '正在副本中打开备份工程并执行原生校验…') emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
check()
release_confirmed = False release_confirmed = False
choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {} choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {}
if stop is not None:choice_options['stop']=stop if stop is not None:choice_options['stop']=stop
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options) source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
release_confirmed = source_result.safe_to_continue release_confirmed = source_result.safe_to_continue
record['source_validation'] = asdict(source_result) record['source_validation'] = asdict(source_result)
completed()
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN' if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
or not source_result.safe_to_continue): or not source_result.safe_to_continue):
return save(replace(source_result, status='FAIL', stderr= return save(replace(source_result, status='FAIL', stderr=
'备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail))) '备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail)))
idle_check(library, project, pcb) idle_check(library, project, pcb)
completed()
idle_check(staged_library, staged_project, staged_pcb) idle_check(staged_library, staged_project, staged_pcb)
completed()
token = root.name.removeprefix('backup-restore-') token = root.name.removeprefix('backup-restore-')
work = project.parent.resolve() work = project.parent.resolve()
incoming = work.with_name('Work.restore-' + token) incoming = work.with_name('Work.restore-' + token)
retained = work.with_name('Work.before-restore-' + token) retained = work.with_name('Work.before-restore-' + token)
_copy_verified(staged_work, incoming, _copy_verified(staged_work, incoming,
progress=copy_progress('prepare_source', '正在准备恢复工程:')) progress=copy_progress('prepare_source', '正在准备恢复工程:'))
completed()
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library) _align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
completed()
idle_check(library, source, source_pcb) idle_check(library, source, source_pcb)
completed()
if _manifest(source.parent) != source_manifest: if _manifest(source.parent) != source_manifest:
raise ValueError('备份来源在验证期间发生变化,目标未更改。') raise ValueError('备份来源在验证期间发生变化,目标未更改。')
completed()
if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest: if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest:
raise ValueError('目标中心库在验证期间发生变化,停止恢复。') raise ValueError('目标中心库在验证期间发生变化,停止恢复。')
completed()
emit('install', '备份已通过验证,正在保留原工程并恢复…') emit('install', '备份已通过验证,正在保留原工程并恢复…')
check()
with local_commit():
work.rename(retained) work.rename(retained)
try: try:
incoming.rename(work) incoming.rename(work)
@@ -297,7 +319,9 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
raise raise
installed = True installed = True
record['retained_work'] = str(retained) record['retained_work'] = str(retained)
completed()
emit('verify_target', '正在重新打开恢复后的目标工程并校验…') emit('verify_target', '正在重新打开恢复后的目标工程并校验…')
check()
release_confirmed = False release_confirmed = False
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify', final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
auto_repair=False, native_lm_verify=False, interactive_input=False), auto_repair=False, native_lm_verify=False, interactive_input=False),
@@ -320,7 +344,4 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
if library_lock is not None: if library_lock is not None:
library_lock.__exit__(None, None, None) library_lock.__exit__(None, None, None)
finally: finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
uninitialize_com(initialized) uninitialize_com(initialized)
+18 -11
View File
@@ -172,7 +172,8 @@ class BatchCheckpoint:
) )
return cls(records) return cls(records)
def append(self, path: Path, record: BatchStatusRecord) -> None: def append(self, path: Path | None, record: BatchStatusRecord) -> None:
if path is not None:
checkpoint = Path(path) checkpoint = Path(path)
checkpoint.parent.mkdir(parents=True, exist_ok=True) checkpoint.parent.mkdir(parents=True, exist_ok=True)
with checkpoint.open("a", encoding="utf-8", newline="\n") as handle: with checkpoint.open("a", encoding="utf-8", newline="\n") as handle:
@@ -200,13 +201,17 @@ class BatchStatusSession:
self.rotate_every = max(1, int(rotate_every)) self.rotate_every = max(1, int(rotate_every))
self.restart_count = 0 self.restart_count = 0
def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path, def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path | None,
*, block_type: str = "RULP", resume: bool = False) -> list[BatchStatusRecord]: *, block_type: str = "RULP", resume: bool = False) -> list[BatchStatusRecord]:
fingerprint = fingerprint_library(Path(lmc_file)) from .operation_queue import check_active
check_active()
fingerprint = fingerprint_library(Path(lmc_file)).sha256 if checkpoint_path is not None else ''
checkpoint = BatchCheckpoint()
if checkpoint_path is not None:
if resume: if resume:
checkpoint = BatchCheckpoint.load(checkpoint_path) checkpoint = BatchCheckpoint.load(checkpoint_path)
else: else:
checkpoint = BatchCheckpoint()
checkpoint_file = Path(checkpoint_path) checkpoint_file = Path(checkpoint_path)
checkpoint_file.parent.mkdir(parents=True, exist_ok=True) checkpoint_file.parent.mkdir(parents=True, exist_ok=True)
checkpoint_file.write_text('', encoding='utf-8') checkpoint_file.write_text('', encoding='utf-8')
@@ -219,9 +224,10 @@ class BatchStatusSession:
try: try:
queried = 0 queried = 0
for index, name in enumerate(names): for index, name in enumerate(names):
check_active()
previous = checkpoint.get(name) previous = checkpoint.get(name)
if (previous and previous.status in {'READY', 'PENDING'} if (previous and previous.status in {'READY', 'PENDING'}
and previous.fingerprint == fingerprint.sha256 and previous.block_type == block_type): and previous.fingerprint == fingerprint and previous.block_type == block_type):
results.append(previous) results.append(previous)
continue continue
try: try:
@@ -232,12 +238,12 @@ class BatchStatusSession:
record = BatchStatusRecord( record = BatchStatusRecord(
block_name=name, status=result.status, source=result.source, block_name=name, status=result.status, source=result.source,
raw_status=result.raw_status, detail=result.detail, raw_status=result.raw_status, detail=result.detail,
fingerprint=fingerprint.sha256, timestamp=_now(), fingerprint=fingerprint, timestamp=_now(),
block_type=block_type, block_type=block_type,
) )
except BridgeUnavailable as error: except BridgeUnavailable as error:
record = BatchStatusRecord(block_name=name, status="UNAVAILABLE", record = BatchStatusRecord(block_name=name, status="UNAVAILABLE",
detail=str(error), fingerprint=fingerprint.sha256, detail=str(error), fingerprint=fingerprint,
timestamp=_now(), block_type=block_type) timestamp=_now(), block_type=block_type)
except BridgeResponseError as error: except BridgeResponseError as error:
message = str(error) message = str(error)
@@ -252,7 +258,7 @@ class BatchStatusSession:
else "UNAVAILABLE" if unavailable else "UNAVAILABLE" if unavailable
else "MALFORMED" if malformed else "ERROR") else "MALFORMED" if malformed else "ERROR")
record = BatchStatusRecord(block_name=name, status=status, detail=message, record = BatchStatusRecord(block_name=name, status=status, detail=message,
fingerprint=fingerprint.sha256, timestamp=_now(), block_type=block_type) fingerprint=fingerprint, timestamp=_now(), block_type=block_type)
if server is not None and status != "UNAVAILABLE": if server is not None and status != "UNAVAILABLE":
try: try:
server.restart() server.restart()
@@ -260,12 +266,13 @@ class BatchStatusSession:
pass pass
except Exception as error: # bridge failures isolate one CBB except Exception as error: # bridge failures isolate one CBB
record = BatchStatusRecord(block_name=name, status="ERROR", detail=str(error), record = BatchStatusRecord(block_name=name, status="ERROR", detail=str(error),
fingerprint=fingerprint.sha256, timestamp=_now(), block_type=block_type) fingerprint=fingerprint, timestamp=_now(), block_type=block_type)
if server is not None: if server is not None:
try: try:
server.restart() server.restart()
except BridgeUnavailable: except BridgeUnavailable:
pass pass
check_active()
checkpoint.append(checkpoint_path, record) checkpoint.append(checkpoint_path, record)
results.append(record) results.append(record)
if record.status == "UNAVAILABLE" and index + 1 < len(names): if record.status == "UNAVAILABLE" and index + 1 < len(names):
@@ -276,7 +283,7 @@ class BatchStatusSession:
for remaining in names[index + 1:]: for remaining in names[index + 1:]:
unavailable_record = BatchStatusRecord( unavailable_record = BatchStatusRecord(
block_name=remaining, status=record.status, detail=record.detail, block_name=remaining, status=record.status, detail=record.detail,
fingerprint=fingerprint.sha256, timestamp=_now(), fingerprint=fingerprint, timestamp=_now(),
block_type=block_type, block_type=block_type,
) )
checkpoint.append(checkpoint_path, unavailable_record) checkpoint.append(checkpoint_path, unavailable_record)
@@ -291,7 +298,7 @@ class BatchStatusSession:
return results return results
def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_path: Path, def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_path: Path | None = None,
*, bridge_path: Path | None = None, *, bridge_path: Path | None = None,
timeout_seconds: float = 10.0) -> dict[str, str]: timeout_seconds: float = 10.0) -> dict[str, str]:
"""Return only bridge-backed statuses for an optional UI integration. """Return only bridge-backed statuses for an optional UI integration.
@@ -463,6 +463,7 @@ def check_target_window(job, pcb_pid, *, emit, error_reader, launcher_process=No
if not session.pcb_alive(): if not session.pcb_alive():
raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence') raise RuntimeError('DIAGNOSTIC_OPEN_UNCONFIRMED: target PCB exited before loaded evidence')
windows = scan(deadline) windows = scan(deadline)
_cancel(job)
if any(window['pid'] != int(pcb_pid) for window in windows): if any(window['pid'] != int(pcb_pid) for window in windows):
raise RuntimeError('DIAGNOSTIC_PID_MISMATCH') raise RuntimeError('DIAGNOSTIC_PID_MISMATCH')
frame = _target_frame(windows, Path(job['pcb']).stem, require_ready=False) frame = _target_frame(windows, Path(job['pcb']).stem, require_ready=False)
+6 -2
View File
@@ -100,9 +100,10 @@ class DialogBackend(Protocol):
class AgentDialogBackend: class AgentDialogBackend:
"""Adapt the private-desktop JSONL client to the supervisor backend.""" """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.client = client
self.pids = pids self.pids = pids
self.before_action = before_action
def observe(self, phase: DialogPhase): def observe(self, phase: DialogPhase):
if self.pids is None: 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) 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: 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( return self.client.perform(
hwnd=snapshot.hwnd, hwnd=snapshot.hwnd,
fingerprint=stable_fingerprint(snapshot), fingerprint=stable_fingerprint(snapshot),
@@ -123,7 +125,7 @@ class Win32DialogBackend:
"""Observe and act on dialogs without moving focus, cursor, or desktop.""" """Observe and act on dialogs without moving focus, cursor, or desktop."""
def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None, def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None,
win32con=None) -> None: win32con=None, before_action=None) -> None:
if win32gui is None: if win32gui is None:
import win32gui as win32gui_module import win32gui as win32gui_module
win32gui = win32gui_module win32gui = win32gui_module
@@ -138,6 +140,7 @@ class Win32DialogBackend:
self.win32gui = win32gui self.win32gui = win32gui
self.win32process = win32process self.win32process = win32process
self.win32con = win32con self.win32con = win32con
self.before_action = before_action
def _allowed_pids(self) -> set[int]: def _allowed_pids(self) -> set[int]:
values = self.pids() if callable(self.pids) else self.pids values = self.pids() if callable(self.pids) else self.pids
@@ -256,6 +259,7 @@ class Win32DialogBackend:
return control.control_id return control.control_id
def perform(self, snapshot: DialogSnapshot, action: str) -> tuple[int, ...]: 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) buttons = self._buttons(snapshot)
positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load", positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load",
"是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载") "是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载")
+164 -6
View File
@@ -43,7 +43,21 @@ def _cancel_target(snapshot):
from .post_repair_consent import exact_prompt from .post_repair_consent import exact_prompt
from .dialog_rules import pcb_version_choice from .dialog_rules import pcb_version_choice
if exact_prompt(snapshot): if exact_prompt(snapshot):
return 'read_write_access', next(c for c in snapshot.controls if c.control_id == 7) no = next((c for c in snapshot.controls if c.class_name == 'Button'
and c.control_id == 7 and c.enabled), None)
return ('read_write_access', no) if no is not None else None
text = ' '.join(' '.join(c.name for c in snapshot.controls
if c.class_name == 'Static').split())
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
if (snapshot.window_class == '#32770' and snapshot.title == 'Expedition PCB'
and text == ('Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed. '
'Do you wish to view the log file now?')
and {c.control_id for c in buttons} == {6, 7}
and len(buttons) == 2):
no = next(c for c in buttons if c.control_id == 7)
if no.enabled:
return 'database_load_log', no
if pcb_version_choice(snapshot) is not None: if pcb_version_choice(snapshot) is not None:
buttons = [c for c in snapshot.controls if c.class_name == 'Button'] buttons = [c for c in snapshot.controls if c.class_name == 'Button']
cancel = [c for c in buttons if c.control_id == 2 and c.name == 'Cancel' and c.enabled] cancel = [c for c in buttons if c.control_id == 2 and c.name == 'Cancel' and c.enabled]
@@ -62,6 +76,112 @@ def _tip_target(snapshot):
return target if target is not None and target.class_name == 'Button' else None return target if target is not None and target.class_name == 'Button' else None
def _database_log_declined(root, pcb_pid):
"""The supervisor can dismiss this exact failed-open question before cleanup."""
from dataclasses import fields
from .dialog_models import WindowSnapshot
path = root/'dialogs.jsonl'
try:
if path.stat().st_size > 1024*1024:
return False
for line in path.read_text(encoding='utf-8').splitlines():
record = json.loads(line)
if (record.get('pid') != pcb_pid or record.get('phase') != 'PCB_STARTING'
or record.get('error_code') != 'MENTOR_DATABASE_LOAD_FAILED'
or record.get('action') != 'acknowledge_fatal'
or record.get('accepted_control') != [7]):
continue
snapshot = WindowSnapshot.from_record({f.name:record[f.name]
for f in fields(WindowSnapshot) if f.name in record})
target = _cancel_target(snapshot)
if target is not None and target[0] == 'database_load_log':
return True
except (OSError, ValueError, TypeError, KeyError):
pass
return False
def _read_write_declined(job, root, pcb_pid):
from .dialog_models import WindowSnapshot
from .session_record import IDENTITY_KEYS
choice_path = root/'pcb-open-user-choice.json'
dialogs_path = root/'dialogs.jsonl'
try:
if (choice_path.stat().st_size > 1024*1024 or dialogs_path.stat().st_size > 1024*1024
or not job.get('operation_id') or (root/'save.log').exists()):
return False
choice = json.loads(choice_path.read_text(encoding='utf-8'))
binding = {key: job[key] for key in ('operation_id', 'desktop', 'project', 'pcb')}
if (any(choice.get(key) != value for key, value in binding.items())
or choice.get('library') != job['lmc_file'] or choice.get('choice') not in ('skip', 'cancel')):
return False
owner = choice['owner']['target']
if (owner.get('pid') != pcb_pid or not owner.get('owner_sid')
or any(owner.get(key) is None for key in IDENTITY_KEYS)):
return False
original = choice['snapshot']
snapshot = WindowSnapshot.from_record(original)
target = _cancel_target(snapshot)
if snapshot.pid != pcb_pid or target is None or target[0] != 'read_write_access':
return False
expected = 'PCB_OPEN_SKIPPED' if choice['choice'] == 'skip' else 'USER_CANCELLED'
for line in dialogs_path.read_text(encoding='utf-8').splitlines():
record = json.loads(line)
if (record.get('action') == 'user_confirmed_pcb_open' and record.get('accepted_control') == [7]
and record.get('error_code') == expected
and all(record.get(key) == value for key, value in original.items())):
return owner
except (OSError, ValueError, TypeError, KeyError, AttributeError):
pass
return False
def cancelled_prewrite_startup(job, pcb_pid=None):
"""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, def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
timeout_seconds=None, launcher_process=None): timeout_seconds=None, launcher_process=None):
"""Normally close our empty PCB after a diagnosed database startup failure. """Normally close our empty PCB after a diagnosed database startup failure.
@@ -95,15 +215,18 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
and isinstance(job.get('diagnostic_log_baseline'), dict) and isinstance(job.get('diagnostic_log_baseline'), dict)
and {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys() and {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys()
and not (root/'save.log').exists()) 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 # Diagnostic close already owns a 30-second cleanup budget. Start it
# once here; the empty-to-loaded transition never resets that deadline. # once here; the empty-to-loaded transition never resets that deadline.
if timeout_seconds is None: if timeout_seconds is None:
timeout_seconds = 30 if cancelled_diagnostic else 20 timeout_seconds = 30 if cancelled_diagnostic or cancelled_prewrite else 20
deadline = time.monotonic() + max(0, timeout_seconds) deadline = time.monotonic() + max(0, timeout_seconds)
sent = False sent = False
declined_hwnd = None declined_hwnd = None
declined_kind = None declined_kind = None
cancelled_open = False cancelled_open = _database_log_declined(root, pcb_pid)
decline_owner = None
dismissed_tips = set() dismissed_tips = set()
close_handle = None close_handle = None
close_identity = None close_identity = None
@@ -111,12 +234,24 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
diagnostic_state = {'clicked': set()} diagnostic_state = {'clicked': set()}
def cleanup_post(hwnd, message): def cleanup_post(hwnd, message):
if (time.monotonic() >= deadline or _current_desktop_name() != desktop 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 win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_TIMEOUT
or residual_sessions._handle_identity(close_handle) != close_identity or residual_sessions._handle_identity(close_handle) != close_identity
or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid): or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid):
raise ValueError('STARTUP_ACTION_UNCONFIRMED') raise ValueError('STARTUP_ACTION_UNCONFIRMED')
if decline_owner:
actual = {'pid': pcb_pid, **close_identity,
**residual_sessions._force_ownership(close_handle, pcb_pid)}
if any(actual.get(key) != value for key, value in decline_owner.items()):
raise ValueError('STARTUP_ACTION_UNCONFIRMED: 原进程身份变化')
win32gui.PostMessage(hwnd, message, 0, 0) win32gui.PostMessage(hwnd, message, 0, 0)
while True: while True:
# PCB can dismiss the prompt before the supervisor records its action.
if not cancelled_open:
decline_owner = _read_write_declined(job, root, pcb_pid)
if decline_owner:
cancelled_open = True
result['cancelled_prompt'] = 'read_write_access'
records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid] records = [r for r in _process_details('ExpeditionPCB.exe') if r[0] == pcb_pid]
if not records: if not records:
if (close_handle is not None if (close_handle is not None
@@ -134,6 +269,8 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited, result['release'] = {'pcb_exited': True, 'launcher_exited': launcher_exited,
'addresses': addresses, 'addresses': addresses,
'safe_to_continue': launcher_exited and (cancelled_open or not addresses)} 'safe_to_continue': launcher_exited and (cancelled_open or not addresses)}
if addresses:
result['release']['resource_release_confirmed'] = False
if result['release']['safe_to_continue']: if result['release']['safe_to_continue']:
result['status'] = 'CLOSED' result['status'] = 'CLOSED'
result.pop('detail', None) result.pop('detail', None)
@@ -150,19 +287,31 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
or '-reusablecircuit' not in [a.casefold() for a in args] 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:]]): or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
raise ValueError('STARTUP_PROCESS_UNCONFIRMED') raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
if cancelled_diagnostic and time.monotonic() < deadline: 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: if close_handle is None:
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid)) close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
close_identity = residual_sessions._handle_identity(close_handle) close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe': if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED') raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
from .diagnostic_open import cancelled_startup_step 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, acted = cancelled_startup_step(job, pcb_pid, diagnostic_state,
closed_frame=close_frame, deadline=deadline, post=cleanup_post, emit=emit) 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: if closed is not None and not sent:
sent, close_frame = True, closed sent, close_frame = True, closed
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=closed, emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=closed,
document_identity='native_path_pid_logs', cleanup='cancelled_diagnostic') document_identity='native_path_pid_logs',
cleanup='cancelled_prewrite' if cancelled_prewrite else 'cancelled_diagnostic')
if acted: if acted:
continue continue
if not sent: if not sent:
@@ -187,6 +336,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
current = _startup_snapshot(hwnd, pcb_pid) current = _startup_snapshot(hwnd, pcb_pid)
if current != snapshot or _tip_target(current) != target: if current != snapshot or _tip_target(current) != target:
raise ValueError('STARTUP_TIP_CHANGED') 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) win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0)
dismissed_tips.add(hwnd) dismissed_tips.add(hwnd)
dismissed = True dismissed = True
@@ -207,6 +359,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
if _cancel_target(current) != target or current != snapshot: if _cancel_target(current) != target or current != snapshot:
raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED') raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED')
declined_kind, cancel = target declined_kind, cancel = target
if cancelled_diagnostic or cancelled_prewrite:
cleanup_post(cancel.handle,win32con.BM_CLICK)
else:
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0) win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
declined_hwnd = hwnd declined_hwnd = hwnd
emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd, emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd,
@@ -251,6 +406,9 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
close_identity = residual_sessions._handle_identity(close_handle) close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe': if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED') raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
if cancelled_diagnostic or cancelled_prewrite or decline_owner:
cleanup_post(main[0],win32con.WM_CLOSE)
else:
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0) win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
close_frame = main[0] close_frame = main[0]
sent = True sent = True
+8 -2
View File
@@ -41,6 +41,7 @@ def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None):
if record.get('token') != token or record.get('status') != 'HELD' or process.poll() is not None: if record.get('token') != token or record.get('status') != 'HELD' or process.poll() is not None:
error = OSError('FILE_PROBE_UNCONFIRMED: '+str(record.get('error', '探测身份或句柄失效'))) error = OSError('FILE_PROBE_UNCONFIRMED: '+str(record.get('error', '探测身份或句柄失效')))
error.winerror = record.get('winerror') error.winerror = record.get('winerror')
error.blocked_resources = record.get('blocked_resources', [])
raise error raise error
# Duplicate the already-open handles before acknowledging the probe. # Duplicate the already-open handles before acknowledging the probe.
# Its exit can never create a gap in the parent's commit protection. # Its exit can never create a gap in the parent's commit protection.
@@ -108,6 +109,7 @@ def file_probe_main(job):
job = Path(job) job = Path(job)
request = json.loads(job.read_text('utf-8')) request = json.loads(job.read_text('utf-8'))
result = {'token': request['token'], 'status': 'UNCONFIRMED'} result = {'token': request['token'], 'status': 'UNCONFIRMED'}
opening = None
try: try:
def checked_path(value): def checked_path(value):
path = Path(value).absolute() path = Path(value).absolute()
@@ -127,15 +129,18 @@ def file_probe_main(job):
with ExitStack() as stack: with ExitStack() as stack:
handles = [] handles = []
for path in snapshot['exclusive_files']: for path in snapshot['exclusive_files']:
opening = path
handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None, handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close) stack.callback(handle.Close)
handles.append(int(handle)) handles.append(int(handle))
for path in snapshot['binding_files']: for path in snapshot['binding_files']:
opening = path
handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ, handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ,
None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close) stack.callback(handle.Close)
handles.append(int(handle)) handles.append(int(handle))
opening = None
if _snapshot(library, roots) != snapshot: if _snapshot(library, roots) != snapshot:
raise ValueError('占用检查期间资源集合变化') raise ValueError('占用检查期间资源集合变化')
pending = job.with_name('result.pending') pending = job.with_name('result.pending')
@@ -145,7 +150,8 @@ def file_probe_main(job):
return 0 return 0
except Exception as error: except Exception as error:
pending = job.with_name('result.pending') pending = job.with_name('result.pending')
pending.write_text(json.dumps({**result, 'error': str(error), blocked = [opening] if opening and getattr(error, 'winerror', None) in (32,33) else []
'winerror': getattr(error, 'winerror', None)}), 'utf-8') pending.write_text(json.dumps({**result, 'error': (opening+': ' if opening else '')+str(error),
'winerror': getattr(error, 'winerror', None), 'blocked_resources': blocked}), 'utf-8')
pending.replace(job.with_name('result.json')) pending.replace(job.with_name('result.json'))
return 1 return 1
+2
View File
@@ -559,6 +559,7 @@ def _prove_library_released(library, block_name=None, *, block_names=(), allow_u
except OSError as error: except OSError as error:
blocked = LibraryBusy(str(error)) blocked = LibraryBusy(str(error))
blocked.winerror = getattr(error, 'winerror', None) blocked.winerror = getattr(error, 'winerror', None)
blocked.blocked_resources = getattr(error, 'blocked_resources', [])
raise blocked from error raise blocked from error
note_metadata_progress() note_metadata_progress()
if files['addresses']: if files['addresses']:
@@ -576,6 +577,7 @@ def _prove_library_released(library, block_name=None, *, block_names=(), allow_u
except OSError as error: except OSError as error:
blocked = LibraryBusy(str(error)) blocked = LibraryBusy(str(error))
blocked.winerror = getattr(error, 'winerror', None) blocked.winerror = getattr(error, 'winerror', None)
blocked.blocked_resources = getattr(error, 'blocked_resources', [])
raise blocked from error raise blocked from error
if any(current[key] != files[key] for key in ( if any(current[key] != files[key] for key in (
'exclusive_files', 'addresses', 'signatures', 'inspection_targets')): 'exclusive_files', 'addresses', 'signatures', 'inspection_targets')):
+28 -9
View File
@@ -171,7 +171,7 @@ def _may_have_mutated(record):
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None, version_prompt=None, def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None, version_prompt=None,
write_admission=None): write_admission=None):
from .verify_runner import VerifyRequest, run_verify from .verify_runner import VerifyRequest, run_verify, _notify_progress
from .backup_recovery import _idle_check from .backup_recovery import _idle_check
from contextlib import ExitStack from contextlib import ExitStack
from .operation_queue import check_active, native_channel, task_stop, remember_result from .operation_queue import check_active, native_channel, task_stop, remember_result
@@ -216,7 +216,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
_write_json(report, {**asdict(request), 'stage': stage, 'status': 'RUNNING', _write_json(report, {**asdict(request), 'stage': stage, 'status': 'RUNNING',
'safe_to_continue': False, 'history': history, 'backup_policy': 'manual'}) 'safe_to_continue': False, 'history': history, 'backup_policy': 'manual'})
if progress: if progress:
progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details}) _notify_progress(progress, {'stage': stage, 'block': request.name, 'operation': request.operation, **details})
def finish(status, detail='', safe=True): def finish(status, detail='', safe=True):
nonlocal change_report nonlocal change_report
remember_result(ManagementResult(request.operation, request.library, request.name, request.partition, remember_result(ManagementResult(request.operation, request.library, request.name, request.partition,
@@ -465,7 +465,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, context=None, **kwargs): def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, context=None, **kwargs):
from threading import Event from threading import Event
from .write_admission import WriteAdmission from .write_admission import WriteAdmission
from .operation_queue import QueueCancelled, TaskHandoff, request_library_keys, remember_result, current_context from .verify_runner import _notify_progress
from .operation_queue import QueueCancelled, QueueUnavailable, TaskHandoff, request_library_keys, remember_result, current_context
context = context or current_context() context = context or current_context()
if context is not None: if context is not None:
stop = stop if stop is not None else context.stop stop = stop if stop is not None else context.stop
@@ -474,19 +475,30 @@ def run_management_batch(requests, *, stop=None, progress=None, item_executor=No
stop = Event() stop = Event()
kwargs.setdefault('write_admission',WriteAdmission(prompt=kwargs.get('version_prompt'),stop=stop)) kwargs.setdefault('write_admission',WriteAdmission(prompt=kwargs.get('version_prompt'),stop=stop))
results = [] results = []
retained_libraries = set() retained_libraries = {}
cancelled = False cancelled = False
for request in requests: for request in requests:
keys = request_library_keys(request, context) keys = request_library_keys(request, context)
stopped = (cancelled or stop.is_set() or context is not None stopped = (cancelled or stop.is_set() or context is not None
and (context.stop.is_set() or context.stop_after_current.is_set())) and (context.stop.is_set() or context.stop_after_current.is_set()))
if not stopped:
for index in {retained_libraries[key][1] for key in keys.intersection(retained_libraries)}:
previous = next(value[0] for value in retained_libraries.values() if value[1] == index)
from .operation_lifecycle import recheck_failed_release
refreshed = recheck_failed_release(previous.library, previous.name, results[index], stop=stop)
if refreshed.safe_to_continue:
results[index] = refreshed
retained_libraries = {k:v for k,v in retained_libraries.items() if v[1] != index}
if stopped or keys.intersection(retained_libraries): if stopped or keys.intersection(retained_libraries):
previous = (retained_libraries[next(iter(keys.intersection(retained_libraries)))][0]
if not stopped else None)
result = ManagementResult(request.operation, request.library, request.name, request.partition, result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'complete', 'SKIPPED', True, request.source, request.auto_verify, 'admission', 'SKIPPED', True,
'队列已停止,未操作此 CBB' if stopped else '同库原生会话尚未释放,未启动新的写入') '队列已停止,未操作此 CBB' if stopped else
f'PREVIOUS_SESSION_UNRELEASED: 前项 {previous.name} 的同库会话尚未释放,当前项未启动。')
results.append(result) results.append(result)
if progress: if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail}) _notify_progress(progress, {'stage': result.status, 'block': result.name, 'detail': result.detail})
continue continue
def action(): def action():
result = run_management(request, progress=progress, stop=stop, **kwargs) result = run_management(request, progress=progress, stop=stop, **kwargs)
@@ -497,6 +509,9 @@ def run_management_batch(requests, *, stop=None, progress=None, item_executor=No
return result return result
try: try:
result = item_executor(request, action) if item_executor is not None else action() result = item_executor(request, action) if item_executor is not None else action()
except QueueUnavailable as error:
result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'admission', 'SKIPPED', True, str(error))
except QueueCancelled as error: except QueueCancelled as error:
known = error.result if isinstance(error, TaskHandoff) else None known = error.result if isinstance(error, TaskHandoff) else None
if isinstance(known, ManagementResult): if isinstance(known, ManagementResult):
@@ -510,12 +525,16 @@ def run_management_batch(requests, *, stop=None, progress=None, item_executor=No
request.source, request.auto_verify, 'complete', request.source, request.auto_verify, 'complete',
'TIMEOUT' if isinstance(error, TaskHandoff) and not error.cancelled else 'CANCELLED', 'TIMEOUT' if isinstance(error, TaskHandoff) and not error.cancelled else 'CANCELLED',
not isinstance(error, TaskHandoff), str(error)) not isinstance(error, TaskHandoff), str(error))
except Exception as error:
result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'exception', 'RECOVERY_REQUIRED', False,
'BATCH_ITEM_EXCEPTION: '+str(error))
results.append(result) results.append(result)
if progress: if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail, _notify_progress(progress, {'stage': result.status, 'block': result.name, 'detail': result.detail,
'evidence_path': str(result.evidence_path or '')}) 'evidence_path': str(result.evidence_path or '')})
if not result.safe_to_continue: if not result.safe_to_continue:
retained_libraries.update(keys) retained_libraries.update({key:(request, len(results)-1) for key in keys})
if result.status == 'CANCELLED': if result.status == 'CANCELLED':
cancelled = True cancelled = True
return results return results
+19 -1
View File
@@ -684,6 +684,11 @@ def execute_job(job, emit):
launcher_process = None launcher_process = None
completed = False completed = False
identity_verified = 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 diagnostic_close_attempted = False
helper = None helper = None
app = doc = pi = None app = doc = pi = None
@@ -706,6 +711,11 @@ def execute_job(job, emit):
for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])): for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])):
ensure_project_central_library(config, job['lmc_file'], ensure_project_central_library(config, job['lmc_file'],
evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit) evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit)
if 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( emit(
stage='verify_mode', stage='verify_mode',
mode=('library_manager_native' if bool(job.get('native_lm_verify', False)) mode=('library_manager_native' if bool(job.get('native_lm_verify', False))
@@ -810,6 +820,10 @@ def execute_job(job, emit):
# the old, working path acquires the token inside the SysWOW64 # the old, working path acquires the token inside the SysWOW64
# cscript save helper below. The PCB UI license dialog has already # cscript save helper below. The PCB UI license dialog has already
# been handled by the private-desktop supervisor. # 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( refresh_integration(
pi, pi,
emit=emit, emit=emit,
@@ -897,7 +911,7 @@ def execute_job(job, emit):
pass pass
if helper is not None and helper.poll() is None: if helper is not None and helper.poll() is None:
emit(stage='save_helper_retained', helper_pid=helper.pid) emit(stage='save_helper_retained', helper_pid=helper.pid)
elif helper is not None: elif helper is not None and not completed:
# A failed/truncated Save result never authorizes discard-close. # A failed/truncated Save result never authorizes discard-close.
emit(stage='save_result_retained', detail='保存或关闭结果不完整,保留原生会话供核对') emit(stage='save_result_retained', detail='保存或关闭结果不完整,保留原生会话供核对')
elif diagnostic_close_attempted: elif diagnostic_close_attempted:
@@ -915,6 +929,10 @@ def execute_job(job, emit):
elif not completed and worker_pid is not None: elif not completed and worker_pid is not None:
try: try:
from .failed_session import close_failed_startup 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, failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit,
launcher_process=launcher_process) launcher_process=launcher_process)
if failed_close.get('status') == 'CLOSED' and lm_session is not None: if failed_close.get('status') == 'CLOSED' and lm_session is not None:
+1 -1
View File
@@ -61,7 +61,7 @@ def native_backup_target(request, *, mode='versions', target_database=None):
values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"\s*$', _project_text(config), re.M) 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 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: if config == project or target_database is None:
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 主 PRJ 的 iCDBDir 未唯一绑定') raise ValueError('NATIVE_TARGET_UNCONFIRMED: 主 PRJ 的 iCDBDir 必须唯一且为工程内相对路径,不支持绝对路径或多条记录')
continue continue
database = (config.parent/values[0]).resolve() database = (config.parent/values[0]).resolve()
if not database.is_relative_to(project.parent.resolve()): if not database.is_relative_to(project.parent.resolve()):
+12 -5
View File
@@ -245,13 +245,17 @@ class NativeManagementAdapter:
if hasattr(worker, 'bind_session'): if hasattr(worker, 'bind_session'):
worker.bind_session(job) worker.bind_session(job)
from contextlib import nullcontext from contextlib import nullcontext
from .operation_queue import commit_worker_start, native_channel from .operation_queue import commit_worker_start, native_channel, task_stop
# Only admitted native waiting outlives the UI's metadata deadline. # Only admitted native waiting outlives the UI's metadata deadline.
channel = native_channel(read_only=True) if job.get('worker_role') == 'catalog_readonly' else nullcontext() read_only = job.get('worker_role') == 'catalog_readonly'
channel = native_channel(read_only=True) if read_only else nullcontext()
stop = task_stop(self.stop) if read_only else self.stop
cancelled = False
with channel: with channel:
commit_worker_start(worker, job) commit_worker_start(worker, job)
while worker.poll() is None and time.monotonic() < deadline: while worker.poll() is None and time.monotonic() < deadline:
if self.stop is not None and self.stop.is_set(): if stop is not None and stop.is_set():
cancelled = True
Path(job['cancel_signal']).touch() Path(job['cancel_signal']).touch()
break break
time.sleep(.1) time.sleep(.1)
@@ -268,8 +272,9 @@ class NativeManagementAdapter:
if self.session_progress is not None else None) if self.session_progress is not None else None)
if add_job: if add_job:
(evidence/'cancel-native-add.signal').touch() (evidence/'cancel-native-add.signal').touch()
reason = 'CANCELLED' if cancelled else 'TIMEOUT'
return {'success': False, 'safe_to_continue': False, return {'success': False, 'safe_to_continue': False,
'detail': f'TIMEOUT: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'} 'detail': f'{reason}: 原生调用尚未返回,保留私有桌面 {desktop},请检查 {evidence}'}
try: try:
result = json.loads((evidence/'result.json').read_text(encoding='utf-8')) result = json.loads((evidence/'result.json').read_text(encoding='utf-8'))
if not isinstance(result.get('safe_to_continue'), bool): if not isinstance(result.get('safe_to_continue'), bool):
@@ -1117,7 +1122,7 @@ def _catalog_com(job, root):
if name != job['desktop'] or not name.startswith('CbbManagement_'): if name != job['desktop'] or not name.startswith('CbbManagement_'):
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。') raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
if _process_details('LibraryManager.exe'): if _process_details('LibraryManager.exe'):
raise RuntimeError('已有 Library Manager 运行,请关闭后重试。') raise RuntimeError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行,请关闭后重试。')
except Exception as error: except Exception as error:
error.safe_to_continue = True error.safe_to_continue = True
raise raise
@@ -1217,6 +1222,8 @@ def _catalog_com(job, root):
for i in range(1, int(parts.Count) + 1): for i in range(1, int(parts.Count) + 1):
partition = parts.Item(i) partition = parts.Item(i)
for j in range(1, int(partition.Count) + 1): for j in range(1, int(partition.Count) + 1):
if job.get('worker_role') == 'catalog_readonly':
_require_management_continuation(job, root)
item = partition.Item(j) item = partition.Item(j)
block_name, partition_name = str(item.Name), str(item.PartitionName) block_name, partition_name = str(item.Name), str(item.PartitionName)
validate_name(block_name) validate_name(block_name)
+2
View File
@@ -336,6 +336,7 @@ def _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress,
worker.request_stop() worker.request_stop()
raise raise
finally: finally:
try:
if entered: if entered:
native.__exit__(None, None, None) native.__exit__(None, None, None)
if worker.poll() is None and getattr(worker, 'session_record_path', None): if worker.poll() is None and getattr(worker, 'session_record_path', None):
@@ -343,4 +344,5 @@ def _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress,
from .operation_queue import hold_native_handoff from .operation_queue import hold_native_handoff
handoff_session(worker.session_record_path, evidence_root=root, process=worker) handoff_session(worker.session_record_path, evidence_root=root, process=worker)
hold_native_handoff(worker, worker.session_record_path) hold_native_handoff(worker, worker.session_record_path)
finally:
worker.close() worker.close()
+17 -3
View File
@@ -6,13 +6,13 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
"""Refresh resource facts after a late exit; keep the original business failure.""" """Refresh resource facts after a late exit; keep the original business failure."""
if result.safe_to_continue or not result.evidence_path: if result.safe_to_continue or not result.evidence_path:
return result return result
from .operation_queue import BatchTaskContext, TaskHandoff, current_context, task_stop from .operation_queue import BatchTaskContext, QueueCancelled, current_context, task_stop
if current_context() is None: if current_context() is None:
context = BatchTaskContext(library=str(library), targets=(block,)) context = BatchTaskContext(library=str(library), targets=(block,))
try: try:
return context.run(lambda: recheck_failed_release(library, block, result, stop=stop), return context.run(lambda: recheck_failed_release(library, block, result, stop=stop),
stop=stop, timeout_seconds=timeout_seconds) stop=stop, timeout_seconds=timeout_seconds)
except TaskHandoff: except QueueCancelled:
return result return result
stop = task_stop(stop) stop = task_stop(stop)
from pathlib import Path from pathlib import Path
@@ -27,6 +27,9 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
record = read_session_record(session, evidence_root=evidence.parent) record = read_session_record(session, evidence_root=evidence.parent)
if record.get('block') != block or Path(record.get('library', '')).resolve() != Path(library).resolve(): if record.get('block') != block or Path(record.get('library', '')).resolve() != Path(library).resolve():
return result return result
if inspect_session_record(session, evidence_root=evidence.parent).get('status') == 'ACTIVE':
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': if inspect_session_record(session, evidence_root=evidence.parent).get('status') == 'ACTIVE':
return result return result
else: else:
@@ -41,6 +44,9 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
owned = read_session_record(candidate, evidence_root=evidence.parent) owned = read_session_record(candidate, evidence_root=evidence.parent)
if Path(owned.get('library', '')).resolve() != Path(library).resolve(): if Path(owned.get('library', '')).resolve() != Path(library).resolve():
return result return result
if inspect_session_record(candidate, evidence_root=evidence.parent).get('status') == 'ACTIVE':
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': if inspect_session_record(candidate, evidence_root=evidence.parent).get('status') == 'ACTIVE':
return result return result
bound.append(candidate) bound.append(candidate)
@@ -60,7 +66,15 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
business_status=result.status, safe_to_continue=True, release_proof=proof), business_status=result.status, safe_to_continue=True, release_proof=proof),
ensure_ascii=False, default=str, indent=2), 'utf-8') ensure_ascii=False, default=str, indent=2), 'utf-8')
return replace(result, safe_to_continue=True, release_proof=proof) return replace(result, safe_to_continue=True, release_proof=proof)
except Exception: except Exception as error:
try:
evidence.with_name('late-release-attempt.json').write_text(json.dumps(dict(
business_status=result.status, safe_to_continue=False,
status='IN_USE' if getattr(error,'winerror',None) in (32,33) else 'UNCONFIRMED',
library=str(library), block=block, detail=str(error),
blocked_resources=getattr(error,'blocked_resources',[])),ensure_ascii=False,indent=2),'utf-8')
except OSError:
pass
return result return result
+42 -6
View File
@@ -11,6 +11,14 @@ class QueueCancelled(RuntimeError):
pass 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): class TaskHandoff(QueueCancelled):
"""The call is still observable; this is never a release receipt.""" """The call is still observable; this is never a release receipt."""
def __init__(self, context, *, cancelled=False, result=None): def __init__(self, context, *, cancelled=False, result=None):
@@ -68,6 +76,7 @@ class _Call:
done: Event = field(default_factory=Event) done: Event = field(default_factory=Event)
abandoned: bool = False abandoned: bool = False
native_depth: int = 0 native_depth: int = 0
commit_depth: int = 0
readonly_depth: int = 0 readonly_depth: int = 0
supervised_depth: int = 0 supervised_depth: int = 0
worker_sessions: list = field(default_factory=list) worker_sessions: list = field(default_factory=list)
@@ -175,6 +184,25 @@ def hold_native_handoff(process, session_record_path):
raise TaskHandoff(call.context, cancelled=call.handoff_cancelled, result=call.last_result) 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 @contextmanager
def native_phase(*, read_only=False, supervised=False): def native_phase(*, read_only=False, supervised=False):
"""Never abandon a transaction between native writes (including Remove/Add).""" """Never abandon a transaction between native writes (including Remove/Add)."""
@@ -266,7 +294,7 @@ class BatchTaskContext:
'CANCELLED' if self.stop.is_set() else 'CANCELLED' if self.stop.is_set() else
'HANDED_OFF' if any(c.abandoned for c in calls) else 'HANDED_OFF' if any(c.abandoned for c in calls) else
'RUNNING' if pending else 'IDLE', pending=pending, 'RUNNING' if pending else 'IDLE', pending=pending,
pending_native=any(c.native_depth for c in calls)) pending_native=any(c.native_depth or c.commit_depth for c in calls))
def shutdown(self): def shutdown(self):
"""Yield UI supervision, never a native worker's write/lease ownership. """Yield UI supervision, never a native worker's write/lease ownership.
@@ -285,7 +313,7 @@ class BatchTaskContext:
call.supervised_depth == call.native_depth and call.supervised_depth == call.native_depth and
all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only', 'catalog_readonly') all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only', 'catalog_readonly')
for s in call.worker_sessions)) for s in call.worker_sessions))
if not call.native_depth or readonly or external: if not call.commit_depth and (not call.native_depth or readonly or external):
call.shutdown_handoff = call.abandoned = True call.shutdown_handoff = call.abandoned = True
return {**self.snapshot(), 'safe_to_continue': False, return {**self.snapshot(), 'safe_to_continue': False,
'shutdown_handoff': all(c.shutdown_handoff for c in calls), 'shutdown_handoff': all(c.shutdown_handoff for c in calls),
@@ -319,7 +347,7 @@ class BatchTaskContext:
call.done.wait(max(0, deadline-time.monotonic())) call.done.wait(max(0, deadline-time.monotonic()))
with _tasks_guard: with _tasks_guard:
for call in calls: for call in calls:
if not call.done.is_set() and not call.native_depth: if not call.done.is_set() and not call.native_depth and not call.commit_depth:
call.abandoned = True call.abandoned = True
return self.snapshot() return self.snapshot()
@@ -357,7 +385,7 @@ class BatchTaskContext:
call.abandoned = True call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result) raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
elapsed = time.monotonic()-call.phase_started elapsed = time.monotonic()-call.phase_started
if not call.native_depth and (call.abandoned or elapsed >= timeout_seconds): if not call.native_depth and not call.commit_depth and (call.abandoned or elapsed >= timeout_seconds):
cancelled = call.is_set() cancelled = call.is_set()
call.abandoned = True call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result) raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
@@ -389,14 +417,19 @@ class NativeQueue:
for context in contexts) for context in contexts)
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None, def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None,
context=None, timeout_seconds=10): context=None, timeout_seconds=10, skip_unavailable=False):
def available_now(): def available_now():
if not ready(): if not ready():
return False return False
if context is None: if context is None:
return True # Explicit recovery controls must still reach their retained clients. return True # Explicit recovery controls must still reach their retained clients.
from .session_record import _live_library_available from .session_record import _live_library_available
return all(_live_library_available(path) for path in (context.library, *context.aliases)) for path in (context.library, *context.aliases):
if not _live_library_available(path):
if skip_unavailable:
raise QueueUnavailable(path)
return False
return True
ticket = [object(), False] ticket = [object(), False]
acquired, notified = False, False acquired, notified = False, False
previous_state = None previous_state = None
@@ -408,6 +441,9 @@ class NativeQueue:
self.pending.append(ticket) self.pending.append(ticket)
try: try:
while not acquired: while not acquired:
if (self.closed or stop is not None and stop.is_set()
or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())):
raise QueueCancelled('已取消排队,未启动原生操作。')
available = available_now() # Cached predicates only, outside the queue lock. available = available_now() # Cached predicates only, outside the queue lock.
with self.condition: with self.condition:
if (self.closed or stop is not None and stop.is_set() if (self.closed or stop is not None and stop.is_set()
+96 -34
View File
@@ -1,6 +1,7 @@
"""Explicit user answers to the owned PCB's exact read/write question.""" """Bound authorization for the owned PCB's exact read/write question."""
from contextlib import contextmanager, ExitStack from contextlib import contextmanager, ExitStack
from pathlib import Path from pathlib import Path, PureWindowsPath
import re
from threading import Lock from threading import Lock
import time import time
@@ -15,8 +16,9 @@ def _prompt_identity(snapshot):
class OpenChoice: class OpenChoice:
def __init__(self, block, library): def __init__(self, block, library, *, auto_confirm=False):
self.block, self.library = block, library self.block, self.library = block, library
self.auto_confirm = auto_confirm
self.decision = None self.decision = None
self.decision_origin = None self.decision_origin = None
self._lock = Lock() self._lock = Lock()
@@ -26,8 +28,8 @@ class OpenChoice:
raise ValueError('无效的打开工程选择') raise ValueError('无效的打开工程选择')
with self._lock: with self._lock:
if self.decision is None: if self.decision is None:
self.decision = decision
self.decision_origin = origin self.decision_origin = origin
self.decision = decision
def validate_owner(job, target_pid, launcher_pid, worker_pid): def validate_owner(job, target_pid, launcher_pid, worker_pid):
@@ -47,14 +49,14 @@ def validate_owner(job, target_pid, launcher_pid, worker_pid):
@contextmanager @contextmanager
def resource_guard(job, allowed_pids): def resource_guard(job, allowed_pids, *, require_complete_proof=False):
import hashlib import hashlib
from .file_probe import hold_release_files from .file_probe import hold_release_files
from .maintenance_entry import maintenance_project_files from .maintenance_entry import maintenance_project_files
from .native_repair import RepairTarget, run_native_repair from .native_repair import RepairTarget, run_native_repair
from .native_occupancy import confirmed_inspection from .native_occupancy import confirmed_inspection
from .session_record import IDENTITY_KEYS from .session_record import IDENTITY_KEYS
from .operation_queue import task_stop from .operation_queue import check_active, task_stop
from .management import _write_json from .management import _write_json
from .owner_probe import query_process_snapshot from .owner_probe import query_process_snapshot
from .library_lock import _owner_is_blocking from .library_lock import _owner_is_blocking
@@ -72,15 +74,43 @@ def resource_guard(job, allowed_pids):
for row in query_process_snapshot(): for row in query_process_snapshot():
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots): if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。') raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
check_active()
check() check()
stop = task_stop(None) stop = task_stop(None)
with ExitStack() as stack: with ExitStack() as stack:
files = stack.enter_context(hold_release_files(library, roots, stop=stop)) files = stack.enter_context(hold_release_files(library, roots, stop=stop))
inspections = [] inspections = []
if require_complete_proof:
from .backup_recovery import _project_text
references = re.findall(r'^KEY ProjectFile "([^"]+)"', _project_text(pcb), re.M)
if len(references) != 1 or (pcb.parent/references[0]).resolve() != project.resolve():
raise ValueError(f'PCB_OPEN_PROJECT_CHANGED: PCB 未唯一关联当前工程:{pcb}')
required_files = {library.resolve(), (pcb.parent/'Layout/LayoutDB.lyt').resolve()}
for config in configs:
text = _project_text(config)
references = re.findall(r'^KEY iCDBDir\b.*$', text, re.M)
if not references and config != project:
continue
reference = re.fullmatch(r'KEY iCDBDir "([^"]+)"\s*', references[0]) if len(references) == 1 else None
if reference is None or PureWindowsPath(reference[1]).anchor:
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: iCDBDir 必须唯一且为相对路径:{config}')
database = (config.parent/reference[1]).resolve()
if not database.is_relative_to(project.parent.resolve()):
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: iCDBDir 越出工程:{database}')
required_files.add(database/'icdb.dat')
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb'
if shared.exists():
required_files.add((shared/'icdb.dat').resolve())
missing = required_files - {Path(path).resolve() for path in files['exclusive_files']}
if missing:
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 缺少文件占用证明:'
+ '、'.join(str(path) for path in sorted(missing)))
if files['addresses']: if files['addresses']:
targets = files['inspection_targets'] targets = files['inspection_targets']
if any(Path(item['project']).resolve() not in {p.resolve() for p in configs} for item in targets): for item in targets:
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置,需人工核对') if Path(item['project']).resolve() not in {p.resolve() for p in configs}:
raise ValueError(f"PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置:{item['database']}")
stack.close() # Native inspection must access the DB; repeat exact proof afterwards. stack.close() # Native inspection must access the DB; repeat exact proof afterwards.
for index, item in enumerate(targets): for index, item in enumerate(targets):
target = RepairTarget(Path(item['project']), Path(item['database'])) target = RepairTarget(Path(item['project']), Path(item['database']))
@@ -88,11 +118,15 @@ def resource_guard(job, allowed_pids):
result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'), result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'),
timeout_seconds=min(45, float(job.get('timeout', 45))), inspection_only=True, stop=stop) timeout_seconds=min(45, float(job.get('timeout', 45))), inspection_only=True, stop=stop)
identity = result.get('native_identity') or {} identity = result.get('native_identity') or {}
if (not confirmed_inspection(target, result) or result['status'] != 'NOT_IN_USE' if (not confirmed_inspection(target, result)
or identity.get('pid') != result.get('native_pid') or identity.get('pid') != result.get('native_pid')
or any(identity.get(key) is None for key in IDENTITY_KEYS) or any(identity.get(key) is None for key in IDENTITY_KEYS)
or not identity.get('image') or not identity.get('owner_sid')): or not identity.get('image') or not identity.get('owner_sid')):
raise ValueError('PCB_OPEN_DATABASE_UNCONFIRMED: 原生检查未确认当前数据库未占用') raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: 原生占用检查无法确认:{target.database}')
if result['status'] == 'IN_USE':
raise ValueError(f'PCB_OPEN_DATABASE_IN_USE: 原生检查确认数据库占用:{target.database}')
if require_complete_proof and result['repair_required']:
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: 原生检查提示需要维护:{target.database}')
inspections.append(result) inspections.append(result)
current = stack.enter_context(hold_release_files(library, roots, stop=stop)) current = stack.enter_context(hold_release_files(library, roots, stop=stop))
if any(current[key] != files[key] for key in ( if any(current[key] != files[key] for key in (
@@ -101,6 +135,7 @@ def resource_guard(job, allowed_pids):
if binding() != original_binding: if binding() != original_binding:
raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化') raise ValueError('PCB_OPEN_PROJECT_CHANGED: 原生检查期间工程引用变化')
check() check()
check_active()
_write_json(Path(job['root'])/'pcb-open-resource-proof.json', { _write_json(Path(job['root'])/'pcb-open-resource-proof.json', {
'operation_id': job.get('operation_id'), 'library': str(library), 'operation_id': job.get('operation_id'), 'library': str(library),
'project': str(project), 'pcb': str(pcb), 'binding': original_binding, 'project': str(project), 'pcb': str(pcb), 'binding': original_binding,
@@ -110,8 +145,10 @@ def resource_guard(job, allowed_pids):
class OpenController: class OpenController:
def __init__(self, job): def __init__(self, job, *, auto_confirm=False, require_complete_proof=False):
self.job = job self.job = job
self.auto_confirm = auto_confirm
self.require_complete_proof = require_complete_proof or auto_confirm
self.choice = None self.choice = None
self.original = self.owner = None self.original = self.owner = None
self.sent = False self.sent = False
@@ -120,14 +157,21 @@ class OpenController:
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, show, perform): def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, show, perform):
from .dialog_supervisor import DialogPollResult from .dialog_supervisor import DialogPollResult
from .management import _write_json from .management import _write_json
from .operation_queue import QueueCancelled, check_active
try: try:
if not exact_prompt(snapshot) or snapshot.pid != target_pid or len(snapshots) != 1: if not exact_prompt(snapshot) or snapshot.pid != target_pid or len(snapshots) != 1:
raise ValueError('PCB_OPEN_PROMPT_CHANGED') raise ValueError('PCB_OPEN_PROMPT_CHANGED')
owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid) owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid)
if self.choice is None: if self.choice is None:
self.owner, self.original = owner, snapshot self.owner, self.original = owner, snapshot
self.choice = OpenChoice(self.job['block_name'], self.job['lmc_file']) self.choice = OpenChoice(self.job['block_name'], self.job['lmc_file'],
auto_confirm=self.auto_confirm)
if show is not None:
show(self.choice) show(self.choice)
elif self.auto_confirm:
self.choice.choose('continue', origin='headless_opt_in')
else:
raise ValueError('PCB_OPEN_CONFIRMATION_REQUIRED')
if (owner != self.owner or snapshot.hwnd != self.original.hwnd if (owner != self.owner or snapshot.hwnd != self.original.hwnd
or _prompt_identity(snapshot) != _prompt_identity(self.original)): or _prompt_identity(snapshot) != _prompt_identity(self.original)):
raise ValueError('PCB_OPEN_IDENTITY_CHANGED') raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
@@ -137,36 +181,54 @@ class OpenController:
raise ValueError('PCB_OPEN_ANSWER_NOT_COMPLETED') raise ValueError('PCB_OPEN_ANSWER_NOT_COMPLETED')
if self.choice.decision is None: if self.choice.decision is None:
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots)) return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
control = 6 if self.choice.decision == 'continue' else 7 decision = self.choice.decision
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'], origin = self.choice.decision_origin
'target': {'control_id': control}, 'desktop': self.job['desktop'], skipped_detail = ('超时默认跳过本项。' if origin == 'timeout_default' else '用户跳过本项。')
'pid': target_pid, 'owner': owner, 'choice': self.choice.decision} if decision == 'continue':
action['decision_origin'] = self.choice.decision_origin
def send():
_write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict(
choice=self.choice.decision, decision_origin=self.choice.decision_origin,
project=self.job['project'], pcb=self.job['pcb'],
library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record()))
self.sent, self.sent_at = True, time.monotonic()
return perform(snapshot, action, snapshot.phase)
if control == 6:
allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')} allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')}
with resource_guard(self.job, allowed): try:
guard = (resource_guard(self.job, allowed, require_complete_proof=True) if self.require_complete_proof
else resource_guard(self.job, allowed))
with guard:
pass pass
# Deliberate TOCTOU tradeoff: release probes before Yes so Mentor # Mentor needs the handles released before Yes. Recheck the
# can acquire the files without a sharing violation; recheck identity. # owner here and the actual window in the private agent.
check_active()
except QueueCancelled:
decision, skipped_detail = 'cancel', '校验已取消。'
except Exception as error:
if not self.require_complete_proof:
raise
decision, skipped_detail = 'skip', str(error)
if validate_owner(self.job, target_pid, launcher_pid, worker_pid) != owner: if validate_owner(self.job, target_pid, launcher_pid, worker_pid) != owner:
raise ValueError('PCB_OPEN_IDENTITY_CHANGED') raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
result = send() if decision == 'continue':
else: try:
result = send() check_active()
except QueueCancelled:
decision, skipped_detail = 'cancel', '校验已取消。'
control = 6 if decision == 'continue' else 7
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'],
'target': {'control_id': control}, 'desktop': self.job['desktop'],
'pid': target_pid, 'owner': owner, 'choice': decision, 'decision_origin': origin}
_write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict(
choice=decision, decision_origin=origin, detail=skipped_detail if control == 7 else '',
operation_id=self.job.get('operation_id'), desktop=self.job['desktop'],
project=self.job['project'], pcb=self.job['pcb'],
library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record()))
if control == 6:
try:
check_active()
except QueueCancelled:
return DialogPollResult(error_code='USER_CANCELLED', detail='校验已取消。',
snapshot=snapshot, observed_snapshots=tuple(snapshots))
self.sent, self.sent_at = True, time.monotonic()
result = perform(snapshot, action, snapshot.phase)
error = result.error_code error = result.error_code
if not error and result.accepted_controls != (control,): if not error and result.accepted_controls != (control,):
error = 'PCB_OPEN_ANSWER_FAILED' error = 'PCB_OPEN_ANSWER_FAILED'
if not error and control == 7: if not error and control == 7:
error = 'PCB_OPEN_SKIPPED' if self.choice.decision == 'skip' else 'USER_CANCELLED' error = 'PCB_OPEN_SKIPPED' if decision == 'skip' else 'USER_CANCELLED'
skipped_detail = ('超时默认跳过本项。' if self.choice.decision_origin == 'timeout_default'
else '用户跳过本项。')
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot, return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
error_code=error, detail=result.detail or (skipped_detail if control == 7 else ''), error_code=error, detail=result.detail or (skipped_detail if control == 7 else ''),
accepted_controls=result.accepted_controls, channel=result.channel, accepted_controls=result.accepted_controls, channel=result.channel,
+199 -6
View File
@@ -600,7 +600,7 @@ def _cancelled_diagnostic_record(row):
operation = session['operation_id'] operation = session['operation_id']
scope = session.get('resource_scope', {}) scope = session.get('resource_scope', {})
if (record.get('operation_id') != operation or job.get('operation_id') != operation if (record.get('operation_id') != operation or job.get('operation_id') != operation
or job.get('diagnostic_only') is not True or job.get('interactive_input') is not False 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 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 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 not same(job['root'], root) or not same(job['session_record_path'], path)
@@ -644,8 +644,18 @@ def _cancelled_diagnostic_record(row):
continue continue
if any(r.get('operation_id') != operation for r in active_write_records(row['library'])): if any(r.get('operation_id') != operation for r in active_write_records(row['library'])):
continue 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, matches.append(dict(job=job, record_path=str(path), operation_id=operation,
closed_frame=closes[0]['hwnd'] if closes else None)) 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): except (OSError, pywintypes.error, ValueError, KeyError, TypeError):
continue continue
return matches[0] if len(matches) == 1 else None return matches[0] if len(matches) == 1 else None
@@ -674,12 +684,12 @@ def _legacy_diagnostic_windows(row):
return result return result
def _close_registered_startup(row, handle, proof, *, stop=None): def _close_registered_startup(row, handle, proof, *, stop=None, deadline=None):
import pywintypes, win32con, win32event import pywintypes, win32con, win32event
from .diagnostic_open import cancelled_startup_step from .diagnostic_open import cancelled_startup_step
from .operation_queue import check_active from .operation_queue import check_active
job = proof['job']; bound = dict(row, cleanup_desktop=job['desktop']) job = proof['job']; bound = dict(row, cleanup_desktop=job['desktop'])
deadline = time.monotonic()+30 # One diagnostic cleanup intent; ordinary close still uses 3 seconds. if deadline is None:deadline = time.monotonic()+30
def active_owner(): def active_owner():
check_active() check_active()
if stop is not None and stop.is_set(): if stop is not None and stop.is_set():
@@ -698,7 +708,13 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
if not active_owner() or time.monotonic() >= deadline: if not active_owner() or time.monotonic() >= deadline:
raise ValueError('STARTUP_ACTION_UNCONFIRMED') raise ValueError('STARTUP_ACTION_UNCONFIRMED')
_post_window_message({'desktop':job['desktop']}, hwnd, row['pid'], message) _post_window_message({'desktop':job['desktop']}, hwnd, row['pid'], message)
state = {'clicked':set()}; closed = proof['closed_frame']; dismissed_tips = set() 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: try:
while time.monotonic() < deadline: while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0: if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
@@ -726,7 +742,7 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
break # Never stack another Close after a legacy Tip acknowledgement. break # Never stack another Close after a legacy Tip acknowledgement.
try: try:
closed,_ = cancelled_startup_step(job,row['pid'],state,closed_frame=closed,deadline=deadline, closed,_ = cancelled_startup_step(job,row['pid'],state,closed_frame=closed,deadline=deadline,
post=post,emit=lambda **event:None,read_windows=lambda:_legacy_diagnostic_windows(bound), post=post,emit=lambda **event:None,read_windows=read_bound_windows,
identity_check=confirmed) identity_check=confirmed)
except RuntimeError as error: except RuntimeError as error:
if not str(error).startswith('STARTUP_WINDOW_CHANGED:'): if not str(error).startswith('STARTUP_WINDOW_CHANGED:'):
@@ -739,6 +755,181 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
return {'release_status':'WAITING','detail':'已请求取消启动清理,等待原生退出后重新检查'} 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): def _request_close(row, *, stop=None):
import win32con, win32event import win32con, win32event
with _process_handle(row['pid']) as handle: with _process_handle(row['pid']) as handle:
@@ -763,6 +954,8 @@ def _request_close(row, *, stop=None):
from .session_record import handoff_session from .session_record import handoff_session
record_path = Path(proof['record_path']) record_path = Path(proof['record_path'])
handoff_session(record_path, evidence_root=record_path.parent, observe_only=False) 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 from .operation_queue import native_phase
# This confirmed no-write native cleanup has its own single bounded # This confirmed no-write native cleanup has its own single bounded
# budget; metadata inactivity must not abandon it between No and Close. # budget; metadata inactivity must not abandon it between No and Close.
+20 -8
View File
@@ -1,6 +1,6 @@
Option Explicit Option Explicit
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK, remaining Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK, remaining
Dim nativeError, nativeDescription Dim nativeError, nativeDescription, actualProject, actualDocument, expectedDocument, savedState
WaitForStartGate WaitForStartGate
CheckCancellation CheckCancellation
expected = WScript.Arguments(0) expected = WScript.Arguments(0)
@@ -79,13 +79,25 @@ If Not stable Then
WScript.Quit 7 WScript.Quit 7
End If End If
WScript.Echo "POST_SAVE_SYNCHRONIZED" WScript.Echo "POST_SAVE_SYNCHRONIZED"
On Error Resume Next expectedDocument = ""
operationOK = doc.IsSaved() And LCase(pi.ProjectFile) = LCase(expected) If WScript.Arguments.Count > 1 Then expectedDocument = WScript.Arguments(1)
If WScript.Arguments.Count > 1 Then operationOK = operationOK And LCase(doc.Name) = LCase(WScript.Arguments(1)) For attempt = 1 To 10
nativeError = Err.Number On Error Resume Next
nativeDescription = Err.Description savedState = doc.IsSaved()
Err.Clear actualProject = pi.ProjectFile
On Error GoTo 0 actualDocument = ""
If expectedDocument <> "" Then actualDocument = doc.Name
nativeError = Err.Number
nativeDescription = Err.Description
Err.Clear
On Error GoTo 0
WScript.Echo "POST_SAVE_IDENTITY|project=" & actualProject & "|expected=" & expected & "|document=" & actualDocument & "|expected_document=" & expectedDocument
WScript.Echo "POST_SAVE_STATE|saved=" & CStr(savedState) & "|attempt=" & CStr(attempt) & "|error=" & CStr(nativeError)
operationOK = savedState And LCase(actualProject) = LCase(expected) And LCase(actualDocument) = LCase(expectedDocument)
If operationOK Or nativeError <> 0 Then Exit For
If LCase(actualProject) <> LCase(expected) Or LCase(actualDocument) <> LCase(expectedDocument) Then Exit For
WScript.Sleep 200
Next
If nativeError <> 0 Or Not operationOK Then If nativeError <> 0 Or Not operationOK Then
WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|identity_or_saved_state_unconfirmed|" & nativeDescription WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|identity_or_saved_state_unconfirmed|" & nativeDescription
WScript.Quit 8 WScript.Quit 8
+6 -8
View File
@@ -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 generated categories are ignored by semantic comparisons; they are still copied
and their membership/size/mtime must remain stable throughout the snapshot. and their membership/size/mtime must remain stable throughout the snapshot.
""" """
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack from contextlib import ExitStack
from dataclasses import asdict, dataclass from dataclasses import asdict, dataclass
import hashlib import hashlib
@@ -252,8 +251,8 @@ def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_functi
files = {} files = {}
hashed_bytes = 0 hashed_bytes = 0
_emit(progress, 'hash', 0, 0, total_files=len(selected)) _emit(progress, 'hash', 0, 0, total_files=len(selected))
with ThreadPoolExecutor(max_workers=8) as pool: # Stay on the bounded task thread: executor workers are joined at interpreter exit.
for count, (relative, item) in enumerate(pool.map(hashed, selected), 1): for count, (relative, item) in enumerate(map(hashed, selected), 1):
note_metadata_progress() note_metadata_progress()
files[relative] = item files[relative] = item
hashed_bytes += item['size'] hashed_bytes += item['size']
@@ -332,7 +331,7 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
destination.mkdir(parents=True, exist_ok=False) destination.mkdir(parents=True, exist_ok=False)
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)] files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
from .library_lock import owned_snapshot 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 owned = {path: data for path in files
if path.name.endswith('.cbb-upload.lock') if path.name.endswith('.cbb-upload.lock')
and (data := owned_snapshot(path)) is not None} and (data := owned_snapshot(path)) is not None}
@@ -390,8 +389,7 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
raise OSError(f'复制期间文件变化:{path}') raise OSError(f'复制期间文件变化:{path}')
return relative.as_posix(), digest, label return relative.as_posix(), digest, label
with ThreadPoolExecutor(max_workers=8) as pool: for count, (relative, digest, label) in enumerate(map(copy_file, files), 1):
for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1):
note_metadata_progress() note_metadata_progress()
if label is not None: if label is not None:
size = entries[source/relative].st_size size = entries[source/relative].st_size
@@ -409,8 +407,8 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
raise OSError(f'复制期间主要文件内容变化:{path}') raise OSError(f'复制期间主要文件内容变化:{path}')
if hash_function(destination/relative) != item['sha256']: if hash_function(destination/relative) != item['sha256']:
raise OSError(f'复制内容校验失败:{path}') raise OSError(f'复制内容校验失败:{path}')
with ThreadPoolExecutor(max_workers=8) as pool: for relative in record:
for _ in pool.map(validate_bytes, record): validate_bytes(relative)
note_metadata_progress() note_metadata_progress()
if _metadata_record(source, scan_tree(source)) != expected_metadata: if _metadata_record(source, scan_tree(source)) != expected_metadata:
raise OSError(f'复制期间目录内容变化:{source}') raise OSError(f'复制期间目录内容变化:{source}')
+10 -1
View File
@@ -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 contextlib import ExitStack
from datetime import datetime, timezone from datetime import datetime, timezone
import json import json
@@ -407,6 +407,15 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
session={'library': str(process.cbb_library)}, proof=proof) session={'library': str(process.cbb_library)}, proof=proof)
except Exception: except Exception:
pass pass
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: if result['status'] == 'IDENTITY_CHANGED' and not observation_only:
try: try:
from .library_lock import release_retained_library from .library_lock import release_retained_library
@@ -113,13 +113,17 @@ class BackupRecoveryDialog(QDialog):
options = {'version_prompt': lambda choice:self._emit(context, 'choice',choice),'stop':context.stop} if self.recoverer is None else {} options = {'version_prompt': lambda choice:self._emit(context, 'choice',choice),'stop':context.stop} if self.recoverer is None else {}
action = lambda: recoverer(request, source, progress=lambda event:self._emit(context, 'progress',event), **options) action = lambda: recoverer(request, source, progress=lambda event:self._emit(context, 'progress',event), **options)
if self.native_queue is None: return context.run(action) if self.native_queue is None: return context.run(action)
from ..operation_queue import QueueCancelled from ..operation_queue import QueueCancelled, QueueUnavailable
def restore(): def restore():
self._emit(context, 'progress',{'stage': 'queue_acquired'}) self._emit(context, 'progress',{'stage': 'queue_acquired'})
return action() return action()
try: try:
return self.native_queue.run(restore, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress', return self.native_queue.run(restore, stop=context.stop, context=context, skip_unavailable=True, waiting=lambda: self._emit(context, 'progress',
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'})) {'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}))
except QueueUnavailable as error:
from ..verify_runner import VerifyResult
return VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
error_stage='admission')
except QueueCancelled as error: except QueueCancelled as error:
from ..operation_queue import TaskHandoff from ..operation_queue import TaskHandoff
from ..verify_runner import VerifyResult, _handoff_verify_result from ..verify_runner import VerifyResult, _handoff_verify_result
+21 -7
View File
@@ -1,7 +1,7 @@
"""A check batch owns its snapshot and yields the native queue after each CBB.""" """A check batch owns its snapshot and yields the native queue after each CBB."""
from PySide6.QtCore import QObject, QThreadPool, Signal from PySide6.QtCore import QObject, QThreadPool, Signal
from .workers import ServiceWorker from .workers import ServiceWorker
from ..operation_queue import QueueCancelled, BatchTaskContext from ..operation_queue import QueueCancelled, QueueUnavailable, BatchTaskContext, request_library_keys
from ..verify_runner import VerifyResult, run_verify, write_batch_report from ..verify_runner import VerifyResult, run_verify, write_batch_report
from ..icdb_maintenance import write_maintenance_report from ..icdb_maintenance import write_maintenance_report
@@ -30,7 +30,7 @@ class IcdbCheckTask(QObject):
self.running = False self.running = False
self.report = None self.report = None
self.report_error = '' self.report_error = ''
self.retained_libraries = set() self.retained_libraries = {}
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1) self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
def _emit_event(self, event): def _emit_event(self, event):
@@ -66,9 +66,6 @@ class IcdbCheckTask(QObject):
if self.stop.is_set(): if self.stop.is_set():
self.results.extend(VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB') self.results.extend(VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
for _ in self.requests[len(self.results):]) for _ in self.requests[len(self.results):])
while len(self.results) < len(self.requests) and str(
self.requests[len(self.results)].lmc_file).casefold() in self.retained_libraries:
self.results.append(VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的检查'))
if len(self.results) == len(self.requests): if len(self.results) == len(self.requests):
self._report(); return self._report(); return
if self.paused: return if self.paused: return
@@ -76,6 +73,19 @@ class IcdbCheckTask(QObject):
def check(): def check():
from ..session_record import library_available, library_wait_reason from ..session_record import library_available, library_wait_reason
try: try:
keys = request_library_keys(request, self.context)
for index in {self.retained_libraries[key] for key in keys.intersection(self.retained_libraries)}:
previous = self.requests[index]
from ..operation_lifecycle import recheck_failed_release
refreshed = recheck_failed_release(previous.lmc_file, previous.block_name,
self.results[index], stop=self.stop)
if refreshed.safe_to_continue:
self.results[index] = refreshed
self.retained_libraries = {k:v for k,v in self.retained_libraries.items() if v != index}
if keys.intersection(self.retained_libraries):
index = self.retained_libraries[next(iter(keys.intersection(self.retained_libraries)))]
return VerifyResult('SKIPPED', error_category='PREVIOUS_SESSION_UNRELEASED',
error_stage='admission', stderr=f'前项 {self.requests[index].block_name} 的同库会话尚未释放,当前项未启动。')
def execute(): def execute():
if self.status_reader is not None: if self.status_reader is not None:
statuses = self.status_reader((request.block_name,), request.lmc_file) statuses = self.status_reader((request.block_name,), request.lmc_file)
@@ -92,12 +102,15 @@ class IcdbCheckTask(QObject):
from ..operation_lifecycle import recheck_failed_release from ..operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.lmc_file, request.block_name, result) result = recheck_failed_release(request.lmc_file, request.block_name, result)
return result return result
return self.queue.run(execute, stop=self.stop, context=self.context, return self.queue.run(execute, stop=self.stop, context=self.context, skip_unavailable=True,
wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)), wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)),
ready=lambda: not self.paused, ready=lambda: not self.paused,
waiting=lambda: self._emit_event({'stage': 'waiting_native_slot', 'block': request.block_name, waiting=lambda: self._emit_event({'stage': 'waiting_native_slot', 'block': request.block_name,
'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file), 'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file),
'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'})) 'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'}))
except QueueUnavailable as error:
return VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
error_stage='admission')
except QueueCancelled as error: except QueueCancelled as error:
from ..operation_queue import TaskHandoff from ..operation_queue import TaskHandoff
from ..verify_runner import _handoff_verify_result from ..verify_runner import _handoff_verify_result
@@ -116,7 +129,8 @@ class IcdbCheckTask(QObject):
request = self.requests[len(self.results)] request = self.requests[len(self.results)]
name = request.block_name name = request.block_name
if not result.safe_to_continue: if not result.safe_to_continue:
self.retained_libraries.add(str(request.lmc_file).casefold()) self.retained_libraries.update({key:len(self.results)
for key in request_library_keys(request, self.context)})
self.results.append(result) self.results.append(result)
if result.status in ('CANCELLED', 'QUEUE_STOP'): self.stop.set() if result.status in ('CANCELLED', 'QUEUE_STOP'): self.stop.set()
self.item_done.emit(name, result) self.item_done.emit(name, result)
+182 -40
View File
@@ -11,11 +11,11 @@ import json
from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled, TaskHandoff from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled, TaskHandoff
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt, QTimer from PySide6.QtCore import QObject, QThreadPool, Signal, Qt, QTimer
from PySide6.QtGui import QColor, QIcon from PySide6.QtGui import QColor, QIcon, QTextCursor
from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout, from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton, QTextEdit, QFileDialog, QHBoxLayout, QLabel, QSpinBox, QMessageBox, QToolButton,
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox, QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
QTabBar, QStackedWidget, QSizePolicy) QTabBar, QStackedWidget, QSizePolicy, QDialog, QDialogButtonBox, QPlainTextEdit)
from PySide6.QtWidgets import QStyle from PySide6.QtWidgets import QStyle
@@ -123,6 +123,7 @@ class MainWindow(QWidget):
self._dialogs = [] self._dialogs = []
self._current_job = None self._current_job = None
self._stale_table = False self._stale_table = False
self._table_library_path = None
self._read_counts = (None, None, None) self._read_counts = (None, None, None)
self._diagnostic_evidence = {} self._diagnostic_evidence = {}
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8) self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8)
@@ -154,8 +155,7 @@ class MainWindow(QWidget):
self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set() self.busy = False; self.loaded_path = None; self.stop = Event(); self.ready_names = set()
self._row_by_name = {} self._row_by_name = {}
self._records_by_name = {} self._records_by_name = {}
self.status_refresher = status_refresher or (lambda names, path: authoritative_status_map( self.status_refresher = status_refresher or authoritative_status_map
names, path, self.data_root / 'status-refresh.jsonl'))
self.skipped_names = set(); self.skip_reasons = {} self.skipped_names = set(); self.skip_reasons = {}
self._global_icdb_run = False self._global_icdb_run = False
self._icdb_completed = 0 self._icdb_completed = 0
@@ -176,6 +176,9 @@ class MainWindow(QWidget):
self.native_lm_verify_check.setChecked(native_lm_verify_enabled()) self.native_lm_verify_check.setChecked(native_lm_verify_enabled())
self.native_lm_verify_check.setToolTip( self.native_lm_verify_check.setToolTip(
'仅在 Win10 兼容测试时启用;默认仍使用已验证的 ReusableCircuit 直接流程。') '仅在 Win10 兼容测试时启用;默认仍使用已验证的 ReusableCircuit 直接流程。')
self.auto_confirm_pcb_open_check = QCheckBox('无人应答时自动核验 PCB 读写占用')
self.auto_confirm_pcb_open_check.setChecked(True)
self.auto_confirm_pcb_open_check.setToolTip('普通校验中,3 秒后检查占用,确认可写后继续。关闭后默认跳过本项。')
self.advanced_toggle = QToolButton(); self.advanced_toggle.setText('高级设置') self.advanced_toggle = QToolButton(); self.advanced_toggle.setText('高级设置')
self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton)) self.advanced_toggle.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_TitleBarUnshadeButton))
self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False) self.advanced_toggle.setCheckable(True); self.advanced_toggle.setChecked(False)
@@ -185,10 +188,12 @@ class MainWindow(QWidget):
advanced_layout.addRow('DMS 登录配置', self.dms_edit) advanced_layout.addRow('DMS 登录配置', self.dms_edit)
advanced_layout.addRow('Mentor bin', self.mentor_bin_edit) advanced_layout.addRow('Mentor bin', self.mentor_bin_edit)
advanced_layout.addRow('触发方式', self.native_lm_verify_check) advanced_layout.addRow('触发方式', self.native_lm_verify_check)
advanced_layout.addRow('读写确认', self.auto_confirm_pcb_open_check)
self.advanced_panel.setVisible(False) self.advanced_panel.setVisible(False)
self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible) self.advanced_toggle.toggled.connect(self.advanced_panel.setVisible)
self.cbb_table = QTableWidget(0, 4) self.cbb_table = QTableWidget(0, 4)
self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '备注']) self.cbb_table.setHorizontalHeaderLabels(['CBB 名称', '分区', '状态', '备注(双击查看)'])
self.cbb_table.cellDoubleClicked.connect(self._show_result_detail)
self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch) self.cbb_table.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
self.cbb_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch) self.cbb_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
for column in (1, 2): for column in (1, 2):
@@ -349,6 +354,7 @@ class MainWindow(QWidget):
self._update() self._update()
def _invalidate(self): def _invalidate(self):
self._cancel_catalog_read()
if self._current_job is not None and self._current_job.kind == 'read': if self._current_job is not None and self._current_job.kind == 'read':
self._current_job.context.close(timeout_seconds=0) self._current_job.context.close(timeout_seconds=0)
self._view_revision += 1 self._view_revision += 1
@@ -407,6 +413,7 @@ class MainWindow(QWidget):
elif not any(other.lease is job.lease for other in self._jobs.values()): elif not any(other.lease is job.lease for other in self._jobs.values()):
self._close_path_lease(job.lease) self._close_path_lease(job.lease)
if self._job_current(job): self._finished() if self._job_current(job): self._finished()
else: self._update()
def _release_library_lease(self): def _release_library_lease(self):
lease, self.library_lease = self.library_lease, None lease, self.library_lease = self.library_lease, None
@@ -509,8 +516,8 @@ class MainWindow(QWidget):
'请选择一个当前可见的非 READY CBB。' if native_target is None else '') '请选择一个当前可见的非 READY CBB。' if native_target is None else '')
self.native_repair_button.setToolTip(reason or '打开原生工具;请在其中手动选择 Repair。') self.native_repair_button.setToolTip(reason or '打开原生工具;请在其中手动选择 Repair。')
ready = ready and not self._native_backup_same_library() ready = ready and not self._native_backup_same_library()
self.batch_button.setEnabled(ready and bool(self._eligible_names())) self.batch_button.setEnabled(ready and bool(self._eligible_names(require_status=True)))
self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True))) self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True, require_status=True)))
self.icdb_repair_button.setEnabled(ready and not self._icdb_active() and bool(self._maintenance_names())) self.icdb_repair_button.setEnabled(ready and not self._icdb_active() and bool(self._maintenance_names()))
self.icdb_stop_button.setEnabled(self._icdb_active() and not self.icdb_task.stop.is_set()) self.icdb_stop_button.setEnabled(self._icdb_active() and not self.icdb_task.stop.is_set())
self.backup_restore_button.setEnabled(ready and bool( self.backup_restore_button.setEnabled(ready and bool(
@@ -540,15 +547,18 @@ class MainWindow(QWidget):
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
notice = ('上次操作结果待复查,执行前将重新检查占用。' notice = ('上次操作结果待复查,执行前将重新检查占用。'
if self._management_library_unsafe(current_library) else '') if self._management_library_unsafe(current_library) else '')
notice = '旧表已失效,请重新读取中心库。' if self._stale_table else notice notice = '当前显示上次读取结果(已失效)· 请重新读取中心库。' if self._stale_table else notice
self.library_notice.setText(notice) self.library_notice.setText(notice)
self.library_notice.setVisible(bool(notice)) self.library_notice.setVisible(bool(notice))
for widget in (self.lmc_edit, self.browse_button, self.load_button, for widget in (self.lmc_edit, self.browse_button, self.load_button,
self.timeout_spin, self.advanced_toggle, self.advanced_panel): self.timeout_spin, self.advanced_toggle, self.advanced_panel):
widget.setEnabled(not self._closing) widget.setEnabled(not self._closing)
counts = self.visible_counts() counts = self.visible_counts()
unknown = sum(r.status == 'UNKNOWN' for r in self.visible_records())
pending = sum(r.status == 'PENDING' for r in self.visible_records())
self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · ' self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · '
f'READY {counts["ready"]} · 异常/待确认 {counts["error"]}') f'READY {counts["ready"]} · 待验证 {pending} · 待读取 {unknown} · '
f'异常 {counts["error"]}')
directory, native, missing = self._read_counts directory, native, missing = self._read_counts
if directory is not None: if directory is not None:
self.counts_label.setText(self.counts_label.text() + self.counts_label.setText(self.counts_label.text() +
@@ -956,12 +966,13 @@ class MainWindow(QWidget):
def visible_counts(self): def visible_counts(self):
records = self.visible_records() records = self.visible_records()
return {'visible': len(records), 'ready': sum(r.status == 'READY' for r in records), return {'visible': len(records), 'ready': sum(r.status == 'READY' for r in records),
'error': sum(r.status not in {'READY', 'PENDING'} or r.name in self.skipped_names 'error': sum(r.status not in {'READY', 'PENDING', 'UNKNOWN'} or r.name in self.skipped_names
for r in records)} for r in records)}
def _eligible_names(self, *, checked_only=False): def _eligible_names(self, *, checked_only=False, require_status=False):
records = self.selected_records() if checked_only else self.visible_records() records = self.selected_records() if checked_only else self.visible_records()
return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names] return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names
and (not require_status or self.catalog_reader is None or r.status == 'PENDING')]
def _maintenance_names(self): def _maintenance_names(self):
records = self.selected_records() or self.visible_records() records = self.selected_records() or self.visible_records()
@@ -1030,7 +1041,8 @@ class MainWindow(QWidget):
if isinstance(error, TaskHandoff) and job.lease is not None: if isinstance(error, TaskHandoff) and job.lease is not None:
self._retain_path_lease(job.lease) self._retain_path_lease(job.lease)
if not self._job_current(job): return if not self._job_current(job): return
if isinstance(error, QueueCancelled): self._display_error(error) if isinstance(error, QueueCancelled):
self._display_error('已取消读取中心库。' if job.kind == 'read' else error)
else: self._failed(error) else: self._failed(error)
self.worker.signals.failed.connect(failed) self.worker.signals.failed.connect(failed)
self.worker.signals.finished.connect(lambda: (self._lifecycle_workers.discard(worker), self._finish_job(job))) self.worker.signals.finished.connect(lambda: (self._lifecycle_workers.discard(worker), self._finish_job(job)))
@@ -1054,7 +1066,7 @@ class MainWindow(QWidget):
event['detail'] = label+'中…' event['detail'] = label+'中…'
emit(event) emit(event)
return action() return action()
return lambda: self.native_queue.run(execute, stop=stop, context=job.context if job else None, return lambda: self.native_queue.run(execute, stop=stop, context=job.context if job else None, skip_unavailable=True,
wait_state=lambda: library_wait_reason(library), wait_state=lambda: library_wait_reason(library),
waiting=lambda: emit({'stage': 'waiting_native_slot', waiting=lambda: emit({'stage': 'waiting_native_slot',
'library': str(library), 'retained': not library_available(library), 'library': str(library), 'retained': not library_available(library),
@@ -1111,6 +1123,7 @@ class MainWindow(QWidget):
self._current_job = previous_job self._current_job = previous_job
self._jobs.pop(job.context.operation_id, None) self._jobs.pop(job.context.operation_id, None)
job.context = task.context job.context = task.context
self.stop = task.stop
self._jobs[job.context.operation_id] = job self._jobs[job.context.operation_id] = job
task.ui_job = job task.ui_job = job
task.revision = self._view_revision task.revision = self._view_revision
@@ -1247,10 +1260,17 @@ class MainWindow(QWidget):
self._bind_summary_action(summary, action, recover) self._bind_summary_action(summary, action, recover)
summary.show(); self._update() summary.show(); self._update()
def _cancel_catalog_read(self):
for job in self._jobs.values():
if job.kind == 'catalog':
job.context.cancel()
self.native_queue.wake()
def load_library(self): def load_library(self):
if self._closing or not self.lmc_edit.text(): return if self._closing or not self.lmc_edit.text(): return
if (self._current_job is not None and self._current_job.kind == 'read' if (self._current_job is not None and self._current_job.kind == 'read'
and self._current_job.active and self._current_job.revision == self._view_revision): return and self._current_job.active and self._current_job.revision == self._view_revision): return
self._cancel_catalog_read()
self._view_revision += 1 self._view_revision += 1
self._diagnostic_evidence.clear() self._diagnostic_evidence.clear()
self._stale_table = bool(self._records_by_name) self._stale_table = bool(self._records_by_name)
@@ -1269,6 +1289,7 @@ class MainWindow(QWidget):
self._release_library_lease() self._release_library_lease()
self.loaded_path = None self.loaded_path = None
path = self.lmc_edit.text() path = self.lmc_edit.text()
preserve = self._table_library_path == path and self._read_counts[1] is not None
self.status_label.setText('正在读取中心库…') self.status_label.setText('正在读取中心库…')
def read(): def read():
import pythoncom import pythoncom
@@ -1290,9 +1311,6 @@ class MainWindow(QWidget):
recovery_view = False recovery_view = False
result = self.reader(mentor_path) result = self.reader(mentor_path)
job.context.check_active() job.context.check_active()
if not result.error:
self._publish_check_statuses(mentor_path,
{record.name: record.status for record in result.records}, lease)
if self.logging_context: if self.logging_context:
statuses = Counter(record.status for record in result.records) statuses = Counter(record.status for record in result.records)
unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}] unknown = [record.name for record in result.records if record.status in {'UNKNOWN', 'UNAVAILABLE'}]
@@ -1317,15 +1335,24 @@ class MainWindow(QWidget):
if path != self.lmc_edit.text() or job.revision != self._view_revision: if path != self.lmc_edit.text() or job.revision != self._view_revision:
self._close_path_lease(lease) self._close_path_lease(lease)
return return
if result.error: if result.error or (job.active and job.context.stop.is_set()):
self._close_path_lease(lease) self._close_path_lease(lease)
self.status_label.setText(result.error); return self.status_label.setText(result.error or '已取消读取中心库。')
return
self.library_lease = lease self.library_lease = lease
self.mentor_lmc_path = mentor_path
if preserve and self.catalog_reader is not None and not result.catalog_verified:
self._start_catalog(job, result, lease, mentor_path, loaded)
return
if result.catalog_verified or self.catalog_reader is None:
self._publish_check_statuses(mentor_path,
{record.name: record.status for record in result.records
if record.catalog_source != 'directory_only'}, lease)
self._stale_table = False self._stale_table = False
self._table_library_path = path
self._read_counts = (result.directory_count, result.native_count, self._read_counts = (result.directory_count, result.native_count,
result.missing_project_count if result.missing_project_count is not None else len(skip_reasons)) result.missing_project_count if result.missing_project_count is not None else len(skip_reasons))
self._maintenance_recovery_view = recovery_view self._maintenance_recovery_view = recovery_view
self.mentor_lmc_path = mentor_path
self.loaded_path = path self.loaded_path = path
try: try:
if self._settings_enabled: if self._settings_enabled:
@@ -1406,18 +1433,41 @@ class MainWindow(QWidget):
job = SimpleNamespace(context=context, kind='catalog', revision=read_job.revision, job = SimpleNamespace(context=context, kind='catalog', revision=read_job.revision,
lease=lease, requests=(), records={}, active=True, keep_session=False) lease=lease, requests=(), records={}, active=True, keep_session=False)
self._jobs[context.operation_id] = job self._jobs[context.operation_id] = job
def reconcile(): root = self.data_root/'catalog'/context.operation_id
catalog = self.catalog_reader(Path(library), self.data_root/'catalog'/context.operation_id) checkpoint = root/'status-refresh.pending.jsonl' if self.status_refresher is authoritative_status_map else None
started = time.monotonic()
def phase(stage, detail):
if self.logging_context:
self.logging_context.logger.info('%s library=%s elapsed_ms=%d detail=%s', stage,
library, int((time.monotonic()-started)*1000), detail)
try:
self.signals.event.emit((read_job.revision, read_job, {
'stage': stage, 'detail': detail, 'library': str(library),
'catalog_id': context.operation_id,
}))
except RuntimeError:
pass # A closed Qt receiver cannot change the scan outcome.
def reconcile(evidence):
phase('catalog_start', '正在读取 Mentor 原生目录…')
catalog = self.catalog_reader(Path(library), evidence)
if _path_key(catalog.library) != _path_key(library) or not catalog.safe_to_continue or catalog.flow != 1: if _path_key(catalog.library) != _path_key(library) or not catalog.safe_to_continue or catalog.flow != 1:
raise ValueError('CATALOG_UNCONFIRMED: 原生目录身份或退出未确认。') raise ValueError('CATALOG_UNCONFIRMED: 原生目录身份或退出未确认。')
native = {entry.name: entry for entry in catalog.entries if entry.partition == 'Logical-Physical'} native = {entry.name: entry for entry in catalog.entries if entry.partition == 'Logical-Physical'}
directories = {record.name: record for record in initial.records} directories = {record.name: record for record in initial.records}
names = tuple(sorted(native.keys() | directories.keys())) names = tuple(sorted(native.keys() | directories.keys()))
try: context.check_active()
phase('catalog_status', f'正在核对 {len(native)} 项原生状态…')
if checkpoint is None:
statuses = self.status_refresher(tuple(native), Path(library)) statuses = self.status_refresher(tuple(native), Path(library))
except Exception: else:
statuses = {name:'UNAVAILABLE' for name in native} statuses = self.status_refresher(tuple(native), Path(library), checkpoint)
self._publish_check_statuses(library, statuses, lease) if native and (not native.keys() <= statuses.keys()
or any(statuses[name] == 'UNAVAILABLE' for name in native)
or not any(statuses[name] in {'READY', 'PENDING'} for name in native)):
raise ValueError('原生状态读取未确认,请重新读取中心库。')
context.check_active()
records, reasons = [], {} records, reasons = [], {}
for name in names: for name in names:
source = ('both' if name in native and name in directories else source = ('both' if name in native and name in directories else
@@ -1434,13 +1484,63 @@ class MainWindow(QWidget):
result = LibraryReadResult(tuple(records), directory_count=len(directories), native_count=len(native), result = LibraryReadResult(tuple(records), directory_count=len(directories), native_count=len(native),
missing_project_count=sum(name in native for name in reasons), catalog_verified=True) missing_project_count=sum(name in native for name in reasons), catalog_verified=True)
return result, reasons, lease, library, False return result, reasons, lease, library, False
worker = ServiceWorker(lambda:self.native_queue.run(reconcile, context=context))
def attempt(evidence):
return self.native_queue.run(lambda: reconcile(evidence), context=context,
timeout_seconds=120, skip_unavailable=True)
def scan():
from cbb_refresh_verify.native_management import NativeOperationError
from cbb_refresh_verify.owner_probe import query_owners
try:
return attempt(root)
except NativeOperationError as error:
if not error.safe_to_continue or not str(error).startswith('LIBRARY_MANAGER_BUSY:'):
raise
phase('catalog_waiting', 'Library Manager 正在使用,退出后将自动重试读取。')
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
context.check_active()
owners = query_owners(('LibraryManager.exe',), timeout_seconds=2)
context.check_active()
if not owners:
return attempt(root/'retry')
context.stop.wait(1)
context.check_active()
raise
self.status_label.setText('正在读取 Mentor 原生目录…')
worker = ServiceWorker(scan)
self._lifecycle_workers.add(worker) self._lifecycle_workers.add(worker)
def completed(payload):
if self._job_current(read_job): deliver(payload)
def failed(error): def failed(error):
if self._job_current(read_job): from cbb_refresh_verify.native_management import NativeOperationError
self.status_label.setText(f'目录已显示;原生目录未确认:{error}')
if isinstance(error, TaskHandoff) or (isinstance(error, NativeOperationError)
and not error.safe_to_continue):
self._retain_path_lease(lease)
if not self._job_current(read_job):
return
cancelled = context.stop.is_set() or isinstance(error, QueueCancelled)
detail = '已取消读取中心库。' if cancelled else f'原生目录未确认,请重新读取:{error}'
phase('catalog_cancelled' if cancelled else 'catalog_failed', detail)
self.status_label.setText(detail)
def completed(payload):
if not self._job_current(read_job):
return
if context.stop.is_set():
failed(QueueCancelled('读取已取消'))
return
try:
if checkpoint is not None:
checkpoint.replace(self.data_root/'status-refresh.jsonl')
except OSError as error:
failed(error)
return
deliver(payload)
phase('catalog_done', f'已读取 {len(payload[0].records)} 项。')
worker.signals.succeeded.connect(completed) worker.signals.succeeded.connect(completed)
worker.signals.failed.connect(failed) worker.signals.failed.connect(failed)
worker.signals.finished.connect(lambda:(self._lifecycle_workers.discard(worker),self._finish_job(job))) worker.signals.finished.connect(lambda:(self._lifecycle_workers.discard(worker),self._finish_job(job)))
@@ -1479,10 +1579,10 @@ class MainWindow(QWidget):
return [record.name for record in self.selected_records()] return [record.name for record in self.selected_records()]
def verify_selected(self): def verify_selected(self):
self._confirm_verify(self._eligible_names(checked_only=True)) self._confirm_verify(self._eligible_names(checked_only=True, require_status=True))
def verify_all(self): def verify_all(self):
self._confirm_verify(self._eligible_names()) self._confirm_verify(self._eligible_names(require_status=True))
def _confirm_verify(self, names): def _confirm_verify(self, names):
from .backup_notice import MANUAL_BACKUP_NOTICE from .backup_notice import MANUAL_BACKUP_NOTICE
@@ -1708,7 +1808,7 @@ class MainWindow(QWidget):
if self._native_backup_same_library(): if self._native_backup_same_library():
self.status_label.setText('请先关闭该库的版本与备份窗口。') self.status_label.setText('请先关闭该库的版本与备份窗口。')
return return
eligible = set(self._maintenance_names() if maintenance else self._eligible_names()) eligible = set(self._eligible_names(require_status=True))
names = [name for name in names if name in eligible] names = [name for name in names if name in eligible]
if not names: if not names:
self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。') self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。')
@@ -1717,6 +1817,8 @@ class MainWindow(QWidget):
requests = ([request for request in request_snapshot if request.block_name in names] if request_snapshot is not None requests = ([request for request in request_snapshot if request.block_name in names] if request_snapshot is not None
else [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names]) else [replace(self._request(name), maintenance=maintenance, auto_repair=False) for name in names])
if not requests: return if not requests: return
auto_confirm = self.auto_confirm_pcb_open_check.isChecked()
requests = [replace(request, auto_confirm_pcb_open=auto_confirm) for request in requests]
library = requests[0].lmc_file library = requests[0].lmc_file
if any(job.active and job.kind == 'verify' and job.requests == tuple(requests) if any(job.active and job.kind == 'verify' and job.requests == tuple(requests)
and _path_key(job.context.library) == _path_key(library) for job in self._jobs.values()): return and _path_key(job.context.library) == _path_key(library) for job in self._jobs.values()): return
@@ -1743,7 +1845,8 @@ class MainWindow(QWidget):
def action(): def action():
from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify from cbb_refresh_verify.verify_runner import read_library_flag_if_available, run_verify
verify = self.verifier or (lambda req: run_verify( verify = self.verifier or (lambda req: run_verify(
req, progress=lambda e: self._emit_job(job, 'event', e), req,
progress=lambda e: self._emit_job(job, 'event', e),
flag_reader=read_library_flag_if_available, flag_reader=read_library_flag_if_available,
version_prompt=lambda choice: self._emit_job(job, 'version_choice', choice), stop=job.context.stop)) version_prompt=lambda choice: self._emit_job(job, 'version_choice', choice), stop=job.context.stop))
def verifier(req): def verifier(req):
@@ -1756,6 +1859,10 @@ class MainWindow(QWidget):
if statuses.get(req.block_name) == 'NOT_REGISTERED': if statuses.get(req.block_name) == 'NOT_REGISTERED':
from cbb_refresh_verify.verify_runner import VerifyResult from cbb_refresh_verify.verify_runner import VerifyResult
return VerifyResult('SKIPPED', stderr='仅发现目录,原生目录未登记此 CBB。') return VerifyResult('SKIPPED', stderr='仅发现目录,原生目录未登记此 CBB。')
if statuses.get(req.block_name) != 'PENDING':
from cbb_refresh_verify.verify_runner import VerifyResult
return VerifyResult('SKIPPED', error_category='STATUS_UNCONFIRMED',
error_stage='admission', stderr='STATUS_UNCONFIRMED: 当前状态未确认,未启动校验;请重新读取。')
if maintenance: if maintenance:
self._emit_job(job, 'event', {'block': req.block_name, 'stage': 'icdb_check_start'}) self._emit_job(job, 'event', {'block': req.block_name, 'stage': 'icdb_check_start'})
return verify(req) return verify(req)
@@ -1777,12 +1884,12 @@ class MainWindow(QWidget):
safe = all(result.safe_to_continue for result in results) safe = all(result.safe_to_continue for result in results)
self._emit_job(job, 'batch_ready', (results, report)) self._emit_job(job, 'batch_ready', (results, report))
refresh = None refresh = None
if safe and not job.context.stop.is_set(): if safe and affected and not job.context.stop.is_set():
from cbb_refresh_verify.operation_queue import QueueCancelled from cbb_refresh_verify.operation_queue import QueueCancelled, QueueUnavailable
try: try:
refresh = self._queued_action(lambda: self._read_affected_records(affected, library=library, lease=job.lease), refresh = self._queued_action(lambda: self._read_affected_records(affected, library=library, lease=job.lease),
label='批次已结束,状态刷新', library=library, job=job)() label='批次已结束,状态刷新', library=library, job=job)()
except QueueCancelled: except (QueueCancelled, QueueUnavailable):
pass # Cancelling the refresh must not erase completed item results. pass # Cancelling the refresh must not erase completed item results.
return results, report, affected, refresh return results, report, affected, refresh
self._start(action, self._batch_refreshed, queued=False, job=job, bounded=False) self._start(action, self._batch_refreshed, queued=False, job=job, bounded=False)
@@ -1888,6 +1995,11 @@ class MainWindow(QWidget):
from shiboken6 import isValid from shiboken6 import isValid
if not isValid(self) or not isValid(self.cbb_table): if not isValid(self) or not isValid(self.cbb_table):
return return
if event.get('stage') in {'catalog_start', 'catalog_status', 'catalog_waiting'}:
catalog_job = self._jobs.get(event.get('catalog_id'))
if catalog_job is None or catalog_job.context.stop.is_set():
return
self.status_label.setText(event['detail'])
if event.get('stage') == 'waiting_native_slot': if event.get('stage') == 'waiting_native_slot':
self.status_label.setText(event.get('detail', '已排队,等待执行')) self.status_label.setText(event.get('detail', '已排队,等待执行'))
self._queue_waiting(event) self._queue_waiting(event)
@@ -1932,6 +2044,36 @@ class MainWindow(QWidget):
self.cbb_table.item(row, 3).setToolTip(detail) self.cbb_table.item(row, 3).setToolTip(detail)
if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line) if self.logging_context: self.logging_context.logger.info('cbb_progress %s', line)
def _show_result_detail(self, row, column):
if column != 3:
return
item = self.cbb_table.item(row, column)
name = self.cbb_table.item(row, 0)
if item is None or name is None or not item.toolTip():
return
dialog = QDialog(self)
dialog.setAttribute(Qt.WA_DeleteOnClose)
dialog.setWindowTitle(f'{name.text()} 结果详情')
dialog.resize(660, 380)
layout = QVBoxLayout(dialog)
text = QPlainTextEdit(dialog)
text.setReadOnly(True)
text.setPlainText(item.toolTip())
text.moveCursor(QTextCursor.Start)
layout.addWidget(text)
buttons = QDialogButtonBox(QDialogButtonBox.Close, dialog)
copy = buttons.addButton('复制全文', QDialogButtonBox.ActionRole)
def copy_detail():
from PySide6.QtWidgets import QApplication
QApplication.clipboard().setText(text.toPlainText())
copy.clicked.connect(copy_detail)
buttons.rejected.connect(dialog.close)
layout.addWidget(buttons)
dialog.show()
def _mark_row_ready(self, row): def _mark_row_ready(self, row):
"""Color authoritative READY rows while retaining management selection.""" """Color authoritative READY rows while retaining management selection."""
name_item = self.cbb_table.item(row, 0) name_item = self.cbb_table.item(row, 0)
@@ -2146,8 +2288,8 @@ class MainWindow(QWidget):
'已请求取消;检查将停止,原生写入只等待安全结束,不强制终止。'); self._update() '已请求取消;检查将停止,原生写入只等待安全结束,不强制终止。'); self._update()
def _failed(self, error): def _failed(self, error):
from cbb_refresh_verify.operation_queue import QueueCancelled from cbb_refresh_verify.operation_queue import QueueCancelled, QueueUnavailable
if self.library_lease is not None and not isinstance(error, QueueCancelled): if self.library_lease is not None and not isinstance(error, (QueueCancelled, QueueUnavailable)):
self._retain_path_lease(self.library_lease, hold_busy=True) self._retain_path_lease(self.library_lease, hold_busy=True)
self._display_error(error) self._display_error(error)
+12 -6
View File
@@ -5,6 +5,7 @@ from pathlib import Path
from PySide6.QtCore import QObject, QThreadPool, Signal, Qt from PySide6.QtCore import QObject, QThreadPool, Signal, Qt
from PySide6.QtWidgets import (QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLabel, from PySide6.QtWidgets import (QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLabel,
QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout) QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout)
from shiboken6 import isValid
from .workers import ServiceWorker from .workers import ServiceWorker
from .backup_notice import MANUAL_BACKUP_NOTICE from .backup_notice import MANUAL_BACKUP_NOTICE
@@ -192,12 +193,12 @@ class ManagementDialog(QDialog):
action = lambda: self.runner(requests, adapter=self.adapter, stop=context.stop, action = lambda: self.runner(requests, adapter=self.adapter, stop=context.stop,
progress=lambda event:self._emit(context, 'progress',event),**choices) progress=lambda event:self._emit(context, 'progress',event),**choices)
if self.native_queue is None: return context.run(action) if self.native_queue is None: return context.run(action)
from ..operation_queue import QueueCancelled from ..operation_queue import QueueCancelled, QueueUnavailable
from ..session_record import library_available, library_wait_reason from ..session_record import library_available, library_wait_reason
try: try:
if self.runner is run_management_batch: if self.runner is run_management_batch:
def item(request, action): def item(request, action):
return self.native_queue.run(action, stop=context.stop, context=context, return self.native_queue.run(action, stop=context.stop, context=context, skip_unavailable=True,
wait_state=lambda: library_wait_reason(request.library), wait_state=lambda: library_wait_reason(request.library),
waiting=lambda: self._emit(context, 'progress',{'stage': 'waiting_native_slot', waiting=lambda: self._emit(context, 'progress',{'stage': 'waiting_native_slot',
'retained': not library_available(request.library), 'retained': not library_available(request.library),
@@ -205,11 +206,15 @@ class ManagementDialog(QDialog):
return self.runner(requests, adapter=self.adapter, stop=context.stop, return self.runner(requests, adapter=self.adapter, stop=context.stop,
progress=lambda event:self._emit(context, 'progress',event), item_executor=item, progress=lambda event:self._emit(context, 'progress',event), item_executor=item,
version_prompt=lambda choice:self._emit(context, 'choice',choice), context=context) version_prompt=lambda choice:self._emit(context, 'choice',choice), context=context)
return self.native_queue.run(action, stop=context.stop, context=context, waiting=lambda: self._emit(context, 'progress', return self.native_queue.run(action, stop=context.stop, context=context, skip_unavailable=True, waiting=lambda: self._emit(context, 'progress',
{'stage': 'waiting_native_slot', {'stage': 'waiting_native_slot',
'retained': not library_available(self.template.library), 'retained': not library_available(self.template.library),
'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}), 'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}),
wait_state=lambda: library_wait_reason(self.template.library)) wait_state=lambda: library_wait_reason(self.template.library))
except QueueUnavailable as error:
from ..management import ManagementResult
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
'admission', 'SKIPPED', True, str(error)) for r in requests]
except QueueCancelled as error: except QueueCancelled as error:
from ..operation_queue import TaskHandoff from ..operation_queue import TaskHandoff
from ..management import ManagementResult from ..management import ManagementResult
@@ -217,9 +222,10 @@ class ManagementDialog(QDialog):
'complete', 'RECOVERY_REQUIRED' if isinstance(error,TaskHandoff) else 'CANCELLED', 'complete', 'RECOVERY_REQUIRED' if isinstance(error,TaskHandoff) else 'CANCELLED',
not isinstance(error,TaskHandoff), str(error)) for r in requests] not isinstance(error,TaskHandoff), str(error)) for r in requests]
self.worker = ServiceWorker(execute) self.worker = ServiceWorker(execute)
self.worker.signals.succeeded.connect(context.guard_callback(self._result, current=lambda:self.context)) current = lambda: self.context if isValid(self) else None
self.worker.signals.failed.connect(context.guard_callback(self._failed, current=lambda:self.context)) self.worker.signals.succeeded.connect(context.guard_callback(self._result, current=current))
self.worker.signals.finished.connect(lambda:self._finished() if self.context is context else None) 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) self.pool.start(self.worker)
def _emit(self, context, signal, value): def _emit(self, context, signal, value):
+6 -4
View File
@@ -8,17 +8,19 @@ class PcbOpenDialog(QMessageBox):
self.choice = choice self.choice = choice
self.setWindowTitle('确认打开 PCB 工程') self.setWindowTitle('确认打开 PCB 工程')
self.setIcon(QMessageBox.Question) self.setIcon(QMessageBox.Question)
advice = ('程序将检查工程和共享库占用,再决定是否继续。' if choice.auto_confirm else
'请确认没有其他用户打开此工程,再选择继续以读写权限打开。')
self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n' self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n'
'PCB 提示上次可能未正常关闭,或工程仍被其他用户打开。\n' 'PCB 提示上次可能未正常关闭,或工程仍被其他用户打开。\n'
'请确认没有其他用户打开此工程,再选择继续以读写权限打开。') + advice)
self.continue_button = self.addButton('确认无人使用,继续打开', QMessageBox.ActionRole) self.continue_button = self.addButton(
'检查占用后继续' if choice.auto_confirm else '确认无人使用,继续打开', QMessageBox.ActionRole)
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole) self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole) self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
self.setDefaultButton(self.skip_button)
self.setEscapeButton(self.cancel_button) self.setEscapeButton(self.cancel_button)
self.setModal(True) self.setModal(True)
self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else
'skip' if b is self.skip_button else 'cancel', 'skip' if b is self.skip_button else 'cancel',
origin=self.property('selectionOrigin') or 'user')) origin=self.property('selectionOrigin') or 'user'))
self.finished.connect(lambda _: choice.choose('cancel')) self.finished.connect(lambda _: choice.choose('cancel'))
arm_default(self, self.skip_button) arm_default(self, self.continue_button if choice.auto_confirm else self.skip_button)
+96 -14
View File
@@ -83,6 +83,9 @@ class VerifyRequest:
maintenance: bool = False maintenance: bool = False
post_repair_proof: object | None = field(default=None, repr=False, compare=False) post_repair_proof: object | None = field(default=None, repr=False, compare=False)
diagnostic_only: bool = False diagnostic_only: bool = False
# Explicit True/False selects ordinary Verify's complete access proof.
# None preserves the manual confirmation policy for other callers.
auto_confirm_pcb_open: bool | None = None
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -243,7 +246,8 @@ def _stop_worker(process, *, timeout=5, wait_for_native_write=True):
process.wait(timeout=timeout) process.wait(timeout=timeout)
except Exception: except Exception:
pending = getattr(process, 'native_write_pending', lambda: False)() pending = getattr(process, 'native_write_pending', lambda: False)()
if wait_for_native_write and 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 from .defaults import NATIVE_WRITE_STOP_WAIT_SECONDS
try: try:
process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout)) process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout))
@@ -656,7 +660,7 @@ def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner
Path(request.evidence_dir)/'previous-release', block_name=request.block_name, Path(request.evidence_dir)/'previous-release', block_name=request.block_name,
progress=progress, stop=stop) progress=progress, stop=stop)
check_active() check_active()
library_lock = LibraryLock(request.lmc_file, checkpoint=False, library_lock = LibraryLock(request.lmc_file, checkpoint=False, block_name=request.block_name,
safe_to_release=clients_released) safe_to_release=clients_released)
library_lock.__enter__() library_lock.__enter__()
check_active() check_active()
@@ -669,6 +673,46 @@ def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner
request, progress=progress, flag_reader=flag_reader, request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check, process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop) dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
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'} if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'}
and result.error_category == 'ICDB_REPAIR_REQUIRED' and result.error_category == 'ICDB_REPAIR_REQUIRED'
and result.evidence_path): and result.evidence_path):
@@ -985,6 +1029,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
except Exception as error: except Exception as error:
return finish(VerifyResult('FAIL', stderr=str(error))) return finish(VerifyResult('FAIL', stderr=str(error)))
events = root/'events.jsonl' 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 offset = 0
target_pid = None target_pid = None
diagnostic_closing = False diagnostic_closing = False
@@ -1000,7 +1053,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .desktop_worker import DesktopWorker from .desktop_worker import DesktopWorker
from .dialog_supervisor import AgentDialogBackend, DialogSupervisor, Win32DialogBackend from .dialog_supervisor import AgentDialogBackend, DialogSupervisor, Win32DialogBackend
from .dialog_models import DialogPhase from .dialog_models import DialogPhase
from .operation_queue import check_active, native_channel from .operation_queue import TaskHandoff, check_active, native_channel
check_active() check_active()
worker_launch_attempted = False worker_launch_attempted = False
native = native_channel() native = native_channel()
@@ -1011,6 +1064,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
native.__exit__(None, None, None) native.__exit__(None, None, None)
phase_entered = False phase_entered = False
try: try:
if prewrite_eligible:startup_phase('startup_supervisor_no_write')
timing.begin('worker_setup') timing.begin('worker_setup')
with (root/'worker.log').open('w', encoding='utf-8') as log: with (root/'worker.log').open('w', encoding='utf-8') as log:
check_active() check_active()
@@ -1037,14 +1091,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .dialog_rules import default_rules_path, load_rules from .dialog_rules import default_rules_path, load_rules
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop) dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop)
dialog_supervisor = DialogSupervisor( 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}), int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}),
rules=load_rules(default_rules_path(), diagnostic_only=request.diagnostic_only), rules=load_rules(default_rules_path(), diagnostic_only=request.diagnostic_only),
) )
else: else:
dialog_supervisor = DialogSupervisor(Win32DialogBackend( dialog_supervisor = DialogSupervisor(Win32DialogBackend(
lambda: ({value for value in (target_pid, lm_pid) if value is not None}), 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: else:
dialog_supervisor = dialog_supervisor_factory( dialog_supervisor = dialog_supervisor_factory(
@@ -1070,7 +1124,9 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'已请求停止,等待当前原生操作返回') '已请求停止,等待当前原生操作返回')
_notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name, _notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name,
'detail': detail}) 'detail': detail})
_stop_worker(process, wait_for_native_write=not request.diagnostic_only) 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='已取消当前校验。', return finish(VerifyResult('CANCELLED', stderr='已取消当前校验。',
safe_to_continue=False, error_stage=phase.value)) safe_to_continue=False, error_stage=phase.value))
if events.exists(): if events.exists():
@@ -1152,14 +1208,18 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
diagnostic_closing = True diagnostic_closing = True
from .dialog_supervisor import DialogPollResult from .dialog_supervisor import DialogPollResult
dialog_result = DialogPollResult(activity=False) dialog_result = DialogPollResult(activity=False)
if (version_prompt is not None and consent is None and dialog_agent is not None if ((version_prompt is not None or request.auto_confirm_pcb_open)
and consent is None and dialog_agent is not None
and not request.diagnostic_only and not request.native_lm_verify and not request.diagnostic_only and not request.native_lm_verify
and not request.maintenance and not request.interactive_input
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED' and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
and dialog_result.snapshot is not None): and dialog_result.snapshot is not None):
from .pcb_open_consent import OpenController, exact_prompt from .pcb_open_consent import OpenController, exact_prompt
if exact_prompt(dialog_result.snapshot): if exact_prompt(dialog_result.snapshot):
if open_controller is None: if open_controller is None:
open_controller = OpenController(job) open_controller = OpenController(
job, auto_confirm=request.auto_confirm_pcb_open is True,
require_complete_proof=request.auto_confirm_pcb_open is not None)
dialog_result = open_controller.handle(dialog_result.snapshot, dialog_result.observed_snapshots, dialog_result = open_controller.handle(dialog_result.snapshot, dialog_result.observed_snapshots,
target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid, target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid,
show=version_prompt, perform=dialog_supervisor.backend.perform) show=version_prompt, perform=dialog_supervisor.backend.perform)
@@ -1217,6 +1277,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'CANCELLED' if dialog_result.error_code == 'USER_CANCELLED' else 'CANCELLED' if dialog_result.error_code == 'USER_CANCELLED' else
'SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else 'FAIL', 'SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else 'FAIL',
stderr=f'{dialog_result.error_code}: {dialog_result.detail}', stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
error_category='PCB_OPEN_SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else '',
error_stage=phase.value, error_stage=phase.value,
safe_to_continue=False, safe_to_continue=False,
)) ))
@@ -1309,6 +1370,12 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'detail': '已转后台观察,可查看状态'}) 'detail': '已转后台观察,可查看状态'})
from .operation_queue import hold_native_handoff from .operation_queue import hold_native_handoff
hold_native_handoff(process, process.session_record_path) 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: except Exception as error:
close_errors.append(str(error)) close_errors.append(str(error))
if 'process' in locals(): if 'process' in locals():
@@ -1446,7 +1513,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None, def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None,
context=None): context=None):
"""Run serially and stop when database/session safety is unconfirmed.""" """Run serially; isolate failures and skip writes to resources still retained."""
if max_workers != 1: if max_workers != 1:
raise ValueError('Only serial Verify is supported for the shared Library Manager session') raise ValueError('Only serial Verify is supported for the shared Library Manager session')
if context is not None: if context is not None:
@@ -1457,15 +1524,28 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
stop=stop, context=context) # noqa: E731 stop=stop, context=context) # noqa: E731
results = [] results = []
queue_stop = False queue_stop = False
retained_libraries = set() retained_libraries = {}
for request in requests: for request in requests:
from .operation_queue import request_library_keys from .operation_queue import request_library_keys
library_keys = request_library_keys(request, context) library_keys = request_library_keys(request, context)
for index in {retained_libraries[key][1] for key in library_keys.intersection(retained_libraries)}:
previous = next(value[0] for value in retained_libraries.values() if value[1] == index)
if queue_stop or stop is not None and stop.is_set():
break
if not results[index].evidence_path:
continue
from .operation_lifecycle import recheck_failed_release
refreshed = recheck_failed_release(previous.lmc_file, previous.block_name, results[index], stop=stop)
if refreshed.safe_to_continue:
results[index] = refreshed
retained_libraries = {k:v for k,v in retained_libraries.items() if v[1] != index}
if (queue_stop or stop is not None and stop.is_set() if (queue_stop or stop is not None and stop.is_set()
or context is not None and context.stop.is_set()): or context is not None and context.stop.is_set()):
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB') result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
elif library_keys.intersection(retained_libraries): elif library_keys.intersection(retained_libraries):
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入') previous, index = retained_libraries[next(iter(library_keys.intersection(retained_libraries)))]
result = VerifyResult('SKIPPED', error_category='PREVIOUS_SESSION_UNRELEASED',
error_stage='admission', stderr=f'前项 {getattr(previous, "block_name", previous)} 的同库会话尚未释放,当前项未启动。')
else: else:
try: try:
def execute(): def execute():
@@ -1476,15 +1556,17 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
return result return result
result = item_executor(request, execute) if item_executor is not None else execute() result = item_executor(request, execute) if item_executor is not None else execute()
except Exception as error: except Exception as error:
from .operation_queue import QueueCancelled, TaskHandoff from .operation_queue import QueueCancelled, QueueUnavailable, TaskHandoff
# An unexpected exception cannot establish database safety. # An unexpected exception cannot establish database safety.
result = (_handoff_verify_result(error) if isinstance(error, TaskHandoff) else result = (VerifyResult('SKIPPED', stderr=str(error), error_category='NATIVE_SESSION_PENDING',
error_stage='admission') if isinstance(error, QueueUnavailable) else
_handoff_verify_result(error) if isinstance(error, TaskHandoff) else
VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL', VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled))) stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled)))
results.append(result) results.append(result)
# Never start another writer after an unconfirmed native shutdown. # Never start another writer after an unconfirmed native shutdown.
if not result.safe_to_continue: if not result.safe_to_continue:
retained_libraries.update(library_keys) retained_libraries.update({key:(request, len(results)-1) for key in library_keys})
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'} queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'}
if queue_stop and stop is not None: if queue_stop and stop is not None:
stop.set() stop.set()
+41
View File
@@ -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() workspace = Path(sys.argv[1]).resolve()
bundle_root = Path(sys.argv[2]).resolve() bundle_root = Path(sys.argv[2]).resolve()
sys.path.insert(0, str(workspace/'src')) sys.path.insert(0, str(workspace/'src'))
from cbb_refresh_verify import __version__
exe = bundle_root/'dist/CbbRefreshVerify-Background/CbbRefreshVerify.exe' exe = bundle_root/'dist/CbbRefreshVerify-Background/CbbRefreshVerify.exe'
root = bundle_root/('smoke-' + uuid4().hex[:8]) root = bundle_root/('smoke-' + uuid4().hex[:8])
root.mkdir() root.mkdir()
@@ -64,7 +65,7 @@ finally:
from PyInstaller.archive.readers import ZlibArchiveReader from PyInstaller.archive.readers import ZlibArchiveReader
pyz = bundle_root/'build/CbbRefreshVerify/PYZ-00.pyz' pyz = bundle_root/'build/CbbRefreshVerify/PYZ-00.pyz'
code = ZlibArchiveReader(str(pyz)).extract('cbb_refresh_verify') code = ZlibArchiveReader(str(pyz)).extract('cbb_refresh_verify')
assert '0.2.4b3' 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')) toc = ast.literal_eval((bundle_root/'build/CbbRefreshVerify/Analysis-00.toc').read_text('utf-8'))
stack, rows = [toc], [] stack, rows = [toc], []
while stack: while stack:
@@ -77,6 +78,6 @@ while stack:
stack.extend(value) stack.extend(value)
assert rows and all(Path(row[1]).is_relative_to(workspace/'src') for row in rows) 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['module_origins'] = {'status': 'passed', 'module_count': len(rows), 'source_root': str(workspace/'src')}
results['version'] = '0.2.4b3' results['version'] = __version__
(root/'result.json').write_text(json.dumps(results, ensure_ascii=False, indent=2), 'utf-8') (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) print(json.dumps({'evidence': str(root/'result.json'), **results}, ensure_ascii=False), flush=True)
+248
View File
@@ -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
+198
View File
@@ -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
+20
View File
@@ -122,6 +122,26 @@ def test_persistent_loading_progress_keeps_deadline_and_never_closes(diagnostic,
assert Session.instances[-1].posted == [] assert Session.instances[-1].posted == []
def test_cancel_from_window_scan_wins_expired_open_deadline(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job)
signal = Path(job['root']).parent/'cancel-after-scan'
job['cancel_signal'] = str(signal)
clock = [0.0]
monkeypatch.setattr(diagnostic.time, 'monotonic', lambda: clock[0])
monkeypatch.setattr(diagnostic, '_NativeSession', Session)
target = frame(job)
target['children'].append({'hwnd':13,'class':'msctls_progress32','text':'','visible':True})
def windows(pid):
signal.touch()
clock[0] = 10.0
return [target]
monkeypatch.setattr(diagnostic, '_windows', windows)
with pytest.raises(RuntimeError, match='VERIFY_CANCELLED'):
diagnostic.check_target_window(job, 42, emit=lambda **event: None, error_reader=lambda: None)
assert Session.instances[-1].posted == []
def test_diagnostic_waits_for_startup_forward_no_before_close(diagnostic, job, monkeypatch): def test_diagnostic_waits_for_startup_forward_no_before_close(diagnostic, job, monkeypatch):
job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job) job['diagnostic_log_baseline'] = diagnostic.snapshot_diagnostic_logs(job)
write_logs(job); job['timeout'] = 1 write_logs(job); job['timeout'] = 1
+53
View File
@@ -371,3 +371,56 @@ def test_only_exact_empty_zero_area_childless_ie_infrastructure_is_benign(tmp_pa
entry = result['benign_auxiliary_windows'][0] entry = result['benign_auxiliary_windows'][0]
assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0] assert entry['class'] == 'Internet Explorer_Hidden' and entry['rect'] == [0, 0, 0, 0]
assert entry['children'] == [] assert entry['children'] == []
@pytest.mark.parametrize('receipt', ['matching', 'late', 'different_operation', 'different_identity'])
def test_supervisor_no_lets_own_empty_pcb_close_with_address_remaining(tmp_path, monkeypatch, receipt):
import win32con
job, records, messages, _, visible = read_write_fixture(tmp_path, monkeypatch)
job['operation_id'] = 'verify-owned'
address = tmp_path/'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('existing address')
snapshot = failed_session._startup_snapshot(200, 12).to_record()
from cbb_refresh_verify import residual_sessions
monkeypatch.setattr(residual_sessions, '_force_ownership', lambda *_: {
'owner_sid': 'S-1-5-21-test', 'session_id': 1})
owner = {'pid': 12, 'owner_sid': 'S-1-5-21-test', 'session_id': 1,
'image': records[0][1], 'created_handle': 'reused' if receipt == 'different_identity' else 'original'}
(tmp_path/'pcb-open-user-choice.json').write_text(json.dumps(dict(
operation_id='another-operation' if receipt == 'different_operation' else job['operation_id'],
desktop=job['desktop'], project=job['project'], pcb=job['pcb'],
library=job['lmc_file'], choice='skip', snapshot=snapshot, owner={'target': owner})))
visible.remove(200)
def record_acknowledgement():
(tmp_path/'dialogs.jsonl').write_text(json.dumps(dict(
snapshot, action='user_confirmed_pcb_open', error_code='PCB_OPEN_SKIPPED',
accepted_control=[7]))+'\n')
if receipt == 'late':
from types import SimpleNamespace
elapsed = 0.0
def advance(seconds):
nonlocal elapsed
elapsed += seconds
if elapsed < 0.3:
record_acknowledgement()
monkeypatch.setattr(failed_session, 'time',
SimpleNamespace(monotonic=lambda: elapsed, sleep=advance))
else:
record_acknowledgement()
result = failed_session.close_failed_startup(
job, 12, timeout_seconds=0 if receipt == 'different_operation' else 1)
if receipt in {'different_operation', 'different_identity'}:
assert result['status'] == 'RETAINED' and records and not messages
return
assert result['status'] == 'CLOSED'
assert result['cancelled_prompt'] == 'read_write_access'
assert result['release']['addresses'] == [str(address)]
assert result['release']['resource_release_confirmed'] is False
assert messages == [(100, win32con.WM_CLOSE)]
assert not records and address.is_file()
+32
View File
@@ -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)
@@ -91,6 +91,9 @@ def test_exited_verify_worker_outcome_read_is_bounded_and_releases_channel(tmp_p
def poll(self): return 0 def poll(self): return 0
def close(self): pass def close(self): pass
monkeypatch.setattr('cbb_refresh_verify.desktop_worker.DesktopWorker', ExitedWorker) 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 original = Path.read_text
def read(path, *args, **kwargs): def read(path, *args, **kwargs):
if path.name == 'outcome.json': if path.name == 'outcome.json':
@@ -221,6 +224,9 @@ def test_handed_off_worker_accepts_exact_controls_but_excludes_new_writers(tmp_p
monkeypatch.setattr(sessions, '_request_native_cancel', answer) 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, 'query_process_snapshot', lambda: [row] if child[0].poll() is None else [])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {}) 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]), command = lambda: sessions.release_residual_sessions(dict(library=str(library), sessions=[row]),
tmp_path/'controls', cancel_native=True) tmp_path/'controls', cancel_native=True)
def control_call(): def control_call():
+100 -1
View File
@@ -172,7 +172,7 @@ def test_catalog_union_keeps_registration_source_and_counts(qtbot, tmp_path, mon
load(window,qtbot) load(window,qtbot)
qtbot.waitUntil(entered.is_set) qtbot.waitUntil(entered.is_set)
assert '未知' in window.counts_label.text() assert '未知' in window.counts_label.text()
assert window.batch_button.isEnabled() assert not window.batch_button.isEnabled()
release.set() release.set()
qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name) qtbot.waitUntil(lambda:'NativeOnly' in window._records_by_name)
assert window._records_by_name['Orphan'].catalog_source == 'directory_only' assert window._records_by_name['Orphan'].catalog_source == 'directory_only'
@@ -649,3 +649,102 @@ def test_recovery_retry_rejects_old_external_progress_and_choice(qtbot,tmp_path,
assert choice.decision=='cancel' assert choice.decision=='cancel'
finally: finally:
release.set(); qtbot.waitUntil(lambda:not dialog.busy) release.set(); qtbot.waitUntil(lambda:not dialog.busy)
@pytest.mark.parametrize('cancel', [True, False])
def test_uncommitted_catalog_refresh_preserves_last_full_result(qtbot, tmp_path, monkeypatch, cancel):
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.ui import main_window as ui
reading, release = Event(), Event()
calls = []
snapshot = tmp_path/'status-refresh.jsonl'
def read_status(names, path, checkpoint_path=None):
calls.append(names)
if checkpoint_path is not None:
checkpoint_path.parent.mkdir(parents=True, exist_ok=True)
checkpoint_path.write_text('full scan' if len(calls) == 1 else 'partial scan', encoding='utf-8')
if len(calls) == 2:
reading.set()
release.wait(5)
return {name: 'READY' for name in names}
monkeypatch.setattr(ui, 'authoritative_status_map', read_status)
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
catalog_reader=lambda path, _: Catalog(path, 1, (CatalogEntry('A', 'Logical-Physical'),)))
try:
load(window, qtbot)
qtbot.waitUntil(lambda: window.ready_names == {'A'})
reports = []
monkeypatch.setattr(window, '_publish_check_statuses',
lambda library, statuses, lease: reports.append(dict(statuses)))
original_replace = Path.replace
def replace_file(path, target):
if target == snapshot:
raise PermissionError('snapshot is held')
return original_replace(path, target)
if not cancel:
monkeypatch.setattr(Path, 'replace', replace_file)
window.load_button.click()
qtbot.waitUntil(reading.is_set)
assert window.ready_names == {'A'}
assert not window.batch_button.isEnabled()
assert snapshot.read_text(encoding='utf-8') == 'full scan'
if cancel:
window.stop_button.click()
release.set()
qtbot.waitUntil(lambda: not any(job.kind == 'catalog' for job in window._jobs.values()))
assert ('已取消读取' if cancel else 'snapshot is held') in window.status_label.text()
assert reports == []
assert window.ready_names == {'A'}
assert snapshot.read_text(encoding='utf-8') == 'full scan'
window.status_refresher(('A',), Path('a.lmc'))
assert snapshot.read_text(encoding='utf-8') == 'full scan'
finally:
release.set()
window.pool.waitForDone(6000)
@pytest.mark.parametrize('cancelled', [False, True])
def test_external_catalog_owner_wait_retries_once_or_cancels(qtbot, tmp_path, monkeypatch, cancelled):
from cbb_refresh_verify.management import Catalog, CatalogEntry
from cbb_refresh_verify.native_management import NativeOperationError
probing, released = Event(), Event()
calls = []
def read_catalog(path, evidence):
calls.append(evidence)
if len(calls) == 1:
raise NativeOperationError('LIBRARY_MANAGER_BUSY: 已有 Library Manager 运行。', safe_to_continue=True)
return Catalog(path, 1, (CatalogEntry('A', 'Logical-Physical'),))
def owners(*args, **kwargs):
probing.set()
return [] if released.is_set() else [{'pid': 123}]
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', owners)
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A', 'LP'),), directory_count=1),
catalog_reader=read_catalog, status_refresher=lambda names, _: {name: 'READY' for name in names})
try:
load(window, qtbot)
qtbot.waitUntil(probing.is_set)
assert not window.native_queue.active
if cancelled:
window.stop_button.click()
released.set()
qtbot.waitUntil(lambda: not any(job.kind == 'catalog' for job in window._jobs.values()), timeout=4000)
assert len(calls) == (1 if cancelled else 2)
if cancelled:
assert '已取消读取' in window.status_label.text()
else:
assert calls[0] != calls[1]
assert window.ready_names == {'A'}
finally:
released.set()
window.pool.waitForDone(6000)
+40
View File
@@ -238,3 +238,43 @@ def test_catalog_native_wait_outlives_metadata_deadline(tmp_path, transport, mon
(evidence/'finish').touch() (evidence/'finish').touch()
finisher.join(6) finisher.join(6)
context.close(timeout_seconds=6) context.close(timeout_seconds=6)
@pytest.mark.parametrize('switch', [False, True])
def test_stop_reaches_active_catalog_adapter(qtbot, tmp_path, monkeypatch, transport, switch):
from types import SimpleNamespace
from cbb_refresh_verify.native_management import NativeManagementAdapter
Transport, workers = transport
original = Transport.__init__
def hold_until_signalled(self, command, *args, **kwargs):
Path(command[-1]).with_name('hold-handler').touch()
original(self, command, *args, **kwargs)
monkeypatch.setattr(Transport, '__init__', hold_until_signalled)
library = tmp_path/'library.lmc'
library.write_bytes(b'isolated')
adapter = NativeManagementAdapter(worker_factory=Transport)
window = window_for(qtbot, tmp_path/'ui', monkeypatch, catalog_reader=adapter.catalog)
mapping_calls = []
window.path_lease_factory = lambda path: SimpleNamespace(mentor_path=path, display_path=path,
drive='', remote_root='', close=lambda: mapping_calls.append('close'),
retain_for_recovery=lambda: mapping_calls.append('retain'))
load(window, qtbot, str(library))
qtbot.waitUntil(lambda: bool(workers) and workers[0].path.with_name('handler-entered').exists())
worker = workers[0]
try:
if switch:
window.lmc_edit.setText(str(tmp_path/'different.lmc'))
else:
window.stop_button.click()
qtbot.waitUntil(lambda: worker.path.with_name('cancel-management.signal').exists(), timeout=3000)
qtbot.waitUntil(lambda: bool(mapping_calls), timeout=3000)
assert mapping_calls[0] == 'retain'
if not switch:
qtbot.waitUntil(lambda: '已取消读取中心库' in window.status_label.text(), timeout=3000)
assert not window.native_queue.active
assert worker.poll() is None
finally:
worker.path.with_name('finish').touch()
qtbot.waitUntil(lambda: worker.poll() is not None, timeout=5000)
+231
View File
@@ -0,0 +1,231 @@
"""Field #17: data failures finish their own cleanup before the next writer."""
import json
import time
from dataclasses import replace
from pathlib import Path
from types import SimpleNamespace
import pytest
from cbb_refresh_verify import failed_session, verify_runner
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
def test_database_load_question_declines_log_view_then_closes_empty_target(tmp_path, monkeypatch):
import win32con
from test_failed_startup import read_write_fixture
job, records, messages, names, _ = read_write_fixture(tmp_path, monkeypatch)
names[203] = ('Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed.\r\r'
'Do you wish to view the log file now?')
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'CLOSED', result
assert messages == [(202, win32con.BM_CLICK), (100, win32con.WM_CLOSE)]
assert not records
@pytest.mark.parametrize('text', [
'Problem encountered while opening one of the database files. Delete database?',
'Loading of the job has failed. Do you wish to repair it?',
])
def test_unknown_database_question_is_preserved(tmp_path, monkeypatch, text):
from test_failed_startup import read_write_fixture
job, records, messages, names, _ = read_write_fixture(tmp_path, monkeypatch)
names[203] = text
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'RETAINED' and records and not messages
def test_supervisor_acknowledged_failed_open_can_close_empty_shell_with_address(tmp_path, monkeypatch):
import win32con
from cbb_refresh_verify.dialog_models import WindowSnapshot, ControlSnapshot, DialogPhase
from test_failed_startup import startup_fixture
job, records, messages = startup_fixture(tmp_path, monkeypatch)
address = tmp_path/'database/cdbsvr/sAddress.adr'
address.parent.mkdir(parents=True)
address.write_text('original address')
popup = WindowSnapshot(200,12,'ExpeditionPCB.exe','pcb','#32770','Expedition PCB',
DialogPhase.PCB_STARTING, (
ControlSnapshot(201,6,'Button','Yes'), ControlSnapshot(202,7,'Button','No'),
ControlSnapshot(203,65535,'Static',
'Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed.\r\r'
'Do you wish to view the log file now?')))
(tmp_path/'dialogs.jsonl').write_text(json.dumps(dict(popup.to_record(),
action='acknowledge_fatal', error_code='MENTOR_DATABASE_LOAD_FAILED', accepted_control=[7]))+'\n')
result = failed_session.close_failed_startup(job, 12, timeout_seconds=0)
assert result['status'] == 'CLOSED', result
assert messages == [(100,win32con.WM_CLOSE)]
assert not records and address.read_text() == 'original address'
@pytest.mark.parametrize('aliased', [False, True])
@pytest.mark.parametrize('first_status', ['FAIL', 'SKIPPED'])
def test_late_release_is_rechecked_before_later_same_library_item(tmp_path, monkeypatch, aliased, first_status):
library = tmp_path/'lib.lmc'
calls, checks = [], []
failed = verify_runner.VerifyResult(first_status, stderr='native operation declined', safe_to_continue=False,
evidence_path=tmp_path/'result.json',
error_category='PCB_OPEN_SKIPPED' if first_status == 'SKIPPED' else 'MENTOR_DATABASE_LOAD_FAILED')
def verify(request):
calls.append(request.block_name)
return failed if request.block_name == 'Bad' else verify_runner.VerifyResult('PASS')
def recheck(library, block, result, **kwargs):
checks.append(block)
return result if len(checks) == 1 else replace(result, safe_to_continue=True)
monkeypatch.setattr('cbb_refresh_verify.operation_lifecycle.recheck_failed_release', recheck)
if aliased:
monkeypatch.setattr('cbb_refresh_verify.operation_queue.request_library_keys',
lambda *args:{'display-path','mapped-path'})
results = verify_runner.run_batch([verify_runner.VerifyRequest(library, n, tmp_path)
for n in ('Bad','Good')], verifier=verify)
assert calls == ['Bad','Good']
assert [r.status for r in results] == [first_status,'PASS']
assert results[0].safe_to_continue
def test_slow_catalog_status_is_delivered_and_unknown_cannot_start_bulk(qtbot, tmp_path, monkeypatch):
from test_issue15_ui_integration import window_for
from cbb_refresh_verify.management import Catalog, CatalogEntry
from threading import Event
entered, release = Event(), Event()
def statuses(names, library):
entered.set()
assert release.wait(15)
return {name:'READY' for name in names}
window = window_for(qtbot, tmp_path, monkeypatch,
reader=lambda _: LibraryReadResult((CbbRecord('A','LP'),), directory_count=1),
catalog_reader=lambda p,e:Catalog(p,1,(CatalogEntry('A','Logical-Physical'),)),
status_refresher=statuses)
window.lmc_edit.setText('a.lmc')
window.load_library()
qtbot.waitUntil(entered.is_set)
try:
assert not window.batch_button.isEnabled()
assert window.backup_restore_button.isEnabled()
assert '待读取 1' in window.counts_label.text()
# Actual prior metadata cutoff; native IO is simulated, task/Qt delivery is real.
qtbot.wait(10300)
release.set()
qtbot.waitUntil(lambda:window.ready_names == {'A'}, timeout=3000)
assert '原生 1' in window.counts_label.text()
finally:
release.set()
window.pool.waitForDone(5000)
def test_successful_worker_does_not_report_retained_save(tmp_path, monkeypatch):
from test_verify_worker_stability import exercise_worker
job, events, execute = exercise_worker(tmp_path, monkeypatch)
assert execute()['status'] == 'PASS'
assert not [e for e in events if e.get('stage') == 'save_result_retained']
@pytest.mark.parametrize('fresh', ['UNKNOWN', 'UNAVAILABLE', None])
def test_execution_rechecks_status_without_starting_unknown_target(qtbot, tmp_path, monkeypatch, fresh):
from test_issue15_ui_integration import window_for
from cbb_refresh_verify.management import Catalog, CatalogEntry
calls, reads = [], []
def statuses(names, library):
reads.append(tuple(names))
return {'A':'PENDING'} if len(reads) == 1 else ({} if fresh is None else {'A':fresh})
window = window_for(qtbot,tmp_path,monkeypatch,
reader=lambda _:LibraryReadResult((CbbRecord('A','LP'),), directory_count=1),
catalog_reader=lambda p,e:Catalog(p,1,(CatalogEntry('A','Logical-Physical'),)),
status_refresher=statuses,
verifier=lambda request:(calls.append(request.block_name) or verify_runner.VerifyResult('PASS')))
window.lmc_edit.setText('a.lmc'); window.load_library()
qtbot.waitUntil(lambda:window._read_counts[1] == 1)
window._run(['A'])
qtbot.waitUntil(lambda:not window.busy)
assert calls == []
reports=list((tmp_path/'reports').glob('batch-*.log'))
assert reports and 'STATUS_UNCONFIRMED' in reports[0].read_text(encoding='utf-8')
@pytest.mark.parametrize('second_ready', [True,False])
def test_saved_closed_pending_commit_gets_only_one_followup(tmp_path, monkeypatch, second_ready):
root=tmp_path/'first';root.mkdir()
evidence=root/'result.json';evidence.write_text('{"status":"FAIL"}')
second=tmp_path/'second';second.mkdir()
second_evidence=second/'result.json';second_evidence.write_text('{}')
pending=verify_runner.VerifyResult('FAIL',safe_to_continue=True,evidence_path=evidence,
library_flag='NOT_GREEN',error_category='MENTOR_VERIFY_NOT_COMMITTED',error_stage='library_flag',
bridge_attempts=({'status':'PENDING','source':'IsVerifiedReuseBlock','raw_status':0},),
timings_seconds={'total':2.0},
write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',
resource_state='RELEASED',interrupted=False))
calls=[]
def serialized(request,**kwargs):
calls.append(request.block_name)
if len(calls)==1:return pending
return (verify_runner.VerifyResult('PASS',library_flag='GREEN',evidence_path=second_evidence,timings_seconds={'total':3.0})
if second_ready else replace(pending,evidence_path=second_evidence,timings_seconds={'total':3.0}))
monkeypatch.setattr(verify_runner,'_run_verify_serialized',serialized)
result=verify_runner._run_verify_task(verify_runner.VerifyRequest(tmp_path/'missing.lmc','Block',tmp_path))
assert calls == ['Block','Block']
assert result.status == ('PASS' if second_ready else 'FAIL')
assert result.timings_seconds['total']==5.0
assert json.loads(evidence.read_text()) == {'status':'FAIL'}
link=json.loads((root/'commit-followup.json').read_text())
assert link['status']==('READY' if second_ready else 'UNCONFIRMED')
@pytest.mark.parametrize('obstacle', ['unsafe','save_unknown','close_unknown','native_retained',
'helper_running','interrupted','database_failure','unknown_status','diagnostic','auto_repair','cancelled'])
def test_incomplete_or_failed_native_operation_never_gets_commit_followup(tmp_path,monkeypatch,obstacle):
from threading import Event
evidence=tmp_path/'result.json';evidence.write_text('{}')
facts=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',resource_state='RELEASED',interrupted=False)
if obstacle=='save_unknown':facts['save_state']='UNKNOWN'
if obstacle=='close_unknown':facts['close_state']='UNKNOWN'
if obstacle=='native_retained':facts['resource_state']='RETAINED'
if obstacle=='helper_running':facts['helper_state']='RUNNING'
if obstacle=='interrupted':facts['interrupted']=True
pending=verify_runner.VerifyResult('FAIL',safe_to_continue=obstacle!='unsafe',evidence_path=evidence,
library_flag='NOT_GREEN' if obstacle!='unknown_status' else 'UNKNOWN',
error_category='MENTOR_DATABASE_LOAD_FAILED' if obstacle=='database_failure' else 'MENTOR_VERIFY_NOT_COMMITTED',
error_stage='library_flag',bridge_attempts=({'status':'PENDING','source':'IsVerifiedReuseBlock','raw_status':0},),
write_outcome=facts)
stop=Event();calls=[]
def serialized(*args,**kwargs):
calls.append(1)
if obstacle=='cancelled':stop.set()
return pending
monkeypatch.setattr(verify_runner,'_run_verify_serialized',serialized)
verify_runner._run_verify_task(verify_runner.VerifyRequest(tmp_path/'missing.lmc','Block',tmp_path,
diagnostic_only=obstacle=='diagnostic',auto_repair=obstacle=='auto_repair'),stop=stop)
assert calls == [1]
assert not (tmp_path/'commit-followup.json').exists()
def test_cancel_after_followup_checkpoint_releases_completed_first_lease(tmp_path,monkeypatch):
from cbb_refresh_verify.operation_queue import BatchTaskContext, QueueCancelled
from cbb_refresh_verify import library_lock
import win32con, win32file
library=tmp_path/'lib.lmc';library.write_bytes(b'isolated fixture')
evidence=tmp_path/'result.json';evidence.write_text('{}')
pending=verify_runner.VerifyResult('FAIL',safe_to_continue=True,evidence_path=evidence,
library_flag='NOT_GREEN',error_category='MENTOR_VERIFY_NOT_COMMITTED',error_stage='library_flag',
write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',resource_state='RELEASED',interrupted=False))
monkeypatch.setattr(library_lock,'recheck_previous_release',lambda *a,**k:None)
monkeypatch.setattr(verify_runner,'_run_verify_serialized',lambda *a,**k:pending)
context=BatchTaskContext(str(library))
original=Path.write_text
def write(path,*a,**k):
result=original(path,*a,**k)
if path.name=='commit-followup.json':context.cancel()
return result
monkeypatch.setattr(Path,'write_text',write)
try:
with pytest.raises(QueueCancelled):
context.run(lambda:verify_runner._run_verify_task(
verify_runner.VerifyRequest(library,'Block',tmp_path),stop=context.stop))
lock=library_lock.LibraryLock(library)
handle=win32file.CreateFile(str(lock.path),win32con.GENERIC_READ,0,None,win32con.OPEN_EXISTING,0,None)
handle.Close()
finally:
context.close(timeout_seconds=0)
with library_lock._guard:
owner=library_lock._owners.pop(library_lock.LibraryLock(library).key,None)
if owner:owner['handle'].Close()
+32
View File
@@ -0,0 +1,32 @@
"""Queued worker completion must not touch a destroyed management dialog."""
import pytest
from PySide6.QtWidgets import QMessageBox
from shiboken6 import delete, isValid
@pytest.mark.parametrize('failed', [False, True])
def test_queued_management_completion_ignores_deleted_receiver(qtbot, tmp_path, monkeypatch, failed):
from cbb_refresh_verify.management import ManagementRequest
from cbb_refresh_verify.ui import timed_prompt
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
def run(*args, **kwargs):
if failed:
raise ValueError('simulated native-boundary failure')
return []
monkeypatch.setattr(timed_prompt, 'question', lambda *args, **kwargs: QMessageBox.Yes)
dialog = ManagementDialog([ManagementRequest('remove', tmp_path/'library.lmc', 'Block',
evidence_dir=tmp_path/'evidence')], runner=run)
completed = []
dialog.completed.connect(completed.append)
try:
dialog.execute_button.click()
worker = dialog.worker # Retain the real sender while its queued signals are delivered.
assert dialog.pool.waitForDone(3000)
delete(dialog)
assert not isValid(dialog)
qtbot.wait(30)
assert not completed
finally:
if isValid(dialog):
delete(dialog)
@@ -29,6 +29,8 @@ def test_soft_stop_finishes_current_transaction_and_skips_next(setup, qtbot, mon
entered, release = Event(), Event() entered, release = Event(), Event()
admitted, results = [], [] admitted, results = [], []
monkeypatch.setattr(backup_recovery, '_idle_check', lambda *a, **kw: None) monkeypatch.setattr(backup_recovery, '_idle_check', lambda *a, **kw: None)
# Native work is simulated here; machine WMI latency is not the stop/readback boundary.
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: [])
monkeypatch.setattr(timed_prompt, 'question', lambda *a, **kw: QMessageBox.Yes) monkeypatch.setattr(timed_prompt, 'question', lambda *a, **kw: QMessageBox.Yes)
class Worker: class Worker:
+35
View File
@@ -0,0 +1,35 @@
import os
from pathlib import Path
import subprocess
import sys
import time
import pytest
@pytest.mark.parametrize('mode',['hash','copy','validate'])
def test_actual_app_exits_without_releasing_stalled_manifest_boundary(tmp_path,mode):
script=Path(__file__).parent/'support/manifest_process_exit.py'
env=dict(os.environ,QT_QPA_PLATFORM='offscreen')
child=subprocess.Popen([sys.executable,'-X','utf8',str(script),str(tmp_path),mode],
env=env,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
exited=False
try:
deadline=time.monotonic()+8
while not (tmp_path/'main-returning').exists() and child.poll() is None and time.monotonic()<deadline:
time.sleep(.02)
assert (tmp_path/'entered').exists()
assert (tmp_path/'main-returning').exists()
try:
child.wait(timeout=1)
exited=True
except subprocess.TimeoutExpired:
pass
assert not (tmp_path/'late-dispatch').exists()
finally:
(tmp_path/'release').touch() # Failed-version cleanup is cooperative, never termination.
stdout,stderr=child.communicate(timeout=5)
assert child.returncode==0,(stdout,stderr)
assert not (tmp_path/'late-dispatch').exists()
if mode!='hash':assert (tmp_path/'partial-copy').is_dir()
assert exited,'Interpreter waited for nested metadata executor despite the completed UI close'
+171
View File
@@ -0,0 +1,171 @@
import json
from pathlib import Path
import threading
import pytest
from cbb_refresh_verify import diagnostic_open, residual_sessions, session_record
from test_registered_startup_release import registered_fixture
from test_cancelled_ordinary_startup import ordinary_proof
def fixture(tmp_path, monkeypatch, *, obstacle='', closed=False):
load=diagnostic_open._load_evidence
job,row,records,messages,state=registered_fixture(tmp_path,monkeypatch,obstacle=obstacle,closed=closed)
monkeypatch.setattr(diagnostic_open,'_load_evidence',load)
events=ordinary_proof(job,tmp_path,state['prelaunch_baseline'])
if closed:events.append(dict(stage='startup_close_requested',pcb_pid=12,hwnd=100))
(tmp_path/'events.jsonl').write_text(''.join(json.dumps(e)+'\n' for e in events))
(tmp_path/'request.json').write_text(json.dumps(job))
monkeypatch.setattr(residual_sessions,'inspect_residual_sessions',lambda *a,**k:dict(sessions=[row]))
return job,row,records,messages,state
@pytest.mark.parametrize('closed',[False,True])
def test_registered_observer_finishes_late_loaded_ordinary_startup_once(tmp_path,monkeypatch,closed):
job,row,records,messages,state=fixture(tmp_path,monkeypatch,closed=closed)
original=(tmp_path/'result.json').read_bytes()
states=[]
def reconcile(*a,**kw):
states.append(1)
return dict(status='ACTIVE' if records else 'RELEASED',operation_id=job['operation_id'],
release_proof=None if records else dict(status='RELEASE_CONFIRMED'))
monkeypatch.setattr(session_record,'_reconcile',reconcile)
stop=threading.Event()
def progress(value):
if len(states)>2:stop.set()
result=session_record.observe_retained_session(tmp_path/'session.json',evidence_root=tmp_path,stop=stop,progress=progress)
assert result['status']=='RELEASED'
assert messages==([(31,245)] if closed else [(31,245),(100,16)])
assert (tmp_path/'result.json').read_bytes()==original
claim=json.loads((tmp_path/'session.json').read_text())['retained_startup_cleanup']
assert claim['operation_id']==job['operation_id'] and claim['pcb_pid']==12
@pytest.mark.parametrize('obstacle',['live_worker','other_write','save','foreign_identity','missing_cancel'])
def test_automatic_observer_does_not_consume_intent_or_act_without_positive_proof(tmp_path,monkeypatch,obstacle):
job,row,records,messages,state=fixture(tmp_path,monkeypatch,obstacle=obstacle)
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
assert not messages and records
assert 'retained_startup_cleanup' not in json.loads((tmp_path/'session.json').read_text())
def test_timed_out_retained_phase_is_not_restarted_by_observer_or_explicit_release(tmp_path,monkeypatch):
job,row,records,messages,state=fixture(tmp_path,monkeypatch)
read=residual_sessions._legacy_diagnostic_windows
def progress(bound):
values=read(bound)
if state['declined']:values[0]['children'].append(dict(hwnd=123,**{'class':'msctls_progress32'},visible=True))
return values
monkeypatch.setattr(residual_sessions,'_legacy_diagnostic_windows',progress)
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
first=state['ticks']
assert 30<=first<30.2 and messages==[(31,245)]
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
assert residual_sessions._request_close(row)['release_status']=='WAITING'
assert state['ticks']==first and messages==[(31,245)] and records
def test_claim_is_persisted_before_any_native_action_and_failure_prevents_action(tmp_path,monkeypatch):
job,row,records,messages,state=fixture(tmp_path,monkeypatch)
def denied(*a,**kw):raise OSError('journal unavailable')
monkeypatch.setattr(session_record,'write_session_record',denied)
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
assert not messages and records
def test_retained_phase_never_repeats_worker_no_on_still_visible_prompt(tmp_path,monkeypatch):
job,row,records,messages,state=fixture(tmp_path,monkeypatch)
with (tmp_path/'events.jsonl').open('a') as stream:
stream.write(json.dumps(dict(stage='startup_prompt_no',pcb_pid=12,hwnd=31,control_id=7))+'\n')
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
assert not messages and records and 30<=state['ticks']<30.2
def test_explicit_ordinary_release_promotes_cold_observer_before_native_action(tmp_path,monkeypatch):
job,row,records,messages,state=fixture(tmp_path,monkeypatch)
assert residual_sessions._request_close(row)['release_status']=='RELEASED'
assert state['observer_requests']
path,actions,options=state['observer_requests'][0]
assert path==tmp_path/'session.json' and actions==[] and options['observe_only'] is False
@pytest.mark.parametrize('obstacle',['unknown','hidden_document','revoked'])
def test_late_observer_preserves_unknown_or_changed_loaded_state_before_claim(tmp_path,monkeypatch,obstacle):
job,row,records,messages,state=fixture(tmp_path,monkeypatch)
read=residual_sessions._legacy_diagnostic_windows
def windows(bound):
values=read(bound)
if obstacle=='unknown':values.append(dict(hwnd=999,pid=12,**{'class':'#32770'},text='Unknown',children=[]))
if obstacle=='hidden_document':values[0]['children'].append(dict(hwnd=888,**{'class':'Afx:document'},text='Other',parent=101,visible=False))
if obstacle=='revoked':
with (tmp_path/'events.jsonl').open('a') as stream:stream.write('{"stage":"startup_write_admitted"}\n')
return values
monkeypatch.setattr(residual_sessions,'_legacy_diagnostic_windows',windows)
residual_sessions.resume_cancelled_startup(tmp_path/'session.json')
assert not messages and records
assert 'retained_startup_cleanup' not in json.loads((tmp_path/'session.json').read_text())
def test_duplicate_observer_explicit_release_and_process_restart_share_persisted_claim(tmp_path):
"""Real process/mutex/file race; only native evidence and action boundary are stubs."""
import os,subprocess,sys,time
path=tmp_path/'session.json'
session_record.write_session_record(path,dict(operation_id='one',block='B',library=str(tmp_path/'lib.lmc')))
(tmp_path/'request.json').write_text(json.dumps(dict(diagnostic_only=False)))
script=tmp_path/'race.py'
script.write_text('''
import json,sys,time
from pathlib import Path
from contextlib import nullcontext
import win32api
from cbb_refresh_verify import session_record as s,residual_sessions as r,diagnostic_open as d,failed_session as f
root=Path(sys.argv[1]);mode=sys.argv[2];tag=sys.argv[3];path=root/'session.json'
job=dict(diagnostic_only=False,desktop='CbbVerify_test',pcb=str(root/'B.pcb'))
row=dict(pid=1,name='ExpeditionPCB.exe',created_handle='bound',image='ExpeditionPCB.exe',owner_sid='owner',session_id=1)
proof=dict(job=job,record_path=str(path),operation_id='one',closed_frame=None)
r._process_handle=lambda *a,**k:nullcontext(win32api.GetCurrentProcess())
r._handle_identity=lambda h:dict(created_handle='bound',image='ExpeditionPCB.exe')
r._force_ownership=lambda *a:dict(force_user_confirmed=True,owner_sid='owner',session_id=1)
r._process_windows=lambda *a:{}
r._cancelled_diagnostic_record=lambda *a:proof
r._legacy_diagnostic_windows=lambda *a:[dict(hwnd=100,pid=1)]
d._target_frame=lambda *a,**k:dict(hwnd=100,pid=1)
d._pending_prompt=lambda *a,**k:False
f.cancelled_prewrite_startup=lambda *a:{}
r.inspect_residual_sessions=lambda *a,**k:dict(sessions=[row])
s._session=lambda *a:(s.read_session_record(path,evidence_root=root),{},[dict(role='native',pid=1,image='ExpeditionPCB.exe')])
def close(*a,**k):
assert 'retained_startup_cleanup' in json.loads(path.read_text())
(root/('action-'+tag)).write_text('one native phase')
until=time.monotonic()+8
while not (root/'release').exists() and time.monotonic()<until:time.sleep(.01)
return dict(release_status='WAITING')
r._close_registered_startup=close
(root/('ready-'+tag)).touch()
until=time.monotonic()+8
while not (root/'go').exists() and time.monotonic()<until:time.sleep(.01)
result=r.resume_cancelled_startup(path) if mode=='observer' else r._request_close(row)
(root/('result-'+tag)).write_text(json.dumps(result))
''',encoding='utf-8')
env=dict(os.environ,PYTHONPATH=str(Path(session_record.__file__).parents[1]))
children=[]
def start(mode,tag):
child=subprocess.Popen([sys.executable,str(script),str(tmp_path),mode,tag],env=env)
children.append(child);return child
try:
start('observer','a');start('explicit','b')
end=time.monotonic()+5
while len(list(tmp_path.glob('ready-*')))<2 and time.monotonic()<end:time.sleep(.01)
assert len(list(tmp_path.glob('ready-*')))==2
(tmp_path/'go').touch()
end=time.monotonic()+5
while not list(tmp_path.glob('action-*')) and time.monotonic()<end:time.sleep(.01)
assert len(list(tmp_path.glob('action-*')))==1
(tmp_path/'release').touch()
for child in children:assert child.wait(5)==0
assert start('observer','restart').wait(5)==0
assert len(list(tmp_path.glob('action-*')))==1
finally:
(tmp_path/'go').touch();(tmp_path/'release').touch()
for child in children:child.wait(10)
+219
View File
@@ -0,0 +1,219 @@
"""Finish a proved owned idle client, then prove resources independently."""
from contextlib import nullcontext
from dataclasses import replace
import json
from pathlib import Path
from threading import Event
import pytest
from cbb_refresh_verify import residual_sessions as residual, session_record as sessions
from cbb_refresh_verify import operation_lifecycle as lifecycle
from cbb_refresh_verify.verify_runner import VerifyResult
def owned_fixture(tmp_path, monkeypatch, kind='startup'):
import win32con, win32event
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
root=tmp_path/'evidence';root.mkdir()
operation='catalog' if kind=='catalog' else 'verify'
desktop=('CbbManagement_' if kind=='catalog' else 'CbbVerify_')+'owned'
job=dict(operation_id='owned',operation=operation,library=str(library),lmc_file=str(library),
block='Bad',root=str(root),desktop=desktop,interactive_input=False,
project=str(library.parent/'ReusableBlocksLP/Bad/Work/Bad.prj'),
pcb=str(library.parent/'ReusableBlocksLP/Bad/Work/PCB/Bad.pcb'),
session_record_path=str(root/'session.json'))
if kind=='catalog':job['worker_role']='catalog_readonly'
worker=dict(role='worker',pid=11,created_handle='worker-created',image='C:/Python/python.exe',
owner_sid='owner',session_id=1)
native=dict(role='native',pid=12,created_handle='native-created',
image='D:/Mentor/LibraryManager.exe' if kind=='catalog' else 'D:/Mentor/ExpeditionPCB.exe',
owner_sid='owner',session_id=1)
sessions.write_session_record(root/'session.json',dict(operation_id='owned',operation=operation,
library=str(library),block='Bad',desktop=desktop,processes=[worker]))
sessions.write_session_record(root/'worker-state.json',dict(operation_id='owned',phase='UNCONFIRMED',processes=[native]))
result=dict(status='FAIL',safe_to_continue=False,error_stage='PCB_STARTING',
error_category='MENTOR_DATABASE_LOAD_FAILED',block_name='Bad',evidence_path=str(root/'result.json'))
if kind=='saved':
result.update(error_stage='library_flag',error_category='MENTOR_VERIFY_NOT_COMMITTED',
write_outcome=dict(save_state='COMMITTED',close_state='CLOSED',helper_state='EXITED',interrupted=False))
if kind=='catalog':result=dict(success=False,safe_to_continue=False,detail='catalog close failed')
(root/'request.json').write_text(json.dumps(job))
(root/'result.json').write_text(json.dumps(result))
windows=[dict(hwnd=100,**{'class':'Afx:main'},title='Library Manager' if kind=='catalog' else 'Expedition PCB',
desktop=desktop,enabled=True,documents=[],children=[])]
state=dict(worker_alive=False,native_alive=True,identity_changed=False,posts=[])
monkeypatch.setattr(residual,'_process_handle',lambda pid,**kw:nullcontext(pid))
monkeypatch.setattr(residual,'_handle_identity',lambda handle:
{k:(('replacement' if state['identity_changed'] else v) if k=='created_handle' else v)
for k,v in (worker if handle==11 else native).items() if k in ('created_handle','image')})
monkeypatch.setattr(residual,'_force_ownership',lambda *a:dict(force_user_confirmed=True,owner_sid='owner',session_id=1))
monkeypatch.setattr(residual,'_process_windows',lambda *a,**kw:{12:windows})
monkeypatch.setattr(sessions,'active_write_records',lambda library:[])
wait=win32event.WaitForSingleObject
monkeypatch.setattr(win32event,'WaitForSingleObject',lambda handle,ms:
(win32con.WAIT_TIMEOUT if state['worker_alive' if handle==11 else 'native_alive'] else win32con.WAIT_OBJECT_0)
if handle in (11,12) else wait(handle,ms))
def post(window, hwnd, pid, message):
record=sessions.read_session_record(root/'session.json',evidence_root=root)
assert record.get('owned_idle_cleanup'), 'intent must be durable before native action'
state['posts'].append((hwnd,pid,message))
state['native_alive']=False
monkeypatch.setattr(residual,'_post_window_message',post)
return root,job,result,windows,state
@pytest.mark.parametrize('kind',['startup','saved','catalog'])
def test_owned_idle_client_is_closed_once_without_changing_business_result(tmp_path,monkeypatch,kind):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch,kind)
before=(root/'result.json').read_bytes()
assert residual.finish_owned_idle_session(root/'session.json')
assert state['posts']==[(100,12,16)] and not state['native_alive']
residual.finish_owned_idle_session(root/'session.json')
assert state['posts']==[(100,12,16)]
assert (root/'result.json').read_bytes()==before
@pytest.mark.parametrize('obstacle',['worker_alive','identity_changed','documents','hidden_document','unknown',
'progress','desktop','request_identity','save_unknown','other_write','stopped','claim_io','window_race'])
def test_unproved_or_writing_client_is_never_automatically_closed(tmp_path,monkeypatch,obstacle):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch)
stop=Event()
if obstacle in ('worker_alive','identity_changed'):state[obstacle]=True
if obstacle=='documents':windows[0]['documents']=[55]
if obstacle=='hidden_document':windows[0]['children'].append(dict(hwnd=55,**{'class':'Afx:document'},visible=False))
if obstacle=='unknown':windows.append(dict(hwnd=200,**{'class':'#32770'},title='Unknown',enabled=True,desktop=job['desktop'],documents=[],children=[]))
if obstacle=='progress':windows[0]['children'].append(dict(hwnd=60,**{'class':'msctls_progress32'}))
if obstacle=='desktop':windows[0]['desktop']='Default'
if obstacle=='request_identity':
job['operation_id']='other';(root/'request.json').write_text(json.dumps(job))
if obstacle=='save_unknown':(root/'save.log').write_text('SAVE_START\n')
if obstacle=='other_write':monkeypatch.setattr(sessions,'active_write_records',lambda _: [dict(operation_id='other')])
if obstacle=='stopped':stop.set()
if obstacle=='claim_io':
monkeypatch.setattr(sessions,'write_session_record',lambda *a,**kw: (_ for _ in ()).throw(OSError('journal unavailable')))
if obstacle=='window_race':
original=sessions.write_session_record
def write(path,value):
original(path,value)
if value.get('owned_idle_cleanup'):windows[0]['documents']=[55]
monkeypatch.setattr(sessions,'write_session_record',write)
residual.finish_owned_idle_session(root/'session.json',stop=stop)
assert not state['posts'] and state['native_alive']
def test_late_release_actively_finishes_owned_idle_client_then_proves_shared_files(tmp_path,monkeypatch):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch)
monkeypatch.setattr(sessions,'inspect_session_record',lambda *a,**kw:
dict(status='ACTIVE' if state['native_alive'] else 'UNCONFIRMED'))
def release(library,evidence,**kw):
assert not state['native_alive'], 'resource proof must follow native cleanup'
return dict(status='RELEASE_CONFIRMED',lease_state='RELEASED',library=library,
blocked_resources=[],resource_scope=dict(scope_state='OBSERVED'))
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library',release)
failed=VerifyResult('FAIL',stderr='database load failed',safe_to_continue=False,
evidence_path=root/'result.json')
updated=lifecycle.recheck_failed_release(job['library'],'Bad',failed)
assert updated.status=='FAIL' and updated.safe_to_continue
assert state['posts']==[(100,12,16)]
def test_closed_client_does_not_imply_shared_database_released(tmp_path,monkeypatch):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch)
monkeypatch.setattr(sessions,'inspect_session_record',lambda *a,**kw:
dict(status='ACTIVE' if state['native_alive'] else 'UNCONFIRMED'))
from cbb_refresh_verify.library_lock import LibraryBusy
def release(*a,**kw):raise LibraryBusy('shared database still held by another client')
monkeypatch.setattr('cbb_refresh_verify.library_lock.release_retained_library',release)
failed=VerifyResult('FAIL',safe_to_continue=False,evidence_path=root/'result.json')
updated=lifecycle.recheck_failed_release(job['library'],'Bad',failed)
assert not updated.safe_to_continue and updated.status=='FAIL'
assert state['posts']==[(100,12,16)]
attempt=json.loads((root/'late-release-attempt.json').read_text())
assert 'shared database' in attempt['detail']
def test_retained_verify_lease_does_not_expand_one_target_to_every_cbb(tmp_path,monkeypatch):
from cbb_refresh_verify import verify_runner as runner, library_lock as locks
library=tmp_path/'library/lib.lmc';library.parent.mkdir();library.touch()
other=library.parent/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
other.parent.mkdir(parents=True);other.write_text('unrelated occupied engineering database')
evidence=tmp_path/'evidence/result.json';evidence.parent.mkdir()
evidence.write_text('{}')
monkeypatch.setattr(runner,'_run_verify_serialized',lambda *a,**kw:
VerifyResult('FAIL',safe_to_continue=False,evidence_path=evidence))
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:[])
result=runner._run_verify_task(runner.VerifyRequest(library,'Bad',evidence.parent))
assert not result.safe_to_continue
try:
proof=locks.release_retained_library(library,tmp_path/'release',block_name='Bad')
assert proof['proof_scope']=='BLOCK' and proof['proof_block_name']=='Bad'
assert other.read_text()=='unrelated occupied engineering database'
finally:
with locks._guard:
owner=locks._owners.pop(locks.LibraryLock(library).key,None)
if owner:owner['handle'].Close()
@pytest.mark.parametrize('read_only',[False,True])
def test_background_observer_finishes_owned_idle_client_but_cold_observation_stays_read_only(tmp_path,monkeypatch,read_only):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch)
def reconcile(*a,**kw):
return dict(status='ACTIVE' if state['native_alive'] else 'RELEASED',operation_id='owned',
library=job['library'],block='Bad',release_proof=None)
monkeypatch.setattr(sessions,'_reconcile',reconcile)
stop=Event()
outcome=sessions.observe_retained_session(root/'session.json',evidence_root=root,
observe_only=read_only,stop=stop,progress=lambda value:stop.set())
assert outcome['status']==('ACTIVE' if read_only else 'RELEASED')
assert state['posts']==([] if read_only else [(100,12,16)])
def test_real_shared_database_handle_still_prevents_release_after_own_client_exits(tmp_path,monkeypatch):
import win32con,win32file
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch)
library=Path(job['library'])
shared=library.parent/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
shared.parent.mkdir(parents=True);shared.write_bytes(b'actual shared database fixture')
monkeypatch.setattr(sessions,'inspect_session_record',lambda *a,**kw:
dict(status='ACTIVE' if state['native_alive'] else 'UNCONFIRMED'))
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners',lambda *_:[])
held=win32file.CreateFile(str(shared),win32con.GENERIC_READ,0,None,win32con.OPEN_EXISTING,0,None)
try:
failed=VerifyResult('FAIL',safe_to_continue=False,evidence_path=root/'result.json')
updated=lifecycle.recheck_failed_release(library,'Bad',failed)
assert state['posts']==[(100,12,16)] and not updated.safe_to_continue
attempt=json.loads((root/'late-release-attempt.json').read_text())
assert 'icdb.dat' in attempt['detail']
assert attempt['status']=='IN_USE' and attempt['blocked_resources']==[str(shared)]
finally:
held.Close()
@pytest.mark.parametrize('malformed',['request','result','write_outcome'])
def test_malformed_record_never_authorizes_or_crashes_cleanup(tmp_path,monkeypatch,malformed):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch,'saved')
if malformed=='write_outcome':
result['write_outcome']=['not facts'];(root/'result.json').write_text(json.dumps(result))
else:
(root/(malformed+'.json')).write_text('[]')
assert not residual.finish_owned_idle_session(root/'session.json')
assert not state['posts']
@pytest.mark.parametrize('changed',['result_block','result_path','state_after_claim'])
def test_wrong_result_or_changed_state_cannot_authorize_normal_close(tmp_path,monkeypatch,changed):
root,job,result,windows,state=owned_fixture(tmp_path,monkeypatch,'saved')
if changed=='result_block':result['block_name']='Other'
if changed=='result_path':result['evidence_path']=str(tmp_path/'other/result.json')
(root/'result.json').write_text(json.dumps(result))
if changed=='state_after_claim':
write=sessions.write_session_record
def changed_state(path,record):
write(path,record)
if record.get('owned_idle_cleanup'):
previous=sessions.read_session_record(root/'worker-state.json',evidence_root=root)
write(root/'worker-state.json',{**previous,'phase':'NATIVE_CALL'})
monkeypatch.setattr(sessions,'write_session_record',changed_state)
assert not residual.finish_owned_idle_session(root/'session.json')
assert not state['posts']
+208
View File
@@ -112,3 +112,211 @@ def test_readwrite_choice_rejects_replaced_native_button(tmp_path,monkeypatch):
changed=replace(original,controls=tuple(replace(c,handle=c.handle+1) if c.control_id==6 else c changed=replace(original,controls=tuple(replace(c,handle=c.handle+1) if c.control_id==6 else c
for c in original.controls)) for c in original.controls))
assert controller.handle(changed,(changed,),**kwargs).error_code=='DATABASE_RECOVERY_REQUIRED' assert controller.handle(changed,(changed,),**kwargs).error_code=='DATABASE_RECOVERY_REQUIRED'
@pytest.mark.parametrize('origin', ['user', 'timeout_default'])
@pytest.mark.parametrize('guard_error, control, code', [
(None, 6, ''),
(OSError('共享数据库被占用:SymbolLibs/icdb.dat'), 7, 'PCB_OPEN_SKIPPED'),
(TimeoutError('原生检查超时'), 7, 'PCB_OPEN_SKIPPED'),
])
def test_normal_readwrite_uses_same_resource_check(tmp_path, monkeypatch, origin, guard_error, control, code):
from contextlib import contextmanager
import json
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'owned'})
events = []
@contextmanager
def guard(*_, require_complete_proof=False):
assert require_complete_proof
events.append('probe')
if guard_error is not None:
raise guard_error
yield
events.append('released_probe_handles')
monkeypatch.setattr(consent, 'resource_guard', guard)
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
shown = []
def perform(_, action, phase):
clicked = action['target']['control_id']
events.append(clicked)
return SimpleNamespace(accepted_controls=(clicked,), error_code='', detail='', channel='win32_button_click')
kwargs = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, perform=perform)
controller.handle(snapshot(), (snapshot(),), **kwargs)
assert not events
shown[0].choose('continue', origin=origin)
result = controller.handle(snapshot(), (snapshot(),), **kwargs)
assert result.error_code == code
assert events == (['probe', 'released_probe_handles', control] if guard_error is None else ['probe', control])
if guard_error is not None:
assert str(guard_error) in result.detail
record = json.loads((tmp_path/'pcb-open-user-choice.json').read_text(encoding='utf-8'))
assert record['decision_origin'] == origin
assert record['choice'] == ('continue' if control == 6 else 'skip')
controller.handle(snapshot(), (snapshot(),), **kwargs)
assert events.count(control) == 1
def test_unattended_ordinary_dialog_defaults_to_checking_resources(qtbot):
from cbb_refresh_verify.pcb_open_consent import OpenChoice
from cbb_refresh_verify.ui.pcb_open_dialog import PcbOpenDialog
choice = OpenChoice('A', 'lib.lmc', auto_confirm=True)
dialog = PcbOpenDialog(choice)
qtbot.addWidget(dialog)
assert dialog.defaultButton() is dialog.continue_button
dialog.skip_button.click()
assert choice.decision == 'skip'
assert choice.decision_origin == 'user'
def test_unattended_readwrite_checks_actual_shared_database_handle(tmp_path, monkeypatch):
import win32con
import win32file
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify import owner_probe
library = tmp_path/'lib.lmc'
work = tmp_path/'ReusableBlocksLP/A/Work'
project, pcb = work/'A.prj', work/'PCB/A.pcb'
shared = tmp_path/'SymbolLibs/__ReusableBlocksSymb/icdb.dat'
for path in (library, work/'database/icdb.dat', pcb.parent/'Layout/LayoutDB.lyt', shared):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(b'fixture')
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "database"\n')
pcb.write_text('KEY ProjectFile "../A.prj"\n')
owner = {'target': 'bound'}
monkeypatch.setattr(consent, 'validate_owner', lambda *_: owner)
monkeypatch.setattr(owner_probe, 'query_process_snapshot', lambda: [])
def run(attempt, expected_control):
evidence = tmp_path/attempt
evidence.mkdir()
controller = consent.OpenController(dict(root=str(evidence), block_name='A', lmc_file=str(library),
project=str(project), pcb=str(pcb), desktop='CbbVerify_test'), auto_confirm=True)
shown, actions = [], []
def perform(_, action, phase):
actions.append(action['target']['control_id'])
if expected_control == 6:
handle = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
handle.Close()
return SimpleNamespace(error_code='', accepted_controls=tuple(actions), detail='', channel='win32_button_click')
options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append, perform=perform)
controller.handle(snapshot(), (snapshot(),), **options)
shown[0].choose('continue', origin='timeout_default')
result = controller.handle(snapshot(), (snapshot(),), **options)
assert actions == [expected_control], result.detail
return result, evidence
held = win32file.CreateFile(str(shared), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
try:
skipped, evidence = run('occupied', 7)
assert skipped.error_code == 'PCB_OPEN_SKIPPED'
assert str(shared) in skipped.detail
assert not (evidence/'pcb-open-resource-proof.json').exists()
finally:
held.Close()
resumed, evidence = run('released', 6)
assert not resumed.error_code
assert (evidence/'pcb-open-resource-proof.json').is_file()
from cbb_refresh_verify import native_repair
address = work/'database/cdbsvr/sAddress.adr'
address.parent.mkdir()
address.write_text('recorded address')
verdict = 'NOT_IN_USE'
inspected = []
def inspect(target, root, **kwargs):
assert kwargs['inspection_only'] is True
assert target.project == project and target.database == address.parent.parent
inspected.append(target.database)
output = (f'Loading project file [{project}].\nChecking if project is in use.\n'
+ ("Project is not in use. Full iCDB Project Backup's functionality is available.\n"
"Backup information loaded correctly." if verdict == 'NOT_IN_USE' else 'Project is in use.'))
return dict(status=verdict, repair_required=False, inspection_only=True,
repair_requested=False, native_pid=100, native_exit_code=0,
native_identity=dict(pid=100, created_handle=1, image='iCDBProjectBackup.exe',
owner_sid='test', session_id=1),
release={'native_exited': True}, project=str(project),
database=str(target.database), output=output)
monkeypatch.setattr(native_repair, 'run_native_repair', inspect)
unoccupied, _ = run('address-checked-unoccupied', 6)
assert not unoccupied.error_code and inspected == [address.parent.parent]
verdict = 'IN_USE'
occupied, _ = run('address-checked-occupied', 7)
assert occupied.error_code == 'PCB_OPEN_SKIPPED' and 'PCB_OPEN_DATABASE_IN_USE' in occupied.detail
assert inspected == [address.parent.parent]*2
assert address.read_text() == 'recorded address'
address.unlink()
project.write_text('KEY PCBDesignPath "PCB/A.pcb"\nKEY iCDBDir "../../../outside"\n')
unbound, _ = run('wrong-project-database', 7)
assert 'iCDBDir' in unbound.detail
def test_stop_during_receipt_never_sends_native_yes(tmp_path, monkeypatch):
from cbb_refresh_verify import management
from cbb_refresh_verify import pcb_open_consent as consent
from cbb_refresh_verify.operation_queue import QueueCancelled
stopped = False
original = management._write_json
def write_choice(path, value):
nonlocal stopped
original(path, value)
stopped = True
def check_active():
if stopped:
raise QueueCancelled('cancelled')
monkeypatch.setattr(management, '_write_json', write_choice)
monkeypatch.setattr('cbb_refresh_verify.operation_queue.check_active', check_active)
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'bound'})
monkeypatch.setattr(consent, 'resource_guard', lambda *_, **__: nullcontext())
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
shown = []
options = dict(target_pid=20, launcher_pid=10, worker_pid=5, show=shown.append,
perform=lambda *_: pytest.fail('sent during cancellation'))
controller.handle(snapshot(), (snapshot(),), **options)
shown[0].choose('continue')
assert controller.handle(snapshot(), (snapshot(),), **options).error_code == 'USER_CANCELLED'
def test_headless_opt_in_checks_resources_without_presenting_dialog(tmp_path, monkeypatch):
import json
from cbb_refresh_verify import pcb_open_consent as consent
monkeypatch.setattr(consent, 'validate_owner', lambda *_: {'target': 'bound'})
checked = []
def guard(_, __, *, require_complete_proof):
checked.append(require_complete_proof)
return nullcontext()
monkeypatch.setattr(consent, 'resource_guard', guard)
controller = consent.OpenController(dict(root=str(tmp_path), block_name='A', lmc_file='lib.lmc',
project='A.prj', pcb='A.pcb', desktop='CbbVerify_test'), auto_confirm=True)
actions = []
def perform(_, action, phase):
actions.append(action['target']['control_id'])
return SimpleNamespace(error_code='', accepted_controls=tuple(actions), detail='', channel='win32_button_click')
result = controller.handle(snapshot(), (snapshot(),), target_pid=20, launcher_pid=10, worker_pid=5,
show=None, perform=perform)
assert not result.error_code
assert checked == [True] and actions == [6]
receipt = json.loads((tmp_path/'pcb-open-user-choice.json').read_text(encoding='utf-8'))
assert receipt['decision_origin'] == 'headless_opt_in'
+112
View File
@@ -0,0 +1,112 @@
"""PR 16: handoff must preserve control flow, resource cleanup and cancellation."""
import json
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
def test_verify_handoff_skips_duplicate_native_cleanup_and_keeps_result(tmp_path, monkeypatch):
from cbb_refresh_verify import operation_queue, verify_runner
from test_cancelled_session_handoff import worker_fixture
handoff = operation_queue.hold_native_handoff
state, _, run = worker_fixture(tmp_path, monkeypatch)
monkeypatch.setattr(operation_queue, 'hold_native_handoff', handoff)
late_cleanup = []
monkeypatch.setattr(verify_runner, '_cleanup_session_processes',
lambda *a, **kw: late_cleanup.append(True) or {'safe_to_continue': False})
completed = Event()
original = verify_runner._run_verify_task
def execute(*args, **kwargs):
try:
return original(*args, **kwargs)
finally:
completed.set()
monkeypatch.setattr(verify_runner, '_run_verify_task', execute)
result = run(True)
assert completed.wait(3)
assert result.status == 'CANCELLED' and not result.safe_to_continue
assert state['observers'] and not state['closed']
assert not late_cleanup, 'The registered observer owns native cleanup after handoff'
saved = json.loads(state['path'].with_name('result.json').read_text(encoding='utf-8'))
assert saved['status'] == 'CANCELLED' and saved['safe_to_continue'] is False
@pytest.mark.parametrize('registration_error', [False, True])
def test_repair_handoff_always_closes_local_worker_resources(tmp_path, monkeypatch, registration_error):
from cbb_refresh_verify import desktop_worker, native_repair, session_record
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff
events = []
class Worker:
pid = 700
session_record_path = tmp_path/'session.json'
def __init__(self, *args): pass
def bind_cancellation(self, path): pass
def bind_session(self, job): pass
def poll(self): return None
def request_stop(self): events.append('stop')
def close(self): events.append('close')
monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker)
ticks = iter((0, 100))
monkeypatch.setattr(native_repair, 'time', SimpleNamespace(monotonic=lambda: next(ticks)))
def observe(*args, **kwargs):
events.append('observe')
if registration_error:
raise OSError('observer registration failed')
monkeypatch.setattr(session_record, 'handoff_session', observe)
context = BatchTaskContext(str(tmp_path/'library.lmc'))
completed = Event()
def execute():
try:
return native_repair._supervise_repair([], 'CbbRepair_test', tmp_path/'cancel',
tmp_path, 1, None, None, {'start_gate': str(tmp_path/'start')})
finally:
completed.set()
with pytest.raises(OSError if registration_error else TaskHandoff):
context.run(execute)
assert completed.wait(3)
assert events == ['stop', 'observe', 'close']
def test_icdb_fallback_stop_cancels_the_active_task_context(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.verify_runner import VerifyResult
from test_ui_filters import load_window
entered, release = Event(), Event()
def verify(request):
entered.set()
assert release.wait(3)
return VerifyResult('CANCELLED')
window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify)
window._start_icdb_check(['Beta'])
try:
qtbot.waitUntil(entered.is_set)
window.stop.set()
assert window.icdb_task.stop.is_set(), 'Fallback Stop must cancel the running ICDB task'
finally:
window.icdb_task.cancel()
release.set()
qtbot.waitUntil(lambda: not window.icdb_task.active)
@pytest.mark.parametrize('mode', ['versions', 'repair'])
@pytest.mark.parametrize('config', [
'KEY iCDBDir "C:\\outside\\database"\n',
'KEY iCDBDir "database"\nKEY iCDBDir "other"\n',
])
def test_ambiguous_or_absolute_database_stops_before_native_launch(tmp_path, monkeypatch, mode, config):
from cbb_refresh_verify import native_backup
from test_native_backup import project_fixture
request, project = project_fixture(tmp_path)
project.write_text(config, encoding='utf-8')
monkeypatch.setattr(native_backup, 'native_backup_executable',
lambda *_: pytest.fail('Invalid database binding reached native preparation'))
with pytest.raises(ValueError, match='NATIVE_TARGET_UNCONFIRMED'):
native_backup.launch_native_backup(request, mode=mode)
assert not request.evidence_dir.exists()
+152
View File
@@ -0,0 +1,152 @@
from threading import Event
from types import SimpleNamespace
import time
import pytest
from test_backup_recovery import recovery_files
from cbb_refresh_verify import backup_recovery as recovery
from cbb_refresh_verify.library_lock import LibraryLock,LibraryBusy
from cbb_refresh_verify.operation_queue import BatchTaskContext,TaskHandoff,native_channel
from cbb_refresh_verify.verify_runner import VerifyResult
@pytest.mark.parametrize('boundary',['idle','staging','final_manifest'])
@pytest.mark.parametrize('cancel',[False,True])
def test_real_recovery_handoff_preserves_A_lease_without_blocking_B_or_late_install(recovery_files,monkeypatch,boundary,cancel):
request,original,source=recovery_files
entered,release,done=Event(),Event(),Event();calls=[]
context=BatchTaskContext(str(request.lmc_file),native_policy='external')
from cbb_refresh_verify import operation_queue
# Expire inactivity at the chosen stall, not during variable filesystem setup.
clock=[time.monotonic()]
monkeypatch.setattr(operation_queue,'time',SimpleNamespace(
monotonic=lambda:clock[0] if clock[0] is not None else time.monotonic()))
def hold():
entered.set()
if cancel:context.cancel()
clock[0]=time.monotonic()+1
assert release.wait(5)
def idle(*args):
if boundary=='idle' and not entered.is_set():hold()
copier=recovery._copy_verified
def copy(*args,**kwargs):
value=copier(*args,**kwargs)
if boundary=='staging' and not entered.is_set():hold()
return value
monkeypatch.setattr(recovery,'_copy_verified',copy)
manifest=recovery._manifest
def build(root,**kwargs):
value=manifest(root,**kwargs)
if boundary=='final_manifest' and root==request.lmc_file.parent:hold()
return value
monkeypatch.setattr(recovery,'_manifest',build)
def verify(req,**kwargs):
calls.append(req.lmc_file)
return VerifyResult('PASS',library_flag='GREEN')
def action():
try:return recovery.recover_from_backup(request,source,verifier=verify,idle_check=idle)
finally:done.set()
refusal=None
try:
with pytest.raises(TaskHandoff):context.run(action,timeout_seconds=.3)
assert entered.is_set()
clock[0]=None
with pytest.raises(LibraryBusy):
with LibraryLock(request.lmc_file):pytest.fail('A lease lost during stalled metadata')
def B():
with native_channel():return 'admitted'
try:
result=BatchTaskContext(str(request.lmc_file.parent.parent/'B/library.lmc'),native_policy='external').run(B)
except RuntimeError as error:refusal=str(error)
finally:
release.set();assert done.wait(5);context.close(timeout_seconds=2)
assert (original.parent/'database/icdb.dat').read_bytes()==b'damaged'
assert not list(original.parent.parent.glob('Work.before-restore-*'))
assert len(calls)==(1 if boundary=='final_manifest' else 0)
assert request.lmc_file not in calls
assert refusal is None,refusal
assert result=='admitted'
def test_cancel_during_work_swap_finishes_atomic_pair_without_target_verify(recovery_files,monkeypatch):
from pathlib import Path
request,original,source=recovery_files
context=BatchTaskContext(str(request.lmc_file),native_policy='external');calls=[]
rename=Path.rename
def swap(path,target):
value=rename(path,target)
if path==original.parent:context.cancel()
return value
monkeypatch.setattr(Path,'rename',swap)
def verify(req,**kwargs):
calls.append(req.lmc_file)
return VerifyResult('PASS',library_flag='GREEN')
result=context.run(lambda:recovery.recover_from_backup(request,source,verifier=verify,idle_check=lambda *a:None))
assert result.status!='PASS'
assert (original.parent/'database/icdb.dat').read_bytes()==b'healthy'
retained=list(original.parent.parent.glob('Work.before-restore-*'))
assert len(retained)==1 and (retained[0]/'database/icdb.dat').read_bytes()==b'damaged'
assert len(calls)==1 and request.lmc_file not in calls
def test_shutdown_cannot_abandon_local_work_swap_or_hold_host_channel(recovery_files,monkeypatch):
from pathlib import Path
from threading import Thread
request,original,source=recovery_files
context=BatchTaskContext(str(request.lmc_file),native_policy='external')
entered,release,done=Event(),Event(),Event();calls=[];errors=[]
rename=Path.rename
def swap(path,target):
value=rename(path,target)
if path==original.parent:
entered.set();assert release.wait(5)
return value
monkeypatch.setattr(Path,'rename',swap)
def verify(req,**kwargs):
calls.append(req.lmc_file);return VerifyResult('PASS',library_flag='GREEN')
def run():
try:context.run(lambda:recovery.recover_from_backup(request,source,verifier=verify,idle_check=lambda *a:None))
except Exception as error:errors.append(error)
finally:done.set()
thread=Thread(target=run);thread.start()
try:
assert entered.wait(3)
state=context.shutdown()
assert state['shutdown_handoff'] is False
assert not done.wait(.1)
def B():
with native_channel():return True
assert BatchTaskContext(str(request.lmc_file.parent.parent/'B/library.lmc'),native_policy='external').run(B)
finally:
release.set();thread.join(5)
assert done.is_set() and len(calls)==1
assert (original.parent/'database/icdb.dat').read_bytes()==b'healthy'
def test_cancelled_failed_install_rolls_back_before_releasing_commit(recovery_files,monkeypatch):
from pathlib import Path
request,original,source=recovery_files;calls=[]
context=BatchTaskContext(str(request.lmc_file),native_policy='external');rename=Path.rename
def swap(path,target):
if path.name.startswith('Work.restore-'):
context.cancel();raise OSError('install rename refused')
return rename(path,target)
monkeypatch.setattr(Path,'rename',swap)
def verify(req,**kwargs):
calls.append(req.lmc_file);return VerifyResult('PASS',library_flag='GREEN')
result=context.run(lambda:recovery.recover_from_backup(request,source,verifier=verify,idle_check=lambda *a:None))
assert result.status!='PASS' and 'install rename refused' in result.stderr
assert (original.parent/'database/icdb.dat').read_bytes()==b'damaged'
assert not list(original.parent.parent.glob('Work.before-restore-*'))
assert len(calls)==1
def test_metadata_only_context_cannot_enter_local_commit(tmp_path):
from cbb_refresh_verify.operation_queue import local_commit
mutations=[]
def commit():
with local_commit():mutations.append('rename')
with pytest.raises(RuntimeError,match='Read-only metadata'):
BatchTaskContext(str(tmp_path/'lib.lmc')).run(commit,metadata_only=True)
assert not mutations
+3
View File
@@ -10,6 +10,7 @@ from test_cancelled_loaded_startup import loaded_fixture
def registered_fixture(tmp_path,monkeypatch,*,closed=False,obstacle=''): def registered_fixture(tmp_path,monkeypatch,*,closed=False,obstacle=''):
import win32con,win32event import win32con,win32event
kernel_wait=win32event.WaitForSingleObject
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch) job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
state.update(tip=False,closing=closed) state.update(tip=False,closing=closed)
state['observer_requests']=[] state['observer_requests']=[]
@@ -17,6 +18,7 @@ def registered_fixture(tmp_path,monkeypatch,*,closed=False,obstacle=''):
state['observer_requests'].append((path,list(messages),kw))) state['observer_requests'].append((path,list(messages),kw)))
job.update(operation_id='verify-old',operation='verify',library=job['lmc_file'],block='IP101GR', job.update(operation_id='verify-old',operation='verify',library=job['lmc_file'],block='IP101GR',
session_record_path=str(tmp_path/'session.json'),interactive_input=False) session_record_path=str(tmp_path/'session.json'),interactive_input=False)
state['prelaunch_baseline']=job['diagnostic_log_baseline']
job.pop('diagnostic_log_baseline') # Old builds never persisted this; do not invent it. job.pop('diagnostic_log_baseline') # Old builds never persisted this; do not invent it.
identity=dict(pid=12,created_handle='native-created',image=records[0][1],owner_sid='current',session_id=1) identity=dict(pid=12,created_handle='native-created',image=records[0][1],owner_sid='current',session_id=1)
worker=dict(pid=11,created_handle='worker-created',image='C:/App/CbbRefreshVerify.exe',owner_sid='current',session_id=1) worker=dict(pid=11,created_handle='worker-created',image='C:/App/CbbRefreshVerify.exe',owner_sid='current',session_id=1)
@@ -51,6 +53,7 @@ def registered_fixture(tmp_path,monkeypatch,*,closed=False,obstacle=''):
monkeypatch.setattr(sessions,'_handle_identity',lambda handle:{k:v for k,v in (worker if handle==11 else identity).items() if k in ('created_handle','image')}) monkeypatch.setattr(sessions,'_handle_identity',lambda handle:{k:v for k,v in (worker if handle==11 else identity).items() if k in ('created_handle','image')})
monkeypatch.setattr(sessions,'_force_ownership',lambda h,p:{'owner_sid':'current','session_id':1,'force_user_confirmed':True}) monkeypatch.setattr(sessions,'_force_ownership',lambda h,p:{'owner_sid':'current','session_id':1,'force_user_confirmed':True})
def wait(handle,ms): def wait(handle,ms):
if handle not in (11,12):return kernel_wait(handle,ms)
state['ticks']+=ms/1000 state['ticks']+=ms/1000
return win32con.WAIT_OBJECT_0 if handle==11 and obstacle!='live_worker' or handle==12 and not records else win32con.WAIT_TIMEOUT return win32con.WAIT_OBJECT_0 if handle==11 and obstacle!='live_worker' or handle==12 and not records else win32con.WAIT_TIMEOUT
monkeypatch.setattr(win32event,'WaitForSingleObject',wait) monkeypatch.setattr(win32event,'WaitForSingleObject',wait)
+14
View File
@@ -166,3 +166,17 @@ def test_retained_mapping_logs_context_and_confirmed_release_guidance(batch_cli,
assert 'Z:' in notice and r'\\server\share' in notice assert 'Z:' in notice and r'\\server\share' in notice
assert '释放残留会话' in notice and '确认' in notice assert '释放残留会话' in notice and '确认' in notice
assert 'net use' not in notice.lower() assert 'net use' not in notice.lower()
def test_batch_cli_can_enable_verified_pcb_open(batch_cli, monkeypatch):
app, runner, _, _, _ = batch_cli
received = []
def run(requests, **kwargs):
received.extend(request.auto_confirm_pcb_open for request in requests)
return [VerifyResult('PASS') for _ in requests]
monkeypatch.setattr(runner, 'run_batch', run)
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One']) == 0
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One', '--auto-confirm-pcb-open']) == 0
assert received == [False, True]
+23 -1
View File
@@ -88,7 +88,7 @@ End Class
def run_helper(tmp_path, *, save_body='Save = True', close_body='Close = True', def run_helper(tmp_path, *, save_body='Save = True', close_body='Close = True',
is_saved='True', gated=False, cancelled=False): is_saved='True', gated=False, cancelled=False, transform=None):
source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8') source = Path('src/cbb_refresh_verify/save_verified_block.vbs').read_text('utf-8')
classes = ''' classes = '''
Class FakePi Class FakePi
@@ -145,6 +145,8 @@ End Class
source = source.replace('Option Explicit', 'Option Explicit\nDim closedDoc\n' + classes) source = source.replace('Option Explicit', 'Option Explicit\nDim closedDoc\n' + classes)
source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp') source = source.replace('GetObject(, "MGCPCB.Application")', 'New FakeApp')
source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic') source = source.replace('CreateObject("MGCPCBAutomationLicensing.Application")', 'New FakeLic')
if transform is not None:
source = transform(source)
harness = tmp_path/'facts.vbs' harness = tmp_path/'facts.vbs'
harness.write_text(source, encoding='ascii') harness.write_text(source, encoding='ascii')
cancel = tmp_path/'cancel.signal' cancel = tmp_path/'cancel.signal'
@@ -201,3 +203,23 @@ def test_unopened_gate_cancellation_exits_before_com(tmp_path):
assert 'TEST_SAVE_CALLED' not in result.stdout assert 'TEST_SAVE_CALLED' not in result.stdout
assert 'VALIDATE_START' not in result.stdout assert 'VALIDATE_START' not in result.stdout
assert result.returncode == 9 assert result.returncode == 9
def test_post_save_identity_failure_names_actual_and_expected_values(tmp_path):
result = run_helper(tmp_path, transform=lambda source:source.replace(
'ProjectFile = WScript.Arguments(0)',
'If afterSave Then\nProjectFile = "other.prj"\nElse\nProjectFile = WScript.Arguments(0)\nEnd If')
.replace('Dim closedDoc', 'Dim closedDoc, afterSave')
.replace('Save = True', 'afterSave = True\nSave = True'))
assert result.returncode == 8, result.stdout + result.stderr
assert 'POST_SAVE_IDENTITY|project=other.prj|expected=expected.prj|document=CBB.pcb|expected_document=CBB.pcb' in result.stdout
assert 'CLOSE_START' not in result.stdout
def test_post_save_transient_unsaved_state_retries_before_closing(tmp_path):
def transform(source):
return source.replace('Dim closedDoc', 'Dim closedDoc, savedCalls').replace(
'IsSaved = True', 'savedCalls = savedCalls + 1\nIsSaved = (savedCalls <> 2)')
result = run_helper(tmp_path, transform=transform)
assert result.returncode == 0, result.stdout + result.stderr
assert 'CLOSE_OK' in result.stdout
+49 -2
View File
@@ -47,7 +47,7 @@ def names(records):
def test_search_and_filters_use_cached_catalog_and_count_visible_states(qtbot, tmp_path, monkeypatch): def test_search_and_filters_use_cached_catalog_and_count_visible_states(qtbot, tmp_path, monkeypatch):
window = load_window(qtbot, tmp_path, monkeypatch) window = load_window(qtbot, tmp_path, monkeypatch)
window.reader = lambda _: pytest.fail('filter reread Mentor') window.reader = lambda _: pytest.fail('filter reread Mentor')
assert window.visible_counts() == {'visible': 5, 'ready': 2, 'error': 3} assert window.visible_counts() == {'visible': 5, 'ready': 2, 'error': 2}
expected = { expected = {
'ready': ['Alpha', 'Missing'], 'non_ready': ['Beta', 'Gamma', 'Delta'], 'ready': ['Alpha', 'Missing'], 'non_ready': ['Beta', 'Gamma', 'Delta'],
'pending': ['Beta'], 'errors': ['Gamma', 'Delta'], 'missing': ['Missing'], 'pending': ['Beta'], 'errors': ['Gamma', 'Delta'], 'missing': ['Missing'],
@@ -58,7 +58,7 @@ def test_search_and_filters_use_cached_catalog_and_count_visible_states(qtbot, t
window.status_filter.setCurrentIndex(window.status_filter.findData('all')) window.status_filter.setCurrentIndex(window.status_filter.findData('all'))
window.search_edit.setText(' ANALOG ') window.search_edit.setText(' ANALOG ')
assert names(window.visible_records()) == ['Gamma', 'Delta'] assert names(window.visible_records()) == ['Gamma', 'Delta']
assert window.visible_counts() == {'visible': 2, 'ready': 0, 'error': 2} assert window.visible_counts() == {'visible': 2, 'ready': 0, 'error': 1}
window.search_edit.setText('aLpH') window.search_edit.setText('aLpH')
assert names(window.visible_records()) == ['Alpha'] assert names(window.visible_records()) == ['Alpha']
assert '1' in window.counts_label.text() assert '1' in window.counts_label.text()
@@ -290,3 +290,50 @@ def test_large_catalog_local_filter_and_selection_remain_responsive(qtbot, tmp_p
print(f'catalog rows={size} load={loaded:.3f}s local_actions={elapsed:.3f}s') print(f'catalog rows={size} load={loaded:.3f}s local_actions={elapsed:.3f}s')
assert elapsed < 2.0 assert elapsed < 2.0
assert window.selected_records() == () assert window.selected_records() == ()
def test_double_click_shows_complete_skipped_reason(qtbot, tmp_path, monkeypatch):
from PySide6.QtWidgets import QApplication, QDialog, QPlainTextEdit, QPushButton
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
reason = ('PCB_OPEN_SKIPPED: 检查未通过\n' +
'\n'.join(f'共享数据库占用记录 {index}' for index in range(30)) +
'\n完整路径 <library>/SymbolLibs/icdb.dat')
window._progress({'block': 'Beta', 'stage': 'SKIPPED', 'detail': reason})
row = window._row_by_name['Beta']
item = window.cbb_table.item(row, 3)
window.cbb_table.scrollToItem(item)
position = window.cbb_table.visualItemRect(item).center()
viewport = window.cbb_table.viewport()
assert viewport.rect().contains(position)
qtbot.mouseClick(viewport, Qt.LeftButton, pos=position)
qtbot.mouseDClick(viewport, Qt.LeftButton, pos=position)
dialogs = [dialog for dialog in window.findChildren(QDialog)
if dialog.isVisible() and '结果详情' in dialog.windowTitle()]
assert len(dialogs) == 1
dialog = dialogs[0]
text = dialog.findChild(QPlainTextEdit)
assert text.isReadOnly()
assert text.toPlainText() == reason
copy, = [button for button in dialog.findChildren(QPushButton) if button.text() == '复制全文']
qtbot.mouseClick(copy, Qt.LeftButton)
assert QApplication.clipboard().text() == reason
dialog.close()
@pytest.mark.parametrize('enabled', [False, True])
def test_pcb_open_option_is_bound_only_to_ordinary_verify(qtbot, tmp_path, monkeypatch, enabled):
requests = []
def verify(request):
requests.append(request)
return VerifyResult('SKIPPED')
window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify)
window.auto_confirm_pcb_open_check.setChecked(enabled)
assert window._request('Beta').auto_confirm_pcb_open is None
window._run(['Beta'])
qtbot.waitUntil(lambda: not window.busy)
assert len(requests) == 1
assert requests[0].auto_confirm_pcb_open is enabled