fix: reconcile saved database locks without replaying replacements
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m44s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 3m57s
Core regression / JavaScript syntax (pull_request) Successful in 6s
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m44s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 3m57s
Core regression / JavaScript syntax (pull_request) Successful in 6s
This commit is contained in:
1 parent
cdbc92fab8
commit
e63a82b695
10 files changed
+748
-15
No files matched your search
@@ -0,0 +1,86 @@
|
||||
# 保存后数据库占用:修复与验收
|
||||
|
||||
日期:2026-11-18。分支:`codex/issue29-blocking-cleanup`,基础提交:`cdbc92f`。范围为保存后的源文件绑定、占锁交接、诊断与收尾错误;不涉及独立校验工作台。
|
||||
|
||||
## 问题与处理
|
||||
|
||||
先前 `mentor-live/first-project` 的 RL02、RL05 两处替换及 Save/CloseProject 已返回,随后 `bind_project_commit_source()` 读取 `database/icdb.dat` 时发生 PermissionError。该异常被归为通用错误,外层资源释放错误又掩盖了原始位置。历史日志缺少底层 Windows 代码和持锁者证据,仍不能认定当时的具体持锁进程。
|
||||
|
||||
现在先验证 CAD 身份及工程确实关闭,固定保存 marker、原始尝试和目标证据到 `project-save-pending.json`,再进行源文件绑定。只有绑定成功才发布完整 `project-checkpoint.json` 并登记工程检查点。等待期间显示“工程已保存,等待数据库释放后核验”;不是已经核验成功。
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[替换、保存及关闭工程] --> B[验证空工程与本批身份]
|
||||
B --> C[保留保存 marker 和原始尝试证据]
|
||||
C --> D[读取保存源文件]
|
||||
D --> E{读取结果}
|
||||
E -- 正常 --> F[绑定稳定源文件及命令摘要]
|
||||
E -- Windows 32 / 33 --> G[记录错误及持锁观察,最多等待 3 秒]
|
||||
E -- 权限、缺失等 --> P[已保存但待核验,保留首发原因]
|
||||
G --> D
|
||||
G -- 仍占用 --> H[再检查暂停意图,正常退出本批 Mentor 一次]
|
||||
H -- 正常退出 --> I[再次读取,最多等待 3 秒]
|
||||
H -- 强杀或收尾未确认 --> P
|
||||
I -- 仍占用或暂停 --> P
|
||||
I -- 可稳定读取 --> F
|
||||
F --> J[从保存副本导出原生数据并核验目标]
|
||||
J --> K[提交真实回执,任务完成]
|
||||
```
|
||||
|
||||
Windows 读文件使用 CreateFile 保留原生错误码,使用与后续 CRT 校验一致的 READ/WRITE 共享模式。仅 32(共享冲突)、33(锁冲突)进入等待;5(权限不足)、2(文件缺失)等直接形成明确的 `saved_source_pending` 错误。源文件读前后的工程摘要必须一致,改变或不可确认时保留待核验。
|
||||
|
||||
退出回调只存在于受管理 runtime 的已关闭工程、已验证保存 marker 分支。正常可读时继续复用 CAD;异常才走现有身份绑定的正常 Quit。该路径不派发替换,也不重新打开原工程。退出失败或需要强杀时,不绑定成功证明;资源释放和业务待核验分别保留。暂停会阻止进入退出回调,并在诊断、读取恢复后重新检查。已请求普通暂停但未遇锁的安全保存收尾仍沿用原流程。
|
||||
|
||||
首次锁冲突使用 Windows Restart Manager 只读查询候选进程,记录 PID、创建时间和名称。结果是该接口返回的观察,不是穷举全部内核句柄;空结果或查询失败均不授权结束任何外部进程。查询后重读,防止用已经过时的锁状态触发 CAD 回收。
|
||||
|
||||
`saved-source-status.json` 保留同一 session token、同一工程的首发错误、持锁观察及回收事实,后续 SQL 回执再次绑定时不会覆盖它;新 token 重置诊断。该文件不是成功证明,实际源文件始终重新验证。`operation-events.jsonl` 保留绑定及 Mentor 退出调用的先后顺序。多层资源异常仍显示最初的保存读取错误;诊断写入失败通过附注保留,不能替换首发错误。
|
||||
|
||||
## 验收结果
|
||||
|
||||
证据根目录:`D:/CodexValidation/saved-source-20261118/`。测试 XML 在仓库 `build/managed-desktop/`,集合有交集,不累加为独立用例或业务样本数。
|
||||
|
||||
| 验证 | 结果 | 证据 |
|
||||
| --- | --- | --- |
|
||||
| 保存、runtime、回执、恢复与反馈相关回归 | 124 passed,108.18 秒 | `saved-source-regression-final.xml` |
|
||||
| 源文件交接及资源状态增量回归 | 64 passed,26.56 秒 | `saved-source-delta-final.xml` |
|
||||
| 最终专项,Windows 默认 GBK 环境 | 21 passed,5.52 秒 | `saved-source-handoff-final.xml` |
|
||||
| 最终原生文件锁探针 | 20 个样本通过,28.320 秒 | `native-final-02/report.json` |
|
||||
| 原失败双目标工程,正常运行 | 2 saved / 0 failed,原生回读通过 | `mentor-dual/report.json` |
|
||||
| 双目标工程,保存后注入真实锁 | 2 saved / 0 failed,正常退出后核验通过 | `mentor-dual-fault/report.json`、`fault-result.json` |
|
||||
|
||||
新逻辑均先观察失败再修复;覆盖权限/缺失不重试、短暂锁、持续外部锁、源文件变化、暂停在诊断中到达和在退出提示后到达、强杀/退出未确认不发布证明、日志写失败、嵌套异常、诊断再绑定历史、下一工程新代次和可选进度损坏。独立只读审查提出的具体问题已修复,最终复查无剩余可操作发现。
|
||||
|
||||
### 20 个原生文件锁样本
|
||||
|
||||
脚本:`tools/probe_saved_source_handoff.py`。使用合成工程与文件,不启动 CAD。五种场景各 4 次:短暂独占锁、退出持有者后读取、持续外部锁、等待中暂停、文件缺失。真实 CreateFile 独占锁返回 32;Restart Manager 查到已知 fixture 进程。仅前两类最终绑定成功,其余保留 pending,退出回调次数受限,均不执行替换。真正 ACL 拒绝不通过修改用户 ACL 制造,错误 5 由专项测试模拟。
|
||||
|
||||
探针中的退出回调只释放其自建 fixture 进程,不能当成真实 Mentor 回收测试。首轮 `native-01` 曾发现诊断耗时导致使用旧冲突触发退出,报告保留;补重读及回归后通过,最终又以默认编码环境运行。20 个文件锁样本不是 20 个 BOM 业务样本。
|
||||
|
||||
### 两次真实 Mentor 双目标验收
|
||||
|
||||
两个独立的新副本均替换 RL02、RL05:`4100-CA3300-T7` → `4100-CA3300-2200`。从保存后的原生数据独立读取两个目标及其余未选位号;每次仅一个 VBS worker、一次 OpenProject、一次保存,没有重放。
|
||||
|
||||
| 指标 | 正常双目标 | 注入锁双目标 |
|
||||
| --- | --- | --- |
|
||||
| 队列耗时 | 257.842 秒 | 271.420 秒 |
|
||||
| saved / failed | 2 / 0 | 2 / 0 |
|
||||
| 任务 / 操作状态 | completed / verified | completed / verified |
|
||||
| CAD 代次 | 1 | 1 |
|
||||
| 正常退出 / 强杀 | 正常 / 无 | 正常 / 无 |
|
||||
| CAD 退出耗时 | 16.625 秒 | 5.688 秒 |
|
||||
|
||||
正常运行没有复现历史锁。故障运行由 `build/managed-desktop/live_saved_source_fault.py` 在已保存关闭后,用一个自建独立进程持有副本数据库的只读独占句柄;产品调用正常退出 Mentor,驱动确认退出回调返回后才释放 fixture,然后由产品继续核验。`fault-result.json` 证明注入成功、退出回调确实调用且运行退出码为 0。外部 fixture 并非被产品杀死,不能据此声称 Mentor 的 Quit 可以关闭任意外部文件句柄。
|
||||
|
||||
故障时间线(本地时间):18:16:39.722 开始绑定,18:16:43.192 开始正常退出 Mentor,18:16:48.910 退出返回,18:16:49.806 绑定完成。两次总耗时差异包含 CAD 运行波动,不能直接视为等待逻辑的固定开销。
|
||||
|
||||
任务 ID:正常 `d9a1c9af-7a39-4659-a445-a682c8c41a91`;故障 `be954b05-2b8c-4990-a74f-e18655ca93af`。两次任务数据库均 completed、两个操作均 verified;全部已记录写进程身份退出,受管理桌面消失。原始备份 34 文件 SHA-256 全部未变化。
|
||||
|
||||
真实故障验收后发现并修正同 token 诊断被第二次绑定覆盖的问题;暂停、嵌套报错、编码及诊断保留的最终增量由专项和资源回归验证。真实工程写入场景未为这些诊断增量重复执行。
|
||||
|
||||
## 边界
|
||||
|
||||
历史失败的具体持锁者仍不可从旧日志还原,本次修复并验证的是这类冲突的交接处理。持续的外部锁、真正权限不足、文件变化及强杀后不确定写入继续保留待核验,不能算执行成功,也不会自动重替换。
|
||||
|
||||
如果在完成源文件绑定之前退出程序,只保留保存 marker 和原始尝试,现有恢复逻辑不会把未绑定的 `project-save-pending.json` 当成成功证明。该状态仍需核对原结果,不提供自动重放或自动成功恢复。
|
||||
|
||||
未构建安装包、推送或发布版本;未修改原工程、中心库、系统配置和外部 Agent。
|
||||
@@ -19,6 +19,13 @@ LIVE_RESOURCES = {}
|
||||
|
||||
class BatchResourceCleanupError(TaskCenterError):
|
||||
def __init__(self, message, *, completed_result=None, primary_error=None, cleanup_error=None):
|
||||
original, seen = primary_error, set()
|
||||
while original is not None and id(original) not in seen:
|
||||
if getattr(original, 'code', None) in {'saved_source_pending', 'saved_source_changed'}:
|
||||
message = str(original) + ';资源收尾异常:' + message
|
||||
break
|
||||
seen.add(id(original))
|
||||
original = getattr(original, 'primary_error', None)
|
||||
super().__init__('batch_resources_pending', message)
|
||||
self.completed_result = completed_result
|
||||
self.primary_error = primary_error
|
||||
|
||||
@@ -422,8 +422,6 @@ class BatchCadRuntime:
|
||||
def _checkpoint(self, root, project, attempt_id):
|
||||
self.cad.checkpoint(root / ('cad-closed-' + attempt_id + '.json'))
|
||||
key = str(root).casefold()
|
||||
self.record['checkpoints'][key] = attempt_id
|
||||
self._save(state='ready')
|
||||
checkpoint = {'version': 1, 'resource_record': str(self.path),
|
||||
'session_id': self.session_id, 'generation': self.generation, 'attempt_id': attempt_id,
|
||||
'evidence_root': str(root), 'project_path': str(project), 'project_closed': True,
|
||||
@@ -455,7 +453,6 @@ class BatchCadRuntime:
|
||||
raise WorkerMonitorError('native project commit marker has an invalid outcome')
|
||||
proof = capture_project_commit(self.root, root, {'session_token': request[0],
|
||||
'project_path': str(project).casefold(), 'jobs_json': json.dumps(jobs)})
|
||||
proof = bind_project_commit_source(proof, self.root, root, project)
|
||||
proof['marker_sha256'] = hashlib.sha256(marker.read_bytes()).hexdigest()
|
||||
proof['files'].append({'path': str(canonical_path(marker)), 'sha256': proof['marker_sha256']})
|
||||
readback_names = []
|
||||
@@ -503,10 +500,29 @@ class BatchCadRuntime:
|
||||
if saved_only:
|
||||
proof.update(marker_state='project_saved', saved_only=True, validation_required='saved_netlist_v1',
|
||||
native_outcomes=dict(rows[1:]), outcomes=dict(rows[1:]))
|
||||
# Keep the saved marker and attempt evidence before any file-lock wait.
|
||||
write_record(root / 'project-save-pending.json', dict(checkpoint, project_commit_pending=proof))
|
||||
proof = bind_project_commit_source(proof, self.root, root, project,
|
||||
stop_event=self.stop_event, release_mentor=self._release_saved_source_owner if saved_only else None)
|
||||
checkpoint['project_commit_source'] = proof
|
||||
write_record(root / 'project-checkpoint.json', checkpoint)
|
||||
self.record['checkpoints'][key] = attempt_id
|
||||
self._save()
|
||||
self._active_attempts = []
|
||||
|
||||
def _release_saved_source_owner(self, error):
|
||||
"""Only a closed project's read handoff may recycle an idle CAD here."""
|
||||
try:
|
||||
self.close(rebuilding=True, reason='saved_source_locked')
|
||||
except Exception as cleanup:
|
||||
self.record['primary_error'] = {'type': type(error).__name__, 'code': error.code, 'message': str(error)}
|
||||
try:
|
||||
self._save()
|
||||
except Exception as diagnostic:
|
||||
error.add_note('资源收尾记录写入失败:' + str(diagnostic))
|
||||
raise BatchResourceCleanupError(str(cleanup), primary_error=error, cleanup_error=cleanup) from cleanup
|
||||
self.desktop = self.cad = None
|
||||
|
||||
def _certify_unlaunched_worker(self, root, project, command, attempt_id, expected, before, inputs, *, failure=None,
|
||||
worker_creation_rejected=False):
|
||||
"""Certify no worker was created, using exact launch and release provenance."""
|
||||
|
||||
@@ -20,7 +20,7 @@ class ExecutionFeedback:
|
||||
|
||||
|
||||
def wait_reason_for_stage(stage):
|
||||
return {'save_and_close': 'save', 'verify_saved_project': 'readback',
|
||||
return {'save_and_close': 'save', 'verify_saved_project': 'readback', 'saved_source_wait': 'readback',
|
||||
'native_snapshot_read': 'readback', 'capture_semantic_state': 'readback',
|
||||
'private_shutdown': 'desktop_release',
|
||||
'awaiting_reconciliation': 'reconciliation', 'mentor_exit': 'mentor_exit',
|
||||
|
||||
@@ -160,18 +160,11 @@ def capture_project_commit(data_root, root, commit):
|
||||
raise TaskCenterError('quick_run_uncertain', '工程统一保存或回读尚未得到完整证明,保留全部暂存项待核验。') from error
|
||||
|
||||
|
||||
def bind_project_commit_source(proof, data_root, root, project):
|
||||
def bind_project_commit_source(proof, data_root, root, project, *, stop_event=None, release_mentor=None):
|
||||
"""Capture saved bytes only at the completed native-close callback."""
|
||||
from .project_session_health import _source_parameters, _source_digest
|
||||
from .project_isolation import write_sources
|
||||
value = dict(proof, **_source_parameters(Path(project), data_root))
|
||||
value['source_sha256'] = _source_digest(value)
|
||||
value['command_sha256'] = hashlib.sha256(internal_path(root / 'command.tsv').read_bytes()).hexdigest()
|
||||
value['saved_sources'] = {source: hashlib.sha256(internal_path(source).read_bytes()).hexdigest()
|
||||
for source in write_sources(project)}
|
||||
if not value['source_sha256']:
|
||||
raise TaskCenterError('quick_run_uncertain', '已保存工程源文件无法稳定绑定,保留待核验。')
|
||||
return value
|
||||
from .saved_source import bind_sources
|
||||
return bind_sources(proof, data_root, root, project,
|
||||
stop_event=stop_event, release_mentor=release_mentor)
|
||||
|
||||
|
||||
def validate_project_commit_source(proof, root):
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Read-only Restart Manager observations; never shut down registered applications."""
|
||||
import ctypes
|
||||
from ctypes import wintypes as w
|
||||
import os
|
||||
|
||||
from .path_access import strip_extended_prefix
|
||||
|
||||
|
||||
def locking_processes(path):
|
||||
result = dict(method='windows_restart_manager', processes=[], complete=False)
|
||||
if os.name != 'nt':
|
||||
return dict(result, error='unsupported platform')
|
||||
class UniqueProcess(ctypes.Structure):
|
||||
_fields_ = [('pid', w.DWORD), ('started', w.FILETIME)]
|
||||
class ProcessInfo(ctypes.Structure):
|
||||
_fields_ = [('process', UniqueProcess), ('name', w.WCHAR*256), ('service', w.WCHAR*64),
|
||||
('type', ctypes.c_int), ('status', w.ULONG), ('session', w.DWORD), ('restartable', w.BOOL)]
|
||||
session = w.DWORD()
|
||||
api = ctypes.WinDLL('rstrtmgr')
|
||||
api.RmStartSession.argtypes = [ctypes.POINTER(w.DWORD), w.DWORD, w.LPWSTR]
|
||||
api.RmRegisterResources.argtypes = [w.DWORD, w.UINT, ctypes.POINTER(w.LPCWSTR), w.UINT,
|
||||
ctypes.POINTER(UniqueProcess), w.UINT, ctypes.POINTER(w.LPCWSTR)]
|
||||
api.RmGetList.argtypes = [w.DWORD, ctypes.POINTER(w.UINT), ctypes.POINTER(w.UINT),
|
||||
ctypes.POINTER(ProcessInfo), ctypes.POINTER(w.DWORD)]
|
||||
api.RmEndSession.argtypes = [w.DWORD]
|
||||
started = False
|
||||
try:
|
||||
code = api.RmStartSession(ctypes.byref(session), 0, ctypes.create_unicode_buffer(33))
|
||||
if code: raise OSError(code, 'RmStartSession')
|
||||
started = True
|
||||
files = (w.LPCWSTR*1)(strip_extended_prefix(path))
|
||||
code = api.RmRegisterResources(session, 1, files, 0, None, 0, None)
|
||||
if code: raise OSError(code, 'RmRegisterResources')
|
||||
needed, count, reboot = w.UINT(), w.UINT(), w.DWORD()
|
||||
code = api.RmGetList(session, ctypes.byref(needed), ctypes.byref(count), None, ctypes.byref(reboot))
|
||||
for _ in range(3):
|
||||
if code != 234: break # ERROR_MORE_DATA
|
||||
count.value = needed.value
|
||||
items = (ProcessInfo*count.value)()
|
||||
code = api.RmGetList(session, ctypes.byref(needed), ctypes.byref(count), items, ctypes.byref(reboot))
|
||||
if code == 0:
|
||||
result['processes'] = [dict(pid=item.process.pid, name=item.name,
|
||||
creation_filetime=(item.process.started.dwHighDateTime << 32) | item.process.started.dwLowDateTime)
|
||||
for item in items[:count.value]]
|
||||
if code: raise OSError(code, 'RmGetList')
|
||||
result['complete'] = True # Complete RM result, not an exhaustive kernel-handle scan.
|
||||
except Exception as error:
|
||||
result['error'] = str(error)
|
||||
finally:
|
||||
if started: api.RmEndSession(session)
|
||||
return result
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Read saved sources after native close, retrying only actual Windows locks."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .file_lock_diagnostics import locking_processes
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
LOCK_WAIT_SECONDS = 3.0
|
||||
|
||||
|
||||
class SavedSourceReadError(TaskCenterError):
|
||||
def __init__(self, error, path, *, interrupted=False):
|
||||
self.winerror = getattr(error, 'winerror', None)
|
||||
self.path = str(path)
|
||||
self.retryable = self.winerror in (32, 33)
|
||||
self.interrupted = interrupted
|
||||
reason = '核验已暂停' if interrupted else '数据库仍被占用' if self.retryable else '源文件读取失败'
|
||||
super().__init__('saved_source_pending',
|
||||
f'工程已返回保存,{reason},结果待核验;不会重复替换。文件:{path};Windows 错误码:{self.winerror};{error}')
|
||||
|
||||
|
||||
def source_hash(path):
|
||||
"""Retain CreateFile's error code; Python open can reduce sharing errors to EACCES."""
|
||||
path = internal_path(path)
|
||||
if os.name != 'nt':
|
||||
with path.open('rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
import msvcrt
|
||||
import pywintypes
|
||||
import win32file
|
||||
try:
|
||||
# Match the CRT reads used by subsequent source validation.
|
||||
handle = win32file.CreateFile(str(path), 0x80000000, 3, None, 3, 0, None)
|
||||
except pywintypes.error as error:
|
||||
failure = OSError(error.winerror, error.strerror, str(path))
|
||||
failure.winerror = error.winerror
|
||||
raise failure from error
|
||||
try:
|
||||
fd = msvcrt.open_osfhandle(int(handle), os.O_RDONLY | os.O_BINARY)
|
||||
handle.Detach() # The file descriptor now owns this handle.
|
||||
finally:
|
||||
handle.Close()
|
||||
with os.fdopen(fd, 'rb') as stream:
|
||||
return hashlib.file_digest(stream, 'sha256').hexdigest()
|
||||
|
||||
|
||||
def bind_sources(proof, data_root, root, project, *, stop_event=None, release_mentor=None):
|
||||
from .batch_resources import write_record
|
||||
from .operation_diagnostics import record_operation
|
||||
from .project_session_health import _source_parameters, _source_digest
|
||||
from .project_isolation import write_sources
|
||||
from .worker_monitor import _publish_progress
|
||||
root = Path(root)
|
||||
parameters = _source_parameters(Path(project), data_root)
|
||||
started = time.monotonic()
|
||||
deadline = started + LOCK_WAIT_SECONDS
|
||||
status = dict(session_token=proof.get('session_token'), project_path=str(project),
|
||||
replacement_replayed=False, mentor_released_for_read=False)
|
||||
try:
|
||||
prior = json.loads(internal_path(root / 'saved-source-status.json').read_text(encoding='utf-8'))
|
||||
if (proof.get('session_token') and prior.get('session_token') == proof['session_token']
|
||||
and prior.get('project_path', '').casefold() == str(project).casefold()):
|
||||
status.update({key: prior[key] for key in ('first_error', 'last_error', 'lock_observation') if key in prior})
|
||||
status['mentor_released_for_read'] = prior.get('mentor_released_for_read') is True
|
||||
except (OSError, ValueError, AttributeError, TypeError):
|
||||
pass # Historical diagnostics never authorize a saved result.
|
||||
last_lock = None
|
||||
observed = False
|
||||
released_this_call = False
|
||||
|
||||
def publish(state, error=None):
|
||||
status.update(state=state, elapsed_seconds=time.monotonic()-started)
|
||||
if error is not None:
|
||||
status['last_error'] = dict(path=getattr(error, 'path', str(project)),
|
||||
winerror=getattr(error, 'winerror', None), message=str(error))
|
||||
status.setdefault('first_error', status['last_error'])
|
||||
write_record(root / 'saved-source-status.json', status)
|
||||
try:
|
||||
progress = json.loads(internal_path(root / 'worker-progress.json').read_text(encoding='utf-8'))
|
||||
except (OSError, ValueError):
|
||||
progress = {}
|
||||
if not isinstance(progress, dict) or type(progress.get('sequence', 0)) is not int:
|
||||
progress = {}
|
||||
progress.update(stage='saved_source_wait' if state in {'waiting', 'releasing_mentor'} else
|
||||
'awaiting_reconciliation' if state == 'pending' else 'verify_saved_project',
|
||||
wait_reason='readback', waiting_for_safe_completion=False,
|
||||
sequence=progress.get('sequence', 0)+1, stage_seconds={})
|
||||
if state == 'pending': progress['primary_error'] = str(error)
|
||||
_publish_progress(internal_path(root / 'worker-progress.json'), progress)
|
||||
|
||||
def publish_read(state, error):
|
||||
try:
|
||||
publish(state, error)
|
||||
except Exception as diagnostic:
|
||||
error.add_note('保存源文件交接状态记录失败:' + str(diagnostic))
|
||||
raise error from diagnostic
|
||||
|
||||
def check_paused():
|
||||
if last_lock is not None and stop_event is not None and stop_event.is_set():
|
||||
raise SavedSourceReadError(last_lock[0], last_lock[1], interrupted=True) from last_lock[0]
|
||||
|
||||
record_operation(root, 'saved_source_bind', 'enter', item_id=proof.get('session_token', ''))
|
||||
try:
|
||||
while True:
|
||||
check_paused()
|
||||
path = project
|
||||
try:
|
||||
before = _source_digest(parameters)
|
||||
hashes = {}
|
||||
for path in sorted(write_sources(project)):
|
||||
hashes[path] = source_hash(path)
|
||||
if not before or before != _source_digest(parameters):
|
||||
raise TaskCenterError('saved_source_changed', '保存后的源文件仍在变化,结果待核验;不会重复替换。')
|
||||
value = dict(proof, **parameters, source_sha256=before, saved_sources=hashes,
|
||||
command_sha256=hashlib.sha256(internal_path(root / 'command.tsv').read_bytes()).hexdigest())
|
||||
check_paused()
|
||||
publish('bound')
|
||||
record_operation(root, 'saved_source_bind', 'return', item_id=proof.get('session_token', ''))
|
||||
return value
|
||||
except OSError as failure:
|
||||
error = SavedSourceReadError(failure, path)
|
||||
stopped = stop_event is not None and stop_event.is_set()
|
||||
if stopped:
|
||||
raise SavedSourceReadError(failure, path, interrupted=True) from failure
|
||||
if not error.retryable:
|
||||
raise error from failure
|
||||
last_lock = failure, path
|
||||
if not observed:
|
||||
publish_read('waiting', error)
|
||||
status['lock_observation'] = locking_processes(path)
|
||||
observed = True
|
||||
continue # The lock may have disappeared during this diagnostic.
|
||||
if time.monotonic() >= deadline:
|
||||
if release_mentor is None or released_this_call:
|
||||
raise error from failure
|
||||
publish_read('releasing_mentor', error)
|
||||
check_paused()
|
||||
release_mentor(error)
|
||||
released_this_call = True
|
||||
status['mentor_released_for_read'] = True
|
||||
deadline = time.monotonic() + LOCK_WAIT_SECONDS
|
||||
else:
|
||||
if status.get('state') != 'waiting': publish_read('waiting', error)
|
||||
time.sleep(.05)
|
||||
except Exception as error:
|
||||
record_operation(root, 'saved_source_bind', 'error', item_id=proof.get('session_token', ''), error=str(error))
|
||||
try:
|
||||
publish('pending', error)
|
||||
except Exception as diagnostic:
|
||||
error.add_note('保存源文件交接状态记录失败:' + str(diagnostic))
|
||||
raise
|
||||
@@ -16,6 +16,7 @@ STAGES = {
|
||||
'restore_attribute_fields': '恢复属性字段', 'restore_attributes': '恢复属性',
|
||||
'verify_restoration': '核验恢复结果', 'verify_attribute_fields': '核验属性字段',
|
||||
'save_and_close': '保存并关闭工程', 'verify_saved_project': '回读工程并核对',
|
||||
'saved_source_wait': '工程已保存,等待数据库释放后核验',
|
||||
'awaiting_reconciliation': '当前结果待核验,已保留工程现场',
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def locked(code=32):
|
||||
error = PermissionError('database is busy')
|
||||
error.winerror = code
|
||||
return error
|
||||
|
||||
|
||||
def inputs(tmp_path):
|
||||
project = tmp_path / 'project/test.prj'
|
||||
project.parent.mkdir()
|
||||
project.write_text('KEY iCDBDir "database"\n')
|
||||
database = project.parent / 'database/icdb.dat'
|
||||
database.parent.mkdir()
|
||||
database.write_bytes(b'saved database')
|
||||
root = tmp_path / 'data/quick-run'
|
||||
root.mkdir(parents=True)
|
||||
(root / 'command.tsv').write_text('frozen command')
|
||||
return project, database, root
|
||||
|
||||
|
||||
def test_transient_sharing_conflict_retries_reads_and_preserves_saved_marker(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import saved_source
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
original = saved_source.source_hash
|
||||
failures = []
|
||||
def read(path):
|
||||
if Path(path).name == 'icdb.dat' and not failures:
|
||||
failures.append(True)
|
||||
raise locked()
|
||||
return original(path)
|
||||
monkeypatch.setattr(saved_source, 'source_hash', read)
|
||||
monkeypatch.setattr(saved_source.time, 'sleep', lambda _: None)
|
||||
proof = bind_project_commit_source({'session_token': 'a'*32}, root.parent, root, project)
|
||||
assert len(proof['saved_sources']) == 2
|
||||
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
|
||||
assert status['state'] == 'bound' and status['session_token'] == 'a'*32
|
||||
assert status['first_error']['winerror'] == 32
|
||||
assert status['replacement_replayed'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('code', [5, 2])
|
||||
def test_non_lock_errors_fail_immediately_with_exact_native_code(tmp_path, monkeypatch, code):
|
||||
from dx_productivity.trial_task_center import saved_source
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
calls = []
|
||||
def denied(path):
|
||||
calls.append(path)
|
||||
raise locked(code)
|
||||
monkeypatch.setattr(saved_source, 'source_hash', denied)
|
||||
monkeypatch.setattr(saved_source.time, 'sleep', lambda _: pytest.fail('non-lock error retried'))
|
||||
with pytest.raises(saved_source.SavedSourceReadError) as caught:
|
||||
bind_project_commit_source({}, root.parent, root, project)
|
||||
assert caught.value.winerror == code and not caught.value.retryable
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_pause_during_lock_wait_keeps_pending_save_without_fallback(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import saved_source
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
stop = Event()
|
||||
monkeypatch.setattr(saved_source, 'source_hash', lambda _: (_ for _ in ()).throw(locked()))
|
||||
monkeypatch.setattr(saved_source.time, 'sleep', lambda _: stop.set())
|
||||
with pytest.raises(saved_source.SavedSourceReadError) as caught:
|
||||
bind_project_commit_source({}, root.parent, root, project, stop_event=stop)
|
||||
assert caught.value.code == 'saved_source_pending' and caught.value.interrupted
|
||||
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
|
||||
assert status['state'] == 'pending' and status['replacement_replayed'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('next_project', [False, True])
|
||||
def test_persistent_lock_recycles_only_after_closed_checkpoint_then_binds_without_replay(tmp_path, monkeypatch, next_project):
|
||||
from dx_productivity.trial_task_center import saved_source
|
||||
from dx_productivity.trial_task_center.execution_proof import validate_project_commit_source
|
||||
from test_batch_runtime import command_for, worker_runtime
|
||||
import subprocess
|
||||
command, project = command_for(tmp_path)
|
||||
root = Path(command[3])
|
||||
token = 'a'*32
|
||||
(root / 'project-session.request').write_text(f'{token}\t{project}\tjob')
|
||||
calls = []
|
||||
def monitor(launch, *args, **kwargs):
|
||||
calls.append('replace')
|
||||
if Path(launch[3]) == root:
|
||||
(root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_saved\njob\tno_match\n')
|
||||
return subprocess.CompletedProcess(launch, 0, '', '')
|
||||
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
|
||||
original = saved_source.source_hash
|
||||
def read(path):
|
||||
if runtime.cad is not None:
|
||||
raise locked()
|
||||
return original(path)
|
||||
monkeypatch.setattr(saved_source, 'source_hash', read)
|
||||
monkeypatch.setattr(saved_source, 'LOCK_WAIT_SECONDS', 0)
|
||||
with runtime:
|
||||
runtime.run_worker(command, 5)
|
||||
proof = json.loads((root / 'project-checkpoint.json').read_text(encoding='utf-8'))['project_commit_source']
|
||||
assert validate_project_commit_source(proof, root)
|
||||
assert runtime.cad is None and runtime.desktop is None
|
||||
if next_project:
|
||||
next_command, _ = command_for(tmp_path, 'two')
|
||||
runtime.run_worker(next_command, 5)
|
||||
assert runtime.generation == 2 and runtime.cad is not None
|
||||
assert calls == ['replace'] * (2 if next_project else 1)
|
||||
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
|
||||
assert status['state'] == 'bound' and status['mentor_released_for_read'] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize('nested', [False, True])
|
||||
def test_cleanup_message_keeps_primary_saved_read_failure_visible(nested):
|
||||
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
primary = TaskCenterError('saved_source_pending', '已保存,数据库持续占用,等待核验')
|
||||
if nested: primary = BatchResourceCleanupError('第一次释放异常', primary_error=primary)
|
||||
error = BatchResourceCleanupError('释放仍有异常', primary_error=primary)
|
||||
assert '已保存,数据库持续占用,等待核验' in error.message and '释放仍有异常' in error.message
|
||||
|
||||
|
||||
def test_sources_changing_during_binding_remain_unverified(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import saved_source
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
project, database, root = inputs(tmp_path)
|
||||
original = saved_source.source_hash
|
||||
def read(path):
|
||||
digest = original(path)
|
||||
if Path(path).name == 'icdb.dat': database.write_bytes(b'changed while reading')
|
||||
return digest
|
||||
monkeypatch.setattr(saved_source, 'source_hash', read)
|
||||
with pytest.raises(TaskCenterError, match='saved_source_changed'):
|
||||
bind_project_commit_source({}, root.parent, root, project)
|
||||
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
|
||||
assert status['state'] == 'pending'
|
||||
assert 'saved_source_changed' in status['last_error']['message']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('code', [5, 32])
|
||||
def test_diagnostic_write_failure_never_replaces_original_read_error(tmp_path, monkeypatch, code):
|
||||
from dx_productivity.trial_task_center import saved_source, batch_resources
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
monkeypatch.setattr(saved_source, 'source_hash', lambda _: (_ for _ in ()).throw(locked(code)))
|
||||
monkeypatch.setattr(batch_resources, 'write_record', lambda *a: (_ for _ in ()).throw(OSError('disk full')))
|
||||
with pytest.raises(saved_source.SavedSourceReadError) as caught:
|
||||
bind_project_commit_source({}, root.parent, root, project)
|
||||
assert caught.value.winerror == code
|
||||
|
||||
|
||||
@pytest.mark.skipif(__import__('os').name != 'nt', reason='Windows delete sharing')
|
||||
def test_native_hash_uses_same_sharing_as_later_source_validation(tmp_path):
|
||||
import win32file
|
||||
from dx_productivity.trial_task_center.saved_source import source_hash
|
||||
project, database, root = inputs(tmp_path)
|
||||
handle = win32file.CreateFile(str(database), 0x10000, 7, None, 3, 0, None)
|
||||
try:
|
||||
with pytest.raises(OSError) as caught:
|
||||
source_hash(database)
|
||||
assert caught.value.winerror == 32
|
||||
finally:
|
||||
handle.Close()
|
||||
assert source_hash(database)
|
||||
|
||||
|
||||
def test_lock_released_during_diagnostics_is_rechecked_before_recycling(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import saved_source
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
original = saved_source.source_hash
|
||||
released = []
|
||||
def read(path):
|
||||
if not released: raise locked()
|
||||
return original(path)
|
||||
def observe(path):
|
||||
released.append(True)
|
||||
return {'processes': [], 'complete': True}
|
||||
monkeypatch.setattr(saved_source, 'source_hash', read)
|
||||
monkeypatch.setattr(saved_source, 'locking_processes', observe)
|
||||
monkeypatch.setattr(saved_source, 'LOCK_WAIT_SECONDS', 0)
|
||||
bind_project_commit_source({}, root.parent, root, project,
|
||||
release_mentor=lambda _: pytest.fail('recycled CAD using stale lock observation'))
|
||||
|
||||
|
||||
def test_pause_arriving_during_diagnostics_keeps_saved_result_pending(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import saved_source
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
original = saved_source.source_hash
|
||||
stop = Event()
|
||||
def read(path):
|
||||
if not stop.is_set(): raise locked()
|
||||
return original(path)
|
||||
def observe(path):
|
||||
stop.set()
|
||||
return {'processes': [], 'complete': True}
|
||||
monkeypatch.setattr(saved_source, 'source_hash', read)
|
||||
monkeypatch.setattr(saved_source, 'locking_processes', observe)
|
||||
with pytest.raises(saved_source.SavedSourceReadError) as caught:
|
||||
bind_project_commit_source({}, root.parent, root, project, stop_event=stop,
|
||||
release_mentor=lambda _: pytest.fail('pause recycled CAD'))
|
||||
assert caught.value.interrupted
|
||||
|
||||
|
||||
def test_journal_failure_during_owner_release_preserves_both_errors(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center.saved_source import SavedSourceReadError
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
|
||||
runtime = BatchCadRuntime(tmp_path / 'data', 'execution')
|
||||
primary = SavedSourceReadError(locked(), 'icdb.dat')
|
||||
cleanup = BatchResourceCleanupError('quit uncertain')
|
||||
monkeypatch.setattr(runtime, 'close', lambda **k: (_ for _ in ()).throw(cleanup))
|
||||
monkeypatch.setattr(runtime, '_save', lambda **k: (_ for _ in ()).throw(OSError('journal full')))
|
||||
with pytest.raises(BatchResourceCleanupError) as caught:
|
||||
runtime._release_saved_source_owner(primary)
|
||||
assert caught.value.primary_error is primary and caught.value.cleanup_error is cleanup
|
||||
|
||||
|
||||
@pytest.mark.parametrize('progress', [[], {'sequence': 'partial'}])
|
||||
def test_bad_optional_progress_does_not_block_saved_source_binding(tmp_path, progress):
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
(root / 'worker-progress.json').write_text(json.dumps(progress), encoding='utf-8')
|
||||
assert bind_project_commit_source({}, root.parent, root, project)['saved_sources']
|
||||
|
||||
|
||||
def test_pause_after_release_notice_never_starts_cad_recycling(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import saved_source, batch_resources
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
stop = Event()
|
||||
original = batch_resources.write_record
|
||||
def write(path, record):
|
||||
original(path, record)
|
||||
if record.get('state') == 'releasing_mentor': stop.set()
|
||||
monkeypatch.setattr(batch_resources, 'write_record', write)
|
||||
monkeypatch.setattr(saved_source, 'source_hash', lambda _: (_ for _ in ()).throw(locked()))
|
||||
monkeypatch.setattr(saved_source, 'locking_processes', lambda _: {'processes': []})
|
||||
monkeypatch.setattr(saved_source, 'LOCK_WAIT_SECONDS', 0)
|
||||
with pytest.raises(saved_source.SavedSourceReadError) as caught:
|
||||
bind_project_commit_source({}, root.parent, root, project, stop_event=stop,
|
||||
release_mentor=lambda _: pytest.fail('pause recycled CAD after release notice'))
|
||||
assert caught.value.interrupted
|
||||
|
||||
|
||||
def test_rebinding_same_saved_prefix_preserves_first_handoff_diagnostics(tmp_path):
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
prior = dict(session_token='c'*32, project_path=str(project).upper(),
|
||||
first_error={'winerror': 32, 'message': 'original lock'},
|
||||
mentor_released_for_read=True, lock_observation={'processes': [{'pid': 123}]})
|
||||
(root / 'saved-source-status.json').write_text(json.dumps(prior), encoding='utf-8')
|
||||
bind_project_commit_source({'session_token': 'c'*32}, root.parent, root, project)
|
||||
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
|
||||
assert status['state'] == 'bound' and status['mentor_released_for_read'] is True
|
||||
assert status['first_error'] == prior['first_error']
|
||||
assert status['lock_observation'] == prior['lock_observation']
|
||||
bind_project_commit_source({'session_token': 'd'*32}, root.parent, root, project)
|
||||
status = json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))
|
||||
assert 'first_error' not in status and status['mentor_released_for_read'] is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize('forced', [False, True])
|
||||
def test_owner_exit_failure_or_external_lock_never_replays_or_publishes_checkpoint(tmp_path, monkeypatch, forced):
|
||||
from dx_productivity.trial_task_center import saved_source
|
||||
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
|
||||
from test_batch_runtime import command_for, worker_runtime
|
||||
import subprocess
|
||||
command, project = command_for(tmp_path)
|
||||
root = Path(command[3]); token = 'b'*32
|
||||
(root / 'project-session.request').write_text(f'{token}\t{project}\tjob')
|
||||
calls = []
|
||||
def monitor(*a, **k):
|
||||
calls.append('replace')
|
||||
(root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_saved\njob\tno_match\n')
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
|
||||
monkeypatch.setattr(saved_source, 'source_hash', lambda _: (_ for _ in ()).throw(locked()))
|
||||
monkeypatch.setattr(saved_source, 'LOCK_WAIT_SECONDS', 0)
|
||||
if forced:
|
||||
original_close = runtime.close
|
||||
def close(**options):
|
||||
original_close(**options)
|
||||
raise BatchResourceCleanupError('forced termination was required')
|
||||
monkeypatch.setattr(runtime, 'close', close)
|
||||
try:
|
||||
runtime.run_worker(command, 5)
|
||||
pytest.fail('persistent lock or forced cleanup admitted verification')
|
||||
except (saved_source.SavedSourceReadError, BatchResourceCleanupError):
|
||||
assert not (root / 'project-checkpoint.json').exists()
|
||||
pending = json.loads((root / 'project-save-pending.json').read_text(encoding='utf-8'))
|
||||
assert pending['project_commit_pending']['jobs'] == ['job']
|
||||
assert json.loads((root / 'saved-source-status.json').read_text(encoding='utf-8'))['state'] == 'pending'
|
||||
assert calls == ['replace']
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Exercise saved-source handoff using real Windows file locks on synthetic files."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from threading import Event, Thread
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
|
||||
|
||||
from dx_productivity.trial_task_center import saved_source
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
|
||||
|
||||
HOLDER = ('import win32file,sys;h=win32file.CreateFile(sys.argv[1],0x80000000,0,None,3,0,None);'
|
||||
'print("locked",flush=True);sys.stdin.readline();h.Close()')
|
||||
|
||||
|
||||
def probe(root, cycles):
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
started = time.perf_counter()
|
||||
report = dict(passed=False, cad_started=False, samples=[])
|
||||
saved_source.LOCK_WAIT_SECONDS = .3
|
||||
try:
|
||||
for index in range(cycles):
|
||||
mode = ('transient', 'release_then_read', 'persistent_external', 'pause', 'missing')[index % 5]
|
||||
folder = root / f'{index:02d}-{mode}'
|
||||
folder.mkdir()
|
||||
project = folder / 'test.prj'
|
||||
project.write_text('KEY iCDBDir "database"\n')
|
||||
database = folder / 'database/icdb.dat'
|
||||
database.parent.mkdir()
|
||||
database.write_bytes(b'synthetic saved source')
|
||||
evidence = folder / 'data/quick-run'
|
||||
evidence.mkdir(parents=True)
|
||||
(evidence / 'command.tsv').write_text('immutable synthetic command')
|
||||
stop = Event()
|
||||
holder = thread = None
|
||||
failures = []
|
||||
releases = []
|
||||
sample = dict(mode=mode, passed=False)
|
||||
try:
|
||||
if mode == 'missing':
|
||||
database.unlink()
|
||||
else:
|
||||
holder = subprocess.Popen([sys.executable, '-u', '-c', HOLDER, str(database)],
|
||||
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
text=True, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
assert holder.stdout.readline().strip() == 'locked'
|
||||
try:
|
||||
saved_source.source_hash(database)
|
||||
raise AssertionError('exclusive file lock admitted a reader')
|
||||
except OSError as error:
|
||||
assert error.winerror == 32
|
||||
observation = saved_source.locking_processes(database)
|
||||
assert any(p['pid'] == holder.pid for p in observation['processes']), observation
|
||||
sample['observed_holder'] = observation
|
||||
|
||||
def release():
|
||||
if holder is not None and holder.poll() is None:
|
||||
holder.stdin.write('release\n'); holder.stdin.flush()
|
||||
assert holder.wait(timeout=5) == 0
|
||||
|
||||
def after_wait():
|
||||
deadline = time.monotonic() + 10
|
||||
try:
|
||||
while time.monotonic() < deadline:
|
||||
path = evidence / 'saved-source-status.json'
|
||||
if path.is_file() and json.loads(path.read_text(encoding='utf-8'))['state'] == 'waiting':
|
||||
if mode == 'pause': stop.set()
|
||||
else: release()
|
||||
return
|
||||
time.sleep(.01)
|
||||
raise AssertionError('did not reach saved-source wait')
|
||||
except Exception as error:
|
||||
failures.append(str(error))
|
||||
|
||||
if mode in ('transient', 'pause'):
|
||||
thread = Thread(target=after_wait)
|
||||
thread.start()
|
||||
|
||||
def release_owner(error):
|
||||
releases.append(error.winerror)
|
||||
if mode == 'release_then_read': release()
|
||||
|
||||
try:
|
||||
proof = bind_project_commit_source(dict(session_token=f'{index:032x}'), evidence.parent,
|
||||
evidence, project, stop_event=stop, release_mentor=release_owner)
|
||||
assert mode in ('transient', 'release_then_read')
|
||||
assert proof['saved_sources'][str(database.resolve()).casefold()] == hashlib.sha256(database.read_bytes()).hexdigest()
|
||||
except saved_source.SavedSourceReadError as error:
|
||||
assert mode in ('persistent_external', 'pause', 'missing'), str(error)
|
||||
assert error.winerror == (2 if mode == 'missing' else 32)
|
||||
assert error.interrupted == (mode == 'pause')
|
||||
sample['pending_code'] = error.code
|
||||
if thread is not None:
|
||||
thread.join(timeout=12)
|
||||
assert not thread.is_alive() and not failures, failures
|
||||
assert releases == ([32] if mode in ('release_then_read', 'persistent_external') else [])
|
||||
status = json.loads((evidence / 'saved-source-status.json').read_text(encoding='utf-8'))
|
||||
assert status['replacement_replayed'] is False
|
||||
sample.update(passed=True, state=status['state'], release_requests=len(releases))
|
||||
finally:
|
||||
if holder is not None:
|
||||
release()
|
||||
for stream in (holder.stdin, holder.stdout, holder.stderr): stream.close()
|
||||
if thread is not None: thread.join(timeout=12)
|
||||
report['samples'].append(sample)
|
||||
report['passed'] = all(sample['passed'] for sample in report['samples'])
|
||||
finally:
|
||||
report['seconds'] = time.perf_counter()-started
|
||||
(root / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print(json.dumps(dict(passed=report['passed'], samples=len(report['samples']), seconds=report['seconds'])))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
parser.add_argument('--cycles', type=int, default=20)
|
||||
args = parser.parse_args()
|
||||
probe(args.output.resolve(), args.cycles)
|
||||
Reference in new issue
Block a user