Compare commits

...
4 Commits
18 changed files with 984 additions and 71 deletions

No files matched your search

@@ -1,6 +1,6 @@
# 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 is pending.
## Executable bindings
@@ -19,6 +19,9 @@ Each case retains its actual executable hash. Rebuilds checked all packaged modu
| B9 | a3f69de | `bfd6c122724f71a2aac4748ed01336a9949aa753f9c58aca55db574668140083` |
| B10 | 701e5cd | `a6271e4219a02123e301ed1e0ea3109e78307bf1f92574b4a5cacb70690695a4` |
| B11 | 8818fa9 | `03452e39f394c3c63113aaa701f64bacf14e817ae3b4e194965f333ecc645b98` |
| B12 | 906cfc0 | `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc` |
| B13 | 5e9509e | `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` |
| B14 | c1e2596 | `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c` |
B9 ZIP SHA-256: `4c589bae6bf7b68732cd7ebe373b2924016c71f6731fd661c1cd0fd848427438`. All 68 packaged modules and required assets/scripts/bridges/icons match the source; all 242 extracted files match the build. Its five pre-cancelled worker entry routes and common GUI/worker/owner-probe/dialog-agent smoke passed without launching Mentor. B8 is separately archived with ZIP SHA-256 `795010cc0b54b995eced859cac1513bf105092e484a44b1231955801deed879f`; B5 retains ZIP SHA-256 `176c7cda89c2a2706f969fa6dca513d2760615491aaf70c19fe7a0688abe471a`.
@@ -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.
B14 ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`; 68 modules/resources, 242 extracted files, five cancelled entries and common smoke passed. B13 actual native cases retain their original hashes. B12 failed late ordinary cancellation remains archived with its exact identity.
## Reported issues A–H
| Issue | Source verification | Actual frozen evidence and limits |
@@ -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. |
| B5-to-B9 legacy release — one confirmation | icdb-check-378044ad1122 / verify-d2acda2739c2; sessions-a5a9fe06b7c1 | Real B5 retained loaded target/Forward; old app normally exited. B9 initial inspection succeeded, one normal Confirm, zero Recheck/second confirmation/manual native actions. Forward disappeared after 3.562 s; 210 read-only snapshots show kernel exit. PCB, launcher and server RELEASED, fresh RELEASE_CONFIRMED at 22.634 s; UI agreed and Confirm disabled. Existing cold observer RELEASED; original cancellation result retained. |
| B10 I3 setup — second pending item | management-f25df6a207ca4744ab4a0c23ddabb06c | Legitimate exact-name update from the existing healthy source, auto-verify off; UPLOADED/safe, native catalog/readback. Prepared two pending items without fabricated native failure. Selection made before final refresh was cleared; disabled Verify rejected the harness click; reselection afterward succeeded. |
| B10 ordinary Stop — 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 result Release | button-watch-1794884430968047900; verify-4f959f61fbc4 | One bounded same-scenario timing repeat caught actual result Release and opened its residual plan. Ordinary Stop again retained Forward, 32.844 s; this remains a failure. Exact manual No/normal Close, no Save/force; sessions-6bfdf0a26476 fresh release. |
| B5-to-B10 affected legacy release | icdb-check-92a3c92f6d6c / verify-9f3856153c79; sessions-82cc60b6eacb | Initial inspection succeeded; one Confirm, zero Recheck/manual native actions. Forward disappeared +6.5 s; 278 read-only samples/kernel exit. Intermediate PARTIAL then fresh RELEASE_CONFIRMED +35.387 s under the same intent; all three clients and existing observer RELEASED, UI agreed. Original CANCELLED/safe=false preserved. Entry was loaded Forward; actual Tip replay is not claimed. |
| B12 ordinary Stop — late loaded failure | verify-642171759614 | UI terminal 7.797 s; loaded Forward at 34.406 s after original cleanup deadline. Manual exact No/normal Close required. Failed-run cleanup only; original CANCELLED/safe=false preserved. |
| B13 ordinary Stop / cross-owner queue | verify-71aee0603183; native-backup-b63e7f708fd5 | Actual candidate worker No/one Close before first 30 s deadline; late kernel exit and fresh candidate/independent proofs. UI terminal 7.375 s; real Versions creation 5.220 s after candidate proof and 1.506 s after independent proof, catalog loaded. No Release/manual ordinary native action. Retained-phase No/Close branch not replayed in Mentor. |
| B13 CBB backup recovery | backup-restore-3f98efb14448; source verify-06c8149375e6; target verify-f902921f2440 | Both PASS/GREEN/safe and COMMITTED/CLOSED/EXITED/RELEASED, installed=true; old Work retained, all 366 original source files unchanged, no native intervention. |
The B2 diagnostic run supports the implemented sole-handler No sequence through observed windows and verified code; there is no separate startup button acknowledgement event. The hidden-owner-chain save branch did not recur on corrected native runs and remains covered by regression tests plus the original captured chain. The original failed diagnostic required manual cleanup and a native crash acknowledgement; that crash was **NOT REPRODUCED** in the subsequent bounded runs.
@@ -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. |
| Library chooser Open/Cancel and Read CBB | Actual chooser/catalog; invalid-input tests | B1 chooser cancellation and catalog; B3 removal/reimport catalog; B4/B5 explicit reload. |
| Select visible, Clear, filter/hidden selection | Actual UI and 381/3,000-row Qt checks | B1/B2 actual controls and view changes; immutable original operation retained. |
| Verify selected / visible non-READY | Actual source native verification and Qt admission | B2 ordinary Verify; B3 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. |
| Manual Repair Cancel/Confirm | Actual native healthy control | B1 native diagnostics/defragmentation; not field-fault recovery proof. |
| Versions / create backup / restore Cancel/Confirm / verify / Close/reopen | Actual exact archive and location | B1 native tool operations and reopening. |
| Add / source chooser / empty input / auto-verify / logs / No/default Yes | Actual source and Qt | B1 duplicate-plus-independent Add; B3 reimport. |
| Same-name update / wrong source / reselection / No/default Yes | Actual source and Qt | B2 mismatch rejected before writing; B3 correct update. |
| Remove / hidden source chooser / No/Yes / result | Actual source and Qt | B3 REMOVED and native catalog absence before reimport. |
| CBB backup recovery / empty input / chooser Cancel / No/Yes | Actual source and Qt | B3 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. |
| Queued cancellation / active dialog close | Qt queue, close, hard-cancel and shutdown tests | B10 recovery dialog queued behind an owned diagnostic, Cancel queued clicked, UI CANCELLED/no native admission/no recovery job. Underlying diagnostic verify-96d285ffa450 completed CHECKED/safe. Earlier second management submission/active lower Close remained disabled. |
| Residual sessions / Recheck / Confirm / Close | Qt exact scope, one-intent observer promotion and real Windows proofs | B5 zero-active-session release; B9 initial inspection and one-confirmation release of a real B5 cancelled session; previous failed/multiple confirmations retained. |
| Native details / Save prompt / native Cancel / forced termination | Qt exact ownership/prompt and default-Cancel tests | Disabled with no matching active owned client. No forced native termination claimed. |
| Conditional result recovery/release/resume buttons | Qt target binding, stale results and single continuation | B10 actual result Release and Continue/no-replay receipts above. 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. |
| Double submission / result remaining open / view changes / restart | Qt and Windows lifecycle tests | Active execute controls disabled; modeless dialogs and view changes observed; B4 no replay. |
| Open logs/evidence / shell errors | Qt dispatch and error reporting | B10 actual Open logs/Open exception clicks opened exact application logs and verify-e464474b7bab folders; complete private Explorer breadcrumbs recorded. Only the two task-created Explorer windows normally closed. No shell-error case is claimed. |
One B1 harness edit targeted the library textbox while a modeless dialog changed control indices. The immutable original-library operation still completed and the changed view was invalidated. This is retained as a harness/misuse event, not a product search failure.
## Final-wave evidence and limits
B14 EXE SHA-256: `0cd5f37b113802bcf3abd07a94d8c5b9f73d40696b1c56af66fedf39112e2d8c`. ZIP SHA-256: `a580e3e9945261761e0eb3968b4e271d9f4745ce982dea96c283af4ab06e565f`. All 68 packaged product modules/resources and all 242 extracted files match source/build. Five pre-cancelled frozen routes and common GUI/worker/owner-probe/dialog-agent smoke passed. Full-suite log SHA-256: `d9c57b7998e02154fb703f0fe2ba1f37f73dc4687d116c4b6efc0e5ad7e5c30e`; JUnit SHA-256: `4303cc123e90689103cc4135e483ac936b04a052067e952a1861ae167c7811ea`. Native clients and writer/management mutexes were idle before and after the full suite.
B13 (`5e9509e`) retains EXE `966e00fe57eccbdf4975c624026d39d24d4613f4174a932db248fb444a7caa9d` and ZIP `7a1da94e05b85873f791cde77907bdc280106768fbf84e5d89066ab8aa57a61b`. A final self-audit found that the new ordinary explicit-release branch bypassed existing cold-observer promotion. Its focused test failed before the two-line ordering correction at `c1e2596`; 110 related tests then passed in 21.96 seconds, including actual harmless worker exit, cold-observer promotion and queue proof. The in-progress B13 full suite was interrupted through its own execution session before editing, and is archived without a completion/JUnit claim. No additional native matrix was run for this narrow B14 delta.
The three review defects had retained RED evidence: actual MainWindow subprocess exit hung on stalled hash/copy/validation; real recovery callers held the unrelated native channel and could install after abandoned metadata; ordinary cancelled startup failed to clean a later loaded target. B13 related observer coverage passed 232 tests in 34.81 seconds, including an actual two-process mutex/file race between observer and explicit release plus a process restart. These race tests stub the native evidence/action boundary; they are not Mentor window tests.
B12 (`906cfc0`, EXE `7d7929d6621ae6c379205380e06f94eb076135343417d000018a8ab04efea8cc`, ZIP `bbe68005469d8b6cf87726200ef85646e442de45d164ab2ac0aec23b51d0bd65`) retained a new failure: ordinary `verify-642171759614` returned its visible cancellation terminal state in 7.797 seconds, but Forward loaded at 34.406 seconds, after the worker cleanup budget. Exact manual No/normal Close was used solely to clear that failed run. A later independent queue-helper attempt was refused with sharing violation 32 before native creation while two releasing observers raced for the coordination lease. Both failures are archived and are not relabelled as B13 passes.
B13 ordinary `verify-71aee0603183` reached the visible terminal state in 7.375 seconds. Its candidate worker acknowledged Tip at 21.359 seconds, Forward No at 27.422 seconds and one Close at 28.750 seconds; native exit followed the original cleanup deadline. Read-only sampling confirmed kernel exit. The original result remains CANCELLED/safe=false. No Release click or manual ordinary native action occurred. The helper stayed observe-only until the actual candidate produced fresh RELEASED proof, then obtained its own independent fresh proof. Its prequeued real Versions client `native-backup-b63e7f708fd5` was created 5.220 seconds after the candidate proof and 1.506 seconds after the independent proof, loaded the backup catalog and closed normally. This is **cross-owner queue acceptance**, using source-hash-pinned production queue/observer/native-worker modules; it is not survival of work in the same app after global Stop. The candidate itself performed every ordinary No/Close action.
The B13 native run issued Close within the first worker budget, so the new retained-phase No/Close branch was **NOT REPLAYED in Mentor**. That branch has source guard, real process race/restart and existing real Win32 adapter evidence. No repeated cold-start attempts were used to manufacture a slower launch.
B13 actual recovery `backup-restore-3f98efb14448` used the current pending original target and healthy independent source A. Its isolated source and installed target both returned PASS/GREEN/safe; native save/close/release completed without intervention. The old Work directory is retained and all 366 original source files are unchanged. The 27,689-file complete validation library copy progressed through the serial metadata path without a false inactivity handoff.
Separate frozen metadata-exit harness EXE SHA-256: `7490be1988d823944307510f7cfd22c85cf8570c7c25f6ee60d97f542bb72753`. All 68 packaged product modules equal final B14. A disposable I/O stall at each of hash/copy/validation exercised actual MainWindow close and interpreter exit before releasing the stall; no late dispatch occurred and partial copies were retained. This uses an acceptance-only entry, **not stall injection into the candidate EXE**. The earlier B12/B13 harnesses and all RED/setup attempts remain archived.
The original complete fault-bearing field snapshot remains unavailable (**NOT REPRODUCED**); the constructed partial copy remains **COPY_BLOCKED** and was never opened. Windows 10 and production SMB remain **NOT RUN**. The earlier first-pass B-control PENDING result and explicit retry remain separate outcomes. No merge, publication or issue closure is performed.
## Constructed copy and remaining limits
Constructed-copy experiment: **COPY_BLOCKED; inconsistency NOT REPRODUCED** (1 attempt, maximum 3). The healthy control passed normal native Verify. On a separate disposable copy, the documented native property write and stock Save actually ran; ordinary Work copying encountered Windows sharing violation 32 at the 113th attempted file, database/icdb.dat, after 0.470 seconds. The source still completed Save/Close and authoritative PASS/GREEN with released resources. The partial clone was never opened and no native Repair claim is made for it. This fault-creation instrumentation did not modify the frozen product and does not reproduce the original field incident.
@@ -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.
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 is pending.
The PR base is main at e4875b4. The branch also includes the previously approved efb8cae three-second confirmation defaults.
The change separates native task execution, client exit, coordination-lease release, data recovery and eligibility for the next write. A completed independent item no longer inherits another project's address or a stale historical blocker. Unknown ownership still requires fresh proof; the application does not delete native address or lock files.
## Final grouped review fixes
- Ordinary pre-document cancellation now requires positive supervisor and worker no-write events, a bound prelaunch log baseline, and exact worker/process/project/private-desktop identity. Potentially mutating supervisor actions and integration admission revoke this authority before dispatch. Proven no-write startup uses one 30-second cleanup budget and the existing five-second UI handoff; unproved ordinary cleanup and active-write waiting retain their existing policies. Ordinary global Stop still cancels its own queue.
- A late loaded ordinary target may enter one separate retained cleanup phase only after its original worker/helpers have exited and fresh complete loaded evidence is available. The existing observer persists the intent and absolute 30-second deadline in the existing session record before any action, under the existing native management mutex. Duplicate observers, explicit release and process restart cannot start it again. Prior No/Tip acknowledgements and the sole Close remain deduplicated. Unknown or multiple documents, changed identities and active writes authorize no action. Cleanup return never establishes release or successful verification; queued writes still use fresh scoped resource proof.
- Manifest hashing/copy/validation now run serially on the existing bounded daemon task. Nested executors no longer keep the Python interpreter alive after real MainWindow closure during stalled metadata I/O. Completed work renews inactivity; cancellation prevents late dispatch and incomplete copies remain available as evidence.
- Backup recovery no longer holds the global native mutex during abandonable metadata work. It retains the exact library lease and completed-work fences. Only the short pair of Work renames, rollback and installed-state update is protected from abandonment; the task registry guard is never held over filesystem operations. Cancellation after that pair cannot start target verification. An OS rename that itself never returns cannot be safely interrupted; the implementation preserves ownership rather than claiming cancellation completed.
## Implementation
- Resource release uses exact project/database/library scope and observed process identity. Read-only file probes retain exclusive handles through release commitment. Legacy receipts are rechecked; a proof for one block cannot close another block's session.
@@ -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.
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.
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.
+39 -18
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):
"""Validate in copies before changing Work; preserve all recovery evidence."""
import pythoncom, win32con, win32event
from .operation_queue import check_active, local_commit, note_metadata_progress, QueueCancelled
from .network_path import absolute_preserving_drive
from .verify_runner import run_verify, read_library_flag_if_available
verifier = verifier or run_verify
@@ -187,11 +187,16 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
return VerifyResult('BLOCKED', stderr='恢复记录目录不能位于备份工程内。')
if validation_dir.is_relative_to(library_root) or validation_dir.is_relative_to(source.parent):
return VerifyResult('BLOCKED', stderr='本机验证目录不能位于目标库或备份工程内。')
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
library_lock = None
release_confirmed = True
installed = False
def check():
check_active()
if stop is not None and stop.is_set():
raise QueueCancelled('恢复已取消,未提交后续操作。')
def completed():
check()
note_metadata_progress()
record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source),
'library': str(library), 'block': request.block_name, 'installed': False,
'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'}
@@ -216,23 +221,25 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
from .com_runtime import initialize_com, uninitialize_com
initialized = initialize_com()
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
return VerifyResult('BLOCKED', stderr='已有 CBB 任务运行,请等待结束。', safe_to_continue=False)
check()
from .library_lock import LibraryLock
library_lock = LibraryLock(library, safe_to_release=lambda: release_confirmed)
library_lock.__enter__()
if source.is_relative_to(library_root):
raise ValueError('请选择目标中心库之外的独立备份工程。')
project, pcb = preflight(replace(request, lmc_file=library))
completed()
source_pcb = _source_check(source, request.block_name, project)
completed()
root.mkdir(parents=True, exist_ok=False)
idle_check(library, project, pcb)
completed()
idle_check(library, source, source_pcb)
completed()
validation_base.mkdir(parents=True, exist_ok=True)
library_size = sum(info.st_size for info in _scan(library_root).values() if stat.S_ISREG(info.st_mode))
source_size = sum(info.st_size for info in _scan(source.parent).values() if stat.S_ISREG(info.st_mode))
completed()
same_drive = root.anchor.casefold() == validation_dir.anchor.casefold()
required = (library_size + source_size * 2) if same_drive else 0
if (shutil.disk_usage(root).free < required
@@ -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)
original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope,
progress=copy_progress('prepare_source', '正在准备验证库:'))
completed()
(root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
staged_library = validation_dir/library.name
staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work'
@@ -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()):
raise ValueError('验证副本工程路径越界。')
shutil.rmtree(resolved_work)
completed()
source_manifest = _copy_verified(source.parent, staged_work,
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
completed()
(root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
staged_project = staged_work/source.name
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
@@ -263,41 +273,55 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
auto_repair=False, libspec='', dms_login_config='', mapped_drive='', mapped_remote_root='',
native_lm_verify=False, interactive_input=False)
preflight(validation)
completed()
emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
check()
release_confirmed = False
choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {}
if stop is not None:choice_options['stop']=stop
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
release_confirmed = source_result.safe_to_continue
record['source_validation'] = asdict(source_result)
completed()
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
or not source_result.safe_to_continue):
return save(replace(source_result, status='FAIL', stderr=
'备份校验未通过,目标未更改。\n' + (source_result.stderr or source_result.library_flag_detail)))
idle_check(library, project, pcb)
completed()
idle_check(staged_library, staged_project, staged_pcb)
completed()
token = root.name.removeprefix('backup-restore-')
work = project.parent.resolve()
incoming = work.with_name('Work.restore-' + token)
retained = work.with_name('Work.before-restore-' + token)
_copy_verified(staged_work, incoming,
progress=copy_progress('prepare_source', '正在准备恢复工程:'))
completed()
_align_library(incoming/source.name, incoming/source_pcb.relative_to(source.parent), library)
completed()
idle_check(library, source, source_pcb)
completed()
if _manifest(source.parent) != source_manifest:
raise ValueError('备份来源在验证期间发生变化,目标未更改。')
completed()
if _manifest(library_root, scope=library_scope, exclude=incoming.resolve()) != original_manifest:
raise ValueError('目标中心库在验证期间发生变化,停止恢复。')
completed()
emit('install', '备份已通过验证,正在保留原工程并恢复…')
work.rename(retained)
try:
incoming.rename(work)
except Exception:
retained.rename(work)
raise
installed = True
record['retained_work'] = str(retained)
check()
with local_commit():
work.rename(retained)
try:
incoming.rename(work)
except Exception:
retained.rename(work)
raise
installed = True
record['retained_work'] = str(retained)
completed()
emit('verify_target', '正在重新打开恢复后的目标工程并校验…')
check()
release_confirmed = False
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
auto_repair=False, native_lm_verify=False, interactive_input=False),
@@ -320,7 +344,4 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
if library_lock is not None:
library_lock.__exit__(None, None, None)
finally:
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()
uninitialize_com(initialized)
+6 -2
View File
@@ -100,9 +100,10 @@ class DialogBackend(Protocol):
class AgentDialogBackend:
"""Adapt the private-desktop JSONL client to the supervisor backend."""
def __init__(self, client, *, pids=None) -> None:
def __init__(self, client, *, pids=None, before_action=None) -> None:
self.client = client
self.pids = pids
self.before_action = before_action
def observe(self, phase: DialogPhase):
if self.pids is None:
@@ -111,6 +112,7 @@ class AgentDialogBackend:
return tuple(w for w in self.client.observe(phase, pids=pids) if w.pid in pids)
def perform(self, snapshot: WindowSnapshot, action: dict, phase: DialogPhase) -> ActionResult:
if self.before_action is not None:self.before_action(snapshot,action)
return self.client.perform(
hwnd=snapshot.hwnd,
fingerprint=stable_fingerprint(snapshot),
@@ -123,7 +125,7 @@ class Win32DialogBackend:
"""Observe and act on dialogs without moving focus, cursor, or desktop."""
def __init__(self, pids, *, desktop=None, win32gui=None, win32process=None,
win32con=None) -> None:
win32con=None, before_action=None) -> None:
if win32gui is None:
import win32gui as win32gui_module
win32gui = win32gui_module
@@ -138,6 +140,7 @@ class Win32DialogBackend:
self.win32gui = win32gui
self.win32process = win32process
self.win32con = win32con
self.before_action = before_action
def _allowed_pids(self) -> set[int]:
values = self.pids() if callable(self.pids) else self.pids
@@ -256,6 +259,7 @@ class Win32DialogBackend:
return control.control_id
def perform(self, snapshot: DialogSnapshot, action: str) -> tuple[int, ...]:
if self.before_action is not None:self.before_action(snapshot,action)
buttons = self._buttons(snapshot)
positive = ("yes", "ok", "continue", "retry", "restore", "open", "use", "load",
"是", "确定", "继续", "重试", "恢复", "打开", "使用", "加载")
+76 -7
View File
@@ -62,6 +62,51 @@ def _tip_target(snapshot):
return target if target is not None and target.class_name == 'Button' else None
def cancelled_prewrite_startup(job, pcb_pid=None):
"""Positive ordinary pre-document cancellation proof; absence of Save is insufficient."""
from .session_record import IDENTITY_KEYS, read_session_record
try:
if (job.get('diagnostic_only') is not False or job.get('interactive_input')
or job.get('native_lm_verify') or job.get('post_repair_consent')
or job.get('operation') != 'verify' or not job.get('operation_id')
or not job.get('desktop', '').startswith('CbbVerify_')):
return None
root=Path(job['root'])
if not Path(job['cancel_signal']).is_file() or (root/'save.log').exists():return None
path=root/'events.jsonl'
if path.stat().st_size>1024*1024:return None
events=[json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()]
if any(str(e.get('stage','')).startswith(('save','integration','validate','failure_close'))
or e.get('stage') in ('startup_write_admitted','startup_supervisor_write_possible','identity_verified')
for e in events):return None
stages=('startup_supervisor_no_write','startup_prewrite_ready','startup_cancelled_prewrite')
selected=[]
for stage in stages:
matches=[(i,e) for i,e in enumerate(events) if e.get('stage')==stage]
if len(matches)!=1:return None
selected.append(matches[0])
if [i for i,_ in selected]!=sorted(i for i,_ in selected):return None
binding={k:job[k] for k in ('operation_id','project','pcb','desktop')}
if any(any(e.get(k)!=v for k,v in binding.items()) for _,e in selected):return None
ready,cancelled=selected[1][1],selected[2][1]
pid=cancelled.get('pcb_pid')
if (not pid or pcb_pid is not None and pid!=pcb_pid
or cancelled.get('identity_verified') is not False or cancelled.get('write_admitted') is not False):return None
if not any(e.get('stage')=='pcb_worker_started' and e.get('pcb_pid')==pid
for e in events[selected[1][0]+1:selected[2][0]]):return None
session=read_session_record(Path(job['session_record_path']),evidence_root=root)
workers=[p for p in session.get('processes',()) if p.get('role')=='worker']
if (session.get('operation_id')!=job['operation_id'] or session.get('desktop')!=job['desktop']
or session.get('library')!=job['library'] or len(workers)!=1
or not set(IDENTITY_KEYS)<=ready.get('worker_identity',{}).keys()
or any(ready.get('worker_identity',{}).get(k)!=workers[0].get(k) for k in IDENTITY_KEYS)):return None
baseline=ready.get('baseline')
if not isinstance(baseline,dict) or not {'started_ns','files'}<=baseline.keys():return None
return baseline
except (OSError,ValueError,KeyError,TypeError):
return None
def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event: None,
timeout_seconds=None, launcher_process=None):
"""Normally close our empty PCB after a diagnosed database startup failure.
@@ -95,10 +140,12 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
and isinstance(job.get('diagnostic_log_baseline'), dict)
and {'started_ns', 'files'} <= job['diagnostic_log_baseline'].keys()
and not (root/'save.log').exists())
ordinary_baseline=cancelled_prewrite_startup(job,pcb_pid)
cancelled_prewrite=ordinary_baseline is not None
# Diagnostic close already owns a 30-second cleanup budget. Start it
# once here; the empty-to-loaded transition never resets that deadline.
if timeout_seconds is None:
timeout_seconds = 30 if cancelled_diagnostic else 20
timeout_seconds = 30 if cancelled_diagnostic or cancelled_prewrite else 20
deadline = time.monotonic() + max(0, timeout_seconds)
sent = False
declined_hwnd = None
@@ -111,6 +158,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
diagnostic_state = {'clicked': set()}
def cleanup_post(hwnd, message):
if (time.monotonic() >= deadline or _current_desktop_name() != desktop
or cancelled_prewrite and cancelled_prewrite_startup(job,pcb_pid)!=ordinary_baseline
or win32event.WaitForSingleObject(close_handle, 0) != win32con.WAIT_TIMEOUT
or residual_sessions._handle_identity(close_handle) != close_identity
or win32process.GetWindowThreadProcessId(hwnd)[1] != pcb_pid):
@@ -150,19 +198,31 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
or '-reusablecircuit' not in [a.casefold() for a in args]
or expected not in [os.path.normcase(os.path.abspath(a)) for a in args[1:]]):
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
if cancelled_diagnostic 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:
close_handle = handles.enter_context(residual_sessions._process_handle(pcb_pid))
close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
from .diagnostic_open import cancelled_startup_step
def ordinary_identity():
from .diagnostic_open import _load_evidence
return (cancelled_prewrite_startup(job,pcb_pid)==ordinary_baseline
and _load_evidence(job,pcb_pid,ordinary_baseline,require_autosave=False) is not None)
closed, acted = cancelled_startup_step(job, pcb_pid, diagnostic_state,
closed_frame=close_frame, deadline=deadline, post=cleanup_post, emit=emit)
closed_frame=close_frame, deadline=deadline, post=cleanup_post, emit=emit,
identity_check=ordinary_identity if cancelled_prewrite else None)
if closed is not None and not sent:
sent, close_frame = True, closed
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=closed,
document_identity='native_path_pid_logs', cleanup='cancelled_diagnostic')
document_identity='native_path_pid_logs',
cleanup='cancelled_prewrite' if cancelled_prewrite else 'cancelled_diagnostic')
if acted:
continue
if not sent:
@@ -187,7 +247,10 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
current = _startup_snapshot(hwnd, pcb_pid)
if current != snapshot or _tip_target(current) != target:
raise ValueError('STARTUP_TIP_CHANGED')
win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0)
if cancelled_diagnostic or cancelled_prewrite:
cleanup_post(target.handle,win32con.BM_CLICK)
else:
win32gui.PostMessage(target.handle, win32con.BM_CLICK, 0, 0)
dismissed_tips.add(hwnd)
dismissed = True
emit(stage='startup_tip_dismissed', pcb_pid=pcb_pid, hwnd=hwnd)
@@ -207,7 +270,10 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
if _cancel_target(current) != target or current != snapshot:
raise ValueError('STARTUP_CANCEL_PROMPT_CHANGED')
declined_kind, cancel = target
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
if cancelled_diagnostic or cancelled_prewrite:
cleanup_post(cancel.handle,win32con.BM_CLICK)
else:
win32gui.PostMessage(cancel.handle, win32con.BM_CLICK, 0, 0)
declined_hwnd = hwnd
emit(stage='startup_open_declined', pcb_pid=pcb_pid, hwnd=hwnd,
control_id=cancel.control_id, prompt=declined_kind)
@@ -251,7 +317,10 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
close_identity = residual_sessions._handle_identity(close_handle)
if Path(close_identity['image']).name.casefold() != 'expeditionpcb.exe':
raise ValueError('STARTUP_PROCESS_UNCONFIRMED')
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
if cancelled_diagnostic or cancelled_prewrite:
cleanup_post(main[0],win32con.WM_CLOSE)
else:
win32gui.PostMessage(main[0], win32con.WM_CLOSE, 0, 0)
close_frame = main[0]
sent = True
emit(stage='startup_close_requested', pcb_pid=pcb_pid, hwnd=main[0])
+18
View File
@@ -684,6 +684,11 @@ def execute_job(job, emit):
launcher_process = None
completed = False
identity_verified = False
write_admitted = False
prewrite_eligible = (job.get('diagnostic_only') is False and not job.get('native_lm_verify')
and not job.get('post_repair_consent') and not job.get('interactive_input')
and all(job.get(k) for k in ('operation_id','session_record_path','desktop')))
startup_binding={k:job.get(k) for k in ('operation_id','project','pcb','desktop')}
diagnostic_close_attempted = False
helper = None
app = doc = pi = None
@@ -706,6 +711,11 @@ def execute_job(job, emit):
for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])):
ensure_project_central_library(config, job['lmc_file'],
evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit)
if prewrite_eligible:
from .diagnostic_open import snapshot_diagnostic_logs
from .session_record import process_identity
emit(stage='startup_prewrite_ready',baseline=snapshot_diagnostic_logs(job),
worker_identity=process_identity(os.getpid()),**startup_binding)
emit(
stage='verify_mode',
mode=('library_manager_native' if bool(job.get('native_lm_verify', False))
@@ -810,6 +820,10 @@ def execute_job(job, emit):
# the old, working path acquires the token inside the SysWOW64
# cscript save helper below. The PCB UI license dialog has already
# been handled by the private-desktop supervisor.
if job.get('cancel_signal') and Path(job['cancel_signal']).exists():
raise RuntimeError('VERIFY_CANCELLED: 未开始工程集成')
write_admitted = True
if prewrite_eligible:emit(stage='startup_write_admitted',**startup_binding)
refresh_integration(
pi,
emit=emit,
@@ -915,6 +929,10 @@ def execute_job(job, emit):
elif not completed and worker_pid is not None:
try:
from .failed_session import close_failed_startup
if (prewrite_eligible and not write_admitted and not identity_verified
and job.get('cancel_signal') and Path(job['cancel_signal']).exists()):
emit(stage='startup_cancelled_prewrite',pcb_pid=worker_pid,
identity_verified=False,write_admitted=False,**startup_binding)
failed_close = close_failed_startup(job, worker_pid, baseline_pids=pcb_before, emit=emit,
launcher_process=launcher_process)
if failed_close.get('status') == 'CLOSED' and lm_session is not None:
+24 -4
View File
@@ -68,6 +68,7 @@ class _Call:
done: Event = field(default_factory=Event)
abandoned: bool = False
native_depth: int = 0
commit_depth: int = 0
readonly_depth: int = 0
supervised_depth: int = 0
worker_sessions: list = field(default_factory=list)
@@ -175,6 +176,25 @@ def hold_native_handoff(process, session_record_path):
raise TaskHandoff(call.context, cancelled=call.handoff_cancelled, result=call.last_result)
@contextmanager
def local_commit():
"""Finish an admitted filesystem rename/rollback without native ownership claims."""
call = getattr(_local, 'call', None)
with _tasks_guard:
check_active()
if call is not None:
if call.metadata_only or call.readonly_depth:
raise RuntimeError('Read-only metadata cannot commit filesystem changes')
call.commit_depth += 1
try:
yield
finally:
if call is not None:
with _tasks_guard:
call.commit_depth -= 1
call.phase_started = time.monotonic()
@contextmanager
def native_phase(*, read_only=False, supervised=False):
"""Never abandon a transaction between native writes (including Remove/Add)."""
@@ -266,7 +286,7 @@ class BatchTaskContext:
'CANCELLED' if self.stop.is_set() else
'HANDED_OFF' if any(c.abandoned for c in calls) else
'RUNNING' if pending else 'IDLE', pending=pending,
pending_native=any(c.native_depth for c in calls))
pending_native=any(c.native_depth or c.commit_depth for c in calls))
def shutdown(self):
"""Yield UI supervision, never a native worker's write/lease ownership.
@@ -285,7 +305,7 @@ class BatchTaskContext:
call.supervised_depth == call.native_depth and
all(s.get('worker_protection') in ('duplicated_lease', 'worker_owned_lease', 'inspection_only', 'catalog_readonly')
for s in call.worker_sessions))
if not call.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
return {**self.snapshot(), 'safe_to_continue': False,
'shutdown_handoff': all(c.shutdown_handoff for c in calls),
@@ -319,7 +339,7 @@ class BatchTaskContext:
call.done.wait(max(0, deadline-time.monotonic()))
with _tasks_guard:
for call in calls:
if not call.done.is_set() and not call.native_depth:
if not call.done.is_set() and not call.native_depth and not call.commit_depth:
call.abandoned = True
return self.snapshot()
@@ -357,7 +377,7 @@ class BatchTaskContext:
call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
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()
call.abandoned = True
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
+87 -6
View File
@@ -600,7 +600,7 @@ def _cancelled_diagnostic_record(row):
operation = session['operation_id']
scope = session.get('resource_scope', {})
if (record.get('operation_id') != operation or job.get('operation_id') != operation
or job.get('diagnostic_only') 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 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)
@@ -644,8 +644,18 @@ def _cancelled_diagnostic_record(row):
continue
if any(r.get('operation_id') != operation for r in active_write_records(row['library'])):
continue
if job.get('diagnostic_only') is False:
from .failed_session import cancelled_prewrite_startup
from .diagnostic_open import _load_evidence
baseline=cancelled_prewrite_startup(job,row['pid'])
if baseline is None or _load_evidence(job,row['pid'],baseline,require_autosave=False) is None:
continue
matches.append(dict(job=job, record_path=str(path), operation_id=operation,
closed_frame=closes[0]['hwnd'] if closes else None))
closed_frame=closes[0]['hwnd'] if closes else None,
declined_buttons=[e['hwnd'] for e in events if e.get('stage')=='startup_prompt_no'
and e.get('pcb_pid')==row['pid'] and e.get('control_id')==7 and e.get('hwnd')],
dismissed_tips=[e['hwnd'] for e in events if e.get('stage')=='startup_tip_dismissed'
and e.get('pcb_pid')==row['pid'] and e.get('hwnd')]))
except (OSError, pywintypes.error, ValueError, KeyError, TypeError):
continue
return matches[0] if len(matches) == 1 else None
@@ -674,12 +684,12 @@ def _legacy_diagnostic_windows(row):
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
from .diagnostic_open import cancelled_startup_step
from .operation_queue import check_active
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():
check_active()
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:
raise ValueError('STARTUP_ACTION_UNCONFIRMED')
_post_window_message({'desktop':job['desktop']}, hwnd, row['pid'], message)
state = {'clicked':set()}; closed = proof['closed_frame']; dismissed_tips = set()
state = {'clicked':set()}; closed = proof['closed_frame']; dismissed_tips = set(proof.get('dismissed_tips',()))
def read_bound_windows():
windows=_legacy_diagnostic_windows(bound)
for window in windows:
if any(c['hwnd'] in proof.get('declined_buttons',()) for c in window['children']):
state['clicked'].add(window['hwnd'])
return windows
try:
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0:
@@ -726,7 +742,7 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
break # Never stack another Close after a legacy Tip acknowledgement.
try:
closed,_ = cancelled_startup_step(job,row['pid'],state,closed_frame=closed,deadline=deadline,
post=post,emit=lambda **event:None,read_windows=lambda:_legacy_diagnostic_windows(bound),
post=post,emit=lambda **event:None,read_windows=read_bound_windows,
identity_check=confirmed)
except RuntimeError as error:
if not str(error).startswith('STARTUP_WINDOW_CHANGED:'):
@@ -739,6 +755,69 @@ def _close_registered_startup(row, handle, proof, *, stop=None):
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 _request_close(row, *, stop=None):
import win32con, win32event
with _process_handle(row['pid']) as handle:
@@ -763,6 +842,8 @@ def _request_close(row, *, stop=None):
from .session_record import handoff_session
record_path = Path(proof['record_path'])
handoff_session(record_path, evidence_root=record_path.parent, observe_only=False)
if proof['job'].get('diagnostic_only') is False:
return _ordinary_startup_close(row,handle,proof,stop=stop)
from .operation_queue import native_phase
# This confirmed no-write native cleanup has its own single bounded
# budget; metadata inactivity must not abandon it between No and Close.
+21 -23
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
and their membership/size/mtime must remain stable throughout the snapshot.
"""
from concurrent.futures import ThreadPoolExecutor
from contextlib import ExitStack
from dataclasses import asdict, dataclass
import hashlib
@@ -252,13 +251,13 @@ def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_functi
files = {}
hashed_bytes = 0
_emit(progress, 'hash', 0, 0, total_files=len(selected))
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, item) in enumerate(pool.map(hashed, selected), 1):
note_metadata_progress()
files[relative] = item
hashed_bytes += item['size']
if count % 256 == 0 or count == len(selected):
_emit(progress, 'hash', count, hashed_bytes, total_files=len(selected))
# Stay on the bounded task thread: executor workers are joined at interpreter exit.
for count, (relative, item) in enumerate(map(hashed, selected), 1):
note_metadata_progress()
files[relative] = item
hashed_bytes += item['size']
if count % 256 == 0 or count == len(selected):
_emit(progress, 'hash', count, hashed_bytes, total_files=len(selected))
# Check primary membership and metadata again after every hash completed.
# Runtime files can change/add/disappear without a semantic conflict.
after = scan_tree(root, scope=scope, exclude=exclude)
@@ -332,7 +331,7 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
destination.mkdir(parents=True, exist_ok=False)
files = [path for path, info in entries.items() if stat.S_ISREG(info.st_mode)]
from .library_lock import owned_snapshot
# Resolve ownership on the operation thread, before parallel copy workers.
# Resolve ownership on the operation thread before copying.
owned = {path: data for path in files
if path.name.endswith('.cbb-upload.lock')
and (data := owned_snapshot(path)) is not None}
@@ -390,17 +389,16 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
raise OSError(f'复制期间文件变化:{path}')
return relative.as_posix(), digest, label
with ThreadPoolExecutor(max_workers=8) as pool:
for count, (relative, digest, label) in enumerate(pool.map(copy_file, files), 1):
note_metadata_progress()
if label is not None:
size = entries[source/relative].st_size
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
hashed_count += 1
hashed_bytes += size
if count % 256 == 0 or count == len(files):
_emit(progress, 'copy', hashed_count, hashed_bytes,
copied_files=count, total_files=len(files))
for count, (relative, digest, label) in enumerate(map(copy_file, files), 1):
note_metadata_progress()
if label is not None:
size = entries[source/relative].st_size
record[relative] = {'size': size, 'sha256': digest, 'scope': label}
hashed_count += 1
hashed_bytes += size
if count % 256 == 0 or count == len(files):
_emit(progress, 'copy', hashed_count, hashed_bytes,
copied_files=count, total_files=len(files))
def validate_bytes(relative):
item = record[relative]
@@ -409,9 +407,9 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
raise OSError(f'复制期间主要文件内容变化:{path}')
if hash_function(destination/relative) != item['sha256']:
raise OSError(f'复制内容校验失败:{path}')
with ThreadPoolExecutor(max_workers=8) as pool:
for _ in pool.map(validate_bytes, record):
note_metadata_progress()
for relative in record:
validate_bytes(relative)
note_metadata_progress()
if _metadata_record(source, scan_tree(source)) != expected_metadata:
raise OSError(f'复制期间目录内容变化:{source}')
if _metadata_record(destination, scan_tree(destination)) != expected_metadata:
+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 datetime import datetime, timezone
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)
except Exception:
pass
if result['status'] == 'ACTIVE' and not observation_only and not stop.is_set():
try:
from .residual_sessions import resume_cancelled_startup
if resume_cancelled_startup(path, stop=stop):
# Cleanup is not release proof. Re-read all held identities
# and independently prove the resource release as usual.
result = _reconcile(Path(path), Path(evidence_root), handles, stack)
except Exception:
logging.getLogger(__name__).warning('Retained startup cleanup unavailable', exc_info=True)
if result['status'] == 'IDENTITY_CHANGED' and not observation_only:
try:
from .library_lock import release_retained_library
+17 -4
View File
@@ -243,7 +243,8 @@ def _stop_worker(process, *, timeout=5, wait_for_native_write=True):
process.wait(timeout=timeout)
except Exception:
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
try:
process.wait(timeout=max(0, NATIVE_WRITE_STOP_WAIT_SECONDS - timeout))
@@ -985,6 +986,15 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
except Exception as error:
return finish(VerifyResult('FAIL', stderr=str(error)))
events = root/'events.jsonl'
prewrite_eligible = not (request.diagnostic_only or request.interactive_input or request.native_lm_verify or consent)
def startup_phase(stage,**facts):
record={k:job[k] for k in ('operation_id','project','pcb','desktop')}
with events.open('a',encoding='utf-8') as stream:
stream.write(json.dumps(dict(stage=stage,**record,**facts))+'\n')
def before_dialog_action(snapshot,action):
name=action.get('action') if isinstance(action,dict) else action
if name not in ('dismiss_tip','accept_license','decline_database_log'):
startup_phase('startup_supervisor_write_possible',action=name,pid=snapshot.pid,hwnd=snapshot.hwnd)
offset = 0
target_pid = None
diagnostic_closing = False
@@ -1011,6 +1021,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
native.__exit__(None, None, None)
phase_entered = False
try:
if prewrite_eligible:startup_phase('startup_supervisor_no_write')
timing.begin('worker_setup')
with (root/'worker.log').open('w', encoding='utf-8') as log:
check_active()
@@ -1037,14 +1048,14 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .dialog_rules import default_rules_path, load_rules
dialog_agent = DialogAgentClient.start(process, root/'dialog-agent', stop=stop)
dialog_supervisor = DialogSupervisor(
AgentDialogBackend(dialog_agent, pids=lambda: {
AgentDialogBackend(dialog_agent, before_action=before_dialog_action if prewrite_eligible else None, pids=lambda: {
int(pid) for pid in (target_pid, lm_pid, launcher_pid) if pid}),
rules=load_rules(default_rules_path(), diagnostic_only=request.diagnostic_only),
)
else:
dialog_supervisor = DialogSupervisor(Win32DialogBackend(
lambda: ({value for value in (target_pid, lm_pid) if value is not None}),
desktop=process.desktop,
desktop=process.desktop,before_action=before_dialog_action if prewrite_eligible else None,
))
else:
dialog_supervisor = dialog_supervisor_factory(
@@ -1070,7 +1081,9 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'已请求停止,等待当前原生操作返回')
_notify_progress(progress, {'stage': 'save_stop_requested', 'block': request.block_name,
'detail': detail})
_stop_worker(process, 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='已取消当前校验。',
safe_to_continue=False, error_stage=phase.value))
if events.exists():
+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)
+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
+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)
+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)
+143
View File
@@ -0,0 +1,143 @@
from threading import Event
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')
def hold():
entered.set()
if cancel:context.cancel()
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()
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=''):
import win32con,win32event
kernel_wait=win32event.WaitForSingleObject
job,records,messages,state=loaded_fixture(tmp_path,monkeypatch)
state.update(tip=False,closing=closed)
state['observer_requests']=[]
@@ -17,6 +18,7 @@ def registered_fixture(tmp_path,monkeypatch,*,closed=False,obstacle=''):
state['observer_requests'].append((path,list(messages),kw)))
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)
state['prelaunch_baseline']=job['diagnostic_log_baseline']
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)
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,'_force_ownership',lambda h,p:{'owner_sid':'current','session_id':1,'force_user_confirmed':True})
def wait(handle,ms):
if handle not in (11,12):return kernel_wait(handle,ms)
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
monkeypatch.setattr(win32event,'WaitForSingleObject',wait)