Compare commits

..
Author SHA1 Message Date
阿白叔 a7df105616 fix: recreate batch resume action after release summary retirement 2026-11-09 14:34:28 +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
阿白叔 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
阿白叔 14c9a74bbf fix: show confirmed scope beside actual residual release results 2026-11-09 13:45:53 +08:00
阿白叔 651b539d0e fix: isolate unreadable residual sessions and bound release evidence 2026-11-09 10:39:16 +08:00
阿白叔 35daa77118 Merge branch 'codex/review-ui-integration' into codex/review-residual-release 2026-11-09 10:26:20 +08:00
阿白叔 e73f9c6edc Merge branch 'codex/review-native-backend' into codex/review-ui-integration 2026-11-09 10:26:13 +08:00
阿白叔 b7baa24b5e fix: identify foreign CBB checkpoints in release evidence 2026-11-09 10:26:09 +08:00
阿白叔 5eb4b2d7ed fix: persist release outcomes and guard active native backup sessions 2026-11-06 12:08:54 +08:00
阿白叔 d40192ee58 Merge branch 'codex/review-ui-integration' into codex/review-residual-release 2026-11-06 11:41:05 +08:00
阿白叔 3c1998f2ef Merge branch 'codex/review-native-backend' into codex/review-ui-integration 2026-11-06 11:41:03 +08:00
阿白叔 807aa26baf test: guard actual reads of unrelated CBB content 2026-11-06 11:41:00 +08:00
阿白叔 71029b19a2 Merge branch 'codex/review-ui-integration' into codex/review-residual-release 2026-11-06 11:36:21 +08:00
阿白叔 8c2c60fab1 fix: distinguish native outcomes from report and item recovery status 2026-11-06 11:36:19 +08:00
阿白叔 5b22787418 Merge branch 'codex/review-native-backend' into codex/review-ui-integration 2026-11-06 11:34:27 +08:00
阿白叔 679f33b8cc fix: keep prelaunch release-probe failures from stopping independent work 2026-11-06 11:34:25 +08:00
阿白叔 746e5b5145 Merge branch 'codex/review-native-backend' into codex/review-ui-integration 2026-11-06 11:21:21 +08:00
阿白叔 8eefecd9f0 fix: reconcile historical leases and record scoped native changes 2026-11-06 11:21:15 +08:00
阿白叔 d8156c57f0 Merge remote-tracking branch 'origin/main' into codex/review-native-backend 2026-11-06 11:14:58 +08:00
abaishu0730 959399b974 Merge pull request '审查拆分 1/4:只读占用探测与可取消任务队列' (#9) from codex/review-infrastructure into main 2026-11-06 10:25:10 +08:00
abaishu0730 46dae81190 Merge pull request 'docs: CBB Verify 全量扫描与阻塞分析(关联 #4)' (#5) from docs/scan-20261104-blockers into main 2026-11-06 10:20:23 +08:00
阿白叔 dc536da555 docs: record published review chain and completed verification 2026-11-05 23:33:46 +08:00
阿白叔 173dee1980 feat: add confirmed client release with durable consent and server protection 2026-11-05 23:31:36 +08:00
阿白叔 282be7be7f feat: integrate independent background checks and native management UI 2026-11-05 23:25:25 +08:00
阿白叔 da67de026f feat: integrate native diagnostics and coordinated CBB transactions 2026-11-05 23:18:00 +08:00
阿白叔 9e230e1a46 feat: add bounded read-only owner probes and cooperative native queue 2026-11-05 23:04:35 +08:00
abaishu0730 3dbfca0f44 docs: record full project scan and blocker analysis (#4) 2026-11-04 15:20:37 +08:00
31 changed files with 969 additions and 125 deletions

No files matched your search

@@ -0,0 +1,7 @@
# PR #10 comment 309
Release proof now records the requested CBB, effective BLOCK/LIBRARY proof scope, identities/statuses of archived checkpoints and retained owners, and `reconciled_foreign_blockers`. For example, a BlockA operation which safely reconciles BlockB's historical checkpoint explicitly lists BlockB and the full-library proof. `data_recovery_confirmed` remains false. No extra gate, automatic backup or native action was added.
Three regressions first failed on missing evidence fields. After the fix, 94 backend/lease/release regressions passed; compileall and git diff --check passed. The tests use real temporary file/lease handles with the process-query boundary replaced; no production library was opened. Full regression is run again at the integrated chain tip. Real Mentor/shared-network acceptance and a rebuilt package remain outstanding.
Review: https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/10#issuecomment-309
@@ -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,21 @@
# PR #12 comment 313
## Behavior
Window inspection takes a Windows thread snapshot for the requested processes, finds the desktops assigned to those threads, and opens only those desktops. Failures are recorded per affected PID outside the real window list. Unrelated inaccessible desktops no longer disable healthy rows. Preview, cooperative close, forced close, native Cancel and save-prompt responses all use the same per-PID incomplete-read fact during their fresh action-time observation.
Unknown or active native writes still prohibit forced termination. The review's suggested blanket force override for unreadable windows is not implemented: exact identity and private-desktop ownership do not establish that Save/Repair has returned. A failed read names that session and can be retried, while other sessions remain actionable.
Disk evidence retains window identity and a UTF-8 output excerpt of at most 4,096 bytes, original output length and SHA-256. It omits child-control trees and duplicated native-activity output. The complete preview remains in memory for the existing details action.
Native Cancel carries the preview's `block_names` and checks the same Work + SymbolLibs scope before the exact-process/control checks. It no longer silently widens a scoped preview to the full library.
## Verification
The initial five regressions failed against the old implementation. After the fix, 116 residual/backend/UI/background-queue regressions passed; compileall and git diff --check passed. This includes a real controlled Windows window on a private CbbManagement desktop, read from another process, with clean fixture exit and no Mentor/native database actions.
The real fixture caught a platform limitation missed by API doubles: EnumThreadWindows silently omits windows on another desktop. The final implementation maps threads to desktop names and uses OpenDesktop/EnumDesktopWindows for only those mapped desktops. GetThreadDesktop's borrowed handle is never closed; owned OpenDesktop handles and the thread snapshot are closed.
Independent review and the full integrated-chain run are recorded at the final PR #13 tip. Older deep-review comments #297-#300 remain outside this explicitly selected scope. No candidate was rebuilt; real Mentor, Windows 10 and shared/network release scenarios remain unverified.
Review: https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/12#issuecomment-313
@@ -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.
@@ -0,0 +1,25 @@
# Latest reviews for PR #10/#11/#12
Scope: user selected only the 2026-11-09 comments #309/#310/#313. Earlier deep-review backlog stays out of scope. Preserve ICDB automatic Repair OFF, serial writes, current icon and independent-library admission. No merge to main, issue closure or release.
## PR #10
- [ ] Reproduce BlockA releasing historical BlockB checkpoints and retained owners without naming BlockB in proof.
- [ ] Record requested block, actual proof scope, checkpoint identities and foreign names in existing release proof. Preserve original checkpoint bytes and data_recovery_confirmed=False; no new blocking gate.
- [ ] Run backend/lease regressions, compile/diff checks, commit on codex/review-native-backend.
## PR #11/#12
- [ ] Forward-merge backend into UI, then UI into residual branch; no history rewriting.
- [ ] Test one unreadable process/thread not affecting another, without fabricated modal windows; cover preview and action-time rechecks.
- [ ] Enumerate only target-process threads/windows, store incomplete-read metadata per PID. Keep unknown/active writers protected rather than adding a blind force override.
- [ ] Persist window identities and at most a 4 KiB output excerpt, preserve full preview in memory, stop duplicating activity output.
- [ ] Carry exact preview block scope into native Cancel and recheck identity/scope before clicking.
- [ ] Run residual/UI regressions, compile/diff checks, commit on residual branch.
## Chain tip
- [ ] Merge residual fixes into PR #13, preserving ca39fb3 and icon.
- [ ] Address #11's line-ending note once at the tip: application.py to LF; pin it and main_window.py in EditorConfig. Preserve all other file endings and the global * -text rule.
- [ ] Independent review, integrated full suite, compile/diff checks, validation records and fast-forward pushes to existing PR branches.
- [ ] Update PR descriptions with precise results and no new package/native acceptance. Leave #3 as historical umbrella, without merging or closing it.
@@ -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
@@ -46,6 +46,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)
@@ -57,6 +67,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)
@@ -110,6 +121,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,
@@ -117,13 +133,21 @@ 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:
results = run_batch(requests)
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``.
"""
+13
View File
@@ -559,6 +559,16 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
records = [checkpoint_record(path) for path, data in before.items() if data is not None]
scoped = (block_name if block_name and all(record and record.get('block_name') == block_name
for record in records) and (owner is None or owner.get('block_name') == block_name) else None)
reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None,
**{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}}
for path, data in before.items() if data is not None
for metadata in (checkpoint_record(path),)]
if owner:
reconciled.append({'kind': 'retained_owner', 'path': str(lease.path),
'block_name': owner.get('block_name'), 'lease_id': owner['lease_id'],
'status': 'OWNER_RELEASE_UNCONFIRMED'})
foreign = sorted({item['block_name'] for item in reconciled
if block_name and item.get('block_name') and item['block_name'] != block_name})
proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True) if unknown else
_prove_library_released(library, block_name=scoped)
if scoped else _prove_library_released(library))
@@ -570,6 +580,9 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
root = evidence/('release-' + uuid4().hex)
root.mkdir(parents=True, exist_ok=False)
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,
'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)
@@ -212,6 +212,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:
-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 退出均已确认。'}
+173 -48
View File
@@ -1,6 +1,7 @@
"""Preview and cooperatively close the exact native sessions a user confirms."""
from contextlib import contextmanager
import json
import hashlib
import os
from pathlib import Path
import re
@@ -39,8 +40,8 @@ def force_block_reason(row):
return ''
def native_activity(name, windows):
if any(w['class'] == 'UNCONFIRMED' for w in windows):
def native_activity(name, windows, *, incomplete=None):
if incomplete or any(w['class'] == 'UNCONFIRMED' for w in windows):
return {'status': 'UNCONFIRMED', 'detail': '原生窗口读取不完整'}
if any((name.casefold() == 'icdbprojectbackup.exe' and not w['enabled'])
or any(c['class'].casefold() == 'msctls_progress32' for c in w['children']) for w in windows):
@@ -112,16 +113,85 @@ def _force_ownership(handle, pid):
and session == win32ts.ProcessIdToSessionId(os.getpid())}
class _WindowSnapshot(dict):
def __init__(self, pids):
super().__init__((pid, []) for pid in pids)
self.incomplete = {}
def _process_threads(pids):
import ctypes
from ctypes import wintypes
class ThreadEntry(ctypes.Structure):
_fields_ = [('size', wintypes.DWORD), ('usage', wintypes.DWORD), ('tid', wintypes.DWORD),
('pid', wintypes.DWORD), ('base', wintypes.LONG), ('delta', wintypes.LONG),
('flags', wintypes.DWORD)]
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
for name in ('Thread32First', 'Thread32Next'):
function = getattr(kernel, name)
function.argtypes = [wintypes.HANDLE, ctypes.POINTER(ThreadEntry)]
function.restype = wintypes.BOOL
snapshot = kernel.CreateToolhelp32Snapshot(4, 0) # TH32CS_SNAPTHREAD
if snapshot == ctypes.c_void_p(-1).value:
raise ctypes.WinError(ctypes.get_last_error())
result = {pid: [] for pid in pids}
try:
entry = ThreadEntry(); entry.size = ctypes.sizeof(entry)
more = kernel.Thread32First(snapshot, ctypes.byref(entry))
while more:
if entry.pid in result:
result[entry.pid].append(int(entry.tid))
entry.size = ctypes.sizeof(entry)
more = kernel.Thread32Next(snapshot, ctypes.byref(entry))
if ctypes.get_last_error() != 18: # ERROR_NO_MORE_FILES
raise ctypes.WinError(ctypes.get_last_error())
finally:
kernel.CloseHandle(snapshot)
return result
def _thread_desktop_name(tid):
import ctypes
from ctypes import wintypes
user = ctypes.WinDLL('user32', use_last_error=True)
user.GetThreadDesktop.argtypes = [wintypes.DWORD]
user.GetThreadDesktop.restype = wintypes.HANDLE
user.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID,
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
user.GetUserObjectInformationW.restype = wintypes.BOOL
ctypes.set_last_error(0)
desktop = user.GetThreadDesktop(tid)
if not desktop:
if error := ctypes.get_last_error():
raise ctypes.WinError(error)
return None # A non-GUI thread need not have an assigned desktop.
# GetThreadDesktop returns a borrowed handle; never CloseDesktop it.
name, needed = ctypes.create_unicode_buffer(512), wintypes.DWORD()
if not user.GetUserObjectInformationW(desktop, 2, name, ctypes.sizeof(name), ctypes.byref(needed)):
raise ctypes.WinError(ctypes.get_last_error())
return name.value
def _window_error(snapshot, pid):
return getattr(snapshot, 'incomplete', {}).get(pid)
def _process_windows(pids):
if not pids: return {}
result = _WindowSnapshot(pids)
if not pids: return result
import win32api, win32con, win32gui, win32process, win32service
from .native_repair_ui import _native_output
result = {pid: [] for pid in pids}
observed = set()
def capture(hwnd, _=None, *, desktop_name='Default'):
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
def capture(hwnd, _, *, pid, desktop_name):
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid:
raise ValueError('窗口所属进程已变化')
if hwnd in observed or not win32gui.IsWindowVisible(hwnd):
return
if desktop_name is None:
raise ValueError('窗口所属桌面无法读取')
observed.add(hwnd)
children, documents = [], []
def child(handle, _):
@@ -141,31 +211,46 @@ def _process_windows(pids):
if any(c['class'].casefold().startswith('richedit') for c in children):
window['output'] = _native_output([window])
result[pid].append(window)
win32api.SetLastError(0)
def incomplete():
for pid in result:
result[pid].append({'hwnd': 0, 'title': '窗口状态读取不完整', 'class': 'UNCONFIRMED',
'enabled': False, 'children': []})
try:
win32gui.EnumWindows(capture, None)
except Exception:
incomplete()
try:
desktops = win32service.GetProcessWindowStation().EnumDesktops()
except Exception:
incomplete()
threads = _process_threads(pids)
except Exception as error:
result.incomplete = {pid: str(error)[:500] for pid in pids}
return result
for name in desktops:
if name != 'Default' and not name.startswith(('CbbVerify_', 'CbbRepair_', 'CbbManagement_', 'CbbStatusRead_', 'CbbFlagRead_')):
continue
desktops = {}
for pid in pids:
if not threads.get(pid):
result.incomplete[pid] = '进程线程已退出或暂时无法读取'
for tid in threads.get(pid, ()):
try:
desktop = _thread_desktop_name(tid)
if desktop:
desktops.setdefault(desktop, set()).add(pid)
except Exception as error:
result.incomplete.setdefault(pid, str(error)[:500])
if not any(pid in members for members in desktops.values()):
result.incomplete.setdefault(pid, '窗口所属桌面暂时无法确认')
# EnumThreadWindows silently omits windows on other desktops. Enumerate
# only desktops actually assigned to the target processes' threads.
for name, members in desktops.items():
desktop = None
try:
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd), desktop_name=name)
except Exception:
incomplete()
win32api.SetLastError(0)
for hwnd in desktop.EnumDesktopWindows():
pid = None
try:
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
if pid in members:
capture(hwnd, None, pid=pid, desktop_name=name)
except Exception as error:
for affected in (members if pid is None else {pid} & members):
result.incomplete.setdefault(affected, str(error)[:500])
except Exception as error:
for pid in members:
result.incomplete.setdefault(pid, str(error)[:500])
finally:
if desktop is not None: desktop.CloseDesktop()
if desktop is not None:
desktop.CloseDesktop()
return result
@@ -181,8 +266,10 @@ def _project_name(row, library):
return '当前库关联会话'
def close_target(name, windows):
def close_target(name, windows, *, incomplete=None):
"""No save/restore approval and no close against an unknown modal/window."""
if incomplete:
return None, '该会话窗口读取不完整,请重新检查:'+str(incomplete)
main = [w for w in windows if w['class'].startswith('Afx:') and (
name.casefold() == 'icdbprojectbackup.exe' and w['title'].startswith('iCDB Project Backup')
or name.casefold() == 'librarymanager.exe' and w['title'].startswith('Library Manager')
@@ -212,7 +299,9 @@ def close_target(name, windows):
return window, ('将正常关闭工程;未保存时等待确认' if window.get('documents') else '可正常关闭')
def _save_question(windows):
def _save_question(windows, *, incomplete=None):
if incomplete:
return None
for window in windows:
text = '\n'.join(c['text'] for c in window['children'] if c['class'] == 'Static')
buttons = {c['id']: c for c in window['children'] if c['class'] == 'Button' and c['enabled']}
@@ -224,8 +313,9 @@ def _save_question(windows):
return None
def _cancel_question(name, windows):
if name.casefold() != 'icdbprojectbackup.exe' or native_activity(name, windows)['status'] != 'ACTIVE':
def _cancel_question(name, windows, *, incomplete=None):
if (name.casefold() != 'icdbprojectbackup.exe'
or native_activity(name, windows, incomplete=incomplete)['status'] != 'ACTIVE'):
return None
candidates = []
for window in windows:
@@ -268,20 +358,23 @@ def inspect_residual_sessions(library, *, block_names=()):
sessions = []
for row in candidates:
item = dict(row)
item['block_names'] = list(blocks)
error = _window_error(windows, row['pid'])
item.update(windows_incomplete=bool(error), window_read_error=error)
try:
item.update(_process_identity(row))
target, detail = close_target(row['name'], windows.get(row['pid'], [])) if row['scope_confirmed'] else (
target, detail = close_target(row['name'], windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else (
None, '归属未确认,请在原生窗口确认工程并关闭后重新检查')
item.update(can_close=target is not None, detail=detail)
except Exception as error:
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
except Exception as identity_error:
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{identity_error}')
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
item['prompt'] = _save_question(windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else None
observed = windows.get(row['pid'], [])
item['windows'] = observed
item['desktops'] = sorted({w.get('desktop', '') for w in observed if w.get('desktop')})
item['native_activity'] = native_activity(row['name'], observed)
item['cancel_prompt'] = (_cancel_question(row['name'], observed)
item['native_activity'] = native_activity(row['name'], observed, incomplete=error)
item['cancel_prompt'] = (_cancel_question(row['name'], observed, incomplete=error)
if row['scope_confirmed'] and item.get('force_user_confirmed') is True else None)
if any(name.startswith('Cbb') for name in item['desktops']) and not item['can_close']:
item['detail'] += ';窗口在后台,可查看原生提示并使用已提供的保存/取消操作'
@@ -314,7 +407,10 @@ def _request_close(row, *, stop=None):
identity = _handle_identity(handle)
if identity != {key: row.get(key) for key in ('created_handle', 'image')}:
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未关闭'}
windows = _process_windows({row['pid']}).get(row['pid'], [])
snapshot = _process_windows({row['pid']})
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
if error:
return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error}
if row['name'].casefold() == 'expeditionpcb.exe':
from .failed_session import _startup_snapshot, _cancel_target
for window in windows:
@@ -328,10 +424,13 @@ def _request_close(row, *, stop=None):
return {'release_status': 'RELEASED', 'detail': '已取消启动并退出'}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
windows = _process_windows({row['pid']}).get(row['pid'], [])
snapshot = _process_windows({row['pid']})
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
if error:
break
if close_target(row['name'], windows)[0] is not None: break
break
target, detail = close_target(row['name'], windows)
target, detail = close_target(row['name'], windows, incomplete=error)
if target is None: return {'release_status': 'WAITING', 'detail': detail}
if stop is not None and stop.is_set():
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
@@ -362,7 +461,9 @@ def _force_close(row, *, stop=None):
if (not ownership['force_user_confirmed'] or
any(ownership[k] != row.get(k) for k in ('owner_sid', 'session_id'))):
return {'release_status': 'IDENTITY_CHANGED', 'detail': '用户或 Windows 会话已变化,未结束'}
activity = native_activity(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
snapshot = _process_windows({row['pid']})
activity = native_activity(row['name'], snapshot.get(row['pid'], []),
incomplete=_window_error(snapshot, row['pid']))
if reason := force_block_reason({**row, 'native_activity': activity}):
return {'release_status': 'WAITING', 'detail': reason, 'native_activity': activity}
if stop is not None and stop.is_set():
@@ -392,7 +493,9 @@ def _request_native_cancel(row, *, stop=None):
owner = _force_ownership(handle, row['pid'])
if not owner['force_user_confirmed'] or any(owner[k] != row.get(k) for k in ('owner_sid', 'session_id')):
raise ValueError('取消目标用户/会话已变化')
prompt = _cancel_question(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
snapshot = _process_windows({row['pid']})
prompt = _cancel_question(row['name'], snapshot.get(row['pid'], []),
incomplete=_window_error(snapshot, row['pid']))
if not prompt or prompt != row.get('cancel_prompt'):
raise ValueError('原生取消按钮已变化,请重新检查')
button = prompt['button']
@@ -406,10 +509,29 @@ def _request_native_cancel(row, *, stop=None):
def request_native_cancel(row, library, evidence_dir, *, stop=None):
# Reuse serialized admission, consent and incremental evidence for cancellation.
plan = {'library': str(library), 'sessions': [row]}
plan = {'library': str(library), 'sessions': [row], 'block_names': row.get('block_names', [])}
return release_residual_sessions(plan, evidence_dir, stop=stop, cancel_native=True)
def _session_evidence(row):
"""Keep the full preview in memory, but bound repeatedly written Output."""
value = dict(row)
if 'native_activity' in value:
value['native_activity'] = {k: v for k, v in value['native_activity'].items() if k != 'output'}
if 'windows' in value:
value['windows'] = []
for window in row['windows']:
saved = {k: window[k] for k in ('hwnd', 'title', 'class', 'desktop', 'enabled') if k in window}
output = window.get('output')
if isinstance(output, str):
data = output.encode('utf-8')
saved.update(output_excerpt=data[:4096].decode('utf-8', errors='ignore'),
output_bytes=len(data), output_sha256=hashlib.sha256(data).hexdigest(),
output_truncated=len(data) > 4096)
value['windows'].append(saved)
return value
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
library = Path(plan['library']).resolve()
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
@@ -425,7 +547,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
from .management import _write_json
try:
result['report_saved'] = True
_write_json(root/'result.json', result)
_write_json(root/'result.json', {**result, 'sessions': [_session_evidence(row) for row in result['sessions']]})
return True
except OSError as error:
result.update(status='PARTIAL', report_saved=False, evidence_error=str(error))
@@ -436,7 +558,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
consent_path = root/'consent.json'
consent = {'version': 1, 'mode': 'cancel_native' if cancel_native else 'force_document_clients', 'library': str(library),
'time_ns': time.time_ns(), 'sessions': [
{**row, 'force_allowed': not force_block_reason(row),
{**_session_evidence(row), 'force_allowed': not force_block_reason(row),
'cancel_allowed': bool(row.get('cancel_prompt')) and row.get('scope_confirmed') is True,
'force_block_reason': force_block_reason(row)} for row in plan['sessions']]}
try:
@@ -490,10 +612,12 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
row.update(release_status='RELEASED', detail='已退出')
elif row['release_status'] == 'WAITING':
windows = remaining_windows.get(row['pid'], [])
row.update(prompt=_save_question(windows), windows=windows,
cancel_prompt=(_cancel_question(row['name'], windows)
error = _window_error(remaining_windows, row['pid'])
row.update(prompt=_save_question(windows, incomplete=error), windows=windows,
windows_incomplete=bool(error), window_read_error=error,
cancel_prompt=(_cancel_question(row['name'], windows, incomplete=error)
if row.get('force_user_confirmed') is True else None),
native_activity=native_activity(row['name'], windows))
native_activity=native_activity(row['name'], windows, incomplete=error))
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
result['proof'] = _finish_library_release(library, root/'library-proof')
proof = result['proof']
@@ -554,7 +678,8 @@ def _answer_save_question(row, choice):
with _process_handle(row['pid']) as handle:
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
raise ValueError('进程已变化,请重新检查')
prompt = _save_question(_process_windows({row['pid']}).get(row['pid'], []))
snapshot = _process_windows({row['pid']})
prompt = _save_question(snapshot.get(row['pid'], []), incomplete=_window_error(snapshot, row['pid']))
if not prompt or prompt != row.get('prompt'):
raise ValueError('原生提示已变化,请重新检查')
button = prompt['buttons'][choice]
+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):
+46 -9
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 = {}
@@ -133,6 +132,10 @@ class MainWindow(QWidget):
self._mapping_auto_idle = False
self._mapping_finish_waiters = []
self._closing = self._close_ready = 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
@@ -463,6 +466,12 @@ class MainWindow(QWidget):
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()
@@ -584,7 +593,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)
@@ -760,7 +768,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
@@ -860,7 +868,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)
@@ -1398,6 +1406,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 '未写入'
@@ -1459,7 +1491,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)
@@ -1529,10 +1561,6 @@ class MainWindow(QWidget):
self.version_dialog.reject()
self.version_dialog = 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))
@@ -1554,6 +1582,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()
@@ -1566,6 +1597,11 @@ 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'):
@@ -1580,5 +1616,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()
@@ -209,8 +209,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', '变更清单未确认')
@@ -30,8 +30,8 @@ class ResidualReleaseDialog(QDialog):
self.message = QLabel('正在检查当前库关联的会话…')
self.message.setWordWrap(True)
layout.addWidget(self.message)
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)
@@ -88,9 +88,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)
@@ -226,6 +231,9 @@ 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)
return self.native_queue.run(action, stop=self.stop) if self.native_queue is not None else action()
+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
@@ -283,7 +283,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']
-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
@@ -149,6 +149,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)))
+4 -3
View File
@@ -329,11 +329,12 @@ def test_partial_desktop_enumeration_never_offers_normal_close(monkeypatch):
def failed(*_): raise OSError('desktop disappeared')
monkeypatch.setattr(win32gui, 'EnumWindows', failed)
monkeypatch.setattr(win32service, 'GetProcessWindowStation', lambda: SimpleNamespace(EnumDesktops=lambda: []))
windows = _process_windows({10})[10]
assert any(w['class'] == 'UNCONFIRMED' for w in windows)
snapshot = _process_windows({10})
windows = snapshot[10]
assert snapshot.incomplete[10]
windows.append({'hwnd': 100, 'class': 'Afx:main', 'title': 'Design - Expedition PCB',
'children': [], 'enabled': True})
assert close_target('ExpeditionPCB.exe', windows)[0] is None
assert close_target('ExpeditionPCB.exe', windows, incomplete=snapshot.incomplete[10])[0] is None
@pytest.mark.parametrize('choice', [6, 7, 2])
+171
View File
@@ -0,0 +1,171 @@
from contextlib import nullcontext
import json
import sys
import time
from pathlib import Path
from types import SimpleNamespace
from uuid import uuid4
import pytest
from cbb_refresh_verify import residual_sessions as sessions
from test_residual_sessions import row, OWNERSHIP
def window():
return dict(hwnd=100, title='Design - Expedition PCB', desktop='Default',
**{'class': 'Afx:main'}, enabled=True, children=[], documents=[])
class PartialWindows(dict):
incomplete = {10: 'target thread inaccessible'}
def test_thread_read_failure_does_not_poison_another_process(monkeypatch):
import win32gui, win32process, win32service
def global_failure(*args):
raise OSError('an unrelated desktop is inaccessible')
monkeypatch.setattr(win32gui, 'EnumWindows', global_failure)
monkeypatch.setattr(win32service, 'GetProcessWindowStation',
lambda: SimpleNamespace(EnumDesktops=lambda: ['Default', 'CbbManagement_Unrelated']))
monkeypatch.setattr(sessions, '_process_threads', lambda _: {10: [100], 20: [200]}, raising=False)
monkeypatch.setattr(sessions, '_thread_desktop_name',
lambda tid: 'Default' if tid == 100 else 'CbbManagement_Broken', raising=False)
def open_desktop(name, *args):
if name == 'CbbManagement_Broken':
raise PermissionError('only process 20 is unreadable')
assert name == 'Default', 'an unrelated desktop must not be inspected'
return SimpleNamespace(EnumDesktopWindows=lambda: [1000], CloseDesktop=lambda: None)
monkeypatch.setattr(win32service, 'OpenDesktop', open_desktop)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (100, 10))
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'Design - Expedition PCB')
monkeypatch.setattr(win32gui, 'GetClassName', lambda _: 'Afx:main')
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
monkeypatch.setattr(win32gui, 'GetWindowRect', lambda _: (0, 0, 100, 100))
result = sessions._process_windows({10, 20})
assert [w['hwnd'] for w in result[10]] == [1000]
assert 10 not in result.incomplete and 'unreadable' in result.incomplete[20]
assert result[20] == [], 'a read error must not be represented as a native modal window'
assert sessions.close_target('ExpeditionPCB.exe', result[10])[0]
def test_preview_exposes_only_target_process_incomplete_state(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'; library.touch()
processes = [row(pid, tmp_path/f'ReusableBlocksLP/{pid}/Work/{pid}.prj', name='ExpeditionPCB.exe')
for pid in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
monkeypatch.setattr(sessions, '_process_identity', lambda r: dict(created_handle='creation',
image=r['executable'], **OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: PartialWindows({10: [window()], 20: [window()]}))
affected, healthy = sessions.inspect_residual_sessions(library)['sessions']
assert affected['windows_incomplete'] and not affected['can_close'] and not affected['force_allowed']
assert affected['native_activity']['status'] == 'UNCONFIRMED'
assert '读取' in affected['detail'] and '弹窗' not in affected['detail']
assert healthy['can_close'] and healthy['force_allowed']
def test_action_rechecks_incomplete_read_before_force_termination(monkeypatch):
import win32api, win32con, win32event
process = dict(row(10, 'C:/library/A.prj', name='ExpeditionPCB.exe'),
created_handle='creation', image='C:/Mentor/ExpeditionPCB.exe', scope_confirmed=True, **OWNERSHIP)
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {k: process[k] for k in ('created_handle', 'image')})
monkeypatch.setattr(sessions, '_force_ownership', lambda *args: dict(OWNERSHIP))
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *args: win32con.WAIT_TIMEOUT)
monkeypatch.setattr(sessions, '_process_windows', lambda _: PartialWindows({10: [window()]}))
monkeypatch.setattr(win32api, 'TerminateProcess', lambda *args: pytest.fail('unreadable target was ended'))
result = sessions._force_close(process)
assert result['release_status'] == 'WAITING' and result['native_activity']['status'] == 'UNCONFIRMED'
def test_identity_read_failure_keeps_the_other_preview_row_available(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'; library.touch()
processes = [row(pid, tmp_path/f'ReusableBlocksLP/{pid}/Work/A.prj', name='ExpeditionPCB.exe')
for pid in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
def identity(process):
if process['pid'] == 10:
raise PermissionError('token inaccessible')
return dict(created_handle='creation', image=process['executable'], **OWNERSHIP)
monkeypatch.setattr(sessions, '_process_identity', identity)
monkeypatch.setattr(sessions, '_process_windows', lambda _: {pid: [window()] for pid in (10, 20)})
affected, healthy = sessions.inspect_residual_sessions(library)['sessions']
assert not affected['force_allowed'] and 'token inaccessible' in affected['detail']
assert healthy['force_allowed'] and healthy['can_close']
def test_native_cancel_retains_exact_preview_scope(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
process = dict(row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj'),
scope_confirmed=True, block_names=['A'], cancel_prompt={'hwnd': 100})
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
expected = (library.parent/'ReusableBlocksLP/A/Work', library.parent/'SymbolLibs')
def scoped(actual, selected_library, roots):
assert roots == expected, 'Cancel widened the scope from its preview'
return True
monkeypatch.setattr(library_lock, '_owner_matches_scope', scoped)
monkeypatch.setattr(sessions, '_request_native_cancel', lambda *a, **kw:
dict(release_status='WAITING', detail='cancel requested'))
result = sessions.request_native_cancel(process, library, tmp_path/'evidence')
assert result['sessions'][0]['detail'] == 'cancel requested'
def test_persisted_release_evidence_is_bounded_without_changing_preview(tmp_path, monkeypatch):
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
output = '原生输出' * 100000
observed = dict(window(), output=output, children=[dict(text=output, **{'class': 'RichEdit'})])
process = dict(row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj', name='ExpeditionPCB.exe'),
created_handle='creation', image='C:/Mentor/ExpeditionPCB.exe', scope_confirmed=True,
windows=[observed], native_activity={'status': 'IDLE', 'output': output}, **OWNERSHIP)
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: dict(release_status='RELEASED', detail='ended'))
monkeypatch.setattr(sessions, '_finish_library_release', lambda *args:
dict(status='RELEASE_CONFIRMED', library=str(library)))
result = sessions.release_residual_sessions(dict(library=str(library), sessions=[process]),
tmp_path/'evidence', force=True)
assert result['status'] == 'RELEASE_CONFIRMED'
for path in (Path(result['evidence_path']), Path(result['consent_path'])):
assert path.stat().st_size < 20000
saved = json.loads(path.read_text('utf-8'))['sessions'][0]
assert 'output' not in saved['native_activity']
assert 'children' not in saved['windows'][0] and 'output' not in saved['windows'][0]
assert len(saved['windows'][0]['output_excerpt'].encode('utf-8')) <= 4096
assert saved['windows'][0]['output_truncated'] is True
assert process['windows'][0]['output'] == output
def test_real_private_desktop_is_read_through_its_process_threads(tmp_path):
from cbb_refresh_verify.desktop_worker import DesktopWorker
ready, stop = tmp_path/'ready.json', tmp_path/'stop'
script = tmp_path/'window.py'
name = 'CbbManagement_Review_'+uuid4().hex[:10]
script.write_text('import json,time,win32api,win32con,win32gui\nfrom pathlib import Path\n'
'wc=win32gui.WNDCLASS()\nwc.hInstance=win32api.GetModuleHandle(None)\n'
'wc.lpszClassName="CbbReviewWindow"\nwc.lpfnWndProc=win32gui.DefWindowProc\n'
'atom=win32gui.RegisterClass(wc)\n'
'hwnd=win32gui.CreateWindow(atom,"Controlled review fixture",'
'win32con.WS_OVERLAPPEDWINDOW|win32con.WS_VISIBLE,0,0,300,200,0,0,wc.hInstance,None)\n'
f'Path({str(ready)!r}).write_text(json.dumps(dict(hwnd=hwnd)))\n'
f'while not Path({str(stop)!r}).exists():\n'
' win32gui.PumpWaitingMessages();time.sleep(.02)\n'
'win32gui.DestroyWindow(hwnd)\n', encoding='utf-8')
worker = DesktopWorker([sys.executable, str(script)], name)
try:
deadline = time.monotonic()+8
while not ready.exists() and worker.poll() is None and time.monotonic()<deadline:
time.sleep(.02)
assert ready.exists()
hwnd = json.loads(ready.read_text())['hwnd']
snapshot = sessions._process_windows({worker.pid})
assert worker.pid not in snapshot.incomplete, snapshot.incomplete
target = next(w for w in snapshot[worker.pid] if w['hwnd'] == hwnd)
assert target['desktop'] == name and target['title'] == 'Controlled review fixture'
finally:
stop.touch()
worker.wait(5)
worker.close()
+166
View File
@@ -0,0 +1,166 @@
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):
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(_):
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):
@@ -0,0 +1,52 @@
import json
from pathlib import Path
import pytest
from cbb_refresh_verify import library_lock as locks
@pytest.mark.parametrize('retained_owner', [False, True])
def test_releasing_another_blocks_checkpoint_names_its_owner(tmp_path, monkeypatch, retained_owner):
library = tmp_path/'library/lib.lmc'
library.parent.mkdir(); library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
lease = None
if retained_owner:
with locks.LibraryLock(library, block_name='BlockB', safe_to_release=lambda: False) as lease:
pass
else:
locks._persist_blocker(library, lease_id='b'*32, block_name='BlockB')
before = locks.blocker_path(library).read_bytes()
try:
proof = locks.release_retained_library(library, tmp_path/'evidence', block_name='BlockA')
assert proof['requested_block_name'] == 'BlockA'
assert proof['proof_scope'] == 'LIBRARY'
assert proof['reconciled_foreign_blockers'] == ['BlockB']
assert proof['data_recovery_confirmed'] is False
checkpoint = next(r for r in proof['reconciled_checkpoints'] if r['kind'] == 'checkpoint')
assert checkpoint['block_name'] == 'BlockB' and checkpoint['status'] == 'OWNER_RELEASE_UNCONFIRMED'
assert checkpoint['lease_id']
proof_path = Path(proof['evidence_path'])
assert json.loads(proof_path.read_text('utf-8'))['reconciled_foreign_blockers'] == ['BlockB']
assert (proof_path.parent/'blocker-before-0.json').read_bytes() == before
assert not locks.blocker_path(library).exists()
if retained_owner:
assert any(r['kind'] == 'retained_owner' and r['block_name'] == 'BlockB'
for r in proof['reconciled_checkpoints'])
finally:
if lease:
with locks._guard:
owner = locks._owners.pop(lease.key, None)
if owner:
owner['handle'].Close()
def test_matching_checkpoint_uses_block_scope_without_foreign_targets(tmp_path, monkeypatch):
library = tmp_path/'library/lib.lmc'
library.parent.mkdir(); library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
locks._persist_blocker(library, lease_id='a'*32, block_name='BlockA')
proof = locks.release_retained_library(library, tmp_path/'evidence', block_name='BlockA')
assert proof['proof_scope'] == 'BLOCK' and proof['proof_block_name'] == 'BlockA'
assert proof['reconciled_foreign_blockers'] == []
@@ -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()