Compare commits

...
13 Commits
Author SHA1 Message Date
阿白叔 fdd07224aa docs: record full review fixes and final 1775-test validation 2026-11-09 14:49:45 +08:00
阿白叔 a045683c8a fix: publish management receipt before orphan-exitable terminal state 2026-11-09 14:44:09 +08:00
阿白叔 74a45eb5cf Merge branch 'codex/review-residual-release' into codex/runtime-lifecycle-safety 2026-11-09 14:34:32 +08:00
阿白叔 a7df105616 fix: recreate batch resume action after release summary retirement 2026-11-09 14:34:28 +08:00
阿白叔 78ff118f82 fix: preserve accepted native calls and explain retained queue waits 2026-11-09 14:33:44 +08:00
阿白叔 d0a5ce5d17 Merge branch 'codex/review-residual-release' into codex/runtime-lifecycle-safety 2026-11-09 14:10:38 +08:00
阿白叔 363a279157 Merge branch 'codex/review-ui-integration' into codex/review-residual-release
# Conflicts:
#	src/cbb_refresh_verify/ui/main_window.py
2026-11-09 14:10:30 +08:00
阿白叔 306aa5c544 fix: centralize native dispatch and itemize retained session release 2026-11-09 14:03:07 +08:00
阿白叔 0fca6abb4e Merge branch 'codex/review-native-backend' into codex/review-ui-integration 2026-11-09 14:02:14 +08:00
阿白叔 342a7266c7 fix: retire result dialogs and clarify batch lifecycle 2026-11-09 13:51:32 +08:00
阿白叔 e8a1714d95 fix: clarify backend status freshness and scoped copy evidence 2026-11-09 13:50:04 +08:00
阿白叔 60101b7195 Merge branch 'codex/review-residual-release' into codex/runtime-lifecycle-safety
# Conflicts:
#	src/cbb_refresh_verify/ui/residual_release_dialog.py
2026-11-09 13:47:18 +08:00
阿白叔 14c9a74bbf fix: show confirmed scope beside actual residual release results 2026-11-09 13:45:53 +08:00
34 changed files with 1133 additions and 131 deletions

No files matched your search

@@ -0,0 +1,109 @@
{
"date": "2026-11-09",
"scope": "New full reviews #344/#345/#348 and runtime re-review #326",
"branch_heads_before_validation_commit": {
"codex/review-native-backend": "e8a1714d956e733648dacda1bfdce387e07e4cba",
"codex/review-ui-integration": "0fca6abb4e1b54bd06e6986782ccf45383306e43",
"codex/review-residual-release": "a7df105616a8f5cfab61b85e0c5d93aa74ded415",
"codex/runtime-lifecycle-safety": "a045683c8a6d6918ec701e2944d0e20c25296b65"
},
"environment": {
"python": "3.12.10",
"windows": "10.0.26200"
},
"full_suite": {
"tests": 1775,
"failures": 0,
"errors": 0,
"skipped": 0,
"duration_seconds": 273.089,
"xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\2026-11-09-full-review-final-1775.xml",
"xml_sha256": "a993473b7784748f671a3d38a0e80f1aa7dfaf714b23d6378ed26d0481c1b904",
"warnings": [
"Existing pywinauto STA COM threading warning"
]
},
"focused_runs": [
{
"scope": "Backend",
"passed": 287
},
{
"scope": "UI standalone",
"passed": 65
},
{
"scope": "Residual standalone forward integration",
"passed": 41
},
{
"scope": "Final runtime/UI integration before last merge",
"passed": 211
},
{
"scope": "Terminal-publication fix lifecycle/management group",
"passed": 159
}
],
"compileall": "passed",
"diff_check": "passed",
"independent_review": "No remaining important introduced findings after fixing two queue timing findings",
"tested_files_sha256": {
"src/cbb_refresh_verify/application.py": "62b9b013563a216d020c8366cccb8f949b02afa72dc63c26940804441cc23057",
"src/cbb_refresh_verify/batch_status.py": "55a4007cf54491ca8e045a5bf86aa4353ac8437cca5a76cd79304962e3d3fa0a",
"src/cbb_refresh_verify/desktop_worker.py": "27d751816552d215dd8ee9cd67941d824f7b4493120ead7c3f87e5eba5ec4a92",
"src/cbb_refresh_verify/library_lock.py": "636e0b1c84061796424da6289361c059fecacad31802df2edc3f3455ec8c40d8",
"src/cbb_refresh_verify/management.py": "29ecb101dacf2bb23b8b8931c01078956dd6c641444e82a69a62e811c7261fc5",
"src/cbb_refresh_verify/native_management.py": "7598a18da12dd527e9403a956b1ade76b253f89a9ee4790f0802244b54616844",
"src/cbb_refresh_verify/operation_queue.py": "a6932d8bc68ac436091f6d362557c66d274ec52d0f295a22f014a3396845c79f",
"src/cbb_refresh_verify/pcb_bridge.py": "2f6c2b09642100468814500569dbfc6695fc2a46b9a3b8333daa8e1530cdeef5",
"src/cbb_refresh_verify/scoped_manifest.py": "26ba8303e2de294374443513d667570abed2f0f2563a2e969a9cb35e74d65c00",
"src/cbb_refresh_verify/session_record.py": "fbf31fb38894f75d725b269229c7d928be54136b491cc5339f7a4b018d7b7f5e",
"src/cbb_refresh_verify/ui/icdb_check_task.py": "cc108974e843f31e59e90acd18ad2d810e6bcd67d7cf303b2b772501d95b6d8e",
"src/cbb_refresh_verify/ui/main_window.py": "a05d9d838be4b9e9f6e2b612c25186e77f23899bffc59b67f50fea597eab47c9",
"src/cbb_refresh_verify/ui/management_dialog.py": "f3fc740197fc109ae3ddd8ead556a8847d5e00ec9a97d5cc2e166d656fb861ef",
"src/cbb_refresh_verify/ui/residual_release_dialog.py": "82382af142379c540721dbfa7ba5a5d766130d89807e1f34ad032a0ad1411f5c",
"tests/test_batch_status.py": "c1f9af0c7c6f3171b3726fb53346f480b13b8d9cd88111a9c12e2fae2392bbff",
"tests/test_batch_status_faults.py": "314e890c9aee439c8a75b4dfd605685240c74f6212da975fd50526bd70b4a0ff",
"tests/test_management_retry_blockers.py": "124dbef291dbe331ba0c3e7de1665c910ea43e37b1563429b387f0f2233953ee",
"tests/test_management_supervision.py": "2dcadd6551a94c52e5d4e74285959f10144a89c48af87e508abaea945652d1f6",
"tests/test_pcb_bridge.py": "527fb63147a203a2e9419da989aff600d3e461580989e39e8ede3a8cc57b901a",
"tests/test_residual_release_dialog.py": "10b23d009703d542e5ce8ecb35a4833e0135bb8852b4116e49eedc7010397a1e",
"tests/test_review326_dispatch_and_receipts.py": "ce4d529246da1c4d53c3dec70ef49542165064404301dec3e32851df62492ecf",
"tests/test_review326_queue_guidance.py": "c2c97aceddd9713618afdd5f2a7be4764b56a1b62fc672282fb8c218b4969c74",
"tests/test_review345_ui_cli.py": "795e7e4f9bda8874c6a65a08863cab19f4adb3412287276ee2960588f0fd2fa8",
"tests/test_review348_release_comparison.py": "ceccdb3d6f7bc6cb65562c059f13aa2bc5d89d98c6f64b0f11d9b943ebbde165",
"tests/test_review_backend_followup.py": "c10704fae250c9e204c995843a2baab0a2562e51984ae4d429aa438ba1c88113",
"tests/test_review_management_ui_followup.py": "746602a84c3ba9cb041c5dd354b39d344355b71a3666b27a47eb9aee231e171c",
"tests/test_scoped_manifest.py": "d22749cd240ab365f91ebb9d0469dc3336150338a84a77c1aeb6fbc20ccd439f"
},
"icon_sha256": {
"ico": "62d4472ebaa94f9b39aebae06459685d3322041d0e1a7ada9f368cfd816ba1d6",
"png": "840f657fd7c622d9afd78625a64ed8ad04c90a895dd3c9fd37eebae543cdebe8",
"svg": "cbba5b3f339cbeb5eb43012709237359442ef67c69fc5b6679a8ee4c0a1b7328"
},
"design_choices": [
"Production status always fresh; low-level checkpoint reuse explicit",
"Final source and target hashes retained; copy hashed in stream",
"Optional CLI limit; default all requested targets",
"Release mapping cleanup serialized before waiting task admission",
"New native calls vetoed on supervisor loss; accepted pending calls may record continuation identity"
],
"candidate_rebuilt": false,
"automatic_icdb_repair": false,
"merged": false,
"issue_closed": false,
"not_verified": [
"Real Mentor/native database writes during loss/cancel",
"Frozen execution of this revision",
"Windows 10",
"Shared network/cross-machine release"
],
"first_full_run": {
"tests": 1774,
"failures": 1,
"xml": "F:\\Sync Tool Skyworth\\Work Maps\\cbb-refresh-verify-795\\diagnostics\\2026-11-09-full-review-first-failure-1774.xml",
"xml_sha256": "9d7275b0a4122db12b8367e4367759f3051ce29a56645da5098776d8b9ca2bc8",
"reason": "FINISHED permitted watchdog orphan exit before result publication; receipt now precedes terminal phase"
}
}
@@ -0,0 +1,43 @@
# Full-review follow-up: comments 344 / 345 / 348 / 326
This revision follows the new November 9 full reviews. The old November 6 deep-review backlog remains outside the user's previously selected scope.
## Backend: #10 / 344
- Status scans default to fresh queries. The low-level explicit checkpoint reuse API remains for compatibility with controlled read-only scans; production status queries continue to use `resume=False`. Its lightweight fingerprint is not described as proof that payload databases are unchanged.
- Change reports include rule version, compared scope, excluded directory categories/suffixes and positional runtime rules from the classifier constants. Unrelated CBB content is still explicitly outside comparison. Counts in the management result refer to compared engineering files.
- Removed the tests-only `pcb_bridge.execution_outcome` helper with optimistic release defaults; active production release checks remain authoritative.
- SHA-256 is computed during streaming of unlocked primary files instead of a separate preliminary source pass. The final source SHA-256 and target SHA-256 remain. This reduces three source reads to two without dropping same-size/same-mtime mutation detection. The review's suggested removal of final source hashing was not adopted because it would weaken the requested source-change check.
Backend commit `e8a1714`; 287 focused regressions passed. Details and exact command are in `docs/reviews/2026-11-05-native-backend.md`.
## UI/CLI: #11 / 345
- Replaced repeated same-purpose result windows with lifecycle-managed dialogs. Task recovery associations survive independent result windows; deleted dialogs/actions are forgotten. Forward integration keeps #12's enabled release/resume paths and recreates a resume action if its old summary was closed.
- Closing waits visibly, including a persistent still-waiting notice after 120 seconds. It does not promise a kill deadline or interrupt a write. The final idle check includes the independent lifecycle pool.
- Optional positive CLI `--limit` bounds requested names in order. Omission retains the existing all-target behavior rather than silently dropping work. Logs distinguish selected/total/remaining and explain retained mappings after exceptions or unsafe results, pointing to confirmed release instead of an unconditional network-drive deletion.
- Removed `if False` branches/dead reload field in the standalone UI PR; forward integration retains the later enabled release behavior. File line-ending rules from the prior tip remain.
UI commit `342a726`; 65 targeted UI/CLI tests passed on its branch. Integration keeps PR13 stop propagation; CLI test doubles were updated to accept and assert that stop input.
## Residual release: #12 / 348
The unreadable-window poisoning and oversized repeated-output findings target the old `5eb4b2d` tree and are already fixed in `651b539`. This revision additionally displays confirmation scope and actual execution result as separate columns, and counts allowed-but-unreleased rows with their reasons. Preview consent never overrides a fresh activity/identity refusal. Residual commit `14c9a74`; 35 targeted tests passed.
## Runtime and queue: #13 / 326
- Native management launch/open/create/close/quit/Add submission/Remove launch and editor entry use `dispatch_native`. It records the pending phase before callback entry, synchronous return records POSTCALL, callback failure records UNCONFIRMED, and asynchronous submission requires its existing explicit result acknowledgment. Save/failure-close helpers retain their atomic registration/start gate.
- Identity recording for an already-started Remove uses explicit continuation semantics: it must match the operation's current pending phase, cannot authorize a new call, and may continue tracking/waiting after supervisor loss. A real boundary regression demonstrates that loss immediately after Popen cannot abandon its wait. `required=False` controls journal errors, not permission to dispatch after supervisor loss.
- Pre-proof snapshots freeze alias generation, block and operation ID. Full-library proofs and operation receipts list `reconciled_blocks` and exact retained sessions; a replaced operation is not acknowledged.
- Cached queue reasons name the retained CBB and expose a release entry in verification, ICDB and management waiting states. NativeQueue emits an updated notice only when the cached wait reason changes, so a task transitioning from running to retained cannot leave a hidden dead-end action. Queue predicates do no filesystem/native I/O.
- The queued release's mapping finalizer runs inside the serialized release action before it admits the waiting native ticket. The completion signal skips later destructive mapping cleanup. This prevents an old proof from clearing a new task's mapping retention. Both normal confirmation and native Cancel use this finalizer. Closing the residual panel does not mark the still-queued parent action finished.
## Validation and limits
The final focused integration run passed 211 tests. New tests were first observed failing for missing dispatch/receipt facts, dispatch veto after accepted Remove, missing queue explanations, changed wait reasons, stale mapping cleanup and dialog lifecycle boundaries. Independent review's two queue timing findings were corrected and re-reviewed with no remaining important introduced finding.
The first full run exposed one terminal-publication race (1,773 passed, one failed): management wrote FINISHED before its result receipt, allowing the orphan watchdog to exit between them. The result is now flushed before FINISHED. The regression accepts either the normal failure exit or orphan exit only after checking the saved result and the absence of a subsequent native action. A new test first reproduced the missing receipt at the FINISHED transition; 159 focused lifecycle/management tests then passed. The failed full XML is preserved separately, and the full suite is rerun on the corrected tree.
This does not require a final result before every orphan exit: PRECALL/POSTCALL may deliberately exit during an idle non-COM wait after supervisor loss, as requested by review 319. Such an exit is neither operation success nor resource-release proof. A missing final result is returned as `success=False, safe_to_continue=False` by the launcher, with the last call facts retained in the session journal for explicit reconciliation. FINISHED specifically is now published only after its final receipt; requiring a final receipt before all POSTCALL orphan exits would leave the original idle-orphan problem unresolved.
Full-suite counts, source hashes and immutable XML copies are in the accompanying validation JSON. Compilation/diff checks and icon equality are checked on the integrated tree. No frozen package was rebuilt; the old iconfix package does not contain this revision. No real Mentor Save/Close/Add/Remove or shared/network/cross-machine acceptance was performed. ICDB automatic Repair remains off. No merge to main, formal release, issue closure, native address/lock deletion, foreground mouse control, or native process termination is authorized by this validation.
@@ -0,0 +1,38 @@
# PR11 review 345 follow-up
Repeated CBB verification and ICDB check runs replace the previous result dialog
for the same operation. Closing a result retires its Qt widgets and action
references, while the check task keeps its requests, results, invalidated targets,
and recovery context. A result for the other operation stays available.
During application shutdown, the title and status show that background work and
path release are pending. After approximately 120 seconds a second notice says
the application is still waiting. This is a notice interval, not a deadline;
shutdown still waits for existing workers and never forces native tools to stop.
The batch CLI accepts an optional positive `--limit`:
```powershell
python -m cbb_refresh_verify --batch-lmc 'Z:\library\library.lmc' --limit 2
```
The limit selects the first requested names in their existing order. With no
`--block`, the existing non-READY selection supplies those names; repeated
`--block` options retain their explicit order. Omitting `--limit` retains the
existing all-requested behavior. `batch_selection` logs selected, total, and
remaining counts. On batch exceptions or unconfirmed native release,
`batch_drive_retained` identifies the drive, remote share, display library and
Mentor path, and directs the operator to the confirmed-release entry. It never
disconnects a mapping while a native writer may still be active.
Management change counts explicitly cover the compared engineering files only.
Removed from the standalone PR11 head: all five `if False` blocks for the later
release flow, and `_reload_after_maintenance` assignments and its unused reload
branch. The hidden release control and existing method signatures remain for
the later PR12 implementation. When integrating forward, preserve PR12's live
release/resume behavior and retire its dialog-owned action references as well.
Preserve PR13's asynchronous close and lease guards when adding the wait notice.
Validation uses the isolated offscreen review wrapper with fake native boundaries;
it does not open Mentor, kill native processes, invoke Repair, or back up a library.
@@ -0,0 +1,7 @@
# PR #12 comment 348 follow-up
The review's process-isolation and oversized-output findings target the earlier `5eb4b2d` tree; both are addressed by `651b539` and remain covered by the real private-desktop and bounded-evidence regressions.
The remaining consent/result presentation gap is fixed here. The residual table retains its original six columns and adds confirmation scope and actual result. A row that was allowed at confirmation but rejected after a fresh activity/identity check now shows both facts beside its reason. The result message also counts confirmation-allowed rows and how many remain unreleased; it does not reinterpret preview consent as successful execution or bypass an active-write guard.
The new regression failed before the change. The release-dialog, residual follow-up and private-desktop regression group passed 35 tests. No production/native database action was performed. Integrated full validation is recorded at the PR #13 tip; no candidate build, merge or field acceptance is implied.
@@ -9,3 +9,12 @@ Dependency rationale: library release imports native engineering identity and re
Rollback: before dependents are merged, revert this commit. After merging dependents, revert in reverse order or use the previous candidate package after closing the current app. Code rollback does not undo a native transaction; use a consistent manual backup or explicitly selected native history on an isolated copy.
Validation: full Python suite 1,376 passed (one existing pywinauto COM-threading warning); compileall and git diff --check passed. Native field recovery, Windows 10 and cross-machine shared-library acceptance remain pending.
Review comment 344 follow-up (2026-11-09):
- Production status scans continue to query fresh bridge results. The low-level session now also defaults to fresh scans; explicit checkpoint reuse is documented as a controlled read-only option with no production resume promise.
- `library-changes.json` declares `rule_version`, the selected `scope`, excluded directory categories and suffixes, positional runtime rules, runtime filenames/prefixes, and recognized coordination checkpoints. Names, suffixes, prefixes and native database locations come from the same constants used by semantic classification. These are differences in participating engineering files; excluded content is not proven unchanged, and unrelated CBB content is not checked.
- Removed the tests-only `pcb_bridge.execution_outcome` helper. Production release safety continues to come from observed release state and remaining clients.
- Unlocked primary snapshots hash the copy stream, then independently hash the final source and destination. Source reads decrease from three to two. Rejected the suggestion to remove/threshold the final source hash: size and mtime cannot detect same-size, same-timestamp source edits. Locked LMC/icdb streams and owned lock snapshots retain their existing behavior; no source-rehash skip flag is added.
Validation for this follow-up: 287 targeted cases passed through the isolated mutex/PYTHONPATH wrapper (`test_batch_status`, `test_batch_status_faults`, `test_review_backend_followup`, `test_scoped_manifest`, `test_pcb_bridge`, `test_management_retry_blockers`, `test_backup_recovery`, `test_library_lock`, `test_management`). AST parsing, `git diff --check`, and original newline-style checks passed. No real Mentor, COM automation, shared library or process control was exercised; no full-suite run was requested.
@@ -1,5 +1,7 @@
# CBB Batch Status Bridge Implementation Plan
Current behavior (2026-11-09): production status scans always query the bridge fresh and overwrite checkpoint evidence. `BatchStatusSession.scan` defaults to `resume=False`; `resume=True` remains an explicit low-level option for controlled read-only scans, not an exposed production resume feature. Its lightweight fingerprint cannot detect every native payload/database write, so saved READY/PENDING rows must not authorize production actions.
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Read 180 to 3000 CBB Verify states through one resilient x86 Mentor bridge session with checkpoint recovery and authoritative `READY/PENDING` results.
@@ -1,5 +1,7 @@
# CBB 批量状态桥设计
Current behavior (2026-11-09): production status scans always query the bridge fresh and overwrite checkpoint evidence. `BatchStatusSession.scan` defaults to `resume=False`; `resume=True` remains an explicit low-level option for controlled read-only scans, not an exposed production resume feature. Its lightweight fingerprint cannot detect every native payload/database write, so saved READY/PENDING rows must not authorize production actions.
## 目标
支持对 180 到 3000 个 CBB 进行 Mentor authoritative Verify 状态读取,要求单条失败隔离、过程可恢复、结果可审计,并避免现有“一条 CBB 启动一个桥进程”的启动开销。
+26 -2
View File
@@ -62,6 +62,16 @@ def resolve_data_root(cli_value: Path | None) -> Path:
local = os.environ.get("LOCALAPPDATA")
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
def _positive_int(value):
try:
number = int(value)
except ValueError:
raise argparse.ArgumentTypeError('must be a positive integer') from None
if number <= 0:
raise argparse.ArgumentTypeError('must be a positive integer')
return number
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
@@ -73,6 +83,7 @@ def main(argv: Sequence[str] | None = None) -> int:
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
parser.add_argument('--limit', type=_positive_int, help='Maximum requested CBB names for --batch-lmc (default: all)')
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
@@ -126,6 +137,11 @@ def main(argv: Sequence[str] | None = None) -> int:
if library.error: raise RuntimeError(library.error)
names = [record.name for record in library.records if record.status != 'READY']
if not names: raise RuntimeError('中心库未读取到需要校验的 CBB')
total = len(names)
if args.limit is not None:
names = names[:args.limit]
logger.info('batch_selection selected=%s total=%s remaining=%s limit=%s',
len(names), total, total - len(names), args.limit or 'all')
requests = [VerifyRequest(mentor_path, name, context.root/'evidence',
libspec=args.libspec, dms_login_config=args.dms_login_config,
mentor_bin=args.mentor_bin, logging_context=context,
@@ -133,16 +149,24 @@ def main(argv: Sequence[str] | None = None) -> int:
mapped_remote_root=lease.remote_root,
native_lm_verify=native_lm_verify_enabled())
for name in names]
def retain_mapping(reason):
lease.retain_for_recovery()
logger.warning(
'batch_drive_retained drive=%s remote=%s display=%s mentor=%s reason=%s '
'guidance=请打开此中心库的“释放残留会话…”入口,确认原生会话安全释放后再释放映射;'
'原生写入仍可能运行时请保留映射。',
lease.drive or '-', lease.remote_root or '-', lease.display_path,
mentor_path, reason)
try:
from threading import Event
stop = Event()
with batch_stop_signals(stop):
results = run_batch(requests, stop=stop)
except Exception:
lease.retain_for_recovery()
retain_mapping('batch_exception')
raise
if any(not result.safe_to_continue for result in results):
lease.retain_for_recovery()
retain_mapping('native_release_unconfirmed')
report = write_batch_report(requests, results, context.root/'reports')
logger.info('batch_report path=%s', report)
logger.info('failure_report path=%s', failure_report_path(report))
+10 -3
View File
@@ -107,7 +107,7 @@ def fingerprint_library(lmc: Path) -> LmcFingerprint:
# Metadata alone is not a safe checkpoint key: on network shares and on
# file systems with coarse timestamp resolution, two different LMC
# contents can have the same size and mtime. Include the actual file
# digest so a changed central library can never reuse an old status row.
# digest to invalidate changed LMC bytes; payload edits remain outside this key.
content_sha256 = _sha256_file(path)
combined = hashlib.sha256()
combined.update(str(path).casefold().encode('utf-8', errors='surrogatepass'))
@@ -186,7 +186,12 @@ def _now() -> str:
class BatchStatusSession:
"""Supervised serial bridge session with checkpoint recovery."""
"""Supervised serial bridge session; fresh status queries by default.
Checkpoints record scan evidence. Explicit ``resume=True`` is a low-level
opt-in for controlled read-only scans, not a production freshness proof:
the lightweight fingerprint does not cover native payload/database edits.
"""
def __init__(self, bridge: StatusBridgeClient, *, timeout_seconds: float = 10.0,
rotate_every: int = 500) -> None:
@@ -196,7 +201,7 @@ class BatchStatusSession:
self.restart_count = 0
def scan(self, names: Iterable[str], lmc_file: Path, checkpoint_path: Path,
*, block_type: str = "RULP", resume: bool = True) -> list[BatchStatusRecord]:
*, block_type: str = "RULP", resume: bool = False) -> list[BatchStatusRecord]:
fingerprint = fingerprint_library(Path(lmc_file))
if resume:
checkpoint = BatchCheckpoint.load(checkpoint_path)
@@ -291,6 +296,8 @@ def authoritative_status_map(names: Iterable[str], lmc_file: Path, checkpoint_pa
timeout_seconds: float = 10.0) -> dict[str, str]:
"""Return only bridge-backed statuses for an optional UI integration.
Production always queries fresh statuses, including after native writes;
saved READY/PENDING rows are never reused here.
A missing bridge is represented as ``UNAVAILABLE``/``UNKNOWN`` by callers;
it is never promoted to ``READY``.
"""
+5 -2
View File
@@ -28,9 +28,12 @@ def _phase_pending(phase):
@contextmanager
def worker_phase(operation_id, phase):
def worker_phase(operation_id, phase, *, continuation=False):
with _automation_clients_lock:
if _supervisor_lost.is_set() and phase in ('NATIVE_CALL', 'CLOSING'):
existing = continuation and _native_phases.get(operation_id) == phase and _phase_pending(phase) is True
if continuation and not existing:
raise RuntimeError('WORKER_STATE_UNCONFIRMED: 尚无已派发的原生调用可继续登记')
if _supervisor_lost.is_set() and phase in ('NATIVE_CALL', 'CLOSING') and not existing:
raise RuntimeError('WORKER_CANCELLED: 监督器已退出,未提交新的原生调用')
_native_phases[operation_id] = phase
yield
+8 -2
View File
@@ -528,7 +528,8 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
"""
import win32con, win32event, win32file
library = Path(library).resolve(strict=True)
from .session_record import retained_session_snapshot, acknowledge_library_release
from .session_record import (retained_session_snapshot, acknowledge_library_release,
reconciled_retained_sessions)
retained = retained_session_snapshot(library)
evidence = Path(evidence_dir).resolve()
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
@@ -581,10 +582,15 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
raise LibraryBusy('释放检查期间协调检查点变化,保留原文件。')
root = evidence/('release-' + uuid4().hex)
root.mkdir(parents=True, exist_ok=False)
reconciled_sessions = reconciled_retained_sessions(retained, block_name=scoped)
reconciled_blocks = sorted({item['block_name'] for item in (*reconciled, *reconciled_sessions)
if item.get('block_name')})
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
'requested_block_name': block_name, 'proof_scope': 'BLOCK' if scoped else 'LIBRARY',
'proof_block_name': scoped, 'reconciled_checkpoints': reconciled,
'reconciled_foreign_blockers': foreign,
'reconciled_foreign_blockers': sorted(set(foreign) | {
block for block in reconciled_blocks if block_name and block != block_name}),
'reconciled_blocks': reconciled_blocks, 'reconciled_sessions': reconciled_sessions,
'unknown_checkpoint_archived': unknown,
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
+2 -1
View File
@@ -8,7 +8,7 @@ from uuid import uuid4
from .library_lock import LibraryLock, LibraryBusy
from .scoped_manifest import (ManifestScope, build_manifest, build_exclusive_library_manifest,
copy_verified, hash_file, scan_tree)
comparison_rules, copy_verified, hash_file, scan_tree)
@dataclass(frozen=True)
@@ -214,6 +214,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
nonlocal change_report
if mutated and original is not None and change_report is None:
change_report = {'status': 'UNCONFIRMED', 'scope': original['scope'],
**comparison_rules(scope),
'unrelated_cbb_content_checked': False,
'detail': '原生会话尚未释放,未读取写后内容'}
if safe:
+25 -26
View File
@@ -798,7 +798,8 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
pythoncom.PumpWaitingMessages(); time.sleep(.1)
raise TimeoutError(f'原生窗口未出现:{title}')
_require_add_supervisor(job, root)
app.OnReusableBlocksEditor()
from .session_record import dispatch_native
dispatch_native(job, lambda: app.OnReusableBlocksEditor())
_require_add_supervisor(job, root)
editor = await_window('Reusable Blocks')
tabs = Desktop(backend='uia').window(handle=editor).descendants(control_type='TabItem')
@@ -835,10 +836,11 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
_write_json(root/'native-add-log-baseline.json', log_baseline)
observed_failures = {}
_require_add_supervisor(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL', required=True)
job['_native_add_pending'] = True
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
from .session_record import dispatch_native, update_worker_state
def submit_add():
job['_native_add_pending'] = True
win32gui.PostMessage(ok, win32con.BM_CLICK, 0, 0)
dispatch_native(job, submit_add, asynchronous=True, required=True)
success = None
while time.monotonic() < deadline:
pythoncom.PumpWaitingMessages()
@@ -1106,9 +1108,10 @@ def _catalog_com(job, root):
watcher = None
try:
_require_management_continuation(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL')
app = win32com.client.DispatchEx('LibraryManager.Application')
from .session_record import dispatch_native, update_worker_state
# Keep the launch pending until its exact native identity is recorded.
app = dispatch_native(job, lambda: win32com.client.DispatchEx('LibraryManager.Application'),
asynchronous=True)
app.Visible = True
processes = _process_details('LibraryManager.exe')
owned_pids.update(int(p[0]) for p in processes)
@@ -1124,15 +1127,14 @@ def _catalog_com(job, root):
if job['operation'] in ('probe_create_add', 'probe_create'):
target = prepare_probe_library(job, root)
_require_management_continuation(job, root)
update_worker_state(job, 'NATIVE_CALL')
library = app.CreateLibrary(str(target), 1)
library = dispatch_native(job, lambda: app.CreateLibrary(str(target), 1), asynchronous=True)
_write_json(root.parent/'probe-owner.json', {'library': str(target), 'token': job['probe_token']})
else:
if job['operation'] == 'probe_readd':
validate_probe_readd(job, root)
_require_management_continuation(job, root)
update_worker_state(job, 'NATIVE_CALL')
library = app.OpenLibrary(str(absolute_preserving_drive(job['library'])))
library = dispatch_native(job, lambda: app.OpenLibrary(str(absolute_preserving_drive(job['library']))),
asynchronous=True)
update_worker_state(job, 'POSTCALL')
if refused:
raise RuntimeError('目录读取需要升级中心库或选择流程;已拒绝,目标未获准自动升级。')
@@ -1142,12 +1144,10 @@ def _catalog_com(job, root):
if int(library.FlowType) != 1:
raise RuntimeError('Native Add requires the DxDesigner Logical-Physical library flow.')
_probe_add_dialog(app, job, desktop, owned_pids, root, library=library)
update_worker_state(job, 'CLOSING')
library.Close()
dispatch_native(job, lambda: library.Close(), phase='CLOSING')
library = None
_require_management_continuation(job, root)
update_worker_state(job, 'NATIVE_CALL')
library = app.OpenLibrary(str(absolute_preserving_drive(job['library'])))
library = dispatch_native(job, lambda: app.OpenLibrary(str(absolute_preserving_drive(job['library']))))
if (library is None or Path(str(library.FullName)).resolve() != Path(job['library']).resolve()
or int(library.FlowType) != 1):
raise RuntimeError('Native Add reopen did not confirm the exact library and flow.')
@@ -1189,16 +1189,14 @@ def _catalog_com(job, root):
finally:
if library is not None and not job.get('_native_add_pending'):
try:
update_worker_state(job, 'CLOSING')
library.Close()
dispatch_native(job, lambda: library.Close(), phase='CLOSING')
except Exception as error:
result['close_detail'] = str(error)
result['close_exception'] = _exception_details(error)
library = None
if app is not None and not job.get('_native_add_pending'):
try:
update_worker_state(job, 'CLOSING')
app.Quit()
dispatch_native(job, lambda: app.Quit(), phase='CLOSING')
except Exception as error:
result['quit_detail'] = str(error)
result['quit_exception'] = _exception_details(error)
@@ -1266,16 +1264,15 @@ def management_worker_main(request_path):
_write_json(root/'command.json', command)
with (root/'native-output.txt').open('wb') as output:
_require_management_continuation(job, root)
from .session_record import update_worker_state
update_worker_state(job, 'NATIVE_CALL')
from .session_record import dispatch_native, update_worker_state
result['safe_to_continue'] = False
try:
process = subprocess.Popen(command, stdout=output, stderr=subprocess.STDOUT,
creationflags=subprocess.CREATE_NO_WINDOW)
process = dispatch_native(job, lambda: subprocess.Popen(command, stdout=output,
stderr=subprocess.STDOUT, creationflags=subprocess.CREATE_NO_WINDOW), asynchronous=True)
except (FileNotFoundError, PermissionError):
result['safe_to_continue'] = True
raise
update_worker_state(job, 'NATIVE_CALL', identities=[('native', process.pid)])
update_worker_state(job, 'NATIVE_CALL', identities=[('native', process.pid)], continuation=True)
try:
_write_json(root/'native-process.json', {'pid': process.pid, 'command': command})
except OSError:
@@ -1292,6 +1289,7 @@ def management_worker_main(request_path):
except subprocess.TimeoutExpired:
continue
result['wait_exceeded'] = True
update_worker_state(job, 'POSTCALL')
result.update(safe_to_continue=True, exit_code=code)
text = (root/'native-output.txt').read_bytes().decode('mbcs', errors='replace')
result.update(success=removal_output_ok(code, text, job['name'], job['partition']),
@@ -1305,6 +1303,7 @@ def management_worker_main(request_path):
result['exception'] = _exception_details(error)
finally:
from .session_record import update_worker_state
update_worker_state(job, 'FINISHED' if result.get('safe_to_continue') is True else 'UNCONFIRMED')
_write_json(root/'result.json', result)
# FINISHED permits the orphan watchdog to exit immediately.
update_worker_state(job, 'FINISHED' if result.get('safe_to_continue') is True else 'UNCONFIRMED')
return 0 if result['success'] and result['safe_to_continue'] else 2
+10 -5
View File
@@ -15,9 +15,10 @@ class NativeQueue:
def wake(self):
with self.condition: self.condition.notify_all()
def run(self, action, *, stop=None, waiting=None, ready=lambda: True):
def run(self, action, *, stop=None, waiting=None, ready=lambda: True, wait_state=None):
ticket = object()
acquired, notified = False, False
previous_state = None
with self.condition: self.pending.append((ticket, ready))
try:
while not acquired:
@@ -30,10 +31,14 @@ class NativeQueue:
self.active = acquired = True
else:
self.condition.wait(.1)
if not acquired and not notified and waiting is not None:
notified = True
try: waiting()
except Exception: pass
if not acquired and waiting is not None:
try:
current_state = wait_state() if wait_state is not None else None
if not notified or current_state != previous_state:
waiting()
notified, previous_state = True, current_state
except Exception:
pass
if stop is not None and stop.is_set():
raise QueueCancelled('已取消排队,未启动原生操作。')
return action()
-15
View File
@@ -160,18 +160,3 @@ def wait_for_target_document(job, app_provider, *, process_alive, emit=lambda **
last_observation = observation
sleep(.25)
raise PcbBridgeError('PCB_EXITED_BEFORE_COM', 'PCB 在 COM 文档就绪前退出')
def execution_outcome(*, save_complete: bool, pcb_exited: bool,
fatal_error: str = '') -> dict[str, object]:
if fatal_error:
code, _, detail = str(fatal_error).partition(':')
return {'status': 'FAIL', 'error_code': code.strip() or 'FATAL_DIALOG',
'stderr': detail.strip() or str(fatal_error), 'safe_to_continue': True}
if not save_complete:
return {'status': 'FAIL', 'error_code': 'SAVE_NOT_CONFIRMED',
'stderr': '保存/关闭未完成', 'safe_to_continue': True}
if not pcb_exited:
return {'status': 'FAIL', 'error_code': 'PCB_EXIT_NOT_CONFIRMED',
'stderr': '保存后未确认 PCB 退出', 'safe_to_continue': True}
return {'status': 'PASS', 'stdout': 'Project Integration 已同步;保存、关闭和 PCB 退出均已确认。'}
+59 -11
View File
@@ -15,6 +15,15 @@ import stat
MANIFEST_VERSION = 1
MANIFEST_RULE_VERSION = 1
_ROOT_RUNTIME_PREFIX = 'work.before-restore-'
_ROOT_RUNTIME_PATH = ('projectbackup', 'backups')
_NATIVE_RUNTIME_DIRECTORIES = ('log', 'dbcheck', 'dbrestore')
_NATIVE_SERVER_DIRECTORY = 'cdbsvr'
_PROJECT_PCB_DIRECTORY = 'pcb'
_PROJECT_DATABASE_PREFIXES = (('database',), (_PROJECT_PCB_DIRECTORY, 'database'))
_NONPRIMARY_FILENAMES = ('saddress.adr',)
_NONPRIMARY_FILENAME_PREFIXES = ('~$',)
_NONPRIMARY_DIRECTORIES = frozenset({
'log', 'logs', 'temp', 'tmp', '__pycache__', 'backup', 'backups',
'output', 'outputs', 'report', 'reports', 'gerber', 'gerbers', 'odb++',
@@ -29,22 +38,21 @@ def _root_runtime(directories):
"""Known runtime/history children of a library or project workspace root."""
return bool(directories and (
directories[0] in _NONPRIMARY_DIRECTORIES
or directories[0].startswith('work.before-restore-')
or directories[:2] == ('projectbackup', 'backups')))
or directories[0].startswith(_ROOT_RUNTIME_PREFIX)
or directories[:len(_ROOT_RUNTIME_PATH)] == _ROOT_RUNTIME_PATH))
def _native_runtime(directories, database_prefix):
runtime_prefix = database_prefix + ('cdbsvr',)
runtime_prefix = database_prefix + (_NATIVE_SERVER_DIRECTORY,)
return (directories[:len(runtime_prefix)] == runtime_prefix
and len(directories) > len(runtime_prefix)
and directories[len(runtime_prefix)] in ('log', 'dbcheck', 'dbrestore'))
and directories[len(runtime_prefix)] in _NATIVE_RUNTIME_DIRECTORIES)
def _project_runtime(directories):
return (_root_runtime(directories)
or (directories[:1] == ('pcb',) and _root_runtime(directories[1:]))
or _native_runtime(directories, ('database',))
or _native_runtime(directories, ('pcb', 'database')))
or (directories[:1] == (_PROJECT_PCB_DIRECTORY,) and _root_runtime(directories[1:]))
or any(_native_runtime(directories, prefix) for prefix in _PROJECT_DATABASE_PREFIXES))
@dataclass(frozen=True)
@@ -85,7 +93,8 @@ class ManifestScope:
"""
directories = parts if directory else parts[:-1]
if not directory and (Path(parts[-1]).suffix in _NONPRIMARY_SUFFIXES
or parts[-1] == 'saddress.adr' or parts[-1].startswith('~$')):
or parts[-1] in _NONPRIMARY_FILENAMES
or parts[-1].startswith(_NONPRIMARY_FILENAME_PREFIXES)):
return True
if self.kind == 'project':
return _project_runtime(directories)
@@ -123,6 +132,36 @@ class ManifestScope:
return 'shared_dependency'
def comparison_rules(scope):
"""Describe semantic exclusions using the classifier's rule constants."""
project_positions = ['project root or its PCB child']
project_native = ' or '.join('/'.join(prefix + (_NATIVE_SERVER_DIRECTORY,))
for prefix in _PROJECT_DATABASE_PREFIXES)
native_positions = [project_native + ' under project root']
if scope.kind == 'library':
project_positions = ['library root', 'selected CBB Work/Cert root or its PCB child']
native_positions = [
project_native + ' under selected CBB Work/Cert',
'SymbolLibs/<partition>/' + _NATIVE_SERVER_DIRECTORY,
'<shared dependency>/' + _NATIVE_SERVER_DIRECTORY,
]
return {
'rule_version': MANIFEST_RULE_VERSION,
'excluded_categories': sorted(_NONPRIMARY_DIRECTORIES),
'excluded_suffixes': sorted(_NONPRIMARY_SUFFIXES),
'runtime_exclusions': {
'directory_name_positions': project_positions,
'directory_prefixes': [_ROOT_RUNTIME_PREFIX],
'relative_directories': ['/'.join(_ROOT_RUNTIME_PATH)],
'native_directory_names': sorted(_NATIVE_RUNTIME_DIRECTORIES),
'native_directory_positions': native_positions,
'file_names': list(_NONPRIMARY_FILENAMES),
'file_name_prefixes': list(_NONPRIMARY_FILENAME_PREFIXES),
'coordination_checkpoints': 'recognized CBB coordination checkpoints',
},
}
def hash_file(path):
digest = hashlib.sha256()
with Path(path).open('rb') as stream:
@@ -271,7 +310,10 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
Native icdb.dat/LMC files are held with exclusive read handles for the copy.
Their expected SHA256 comes from the source read stream, independently of
hashing destination bytes. Failures retain the partial destination evidence.
hashing destination bytes. Unlocked primary files are also hashed while
streaming the copy, then rehashed at source to detect even same-size/mtime
edits. Every primary destination is independently hashed. Failures retain
the partial destination evidence.
Progress receives one dict with stage, hashed_files/bytes and copied_files.
"""
import win32con
@@ -329,9 +371,15 @@ def copy_verified(source, destination, *, scope=None, progress=None, hash_functi
shutil.copystat(path, copied)
if stream_hash is not None:
digest = stream_hash.hexdigest()
elif label is not None:
stream_hash = hashlib.sha256()
with path.open('rb') as incoming, copied.open('wb') as outgoing:
for data in iter(lambda: incoming.read(1024 * 1024), b''):
stream_hash.update(data)
outgoing.write(data)
shutil.copystat(path, copied)
digest = stream_hash.hexdigest()
else:
if label is not None:
digest = hash_function(path)
shutil.copy2(path, copied)
before, after = entries[path], path.stat()
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
+41 -6
View File
@@ -32,24 +32,36 @@ def library_available(library):
def retained_session_snapshot(library):
key = _library_key(library)
with _observer_guard:
return {path: (aliases, _retained_results.get(path, {}).get('block'))
return {path: (aliases, _retained_results.get(path, {}).get('block'),
_retained_results.get(path, {}).get('operation_id'))
for path, aliases in _retained_libraries.items() if key in aliases}
def reconciled_retained_sessions(snapshot, *, block_name=None):
with _observer_guard:
return [{'path': path, 'block_name': block, 'operation_id': operation_id}
for path, (aliases, block, operation_id) in snapshot.items()
if _retained_libraries.get(path) is aliases
and _retained_results.get(path, {}).get('operation_id') == operation_id
and (block_name is None or block == block_name)]
def acknowledge_library_release(proof, snapshot, *, block_name=None):
"""Called under fresh proof handles; never clear a newer handoff."""
if proof.get('status') != 'RELEASE_CONFIRMED':
return
key = _library_key(proof['library'])
with _observer_guard:
records = [dict(_retained_results.get(path, {}), path=path)
for path, (aliases, block) in snapshot.items()
records = [dict(path=path, operation_id=operation_id)
for path, (aliases, block, operation_id) in snapshot.items()
if key in aliases and _retained_libraries.get(path) is aliases
and _retained_results.get(path, {}).get('operation_id') == operation_id
and (block_name is None or block == block_name)]
record_session_release(proof, records)
with _observer_guard:
for path, (aliases, block) in snapshot.items():
for path, (aliases, block, operation_id) in snapshot.items():
if (key in aliases and _retained_libraries.get(path) is aliases
and _retained_results.get(path, {}).get('operation_id') == operation_id
and (block_name is None or block == block_name)):
_retained_libraries.pop(path, None)
_retained_results.pop(path, None)
@@ -84,6 +96,15 @@ def retained_session_states(library):
if key in aliases and path in _retained_results]
def library_wait_reason(library):
"""Cached explanation for queue admission; never probe disk or native clients."""
key = _library_key(library)
with _observer_guard:
retained = [path for path, aliases in _retained_libraries.items() if key in aliases]
names = sorted({_retained_results.get(path, {}).get('block') or '当前库' for path in retained})
return '该库有残留会话('+', '.join(names)+'),请查看并处理。' if names else ''
def register_worker_session(worker, job):
"""The launcher must persist identity before opening the worker's gate."""
path = Path(job['session_record_path'])
@@ -94,13 +115,14 @@ def register_worker_session(worker, job):
worker.cbb_library = job['library']
def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False):
def update_worker_state(job, phase, *, identities=(), write_outcome=None, required=False, continuation=False):
"""required controls I/O; only existing same-phase calls may continue recording after supervisor loss."""
if not job.get('session_record_path'):
if required:
raise ValueError('原生写入缺少会话记录位置,未提交新的调用')
return False
from .desktop_worker import worker_phase
with worker_phase(job['operation_id'], phase):
with worker_phase(job['operation_id'], phase, continuation=continuation):
path = Path(job['session_record_path']).with_name('worker-state.json')
try:
state = ({'operation_id': job['operation_id'], 'processes': []} if not path.exists()
@@ -123,6 +145,19 @@ def update_worker_state(job, phase, *, identities=(), write_outcome=None, requir
return False
def dispatch_native(job, call, *, phase='NATIVE_CALL', asynchronous=False, required=False):
"""Reserve the native call before dispatch; asynchronous results require an explicit acknowledgment."""
update_worker_state(job, phase, required=required)
try:
result = call()
except BaseException:
update_worker_state(job, 'UNCONFIRMED')
raise
if not asynchronous:
update_worker_state(job, 'POSTCALL')
return result
def process_identity(pid):
from .residual_sessions import _process_handle, _handle_identity, _force_ownership
with _process_handle(pid) as handle:
+4 -2
View File
@@ -65,7 +65,7 @@ class IcdbCheckTask(QObject):
if self.paused: return
request = self.requests[len(self.results)]
def check():
from ..session_record import library_available
from ..session_record import library_available, library_wait_reason
try:
def execute():
if request.block_name in self.ready_names:
@@ -75,9 +75,11 @@ class IcdbCheckTask(QObject):
self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name})
return self.verifier(request)
return self.queue.run(execute, stop=self.stop,
wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)),
ready=lambda: not self.paused and library_available(request.lmc_file),
waiting=lambda: self.event.emit({'stage': 'waiting_native_slot', 'block': request.block_name,
'detail': '已排队,等待当前原生操作结束'}))
'library': str(request.lmc_file), 'retained': not library_available(request.lmc_file),
'detail': library_wait_reason(request.lmc_file) or '已排队,等待当前原生操作结束'}))
except QueueCancelled as error:
return VerifyResult('CANCELLED', stderr=str(error))
except Exception as error:
+99 -16
View File
@@ -99,7 +99,6 @@ class MainWindow(QWidget):
self._management_unsafe_libraries = set()
self._management_operation_library = None
self._maintenance_recovery_view = False
self._reload_after_maintenance = False
self._reimport_offers = ()
self._batch_requests = ()
self._batch_records = {}
@@ -135,6 +134,12 @@ class MainWindow(QWidget):
self._mapping_auto_idle = False
self._mapping_finish_waiters = []
self._closing = self._close_ready = False
self._queue_wait_library = None
self._queue_release_mode = False
self.close_wait_timer = QTimer(self)
self.close_wait_timer.setSingleShot(True)
self.close_wait_timer.setInterval(120_000)
self.close_wait_timer.timeout.connect(self._show_close_wait_notice)
from cbb_refresh_verify.operation_queue import NativeQueue
self.native_queue = NativeQueue()
self.icdb_task = None
@@ -309,6 +314,10 @@ class MainWindow(QWidget):
self.section_stack.addWidget(management)
layout.addWidget(self.section_stack)
layout.addWidget(self.status_label)
self.queue_release_button = QPushButton('查看残留会话…')
self.queue_release_button.hide()
self.queue_release_button.clicked.connect(lambda: self.check_library_release(queued=True))
layout.addWidget(self.queue_release_button)
self.runtime_log_toggle = QToolButton(); self.runtime_log_toggle.setText('查看运行日志')
self.runtime_log_toggle.setCheckable(True)
self.runtime_log_toggle.toggled.connect(self.output.setVisible)
@@ -410,6 +419,8 @@ class MainWindow(QWidget):
self.backup_restore_button.setEnabled(ready and bool(
self._eligible_names(checked_only=bool(self.selected_records()))))
self.release_library_button.setEnabled(not self.busy and bool(self.lmc_edit.text().strip()))
self.queue_release_button.setVisible(self._queue_wait_library is not None)
self.queue_release_button.setEnabled(self._queue_wait_library is not None and not self._closing)
reasons = []
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
reason = self._management_block_reason(operation)
@@ -481,13 +492,24 @@ class MainWindow(QWidget):
self.output.append(f'未完成会话:{session.get("block") or ""} · '
f'{phase} · {session.get("detail", "")}\n{session["path"]}')
def check_library_release(self):
if self.busy or not self.lmc_edit.text().strip():
def check_library_release(self, checked=False, *, queued=False):
allowed_queue = queued and self._queue_wait_library is not None
if (self.busy and not allowed_queue) or not self.lmc_edit.text().strip():
return
from shiboken6 import isValid
previous = getattr(self, 'release_dialog', None)
if previous is not None and isValid(previous) and previous.isVisible():
previous.raise_()
return
from .residual_release_dialog import ResidualReleaseDialog
library = Path(self.mentor_lmc_path or self.lmc_edit.text().strip())
library = Path(self._queue_wait_library if allowed_queue else self.mentor_lmc_path or self.lmc_edit.text().strip())
self._queue_release_mode = bool(allowed_queue and self.busy)
self.release_dialog = ResidualReleaseDialog(library, self.data_root/'release-checks', self)
self.release_dialog.native_queue = self.native_queue
if self._queue_release_mode:
from cbb_refresh_verify.network_path import release_retained_path_leases
lease = self.library_lease
self.release_dialog.release_finalizer = lambda proof: release_retained_path_leases(proof, current_lease=lease)
self.release_dialog.before_release.connect(self._stop_icdb_check)
self.release_dialog.released.connect(lambda result: self._complete_library_release(self.release_dialog.library, result))
self.release_dialog.finished.connect(self._release_dialog_finished)
@@ -495,10 +517,20 @@ class MainWindow(QWidget):
self.release_dialog.show()
def _release_dialog_finished(self, _=None):
if self._queue_release_mode:
self._queue_release_mode = False
self._update()
return
if self._defer_mapping_finish(self._release_dialog_finished): return
self._finished()
pending = getattr(self, '_resume_batch', None)
if pending and pending['released']:
if getattr(self, 'summary', None) is None:
self.summary = self._new_result_summary('_batch_summary')
self.summary.setWindowTitle('继续未执行项')
self._resume_batch_action = self.summary.addButton('继续未执行项', QMessageBox.ActionRole)
self._resume_batch_action.clicked.connect(self._resume_released_batch)
self._update()
self.summary.setText('会话已释放,可以继续未执行项。')
self.summary.show()
@@ -512,6 +544,9 @@ class MainWindow(QWidget):
except Exception as error:
self._failed(error)
return
if result.get('mapping_cleanup_complete') is True:
self._library_release_ready(library, result)
return
lease = self.library_lease
def release():
try:
@@ -597,6 +632,7 @@ class MainWindow(QWidget):
self.management_dialog = ManagementDialog(requests, self, adapter=self.management_adapter,
recovery_from=recovery_from)
self.management_dialog.native_queue = self.native_queue
self.management_dialog.release_requested.connect(self._open_waiting_release)
self.management_dialog.before_execute.connect(lambda names: self._invalidate_check_targets(requests[0].library, names))
self._management_results = []
self.management_dialog.completed.connect(self._management_completed)
@@ -604,6 +640,12 @@ class MainWindow(QWidget):
self.busy = True; self._update()
self.management_dialog.show()
def _open_waiting_release(self, library):
from cbb_refresh_verify.session_record import library_available
if not library_available(library):
self._queue_wait_library = str(library)
self.check_library_release(queued=True)
def reimport_failed(self):
if self.busy or not self._reimport_offers or not self.management_capabilities['update'].supported:
return
@@ -620,7 +662,6 @@ class MainWindow(QWidget):
mapped_drive=getattr(self.library_lease, 'drive', ''),
mapped_remote_root=getattr(self.library_lease, 'remote_root', '')))
previous[record.name] = str(result.evidence_path)
self._reload_after_maintenance = False
if getattr(self, 'summary', None): self.summary.close()
self._open_management_dialog(requests, recovery_from=previous)
@@ -776,12 +817,14 @@ class MainWindow(QWidget):
self.pool.start(self.worker)
def _queued_action(self, action):
from cbb_refresh_verify.session_record import library_available
from cbb_refresh_verify.session_record import library_available, library_wait_reason
library = getattr(self, 'mentor_lmc_path', None) or self.lmc_edit.text()
return lambda: self.native_queue.run(action, stop=self.stop,
ready=lambda: library_available(library),
wait_state=lambda: library_wait_reason(library),
waiting=lambda: self.signals.event.emit({'stage': 'waiting_native_slot',
'detail': '已排队,等待当前原生操作结束'}))
'library': str(library), 'retained': not library_available(library),
'detail': library_wait_reason(library) or '已排队,等待当前原生操作结束'}))
def _icdb_active(self):
return self.icdb_task is not None and self.icdb_task.active
@@ -799,7 +842,7 @@ class MainWindow(QWidget):
if hasattr(task, 'summary'):
prefix = '已更新的工程:'+', '.join(sorted(task.invalidated))+'。下列为此前检查记录。\n'
task.summary.setDetailedText(prefix+task.summary.detailedText())
if names & getattr(task, 'recovery_names', set()):
if names & getattr(task, 'recovery_names', set()) and hasattr(task, 'recovery_action'):
task.recovery_action.setEnabled(False)
task.recovery_action.setToolTip('工程已有后续管理操作,请重新检查。')
self._reimport_offers = tuple(offer for offer in self._reimport_offers if offer[0].block_name not in names
@@ -842,7 +885,13 @@ class MainWindow(QWidget):
name, stage = str(event.get('block', '')), str(event.get('stage', ''))
detail = str(event.get('detail') or stage)
self.icdb_phase.setText(f'{name} · '+({'icdb_check_start': '正在检查',
'icdb_startup_check': '正在打开工程', 'waiting_native_slot': '已排队,等待执行'}.get(stage, detail)))
'icdb_startup_check': '正在打开工程'}.get(stage, detail)))
if stage == 'waiting_native_slot':
self._queue_wait_library = event.get('library') if event.get('retained') else None
self._update()
elif stage == 'icdb_check_start':
self._queue_wait_library = None
self._update()
if not self.busy: self.status_label.setText('后台 ICDB 检查:'+self.icdb_phase.text())
if self.logging_context:
self.logging_context.logger.info('icdb_background block=%s stage=%s detail=%s', name, stage, detail)
@@ -899,7 +948,7 @@ class MainWindow(QWidget):
self.icdb_phase.setText(text)
if not self.busy: self.status_label.setText(text)
self.output.append(text+'\n'+str(task.report or task.report_error))
summary = QMessageBox(self); self.icdb_summary = summary
summary = self._new_result_summary('icdb_summary')
task.summary = summary
if not self.busy: self.summary = summary
summary.setWindowTitle('ICDB 批量检查结果'); summary.setText(text)
@@ -1397,6 +1446,10 @@ class MainWindow(QWidget):
from shiboken6 import isValid
if not isValid(self) or not isValid(self.cbb_table):
return
if event.get('stage') == 'waiting_native_slot':
self._queue_wait_library = event.get('library') if event.get('retained') else None
self.status_label.setText(event.get('detail', '已排队,等待执行'))
self._update()
if event.get('stage') in ('session_handoff', 'save_stop_requested'):
self.status_label.setText(event.get('detail', '当前状态无法确认'))
if (event.get('stage') == 'session_observation' and event.get('status') == 'RELEASED'
@@ -1446,6 +1499,30 @@ class MainWindow(QWidget):
if cell is not None:
cell.setBackground(QColor('#E8F5E9'))
def _new_result_summary(self, attribute):
previous = getattr(self, attribute, None)
if previous is not None:
previous.close()
summary = QMessageBox(self)
setattr(self, attribute, summary)
summary.setAttribute(Qt.WA_DeleteOnClose)
summary.finished.connect(lambda _: self._forget_result_summary(summary))
return summary
def _forget_result_summary(self, summary):
if getattr(self, '_batch_summary', None) is summary:
self._reimport_summary_action = None
self._residual_release_action = None
self._resume_batch_action = None
for attribute in ('summary', '_batch_summary', 'icdb_summary'):
if getattr(self, attribute, None) is summary:
setattr(self, attribute, None)
for task in self.icdb_tasks:
if getattr(task, 'summary', None) is summary:
del task.summary
if hasattr(task, 'recovery_action'):
del task.recovery_action
def _batch_done(self, outcome):
results, report = outcome[:2]
failure_report = failure_report_path(report) if report is not None else '未写入'
@@ -1507,7 +1584,7 @@ class MainWindow(QWidget):
text += guidance
status_text += guidance
self.status_label.setText(status_text.replace('\n', ' ')); self.output.append(text)
self.summary = QMessageBox(self)
self.summary = self._new_result_summary('_batch_summary')
self.summary.setWindowTitle('ICDB 批量检查结果' if self._global_icdb_run else 'CBB 校验结果')
self.summary.setText(status_text)
self.summary.setDetailedText(text)
@@ -1576,11 +1653,8 @@ class MainWindow(QWidget):
if self.version_dialog is not None:
self.version_dialog.reject()
self.version_dialog = None
self._queue_wait_library = None
self.busy = False; self._update()
if self._reload_after_maintenance:
from PySide6.QtCore import QTimer
self._reload_after_maintenance = False
QTimer.singleShot(0, self.load_library)
def open_logs(self):
self.data_root.mkdir(parents=True, exist_ok=True); os.startfile(str(self.data_root))
@@ -1602,6 +1676,9 @@ class MainWindow(QWidget):
else:
self._closing = True
self.busy = True; self._update()
self.setWindowTitle('CBB 刷新校验 · 等待任务安全结束')
self.status_label.setText('正在等待当前操作安全结束,完成后关闭。')
self.close_wait_timer.start()
retained = None
if self._native_backup_session is not None:
self.native_backup_timer.stop()
@@ -1614,11 +1691,16 @@ class MainWindow(QWidget):
self._close_when_idle()
event.ignore()
def _show_close_wait_notice(self):
if self._closing and not self._close_ready:
self.setWindowTitle('CBB 刷新校验 · 仍在等待任务安全结束')
self.status_label.setText('当前操作尚未结束,仍在等待安全关闭。')
def _close_when_idle(self):
owners = [self, *self.icdb_tasks]
for name in ('management_dialog', 'backup_dialog', 'release_dialog'):
owners.append(getattr(self, name, None))
active = False
active = bool(self.lifecycle_pool.activeThreadCount())
for owner in owners:
try:
pool = getattr(owner, 'pool', None)
@@ -1628,5 +1710,6 @@ class MainWindow(QWidget):
if self._lease_pending or active:
QTimer.singleShot(20, self._close_when_idle)
return
self.close_wait_timer.stop()
self._close_ready = True
self.close()
+16 -6
View File
@@ -38,6 +38,7 @@ class ManagementSignals(QObject):
class ManagementDialog(QDialog):
completed = Signal(object)
before_execute = Signal(object)
release_requested = Signal(object)
def __init__(self, requests, parent=None, *, adapter=None, runner=None, recovery_from=None):
super().__init__(parent)
@@ -73,6 +74,9 @@ class ManagementDialog(QDialog):
self.auto_verify.setVisible(self.operation != 'remove')
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 更新会先移除再重新导入,失败时请使用手动备份恢复。')
self.status_label.setWordWrap(True)
self.release_wait_button = QPushButton('查看残留会话…')
self.release_wait_button.hide()
self.release_wait_button.clicked.connect(lambda: self.release_requested.emit(self.template.library))
self.output = QTextEdit(); self.output.setReadOnly(True)
self.output.document().setMaximumBlockCount(2000)
self.output.hide()
@@ -93,7 +97,8 @@ class ManagementDialog(QDialog):
layout.addWidget(QLabel(f'目标库:{self.template.library}'))
layout.addWidget(self.table)
layout.addWidget(self.sources_button); layout.addWidget(self.auto_verify)
layout.addWidget(self.status_label); layout.addWidget(self.logs_button); layout.addWidget(self.output)
layout.addWidget(self.status_label); layout.addWidget(self.release_wait_button)
layout.addWidget(self.logs_button); layout.addWidget(self.output)
buttons = QHBoxLayout()
for widget in (self.execute_button, self.stop_button, self.close_button): buttons.addWidget(widget)
layout.addLayout(buttons)
@@ -171,11 +176,14 @@ class ManagementDialog(QDialog):
progress=self.signals.progress.emit)
if self.native_queue is None: return action()
from ..operation_queue import QueueCancelled
from ..session_record import library_available
from ..session_record import library_available, library_wait_reason
try:
return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit(
{'stage': 'waiting_native_slot', 'detail': '已排队,等待当前检查结束'}),
ready=lambda: library_available(self.template.library))
{'stage': 'waiting_native_slot',
'retained': not library_available(self.template.library),
'detail': library_wait_reason(self.template.library) or '已排队,等待当前检查结束'}),
ready=lambda: library_available(self.template.library),
wait_state=lambda: library_wait_reason(self.template.library))
except QueueCancelled as error:
from ..management import ManagementResult
return [ManagementResult(r.operation, r.library, r.name, r.partition, r.source, r.auto_verify,
@@ -194,6 +202,7 @@ class ManagementDialog(QDialog):
def _progress(self, event):
stage = str(event.get('stage', ''))
self.release_wait_button.setVisible(stage == 'waiting_native_slot' and bool(event.get('retained')))
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, "正在处理"))}'
if stage == 'waiting_native_slot': text = str(event.get('detail', '已排队,等待执行'))
self.output.append(str(event))
@@ -211,8 +220,8 @@ class ManagementDialog(QDialog):
changes = getattr(result, 'change_report', None)
if changes:
if changes.get('status') == 'RECORDED':
text += (f'\n变更:新增 {len(changes["added"])}、删除 {len(changes["deleted"])}、'
f'修改 {len(changes["modified"])} 个主要文件。')
text += (f'\n已比对的工程文件:新增 {len(changes["added"])}、删除 {len(changes["deleted"])}、'
f'修改 {len(changes["modified"])};范围仅限报告列出的工程文件。')
else:
summary += ',变更清单待核对'
text += '\n'+changes.get('detail', '变更清单未确认')
@@ -239,6 +248,7 @@ class ManagementDialog(QDialog):
request.source, request.auto_verify, 'complete', 'RECOVERY_REQUIRED', False, str(error))])
def _finished(self):
self.release_wait_button.hide()
self.busy = False; self._enabled(True)
def reject(self):
@@ -19,6 +19,7 @@ class ResidualReleaseDialog(QDialog):
self.library, self.evidence_dir = Path(library), Path(evidence_dir)
self.plan = None
self.native_queue = None
self.release_finalizer = None
self.busy = False
self.stop = Event()
self._refresh_after = False
@@ -33,8 +34,8 @@ class ResidualReleaseDialog(QDialog):
self.runtime_label = QLabel()
self.runtime_label.setWordWrap(True)
layout.addWidget(self.runtime_label)
self.table = QTableWidget(0, 6)
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径'])
self.table = QTableWidget(0, 8)
self.table.setHorizontalHeaderLabels(['工程', '程序', 'PID', '状态', '窗口位置', '程序路径', '确认范围', '执行结果'])
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
self.table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
self.table.setEditTriggers(QTableWidget.NoEditTriggers)
@@ -91,9 +92,14 @@ class ResidualReleaseDialog(QDialog):
def _rows(self, sessions):
self.table.setRowCount(len(sessions))
for index, session in enumerate(sessions):
allowed = session.get('consent_allowed')
permission = '允许' if allowed is True else '未允许' if allowed is False else '待确认'
outcome = {'RELEASED': '已释放', 'WAITING': '未释放', 'IDENTITY_CHANGED': '身份已变化',
'CANCELLED': '已停止', 'REQUESTING': '执行中', 'NOT_STARTED': '尚未执行'}.get(
session.get('release_status'), '待执行')
for column, value in enumerate((session.get('project', ''), session['name'],
session['pid'], session.get('detail', ''), ', '.join(session.get('desktops', [])),
session.get('image', session.get('executable', '')))):
session.get('image', session.get('executable', '')), permission, outcome)):
self.table.setItem(index, column, QTableWidgetItem(str(value)))
if sessions: self.table.setCurrentCell(0, 0)
@@ -137,7 +143,8 @@ class ResidualReleaseDialog(QDialog):
from cbb_refresh_verify.residual_sessions import request_native_cancel
self.before_release.emit(); self.stop.clear()
def execute():
action = lambda: request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop)
action = lambda: self._finalize_release_result(
request_native_cancel(session, self.library, self.evidence_dir, stop=self.stop))
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
def done(result):
self.message.setText(result.get('detail') or '\n'.join(r.get('detail', '') for r in result['sessions']))
@@ -162,6 +169,16 @@ class ResidualReleaseDialog(QDialog):
self.released.emit(proof)
return True
def _finalize_release_result(self, result):
"""Complete mapping cleanup before the serialized release admits new work."""
proof = result.get('proof', {})
if (self.release_finalizer is not None and proof.get('status') == 'RELEASE_CONFIRMED'
and Path(proof.get('library', '')).absolute() == self.library.absolute()
and all(row.get('release_status') == 'RELEASED' for row in result['sessions'])):
self.release_finalizer(proof)
return {**result, 'proof': {**proof, 'mapping_cleanup_complete': True}}
return result
def answer_prompt(self):
if self.busy or not self.plan: return
row = self.table.currentRow()
@@ -239,8 +256,13 @@ class ResidualReleaseDialog(QDialog):
self.message.setText(f'已释放 {count} 个会话,其余会话或库状态仍待确认。'
+ ('\n'+result['detail'] if result.get('detail') else '可查看原生提示、处理保存或请求取消后重新检查。')
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
allowed = [row for row in result['sessions'] if row.get('consent_allowed') is True]
pending = sum(row.get('release_status') != 'RELEASED' for row in allowed)
self.message.setText(self.message.text()+f'\n确认允许 {len(allowed)} 项,其中未释放 {pending} 项。')
def execute():
action = lambda: release_residual_sessions(plan, self.evidence_dir, stop=self.stop, force=force)
def action():
result = release_residual_sessions(plan, self.evidence_dir, stop=self.stop, force=force)
return self._finalize_release_result(result)
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
self._start(execute, done)
+21 -2
View File
@@ -84,11 +84,30 @@ def test_scan_reuses_checkpoint_and_queries_only_missing(tmp_path):
encoding="utf-8",
)
bridge = FakeBridge()
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint)
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint, resume=True)
assert bridge.requests == ["B"]
assert {record.block_name for record in records} == {"A", "B"}
def test_default_scan_refreshes_cached_ready_after_payload_change(tmp_path):
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
checkpoint = tmp_path/'scan.jsonl'
BatchStatusSession(FakeBridge()).scan(['A'], lmc, checkpoint)
# The lightweight fingerprint cannot prove payload status is unchanged.
fingerprint = fingerprint_library(lmc)
(tmp_path/'payload.pcb').write_bytes(b'native edit without LMC change')
assert fingerprint_library(lmc) == fingerprint
class PendingBridge(FakeBridge):
def query(self, *args, **kwargs):
self.requests.append(args[1])
return BridgeResult('PENDING', 'fake')
bridge = PendingBridge()
records = BatchStatusSession(bridge).scan(['A'], lmc, checkpoint)
assert [record.status for record in records] == ['PENDING']
assert bridge.requests == ['A']
assert len(checkpoint.read_text('utf-8').splitlines()) == 1
def test_timeout_isolated_and_later_item_continues(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
@@ -180,7 +199,7 @@ def test_retry_rechecks_failed_scan_without_library_changes(tmp_path):
first = BatchStatusSession(FakeBridge(timeout_name='A')).scan(['A', 'B'], lmc, checkpoint)
assert first[0].status == 'TIMEOUT'
bridge = FakeBridge()
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint)
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint, resume=True)
assert bridge.requests == ['A']
assert second[0].status == 'READY'
+1 -1
View File
@@ -82,5 +82,5 @@ def test_fingerprint_change_does_not_reuse_checkpoint(tmp_path):
from cbb_refresh_verify.status_bridge import BridgeResult
return BridgeResult("PENDING", "fake")
bridge = Bridge()
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint)
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint, resume=True)
assert bridge.requests == ["A"]
+1 -1
View File
@@ -291,7 +291,7 @@ def test_status_cache_does_not_reuse_a_different_block_type(tmp_path):
return BridgeResult('READY', 'test')
session = BatchStatusSession(Bridge())
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='RULP')
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other')
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other', resume=True)
assert calls == ['RULP', 'Other']
+20 -1
View File
@@ -103,7 +103,9 @@ def test_real_management_worker_parent_loss_waits_for_native_boundary(tmp_path):
while not cancel.exists() and time.monotonic()<deadline:
time.sleep(.02)
assert cancel.exists() and worker.poll() is None
assert worker.wait(5) == 2
# Either the normal failed result or orphan exit may win after return;
# both require the receipt to have been durably published already.
assert worker.wait(5) in (2, 75)
assert not continued.exists()
assert (tmp_path/'supervisor-lost.json').is_file()
assert json.loads((tmp_path/'result.json').read_text())['safe_to_continue'] is True
@@ -146,3 +148,20 @@ def test_remove_timeout_keeps_worker_observing_until_native_returns(tmp_path, mo
thread.join(3)
assert done.is_set()
assert json.loads((tmp_path/'result.json').read_text())['safe_to_continue'] is True
def test_terminal_management_state_cannot_precede_its_result_receipt(tmp_path, monkeypatch):
job = tmp_path/'request.json'
job.write_text(json.dumps(dict(operation='catalog', library=str(tmp_path/'lib.lmc'),
desktop='CbbManagement_expected', operation_id='terminal-order')))
monkeypatch.setattr(native, '_current_desktop', lambda: (None, 'wrong_desktop'))
from cbb_refresh_verify import session_record
observed = []
def terminal(job, phase, **kwargs):
if phase == 'FINISHED':
receipt = json.loads((tmp_path/'result.json').read_text('utf-8'))
assert receipt['safe_to_continue'] is True and receipt['success'] is False
observed.append(phase)
monkeypatch.setattr(session_record, 'update_worker_state', terminal)
assert native.management_worker_main(job) == 2
assert observed == ['FINISHED']
-18
View File
@@ -2,7 +2,6 @@ import pytest
from cbb_refresh_verify.pcb_bridge import (
PcbBridgeError,
execution_outcome,
require_document_identity,
wait_for_target_document,
)
@@ -74,23 +73,6 @@ def test_bridge_stops_if_pcb_exits_before_com_is_ready(tmp_path):
assert raised.value.error_code == 'PCB_EXITED_BEFORE_COM'
def test_fatal_dialog_overrides_successful_save_markers():
result = execution_outcome(
save_complete=True,
pcb_exited=True,
fatal_error='SAVE_REUSABLE_BLOCK_FAILED: Error saving the Reusable Block',
)
assert result['status'] == 'FAIL'
assert result['error_code'] == 'SAVE_REUSABLE_BLOCK_FAILED'
def test_success_requires_save_and_pcb_exit():
assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS'
assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL'
assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL'
def test_connected_com_without_document_remains_startup_and_checks_native_failure(tmp_path):
errors = iter(('', 'ICDB_REPAIR_REQUIRED: original lost session'))
events = []
+1
View File
@@ -150,6 +150,7 @@ def test_released_batch_can_resume_only_its_unexecuted_items(qtbot, tmp_path, mo
window.release_dialog.close()
qtbot.waitUntil(lambda: not window.busy)
assert window.summary.isVisible()
action = window._resume_batch_action
assert action.isEnabled()
calls = []
monkeypatch.setattr(window, '_run', lambda names, **kw: calls.append((names, kw)))
@@ -0,0 +1,122 @@
from contextlib import contextmanager
import json
from pathlib import Path
from threading import Event
import pytest
from cbb_refresh_verify import desktop_worker as desktop, session_record as sessions
@pytest.mark.parametrize('asynchronous,expected', [(False, 'POSTCALL'), (True, 'NATIVE_CALL')])
@pytest.mark.parametrize('phase', ['NATIVE_CALL', 'CLOSING'])
def test_dispatch_records_pending_before_call_and_waits_for_async_ack(tmp_path, asynchronous, expected, phase):
job = dict(operation_id='dispatch-test', session_record_path=str(tmp_path/'session.json'))
def native_call():
value = sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)
assert value['phase'] == phase
assert desktop._native_phases[job['operation_id']] == phase
return 'native-result'
assert sessions.dispatch_native(job, native_call, phase=phase, asynchronous=asynchronous, required=True) == 'native-result'
assert sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)['phase'] == (
phase if asynchronous else expected)
def test_dispatch_veto_is_not_swallowed_by_optional_journal_mode(tmp_path, monkeypatch):
job = dict(operation_id='veto-test', session_record_path=str(tmp_path/'session.json'))
lost = Event()
monkeypatch.setattr(desktop, '_supervisor_lost', lost)
sessions.update_worker_state(job, 'PRECALL')
lost.set()
with pytest.raises(RuntimeError, match='WORKER_CANCELLED'):
sessions.dispatch_native(job, lambda: pytest.fail('native call after supervisor loss'), required=False)
assert sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)['phase'] == 'PRECALL'
with pytest.raises(RuntimeError, match='WORKER_STATE_UNCONFIRMED'):
sessions.update_worker_state(job, 'NATIVE_CALL', continuation=True)
def test_dispatch_refuses_new_call_if_required_journal_cannot_be_written(tmp_path, monkeypatch):
job = dict(operation_id='disk-test', session_record_path=str(tmp_path/'session.json'))
def unavailable(*args, **kwargs):
raise OSError('disk unavailable')
monkeypatch.setattr(sessions, 'write_session_record', unavailable)
with pytest.raises(OSError, match='disk unavailable'):
sessions.dispatch_native(job, lambda: pytest.fail('unrecorded dispatch'), required=True)
def test_failed_native_return_stays_unconfirmed(tmp_path):
job = dict(operation_id='unknown-test', session_record_path=str(tmp_path/'session.json'))
def interrupted():
raise TimeoutError('COM transport result unknown')
with pytest.raises(TimeoutError):
sessions.dispatch_native(job, interrupted)
assert sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)['phase'] == 'UNCONFIRMED'
def test_whole_library_release_names_every_reconciled_retained_block(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock as locks
monkeypatch.setattr(sessions, '_retained_libraries', {})
monkeypatch.setattr(sessions, '_retained_results', {})
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
for block in ('BlockA', 'BlockB'):
path = tmp_path/block/'session.json'; path.parent.mkdir()
op = 'operation-'+block
sessions.write_session_record(path, dict(operation_id=op, library=str(library), block=block, processes=[]))
key = str(path.absolute()).casefold()
sessions._retained_libraries[key] = {sessions._library_key(library)}
sessions._retained_results[key] = dict(block=block, library=str(library), operation_id=op)
locks._persist_blocker(library, lease_id='b'*32, block_name='BlockB')
@contextmanager
def proof(*args, **kwargs):
yield dict(native_owners=[], addresses=[], exclusive_files=[str(library)])
monkeypatch.setattr(locks, '_prove_library_released', proof)
result = locks.release_retained_library(library, tmp_path/'proof', block_name='BlockA')
assert result['reconciled_blocks'] == ['BlockA', 'BlockB']
assert {r['operation_id'] for r in result['reconciled_sessions']} == {'operation-BlockA', 'operation-BlockB'}
assert result['reconciled_foreign_blockers'] == ['BlockB']
assert sessions.library_available(library)
for block in ('BlockA', 'BlockB'):
receipt = json.loads(next((tmp_path/block).glob('observation-release-*.json')).read_text('utf-8'))
assert receipt['release_proof']['reconciled_blocks'] == ['BlockA', 'BlockB']
def test_release_snapshot_cannot_ack_a_replaced_operation(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'
key = str(tmp_path/'session.json')
aliases = {sessions._library_key(library)}
monkeypatch.setattr(sessions, '_retained_libraries', {key: aliases})
monkeypatch.setattr(sessions, '_retained_results', {key: dict(block='A', operation_id='before')})
snapshot = sessions.retained_session_snapshot(library)
sessions._retained_results[key]['operation_id'] = 'after'
sessions.acknowledge_library_release(dict(status='RELEASE_CONFIRMED', library=str(library)), snapshot)
assert not sessions.library_available(library)
assert sessions.reconciled_retained_sessions(snapshot) == []
def test_parent_loss_after_remove_started_still_records_and_waits(tmp_path, monkeypatch):
import os
from types import SimpleNamespace
from cbb_refresh_verify import native_management as native
lost = Event()
monkeypatch.setattr(desktop, '_supervisor_lost', lost)
job = dict(operation='remove', library=str(tmp_path/'lib.lmc'), desktop='CbbManagement_test',
mentor_home=str(tmp_path), name='A', partition='Logical-Physical', timeout_seconds=1,
supervisor_pid=os.getpid(), operation_id='accepted-remove', session_record_path=str(tmp_path/'session.json'))
request = tmp_path/'request.json'; request.write_text(json.dumps(job))
monkeypatch.setattr(native, '_current_desktop', lambda: (None, job['desktop']))
monkeypatch.setattr(native.NativeManagementAdapter, 'capabilities',
lambda _: {'remove': SimpleNamespace(supported=True)})
monkeypatch.setattr(sessions, 'process_identity', lambda pid: dict(pid=pid, created_handle='native',
image='CleanWGLib.exe', owner_sid='S-1-test', session_id=1))
waited = []
def wait(timeout):
state = sessions.read_session_record(tmp_path/'worker-state.json', evidence_root=tmp_path)
assert state['phase'] == 'NATIVE_CALL' and state['processes'][0]['pid'] == 123456
waited.append(True)
return 0
def launch(*args, **kwargs):
lost.set()
return SimpleNamespace(pid=123456, wait=wait)
monkeypatch.setattr(native.subprocess, 'Popen', launch)
native.management_worker_main(request)
assert waited == [True], 'loss during accepted launch abandoned the native owner'
+158
View File
@@ -0,0 +1,158 @@
from pathlib import Path
from threading import Event
from cbb_refresh_verify import session_record as sessions
def retain(monkeypatch, library):
key = 'controlled-session'
monkeypatch.setattr(sessions, '_retained_libraries', {key: {sessions._library_key(library)}})
monkeypatch.setattr(sessions, '_retained_results', {key: dict(block='BlockedCBB', operation_id='test',
library=str(library), status='UNCONFIRMED', detail='Close result unknown')})
def test_cached_wait_reason_names_retained_block_without_file_io(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'
retain(monkeypatch, library)
monkeypatch.setattr(Path, 'resolve', lambda *a, **kw: (_ for _ in ()).throw(AssertionError('queue filesystem I/O')))
detail = sessions.library_wait_reason(library)
assert 'BlockedCBB' in detail and '残留' in detail
assert sessions.library_wait_reason(tmp_path/'other.lmc') == ''
def test_queued_action_has_visible_release_entry_and_resumes_after_proof(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.verify_runner import VerifyResult
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
library = window.mentor_lmc_path
retain(monkeypatch, library)
finished = Event()
window._start(lambda: VerifyResult('PASS'), lambda _: finished.set())
qtbot.waitUntil(lambda: 'BlockedCBB' in window.status_label.text())
assert window.queue_release_button.isVisible() and window.queue_release_button.isEnabled()
opened = []
monkeypatch.setattr(window, 'check_library_release', lambda **kwargs: opened.append(kwargs))
window.queue_release_button.click()
assert opened == [{'queued': True}]
sessions._retained_libraries.clear()
window.native_queue.wake()
qtbot.waitUntil(finished.is_set)
qtbot.waitUntil(lambda: not window.busy)
assert not window.queue_release_button.isVisible()
def test_release_entry_does_not_clear_the_busy_state_of_a_waiting_ticket(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify import library_lock
window = load_window(qtbot, tmp_path, monkeypatch)
library = window.mentor_lmc_path
retain(monkeypatch, library)
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda _: dict(library=str(library), sessions=[]))
window.busy = True
window._queue_wait_library = str(library)
window.check_library_release(queued=True)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
window.release_dialog.close()
qtbot.waitUntil(lambda: not window._queue_release_mode)
assert window.busy
window.busy = False
def test_release_mapping_cleanup_finishes_before_waiting_ticket_resumes(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify import library_lock
window = load_window(qtbot, tmp_path, monkeypatch)
cleaned, finished = Event(), Event()
library = window.mentor_lmc_path
retain(monkeypatch, library)
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda _: dict(library=str(library), sessions=[]))
def backend_release(*a, **kw):
sessions._retained_libraries.clear()
return dict(status='RELEASE_CONFIRMED', sessions=[], proof=dict(status='RELEASE_CONFIRMED',
library=str(library), evidence_path='controlled-proof.json'))
monkeypatch.setattr(library_lock, 'release_residual_sessions', backend_release)
def finalize(*a, **kw):
assert window.native_queue.active, 'proof cleanup must complete inside serialized release'
cleaned.set()
monkeypatch.setattr('cbb_refresh_verify.network_path.release_retained_path_leases', finalize)
def action():
assert cleaned.is_set(), 'new native operation began before old mapping release completed'
finished.set()
window._start(action, lambda _: None)
qtbot.waitUntil(lambda: window._queue_wait_library is not None)
window.check_library_release(queued=True)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
window.release_dialog.confirm_button.click()
qtbot.waitUntil(finished.is_set)
qtbot.waitUntil(lambda: not window.release_dialog.busy)
qtbot.waitUntil(lambda: not window.busy)
window.release_dialog.close()
def test_wait_reason_updates_when_active_task_becomes_a_retained_session(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
window = load_window(qtbot, tmp_path, monkeypatch)
library = window.mentor_lmc_path
retain(monkeypatch, library)
sessions._retained_libraries.clear()
active = Event()
release = Event()
from threading import Thread
first = Thread(target=lambda: window.native_queue.run(lambda: (active.set(), release.wait(5))))
first.start()
qtbot.waitUntil(active.is_set)
try:
window._start(lambda: None, lambda _: None)
qtbot.waitUntil(lambda: '已排队' in window.status_label.text())
assert window._queue_wait_library is None
sessions._retained_libraries['controlled-session'] = {sessions._library_key(library)}
release.set(); first.join(3)
qtbot.waitUntil(lambda: 'BlockedCBB' in window.status_label.text())
assert not window.queue_release_button.isHidden()
finally:
release.set(); first.join(3)
sessions._retained_libraries.clear(); window.native_queue.wake()
qtbot.waitUntil(lambda: not window.busy)
def test_management_wait_shows_same_block_and_emits_release_target(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
from cbb_refresh_verify.management import ManagementRequest
from cbb_refresh_verify.operation_queue import NativeQueue
from PySide6.QtWidgets import QMessageBox
library = tmp_path/'lib.lmc'
retain(monkeypatch, library)
monkeypatch.setattr(QMessageBox, 'question', lambda *a, **kw: QMessageBox.Yes)
dialog = ManagementDialog([ManagementRequest('remove', library, 'A')], runner=lambda *a, **kw: [])
dialog.native_queue = NativeQueue()
qtbot.addWidget(dialog); dialog.show()
targets = []
dialog.release_requested.connect(targets.append)
dialog.execute_button.click()
qtbot.waitUntil(lambda: 'BlockedCBB' in dialog.status_label.text())
assert dialog.release_wait_button.isVisible()
dialog.release_wait_button.click()
assert targets == [library]
dialog.stop.set()
qtbot.waitUntil(lambda: not dialog.busy)
def test_close_waits_for_independent_release_worker(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.ui.workers import ServiceWorker
window = load_window(qtbot, tmp_path, monkeypatch)
window.show()
started, release = Event(), Event()
worker = ServiceWorker(lambda: (started.set(), release.wait(5)))
window.lifecycle_pool.start(worker)
qtbot.waitUntil(started.is_set)
try:
window.close()
qtbot.wait(40)
assert window.isVisible(), 'window closed while independent release still owned callbacks'
finally:
release.set()
qtbot.waitUntil(lambda: not window.isVisible())
+168
View File
@@ -0,0 +1,168 @@
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from PySide6.QtCore import QCoreApplication, QEvent
from PySide6.QtWidgets import QMessageBox
from shiboken6 import isValid
from cbb_refresh_verify.verify_runner import VerifyResult
def flush_deletes():
QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete)
def test_repeated_batch_results_retire_previous_dialog(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window._batch_done(([VerifyResult('FAIL')], tmp_path/'report.log'))
previous = window.summary
window._batch_done(([VerifyResult('PASS')], tmp_path/'report2.log'))
flush_deletes()
assert not isValid(previous)
assert len(window.findChildren(QMessageBox)) == 1
current = window.summary
current.close()
flush_deletes()
assert not isValid(current)
window._update() # No retained reference to deleted result actions.
def test_repeated_icdb_results_preserve_latest_recovery_task(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from test_reimport_recovery import failed_repair
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: failed_repair(tmp_path/'result.json', safe=True))
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
first_task, previous = window.icdb_task, window.icdb_summary
window._run(['Gamma'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
flush_deletes()
assert not isValid(previous)
assert not hasattr(first_task, 'summary')
assert len(window.findChildren(QMessageBox)) == 1
assert window.icdb_task.summary is window.icdb_summary
action = next(b for b in window.icdb_summary.buttons() if '副本' in b.text())
action.click()
assert [request.name for request in window.management_dialog.requests()] == ['Gamma']
window.management_dialog.reject()
window._invalidate_check_targets('test.lmc', ['Beta', 'Gamma'])
window._update()
def test_batch_replacement_preserves_independent_icdb_result(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('CHECKED'))
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
icdb_summary = window.icdb_summary
window._batch_done(([VerifyResult('PASS')], tmp_path/'first.log'))
old_batch = window.summary
window._batch_done(([VerifyResult('PASS')], tmp_path/'second.log'))
flush_deletes()
assert not isValid(old_batch)
assert isValid(icdb_summary) and icdb_summary.isVisible()
assert window.icdb_task.summary is icdb_summary
assert len(window.findChildren(QMessageBox)) == 2
def test_close_wait_notice_remains_visible_and_timer_stops_on_idle(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
entered, release = Event(), Event()
def close_lease():
entered.set()
release.wait(5)
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window.library_lease = SimpleNamespace(close=close_lease)
window.show()
try:
window.close()
qtbot.waitUntil(entered.is_set)
assert window.isVisible() and '等待' in window.windowTitle()
timer = window.close_wait_timer
assert timer.isActive() and timer.interval() == 120_000
timer.start(10)
qtbot.waitUntil(lambda: '仍在等待' in window.windowTitle())
assert '仍在等待' in window.status_label.text()
window.close()
assert window.isVisible()
finally:
release.set()
qtbot.waitUntil(lambda: not window.isVisible())
assert not timer.isActive()
@pytest.fixture
def batch_cli(tmp_path, monkeypatch):
import cbb_refresh_verify.application as application
import cbb_refresh_verify.library_reader as reader
import cbb_refresh_verify.network_path as network
import cbb_refresh_verify.verify_runner as runner
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
log, requested, retained = [], [], []
def record(message, *args, **kwargs):
log.append(message % args if args else message)
logger = SimpleNamespace(info=record, warning=record, exception=record, handlers=())
monkeypatch.setattr(application, 'configure', lambda *_: SimpleNamespace(root=tmp_path, logger=logger))
class Lease:
display_path = Path(r'\\server\share\library')
mentor_path = tmp_path/'lib.lmc'
drive, remote_root, created = 'Z:', r'\\server\share', True
def __enter__(self): return self
def __exit__(self, *_): pass
def retain_for_recovery(self): retained.append(self.drive)
monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease())
monkeypatch.setattr(network, 'select_library_file', lambda path: path)
monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult((
CbbRecord('Ready', 'LP', status='READY'), CbbRecord('One', 'LP'),
CbbRecord('Two', 'LP'), CbbRecord('Three', 'LP'))))
def run(requests, **kwargs):
assert kwargs.get('stop') is not None
requested.extend(request.block_name for request in requests)
return [VerifyResult('PASS') for _ in requests]
monkeypatch.setattr(runner, 'run_batch', run)
monkeypatch.setattr(runner, 'write_batch_report', lambda *a: tmp_path/'batch.log')
return application, runner, log, requested, retained
@pytest.mark.parametrize('extra, expected, counts', [
([], ['One', 'Two', 'Three'], (3, 3, 0)),
(['--limit', '2'], ['One', 'Two'], (2, 3, 1)),
(['--block', 'Three', '--block', 'One', '--limit', '1'], ['Three'], (1, 2, 1)),
])
def test_batch_cli_limit_is_optional_and_reports_selection(batch_cli, extra, expected, counts):
app, _, log, requested, _ = batch_cli
assert app.main(['--batch-lmc', 'lib.lmc', *extra]) == 0
assert requested == expected
assert any(all(f'{key}={value}' in line for key, value in zip(
('selected', 'total', 'remaining'), counts)) for line in log)
@pytest.mark.parametrize('value', ['0', '-1', 'no'])
def test_batch_cli_rejects_nonpositive_limit(batch_cli, value):
app, _, _, requested, _ = batch_cli
with pytest.raises(SystemExit) as error:
app.main(['--batch-lmc', 'lib.lmc', '--limit', value])
assert error.value.code == 2 and not requested
@pytest.mark.parametrize('raised', [False, True])
def test_retained_mapping_logs_context_and_confirmed_release_guidance(batch_cli, monkeypatch, raised):
app, runner, log, _, retained = batch_cli
def run(_, **kwargs):
assert kwargs.get('stop') is not None
if raised: raise RuntimeError('native writer status unknown')
return [VerifyResult('FAIL', safe_to_continue=False)]
monkeypatch.setattr(runner, 'run_batch', run)
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One']) == (1 if raised else 2)
assert retained == ['Z:']
notice = next(line for line in log if 'batch_drive_retained' in line)
assert 'Z:' in notice and r'\\server\share' in notice
assert '释放残留会话' in notice and '确认' in notice
assert 'net use' not in notice.lower()
@@ -0,0 +1,40 @@
from cbb_refresh_verify import library_lock
from cbb_refresh_verify.ui.residual_release_dialog import ResidualReleaseDialog
def test_confirmed_scope_and_execution_divergence_are_visible(qtbot, tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'
rows = [dict(name='ExpeditionPCB.exe', pid=pid, project=name, detail='可正常关闭')
for pid, name in ((10, 'A'), (20, 'B'))]
monkeypatch.setattr(library_lock, 'inspect_residual_sessions',
lambda *_: dict(library=str(library), sessions=rows))
monkeypatch.setattr(library_lock, 'release_residual_sessions', lambda *a, **kw:
dict(status='PARTIAL', sessions=[
dict(rows[0], consent_allowed=True, release_status='RELEASED', detail='已退出'),
dict(rows[1], consent_allowed=True, release_status='WAITING', detail='原生操作进行中')]))
dialog = ResidualReleaseDialog(library, tmp_path/'evidence')
qtbot.addWidget(dialog)
qtbot.waitUntil(lambda: not dialog.busy)
dialog.confirm_button.click()
qtbot.waitUntil(lambda: not dialog.busy)
assert dialog.table.columnCount() == 8
assert dialog.table.item(0, 6).text() == dialog.table.item(1, 6).text() == '允许'
assert dialog.table.item(0, 7).text() == '已释放'
assert dialog.table.item(1, 7).text() == '未释放'
assert '原生操作进行中' in dialog.table.item(1, 3).text()
assert '确认允许 2' in dialog.message.text() and '未释放 1' in dialog.message.text()
def test_retiring_batch_summary_forgets_enabled_release_actions(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
from test_review345_ui_cli import flush_deletes
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window._batch_done(([VerifyResult('FAIL', safe_to_continue=False)], None))
assert window._residual_release_action is not None
window.summary.close(); flush_deletes()
window._update()
assert window._residual_release_action is None
window._resume_batch = dict(library=tmp_path/'lib.lmc', released=True)
window._release_dialog_finished()
+14
View File
@@ -87,6 +87,20 @@ def test_management_records_scoped_changes_without_hashing_unrelated_cbb(setup,
assert 'SymbolLibs/shared/icdb.dat' in report['modified']
assert 'ReusableBlocksLP/Block/Work/Block.prj' in report['modified']
assert result.change_report == report
assert report['rule_version'] == 1
assert report['scope'] == {'kind': 'library', 'block_name': 'Block',
'library_name': request.library.name}
from cbb_refresh_verify import scoped_manifest as manifests
assert report['excluded_categories'] == sorted(manifests._NONPRIMARY_DIRECTORIES)
assert report['excluded_suffixes'] == sorted(manifests._NONPRIMARY_SUFFIXES)
runtime = report['runtime_exclusions']
assert runtime['native_directory_names'] == ['dbcheck', 'dbrestore', 'log']
assert runtime['file_names'] == ['saddress.adr']
assert runtime['file_name_prefixes'] == ['~$']
assert runtime['relative_directories'] == ['projectbackup/backups']
assert runtime['directory_prefixes'] == ['work.before-restore-']
assert 'selected CBB Work/Cert root or its PCB child' in runtime['directory_name_positions']
assert 'SymbolLibs/<partition>/cdbsvr' in runtime['native_directory_positions']
def test_failed_mutation_still_records_changes_and_release_fact(setup):
@@ -29,3 +29,17 @@ def test_report_failure_is_visible_without_inventing_native_failure(qtbot, setup
assert '历史会话已释放' in dialog.output.toPlainText()
dialog._progress({'stage':'previous_release_check','block':request.name})
assert '正在复核历史占用' in dialog.status_label.text()
def test_recorded_counts_identify_compared_engineering_file_scope(qtbot, setup):
from cbb_refresh_verify.management import ManagementResult
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
request, _, _ = setup
dialog = ManagementDialog([request]); qtbot.addWidget(dialog)
result = ManagementResult(request.operation, request.library, request.name, request.partition,
None, False, 'complete', 'REMOVED', True, 'removed',
change_report={'status': 'RECORDED', 'added': ['a'], 'deleted': [], 'modified': ['b']})
dialog._result([result])
text = dialog.output.toPlainText()
assert '已比对的工程文件' in text
assert '新增 1' in text and '删除 0' in text and '修改 1' in text
+31 -6
View File
@@ -118,17 +118,42 @@ def test_corrupted_destination_bytes_are_rejected_and_evidence_is_preserved(tmp_
assert (destination/relative).exists()
def test_unlocked_primary_copy_reads_source_twice_and_target_once(tmp_path, monkeypatch):
from collections import Counter
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, 'A.prj', b'engineering' * 100000)
reads = Counter()
original_open = Path.open
def opened(path, mode='r', *args, **kwargs):
if mode == 'rb':
reads[path] += 1
return original_open(path, mode, *args, **kwargs)
monkeypatch.setattr(Path, 'open', opened)
hashes = Counter()
original_hash = recovery._hash
def hashed(path):
hashes[path] += 1
return original_hash(path)
monkeypatch.setattr(recovery, '_hash', hashed)
manifest = recovery._copy_verified(source, destination)
assert hashes[primary] == 1 # Only the final source rehash is a separate pass.
assert hashes[destination/'A.prj'] == 1
assert reads[primary] == 2 # Copy/hash stream, then final source content proof.
assert reads[destination/'A.prj'] == 1
assert manifest['files']['A.prj']['sha256'] == hashlib.sha256(primary.read_bytes()).hexdigest()
def test_source_byte_changes_with_preserved_metadata_are_rejected(tmp_path, monkeypatch):
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, 'A.prj')
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_change_source(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
metadata = primary.stat()
primary.write_bytes(b'X' * metadata.st_size)
os.utime(primary, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_change_source)
monkeypatch.setattr(shutil, 'copystat', copy_then_change_source)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert (destination/'A.prj').read_bytes() == b'engineering'
@@ -140,7 +165,7 @@ def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypat
put(source, 'A.prj')
runtime = put(source, 'logs/session.log')
destination = tmp_path/'destination'
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_mutate(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
if Path(src).name == 'A.prj':
@@ -151,7 +176,7 @@ def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypat
else:
put(source, 'logs/added.log')
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_mutate)
monkeypatch.setattr(shutil, 'copystat', copy_then_mutate)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert destination.exists()
@@ -277,7 +302,7 @@ def test_colliding_engineering_names_cannot_bypass_primary_copy_byte_checks(tmp_
scope = ManifestScope.library(block, 'target.lmc')
source, destination = tmp_path/'source', tmp_path/'destination'
put(source, relative)
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_corrupt(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
corrupt = Path(src) if side == 'source' else Path(dst)
@@ -285,7 +310,7 @@ def test_colliding_engineering_names_cannot_bypass_primary_copy_byte_checks(tmp_
corrupt.write_bytes(b'X' * metadata.st_size)
os.utime(corrupt, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_corrupt)
monkeypatch.setattr(shutil, 'copystat', copy_then_corrupt)
with pytest.raises(OSError):
recovery._copy_verified(source, destination, scope=scope)
assert (destination/relative).exists()