Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e230e1a46 |
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` 的协调记录与独占快照依赖库锁协议。这两者在后端审查中一起交付,避免构造导入不完整的“纯工具”基线。
|
||||||
@@ -47,6 +47,7 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
parser = argparse.ArgumentParser(prog="CbbRefreshVerify")
|
||||||
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--verify-worker', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--repair-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('--dialog-agent', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--collect-failure-logs', type=Path, help=argparse.SUPPRESS)
|
||||||
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
|
parser.add_argument('--batch-lmc', type=Path, help=argparse.SUPPRESS)
|
||||||
@@ -56,6 +57,9 @@ def main(argv: Sequence[str] | None = None) -> int:
|
|||||||
parser.add_argument('--mentor-bin', 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)
|
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)
|
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:
|
if args.repair_worker:
|
||||||
from .native_repair_ui import repair_worker_main
|
from .native_repair_ui import repair_worker_main
|
||||||
return repair_worker_main(args.repair_worker)
|
return repair_worker_main(args.repair_worker)
|
||||||
|
|||||||
@@ -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