feat-ui-operation-history-and-durable-execution
Core regression / Python core and release configuration (push) Successful in 17s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s
Core regression / Python core and release configuration (push) Successful in 17s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s
This commit is contained in:
1 parent
4874c7e95a
commit
cf90ced825
44 files changed
+3165
-92
No files matched your search
@@ -31,6 +31,7 @@ class BatchRunResult:
|
||||
last_result: QuickRunStepResult | None = None
|
||||
item_messages: tuple[str, ...] = ()
|
||||
unbacked_project_paths: tuple[Path, ...] = ()
|
||||
safe_failure: bool = False
|
||||
|
||||
|
||||
def execute_batch(
|
||||
@@ -44,6 +45,9 @@ def execute_batch(
|
||||
runtime=None,
|
||||
) -> BatchRunResult:
|
||||
preparer = service._quick_run_preparer
|
||||
journal = getattr(preparer, 'journal', None)
|
||||
if (journal is not None and journal.requires_retry(task_id)) or service._retryable_quick_run(task_id):
|
||||
raise TaskCenterError('quick_run_retry_required', '本工程有失败项,普通继续不会重试;请准备失败项重试。')
|
||||
retention = maintain_quick_run_storage(preparer.data_root)
|
||||
if retention.removed_entries or retention.skipped_entries:
|
||||
service._logging.logger.info(
|
||||
@@ -54,6 +58,7 @@ def execute_batch(
|
||||
task = service._store.get_task(task_id)
|
||||
projects = service._store.list_projects(task_id)
|
||||
rules = service._execution_rules(task_id)
|
||||
preparer.reconcile_terminal_receipts(task_id)
|
||||
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=task.copy_part_number_to_value)
|
||||
mode = 'part_label' if task.copy_part_number_to_value else 'preserve'
|
||||
actual = (str(progress.next_project_path), progress.next_old_part_number, progress.next_new_part_number, mode)
|
||||
@@ -195,6 +200,14 @@ def execute_batch(
|
||||
service._logging.logger.info('quick_run_batch_item task_id=%s state=%s completed=%s total=%s',
|
||||
task_id, last_result.state, updated.completed_items, updated.total_items)
|
||||
progress = updated
|
||||
if task.primary_project_id and last_result.state in {BATCH_FAILED_STATE, 'batch_skipped'}:
|
||||
# execute_step has already rejected possible unverified native
|
||||
# mutation. Leave this engineering task's remaining work held,
|
||||
# but permit the outer serial queue to run the next project.
|
||||
backups.commit_prefetched(progress)
|
||||
service._record_safe_queue_failure(task_id,last_result.message)
|
||||
return BatchRunResult(progress, False, last_result, tuple(item_messages),
|
||||
tuple(backups.unbacked_project_paths), safe_failure=True)
|
||||
if last_result.state == BATCH_SAVED_UNVERIFIED_STATE:
|
||||
_write_uncertain_flag(preparer.data_root / 'quick-run/uncertain.flag',
|
||||
'saved_readback_unverified')
|
||||
|
||||
@@ -3,6 +3,7 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -16,6 +17,32 @@ _BACKUP_STATE_NAME = 'batch-backups.json'
|
||||
_BACKUP_DIRECTORY_NAME = 'batch-backups'
|
||||
|
||||
|
||||
def inherit_backup_for_retry(archive, root, task_id):
|
||||
"""Carry the verified original backup forward; never back up modified work as original."""
|
||||
if archive is None or not (archive / _BACKUP_STATE_NAME).is_file():
|
||||
return
|
||||
state = _read_backup_state(archive / _BACKUP_STATE_NAME, task_id)
|
||||
for key, entry in state.items():
|
||||
if entry.get('status') == 'backed_up' and not _reusable_backup(archive, key, entry):
|
||||
raise TaskCenterError('quick_run_backup_invalid', '原轮次备份不完整,不能准备重试。')
|
||||
from .quick_run import _read_commands
|
||||
eligible={_path_key(Path(row[2]).resolve(strict=False).parent)
|
||||
for row in _read_commands(root/'command.tsv')}
|
||||
state={key:entry for key,entry in state.items() if key in eligible}
|
||||
source = archive / _BACKUP_DIRECTORY_NAME
|
||||
if source.is_dir():
|
||||
destination = root / _BACKUP_DIRECTORY_NAME
|
||||
if destination.exists():
|
||||
raise TaskCenterError('quick_run_backup_invalid', '重试备份目标已存在,已停止以保留原证据。')
|
||||
temporary = root / f'.retry-backups-{uuid4().hex}'
|
||||
shutil.copytree(source, temporary)
|
||||
os.replace(temporary, destination)
|
||||
for key, entry in state.items():
|
||||
if entry.get('status') == 'backed_up' and not _reusable_backup(root, key, entry):
|
||||
raise TaskCenterError('quick_run_backup_invalid', '重试备份复制校验失败,原备份保留。')
|
||||
_write_backup_state(root / _BACKUP_STATE_NAME, task_id, state)
|
||||
|
||||
|
||||
class BatchBackupCoordinator:
|
||||
"""Publish backup outcomes on the queue thread before allowing CAD work.
|
||||
|
||||
|
||||
@@ -0,0 +1,342 @@
|
||||
"""Task-database receipts: display history is never execution authority."""
|
||||
from dataclasses import dataclass
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .history_store import HistoryRepository
|
||||
from .path_access import canonical_path, internal_path
|
||||
|
||||
_SUCCESS={'verified','no_match','restored'}
|
||||
_TERMINAL={'saved_ok','no_match','restored_ok','batch_failed','batch_saved_unverified','batch_skipped'}
|
||||
|
||||
|
||||
def create_execution_schema(connection):
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS execution_transitions (
|
||||
transition_id TEXT PRIMARY KEY, task_id TEXT NOT NULL)''')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS execution_baselines (
|
||||
task_id TEXT NOT NULL, round_id TEXT NOT NULL, project_path TEXT NOT NULL,
|
||||
schematic_name TEXT NOT NULL, sheet_number TEXT NOT NULL, baseline_json TEXT NOT NULL,
|
||||
PRIMARY KEY(task_id,round_id,project_path,schematic_name,sheet_number))''')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS execution_rounds (
|
||||
task_id TEXT PRIMARY KEY, round_id TEXT NOT NULL, plan_json TEXT NOT NULL DEFAULT '[]',
|
||||
retry_authorized INTEGER NOT NULL DEFAULT 0, pause_requested INTEGER NOT NULL DEFAULT 0)''')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS execution_operations (
|
||||
task_id TEXT NOT NULL, round_id TEXT NOT NULL, operation_key TEXT NOT NULL,
|
||||
command_json TEXT NOT NULL, state TEXT NOT NULL, attempt_id TEXT,
|
||||
generation INTEGER NOT NULL DEFAULT 0, receipt_json TEXT,
|
||||
PRIMARY KEY(task_id,round_id,operation_key))''')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS execution_target_claims (
|
||||
task_id TEXT NOT NULL, round_id TEXT NOT NULL, target_key TEXT NOT NULL,
|
||||
operation_key TEXT NOT NULL, PRIMARY KEY(task_id,round_id,target_key))''')
|
||||
|
||||
|
||||
def _json(value):
|
||||
return json.dumps(value,ensure_ascii=False,sort_keys=True,separators=(',',':'))
|
||||
|
||||
|
||||
def _hash(value):
|
||||
return hashlib.sha256(_json(value).encode('utf8')).hexdigest()
|
||||
|
||||
|
||||
def command_identity(row):
|
||||
values={key:str(value) for key,value in row.items() if key not in {'task_id','job_id'}}
|
||||
values['project_path']=str(canonical_path(values['project_path'])).casefold()
|
||||
for field,default in (('schematic_name',''),('sheet_number',''),('target_scope','all'),
|
||||
('target_selectors',''),('target_cell','')):
|
||||
values.setdefault(field,default)
|
||||
values['target_selectors']='\x1e'.join(sorted(values['target_selectors'].split('\x1e')))
|
||||
return values
|
||||
|
||||
|
||||
def _targets(command):
|
||||
if command['target_scope']!='targets':return ()
|
||||
return tuple(_hash([command['project_path'],command['schematic_name'],command['sheet_number'],
|
||||
selector.split('\x1f')[0]])
|
||||
for selector in command['target_selectors'].split('\x1e') if selector)
|
||||
|
||||
|
||||
def read_command_rows(path):
|
||||
from .quick_run import _decode_vbs_field
|
||||
with internal_path(path).open(encoding='utf-8-sig',newline='') as stream:
|
||||
return tuple({key:_decode_vbs_field(value) for key,value in row.items()}
|
||||
for row in csv.DictReader(stream,delimiter='\t'))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class JournalAttempt:
|
||||
task_id: str
|
||||
round_id: str
|
||||
operation_key: str
|
||||
attempt_id: str
|
||||
generation: int
|
||||
|
||||
|
||||
class ExecutionJournal:
|
||||
def __init__(self,store,progress_writer=None):
|
||||
self.store=store
|
||||
self.progress_writer=progress_writer
|
||||
|
||||
def _round(self,task_id,*,create=False):
|
||||
connection=self.store._connection
|
||||
row=connection.execute('SELECT * FROM execution_rounds WHERE task_id=?',(task_id,)).fetchone()
|
||||
if row is None and create:
|
||||
connection.execute('INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)',(task_id,uuid4().hex))
|
||||
row=connection.execute('SELECT * FROM execution_rounds WHERE task_id=?',(task_id,)).fetchone()
|
||||
return row
|
||||
|
||||
def start_round(self,task_id,round_id):
|
||||
with self.store.transaction():
|
||||
current=self._round(task_id)
|
||||
if current:
|
||||
unsafe=self.store._connection.execute('''SELECT 1 FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND state NOT IN ('verified','no_match','restored','superseded') LIMIT 1''',
|
||||
(task_id,current['round_id'])).fetchone()
|
||||
if unsafe:raise TaskCenterError('new_round_unverified','本轮尚未核验完成,不能重置执行回执。')
|
||||
self.store._connection.execute('''INSERT INTO execution_rounds(task_id,round_id) VALUES (?,?)
|
||||
ON CONFLICT(task_id) DO UPDATE SET round_id=excluded.round_id,plan_json='[]',
|
||||
retry_authorized=0,pause_requested=0''',(task_id,round_id))
|
||||
|
||||
def authorize_retry(self,task_id):
|
||||
with self.store.transaction():
|
||||
current=self._round(task_id)
|
||||
if current:
|
||||
unsafe=self.store._connection.execute('''SELECT 1 FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND state IN ('prepared','uncertain') LIMIT 1''',
|
||||
(task_id,current['round_id'])).fetchone()
|
||||
if unsafe:raise TaskCenterError('quick_run_uncertain','原执行项尚待核验,不能准备重试。')
|
||||
self.store._connection.execute('UPDATE execution_rounds SET retry_authorized=1 WHERE task_id=?',(task_id,))
|
||||
|
||||
def pause(self,task_id):
|
||||
with self.store.transaction():
|
||||
self.store._connection.execute('UPDATE execution_rounds SET pause_requested=1 WHERE task_id=?',(task_id,))
|
||||
|
||||
def requires_retry(self,task_id):
|
||||
with self.store._lock:
|
||||
current=self._round(task_id)
|
||||
return bool(current and not current['retry_authorized'] and self.store._connection.execute(
|
||||
"SELECT 1 FROM execution_operations WHERE task_id=? AND round_id=? AND state='failed' LIMIT 1",
|
||||
(task_id,current['round_id'])).fetchone())
|
||||
|
||||
def has_plan(self,task_id):
|
||||
with self.store._lock:
|
||||
current=self._round(task_id)
|
||||
return bool(current and json.loads(current['plan_json']))
|
||||
|
||||
def needs_reconciliation(self,task_id):
|
||||
with self.store._lock:
|
||||
current=self._round(task_id)
|
||||
return bool(current and self.store._connection.execute('''SELECT 1 FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND state='prepared' LIMIT 1''',
|
||||
(task_id,current['round_id'])).fetchone())
|
||||
|
||||
def unresolved_jobs(self,task_id,rows):
|
||||
with self.store._lock:
|
||||
current=self._round(task_id)
|
||||
if current is None:return ()
|
||||
keys={record[0] for record in self.store._connection.execute('''SELECT operation_key
|
||||
FROM execution_operations WHERE task_id=? AND round_id=? AND state IN ('prepared','uncertain')''',
|
||||
(task_id,current['round_id']))}
|
||||
return tuple(row['job_id'] for row in rows if _hash(command_identity(row)) in keys)
|
||||
|
||||
def assert_can_prepare(self,task_id):
|
||||
with self.store._lock:
|
||||
current=self._round(task_id)
|
||||
if current and json.loads(current['plan_json']) and not current['retry_authorized']:
|
||||
raise TaskCenterError('quick_run_pending','本轮已有冻结的执行记录,请继续原队列或核验恢复,不能重新准备覆盖。')
|
||||
|
||||
def bind(self,task_id,rows,latest,*,proof_reader=None):
|
||||
"""Freeze/reconcile identities; return authoritative outcomes keyed by new job ID."""
|
||||
identities=[command_identity(row) for row in rows]
|
||||
keys=[_hash(identity) for identity in identities]
|
||||
if not keys or len(keys)!=len(set(keys)):
|
||||
raise TaskCenterError('quick_run_uncertain','执行计划包含重复或空的逻辑项。')
|
||||
with self.store.transaction():
|
||||
current=self._round(task_id,create=True)
|
||||
round_id=current['round_id'];connection=self.store._connection
|
||||
prior=json.loads(current['plan_json']); retry=bool(current['retry_authorized'])
|
||||
if prior and prior!=keys and not retry:
|
||||
raise TaskCenterError('quick_run_uncertain','执行计划与本轮已保存回执不一致,请核验原范围。')
|
||||
restored={}
|
||||
for row,identity,key in zip(rows,identities,keys):
|
||||
for target in _targets(identity):
|
||||
claimed=connection.execute('''SELECT operation_key FROM execution_target_claims
|
||||
WHERE task_id=? AND round_id=? AND target_key=?''',(task_id,round_id,target)).fetchone()
|
||||
if claimed and claimed[0]!=key:
|
||||
raise TaskCenterError('quick_run_uncertain','该位号本轮已有完成回执,不能重新编组执行。')
|
||||
record=connection.execute('''SELECT * FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',(task_id,round_id,key)).fetchone()
|
||||
if record is None:
|
||||
if prior and retry and key not in prior:
|
||||
# A revision may only replace a known failed scope; it
|
||||
# cannot introduce fresh work under a retry authorization.
|
||||
scope=lambda item:tuple(item.get(name,'') for name in
|
||||
('project_path','schematic_name','sheet_number','old_part','target_scope','target_selectors'))
|
||||
failures=connection.execute('''SELECT operation_key,command_json FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND state='failed' ''',(task_id,round_id)).fetchall()
|
||||
replaced=[entry['operation_key'] for entry in failures if scope(json.loads(entry['command_json']))==scope(identity)]
|
||||
if not replaced:raise TaskCenterError('quick_run_uncertain','重试范围包含非失败项,请重新确认。')
|
||||
for old_key in replaced:
|
||||
connection.execute("UPDATE execution_operations SET state='superseded' WHERE task_id=? AND round_id=? AND operation_key=?",(task_id,round_id,old_key))
|
||||
connection.execute('''INSERT INTO execution_operations
|
||||
(task_id,round_id,operation_key,command_json,state) VALUES (?,?,?,?, 'pending')''',
|
||||
(task_id,round_id,key,_json(identity)))
|
||||
elif record['state'] in _SUCCESS:
|
||||
restored[row['job_id']]=tuple(json.loads(record['receipt_json'])[name] for name in ('native_state','code','message'))
|
||||
continue
|
||||
elif record['state']=='failed' and retry:
|
||||
connection.execute("UPDATE execution_operations SET state='pending',attempt_id=NULL WHERE task_id=? AND round_id=? AND operation_key=?",(task_id,round_id,key))
|
||||
continue # The old failed TSV must not cancel explicit retry.
|
||||
outcome=latest.get(row['job_id'])
|
||||
if outcome and outcome[0] in _TERMINAL:
|
||||
record=connection.execute('''SELECT * FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',(task_id,round_id,key)).fetchone()
|
||||
if record['state']=='prepared':
|
||||
attempt=JournalAttempt(task_id,round_id,key,record['attempt_id'],record['generation'])
|
||||
else:
|
||||
attempt=self.claim(task_id,row,importing=True)
|
||||
proof=proof_reader(row,outcome) if proof_reader else None
|
||||
self.finish(attempt,*outcome,proof=proof)
|
||||
elif record is not None and record['state'] in {'prepared','uncertain'}:
|
||||
raise TaskCenterError('quick_run_uncertain','上次执行尝试没有完整结果,不能重复派发。')
|
||||
connection.execute('UPDATE execution_rounds SET plan_json=?,retry_authorized=0,pause_requested=0 WHERE task_id=?',(_json(keys),task_id))
|
||||
return restored
|
||||
|
||||
def claim(self,task_id,row,*,importing=False):
|
||||
key=_hash(command_identity(row))
|
||||
with self.store.transaction():
|
||||
current=self._round(task_id)
|
||||
if current is None:raise TaskCenterError('quick_run_uncertain','执行计划尚未持久化。')
|
||||
record=self.store._connection.execute('''SELECT * FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',(task_id,current['round_id'],key)).fetchone()
|
||||
if record is None:raise TaskCenterError('quick_run_uncertain','执行项不属于冻结计划。')
|
||||
if record['state'] in _SUCCESS:raise TaskCenterError('quick_run_complete','本轮该项已有完成回执,不会重复执行。')
|
||||
# The current UI owns one CBB per bound task. Legacy unbound
|
||||
# multi-project API queues retain their existing failure policy.
|
||||
hold_project=bool(self.store.get_task(task_id).primary_project_id)
|
||||
if record['state']=='failed' or (hold_project and not importing and self.requires_retry(task_id)):
|
||||
raise TaskCenterError('quick_run_retry_required','本工程有失败项,请准备失败项重试;不会重新执行成功项。')
|
||||
if record['state']!='pending':raise TaskCenterError('quick_run_uncertain','上次尝试尚未核验,禁止再次派发。')
|
||||
identifier=uuid4().hex;generation=record['generation']+1
|
||||
self.store._connection.execute('''UPDATE execution_operations SET state='prepared',attempt_id=?,generation=?
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',(identifier,generation,task_id,current['round_id'],key))
|
||||
return JournalAttempt(task_id,current['round_id'],key,identifier,generation)
|
||||
|
||||
def finish(self,attempt,native_state,code,message,*,progress=None,proof=None):
|
||||
if native_state not in _TERMINAL:raise TaskCenterError('quick_run_uncertain','不能提交未知的执行结果。')
|
||||
state=({'saved_ok':'verified','no_match':'no_match','restored_ok':'restored',
|
||||
'batch_failed':'failed','batch_skipped':'failed','batch_saved_unverified':'uncertain'})[native_state]
|
||||
if native_state=='restored_ok' and code in {'recovery_verified','recovery_saved_verified'}:
|
||||
state='verified'
|
||||
with self.store.transaction():
|
||||
connection=self.store._connection
|
||||
record=connection.execute('''SELECT * FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',
|
||||
(attempt.task_id,attempt.round_id,attempt.operation_key)).fetchone()
|
||||
if (record is None or record['state']!='prepared' or record['attempt_id']!=attempt.attempt_id
|
||||
or record['generation']!=attempt.generation or self._round(attempt.task_id)['round_id']!=attempt.round_id):
|
||||
raise TaskCenterError('quick_run_uncertain','旧尝试的结果不能覆盖当前执行回执。')
|
||||
command=json.loads(record['command_json'])
|
||||
receipt={'native_state':native_state,'code':code,'message':message}
|
||||
if proof is not None:
|
||||
from .execution_proof import proof_intact
|
||||
if not proof_intact(proof):raise TaskCenterError('quick_run_uncertain','执行证明不完整,不能提交回执。')
|
||||
receipt['proof']=proof
|
||||
connection.execute('''UPDATE execution_operations SET state=?,receipt_json=?
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',
|
||||
(state,_json(receipt),attempt.task_id,attempt.round_id,attempt.operation_key))
|
||||
if state in _SUCCESS:
|
||||
if proof and proof.get('baseline'):
|
||||
baseline=dict(proof['baseline'])
|
||||
baseline['project_path']=command['project_path']
|
||||
baseline['files']=proof.get('files',[])
|
||||
connection.execute('''INSERT INTO execution_baselines VALUES (?,?,?,?,?,?)
|
||||
ON CONFLICT(task_id,round_id,project_path,schematic_name,sheet_number)
|
||||
DO UPDATE SET baseline_json=excluded.baseline_json''',
|
||||
(attempt.task_id,attempt.round_id,command['project_path'],baseline['schematic_name'],
|
||||
baseline['sheet_number'],_json(baseline)))
|
||||
for target in _targets(command):
|
||||
connection.execute('INSERT INTO execution_target_claims VALUES (?,?,?,?)',
|
||||
(attempt.task_id,attempt.round_id,target,attempt.operation_key))
|
||||
task=self.store.get_task(attempt.task_id)
|
||||
history_receipt={key:value for key,value in receipt.items() if key!='proof'}
|
||||
if proof:
|
||||
history_receipt['proof_file_count']=len(proof.get('files',()))
|
||||
HistoryRepository(self.store).append(task_id=attempt.task_id,task_name=task.name,
|
||||
project_path=command['project_path'],operation='器件替换',state=state,summary=message,
|
||||
details={**command,**history_receipt,'round_id':attempt.round_id,'attempt_id':attempt.attempt_id,
|
||||
'generation':attempt.generation},
|
||||
source_key=f'receipt:{attempt.task_id}:{attempt.round_id}:{attempt.operation_key}:{attempt.generation}')
|
||||
if progress is not None and self.progress_writer is not None:
|
||||
self.progress_writer(attempt.task_id,progress=progress)
|
||||
|
||||
def reconcile_recovery(self,task_id,row,state,code,message,*,recovery_id=None,proof=None):
|
||||
"""Only called after the existing explicitly confirmed native recovery succeeds."""
|
||||
if state not in {'restored_ok','retry_ready'}:
|
||||
raise TaskCenterError('quick_run_recovery','恢复没有返回明确核验结论。')
|
||||
key=_hash(command_identity(row))
|
||||
with self.store.transaction():
|
||||
if recovery_id:
|
||||
if self.store._connection.execute('SELECT 1 FROM execution_transitions WHERE transition_id=?',(recovery_id,)).fetchone():return
|
||||
self.store._connection.execute('INSERT INTO execution_transitions VALUES (?,?)',(recovery_id,task_id))
|
||||
current=self._round(task_id)
|
||||
if current is None:return # Legacy handoff is imported after recovery.
|
||||
record=self.store._connection.execute('''SELECT * FROM execution_operations
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',(task_id,current['round_id'],key)).fetchone()
|
||||
if record is None:raise TaskCenterError('quick_run_recovery','恢复项与原轮次身份不一致。')
|
||||
if record['state'] in _SUCCESS:return
|
||||
generation=record['generation']+1
|
||||
identifier=uuid4().hex
|
||||
self.store._connection.execute('''UPDATE execution_operations
|
||||
SET state=?,generation=?,attempt_id=?,receipt_json=NULL
|
||||
WHERE task_id=? AND round_id=? AND operation_key=?''',
|
||||
('pending' if state=='retry_ready' else 'prepared',generation,identifier,
|
||||
task_id,current['round_id'],key))
|
||||
if state=='restored_ok':
|
||||
self.finish(JournalAttempt(task_id,current['round_id'],key,identifier,generation),state,code,message,proof=proof)
|
||||
else:
|
||||
task=self.store.get_task(task_id)
|
||||
HistoryRepository(self.store).append(task_id=task_id,task_name=task.name,
|
||||
project_path=command_identity(row)['project_path'],operation='quick_run_recovered',
|
||||
state='restored',summary=message,
|
||||
details={'native_replacement_called':False,'round_id':current['round_id'],'generation':generation},
|
||||
source_key=f'recovery:{task_id}:{current["round_id"]}:{key}:{generation}')
|
||||
|
||||
def conflicts(self,task_id,rows,latest):
|
||||
"""Read-only admission check, including receipt/file rollback detection."""
|
||||
with self.store._lock:
|
||||
current=self._round(task_id)
|
||||
if current is None:return False
|
||||
keys=[_hash(command_identity(row)) for row in rows]
|
||||
if json.loads(current['plan_json'])!=keys and not current['retry_authorized']:return True
|
||||
records={record['operation_key']:record for record in self.store._connection.execute('''
|
||||
SELECT operation_key,state,receipt_json FROM execution_operations WHERE task_id=? AND round_id=?''',
|
||||
(task_id,current['round_id']))}
|
||||
for row,key in zip(rows,keys):
|
||||
record=records.get(key)
|
||||
if record is None:continue
|
||||
outcome=latest.get(row['job_id'])
|
||||
if record['state'] in _SUCCESS:
|
||||
receipt=json.loads(record['receipt_json'])
|
||||
from .execution_proof import proof_intact
|
||||
if not proof_intact(receipt.get('proof',{})):return True
|
||||
if not outcome or tuple(outcome[:2])!=(receipt['native_state'],receipt['code']):return True
|
||||
elif record['state']=='uncertain':return True
|
||||
elif record['state']=='prepared' and (not outcome or outcome[0] not in _TERMINAL):return True
|
||||
return False
|
||||
|
||||
def expected_baselines(self,task_id,project_path):
|
||||
from .execution_proof import proof_intact
|
||||
key=str(canonical_path(project_path)).casefold()
|
||||
with self.store._lock:
|
||||
current=self._round(task_id)
|
||||
if current is None:return ()
|
||||
records=self.store._connection.execute('''SELECT baseline_json FROM execution_baselines
|
||||
WHERE task_id=? AND round_id=? AND project_path=? ORDER BY schematic_name,sheet_number''',
|
||||
(task_id,current['round_id'],key)).fetchall()
|
||||
values=tuple(json.loads(row[0]) for row in records)
|
||||
if any(not proof_intact(value) for value in values):
|
||||
raise TaskCenterError('quick_run_uncertain','最近已核验的工程基线证据缺失或变化,已停止续跑。')
|
||||
return values
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Bind durable receipts to immutable native evidence and the last verified sheet."""
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import canonical_path, internal_path
|
||||
|
||||
|
||||
def proof_intact(proof):
|
||||
try:
|
||||
return all(hashlib.sha256(internal_path(item['path']).read_bytes()).hexdigest()==item['sha256']
|
||||
for item in proof.get('files',()))
|
||||
except (OSError,ValueError,KeyError,TypeError):return False
|
||||
|
||||
|
||||
def capture_result(data_root,root,row,outcome,*,strict=False,persist=True):
|
||||
from .quick_run import _decode_vbs_field, _safe_run_token
|
||||
from .native_helper import read_snapshot, require_resumable_transaction, snapshot_target_cell
|
||||
state,code,_=outcome
|
||||
proof={'files':[]}
|
||||
paths=[]
|
||||
try:
|
||||
_safe_run_token(row['job_id'])
|
||||
if strict and state in {'saved_ok','no_match'} and code not in {'batch_closed','session_verified'}:
|
||||
raise ValueError('save/close was not verified')
|
||||
checked={}
|
||||
baseline=internal_path(root/f'post-state-{row["job_id"]}.tsv')
|
||||
if baseline.is_file():
|
||||
checked[baseline]=baseline.read_bytes()
|
||||
with baseline.open(encoding='utf-8-sig',newline='') as stream:
|
||||
rows=list(csv.DictReader(stream,delimiter='\t'))
|
||||
if len(rows)!=1:raise ValueError('ambiguous semantic state')
|
||||
actual={key:_decode_vbs_field(value) for key,value in rows[0].items()}
|
||||
if (actual['job_id']!=row['job_id'] or
|
||||
canonical_path(actual['project_path'])!=canonical_path(row['project_path']) or
|
||||
(row.get('schematic_name') and (actual['schematic_name'],actual['sheet_number'])!=(row['schematic_name'],row['sheet_number'])) or
|
||||
not actual['semantic_state'].startswith('S\tfull_sheet_v1\r\n')):
|
||||
raise ValueError('semantic state identity mismatch')
|
||||
proof['baseline']={'project_path':str(canonical_path(row['project_path'])).casefold(),
|
||||
'schematic_name':actual['schematic_name'],'sheet_number':actual['sheet_number'],'state':actual['semantic_state']}
|
||||
paths.append(baseline)
|
||||
elif strict and state in {'saved_ok','no_match','restored_ok','recovery_readback'}:
|
||||
raise ValueError('missing verified semantic state')
|
||||
if state=='saved_ok' or (state=='restored_ok' and code in {'recovery_verified','recovery_saved_verified'}):
|
||||
snapshot=internal_path(root/f'snapshot-{row["job_id"]}.tsv')
|
||||
report_path=Path(str(snapshot)+'.native.json')
|
||||
if strict or snapshot.is_file() or report_path.is_file():
|
||||
checked[snapshot]=snapshot.read_bytes()
|
||||
checked[report_path]=report_path.read_bytes()
|
||||
metadata,components=read_snapshot(snapshot)
|
||||
report=json.loads(report_path.read_text(encoding='utf8'))
|
||||
require_resumable_transaction(snapshot,report,metadata,components)
|
||||
expected_sheet=f'{row["schematic_name"]}:{row["sheet_number"]}' if row.get('schematic_name') else metadata[4]
|
||||
if (canonical_path(metadata[1])!=canonical_path(row['project_path']) or
|
||||
metadata[2:4]!=[row['old_part'],row['new_part']] or metadata[4]!=expected_sheet or
|
||||
metadata[5]!=row.get('value_mode','preserve') or
|
||||
(metadata[6:8] if len(metadata)>=8 else ['', '1'])!=[row.get('custom_value',''),row.get('sync_nc','1')] or
|
||||
(metadata[9] if len(metadata)==10 else '')!=row.get('target_selectors','') or
|
||||
(snapshot_target_cell(snapshot,required=False) or '')!=row.get('target_cell','')):
|
||||
raise ValueError('snapshot command changed')
|
||||
attempt=report.get('batch_attempt')
|
||||
if strict:
|
||||
if report.get('stage')!='native_replace_verified' or report.get('ok') is not True:
|
||||
raise ValueError('native result is not verified')
|
||||
if (not isinstance(attempt,dict) or attempt.get('job_id')!=row['job_id'] or
|
||||
attempt.get('task_id')!=row['task_id'] or
|
||||
canonical_path(attempt.get('project_path',''))!=canonical_path(row['project_path']) or
|
||||
type(attempt.get('generation')) is not int or attempt['generation']<1 or
|
||||
not all(isinstance(attempt.get(name),str) and len(attempt[name])==32 for name in ('session_id','attempt_id'))):
|
||||
raise ValueError('native attempt differs from this job')
|
||||
proof['native_attempt']=attempt
|
||||
paths.extend((snapshot,report_path))
|
||||
if any(path.read_bytes()!=data for path,data in checked.items()):
|
||||
raise ValueError('execution evidence changed during receipt binding')
|
||||
if persist and paths:
|
||||
# Independent of active handoff/archive/retention paths.
|
||||
destination=internal_path(data_root/'execution-proof'/uuid4().hex)
|
||||
destination.mkdir(parents=True,exist_ok=False)
|
||||
for path in paths:
|
||||
data=checked[path]
|
||||
target=destination/path.name
|
||||
with target.open('xb') as stream:
|
||||
stream.write(data);stream.flush();os.fsync(stream.fileno())
|
||||
proof['files'].append({'path':str(canonical_path(target)), 'sha256':hashlib.sha256(data).hexdigest()})
|
||||
return proof
|
||||
except (OSError,ValueError,KeyError,TypeError,UnicodeError) as error:
|
||||
raise TaskCenterError('quick_run_uncertain','原生回执、尝试身份或工程语义基线无法核验,已停止以避免重复替换。') from error
|
||||
|
||||
|
||||
def capture_recovery(data_root,audit,row,outcome,*,strict=False):
|
||||
"""The recovery audit proves readback; it never asserts a second replacement."""
|
||||
worker=audit/'worker'
|
||||
proof=capture_result(data_root,worker,row,('recovery_readback','',outcome[2]),strict=strict)
|
||||
try:
|
||||
record=json.loads((audit/'recovery.json').read_text(encoding='utf8'))
|
||||
snapshot=audit/'evidence-before'/f'snapshot-{row["job_id"]}.tsv'
|
||||
if (record['task_id']!=row['task_id'] or record['job_id']!=row['job_id'] or
|
||||
tuple(record['worker_result'][1:3])!=tuple(outcome[:2]) or
|
||||
record['native_replacement_called'] is not False or
|
||||
hashlib.sha256(snapshot.read_bytes()).hexdigest()!=record['snapshot_sha256']):
|
||||
raise ValueError('recovery proof differs from original operation')
|
||||
destination=internal_path(data_root/'execution-proof'/uuid4().hex)
|
||||
destination.mkdir(parents=True,exist_ok=False)
|
||||
for path in (audit/'recovery.json',snapshot,Path(str(snapshot)+'.native.json'),worker/'status.tsv'):
|
||||
data=path.read_bytes();target=destination/path.name
|
||||
with target.open('xb') as stream:
|
||||
stream.write(data);stream.flush();os.fsync(stream.fileno())
|
||||
proof['files'].append({'path':str(canonical_path(target)),'sha256':hashlib.sha256(data).hexdigest()})
|
||||
proof['recovery_id']=audit.name
|
||||
return proof
|
||||
except (OSError,ValueError,KeyError,TypeError) as error:
|
||||
raise TaskCenterError('quick_run_uncertain','恢复审计无法与原执行项绑定,保护记录保留。') from error
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Incomplete execution evidence must never be interpreted as a fresh queue."""
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
def assert_handoff_intact(root, task_id, *, files=None):
|
||||
from . import quick_run as api
|
||||
command=root/'command.tsv'; status=root/'status.tsv'
|
||||
exists=lambda path:internal_path(path).is_file()
|
||||
read=lambda path:files.read(path) if files is not None else internal_path(path).read_text(encoding='utf-8-sig')
|
||||
parser=lambda path:files.path(path) if files is not None else path
|
||||
try:
|
||||
command_exists,status_exists=exists(command),exists(status)
|
||||
if not command_exists and not status_exists:
|
||||
if (exists(root/'current-command.tsv') or exists(root/'uncertain.flag')
|
||||
or exists(root/'quick-part-replace.log')):
|
||||
raise ValueError('execution evidence is missing')
|
||||
return
|
||||
if not command_exists or not status_exists:
|
||||
raise ValueError('incomplete command/status pair')
|
||||
if not read(command).endswith('\n') or not read(status).endswith('\n'):
|
||||
raise ValueError('truncated handoff')
|
||||
commands=api._read_commands(parser(command))
|
||||
details=api._read_status_details(parser(status))
|
||||
jobs={row[1] for row in commands}
|
||||
if not commands or len(jobs)!=len(commands) or any(row[0] not in jobs for row in details):
|
||||
raise ValueError('inconsistent command/status identities')
|
||||
if {row[0] for row in commands}!={task_id}:
|
||||
return # Existing legacy routing validates ownership separately.
|
||||
current=root/'current-command.tsv'
|
||||
if exists(current):
|
||||
current_commands=api._read_commands(parser(current))
|
||||
latest={row[0]:row[1] for row in details}
|
||||
if (len(current_commands)!=1 or current_commands[0] not in commands
|
||||
or current_commands[0][1] not in latest):
|
||||
raise ValueError('dispatched item has no matching outcome')
|
||||
except (OSError, UnicodeError, ValueError, TaskCenterError) as error:
|
||||
raise TaskCenterError('quick_run_uncertain',
|
||||
'执行记录缺失、损坏或不一致,已停止以避免重复替换;请保留证据并核验恢复。') from error
|
||||
@@ -0,0 +1,274 @@
|
||||
"""Transactional user changes and one-time read-only import of legacy task events."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .history_store import HistoryRepository
|
||||
from .path_access import internal_path
|
||||
from .store_read_model import checkpoint, read_lock
|
||||
|
||||
|
||||
_MUTATIONS={
|
||||
'create_task','create_project_tasks','create_scanned_task','update_task','delete_task',
|
||||
'restore_task','purge_task','add_rule','update_rule','delete_rule','move_rule',
|
||||
'replace_target_plan','import_target_plan','save_bom_batch','save_plan_drafts',
|
||||
'set_value_policy','move_project_task','set_project_selected','select_all_projects',
|
||||
'clear_project_selection','scan_projects',
|
||||
}
|
||||
# start_new_round deliberately records inside its existing compensating
|
||||
# transaction. Wrapping its filesystem moves in another transaction would let
|
||||
# its inner savepoint report committed before the outer history COMMIT.
|
||||
_LABELS={'create_task':'新建任务','create_project_tasks':'创建工程任务','create_scanned_task':'创建工程任务',
|
||||
'update_task':'编辑任务','delete_task':'归档任务','restore_task':'恢复任务','purge_task':'删除任务记录',
|
||||
'add_rule':'添加规则','update_rule':'修改规则','delete_rule':'删除规则','move_rule':'调整规则顺序',
|
||||
'replace_target_plan':'保存位号计划','import_target_plan':'导入位号计划','save_bom_batch':'保存 BOM 计划',
|
||||
'save_plan_drafts':'保存位号计划','set_value_policy':'修改 Value 策略','move_project_task':'调整任务顺序',
|
||||
'set_project_selected':'修改工程选择','select_all_projects':'全选工程',
|
||||
'clear_project_selection':'清空工程选择','scan_projects':'扫描工程'}
|
||||
|
||||
_TABLES={
|
||||
'tasks':(('task_id',),('task_id','name','note','discovery_root','status','copy_part_number_to_value',
|
||||
'target_plan_mode','group_id','group_position','primary_project_id','summary')),
|
||||
'rules':(('rule_id',),('rule_id','task_id','position','old_part_number','new_part_number','enabled',
|
||||
'custom_value_enabled','custom_value','sync_nc','target_cell')),
|
||||
'projects':(('project_id',),('project_id','task_id','display_name','path','discovery_root',
|
||||
'selected','available','status','summary')),
|
||||
'target_plan':(('task_id','project_path','schematic_name','sheet_number','uid'),
|
||||
('task_id','project_path','schematic_name','sheet_number','uid','refdes','old_part_number','old_value',
|
||||
'enabled','new_part_number','custom_value_enabled','custom_value','sync_nc','target_cell')),
|
||||
}
|
||||
_CUTOFF='history_import_cutoff_v1'
|
||||
_IMPORTED='history_import_done_v1'
|
||||
_LEGACY_OPERATIONS={'quick_run_executed','quick_run_recovered','quick_run_prepared',
|
||||
'quick_run_queue_paused','quick_run_retry_prepared','value_policy_changed','quick_run_inventory_prefiltered'}
|
||||
_LEGACY_DETAILS={'state','code','refdes','uid','schematic_name','sheet_number','project_path',
|
||||
'old_part_number','new_part_number','old_part','new_part','old_value','custom_value','sync_nc','target_cell',
|
||||
'completed_items','total_items','saved_items','failed_items','no_match_items','completed_projects',
|
||||
'prefiltered_items','copy_part_label_to_value','copy_part_number_to_value','project_ids'}
|
||||
_MAX_LEGACY_LINE=8*1024*1024
|
||||
|
||||
|
||||
def _json_object(prefix,fields):
|
||||
return 'json_object('+','.join(f"'{field}',{prefix}.{field}" for field in fields)+')'
|
||||
|
||||
|
||||
def _install_capture(connection, token):
|
||||
table='history_capture_'+token
|
||||
connection.execute(f'''CREATE TEMP TABLE {table} (
|
||||
sequence INTEGER PRIMARY KEY, table_name TEXT, item_key TEXT, task_id TEXT,
|
||||
before_json TEXT, after_json TEXT)''')
|
||||
triggers=[]
|
||||
for name,(keys,fields) in _TABLES.items():
|
||||
for operation in ('INSERT','UPDATE','DELETE'):
|
||||
trigger=f'{table}_{name}_{operation.lower()}'
|
||||
triggers.append(trigger)
|
||||
prefix='OLD' if operation=='DELETE' else 'NEW'
|
||||
identity='json_array('+','.join(f'{prefix}.{key}' for key in keys)+')'
|
||||
before='NULL' if operation=='INSERT' else _json_object('OLD',fields)
|
||||
after='NULL' if operation=='DELETE' else _json_object('NEW',fields)
|
||||
connection.execute(f'''CREATE TEMP TRIGGER {trigger} AFTER {operation} ON main.{name}
|
||||
BEGIN INSERT INTO {table}(table_name,item_key,task_id,before_json,after_json)
|
||||
VALUES ('{name}',{identity},{prefix}.task_id,{before},{after}); END''')
|
||||
return table,triggers
|
||||
|
||||
|
||||
def _changes(records):
|
||||
combined={}
|
||||
for row in records:
|
||||
key=(row['table_name'],row['item_key'])
|
||||
if key not in combined:
|
||||
combined[key]={'table':row['table_name'],'task_id':row['task_id'],
|
||||
'before':json.loads(row['before_json']) if row['before_json'] is not None else None,
|
||||
'after':None}
|
||||
combined[key]['after']=json.loads(row['after_json']) if row['after_json'] is not None else None
|
||||
result=[]
|
||||
for record in combined.values():
|
||||
before,after=record['before'],record['after']
|
||||
if before==after:continue
|
||||
source=after if after is not None else before
|
||||
keys=_TABLES[record['table']][0]
|
||||
identity={key:source[key] for key in keys}
|
||||
for name in ('refdes','old_part_number','project_path'):
|
||||
if name in source:identity[name]=source[name]
|
||||
if before is not None and after is not None:
|
||||
changed=[key for key in source if before.get(key)!=after.get(key)]
|
||||
before={key:before.get(key) for key in changed}
|
||||
after={key:after.get(key) for key in changed}
|
||||
result.append({'table':record['table'],'task_id':record['task_id'],'identity':identity,
|
||||
'before':before,'after':after})
|
||||
return result
|
||||
|
||||
|
||||
def _task_context(connection,task_id,changes):
|
||||
task=connection.execute('SELECT name FROM tasks WHERE task_id=?',(task_id,)).fetchone()
|
||||
name=task['name'] if task is not None else ''
|
||||
project=connection.execute('SELECT path FROM projects WHERE task_id=? ORDER BY path_identity LIMIT 1',
|
||||
(task_id,)).fetchone()
|
||||
path=project['path'] if project is not None else ''
|
||||
for change in changes:
|
||||
source=change['after'] if change['after'] is not None else change['before']
|
||||
if change['table']=='tasks' and not name:name=source.get('name','')
|
||||
if change['table']=='projects' and not path:path=source.get('path','')
|
||||
if change['table']=='target_plan' and not path:path=change['identity'].get('project_path','')
|
||||
return name or task_id,path
|
||||
|
||||
|
||||
def _summary(name,changes):
|
||||
parts=[]
|
||||
for change in changes[:3]:
|
||||
before,after=change['before'],change['after']
|
||||
identity=change['identity']
|
||||
if change['table']=='tasks' and before and after and 'name' in before:
|
||||
parts.append(f"名称 {before['name']} → {after['name']}")
|
||||
elif change['table']=='rules':
|
||||
old=identity.get('old_part_number','')
|
||||
previous=before.get('new_part_number','') if before else ''
|
||||
current=after.get('new_part_number','') if after else ''
|
||||
parts.append(f'{old}:{previous} → {current}' if previous or current else old)
|
||||
elif change['table']=='target_plan':parts.append(str(identity.get('refdes','位号')))
|
||||
base=_LABELS.get(name,name)
|
||||
return f'{base}:'+(';'.join(parts)+';' if parts else '')+f'记录 {len(changes)} 行实际改动'
|
||||
|
||||
|
||||
def record_operation(service,name,task_id,action):
|
||||
"""Capture only real database changes; history failure rolls them back too."""
|
||||
if name not in _MUTATIONS:return action()
|
||||
store=service._store
|
||||
with store.transaction():
|
||||
table,triggers=_install_capture(store._connection,uuid4().hex)
|
||||
try:
|
||||
result=action()
|
||||
changed=_changes(store._connection.execute(f'SELECT * FROM {table} ORDER BY sequence').fetchall())
|
||||
groups=defaultdict(list)
|
||||
for change in changed:groups[change.pop('task_id')].append(change)
|
||||
repository=HistoryRepository(store)
|
||||
operation_group=uuid4().hex
|
||||
for owner,changes in groups.items():
|
||||
task_name,project_path=_task_context(store._connection,owner,changes)
|
||||
chunks=[changes[index:index+100] for index in range(0,len(changes),100)]
|
||||
for index,chunk in enumerate(chunks):
|
||||
repository.append(task_id=owner,task_name=task_name,project_path=project_path,
|
||||
operation=name,state='recorded',summary=_summary(name,chunk),
|
||||
details={'changes':chunk,'operation_group':operation_group,
|
||||
'chunk_index':index+1,'chunk_count':len(chunks),'total_changed_rows':len(changes)},
|
||||
source_key=f'operation:{operation_group}:{owner}:{index}')
|
||||
return result
|
||||
finally:
|
||||
for trigger in triggers:store._connection.execute(f'DROP TRIGGER IF EXISTS {trigger}')
|
||||
store._connection.execute(f'DROP TABLE IF EXISTS {table}')
|
||||
|
||||
|
||||
def initialize_history_import(store):
|
||||
"""Persist the upgrade boundary once; per-task facades never move it."""
|
||||
cutoff=datetime.now(timezone.utc).isoformat(timespec='microseconds').replace('+00:00','Z')
|
||||
with store.transaction():
|
||||
store._connection.execute('INSERT OR IGNORE INTO metadata(key,value) VALUES (?,?)',(_CUTOFF,cutoff))
|
||||
|
||||
|
||||
def _instant(value):
|
||||
if not isinstance(value,str):raise ValueError('missing legacy event timestamp')
|
||||
result=datetime.fromisoformat(value.replace('Z','+00:00'))
|
||||
if result.tzinfo is None or result.utcoffset() is None:
|
||||
raise ValueError('legacy event timestamp lacks timezone')
|
||||
return result.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _state(operation,details):
|
||||
state=details.get('state')
|
||||
if operation=='quick_run_queue_paused':return 'paused'
|
||||
if operation=='quick_run_inventory_prefiltered':return 'no_match'
|
||||
if operation in {'quick_run_prepared','quick_run_retry_prepared','value_policy_changed'}:return 'recorded'
|
||||
return {'saved_ok':'verified','no_match':'no_match','restored_ok':'restored',
|
||||
'batch_failed':'failed','hard_failure':'failed','batch_skipped':'skipped',
|
||||
'batch_saved_unverified':'uncertain','awaiting_native_replace':'uncertain'}.get(state,'uncertain')
|
||||
|
||||
|
||||
def _reject_redirect(path):
|
||||
info=internal_path(path).lstat()
|
||||
if stat.S_ISLNK(info.st_mode) or getattr(info,'st_file_attributes',0)&0x400:
|
||||
raise OSError('redirected legacy history source')
|
||||
|
||||
|
||||
def _legacy_files(root,read_control):
|
||||
root=Path(root)/'tasks'
|
||||
if not internal_path(root).exists():return
|
||||
_reject_redirect(root)
|
||||
for directory in sorted(internal_path(root).iterdir(),key=lambda value:value.name):
|
||||
checkpoint(read_control)
|
||||
_reject_redirect(directory)
|
||||
if not directory.is_dir():continue
|
||||
for source in sorted(directory.iterdir(),key=lambda value:value.name):
|
||||
checkpoint(read_control)
|
||||
if not re.fullmatch(r'events\.jsonl(?:\.[1-9][0-9]*)?',source.name):continue
|
||||
_reject_redirect(source)
|
||||
if not source.is_file():continue
|
||||
yield directory.name,source
|
||||
|
||||
|
||||
def _import_file(service,repository,task_id,source,cutoff,read_control):
|
||||
connection=service._store._connection
|
||||
task=connection.execute('SELECT name FROM tasks WHERE task_id=?',(task_id,)).fetchone()
|
||||
task_name=task['name'] if task is not None else task_id
|
||||
with internal_path(source).open('r',encoding='utf-8-sig') as stream:
|
||||
while True:
|
||||
checkpoint(read_control)
|
||||
line=stream.readline(_MAX_LEGACY_LINE+1)
|
||||
if not line:break
|
||||
if len(line)>_MAX_LEGACY_LINE:raise ValueError('legacy event exceeds import limit')
|
||||
if not line.strip():continue
|
||||
event=json.loads(line)
|
||||
if not isinstance(event,dict):raise ValueError('legacy event is not an object')
|
||||
operation=event.get('operation')
|
||||
if operation not in _LEGACY_OPERATIONS:continue
|
||||
if event.get('task_id')!=task_id:raise ValueError('legacy event task identity mismatch')
|
||||
instant=_instant(event.get('timestamp_utc'))
|
||||
if instant>=cutoff:continue
|
||||
raw_details=event.get('details',{})
|
||||
if not isinstance(raw_details,dict):raise ValueError('legacy event details are not an object')
|
||||
details={key:value for key,value in raw_details.items() if key in _LEGACY_DETAILS}
|
||||
message=event.get('message','')
|
||||
if not isinstance(message,str):raise ValueError('legacy event message is not text')
|
||||
identity={'task_id':task_id,'sequence':event.get('sequence'),'timestamp_utc':instant.isoformat(),
|
||||
'operation':operation,'details':details,'message':message}
|
||||
source_key='legacy:v1:'+hashlib.sha256(json.dumps(identity,ensure_ascii=False,sort_keys=True,
|
||||
separators=(',',':'),allow_nan=False).encode('utf8')).hexdigest()
|
||||
details=dict(details,legacy_record=True)
|
||||
repository.append(task_id=task_id,task_name=task_name,
|
||||
project_path=str(details.get('project_path') or ''),operation=operation,
|
||||
state=_state(operation,details),summary=message or _LABELS.get(operation,'旧版本操作记录'),
|
||||
details=details,source_key=source_key,timestamp_utc=instant.isoformat())
|
||||
|
||||
|
||||
def ensure_legacy_history(service,read_control=None):
|
||||
"""Import pre-upgrade supported events; cancellation/error never marks done."""
|
||||
store=service._store
|
||||
checkpoint(read_control)
|
||||
with read_lock(store,read_control):
|
||||
complete=store._connection.execute('SELECT value FROM metadata WHERE key=?',(_IMPORTED,)).fetchone()
|
||||
if complete is not None and complete['value']=='1':return
|
||||
cutoff=store._connection.execute('SELECT value FROM metadata WHERE key=?',(_CUTOFF,)).fetchone()
|
||||
if cutoff is None:
|
||||
initialize_history_import(store)
|
||||
with read_lock(store,read_control):
|
||||
cutoff=store._connection.execute('SELECT value FROM metadata WHERE key=?',(_CUTOFF,)).fetchone()
|
||||
try:
|
||||
instant=_instant(cutoff['value'])
|
||||
repository=HistoryRepository(store)
|
||||
for task_id,source in _legacy_files(service._logging.root,read_control):
|
||||
# Commit bounded source files independently. Retried files are
|
||||
# source-deduplicated; an interrupted final file is rolled back.
|
||||
with store.transaction():_import_file(service,repository,task_id,source,instant,read_control)
|
||||
checkpoint(read_control)
|
||||
with store.transaction():
|
||||
checkpoint(read_control)
|
||||
store._connection.execute('INSERT OR REPLACE INTO metadata(key,value) VALUES (?,?)',(_IMPORTED,'1'))
|
||||
except (OSError,UnicodeError,ValueError,TypeError) as error:
|
||||
raise TaskCenterError('history_import','旧操作历史暂时无法完整读取,原文件已保留,可修复后重试。') from error
|
||||
@@ -0,0 +1,153 @@
|
||||
"""User-visible operation history, separate from durable execution admission."""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
|
||||
from .store_read_model import checkpoint, read_lock
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class HistoryPage:
|
||||
rows: tuple[dict, ...]
|
||||
next_cursor: int | None
|
||||
total: int
|
||||
all_total: int | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class HistoryClearSnapshot:
|
||||
cutoff_id: int
|
||||
count: int
|
||||
|
||||
|
||||
def create_history_schema(connection) -> None:
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS operation_history (
|
||||
event_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp_utc TEXT NOT NULL, task_id TEXT NOT NULL, task_name TEXT NOT NULL,
|
||||
project_path TEXT NOT NULL, operation TEXT NOT NULL, state TEXT NOT NULL,
|
||||
summary TEXT NOT NULL, details_json TEXT NOT NULL, search_text TEXT NOT NULL)''')
|
||||
connection.execute('CREATE INDEX IF NOT EXISTS history_state_id ON operation_history(state,event_id)')
|
||||
connection.execute('CREATE INDEX IF NOT EXISTS history_time_id ON operation_history(timestamp_utc DESC,event_id DESC)')
|
||||
connection.execute('CREATE INDEX IF NOT EXISTS history_state_time ON operation_history(state,timestamp_utc DESC,event_id DESC)')
|
||||
# This table deliberately has no foreign key to operation_history: source
|
||||
# identities survive clearing so migration/reindexing cannot resurrect them.
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS operation_history_sources (
|
||||
source_key TEXT PRIMARY KEY, event_id INTEGER NOT NULL)''')
|
||||
connection.execute('''CREATE TABLE IF NOT EXISTS operation_history_meta (
|
||||
singleton INTEGER PRIMARY KEY CHECK(singleton=1), cleared_through_id INTEGER NOT NULL)''')
|
||||
connection.execute('INSERT OR IGNORE INTO operation_history_meta VALUES (1,0)')
|
||||
|
||||
|
||||
class HistoryRepository:
|
||||
def __init__(self, store):
|
||||
self.store = store
|
||||
|
||||
@contextmanager
|
||||
def _read(self, read_control=None):
|
||||
with read_lock(self.store, read_control):
|
||||
connection=self.store._connection
|
||||
owns_transaction=self.store._transaction_depth==0
|
||||
if owns_transaction: connection.execute('BEGIN')
|
||||
try:
|
||||
yield connection
|
||||
checkpoint(read_control)
|
||||
if owns_transaction: connection.execute('COMMIT')
|
||||
except BaseException:
|
||||
if owns_transaction: connection.execute('ROLLBACK')
|
||||
raise
|
||||
|
||||
def append(self, *, task_id='', task_name='', project_path='', operation='',
|
||||
state='recorded', summary='', details=None, source_key=None,
|
||||
timestamp_utc=None) -> int:
|
||||
fields=(task_id,task_name,project_path,operation,state,summary)
|
||||
if not all(isinstance(value,str) for value in fields):
|
||||
raise ValueError('history fields must be strings')
|
||||
if source_key is not None and (not isinstance(source_key,str) or not source_key):
|
||||
raise ValueError('history source identity must be a nonempty string')
|
||||
if details is not None and not isinstance(details,dict):
|
||||
raise ValueError('history details must be an object')
|
||||
if timestamp_utc is None:
|
||||
instant=datetime.now(timezone.utc)
|
||||
else:
|
||||
if not isinstance(timestamp_utc,str):
|
||||
raise ValueError('history timestamp must be an ISO string with timezone')
|
||||
try:instant=datetime.fromisoformat(timestamp_utc.replace('Z','+00:00'))
|
||||
except ValueError as error:raise ValueError('invalid history timestamp') from error
|
||||
if instant.tzinfo is None or instant.utcoffset() is None:
|
||||
raise ValueError('history timestamp requires a timezone')
|
||||
timestamp=instant.astimezone(timezone.utc).isoformat(timespec='microseconds').replace('+00:00','Z')
|
||||
details_json=json.dumps(details or {},ensure_ascii=False,allow_nan=False,sort_keys=True)
|
||||
search_text=' '.join((*fields,details_json)).casefold()
|
||||
with self.store.transaction():
|
||||
connection=self.store._connection
|
||||
if source_key is not None:
|
||||
prior=connection.execute('SELECT event_id FROM operation_history_sources WHERE source_key=?',
|
||||
(source_key,)).fetchone()
|
||||
if prior is not None: return int(prior[0])
|
||||
cursor=connection.execute('''INSERT INTO operation_history
|
||||
(timestamp_utc,task_id,task_name,project_path,operation,state,summary,details_json,search_text)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)''',(timestamp,*fields,details_json,search_text))
|
||||
identifier=int(cursor.lastrowid)
|
||||
if source_key is not None:
|
||||
connection.execute('INSERT INTO operation_history_sources VALUES (?,?)',(source_key,identifier))
|
||||
return identifier
|
||||
|
||||
def page(self, *, query='', state='', before_id=None, limit=100, read_control=None) -> HistoryPage:
|
||||
if not isinstance(query,str) or len(query)>1000 or not isinstance(state,str):
|
||||
raise ValueError('invalid history search')
|
||||
if type(limit) is not int or not 1<=limit<=500:
|
||||
raise ValueError('history page limit must be 1..500')
|
||||
if before_id is not None and (type(before_id) is not int or before_id<1):
|
||||
raise ValueError('invalid history page cursor')
|
||||
conditions=['event_id>(SELECT cleared_through_id FROM operation_history_meta WHERE singleton=1)']
|
||||
parameters=[]
|
||||
if state:
|
||||
conditions.append('state=?'); parameters.append(state)
|
||||
for term in query.casefold().split():
|
||||
conditions.append("search_text LIKE ? ESCAPE '\\'")
|
||||
parameters.append('%'+term.replace('\\','\\\\').replace('%','\\%').replace('_','\\_')+'%')
|
||||
where=' AND '.join(conditions)
|
||||
with self._read(read_control) as connection:
|
||||
total=int(connection.execute('SELECT COUNT(*) FROM operation_history WHERE '+where,parameters).fetchone()[0])
|
||||
all_total=(int(connection.execute('''SELECT COUNT(*) FROM operation_history
|
||||
WHERE event_id>(SELECT cleared_through_id FROM operation_history_meta WHERE singleton=1)''').fetchone()[0])
|
||||
if query.strip() or state else total)
|
||||
checkpoint(read_control)
|
||||
if before_id is not None:
|
||||
cursor=connection.execute('SELECT timestamp_utc FROM operation_history WHERE '+where+
|
||||
' AND event_id=?',(*parameters,before_id)).fetchone()
|
||||
if cursor is None:
|
||||
raise ValueError('history cursor is no longer available; refresh latest records')
|
||||
where+=' AND (timestamp_utc<? OR (timestamp_utc=? AND event_id<?))'
|
||||
parameters.extend((cursor[0],cursor[0],before_id))
|
||||
records=connection.execute('SELECT * FROM operation_history WHERE '+where+
|
||||
' ORDER BY timestamp_utc DESC,event_id DESC LIMIT ?',(*parameters,limit+1)).fetchall()
|
||||
rows=[]
|
||||
for row in records[:limit]:
|
||||
checkpoint(read_control)
|
||||
value={key:row[key] for key in row.keys() if key not in {'details_json','search_text'}}
|
||||
value['details']=json.loads(row['details_json'])
|
||||
rows.append(value)
|
||||
next_cursor=rows[-1]['event_id'] if len(records)>limit else None
|
||||
return HistoryPage(tuple(rows),next_cursor,total,all_total)
|
||||
|
||||
def clear_snapshot(self) -> HistoryClearSnapshot:
|
||||
with self._read() as connection:
|
||||
row=connection.execute('''SELECT COALESCE(MAX(event_id),0),COUNT(*) FROM operation_history
|
||||
WHERE event_id>(SELECT cleared_through_id FROM operation_history_meta WHERE singleton=1)''').fetchone()
|
||||
return HistoryClearSnapshot(int(row[0]),int(row[1]))
|
||||
|
||||
def clear(self, cutoff_id: int) -> int:
|
||||
if type(cutoff_id) is not int or cutoff_id<0:
|
||||
raise ValueError('invalid history clear boundary')
|
||||
with self.store.transaction():
|
||||
connection=self.store._connection
|
||||
sequence=connection.execute("SELECT seq FROM sqlite_sequence WHERE name='operation_history'").fetchone()
|
||||
if cutoff_id>(int(sequence[0]) if sequence is not None else 0):
|
||||
raise ValueError('history clear boundary is in the future')
|
||||
connection.execute('''UPDATE operation_history_meta
|
||||
SET cleared_through_id=MAX(cleared_through_id,?) WHERE singleton=1''',(cutoff_id,))
|
||||
return connection.execute('DELETE FROM operation_history WHERE event_id<=?',(cutoff_id,)).rowcount
|
||||
@@ -121,6 +121,12 @@ def _stage_new_round(service, task_id, transition):
|
||||
Path(source).rename(destination)
|
||||
for member in completed:
|
||||
store.reset_completed_round(member.task_id, summary)
|
||||
from .execution_journal import ExecutionJournal
|
||||
from .history_store import HistoryRepository
|
||||
ExecutionJournal(store).start_round(member.task_id, round_id)
|
||||
HistoryRepository(store).append(task_id=member.task_id, task_name=member.name,
|
||||
operation='start_new_round', summary='原轮次已归档,已明确开始新一轮;需重新采集并确认。',
|
||||
details={'round_id': round_id}, source_key=f'round:{member.task_id}:{round_id}')
|
||||
store.record_round_commit(round_id)
|
||||
return tuple(store.get_task(t.task_id) for t in completed), journal_root
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from functools import lru_cache
|
||||
import inspect
|
||||
@@ -64,6 +64,7 @@ class QuickRunBatchSession:
|
||||
command_header: str
|
||||
target_command_rows: dict[str, str]
|
||||
worker_paths: tuple[str, str]
|
||||
journal_rows: dict[str, dict] = field(default_factory=dict)
|
||||
|
||||
|
||||
class _ProcessRunner(Protocol):
|
||||
@@ -103,6 +104,14 @@ class QuickRunPreparer:
|
||||
discovery_matches: dict[str, dict[tuple[str, str], frozenset[str]]] | None = None,
|
||||
discovery_failures: dict[str, str] | None = None,
|
||||
) -> QuickRunResult:
|
||||
from .handoff_guard import assert_handoff_intact
|
||||
# Preserve the public preparation errors (and diagnostic entries) for
|
||||
# known pending/malformed status before checking the complete handoff.
|
||||
existing_root = self._data_root / 'quick-run'
|
||||
_assert_no_pending_status(existing_root / 'status.tsv', existing_root / 'quick-part-replace.log')
|
||||
assert_handoff_intact(self._data_root / 'quick-run', task_id)
|
||||
if getattr(self, 'journal', None) is not None:
|
||||
self.journal.assert_can_prepare(task_id)
|
||||
selected_projects = _queue_projects(projects)
|
||||
enabled_rules = tuple(rule for rule in rules if rule.enabled)
|
||||
if not selected_projects:
|
||||
@@ -142,7 +151,9 @@ class QuickRunPreparer:
|
||||
)
|
||||
initial_status = _initial_discovery_status(
|
||||
command_path,
|
||||
discovery_matches,
|
||||
# Native completion receipts need a full semantic readback, including
|
||||
# zero-match sheets; a part-number-only inventory cannot certify it.
|
||||
None if getattr(self,'journal',None) is not None and self._process_runner is _run_process else discovery_matches,
|
||||
discovery_failures,
|
||||
)
|
||||
_io_path(status_path).write_text(
|
||||
@@ -262,6 +273,7 @@ class QuickRunPreparer:
|
||||
source = self._required_script_source()
|
||||
if source.resolve() != handoff.script_path.resolve():
|
||||
copy_worker_script(source, handoff.script_path)
|
||||
journal_rows = self._bind_journal_handoff(task_id, handoff)
|
||||
commands = _read_commands(handoff.command_path)
|
||||
command_options = _read_command_options(handoff.command_path)
|
||||
statuses = _read_status_details(handoff.status_path)
|
||||
@@ -304,8 +316,52 @@ class QuickRunPreparer:
|
||||
command_lines[0],
|
||||
target_command_rows,
|
||||
_vbs_worker_paths(handoff.script_path, handoff.script_path.parent),
|
||||
journal_rows,
|
||||
)
|
||||
|
||||
def _bind_journal_handoff(self, task_id, handoff):
|
||||
journal = getattr(self, 'journal', None)
|
||||
if journal is None:
|
||||
return {}
|
||||
from .execution_journal import read_command_rows
|
||||
rows = read_command_rows(handoff.command_path)
|
||||
details = _read_status_details(handoff.status_path)
|
||||
latest = {job: (state, code, message) for job, state, code, message in details}
|
||||
restored = journal.bind(task_id, rows, latest,
|
||||
proof_reader=lambda row,outcome:self.result_proof(handoff.command_path.parent,row,outcome))
|
||||
additional = tuple((job, *outcome) for job, outcome in restored.items() if latest.get(job) != outcome)
|
||||
if additional:
|
||||
_write_status_details(handoff.status_path, (*details, *additional))
|
||||
return {row['job_id']: row for row in rows}
|
||||
|
||||
def reconcile_terminal_receipts(self, task_id):
|
||||
journal = getattr(self, 'journal', None)
|
||||
if journal is None or not journal.needs_reconciliation(task_id):
|
||||
return
|
||||
root = self._data_root/'quick-run'
|
||||
from .handoff_guard import assert_handoff_intact
|
||||
assert_handoff_intact(root, task_id)
|
||||
try:
|
||||
self._bind_journal_handoff(task_id, QuickRunResult(root/'QuickPartReplace.vbs',
|
||||
root/'command.tsv', root/'status.tsv', root/'quick-part-replace.log', self.vbs_root_compatible))
|
||||
except TaskCenterError:
|
||||
_write_uncertain_flag(root/'uncertain.flag','uncommitted_receipt_requires_verification')
|
||||
raise
|
||||
|
||||
def result_proof(self, root, row, outcome, *, persist=True):
|
||||
from .execution_proof import capture_result
|
||||
return capture_result(self._data_root,root,row,outcome,
|
||||
strict=self._process_runner is _run_process,persist=persist)
|
||||
|
||||
def write_expected_baselines(self, task_id, root, project_path):
|
||||
journal=getattr(self,'journal',None)
|
||||
if journal is None:return
|
||||
rows=journal.expected_baselines(task_id,project_path)
|
||||
text='project_path\tschematic_name\tsheet_number\tsemantic_state\r\n'
|
||||
text+=''.join('\t'.join(_encode_vbs_field(row[key]) for key in
|
||||
('project_path','schematic_name','sheet_number','state'))+'\r\n' for row in rows)
|
||||
_write_atomic_queue_text(root/'expected-baselines.tsv',text,'quick_run_uncertain','无法发布已核验工程基线。')
|
||||
|
||||
@contextmanager
|
||||
def project_session_scope(self, *, enabled=True, runtime=None):
|
||||
"""Retain only the built-in supervised worker; injected workers stay compatible."""
|
||||
@@ -384,6 +440,7 @@ class QuickRunPreparer:
|
||||
source = self._required_script_source()
|
||||
if source.resolve() != handoff.script_path.resolve():
|
||||
copy_worker_script(source, handoff.script_path)
|
||||
journal_rows = self._bind_journal_handoff(task_id, handoff)
|
||||
commands = _read_commands(handoff.command_path)
|
||||
before = _read_status_details(handoff.status_path)
|
||||
selected_command = _next_unfinished_command(commands, before)
|
||||
@@ -403,6 +460,12 @@ class QuickRunPreparer:
|
||||
selected_command[1],
|
||||
)
|
||||
batch_request = handoff.script_path.parent / "batch.request"
|
||||
journal = getattr(self, 'journal', None)
|
||||
journal_attempt = None
|
||||
if journal is not None:
|
||||
row = (batch_session.journal_rows if batch_session is not None else journal_rows)[selected_command[1]]
|
||||
self.write_expected_baselines(task_id,handoff.command_path.parent,selected_command[2])
|
||||
journal_attempt = journal.claim(task_id, row)
|
||||
current_command_stamp = None
|
||||
if batch_mode:
|
||||
if batch_session is not None:
|
||||
@@ -465,11 +528,17 @@ class QuickRunPreparer:
|
||||
if completed.returncode == 2 and after == before:
|
||||
_append_log(handoff.log_path, "quick_run_attach_failure exit_code=2")
|
||||
detail = completed.stderr.strip() or completed.stdout.strip() or "DxDesigner attachment failed"
|
||||
if journal_attempt is not None:
|
||||
self._record_rejected_attempt(journal_attempt, handoff, selected_command, before,
|
||||
projects, detail)
|
||||
raise TaskCenterError("quick_run_session", _session_failure_message(detail))
|
||||
if completed.returncode == 3:
|
||||
if after == before:
|
||||
_append_log(handoff.log_path, "quick_run_pre_mutation_failure exit_code=3")
|
||||
detail = completed.stderr.strip() or completed.stdout.strip() or "DxDesigner pre-mutation validation failed"
|
||||
if journal_attempt is not None:
|
||||
self._record_rejected_attempt(journal_attempt, handoff, selected_command, before,
|
||||
projects, detail)
|
||||
raise TaskCenterError("quick_run_session", detail)
|
||||
_write_uncertain_flag(uncertain_path, "contradictory_pre_mutation_status")
|
||||
_append_log(handoff.log_path, "quick_run_uncertain pre_mutation_exit_status_changed exit_code=3")
|
||||
@@ -565,6 +634,16 @@ class QuickRunPreparer:
|
||||
if next_command is not None and batch_session.sheets is not None
|
||||
else (None, None)
|
||||
)
|
||||
if journal_attempt is not None:
|
||||
if progress is None:
|
||||
progress = _progress_from_queue(tuple(project for project in projects if project.selected and project.available),
|
||||
commands, after, _read_command_sheet_targets(handoff.command_path))
|
||||
try:
|
||||
proof=self.result_proof(handoff.command_path.parent,row,(state,code,message))
|
||||
journal.finish(journal_attempt, state, code, message, progress=progress,proof=proof)
|
||||
except Exception:
|
||||
_write_uncertain_flag(uncertain_path, 'receipt_commit_failed')
|
||||
raise
|
||||
return QuickRunStepResult(
|
||||
handoff.script_path,
|
||||
handoff.command_path,
|
||||
@@ -586,6 +665,18 @@ class QuickRunPreparer:
|
||||
return read_snapshot(self, task_id, projects, rules,
|
||||
copy_part_number_to_value=copy_part_number_to_value, read_control=read_control)
|
||||
|
||||
def _record_rejected_attempt(self, attempt, handoff, command, before, projects, message):
|
||||
"""Known pre-mutation exit + unchanged status is a safe failure, not an unknown write."""
|
||||
outcome=(command[1], BATCH_FAILED_STATE, 'pre_mutation_rejected', message)
|
||||
_write_status_details(handoff.status_path, (*before, outcome))
|
||||
progress=_progress_from_queue(tuple(project for project in projects if project.selected and project.available),
|
||||
_read_commands(handoff.command_path), (*before,outcome), _read_command_sheet_targets(handoff.command_path))
|
||||
try:
|
||||
self.journal.finish(attempt, *outcome[1:], progress=progress)
|
||||
except Exception:
|
||||
_write_uncertain_flag(handoff.command_path.parent/'uncertain.flag', 'rejection_receipt_commit_failed')
|
||||
raise
|
||||
|
||||
def has_interrupted(self, task_id: str) -> bool:
|
||||
return self.read_snapshot(task_id, (), ()).interrupted
|
||||
|
||||
@@ -611,6 +702,8 @@ class QuickRunPreparer:
|
||||
value_mode: str,
|
||||
) -> QuickRunResult | None:
|
||||
root = self._data_root / "quick-run"
|
||||
from .handoff_guard import assert_handoff_intact
|
||||
assert_handoff_intact(root, task_id)
|
||||
command_path = root / "command.tsv"
|
||||
status_path = root / "status.tsv"
|
||||
if not _io_path(command_path).is_file() or not _io_path(status_path).is_file():
|
||||
|
||||
@@ -16,6 +16,9 @@ def failed_native_result_uncertain(root, commands, statuses, *, files=None):
|
||||
for _, job, *_ in commands:
|
||||
if latest.get(job) != api.BATCH_FAILED_STATE:
|
||||
continue
|
||||
if any(entry[0]==job and (entry[2]==str(-2147221504+879) or 'QuickPartReplace.Baseline' in entry[3])
|
||||
for entry in statuses):
|
||||
return True
|
||||
if api._rollback_marker_verified(root, job):
|
||||
continue
|
||||
path = root / f'snapshot-{job}.tsv.native.json'
|
||||
@@ -143,6 +146,17 @@ def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_
|
||||
progress = QuickRunProgress(0, len(expected), api._optional_path(first[0]), first[1], first[2], (), False)
|
||||
current = preparer._data_root / 'quick-run'
|
||||
history = preparer._data_root / 'quick-run-history'
|
||||
from .handoff_guard import assert_handoff_intact
|
||||
files.track_root(current)
|
||||
if any(internal_path(preparer.data_root/name).exists() for name in ('recovery-commit.json','retry-preparation.json')):
|
||||
progress=replace(progress,next_project_path=None,next_old_part_number=None,next_new_part_number=None)
|
||||
return QuickRunSnapshot(progress,True,current,True,'retry')
|
||||
try:
|
||||
assert_handoff_intact(current, task_id, files=files)
|
||||
except TaskCenterError:
|
||||
progress = replace(progress, next_project_path=None, next_old_part_number=None,
|
||||
next_new_part_number=None)
|
||||
return QuickRunSnapshot(progress, True, current, True, 'selection')
|
||||
root = None
|
||||
commands = ()
|
||||
# Avoid enumerating history when the active handoff already matches.
|
||||
@@ -169,11 +183,26 @@ def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_
|
||||
break
|
||||
if root is None:
|
||||
files.checkpoint()
|
||||
journal = getattr(preparer, 'journal', None)
|
||||
if journal is not None and journal.has_plan(task_id):
|
||||
progress = replace(progress, next_project_path=None, next_old_part_number=None, next_new_part_number=None)
|
||||
return QuickRunSnapshot(progress, True, current, True, 'selection')
|
||||
return QuickRunSnapshot(progress, False, None, False, 'selection')
|
||||
interrupted = root == current and (internal_path(root / 'uncertain.flag')).is_file()
|
||||
phase = 'selection'
|
||||
try:
|
||||
details = api._read_status_details(files.path(root / 'status.tsv'))
|
||||
journal = getattr(preparer, 'journal', None)
|
||||
if journal is not None:
|
||||
from .execution_journal import read_command_rows
|
||||
rows = read_command_rows(root / 'command.tsv')
|
||||
outcomes = {job: (state, code, message) for job, state, code, message in details}
|
||||
interrupted = interrupted or journal.conflicts(task_id, rows, outcomes)
|
||||
if journal.needs_reconciliation(task_id):
|
||||
for row in rows:
|
||||
outcome=outcomes.get(row['job_id'])
|
||||
if outcome and outcome[0] in api.TERMINAL_STATES:
|
||||
preparer.result_proof(root,row,outcome,persist=False)
|
||||
files.checkpoint()
|
||||
if root == current:
|
||||
latest = {job_id: state for job_id, state, _, _ in details}
|
||||
@@ -198,6 +227,6 @@ def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_
|
||||
if progress.queue_complete:
|
||||
phase = 'retry' if progress.failed_items else 'complete'
|
||||
except TaskCenterError:
|
||||
pass
|
||||
interrupted=True
|
||||
files.checkpoint()
|
||||
return QuickRunSnapshot(progress, True, root, interrupted, phase)
|
||||
@@ -108,6 +108,9 @@ def require_current_cell_binding(snapshot, binding, project, metadata):
|
||||
def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=False, confirmed=False, runtime=None):
|
||||
if not confirmed:
|
||||
raise TaskCenterError('quick_run_recovery_confirmation', '核验恢复需要明确确认,不能作为自动重试执行。')
|
||||
from .recovery_commit import marker_path, publish, stage
|
||||
if marker_path(preparer).is_file():
|
||||
return publish(preparer,task_id,projects,rules,copy_part_number_to_value)
|
||||
maintain_quick_run_storage(preparer._data_root)
|
||||
root = preparer._data_root / 'quick-run'
|
||||
uncertain = root / 'uncertain.flag'
|
||||
@@ -124,6 +127,13 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
if not _value_mode_matches_option(mode, copy_part_number_to_value) or len({command[1] for command in commands}) != len(commands):
|
||||
raise TaskCenterError('quick_run_recovery', 'Value 策略变化或队列编号重复,已停止恢复。')
|
||||
selected = _recovery_command(commands, before, root=root)
|
||||
journal=getattr(preparer,'journal',None)
|
||||
if journal is not None:
|
||||
from .execution_journal import read_command_rows
|
||||
unresolved=journal.unresolved_jobs(task_id,read_command_rows(root/'command.tsv'))
|
||||
if len(unresolved)>1:
|
||||
raise TaskCenterError('quick_run_recovery','多项尝试尚未核验,请保留原证据逐项核对。')
|
||||
if unresolved:selected=next(command for command in commands if command[1]==unresolved[0])
|
||||
if selected is None:
|
||||
raise TaskCenterError('quick_run_recovery', '队列记录已完成但仍有保护锁,需要单独核对,未自动解除。')
|
||||
job_id = _safe_run_token(selected[1])
|
||||
@@ -242,42 +252,10 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
if _recovery_hashes(root) != evidence_before or (worker / snapshot.name).read_bytes() != snapshot.read_bytes():
|
||||
raise TaskCenterError('quick_run_recovery', '核验期间原始证据变化,未提交恢复结果。')
|
||||
state = after[0][1]
|
||||
command_bytes = (root / 'command.tsv').read_bytes()
|
||||
status_bytes = (root / 'status.tsv').read_bytes()
|
||||
recovery_record = {'task_id': task_id, 'job_id': job_id, 'state': state, 'worker_result': after[0],
|
||||
'snapshot_sha256': binding['snapshot_sha256'], 'evidence_before': evidence_before,
|
||||
'project_before': project_before, 'native_replacement_called': False}
|
||||
(audit / 'recovery.json').write_text(json.dumps(recovery_record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
try:
|
||||
if state == 'retry_ready':
|
||||
lines = (root / 'command.tsv').read_text(encoding='utf-8-sig').splitlines()
|
||||
column = lines[0].split('\t').index('job_id')
|
||||
retry_id = uuid4().hex + '_retry'
|
||||
for index in range(1, len(lines)):
|
||||
fields = lines[index].split('\t')
|
||||
if fields[column] == job_id:
|
||||
fields[column] = retry_id
|
||||
lines[index] = '\t'.join(fields)
|
||||
temporary = root / ('command-' + uuid4().hex + '.tmp')
|
||||
temporary.write_text('\n'.join(lines) + '\n', encoding='utf-8')
|
||||
os.replace(temporary, root / 'command.tsv')
|
||||
_write_status_details(root / 'status.tsv', tuple(entry for entry in before if entry[0] != job_id))
|
||||
else:
|
||||
_write_status_details(root / 'status.tsv', (*before, after[0]))
|
||||
os.replace(uncertain, audit / 'resolved-uncertain.flag')
|
||||
except Exception:
|
||||
(root / 'command.tsv').write_bytes(command_bytes)
|
||||
(root / 'status.tsv').write_bytes(status_bytes)
|
||||
if not uncertain.exists():
|
||||
uncertain.write_text('recovery commit interrupted; reconciliation required', encoding='ascii')
|
||||
raise
|
||||
progress = preparer.progress(task_id, projects, rules, copy_part_number_to_value=copy_part_number_to_value)
|
||||
message = ('磁盘工程与替换前快照一致,只读核验工程已关闭,已准备新的执行编号;尚未再次替换,请确认后执行。'
|
||||
if state == 'retry_ready' else
|
||||
'已从磁盘核验本项结果并恢复任务记录,工程已关闭;没有重复执行原生替换。'
|
||||
if after[0][2] == 'recovery_saved_verified' else
|
||||
'已核验并恢复本项任务记录;没有重复执行原生替换。若补做了属性恢复,请保存当前工程。')
|
||||
return QuickRunStepResult(root / 'QuickPartReplace.vbs', root / 'command.tsv', root / 'status.tsv',
|
||||
audit / 'worker-output.txt', state, message, progress.next_project_path,
|
||||
progress.next_old_part_number, progress.next_new_part_number,
|
||||
progress.next_schematic_name, progress.next_sheet_number)
|
||||
from .batch_resources import write_record
|
||||
write_record(audit/'recovery.json',recovery_record)
|
||||
stage(preparer,task_id,audit,job_id,before,after[0])
|
||||
return publish(preparer,task_id,projects,rules,copy_part_number_to_value)
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Durable, replayable file/SQLite handoff after an explicitly verified recovery."""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from .batch_resources import write_record
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
def marker_path(preparer):
|
||||
return internal_path(preparer.data_root/'recovery-commit.json')
|
||||
|
||||
|
||||
def stage(preparer, task_id, audit, job_id, before, outcome):
|
||||
root=internal_path(preparer.data_root/'quick-run')
|
||||
lines=(root/'command.tsv').read_text(encoding='utf-8-sig').splitlines()
|
||||
if outcome[1]=='retry_ready':
|
||||
column=lines[0].split('\t').index('job_id')
|
||||
retry=uuid4().hex+'_retry'
|
||||
for index in range(1,len(lines)):
|
||||
fields=lines[index].split('\t')
|
||||
if fields[column]==job_id:
|
||||
fields[column]=retry;lines[index]='\t'.join(fields)
|
||||
record={'task_id':task_id,'audit_name':audit.name,
|
||||
'audit_sha256':hashlib.sha256((audit/'recovery.json').read_bytes()).hexdigest(),
|
||||
'command_before_sha256':hashlib.sha256((root/'command.tsv').read_bytes()).hexdigest(),
|
||||
'status_before_sha256':hashlib.sha256((root/'status.tsv').read_bytes()).hexdigest(),
|
||||
'command_after':'\n'.join(lines)+'\n',
|
||||
'statuses_after':[entry for entry in before if entry[0]!=job_id] if outcome[1]=='retry_ready' else [*before,outcome]}
|
||||
write_record(marker_path(preparer),record)
|
||||
|
||||
|
||||
def publish(preparer, task_id, projects, rules, copy_part_number_to_value):
|
||||
from .quick_run import _write_atomic_queue_text, _write_status_details, QuickRunStepResult
|
||||
marker=marker_path(preparer)
|
||||
try:
|
||||
record=json.loads(marker.read_text(encoding='utf8'))
|
||||
name=record['audit_name']
|
||||
if record['task_id']!=task_id or not name.startswith('recovery-') or len(name)!=41 or any(c not in '0123456789abcdef' for c in name[9:]):
|
||||
raise ValueError('invalid recovery commit identity')
|
||||
audit=internal_path(preparer.data_root/'quick-run-history'/name)
|
||||
if hashlib.sha256((audit/'recovery.json').read_bytes()).hexdigest()!=record['audit_sha256']:
|
||||
raise ValueError('recovery audit changed')
|
||||
recovery=json.loads((audit/'recovery.json').read_text(encoding='utf8'))
|
||||
if recovery['task_id']!=task_id or recovery['native_replacement_called'] is not False:
|
||||
raise ValueError('invalid recovery proof')
|
||||
root=preparer.data_root/'quick-run'
|
||||
# Reject edits to either original or published files during the handoff.
|
||||
from .quick_run import _encode_vbs_field
|
||||
statuses='job_id\tstate\tcode\tmessage\r\n'+''.join('\t'.join(_encode_vbs_field(v) for v in row)+'\r\n' for row in record['statuses_after'])
|
||||
for filename,after,before_key in (('command.tsv',record['command_after'],'command_before_sha256'),
|
||||
('status.tsv',statuses,'status_before_sha256')):
|
||||
actual=hashlib.sha256((root/filename).read_bytes()).hexdigest()
|
||||
if actual not in {record[before_key],hashlib.sha256(after.encode('utf8')).hexdigest()}:
|
||||
raise ValueError('recovery publication evidence changed')
|
||||
command_before=(root/'command.tsv').read_bytes()
|
||||
status_before=(root/'status.tsv').read_bytes()
|
||||
uncertain=root/'uncertain.flag'
|
||||
try:
|
||||
_write_atomic_queue_text(root/'command.tsv',record['command_after'],'quick_run_recovery','无法发布已核验恢复记录。')
|
||||
_write_status_details(root/'status.tsv',tuple(tuple(row) for row in record['statuses_after']))
|
||||
if uncertain.exists():os.replace(uncertain,audit/'resolved-uncertain.flag')
|
||||
except BaseException:
|
||||
(root/'command.tsv').write_bytes(command_before)
|
||||
(root/'status.tsv').write_bytes(status_before)
|
||||
if not uncertain.exists():uncertain.write_text('recovery commit interrupted',encoding='ascii')
|
||||
raise
|
||||
from .quick_run import _progress_from_queue, _read_commands, _read_command_sheet_targets
|
||||
progress=_progress_from_queue(tuple(p for p in projects if p.selected and p.available),
|
||||
_read_commands(root/'command.tsv'),tuple(tuple(row) for row in record['statuses_after']),
|
||||
_read_command_sheet_targets(root/'command.tsv'))
|
||||
state=recovery['state']
|
||||
message=('磁盘工程与替换前快照一致,已准备新的执行编号;尚未再次替换,请确认后执行。'
|
||||
if state=='retry_ready' else '已从磁盘核验并恢复本项记录;没有重复执行原生替换。')
|
||||
if getattr(preparer,'journal',None) is None:marker.unlink()
|
||||
return QuickRunStepResult(root/'QuickPartReplace.vbs',root/'command.tsv',root/'status.tsv',
|
||||
audit/'worker-output.txt',state,message,progress.next_project_path,progress.next_old_part_number,
|
||||
progress.next_new_part_number,progress.next_schematic_name,progress.next_sheet_number)
|
||||
except (ValueError,KeyError,TypeError) as error:
|
||||
raise TaskCenterError('quick_run_recovery','恢复提交记录与证据不一致,已停止;请保留全部记录。') from error
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Recoverable publication of a retry queue; original evidence stays authoritative."""
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
from .batch_resources import write_record
|
||||
from .errors import TaskCenterError
|
||||
from .path_access import internal_path
|
||||
|
||||
|
||||
def marker_path(preparer):
|
||||
return internal_path(preparer.data_root/'retry-preparation.json')
|
||||
|
||||
|
||||
def recover_startup(root,store):
|
||||
from types import SimpleNamespace
|
||||
root=internal_path(root)
|
||||
markers=(root/'retry-preparation.json',*(root/'tasks').glob('*/retry-preparation.json'))
|
||||
for marker in markers:
|
||||
if marker.is_file():
|
||||
record=json.loads(marker.read_text(encoding='utf8'))
|
||||
recover_publication(SimpleNamespace(data_root=marker.parent),store,record['task_id'])
|
||||
|
||||
|
||||
def recover_publication(preparer, store, task_id):
|
||||
marker = marker_path(preparer)
|
||||
if not marker.exists(): return
|
||||
try:
|
||||
record = json.loads(marker.read_text(encoding='utf8'))
|
||||
token = record['transition_id']
|
||||
if record['task_id'] != task_id or len(token)!=32 or any(c not in '0123456789abcdef' for c in token):
|
||||
raise ValueError('invalid retry transition identity')
|
||||
root = internal_path(preparer.data_root/'quick-run')
|
||||
stage = internal_path(preparer.data_root/('.retry-stage-'+token)/'quick-run')
|
||||
archive = internal_path(preparer.data_root/'quick-run-history'/('obsolete-retry-'+token))
|
||||
committed = store._connection.execute('SELECT 1 FROM execution_transitions WHERE transition_id=?', (token,)).fetchone()
|
||||
if not committed and archive.exists():
|
||||
if root.exists():
|
||||
if stage.exists(): raise ValueError('retry staging conflict')
|
||||
stage.parent.mkdir(parents=True,exist_ok=True)
|
||||
os.replace(root, stage)
|
||||
os.replace(archive, root)
|
||||
if not root.is_dir(): raise ValueError('original retry evidence missing')
|
||||
marker.unlink()
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
raise TaskCenterError('quick_run_uncertain', '重试队列发布未收尾,请保留原队列和暂存记录后核验。') from error
|
||||
|
||||
|
||||
@contextmanager
|
||||
def stage_publication(preparer, store, task_id):
|
||||
"""Caller owns the outer SQL transaction and runs recovery after commit/rollback."""
|
||||
token = uuid4().hex
|
||||
stage = preparer.for_data_root(preparer.data_root/('.retry-stage-'+token))
|
||||
stage.journal = preparer.journal
|
||||
current = internal_path(preparer.data_root/'quick-run')
|
||||
archive = internal_path(preparer.data_root/'quick-run-history'/('obsolete-retry-'+token))
|
||||
write_record(marker_path(preparer), {'task_id':task_id, 'transition_id':token})
|
||||
yield stage, current
|
||||
archive.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(current, archive)
|
||||
os.replace(internal_path(stage.data_root/'quick-run'), current)
|
||||
store._connection.execute('INSERT INTO execution_transitions VALUES (?,?)', (token,task_id))
|
||||
@@ -132,7 +132,14 @@ class TaskCenterService:
|
||||
# another window must not start a batch while startup rewrites state.
|
||||
self._runner = runner or TrialRunner(store, logging_context, probe_source_resolver=probe_source_resolver,
|
||||
**({'recover_on_startup': False} if not recover_on_startup else {}))
|
||||
if runner is None and recover_on_startup:
|
||||
from .retry_preparation import recover_startup
|
||||
recover_startup(logging_context.root,store)
|
||||
self._quick_run_preparer = quick_run_preparer or QuickRunPreparer(logging_context.root)
|
||||
from .execution_journal import ExecutionJournal
|
||||
self._quick_run_preparer.journal = ExecutionJournal(store, self._synchronize_quick_run_progress)
|
||||
from .history_recording import initialize_history_import
|
||||
initialize_history_import(store)
|
||||
self._batch_feedback = None
|
||||
self._project_facades: dict[str, TaskCenterService] = {}
|
||||
self._facade_lock = threading.RLock()
|
||||
@@ -220,15 +227,18 @@ class TaskCenterService:
|
||||
if self._quick_run_preparer.data_root == child_root:
|
||||
return self
|
||||
with self._facade_lock:
|
||||
if task_id not in self._project_facades:
|
||||
child_preparer = self._quick_run_preparer.for_data_root(child_root)
|
||||
# Initializing a new runner replays startup recovery and mutates
|
||||
# the database. A facade shares the initialized runner instead.
|
||||
child = TaskCenterService(self._store, self._logging, path_opener=self._path_opener,
|
||||
clock=self._clock, quick_run_preparer=child_preparer, runner=self._runner)
|
||||
child._supervised = self._supervised
|
||||
self._project_facades[task_id] = child
|
||||
return self._project_facades[task_id]
|
||||
existing=self._project_facades.get(task_id)
|
||||
if existing is not None:
|
||||
return existing
|
||||
# Construction can acquire the database lock (history upgrade boundary).
|
||||
# Do not hold the cache lock: a DB snapshot reader can request a facade
|
||||
# while another thread is initializing one. Only publish under the lock.
|
||||
child_preparer = self._quick_run_preparer.for_data_root(child_root)
|
||||
child = TaskCenterService(self._store, self._logging, path_opener=self._path_opener,
|
||||
clock=self._clock, quick_run_preparer=child_preparer, runner=self._runner)
|
||||
child._supervised = self._supervised
|
||||
with self._facade_lock:
|
||||
return self._project_facades.setdefault(task_id,child)
|
||||
|
||||
def _project_task_service(self, task_id: str) -> "TaskCenterService":
|
||||
return self._facade_for_task_record(self._store.get_task(task_id))
|
||||
@@ -293,6 +303,11 @@ class TaskCenterService:
|
||||
interrupted = snapshot.interrupted
|
||||
has_evidence = snapshot.has_evidence
|
||||
phase = snapshot.phase
|
||||
if facade._quick_run_preparer.journal.requires_retry(task_id) and not interrupted:
|
||||
phase = 'retry'
|
||||
elif (not interrupted and task.summary == 'current-sheet quick-run queue completed with retryable failures'
|
||||
and any(project.status is ProjectStatus.FAILED for project in projects)):
|
||||
phase = 'retry'
|
||||
context = ProjectTaskContext(task, bound, tuple(rules), tuple(targets), progress,
|
||||
phase, has_evidence, interrupted, legacy)
|
||||
return context
|
||||
@@ -660,6 +675,28 @@ class TaskCenterService:
|
||||
def layout_settings_path(self) -> Path:
|
||||
return self._logging.root / "ui-layout.ini"
|
||||
|
||||
def operation_history_page(self, *, query='', state='', before_id=None, limit=100, read_control=None):
|
||||
from .history_recording import ensure_legacy_history
|
||||
from .history_store import HistoryRepository
|
||||
ensure_legacy_history(self, read_control)
|
||||
return HistoryRepository(self._store).page(query=query, state=state, before_id=before_id,
|
||||
limit=limit, read_control=read_control)
|
||||
|
||||
def operation_history_clear_snapshot(self):
|
||||
from .history_recording import ensure_legacy_history
|
||||
from .history_store import HistoryRepository
|
||||
ensure_legacy_history(self)
|
||||
return HistoryRepository(self._store).clear_snapshot()
|
||||
|
||||
def clear_operation_history(self, cutoff_id):
|
||||
from .history_recording import ensure_legacy_history
|
||||
from .history_store import HistoryRepository
|
||||
from .task_queue import assert_task_queue_idle
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
ensure_legacy_history(self)
|
||||
return HistoryRepository(self._store).clear(cutoff_id)
|
||||
|
||||
def can_edit_value_options(self, task_id: str) -> bool:
|
||||
task = self._store.get_task(task_id)
|
||||
return (
|
||||
@@ -797,10 +834,12 @@ class TaskCenterService:
|
||||
if delegated is not self:
|
||||
return delegated.prepare_failed_quick_run(task_id, runtime=runtime)
|
||||
def prepare_retry() -> QuickRunProgress:
|
||||
from .retry_preparation import recover_publication
|
||||
recover_publication(self._quick_run_preparer, self._store, task_id)
|
||||
task = self._store.get_task(task_id)
|
||||
if self._quick_run_preparer.has_interrupted(task_id):
|
||||
raise TaskCenterError('quick_run_uncertain', '原生替换结果尚未核验,不能归档或重试。请先核验并恢复。')
|
||||
if task.status is not TaskStatus.RUNNING:
|
||||
if task.status is not TaskStatus.RUNNING and not self._quick_run_preparer.journal.requires_retry(task_id):
|
||||
raise TaskCenterError("quick_run_task_state", "当前任务没有可重试的失败项")
|
||||
progress = self._quick_run_preparer.progress(
|
||||
task_id,
|
||||
@@ -821,28 +860,38 @@ class TaskCenterService:
|
||||
)
|
||||
if not failed_projects:
|
||||
raise TaskCenterError("quick_run_complete", "当前队列没有可重试的失败工程")
|
||||
self._quick_run_preparer.archive_current_handoff(task_id)
|
||||
for project in failed_projects:
|
||||
self._store.set_project_status(
|
||||
project.project_id,
|
||||
ProjectStatus.PENDING,
|
||||
summary="project queued for retry",
|
||||
)
|
||||
append_task_event(
|
||||
self._logging,
|
||||
level="INFO",
|
||||
task_id=task_id,
|
||||
operation="quick_run_retry_prepared",
|
||||
message="失败工程已重新加入队列",
|
||||
details={"project_ids": [project.project_id for project in failed_projects]},
|
||||
)
|
||||
self._quick_run_preparer.ensure_batch_handoff(
|
||||
task_id,
|
||||
self._store.list_projects(task_id),
|
||||
self._execution_rules(task_id),
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
runtime=runtime,
|
||||
)
|
||||
from .batch_backup import inherit_backup_for_retry
|
||||
from .history_store import HistoryRepository
|
||||
from .quick_run import _read_sheet_manifest, _queue_projects
|
||||
from .retry_preparation import stage_publication, recover_publication
|
||||
try:
|
||||
with self._store.transaction():
|
||||
self._quick_run_preparer.journal.authorize_retry(task_id)
|
||||
with stage_publication(self._quick_run_preparer, self._store, task_id) as (staged, original):
|
||||
# Use the frozen sheet scope. Successful exact targets
|
||||
# now have new parts and must never be rediscovered as old.
|
||||
sheets = (_read_sheet_manifest(original/'sheets.tsv')
|
||||
if (original/'sheets.tsv').is_file() else None)
|
||||
for project in failed_projects:
|
||||
self._store.set_project_status(project.project_id, ProjectStatus.PENDING,
|
||||
summary='project queued for retry')
|
||||
if sheets is not None:
|
||||
eligible={_path_key(project.path) for project in
|
||||
_queue_projects(self._store.list_projects(task_id))}
|
||||
sheets={key:value for key,value in sheets.items() if key in eligible}
|
||||
handoff = staged.prepare(task_id, self._store.list_projects(task_id),
|
||||
self._execution_rules(task_id), sheet_targets=sheets,
|
||||
copy_part_number_to_value=task.copy_part_number_to_value)
|
||||
inherit_backup_for_retry(original, handoff.command_path.parent, task_id)
|
||||
staged._bind_journal_handoff(task_id, handoff)
|
||||
task = self._store.set_task_status(task_id, TaskStatus.RUNNING,
|
||||
summary='failed items prepared; successful receipts preserved')
|
||||
HistoryRepository(self._store).append(task_id=task_id,task_name=task.name,
|
||||
operation='quick_run_retry_prepared',summary='已准备失败项及暂缓项,原成功项的完成回执保留。',
|
||||
details={'project_ids':[project.project_id for project in failed_projects]})
|
||||
finally:
|
||||
# Covers the actual SQL COMMIT boundary, including failed commits.
|
||||
recover_publication(self._quick_run_preparer, self._store, task_id)
|
||||
return self._quick_run_preparer.progress(
|
||||
task_id,
|
||||
self._store.list_projects(task_id),
|
||||
@@ -903,11 +952,35 @@ class TaskCenterService:
|
||||
**control_options(stop_event, on_progress)))
|
||||
|
||||
def _pause_quick_run_queue(self, task_id: str, message: str) -> None:
|
||||
from .history_store import HistoryRepository
|
||||
self._quick_run_preparer.journal.pause(task_id)
|
||||
if self._store.get_task(task_id).status is TaskStatus.RUNNING:
|
||||
self._store.set_task_status(task_id, TaskStatus.PAUSED, summary=message)
|
||||
with self._store.transaction():
|
||||
task = self._store.set_task_status(task_id, TaskStatus.PAUSED, summary=message)
|
||||
HistoryRepository(self._store).append(task_id=task_id, task_name=task.name,
|
||||
operation='quick_run_queue_paused', state='paused', summary=message)
|
||||
append_task_event(self._logging, level='INFO', task_id=task_id,
|
||||
operation='quick_run_queue_paused', message=message)
|
||||
|
||||
def _record_safe_queue_failure(self, task_id, message):
|
||||
"""Hold this project's untouched remainder; ordinary continue must not retry it."""
|
||||
from .history_store import HistoryRepository
|
||||
with self._store.transaction():
|
||||
task=self._store.get_task(task_id)
|
||||
summary='current-sheet quick-run queue completed with retryable failures'
|
||||
if task.summary==summary:return
|
||||
for project in self._store.list_projects(task_id):
|
||||
if project.selected and project.status is not ProjectStatus.COMPLETED:
|
||||
self._store.set_project_status(project.project_id,ProjectStatus.FAILED,
|
||||
summary='quick_run_result:failed | '+message)
|
||||
if task.status in {TaskStatus.DRAFT,TaskStatus.READY,TaskStatus.PAUSED}:
|
||||
self._store.set_task_status(task_id,TaskStatus.RUNNING,summary=summary)
|
||||
elif task.status is TaskStatus.RUNNING:
|
||||
self._store.set_task_status(task_id,TaskStatus.RUNNING,summary=summary)
|
||||
HistoryRepository(self._store).append(task_id=task_id,task_name=task.name,
|
||||
operation='工程执行收尾',state='failed',summary='本工程安全失败,剩余项暂缓;继续后续工程。',
|
||||
details={'reason':message})
|
||||
|
||||
def batch_feedback(self):
|
||||
return self._batch_feedback
|
||||
|
||||
@@ -982,8 +1055,34 @@ class TaskCenterService:
|
||||
result = recover(self._quick_run_preparer, task_id, projects,
|
||||
self._execution_rules(task_id), copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
confirmed=confirmed, runtime=runtime)
|
||||
from .execution_journal import read_command_rows
|
||||
import json
|
||||
handoff_root = result.command_path.parent
|
||||
audit = json.loads((result.log_path.parent / 'recovery.json').read_text(encoding='utf8'))
|
||||
before_rows = read_command_rows(result.log_path.parent / 'evidence-before' / 'command.tsv')
|
||||
recovered_row = next(row for row in before_rows if row['job_id'] == audit['job_id'])
|
||||
native_result = audit['worker_result']
|
||||
from .execution_proof import capture_recovery
|
||||
from .quick_run import _run_process
|
||||
proof=capture_recovery(self._quick_run_preparer.data_root,result.log_path.parent,
|
||||
recovered_row,tuple(native_result[1:]),strict=self._quick_run_preparer._process_runner is _run_process)
|
||||
if not self._quick_run_preparer.journal.has_plan(task_id):
|
||||
# Upgrade legacy evidence into a frozen plan before committing
|
||||
# this verified recovery, so its proof is not re-imported from
|
||||
# the former active handoff (which has no new semantic sidecar).
|
||||
self._quick_run_preparer.journal.bind(task_id,before_rows,{})
|
||||
self._quick_run_preparer.journal.reconcile_recovery(task_id, recovered_row,
|
||||
result.state, native_result[2], native_result[3], recovery_id=result.log_path.parent.name,proof=proof)
|
||||
# The former current-command refers to the completed old attempt;
|
||||
# its preserved copy remains in the recovery audit directory.
|
||||
(handoff_root / 'current-command.tsv').unlink(missing_ok=True)
|
||||
self._quick_run_preparer._bind_journal_handoff(task_id,
|
||||
QuickRunResult(result.script_path, result.command_path, result.status_path,
|
||||
handoff_root/'quick-part-replace.log', True))
|
||||
if task.status in {TaskStatus.PAUSED, TaskStatus.FAILED}:
|
||||
self._store.set_task_status(task_id, TaskStatus.READY, summary="interrupted quick-run reconciled")
|
||||
from .recovery_commit import marker_path
|
||||
marker_path(self._quick_run_preparer).unlink(missing_ok=True)
|
||||
self._synchronize_quick_run_progress(task_id)
|
||||
append_task_event(self._logging, level="INFO", task_id=task_id, operation="quick_run_recovered",
|
||||
message=result.message, details={"state": result.state, "evidence": str(result.log_path.parent)})
|
||||
@@ -1134,7 +1233,8 @@ class TaskCenterService:
|
||||
from .task_queue import assert_task_queue_idle
|
||||
assert_task_queue_idle(self._logging.root)
|
||||
with _quick_run_lease(self._logging.root):
|
||||
return self._operation(name, task_id, action)
|
||||
from .history_recording import record_operation
|
||||
return self._operation(name, task_id, lambda: record_operation(self, name, task_id, action))
|
||||
|
||||
def _manual_operation(self, name: str, task_id: str, action: Callable[[], _Result]) -> _Result:
|
||||
def checked_action():
|
||||
@@ -1237,6 +1337,8 @@ class TaskCenterService:
|
||||
def _retryable_quick_run(self, task_id: str) -> bool:
|
||||
task = self._store.get_task(task_id)
|
||||
return (
|
||||
self._project_task_service(task_id)._quick_run_preparer.journal.requires_retry(task_id)
|
||||
) or (
|
||||
task.status is TaskStatus.RUNNING
|
||||
and task.summary == "current-sheet quick-run queue completed with retryable failures"
|
||||
and any(project.status is ProjectStatus.FAILED for project in self._store.list_projects(task_id))
|
||||
|
||||
@@ -4,7 +4,7 @@ from __future__ import annotations
|
||||
from .errors import TaskCenterError
|
||||
from .models import ProjectStatus, TaskStatus
|
||||
|
||||
_SCHEMA_VERSION = 7
|
||||
_SCHEMA_VERSION = 8
|
||||
_V1_ATTEMPTLESS_ACTIVE_STATES = {ProjectStatus.CAPTURING_BEFORE, ProjectStatus.AWAITING_OPERATOR, ProjectStatus.CAPTURING_AFTER, ProjectStatus.VERIFYING}
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ class StoreSchema:
|
||||
elif int(version_row["value"]) == 3:
|
||||
self._store._create_external_request_schema()
|
||||
self._store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
|
||||
elif int(version_row["value"]) in {4, 5, 6}:
|
||||
elif int(version_row["value"]) in {4, 5, 6, 7}:
|
||||
self._store._connection.execute("UPDATE metadata SET value = ? WHERE key = 'schema_version'", (str(_SCHEMA_VERSION),))
|
||||
elif int(version_row["value"]) != _SCHEMA_VERSION:
|
||||
raise TaskCenterError("schema_version", "task database schema version is unsupported")
|
||||
@@ -56,6 +56,10 @@ class StoreSchema:
|
||||
request_id TEXT PRIMARY KEY, request_hash TEXT NOT NULL, result_json TEXT NOT NULL)''')
|
||||
self._store._connection.execute('''CREATE TABLE IF NOT EXISTS assistant_task_operations (
|
||||
request_id TEXT PRIMARY KEY, request_hash TEXT NOT NULL, result_json TEXT NOT NULL)''')
|
||||
from .history_store import create_history_schema
|
||||
from .execution_journal import create_execution_schema
|
||||
create_history_schema(self._store._connection)
|
||||
create_execution_schema(self._store._connection)
|
||||
|
||||
def _create_schema_v1(self) -> None:
|
||||
statements = (
|
||||
|
||||
@@ -17,7 +17,8 @@ from .quick_run import _write_atomic_queue_text
|
||||
_QUEUE_LOCK = Lock()
|
||||
_QUEUE_OWNER: int | None = None
|
||||
_SAFE_FAILURES = frozenset({'quick_run_preflight', 'quick_run_session', 'quick_run_backup',
|
||||
'target_identity', 'empty_target_scope', 'enabled_rule_required'})
|
||||
'target_identity', 'empty_target_scope', 'enabled_rule_required',
|
||||
'quick_run_retry_required'})
|
||||
_TERMINAL = frozenset({'completed', 'failed', 'skipped'})
|
||||
|
||||
|
||||
@@ -201,6 +202,8 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
try:
|
||||
if child.has_interrupted_quick_run(task_id):
|
||||
raise TaskCenterError('quick_run_uncertain', '该任务有待核验步骤。')
|
||||
if hasattr(child, '_quick_run_preparer'):
|
||||
child._quick_run_preparer.reconcile_terminal_receipts(task_id)
|
||||
progress = child.quick_run_progress(task_id)
|
||||
if progress.queue_complete:
|
||||
entry = {'state': 'failed' if getattr(progress, 'failed_items', 0) else 'completed',
|
||||
@@ -222,14 +225,21 @@ def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
|
||||
result.last_result is not None and result.last_result.state == 'batch_saved_unverified'
|
||||
):
|
||||
raise TaskCenterError('quick_run_uncertain', '保存结果尚未确认,任务队列已停止。')
|
||||
incomplete = result.paused or not result.progress.queue_complete
|
||||
entry = {'state': 'paused' if incomplete else (
|
||||
safe_failure = bool(getattr(result, 'safe_failure', False))
|
||||
incomplete = not safe_failure and (result.paused or not result.progress.queue_complete)
|
||||
entry = {'state': 'failed' if safe_failure else 'paused' if incomplete else (
|
||||
'failed' if getattr(result.progress, 'failed_items', 0) else 'completed'),
|
||||
'message': '已安全暂停。' if incomplete else '任务已收尾。'}
|
||||
'message': '本工程安全失败,剩余项暂缓,继续后续工程。' if safe_failure else
|
||||
'已安全暂停。' if incomplete else '任务已收尾。'}
|
||||
if incomplete:
|
||||
paused = True
|
||||
except TaskCenterError as error:
|
||||
safe = error.code in _SAFE_FAILURES and not child.has_interrupted_quick_run(task_id)
|
||||
if safe and hasattr(child, '_record_safe_queue_failure'):
|
||||
try:
|
||||
child._record_safe_queue_failure(task_id, error.message)
|
||||
except Exception:
|
||||
safe = False # Failure admission must itself be durable before proceeding.
|
||||
entry = {'state': 'failed' if safe else 'blocked', 'message': error.message}
|
||||
paused = not safe
|
||||
except Exception as error:
|
||||
|
||||
@@ -8,7 +8,8 @@ def pending_batch_tasks(tasks, group_id):
|
||||
if not group_id:
|
||||
return ()
|
||||
return tuple(sorted((task for task in tasks if task.group_id == group_id
|
||||
and task.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}),
|
||||
and task.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}
|
||||
and getattr(task, 'summary', '') != 'current-sheet quick-run queue completed with retryable failures'),
|
||||
key=lambda task: task.group_position))
|
||||
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ def icon(name: str, primary: bool = False) -> QIcon:
|
||||
|
||||
BUTTON_ICONS = {
|
||||
'task_center_navigation': 'grid', 'dsh_navigation': 'chat',
|
||||
'history_navigation': 'clock',
|
||||
'newTaskButton': 'plus', 'editTaskButton': 'sliders', 'deleteTaskButton': 'trash',
|
||||
'selectAllTasks': 'check', 'clearTaskSelection': 'close',
|
||||
'restoreTaskButton': 'refresh', 'taskRecycleBin': 'trash',
|
||||
|
||||
@@ -51,6 +51,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._dsh_authorized_tasks = set()
|
||||
self.task_center_action = QAction('任务中心', self)
|
||||
self.task_center_action.triggered.connect(lambda: self.content_stack.setCurrentIndex(0))
|
||||
self.history_action = QAction('操作历史', self)
|
||||
self.history_action.setShortcut('Ctrl+Shift+H')
|
||||
self.history_action.triggered.connect(lambda: self.content_stack.setCurrentWidget(self.history_panel))
|
||||
self.dsh_action = QAction('DSH助手', self)
|
||||
self.dsh_action.setShortcut('Ctrl+Shift+D')
|
||||
self.dsh_action.triggered.connect(self._open_dsh)
|
||||
@@ -63,7 +66,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
brand = QLabel('DxPartReplace', objectName='applicationBrand')
|
||||
navigation_layout.addWidget(brand)
|
||||
navigation_layout.addSpacing(24)
|
||||
for name, action in (('task_center_navigation', self.task_center_action), ('dsh_navigation', self.dsh_action)):
|
||||
for name, action in (('task_center_navigation', self.task_center_action),
|
||||
('history_navigation', self.history_action), ('dsh_navigation', self.dsh_action)):
|
||||
action.setCheckable(True)
|
||||
self._navigation_actions.addAction(action)
|
||||
self.addAction(action)
|
||||
@@ -254,11 +258,24 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
layout.addWidget(self.workspace_splitter)
|
||||
self.content_stack = QStackedWidget()
|
||||
self.content_stack.addWidget(container)
|
||||
self.content_stack.currentChanged.connect(lambda index: (
|
||||
self.task_center_action if index == 0 else self.dsh_action).setChecked(True))
|
||||
from .operation_history import OperationHistoryPage
|
||||
self.history_panel = OperationHistoryPage(self.service, self)
|
||||
self.history_panel.busy_changed.connect(self._history_activity_changed)
|
||||
self.content_stack.addWidget(self.history_panel)
|
||||
self.content_stack.currentChanged.connect(self._workspace_changed)
|
||||
self.setCentralWidget(self.content_stack)
|
||||
self._reset_layout()
|
||||
|
||||
def _workspace_changed(self, index):
|
||||
history = self.content_stack.widget(index) is self.history_panel
|
||||
(self.task_center_action if index == 0 else self.history_action if history else self.dsh_action).setChecked(True)
|
||||
self.history_panel.set_active(history)
|
||||
|
||||
def _history_activity_changed(self):
|
||||
self._update_gates()
|
||||
if self._close_pending and self.history_panel._worker is None and not self._workers and not self._closed:
|
||||
QTimer.singleShot(0, self.close)
|
||||
|
||||
def _layout_widgets(self):
|
||||
return {'workspace': self.workspace_splitter, 'detail': self.detail_splitter,
|
||||
'rules': self.mapping_table.horizontalHeader(), 'targets': self.plan_panel.table.horizontalHeader()}
|
||||
@@ -302,7 +319,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
if self._close_saving:
|
||||
event.ignore()
|
||||
return
|
||||
if self._workers or (self._dsh_operations and self._dsh_operations.worker):
|
||||
if self._workers or self.history_panel._worker or (self._dsh_operations and self._dsh_operations.worker):
|
||||
self._close_pending = True
|
||||
self.plan_panel.cancel_operation()
|
||||
self._pause_queue()
|
||||
@@ -346,6 +363,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._layout_settings.setValue(f'single_project/{name}', widget.saveState())
|
||||
self._layout_settings.setValue('tasks/sort', self.task_list.sort.currentData())
|
||||
self._closed = True
|
||||
self.history_panel.shutdown()
|
||||
if self._dsh_operations:
|
||||
self._dsh_operations.close()
|
||||
self._context_query.close()
|
||||
@@ -438,8 +456,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
|
||||
self._task_context_failed(error)
|
||||
|
||||
def _update_gates(self):
|
||||
busy = bool(self._workers) or self._loading
|
||||
busy = bool(self._workers) or self._loading or self.history_panel._worker is not None
|
||||
resources_pending = self._resource_status.blocked
|
||||
self.history_panel.set_mutations_enabled(not busy and not resources_pending and self._batch_stop is None)
|
||||
self.run_panel.cleanup_resources_button.setVisible(resources_pending and self._resource_status.known)
|
||||
self.run_panel.cleanup_resources_button.setEnabled(resources_pending and self._resource_status.known and not busy)
|
||||
state = execution_state(self._context, busy=busy,
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
"""Searchable user operation history; never participates in execution admission."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
import json
|
||||
|
||||
from PySide6.QtCore import QSignalBlocker, QThreadPool, QTimer, Qt, Slot, Signal
|
||||
from PySide6.QtWidgets import (QAbstractItemView, QComboBox, QHBoxLayout, QHeaderView,
|
||||
QLabel, QLineEdit, QMessageBox, QPlainTextEdit, QPushButton, QSplitter,
|
||||
QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget)
|
||||
|
||||
from .icons import icon
|
||||
from .queries import LatestQuery
|
||||
from .workers import ServiceWorker
|
||||
|
||||
|
||||
STATES={'verified':'已核验完成','no_match':'未命中','failed':'失败','failed_safe':'已确认安全失败',
|
||||
'uncertain':'待核验','saved_unverified':'保存待核验','skipped':'已跳过','recorded':'已记录',
|
||||
'running':'执行中','paused':'已暂停','pending':'待执行','restored':'已恢复'}
|
||||
OPERATIONS={'quick_run_executed':'替换执行','quick_run_prepared':'准备执行',
|
||||
'quick_run_recovered':'核验恢复','quick_run_queue_paused':'暂停执行',
|
||||
'quick_run_retry_prepared':'准备失败项重试','create_project_tasks':'创建工程任务',
|
||||
'create_task':'新建任务','update_task':'编辑任务','delete_task':'归档任务',
|
||||
'restore_task':'恢复任务','purge_task':'删除任务记录','add_rule':'添加规则',
|
||||
'update_rule':'修改规则','delete_rule':'删除规则','move_rule':'调整规则顺序',
|
||||
'replace_target_plan':'保存位号计划','save_plan_drafts':'保存位号计划',
|
||||
'save_bom_batch':'保存 BOM 计划','start_new_round':'开始新一轮',
|
||||
'set_value_policy':'修改 Value 策略','value_policy_changed':'修改 Value 策略',
|
||||
'execution_skipped':'跳过已完成项','execution_receipt':'执行结果'}
|
||||
DETAIL_LABELS={'refdes':'位号','old_part_number':'旧料号','new_part_number':'新料号',
|
||||
'old_part':'旧料号','new_part':'新料号','schematic_name':'原理图','sheet_number':'图页',
|
||||
'target_cell':'目标 Cell','custom_value':'自定义 Value','custom_value_enabled':'启用自定义 Value',
|
||||
'sync_nc':'同步 NC','project_path':'工程','before':'修改前','after':'修改后',
|
||||
'name':'任务名称','note':'备注','enabled':'启用','summary':'说明',
|
||||
'copy_part_number_to_value':'复制料号到 Value','copy_part_label_to_value':'复制料号到 Value'}
|
||||
|
||||
|
||||
def _timestamp(value):
|
||||
try:return datetime.fromisoformat(value.replace('Z','+00:00')).astimezone().strftime('%Y-%m-%d %H:%M:%S')
|
||||
except (TypeError,ValueError,AttributeError):return str(value or '')
|
||||
|
||||
|
||||
def _details_text(details):
|
||||
def translated(value):
|
||||
if isinstance(value,dict):
|
||||
return {DETAIL_LABELS.get(key,key):translated(item) for key,item in value.items()}
|
||||
if isinstance(value,list):return [translated(item) for item in value]
|
||||
return value
|
||||
return json.dumps(translated(details),ensure_ascii=False,indent=2) if details else '此记录没有更多改动详情。'
|
||||
|
||||
|
||||
class OperationHistoryPage(QWidget):
|
||||
busy_changed = Signal()
|
||||
def __init__(self, service, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setObjectName('operationHistoryPage')
|
||||
self.service=service
|
||||
self._active=False
|
||||
self._closed=False
|
||||
self._mutations_enabled=True
|
||||
self._rows=()
|
||||
self._next_cursor=None
|
||||
self._before_id=None
|
||||
self._total=0
|
||||
self._all_total=0
|
||||
self._worker=None
|
||||
self._clear_success=False
|
||||
self._query=LatestQuery(self)
|
||||
self._clear_query=LatestQuery(self)
|
||||
self._query.settled.connect(self._buttons)
|
||||
self._clear_query.settled.connect(self._buttons)
|
||||
|
||||
title=QLabel('操作历史',objectName='projectTitle')
|
||||
description=QLabel('查看工具实际记录的操作与改动。清空历史不会重置任务进度或执行结果。')
|
||||
description.setWordWrap(True)
|
||||
self.search=QLineEdit(objectName='historySearch')
|
||||
self.search.setPlaceholderText('搜索任务、工程、位号、新旧料号或改动说明')
|
||||
self.search.setClearButtonEnabled(True)
|
||||
self.search.addAction(icon('search'),QLineEdit.ActionPosition.LeadingPosition)
|
||||
self.state_filter=QComboBox(objectName='historyStateFilter')
|
||||
self.state_filter.setAccessibleName('操作结果筛选')
|
||||
self.state_filter.addItem('全部结果','')
|
||||
for state in ('verified','no_match','failed','uncertain','restored','running','skipped','recorded'):
|
||||
self.state_filter.addItem(STATES[state],state)
|
||||
self.refresh_button=QPushButton('刷新/返回最新',objectName='historyRefresh')
|
||||
self.refresh_button.setIcon(icon('refresh'))
|
||||
self.clear_button=QPushButton('清空全部历史',objectName='historyClear')
|
||||
self.clear_button.setIcon(icon('trash'))
|
||||
self.clear_button.setToolTip('只清理操作历史,不删除任务、完成回执、工程或备份。执行/恢复期间不可清空。')
|
||||
toolbar=QHBoxLayout()
|
||||
toolbar.addWidget(self.search,1);toolbar.addWidget(self.state_filter)
|
||||
toolbar.addWidget(self.refresh_button);toolbar.addWidget(self.clear_button)
|
||||
self.summary=QLabel('还未读取操作历史',objectName='historySummary')
|
||||
self.table=QTableWidget(0,5,objectName='operationHistoryTable')
|
||||
self.table.setHorizontalHeaderLabels(['时间','任务/CBB','操作','结果','改动摘要'])
|
||||
self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
self.table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
|
||||
self.table.setAlternatingRowColors(True)
|
||||
self.table.verticalHeader().hide()
|
||||
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
|
||||
self.table.horizontalHeader().setStretchLastSection(True)
|
||||
for column,width in enumerate((170,180,130,105,330)):
|
||||
self.table.setColumnWidth(column,width)
|
||||
self.table.setMinimumHeight(150)
|
||||
self.empty_hint=QLabel('还没有操作历史。新的操作会在完成后记录在这里。',objectName='historyEmpty')
|
||||
self.empty_hint.setWordWrap(True)
|
||||
self.empty_hint.setAlignment(Qt.AlignmentFlag.AlignCenter)
|
||||
self.empty_hint.hide()
|
||||
self.details=QPlainTextEdit(objectName='historyDetails')
|
||||
self.details.setReadOnly(True)
|
||||
self.details.setPlaceholderText('选择一条记录,查看工程、操作结果和改动详情。')
|
||||
self.details.setMinimumHeight(70)
|
||||
splitter=QSplitter(Qt.Orientation.Vertical)
|
||||
splitter.setChildrenCollapsible(False)
|
||||
splitter.addWidget(self.table);splitter.addWidget(self.details)
|
||||
splitter.setStretchFactor(0,4);splitter.setStretchFactor(1,1)
|
||||
splitter.setSizes((400,130))
|
||||
self.status=QLabel(objectName='historyStatus')
|
||||
self.status.setWordWrap(True)
|
||||
self.older_button=QPushButton('更早记录',objectName='historyOlder')
|
||||
self.older_button.setIcon(icon('clock'))
|
||||
footer=QHBoxLayout();footer.addWidget(self.status,1);footer.addWidget(self.older_button)
|
||||
layout=QVBoxLayout(self)
|
||||
layout.setContentsMargins(24,18,24,16);layout.setSpacing(12)
|
||||
layout.addWidget(title);layout.addWidget(description);layout.addLayout(toolbar)
|
||||
layout.addWidget(self.summary);layout.addWidget(self.empty_hint)
|
||||
layout.addWidget(splitter,1);layout.addLayout(footer)
|
||||
|
||||
self._search_timer=QTimer(self)
|
||||
self._search_timer.setSingleShot(True);self._search_timer.setInterval(180)
|
||||
self._search_timer.timeout.connect(self.refresh)
|
||||
self.search.textChanged.connect(self._search_changed)
|
||||
self.state_filter.currentIndexChanged.connect(self.refresh)
|
||||
self.refresh_button.clicked.connect(self.refresh)
|
||||
self.older_button.clicked.connect(self._older)
|
||||
self.clear_button.clicked.connect(self._prepare_clear)
|
||||
self.table.itemSelectionChanged.connect(self._detail_selected)
|
||||
self._timer=QTimer(self);self._timer.setInterval(3000)
|
||||
self._timer.timeout.connect(self._poll)
|
||||
self._buttons()
|
||||
|
||||
def set_active(self, active):
|
||||
if self._closed:return
|
||||
self._active=bool(active)
|
||||
if active:
|
||||
self._timer.start()
|
||||
self._read(self._before_id)
|
||||
else:
|
||||
self._timer.stop();self._search_timer.stop()
|
||||
self._query.invalidate();self._clear_query.invalidate()
|
||||
|
||||
def set_mutations_enabled(self, enabled):
|
||||
self._mutations_enabled=bool(enabled)
|
||||
self._buttons()
|
||||
|
||||
def shutdown(self):
|
||||
self._closed=True;self._active=False
|
||||
self._timer.stop();self._search_timer.stop()
|
||||
self._query.close();self._clear_query.close()
|
||||
|
||||
def _buttons(self):
|
||||
if self._closed:return
|
||||
clearing=self._worker is not None or self._clear_query.current_busy
|
||||
self.clear_button.setEnabled(self._mutations_enabled and not clearing and self._all_total>0)
|
||||
self.older_button.setEnabled(not self._query.current_busy and self._next_cursor is not None and not clearing)
|
||||
self.refresh_button.setEnabled(not clearing)
|
||||
|
||||
def _search_changed(self):
|
||||
if self._closed:return
|
||||
self._query.invalidate()
|
||||
self._search_timer.start()
|
||||
|
||||
def refresh(self):
|
||||
if not self._active or self._closed or self._worker is not None:return
|
||||
self._search_timer.stop()
|
||||
self._read(None)
|
||||
|
||||
def _poll(self):
|
||||
if (self._before_id is None and not self._query.current_busy
|
||||
and not self._search_timer.isActive() and not self._clear_query.current_busy):
|
||||
self.refresh()
|
||||
|
||||
def _older(self):
|
||||
if self._next_cursor is not None:self._read(self._next_cursor)
|
||||
|
||||
def _read(self, before_id):
|
||||
if not self._active or self._closed:return
|
||||
query=self.search.text().strip();state=self.state_filter.currentData()
|
||||
self.status.setText('正在读取操作历史…')
|
||||
def received(page):
|
||||
self._before_id=before_id
|
||||
self._next_cursor=page.next_cursor
|
||||
self._total=page.total
|
||||
self._all_total=page.all_total if getattr(page,'all_total',None) is not None else page.total
|
||||
self._render(page.rows)
|
||||
self.summary.setText(f'共 {page.total} 条符合条件的记录 · 本页 {len(page.rows)} 条')
|
||||
self.status.setText('正在查看较早记录;点击刷新可返回最新。' if before_id is not None else '最新记录')
|
||||
self.empty_hint.setText('没有符合条件的操作历史。请调整搜索或结果筛选。' if query or state else
|
||||
'还没有操作历史。新的操作会在完成后记录在这里。')
|
||||
self.empty_hint.setVisible(not page.rows)
|
||||
self._buttons()
|
||||
def failed(error):
|
||||
self.status.setText('历史读取失败,可点击刷新重试。'+str(getattr(error,'message','')))
|
||||
self._buttons()
|
||||
self._query.request(lambda control:self.service.operation_history_page(query=query,state=state,
|
||||
before_id=before_id,limit=100,read_control=control),received,failed,cancellable=True)
|
||||
self._buttons()
|
||||
|
||||
def _render(self, rows):
|
||||
current=self.table.currentRow()
|
||||
selected_id=self._rows[current]['event_id'] if 0<=current<len(self._rows) else None
|
||||
self._rows=tuple(rows)
|
||||
with QSignalBlocker(self.table):
|
||||
self.table.setRowCount(len(rows))
|
||||
selected_row=None
|
||||
for row,record in enumerate(rows):
|
||||
values=(_timestamp(record['timestamp_utc']),record['task_name'] or record['task_id'],
|
||||
OPERATIONS.get(record['operation'],record['operation']),
|
||||
STATES.get(record['state'],record['state']),record['summary'])
|
||||
for column,value in enumerate(values):
|
||||
item=QTableWidgetItem(str(value));item.setToolTip(str(value))
|
||||
self.table.setItem(row,column,item)
|
||||
if record['event_id']==selected_id:selected_row=row
|
||||
if selected_row is not None:self.table.selectRow(selected_row)
|
||||
else:self.table.clearSelection();self.table.setCurrentCell(-1,-1)
|
||||
self._detail_selected()
|
||||
|
||||
def _detail_selected(self):
|
||||
selected=self.table.selectionModel().selectedRows()
|
||||
if not selected:
|
||||
self.details.clear();return
|
||||
row=selected[0].row()
|
||||
if not 0<=row<len(self._rows):return
|
||||
record=self._rows[row]
|
||||
self.details.setPlainText('\n'.join((f"时间:{_timestamp(record['timestamp_utc'])}",
|
||||
f"任务:{record['task_name'] or record['task_id']}",f"工程:{record['project_path'] or '此操作未绑定工程'}",
|
||||
f"操作:{OPERATIONS.get(record['operation'],record['operation'])}",
|
||||
f"结果:{STATES.get(record['state'],record['state'])}",f"说明:{record['summary']}",
|
||||
'',_details_text(record['details']))))
|
||||
|
||||
def _prepare_clear(self):
|
||||
if (self._closed or not self._active or not self._mutations_enabled
|
||||
or self._worker is not None or self._clear_query.current_busy):return
|
||||
self._clear_query.request(self.service.operation_history_clear_snapshot,self._confirm_clear,
|
||||
lambda _:self.status.setText('无法读取清空范围,历史记录保留,请重试。'))
|
||||
self._buttons()
|
||||
|
||||
def _confirm_clear(self, snapshot):
|
||||
if self._closed or not self._active or not self._mutations_enabled:return
|
||||
if snapshot.count==0:
|
||||
self.status.setText('没有需要清空的历史记录。');return
|
||||
answer=QMessageBox.question(self,'清空全部历史',
|
||||
f'将清空确认前的全部 {snapshot.count} 条操作历史,包括当前筛选之外的记录。\n'
|
||||
'任务进度、完成回执、工程、备份和诊断证据都会保留;之后的新记录不会被清空。',
|
||||
QMessageBox.StandardButton.Yes|QMessageBox.StandardButton.No,QMessageBox.StandardButton.No)
|
||||
if (answer!=QMessageBox.StandardButton.Yes or self._closed or not self._active
|
||||
or not self._mutations_enabled):return
|
||||
self._clear_success=False
|
||||
self._worker=ServiceWorker(lambda:self.service.clear_operation_history(snapshot.cutoff_id))
|
||||
self._worker.signals.succeeded.connect(self._clear_succeeded)
|
||||
self._worker.signals.failed.connect(self._clear_failed)
|
||||
self._worker.signals.finished.connect(self._clear_finished)
|
||||
self.busy_changed.emit()
|
||||
self._buttons()
|
||||
QThreadPool.globalInstance().start(self._worker)
|
||||
|
||||
@Slot(object)
|
||||
def _clear_succeeded(self, count):
|
||||
self._clear_success=True
|
||||
if not self._closed:self.status.setText(f'已清空 {count} 条历史,任务执行结果保留。')
|
||||
|
||||
@Slot(object)
|
||||
def _clear_failed(self, _error):
|
||||
if not self._closed:self.status.setText('清空失败,原历史记录保留,请重试。')
|
||||
|
||||
@Slot()
|
||||
def _clear_finished(self):
|
||||
self._worker=None
|
||||
self.busy_changed.emit()
|
||||
if self._closed:return
|
||||
self._buttons()
|
||||
if self._clear_success and self._active:self.refresh()
|
||||
Reference in new issue
Block a user