审查拆分 1/4:只读占用探测与可取消任务队列 #9
No files matched your search
@@ -0,0 +1,13 @@
|
||||
# 独立审查 1:只读进程探测与原生任务准入队列
|
||||
|
||||
基于 main `a56fd17`,不叠加 PR #3 的历史提交。
|
||||
|
||||
**行为变化:** 增加有界、版本化、只读 owner-probe helper 和可取消的 FIFO 原生任务队列。应用仅新增隐藏的只读 helper 分派;现有 UI、验证和原生写操作保持原来的入口。
|
||||
|
||||
**失败安全:** 查询超时或协议/身份异常返回未确认;暂停或取消的队列票据不会运行其动作,也不阻止后面的可执行任务。不启动或终止 Mentor 进程。
|
||||
|
||||
**回滚方式:** 尚未合入下游时撤销本提交即可;下游接入后须按依赖从上层向下回退。
|
||||
|
||||
完整回归:491 passed,1 条既有 pywinauto STA 提示。编译和 diff 检查通过。
|
||||
|
||||
与原评论建议的差别:`management_transaction` 直接导入管理模型和库锁;`scoped_manifest` 的协调记录与独占快照依赖库锁协议。这两者在后端审查中一起交付,避免构造导入不完整的“纯工具”基线。
|
||||
@@ -1,136 +1,140 @@
|
||||
from __future__ import annotations
|
||||
import argparse, os, sys
|
||||
from pathlib import Path
|
||||
from typing import Sequence
|
||||
from .runtime_logging import configure
|
||||
|
||||
|
||||
def configure_qt_application(app):
|
||||
"""Apply a predictable light palette across machines and Qt themes."""
|
||||
from PySide6.QtGui import QColor, QPalette
|
||||
|
||||
app.setStyle('Fusion')
|
||||
palette = app.palette()
|
||||
colors = {
|
||||
QPalette.ColorRole.Window: '#f5f6f8',
|
||||
QPalette.ColorRole.WindowText: '#202124',
|
||||
QPalette.ColorRole.Base: '#ffffff',
|
||||
QPalette.ColorRole.AlternateBase: '#eef1f5',
|
||||
QPalette.ColorRole.Text: '#202124',
|
||||
QPalette.ColorRole.Button: '#eef1f5',
|
||||
QPalette.ColorRole.ButtonText: '#202124',
|
||||
QPalette.ColorRole.Highlight: '#2f6fed',
|
||||
QPalette.ColorRole.HighlightedText: '#ffffff',
|
||||
QPalette.ColorRole.ToolTipBase: '#ffffff',
|
||||
QPalette.ColorRole.ToolTipText: '#202124',
|
||||
QPalette.ColorRole.PlaceholderText: '#6b7280',
|
||||
}
|
||||
for role, color in colors.items():
|
||||
palette.setColor(role, QColor(color))
|
||||
app.setPalette(palette)
|
||||
app.setStyleSheet(
|
||||
'QWidget { color: #202124; }'
|
||||
'QTableWidget, QLineEdit, QTextEdit, QSpinBox { '
|
||||
'background: #ffffff; color: #202124; selection-color: #202124; }'
|
||||
'QHeaderView::section { background: #e9edf2; color: #202124; }'
|
||||
'QPushButton, QToolButton { color: #202124; }'
|
||||
)
|
||||
return app
|
||||
|
||||
def resolve_data_root(cli_value: Path | None) -> Path:
|
||||
if cli_value is not None: return cli_value.expanduser().resolve()
|
||||
if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data"
|
||||
local = os.environ.get("LOCALAPPDATA")
|
||||
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
|
||||
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||
if args.repair_worker:
|
||||
from .native_repair_ui import repair_worker_main
|
||||
return repair_worker_main(args.repair_worker)
|
||||
if args.collect_failure_logs:
|
||||
from .verify_diagnostics import failure_logs_main
|
||||
return failure_logs_main(args.collect_failure_logs)
|
||||
if args.dialog_agent:
|
||||
from .dialog_agent import dialog_agent_main
|
||||
return dialog_agent_main(args.dialog_agent)
|
||||
if args.verify_worker:
|
||||
from .mentor_adapter import worker_main
|
||||
import contextlib
|
||||
with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
||||
return worker_main(args.verify_worker)
|
||||
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
|
||||
try:
|
||||
if args.batch_lmc:
|
||||
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
|
||||
run_batch, write_batch_report, failure_report_path)
|
||||
from .library_reader import read_library_fast
|
||||
from .batch_status import authoritative_status_map
|
||||
from .network_path import LibraryPathLease, select_library_file
|
||||
with LibraryPathLease.acquire(args.batch_lmc) as lease:
|
||||
mentor_path = select_library_file(lease.mentor_path)
|
||||
logger.info(
|
||||
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
|
||||
lease.display_path, mentor_path, lease.drive or '-',
|
||||
lease.remote_root or '-', lease.created)
|
||||
names = list(args.block)
|
||||
if not names:
|
||||
library = read_library_fast(
|
||||
mentor_path,
|
||||
status_reader=lambda path, names: authoritative_status_map(
|
||||
names, path, context.root/'status-scan.jsonl'),
|
||||
)
|
||||
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')
|
||||
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,
|
||||
mapped_drive=lease.drive,
|
||||
mapped_remote_root=lease.remote_root,
|
||||
native_lm_verify=native_lm_verify_enabled())
|
||||
for name in names]
|
||||
try:
|
||||
results = run_batch(requests)
|
||||
except Exception:
|
||||
lease.retain_for_recovery()
|
||||
raise
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
lease.retain_for_recovery()
|
||||
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))
|
||||
code = 0 if all(result.status == 'PASS' for result in results) else 2
|
||||
logger.info('application_clean_shutdown exit_code=%s', code)
|
||||
return code
|
||||
from .ui.main_window import MainWindow, application_icon_path
|
||||
if args.smoke_test:
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
from PySide6.QtWidgets import QApplication
|
||||
app = QApplication.instance() or QApplication([sys.executable])
|
||||
configure_qt_application(app)
|
||||
window = MainWindow(logging_context=context); window.show()
|
||||
icon_path = application_icon_path()
|
||||
if icon_path.is_file():
|
||||
from PySide6.QtGui import QIcon
|
||||
app.setWindowIcon(QIcon(str(icon_path)))
|
||||
if args.smoke_test:
|
||||
from PySide6.QtCore import QTimer
|
||||
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
|
||||
QTimer.singleShot(250, app.quit)
|
||||
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
|
||||
except Exception: logger.exception("application_startup_failure"); return 1
|
||||
finally:
|
||||
for handler in logger.handlers: handler.flush()
|
||||
from __future__ import annotations
|
||||
import argparse, os, sys
|
||||
from pathlib import Path
|
||||
from typing import Sequence
|
||||
from .runtime_logging import configure
|
||||
|
||||
|
||||
def configure_qt_application(app):
|
||||
"""Apply a predictable light palette across machines and Qt themes."""
|
||||
from PySide6.QtGui import QColor, QPalette
|
||||
|
||||
app.setStyle('Fusion')
|
||||
palette = app.palette()
|
||||
colors = {
|
||||
QPalette.ColorRole.Window: '#f5f6f8',
|
||||
QPalette.ColorRole.WindowText: '#202124',
|
||||
QPalette.ColorRole.Base: '#ffffff',
|
||||
QPalette.ColorRole.AlternateBase: '#eef1f5',
|
||||
QPalette.ColorRole.Text: '#202124',
|
||||
QPalette.ColorRole.Button: '#eef1f5',
|
||||
QPalette.ColorRole.ButtonText: '#202124',
|
||||
QPalette.ColorRole.Highlight: '#2f6fed',
|
||||
QPalette.ColorRole.HighlightedText: '#ffffff',
|
||||
QPalette.ColorRole.ToolTipBase: '#ffffff',
|
||||
QPalette.ColorRole.ToolTipText: '#202124',
|
||||
QPalette.ColorRole.PlaceholderText: '#6b7280',
|
||||
}
|
||||
for role, color in colors.items():
|
||||
palette.setColor(role, QColor(color))
|
||||
app.setPalette(palette)
|
||||
app.setStyleSheet(
|
||||
'QWidget { color: #202124; }'
|
||||
'QTableWidget, QLineEdit, QTextEdit, QSpinBox { '
|
||||
'background: #ffffff; color: #202124; selection-color: #202124; }'
|
||||
'QHeaderView::section { background: #e9edf2; color: #202124; }'
|
||||
'QPushButton, QToolButton { color: #202124; }'
|
||||
)
|
||||
return app
|
||||
|
||||
def resolve_data_root(cli_value: Path | None) -> Path:
|
||||
if cli_value is not None: return cli_value.expanduser().resolve()
|
||||
if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent / "data"
|
||||
local = os.environ.get("LOCALAPPDATA")
|
||||
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--repair-worker', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--owner-probe', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
|
||||
parser.add_argument('--block', action='append', default=[], help=argparse.SUPPRESS)
|
||||
parser.add_argument('--libspec', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--dms-login-config', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument('--mentor-bin', default='', help=argparse.SUPPRESS)
|
||||
parser.add_argument("--smoke-test", action="store_true", help=argparse.SUPPRESS); parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS)
|
||||
args = parser.parse_args(list(argv) if argv is not None else None)
|
||||
if args.owner_probe:
|
||||
from .owner_probe import owner_probe_main
|
||||
return owner_probe_main(args.owner_probe)
|
||||
if args.repair_worker:
|
||||
from .native_repair_ui import repair_worker_main
|
||||
return repair_worker_main(args.repair_worker)
|
||||
if args.collect_failure_logs:
|
||||
from .verify_diagnostics import failure_logs_main
|
||||
return failure_logs_main(args.collect_failure_logs)
|
||||
if args.dialog_agent:
|
||||
from .dialog_agent import dialog_agent_main
|
||||
return dialog_agent_main(args.dialog_agent)
|
||||
if args.verify_worker:
|
||||
from .mentor_adapter import worker_main
|
||||
import contextlib
|
||||
with args.verify_worker.with_name('worker.log').open('a', encoding='utf-8') as log:
|
||||
with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):
|
||||
return worker_main(args.verify_worker)
|
||||
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
|
||||
try:
|
||||
if args.batch_lmc:
|
||||
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
|
||||
run_batch, write_batch_report, failure_report_path)
|
||||
from .library_reader import read_library_fast
|
||||
from .batch_status import authoritative_status_map
|
||||
from .network_path import LibraryPathLease, select_library_file
|
||||
with LibraryPathLease.acquire(args.batch_lmc) as lease:
|
||||
mentor_path = select_library_file(lease.mentor_path)
|
||||
logger.info(
|
||||
'library_path_lease display=%s mentor=%s drive=%s remote=%s created=%s',
|
||||
lease.display_path, mentor_path, lease.drive or '-',
|
||||
lease.remote_root or '-', lease.created)
|
||||
names = list(args.block)
|
||||
if not names:
|
||||
library = read_library_fast(
|
||||
mentor_path,
|
||||
status_reader=lambda path, names: authoritative_status_map(
|
||||
names, path, context.root/'status-scan.jsonl'),
|
||||
)
|
||||
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')
|
||||
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,
|
||||
mapped_drive=lease.drive,
|
||||
mapped_remote_root=lease.remote_root,
|
||||
native_lm_verify=native_lm_verify_enabled())
|
||||
for name in names]
|
||||
try:
|
||||
results = run_batch(requests)
|
||||
except Exception:
|
||||
lease.retain_for_recovery()
|
||||
raise
|
||||
if any(not result.safe_to_continue for result in results):
|
||||
lease.retain_for_recovery()
|
||||
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))
|
||||
code = 0 if all(result.status == 'PASS' for result in results) else 2
|
||||
logger.info('application_clean_shutdown exit_code=%s', code)
|
||||
return code
|
||||
from .ui.main_window import MainWindow, application_icon_path
|
||||
if args.smoke_test:
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
from PySide6.QtWidgets import QApplication
|
||||
app = QApplication.instance() or QApplication([sys.executable])
|
||||
configure_qt_application(app)
|
||||
window = MainWindow(logging_context=context); window.show()
|
||||
icon_path = application_icon_path()
|
||||
if icon_path.is_file():
|
||||
from PySide6.QtGui import QIcon
|
||||
app.setWindowIcon(QIcon(str(icon_path)))
|
||||
if args.smoke_test:
|
||||
from PySide6.QtCore import QTimer
|
||||
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
|
||||
QTimer.singleShot(250, app.quit)
|
||||
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
|
||||
except Exception: logger.exception("application_startup_failure"); return 1
|
||||
finally:
|
||||
for handler in logger.handlers: handler.flush()
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Cooperative FIFO admission for this application's native operations."""
|
||||
from threading import Condition
|
||||
|
||||
|
||||
class QueueCancelled(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class NativeQueue:
|
||||
def __init__(self):
|
||||
self.condition = Condition()
|
||||
self.pending = []
|
||||
self.active = False
|
||||
|
||||
def wake(self):
|
||||
with self.condition: self.condition.notify_all()
|
||||
|
||||
def run(self, action, *, stop=None, waiting=None, ready=lambda: True):
|
||||
ticket = object()
|
||||
acquired, notified = False, False
|
||||
with self.condition: self.pending.append((ticket, ready))
|
||||
try:
|
||||
while not acquired:
|
||||
with self.condition:
|
||||
if stop is not None and stop.is_set():
|
||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||
first = next((token for token, available in self.pending if available()), None)
|
||||
if not self.active and first is ticket:
|
||||
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
||||
self.active = acquired = True
|
||||
else:
|
||||
self.condition.wait(.1)
|
||||
if not acquired and not notified and waiting is not None:
|
||||
notified = True
|
||||
try: waiting()
|
||||
except Exception: pass
|
||||
if stop is not None and stop.is_set():
|
||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||
return action()
|
||||
finally:
|
||||
with self.condition:
|
||||
self.pending = [entry for entry in self.pending if entry[0] is not ticket]
|
||||
if acquired: self.active = False
|
||||
self.condition.notify_all()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Bound WMI enumeration in a read-only helper, never in the Qt thread."""
|
||||
from pathlib import Path
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
|
||||
def query_owners(names, *, timeout_seconds=10):
|
||||
names = tuple(names)
|
||||
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
|
||||
raise ValueError('OWNER_QUERY_INVALID')
|
||||
return _query_processes(names, timeout_seconds=timeout_seconds)
|
||||
|
||||
|
||||
def query_process_snapshot(*, timeout_seconds=10):
|
||||
"""Bound a complete process tree; retain unknown executable descendants."""
|
||||
return _query_processes(None, timeout_seconds=timeout_seconds)
|
||||
|
||||
|
||||
def _query_processes(names, *, timeout_seconds):
|
||||
full_snapshot = names is None
|
||||
request = {'snapshot_version': 1} if full_snapshot else {'names': names}
|
||||
with tempfile.TemporaryDirectory(prefix='cbb-owner-probe-') as directory:
|
||||
job = Path(directory)/'request.json'
|
||||
job.write_text(json.dumps(request), encoding='utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--owner-probe', str(job)]
|
||||
try:
|
||||
result = subprocess.run(command, timeout=max(.1, min(10, timeout_seconds)),
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
|
||||
except subprocess.TimeoutExpired as error:
|
||||
# This helper only enumerates processes; it never launches Mentor
|
||||
# or acquires a native database session.
|
||||
raise RuntimeError('OWNER_QUERY_TIMEOUT: 进程查询超时,占用状态无法确认') from error
|
||||
try:
|
||||
record = json.loads(job.with_name('result.json').read_text('utf-8'))
|
||||
rows = record['owners']
|
||||
identity_matches = (type(record.get('snapshot_version')) is int and record['snapshot_version'] == 1
|
||||
if full_snapshot else record.get('names') == list(names))
|
||||
if result.returncode != 0 or not identity_matches or not isinstance(rows, list):
|
||||
raise ValueError('invalid result')
|
||||
seen = set()
|
||||
for row in rows:
|
||||
if (type(row['pid']) is not int or row['pid'] < (0 if full_snapshot else 1)
|
||||
or row['pid'] in seen or not isinstance(row['name'], str) or not row['name']
|
||||
or not full_snapshot and row['name'].casefold() not in {n.casefold() for n in names}
|
||||
or full_snapshot and not isinstance(row['created'], str)
|
||||
or not isinstance(row['command'], str) or not isinstance(row['executable'], str)
|
||||
or type(row['parent']) is not int or row['parent'] < 0):
|
||||
raise ValueError('invalid owner')
|
||||
seen.add(row['pid'])
|
||||
return rows
|
||||
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
|
||||
raise RuntimeError('OWNER_QUERY_UNCONFIRMED: 进程查询未返回有效证据') from error
|
||||
|
||||
|
||||
def owner_probe_main(job):
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
job = Path(job)
|
||||
request = json.loads(job.read_text('utf-8'))
|
||||
full_snapshot = request == {'snapshot_version': 1} and type(request.get('snapshot_version')) is int
|
||||
names = request.get('names')
|
||||
if not full_snapshot:
|
||||
if (not isinstance(names, list) or not names
|
||||
or any(not isinstance(name, str) or not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names)):
|
||||
return 1
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
service = win32com.client.GetObject('winmgmts:')
|
||||
query = ('SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId' +
|
||||
(',CreationDate' if full_snapshot else '') + ' FROM Win32_Process')
|
||||
if not full_snapshot:
|
||||
query += ' WHERE ' + ' OR '.join(f"Name='{name}'" for name in names)
|
||||
rows = [{'pid': int(item.ProcessId), 'name': str(item.Name),
|
||||
'command': str(item.CommandLine or ''), 'executable': str(item.ExecutablePath or ''),
|
||||
'parent': int(item.ParentProcessId or 0),
|
||||
**({'created': str(item.CreationDate or '')} if full_snapshot else {})}
|
||||
for item in service.ExecQuery(query)]
|
||||
service = None
|
||||
response = {'snapshot_version': 1} if full_snapshot else {'names': names}
|
||||
job.with_name('result.json').write_text(json.dumps({**response, 'owners': rows}), encoding='utf-8')
|
||||
return 0
|
||||
finally:
|
||||
pythoncom.CoUninitialize()
|
||||
@@ -0,0 +1,42 @@
|
||||
from threading import Event, Thread
|
||||
|
||||
from cbb_refresh_verify.operation_queue import NativeQueue, QueueCancelled
|
||||
|
||||
|
||||
def test_paused_ticket_yields_to_a_ready_native_task():
|
||||
queue=NativeQueue()
|
||||
ready, waiting, complete=Event(),Event(),Event()
|
||||
order=[]
|
||||
thread=Thread(target=lambda:queue.run(lambda:(order.append('resumed'),complete.set()),
|
||||
ready=ready.is_set,waiting=waiting.set))
|
||||
thread.start()
|
||||
try:
|
||||
assert waiting.wait(2)
|
||||
queue.run(lambda:order.append('ready'))
|
||||
assert order==['ready']
|
||||
ready.set();queue.wake()
|
||||
assert complete.wait(2)
|
||||
assert order==['ready','resumed']
|
||||
finally:
|
||||
ready.set();queue.wake();thread.join(2)
|
||||
assert not thread.is_alive()
|
||||
|
||||
|
||||
def test_cancelled_paused_ticket_does_not_hold_later_work():
|
||||
queue=NativeQueue()
|
||||
waiting,stop=Event(),Event()
|
||||
outcome=[]
|
||||
def wait():
|
||||
try:
|
||||
queue.run(lambda:outcome.append('unexpected'),ready=lambda:False,
|
||||
waiting=waiting.set,stop=stop)
|
||||
except QueueCancelled:outcome.append('cancelled')
|
||||
thread=Thread(target=wait);thread.start()
|
||||
try:
|
||||
assert waiting.wait(2)
|
||||
stop.set();queue.wake();thread.join(2)
|
||||
assert not thread.is_alive()
|
||||
queue.run(lambda:outcome.append('next'))
|
||||
assert outcome==['cancelled','next']
|
||||
finally:
|
||||
stop.set();queue.wake();thread.join(2)
|
||||
@@ -0,0 +1,92 @@
|
||||
import subprocess
|
||||
import pytest
|
||||
|
||||
|
||||
def test_wmi_timeout_is_unknown_not_idle(monkeypatch):
|
||||
from cbb_refresh_verify.owner_probe import query_owners
|
||||
def hang(command, **kw):
|
||||
assert 0 < kw['timeout'] <= 10
|
||||
raise subprocess.TimeoutExpired(command, kw['timeout'])
|
||||
monkeypatch.setattr(subprocess, 'run', hang)
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
|
||||
query_owners(['ExpeditionPCB.exe'])
|
||||
|
||||
|
||||
def test_malformed_wmi_response_is_not_empty_owner_list(monkeypatch):
|
||||
from cbb_refresh_verify.owner_probe import query_owners
|
||||
from pathlib import Path
|
||||
def run(command, **kw):
|
||||
Path(command[-1]).with_name('result.json').write_text('{}')
|
||||
return subprocess.CompletedProcess(command, 0)
|
||||
monkeypatch.setattr(subprocess, 'run', run)
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_UNCONFIRMED'):
|
||||
query_owners(['ExpeditionPCB.exe'])
|
||||
|
||||
|
||||
def test_full_snapshot_timeout_is_bounded_and_not_idle(monkeypatch):
|
||||
from cbb_refresh_verify.owner_probe import query_process_snapshot
|
||||
import json
|
||||
from pathlib import Path
|
||||
def hang(command, **kw):
|
||||
assert json.loads(Path(command[-1]).read_text('utf-8')) == {'snapshot_version': 1}
|
||||
assert 0 < kw['timeout'] <= .5
|
||||
raise subprocess.TimeoutExpired(command, kw['timeout'])
|
||||
monkeypatch.setattr(subprocess, 'run', hang)
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_TIMEOUT'):
|
||||
query_process_snapshot(timeout_seconds=.5)
|
||||
|
||||
|
||||
def test_full_snapshot_keeps_unknown_processes_and_creation_identity(monkeypatch):
|
||||
from cbb_refresh_verify.owner_probe import query_process_snapshot
|
||||
import json
|
||||
from pathlib import Path
|
||||
rows = [{'pid': 0, 'parent': 0, 'name': 'System Idle Process',
|
||||
'command': '', 'executable': '', 'created': ''},
|
||||
{'pid': 999, 'parent': 100, 'name': 'unlisted-child.exe',
|
||||
'command': 'unlisted-child.exe', 'executable': 'C:/native/unlisted-child.exe',
|
||||
'created': '20261105123456.000000+480'}]
|
||||
def run(command, **kw):
|
||||
Path(command[-1]).with_name('result.json').write_text(json.dumps({
|
||||
'snapshot_version': 1, 'owners': rows}), encoding='utf-8')
|
||||
return subprocess.CompletedProcess(command, 0)
|
||||
monkeypatch.setattr(subprocess, 'run', run)
|
||||
assert query_process_snapshot() == rows
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change', ['version', 'created', 'duplicate', 'pid'])
|
||||
def test_full_snapshot_rejects_incomplete_response(monkeypatch, change):
|
||||
from cbb_refresh_verify.owner_probe import query_process_snapshot
|
||||
import json
|
||||
from pathlib import Path
|
||||
row = {'pid': 10, 'parent': 1, 'name': 'child.exe', 'command': '',
|
||||
'executable': '', 'created': ''}
|
||||
record = {'snapshot_version': 1, 'owners': [row]}
|
||||
if change == 'version': record['snapshot_version'] = 2
|
||||
if change == 'created': del row['created']
|
||||
if change == 'duplicate': record['owners'].append(dict(row))
|
||||
if change == 'pid': row['pid'] = -1
|
||||
def run(command, **kw):
|
||||
Path(command[-1]).with_name('result.json').write_text(json.dumps(record), encoding='utf-8')
|
||||
return subprocess.CompletedProcess(command, 0)
|
||||
monkeypatch.setattr(subprocess, 'run', run)
|
||||
with pytest.raises(RuntimeError, match='OWNER_QUERY_UNCONFIRMED'):
|
||||
query_process_snapshot()
|
||||
|
||||
|
||||
def test_full_snapshot_helper_does_not_filter_unknown_descendants(tmp_path, monkeypatch):
|
||||
from cbb_refresh_verify.owner_probe import owner_probe_main
|
||||
import win32com.client
|
||||
from types import SimpleNamespace
|
||||
import json
|
||||
queries = []
|
||||
def query(sql):
|
||||
queries.append(sql)
|
||||
return [SimpleNamespace(ProcessId=42, ParentProcessId=12, Name='custom-native-child.exe',
|
||||
CommandLine='custom-native-child.exe', ExecutablePath='C:/custom-native-child.exe',
|
||||
CreationDate='creation-time')]
|
||||
monkeypatch.setattr(win32com.client, 'GetObject', lambda _: SimpleNamespace(ExecQuery=query))
|
||||
job = tmp_path/'request.json'; job.write_text('{"snapshot_version": 1}')
|
||||
assert owner_probe_main(job) == 0
|
||||
assert len(queries) == 1 and 'WHERE' not in queries[0]
|
||||
row = json.loads(job.with_name('result.json').read_text('utf-8'))['owners'][0]
|
||||
assert row['name'] == 'custom-native-child.exe' and row['created'] == 'creation-time'
|
||||
Reference in new issue
Block a user