feat(dsh): add durable supervision, scheduling and operations dock
This commit is contained in:
1 parent
f861a3d386
commit
736b582bc1
46 files changed
+4122
-93
No files matched your search
@@ -0,0 +1,38 @@
|
||||
"""Safe local DSH response settings; provider credentials stay elsewhere."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
DEFAULTS = {'response_timeout_seconds': 90, 'model_context_limit': 16000}
|
||||
|
||||
|
||||
def validate(raw):
|
||||
if not isinstance(raw, dict) or set(raw) - set(DEFAULTS):
|
||||
raise ValueError('unsupported assistant setting')
|
||||
value = dict(DEFAULTS); value.update(raw)
|
||||
if type(value['response_timeout_seconds']) is not int or not 15 <= value['response_timeout_seconds'] <= 600:
|
||||
raise ValueError('response timeout must be 15..600 seconds')
|
||||
if type(value['model_context_limit']) is not int or not 2000 <= value['model_context_limit'] <= 128000:
|
||||
raise ValueError('model context limit must be 2000..128000 tokens')
|
||||
return value
|
||||
|
||||
|
||||
def load_settings(data_root):
|
||||
try:
|
||||
return validate(json.loads((Path(data_root) / 'dsh/assistant-settings.json').read_text(encoding='utf8')))
|
||||
except (OSError, ValueError, TypeError):
|
||||
return dict(DEFAULTS)
|
||||
|
||||
|
||||
def save_settings(data_root, raw):
|
||||
from ..trial_task_center.path_access import retry_sharing_violation
|
||||
value = validate(raw)
|
||||
path = Path(data_root) / 'dsh/assistant-settings.json'
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_name('settings-' + uuid4().hex + '.tmp')
|
||||
try:
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf8')
|
||||
retry_sharing_violation(lambda: temporary.replace(path), target=path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return value
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Execute a natively confirmed frozen scope and persist its actual receipt."""
|
||||
from __future__ import annotations
|
||||
|
||||
from . import task_lifecycle as tasks
|
||||
from .run_journal import RunJournal
|
||||
from .scheduling import ScheduleStore
|
||||
from ..trial_task_center.errors import TaskCenterError
|
||||
from ..trial_task_center.task_queue import execute_task_queue
|
||||
|
||||
|
||||
def execute_confirmed_run(service, root, task_ids, report, stop, run_id, *, resume=None, schedule=None):
|
||||
if tasks.fingerprint(service, task_ids) != report['fingerprint']:
|
||||
raise TaskCenterError('assistant_stale', '任务状态已变化,请重新预检后确认。')
|
||||
journal = RunJournal(root)
|
||||
schedules = ScheduleStore(root)
|
||||
initialized = False
|
||||
claimed = False
|
||||
try:
|
||||
if schedule:
|
||||
current = next((r for r in schedules.evaluate(service) if r['schedule_id'] == schedule['schedule_id']), None)
|
||||
if not current or not current['ready'] or current['plan_hashes'] != report['plan_hashes']:
|
||||
raise TaskCenterError('schedule_blocked', '排期计划、依赖或执行条件已变化,未启动。')
|
||||
schedules.claim(schedule['schedule_id']); claimed = True
|
||||
if resume:
|
||||
inspected = journal.inspect(service, resume['run_id'])
|
||||
if not inspected['resume_ready'] or inspected['plan_hashes'] != report['plan_hashes']:
|
||||
raise TaskCenterError('run_blocked', '原执行范围或证据已变化,请先核验。')
|
||||
journal.resume(run_id)
|
||||
else:
|
||||
journal.begin(run_id, task_ids, report['plan_hashes'], schedule_id=schedule['schedule_id'] if schedule else None)
|
||||
initialized = True
|
||||
result = execute_task_queue(service, tuple(task_ids), stop_event=stop,
|
||||
expected_plan_hashes=report['plan_hashes'],
|
||||
queue_id=run_id if resume and resume['queue_available'] else None,
|
||||
checkpoint_id=None if resume and resume['queue_available'] else run_id)
|
||||
except Exception as error:
|
||||
failure = {'status': 'interrupted', 'run_id': run_id, 'queue_id': run_id,
|
||||
'code': getattr(error, 'code', 'execution_interrupted'), 'message': '执行未完成,请按原队列证据核验后接续。'}
|
||||
if initialized:
|
||||
journal.finish(run_id, failure)
|
||||
if claimed:
|
||||
schedules.finish(schedule['schedule_id'], 'interrupted', run_id=run_id, receipt=failure)
|
||||
raise
|
||||
entries = [{'task_id': e.task_id, 'state': e.state, 'message': e.message} for e in result.entries]
|
||||
status = ('blocked' if result.paused and any(e['state'] == 'blocked' for e in entries)
|
||||
else 'paused' if result.paused else 'failed' if any(e['state'] == 'failed' for e in entries) else 'completed')
|
||||
receipt = {'status': status, 'run_id': run_id, 'queue_id': result.queue_id, 'paused': result.paused,
|
||||
'user_pause_requested': bool(stop.is_set()), 'awaiting_user_resume': bool(result.paused and stop.is_set()),
|
||||
'entries': entries, 'tasks': [], 'reporting_errors': [],
|
||||
'message': '请按每项实际计数判断;未命中不表示已替换保存。'}
|
||||
# Persist the executor's known outcome before optional readback/enrichment.
|
||||
journal.finish(run_id, receipt)
|
||||
for entry in entries:
|
||||
actual = {**entry, 'saved_items': None, 'failed_items': None, 'no_match_items': None,
|
||||
'interrupted': None, 'queue_complete': None}
|
||||
try:
|
||||
context = service.task_context(entry['task_id']); p = context.progress
|
||||
actual.update(name=context.task.name, saved_items=p.saved_items, failed_items=p.failed_items,
|
||||
no_match_items=p.no_match_items, interrupted=context.interrupted, queue_complete=p.queue_complete)
|
||||
except Exception as error:
|
||||
receipt['reporting_errors'].append({'task_id': entry['task_id'], 'code': getattr(error, 'code', 'context_unavailable')})
|
||||
receipt['tasks'].append(actual)
|
||||
journal.finish(run_id, receipt)
|
||||
if claimed:
|
||||
try:
|
||||
schedules.finish(schedule['schedule_id'], 'interrupted' if status in {'paused', 'blocked'} else status,
|
||||
run_id=run_id, receipt=receipt)
|
||||
except Exception as error:
|
||||
receipt['reporting_errors'].append({'code': getattr(error, 'code', 'schedule_receipt_unavailable')})
|
||||
journal.finish(run_id, receipt)
|
||||
return receipt
|
||||
@@ -0,0 +1,189 @@
|
||||
"""A bounded, read-only index of previously recorded DSH incident evidence."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
from .evidence import scrub, write_json
|
||||
|
||||
|
||||
_IDENTIFIER = re.compile(r"^[0-9a-f]{24}$")
|
||||
_KNOWN_EVIDENCE = (
|
||||
"verification.json", "snapshot.json", "snapshot-after.json", "gates.json",
|
||||
"actions.json", "diagnostics-before.zip", "diagnostics-after.zip", "manifest.json",
|
||||
)
|
||||
|
||||
|
||||
def _text(value, limit):
|
||||
# Scrub before bounding so truncation cannot expose a partial credential.
|
||||
return scrub(value)[:limit] if isinstance(value, str) else ""
|
||||
|
||||
|
||||
def _attempts(value):
|
||||
return value if type(value) is int and value in (0, 1) else 0
|
||||
|
||||
|
||||
def _retry_error(value):
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
return {key: _text(value.get(key), limit) for key, limit in
|
||||
(("type", 128), ("code", 160), ("detail", 1000))}
|
||||
|
||||
|
||||
def _outcome(verification, *, verified):
|
||||
result = {"verified": verified}
|
||||
if isinstance(verification, dict):
|
||||
for key in ("queue_complete", "interrupted", "paused"):
|
||||
if type(verification.get(key)) is bool:
|
||||
result[key] = verification[key]
|
||||
for key in ("saved_items", "failed_items", "no_match_items", "completed_items"):
|
||||
if type(verification.get(key)) is int and 0 <= verification[key] <= 10**9:
|
||||
result[key] = verification[key]
|
||||
return result
|
||||
|
||||
|
||||
def _newest(value):
|
||||
try:
|
||||
date = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
return date.replace(tzinfo=timezone.utc).timestamp() if date.tzinfo is None else date.timestamp()
|
||||
except (TypeError, ValueError, OverflowError, OSError):
|
||||
return 0
|
||||
|
||||
|
||||
class ExperienceStore:
|
||||
"""Index only incident records and named evidence files; never crawl CAD files."""
|
||||
|
||||
def __init__(self, data_root):
|
||||
self.data_root = Path(data_root)
|
||||
self.root = self.data_root / "dsh" / "incidents"
|
||||
self._rows: list[dict] = []
|
||||
|
||||
def refresh(self) -> list[dict]:
|
||||
rows = []
|
||||
if self.root.is_dir():
|
||||
for directory in sorted(self.root.iterdir(), key=lambda p: p.name):
|
||||
path = directory / "incident.json"
|
||||
if not directory.is_dir() or directory.is_symlink() or not path.is_file() or path.is_symlink():
|
||||
continue
|
||||
record = self._read_json(path, 256 * 1024)
|
||||
if not isinstance(record, dict):
|
||||
continue
|
||||
row = self._entry(directory, record)
|
||||
if row:
|
||||
rows.append(row)
|
||||
self._rows = rows
|
||||
write_json(self.data_root / "dsh" / "experience" / "index.json", {"version": 1, "entries": rows})
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def _entry(self, directory: Path, record: dict) -> dict | None:
|
||||
incident_id = str(record.get("incident_id", directory.name))
|
||||
if not _IDENTIFIER.fullmatch(incident_id) or incident_id != directory.name:
|
||||
return None
|
||||
issue_code = str(record.get("issue_code", ""))[:160]
|
||||
message = str(record.get("message", ""))[:2000]
|
||||
task_id = str(record.get("task_id", ""))[:128]
|
||||
evidence_refs = []
|
||||
# Evidence identity is explicit and bounded. Do not recurse into project/CAD files.
|
||||
for name in _KNOWN_EVIDENCE:
|
||||
candidate = directory / name
|
||||
if candidate.is_file() and not candidate.is_symlink():
|
||||
evidence_refs.append(candidate.relative_to(self.data_root).as_posix())
|
||||
verification = None
|
||||
verification_path = directory / "verification.json"
|
||||
if verification_path.is_file() and not verification_path.is_symlink():
|
||||
value = self._read_json(verification_path, 32 * 1024)
|
||||
verification = scrub(value) if isinstance(value, dict) else None
|
||||
verified = self._verified(verification, evidence_refs)
|
||||
analyses = []
|
||||
if isinstance(record.get("analyses"), list):
|
||||
for analysis in record["analyses"][:2]:
|
||||
if isinstance(analysis, dict):
|
||||
analyses.append({"phase": _text(analysis.get("phase"), 64),
|
||||
"reply": _text(analysis.get("reply", analysis.get("error")), 1500)})
|
||||
actions = {}
|
||||
actions_path = directory / "actions.json"
|
||||
if actions_path.is_file() and not actions_path.is_symlink():
|
||||
value = self._read_json(actions_path, 32 * 1024)
|
||||
if isinstance(value, dict):
|
||||
# Fixed observational fields only: model tool calls, commands and
|
||||
# claimed authorizations never become reusable execution rights.
|
||||
actions = {"attempts": _attempts(value.get("attempts")),
|
||||
"retry_error": _retry_error(value.get("retry_error")),
|
||||
"retry_skipped": _text(value.get("retry_skipped"), 1000),
|
||||
"outcome": _outcome(value.get("verification"), verified=verified)}
|
||||
newest = _text(record.get("updated_utc") or record.get("created_utc"), 64)
|
||||
if not newest:
|
||||
newest = datetime.fromtimestamp((directory / "incident.json").stat().st_mtime,
|
||||
timezone.utc).isoformat()
|
||||
return scrub({
|
||||
"incident_id": incident_id,
|
||||
"task_id": task_id,
|
||||
"issue_code": issue_code,
|
||||
"message": message,
|
||||
"status": str(record.get("status", ""))[:64],
|
||||
"verified": verified,
|
||||
"verification": verification,
|
||||
"analyses": analyses,
|
||||
"attempts": _attempts(record.get("attempts")),
|
||||
"actions": actions,
|
||||
"retry_error": _retry_error(record.get("retry_error")),
|
||||
"retry_skipped": _text(record.get("retry_skipped"), 1000),
|
||||
"outcome": _outcome(verification, verified=verified),
|
||||
"updated_utc": newest,
|
||||
"evidence_refs": evidence_refs,
|
||||
"ticket": {}, # Ticket closure is feedback, never verification.
|
||||
} | ({"task_name": str(record["task_name"])[:128]} if "task_name" in record else {}))
|
||||
|
||||
@staticmethod
|
||||
def _verified(verification, evidence_refs: list[str]) -> bool:
|
||||
# verification.json itself is the assertion; require at least one separate
|
||||
# persisted evidence artifact (snapshot, gates, or diagnostic bundle).
|
||||
if not isinstance(verification, dict) or len(evidence_refs) < 2:
|
||||
return False
|
||||
# These are persisted worker facts, rather than a model's ``resolved`` claim.
|
||||
return (verification.get("queue_complete") is True
|
||||
and type(verification.get("failed_items")) is int
|
||||
and verification.get("failed_items") == 0
|
||||
and verification.get("interrupted") is False
|
||||
and verification.get("paused") is False)
|
||||
|
||||
def search(self, issue_code: str = "", *, limit: int = 5) -> list[dict]:
|
||||
if not isinstance(limit, int) or limit <= 0:
|
||||
return []
|
||||
if not self._rows:
|
||||
self.refresh()
|
||||
query = str(issue_code or "").strip().casefold()
|
||||
matches = []
|
||||
for row in self._rows:
|
||||
context = " ".join((row.get("issue_code", ""), row.get("message", ""),
|
||||
row.get("task_id", ""), row.get("task_name", ""),
|
||||
json.dumps(row.get("analyses", []), ensure_ascii=False),
|
||||
json.dumps(row.get("actions", {}), ensure_ascii=False),
|
||||
row.get("retry_skipped", ""))).casefold()
|
||||
if not query or query in context:
|
||||
matches.append(dict(row))
|
||||
matches.sort(key=lambda row: (row.get("verified") is True,
|
||||
bool(query) and row.get("issue_code", "").casefold() == query,
|
||||
_newest(row.get("updated_utc", "")), row["incident_id"]), reverse=True)
|
||||
return matches[:min(limit, 50)]
|
||||
|
||||
def summary(self) -> dict:
|
||||
if not self._rows:
|
||||
self.refresh()
|
||||
counts = {}
|
||||
for row in self._rows:
|
||||
code = row.get("issue_code", "") or "unknown"
|
||||
counts[code] = counts.get(code, 0) + 1
|
||||
return {"total": len(self._rows), "verified": sum(bool(row["verified"]) for row in self._rows),
|
||||
"unverified": sum(not row["verified"] for row in self._rows), "by_issue_code": counts}
|
||||
|
||||
@staticmethod
|
||||
def _read_json(path, limit):
|
||||
try:
|
||||
with path.open("rb") as stream:
|
||||
raw = stream.read(limit + 1)
|
||||
return json.loads(raw) if len(raw) <= limit else None
|
||||
except (OSError, ValueError, TypeError):
|
||||
return None
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Read-only execution impact reports for saved DSH task plans.
|
||||
|
||||
This module deliberately consumes persisted task contexts and target plans only.
|
||||
It never scans CAD files or attempts to resolve mapping rules against a project.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from hashlib import sha256
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from ..trial_task_center.errors import TaskCenterError
|
||||
|
||||
|
||||
_MAX_TASKS = 20
|
||||
_MAX_LIMIT = 100
|
||||
|
||||
|
||||
def _hash(value: Any) -> str:
|
||||
encoded = json.dumps(value, sort_keys=True, ensure_ascii=False,
|
||||
separators=(",", ":"), allow_nan=False).encode("utf-8")
|
||||
return sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def _scope(task_ids: object) -> tuple[str, ...]:
|
||||
if not isinstance(task_ids, (list, tuple)) or not 1 <= len(task_ids) <= _MAX_TASKS:
|
||||
raise TaskCenterError("assistant_task_scope", "请选择 1 至 20 个不同的真实任务。")
|
||||
if any(not isinstance(task_id, str) or not task_id or len(task_id) > 128 for task_id in task_ids):
|
||||
raise TaskCenterError("assistant_task_scope", "任务编号无效。")
|
||||
if len(set(task_ids)) != len(task_ids):
|
||||
raise TaskCenterError("assistant_task_scope", "请选择 1 至 20 个不同的真实任务。")
|
||||
return tuple(task_ids)
|
||||
|
||||
|
||||
def _limit(limit: object) -> int:
|
||||
if type(limit) is not int or not 1 <= limit <= _MAX_LIMIT:
|
||||
raise TaskCenterError("assistant_impact_limit", "影响预览条数必须是 1 至 100 的整数。")
|
||||
return limit
|
||||
|
||||
|
||||
def _policy(task, row) -> tuple[str, str | None]:
|
||||
if bool(getattr(row, "custom_value_enabled", False)):
|
||||
return "custom", str(getattr(row, "custom_value", ""))
|
||||
if bool(getattr(task, "copy_part_number_to_value", False)):
|
||||
# The library label is only known during the CAD execution read. It is
|
||||
# unsafe for a preview to present the replacement part number as Value.
|
||||
return "part_label", None
|
||||
return "preserve", None
|
||||
|
||||
|
||||
def _target_row(task, task_id: str, row) -> dict[str, Any]:
|
||||
target = row.target
|
||||
value_policy, proposed = _policy(task, row)
|
||||
if value_policy == "preserve":
|
||||
proposed = target.old_value
|
||||
sync_nc = bool(getattr(row, "sync_nc", True))
|
||||
target_cell = getattr(row, "target_cell", "")
|
||||
return {
|
||||
"task_id": task_id,
|
||||
"project": str(target.project_path),
|
||||
"coverage": "exact",
|
||||
"enabled": bool(row.enabled),
|
||||
"component_count": int(bool(row.enabled)),
|
||||
"schematic_name": target.schematic_name,
|
||||
"sheet": target.sheet_number,
|
||||
"sheet_number": target.sheet_number,
|
||||
"refdes": target.refdes,
|
||||
"uid": target.uid,
|
||||
"old_part_number": target.old_part_number,
|
||||
"new_part_number": row.new_part_number,
|
||||
"old_value": target.old_value,
|
||||
"proposed_value": proposed,
|
||||
"value_policy": value_policy,
|
||||
"target_cell": target_cell,
|
||||
"target_cell_policy": target_cell,
|
||||
"sync_nc": sync_nc,
|
||||
"nc_policy": "sync" if sync_nc else "preserve",
|
||||
"mapping_scope": None,
|
||||
}
|
||||
|
||||
|
||||
def _mapping_row(task, context, task_id: str, rule) -> dict[str, Any]:
|
||||
value_policy, proposed = _policy(task, rule)
|
||||
project = getattr(context, "project", None)
|
||||
project_path = str(project.path) if project is not None else ""
|
||||
sync_nc = bool(getattr(rule, "sync_nc", True))
|
||||
return {
|
||||
"task_id": task_id,
|
||||
"project": project_path,
|
||||
"coverage": "mapping_only",
|
||||
"enabled": bool(getattr(rule, "enabled", True)),
|
||||
"component_count": None,
|
||||
"schematic_name": None,
|
||||
"sheet": None,
|
||||
"sheet_number": None,
|
||||
"refdes": None,
|
||||
"uid": None,
|
||||
"old_part_number": rule.old_part_number,
|
||||
"new_part_number": rule.new_part_number,
|
||||
"old_value": None,
|
||||
"proposed_value": proposed,
|
||||
"value_policy": value_policy,
|
||||
"target_cell": getattr(rule, "target_cell", ""),
|
||||
"target_cell_policy": getattr(rule, "target_cell", ""),
|
||||
"sync_nc": sync_nc,
|
||||
"nc_policy": "sync" if sync_nc else "preserve",
|
||||
"mapping_scope": {"old_part_number": rule.old_part_number,
|
||||
"new_part_number": rule.new_part_number},
|
||||
}
|
||||
|
||||
|
||||
def execution_impact(service, task_ids, *, limit: int = 100) -> dict[str, Any]:
|
||||
"""Return a bounded, deterministic report of the saved execution scope.
|
||||
|
||||
Mapping tasks retain ``component_count=None`` because no CAD inventory is
|
||||
consulted. Exact target plans count enabled saved rows and include their
|
||||
stable identities and policies.
|
||||
"""
|
||||
ids = _scope(task_ids)
|
||||
bound = _limit(limit)
|
||||
from ..trial_task_center.task_queue import _plan_hash
|
||||
all_rows: list[dict[str, Any]] = []
|
||||
task_reports: list[dict[str, Any]] = []
|
||||
plan_hashes: dict[str, str] = {}
|
||||
coverage_values: list[str] = []
|
||||
known_component_count = 0
|
||||
enabled_scope = 0
|
||||
|
||||
for task_id in ids:
|
||||
context = service.task_context(task_id)
|
||||
task = context.task
|
||||
exact = bool(getattr(task, "target_plan_mode", False))
|
||||
task_rows: list[dict[str, Any]] = []
|
||||
if exact:
|
||||
# service.target_plan() is the authoritative saved-row API and
|
||||
# retains target_cell on versions whose context projection is old.
|
||||
saved_rows = tuple(service.target_plan(task_id))
|
||||
task_rows = [_target_row(task, task_id, row) for row in saved_rows]
|
||||
task_coverage = "exact"
|
||||
task_count = sum(row["component_count"] for row in task_rows)
|
||||
known_component_count += task_count
|
||||
enabled_scope += task_count
|
||||
else:
|
||||
task_rows = [_mapping_row(task, context, task_id, rule)
|
||||
for rule in tuple(getattr(context, "rules", ()))]
|
||||
task_coverage = "mapping_only"
|
||||
enabled_scope += sum(1 for row in task_rows if row["enabled"])
|
||||
coverage_values.append(task_coverage)
|
||||
plan_hashes[task_id] = _plan_hash(service.for_project_task(task_id), task_id)
|
||||
project = getattr(context, "project", None)
|
||||
task_reports.append({
|
||||
"task_id": task_id,
|
||||
"name": getattr(task, "name", ""),
|
||||
"project": str(project.path) if project is not None else "",
|
||||
"coverage": task_coverage,
|
||||
"component_count": task_count if exact else None,
|
||||
"enabled_scope": sum(row["component_count"] for row in task_rows) if exact else sum(1 for row in task_rows if row["enabled"]),
|
||||
"total_rows": len(task_rows),
|
||||
"returned_rows": 0,
|
||||
"omitted_row_count": 0,
|
||||
})
|
||||
all_rows.extend(task_rows)
|
||||
|
||||
full_payload = {"task_ids": list(ids), "rows": all_rows, "plan_hashes": plan_hashes}
|
||||
full_fingerprint = _hash(full_payload)
|
||||
visible_rows = all_rows[:bound]
|
||||
remaining = bound
|
||||
for report in task_reports:
|
||||
count = min(report["total_rows"], remaining)
|
||||
report["returned_rows"] = count
|
||||
report["omitted_row_count"] = report["total_rows"] - count
|
||||
remaining -= count
|
||||
omitted = len(all_rows) - len(visible_rows)
|
||||
coverage = coverage_values[0] if len(set(coverage_values)) == 1 else "mixed"
|
||||
return {
|
||||
"task_ids": list(ids),
|
||||
"coverage": coverage,
|
||||
"component_count": known_component_count if coverage == "exact" else None,
|
||||
"known_component_count": known_component_count,
|
||||
"enabled_scope": enabled_scope,
|
||||
"tasks": task_reports,
|
||||
"rows": visible_rows,
|
||||
"total_rows": len(all_rows),
|
||||
"returned_rows": len(visible_rows),
|
||||
"omitted_row_count": omitted,
|
||||
"truncated": bool(omitted),
|
||||
"limit": bound,
|
||||
"plan_hashes": plan_hashes,
|
||||
"fingerprint": full_fingerprint,
|
||||
"full_fingerprint": full_fingerprint,
|
||||
"cad_connection_checked": False,
|
||||
"read_only": True,
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Bounded live execution state shared by the task center and DSH dock."""
|
||||
|
||||
|
||||
def read_live_run(service, feedback, *, elapsed, pause_requested, run_id, task_ids):
|
||||
task_id = feedback.task_id or (task_ids[0] if task_ids else None)
|
||||
context = service.task_context(task_id) if task_id else None
|
||||
progress = context.progress if context else None
|
||||
return {'active': True, 'run_id': run_id, 'task_id': task_id,
|
||||
'task_ids': list(task_ids), 'name': context.task.name if context else '',
|
||||
'stage': feedback.stage, 'stage_seconds': feedback.stage_seconds,
|
||||
'elapsed_seconds': int(elapsed), 'pause_requested': bool(pause_requested),
|
||||
'saved_items': getattr(progress, 'saved_items', 0),
|
||||
'failed_items': getattr(progress, 'failed_items', 0),
|
||||
'no_match_items': getattr(progress, 'no_match_items', 0),
|
||||
'completed_items': getattr(progress, 'completed_items', 0),
|
||||
'total_items': getattr(progress, 'total_items', 0), 'component_count_known': False}
|
||||
@@ -42,11 +42,11 @@ def launch_environment(data_root: Path) -> dict[str, str]:
|
||||
return env
|
||||
|
||||
|
||||
def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', automation=None, creation=None, lifecycle=None) -> dict:
|
||||
def write_context(data_root: Path, snapshot: TaskSnapshot, *, events=(), action_result='', task_name='', automation=None, creation=None, lifecycle=None, operations=None) -> dict:
|
||||
data_root.mkdir(parents=True, exist_ok=True)
|
||||
value = snapshot.safe_dict() | {'revision': uuid4().hex,
|
||||
'events': [str(e)[:300] for e in events][-20:], 'action_result': str(action_result)[:300],
|
||||
'task_name': str(task_name)[:128], 'automation': automation or {}, 'creation': creation or {}, 'lifecycle': lifecycle or {}}
|
||||
'task_name': str(task_name)[:128], 'automation': automation or {}, 'creation': creation or {}, 'lifecycle': lifecycle or {}, 'operations': operations or {}}
|
||||
temporary = data_root / ('context-' + uuid4().hex + '.tmp')
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False), encoding='utf8')
|
||||
destination = data_root / 'task-context.json'
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Durable, Qt-free execution run receipts and read-only recovery inspection."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, is_dataclass
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sqlite3
|
||||
from typing import Any
|
||||
|
||||
from ..trial_task_center.errors import TaskCenterError
|
||||
|
||||
_ID = re.compile(r"^[0-9a-f]{32}$")
|
||||
_TASK_ID = re.compile(r"(?:[0-9a-f]{32}|[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})")
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _json(value: Any) -> Any:
|
||||
if is_dataclass(value):
|
||||
return _json(asdict(value))
|
||||
if isinstance(value, Path):
|
||||
return str(value)
|
||||
if isinstance(value, (tuple, list)):
|
||||
return [_json(item) for item in value]
|
||||
if isinstance(value, dict):
|
||||
return {str(key): _json(item) for key, item in value.items()}
|
||||
return value
|
||||
|
||||
|
||||
def _check_scope(run_id: str, task_ids: Any, plan_hashes: Any) -> tuple[list[str], dict[str, str]]:
|
||||
if not isinstance(run_id, str) or not _ID.fullmatch(run_id):
|
||||
raise TaskCenterError("run_id", "run identifier is invalid")
|
||||
if not isinstance(task_ids, (list, tuple)) or not 1 <= len(task_ids) <= 20:
|
||||
raise TaskCenterError("run_scope", "run must contain 1 to 20 tasks")
|
||||
ids = list(task_ids)
|
||||
if any(not isinstance(item, str) or not _TASK_ID.fullmatch(item) for item in ids) or len(set(ids)) != len(ids):
|
||||
raise TaskCenterError("run_scope", "task identifiers are invalid")
|
||||
if not isinstance(plan_hashes, dict) or set(plan_hashes) != set(ids) or any(
|
||||
not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value) for value in plan_hashes.values()
|
||||
):
|
||||
raise TaskCenterError("run_plan", "frozen plan hashes are invalid")
|
||||
return ids, dict(plan_hashes)
|
||||
|
||||
|
||||
class RunJournal:
|
||||
def __init__(self, data_root):
|
||||
self.data_root = Path(data_root)
|
||||
self.data_root.mkdir(parents=True, exist_ok=True)
|
||||
self.path = self.data_root / "dsh-state.sqlite3"
|
||||
with self._connect() as db:
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS run_journal (
|
||||
run_id TEXT PRIMARY KEY, queue_id TEXT NOT NULL UNIQUE, task_ids TEXT NOT NULL,
|
||||
plan_hashes TEXT NOT NULL, schedule_id TEXT, status TEXT NOT NULL,
|
||||
started_utc TEXT NOT NULL, finished_utc TEXT, result TEXT)""")
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS run_journal_receipts (
|
||||
receipt_id INTEGER PRIMARY KEY AUTOINCREMENT, run_id TEXT NOT NULL,
|
||||
finished_utc TEXT NOT NULL, status TEXT NOT NULL, result TEXT NOT NULL)""")
|
||||
|
||||
@contextmanager
|
||||
def _connect(self):
|
||||
db = sqlite3.connect(self.path, timeout=10, isolation_level=None)
|
||||
db.row_factory = sqlite3.Row
|
||||
db.execute("PRAGMA busy_timeout=10000")
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@staticmethod
|
||||
def _row(row):
|
||||
if row is None:
|
||||
return None
|
||||
return {"run_id": row["run_id"], "queue_id": row["queue_id"],
|
||||
"task_ids": json.loads(row["task_ids"]), "plan_hashes": json.loads(row["plan_hashes"]),
|
||||
"schedule_id": row["schedule_id"], "status": row["status"],
|
||||
"started_utc": row["started_utc"], "finished_utc": row["finished_utc"],
|
||||
"result": json.loads(row["result"]) if row["result"] else None}
|
||||
|
||||
def begin(self, run_id, task_ids, plan_hashes, *, schedule_id=None):
|
||||
ids, hashes = _check_scope(run_id, task_ids, plan_hashes)
|
||||
if schedule_id is not None and (not isinstance(schedule_id, str) or not _ID.fullmatch(schedule_id)):
|
||||
raise TaskCenterError("schedule_id", "schedule identifier is invalid")
|
||||
with self._connect() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
existing = db.execute("SELECT * FROM run_journal WHERE run_id = ?", (run_id,)).fetchone()
|
||||
if existing:
|
||||
current = self._row(existing)
|
||||
if current["task_ids"] != ids or current["plan_hashes"] != hashes or current["schedule_id"] != schedule_id:
|
||||
raise TaskCenterError("run_conflict", "run is already bound to another frozen scope")
|
||||
db.execute("COMMIT")
|
||||
return current
|
||||
started = _now()
|
||||
db.execute("INSERT INTO run_journal VALUES (?, ?, ?, ?, ?, ?, ?, NULL, NULL)",
|
||||
(run_id, run_id, json.dumps(ids), json.dumps(hashes, sort_keys=True), schedule_id, "running", started))
|
||||
db.execute("COMMIT")
|
||||
return self.get(run_id)
|
||||
|
||||
def finish(self, run_id, result):
|
||||
if not isinstance(run_id, str) or not _ID.fullmatch(run_id):
|
||||
raise TaskCenterError("run_id", "run identifier is invalid")
|
||||
value = _json(result)
|
||||
status = value.get("status") if isinstance(value, dict) else getattr(result, "status", None)
|
||||
if status not in {"completed", "failed", "paused", "blocked", "interrupted"}:
|
||||
status = "completed" if isinstance(value, dict) and value.get("paused") is False else "paused"
|
||||
entries = value.get("entries", []) if isinstance(value, dict) else []
|
||||
if any(entry.get("state") == "blocked" for entry in entries):
|
||||
status = "blocked"
|
||||
elif any(entry.get("state") == "failed" for entry in entries) and status == "completed":
|
||||
status = "failed"
|
||||
with self._connect() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
if db.execute("SELECT 1 FROM run_journal WHERE run_id = ?", (run_id,)).fetchone() is None:
|
||||
raise TaskCenterError("run_missing", "run does not exist")
|
||||
stamp = _now()
|
||||
payload = json.dumps(value, ensure_ascii=False)
|
||||
db.execute("INSERT INTO run_journal_receipts (run_id, finished_utc, status, result) VALUES (?, ?, ?, ?)",
|
||||
(run_id, stamp, status, payload))
|
||||
db.execute("UPDATE run_journal SET status = ?, finished_utc = ?, result = ? WHERE run_id = ?",
|
||||
(status, stamp, payload, run_id))
|
||||
db.execute("COMMIT")
|
||||
return self.get(run_id)
|
||||
|
||||
def resume(self, run_id):
|
||||
"""Mark a natively reconfirmed continuation; keep its last durable receipt."""
|
||||
with self._connect() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
row = db.execute("SELECT status FROM run_journal WHERE run_id = ?", (run_id,)).fetchone()
|
||||
if row is None:
|
||||
raise TaskCenterError("run_missing", "run does not exist")
|
||||
if row["status"] not in {"running", "paused", "blocked", "interrupted"}:
|
||||
raise TaskCenterError("run_terminal", "this run has no resumable execution")
|
||||
db.execute("UPDATE run_journal SET status = 'running', finished_utc = NULL WHERE run_id = ?", (run_id,))
|
||||
db.execute("COMMIT")
|
||||
return self.get(run_id)
|
||||
|
||||
def get(self, run_id):
|
||||
with self._connect() as db:
|
||||
return self._row(db.execute("SELECT * FROM run_journal WHERE run_id = ?", (run_id,)).fetchone())
|
||||
|
||||
def list_runs(self, limit=20):
|
||||
if not isinstance(limit, int) or not 1 <= limit <= 1000:
|
||||
raise TaskCenterError("run_limit", "run limit is invalid")
|
||||
with self._connect() as db:
|
||||
rows = db.execute("SELECT * FROM run_journal ORDER BY started_utc DESC LIMIT ?", (limit,)).fetchall()
|
||||
return [self._row(row) for row in rows]
|
||||
|
||||
def inspect(self, service, run_id):
|
||||
row = self.get(run_id)
|
||||
if row is None:
|
||||
raise TaskCenterError("run_missing", "run does not exist")
|
||||
blockers: list[str] = []
|
||||
checkpoint = self.data_root / "task-queues" / f"{run_id}.json"
|
||||
queue = None
|
||||
try:
|
||||
queue = json.loads(checkpoint.read_text(encoding="utf-8"))
|
||||
if queue.get("version") != 1 or queue.get("task_ids") != row["task_ids"] or queue.get("plan_hashes") != row["plan_hashes"]:
|
||||
raise ValueError
|
||||
entries = queue["entries"]
|
||||
if set(entries) != set(row["task_ids"]) or any(
|
||||
not isinstance(entry, dict) or set(entry) != {"state", "message"} or
|
||||
entry["state"] not in {"pending", "running", "paused", "blocked", "completed", "failed", "skipped"} or
|
||||
not isinstance(entry["message"], str) for entry in entries.values()
|
||||
):
|
||||
raise ValueError
|
||||
except (OSError, ValueError, TypeError, KeyError, json.JSONDecodeError):
|
||||
queue = None
|
||||
blockers.append("queue_missing" if not checkpoint.exists() else "queue_invalid")
|
||||
counters = {"completed": 0, "total": 0, "saved_items": 0, "failed_items": 0, "no_match_items": 0}
|
||||
tasks = []
|
||||
has_evidence = False
|
||||
for task_id in row["task_ids"]:
|
||||
item = {"task_id": task_id, "status": "unknown", "saved_items": 0, "failed_items": 0, "no_match_items": 0}
|
||||
try:
|
||||
context = service.task_context(task_id)
|
||||
has_evidence = has_evidence or context.has_evidence
|
||||
progress = context.progress
|
||||
item.update({"status": context.task.status.value, "interrupted": bool(context.interrupted),
|
||||
"saved_items": int(getattr(progress, "saved_items", 0)),
|
||||
"failed_items": int(getattr(progress, "failed_items", 0)),
|
||||
"no_match_items": int(getattr(progress, "no_match_items", 0)),
|
||||
"total_items": int(getattr(progress, "total_items", 0))})
|
||||
for key in ("saved_items", "failed_items", "no_match_items"):
|
||||
counters[key] += item[key]
|
||||
counters["total"] += item["total_items"]
|
||||
if context.interrupted:
|
||||
blockers.append("interrupted")
|
||||
if getattr(progress, "failed_items", 0):
|
||||
blockers.append("failed_items")
|
||||
from ..trial_task_center.task_queue import _plan_hash
|
||||
if _plan_hash(service.for_project_task(task_id), task_id) != row["plan_hashes"][task_id]:
|
||||
blockers.append("plan_changed")
|
||||
except Exception:
|
||||
blockers.append("task_unavailable")
|
||||
tasks.append(item)
|
||||
if queue:
|
||||
counters["completed"] = sum(queue["entries"][task_id]["state"] in {"completed", "failed", "skipped"} for task_id in row["task_ids"])
|
||||
remaining = [task_id for task_id in row["task_ids"] if not queue or queue["entries"][task_id]["state"] not in {"completed", "failed", "skipped"}]
|
||||
if "queue_missing" in blockers and not has_evidence:
|
||||
# The receipt may have committed before the executor created its checkpoint.
|
||||
# A native reconfirmation can safely create the original queue; no auto replay.
|
||||
blockers.remove("queue_missing")
|
||||
if remaining:
|
||||
try:
|
||||
from .task_lifecycle import preflight
|
||||
if not preflight(service, remaining)["ready"]:
|
||||
blockers.append("preflight_blocked")
|
||||
except Exception:
|
||||
blockers.append("preflight_unavailable")
|
||||
elif service.pending_batch_resources():
|
||||
blockers.append("resources_pending")
|
||||
blockers = list(dict.fromkeys(blockers))
|
||||
return {**row, "queue_available": queue is not None, "tasks": tasks, "counters": counters,
|
||||
"remaining_task_ids": remaining, "blockers": blockers, "resume_ready": not blockers,
|
||||
"requires_confirmation": True,
|
||||
"cad_execution_started": False, "original_scope": {"task_ids": row["task_ids"], "plan_hashes": row["plan_hashes"]}}
|
||||
@@ -0,0 +1,241 @@
|
||||
"""Durable scheduling decisions. This module never starts a worker or CAD operation."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sqlite3
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from ..trial_task_center.errors import TaskCenterError
|
||||
|
||||
_ID = re.compile(r"^[0-9a-f]{32}$")
|
||||
_TASK_ID = re.compile(r"(?:[0-9a-f]{32}|[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})")
|
||||
_PRIORITY = {"low": 0, "normal": 1, "high": 2, "urgent": 3}
|
||||
_FIELDS = {"task_ids", "priority", "not_before", "due_at", "dependencies", "auto_start", "idle_only", "title"}
|
||||
|
||||
|
||||
def _utc(value, *, required=False):
|
||||
if value is None and not required:
|
||||
return None
|
||||
if not isinstance(value, str):
|
||||
raise TaskCenterError("schedule_datetime", "datetime must be an ISO 8601 string with timezone")
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
except ValueError as error:
|
||||
raise TaskCenterError("schedule_datetime", "datetime must be an ISO 8601 string with timezone") from error
|
||||
if parsed.tzinfo is None:
|
||||
raise TaskCenterError("schedule_datetime", "datetime timezone is required")
|
||||
return parsed.astimezone(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _ids(values, *, required=True):
|
||||
if not isinstance(values, (list, tuple)) or (required and not 1 <= len(values) <= 20):
|
||||
raise TaskCenterError("schedule_scope", "schedule must contain 1 to 20 task identifiers")
|
||||
values = list(values)
|
||||
if len(values) > 20 or any(not isinstance(value, str) or not _TASK_ID.fullmatch(value) for value in values) or len(set(values)) != len(values):
|
||||
raise TaskCenterError("schedule_scope", "task identifiers are invalid")
|
||||
return values
|
||||
|
||||
|
||||
class ScheduleStore:
|
||||
def __init__(self, data_root):
|
||||
self.data_root = Path(data_root)
|
||||
self.data_root.mkdir(parents=True, exist_ok=True)
|
||||
self.path = self.data_root / "dsh-state.sqlite3"
|
||||
with self._connect() as db:
|
||||
db.execute("""CREATE TABLE IF NOT EXISTS schedules (
|
||||
schedule_id TEXT PRIMARY KEY, task_ids TEXT NOT NULL, plan_hashes TEXT NOT NULL,
|
||||
priority TEXT NOT NULL, not_before TEXT NOT NULL, due_at TEXT, dependencies TEXT NOT NULL,
|
||||
auto_start INTEGER NOT NULL, idle_only INTEGER NOT NULL, title TEXT NOT NULL,
|
||||
status TEXT NOT NULL, created_utc TEXT NOT NULL, updated_utc TEXT NOT NULL,
|
||||
claimed_utc TEXT, finished_utc TEXT, run_id TEXT, result TEXT)""")
|
||||
|
||||
@contextmanager
|
||||
def _connect(self):
|
||||
db = sqlite3.connect(self.path, timeout=10, isolation_level=None)
|
||||
db.row_factory = sqlite3.Row
|
||||
db.execute("PRAGMA busy_timeout=10000")
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@staticmethod
|
||||
def _row(row):
|
||||
if row is None:
|
||||
return None
|
||||
return {"schedule_id": row["schedule_id"], "task_ids": json.loads(row["task_ids"]),
|
||||
"plan_hashes": json.loads(row["plan_hashes"]), "priority": row["priority"],
|
||||
"not_before": row["not_before"], "due_at": row["due_at"],
|
||||
"dependencies": json.loads(row["dependencies"]), "auto_start": bool(row["auto_start"]),
|
||||
"idle_only": bool(row["idle_only"]), "title": row["title"], "status": row["status"],
|
||||
"created_utc": row["created_utc"], "updated_utc": row["updated_utc"],
|
||||
"claimed_utc": row["claimed_utc"], "finished_utc": row["finished_utc"],
|
||||
"run_id": row["run_id"], "result": json.loads(row["result"]) if row["result"] else None}
|
||||
|
||||
def get(self, schedule_id):
|
||||
with self._connect() as db:
|
||||
return self._row(db.execute("SELECT * FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone())
|
||||
|
||||
def list_schedules(self):
|
||||
with self._connect() as db:
|
||||
return [self._row(row) for row in db.execute("SELECT * FROM schedules ORDER BY not_before, created_utc").fetchall()]
|
||||
|
||||
def _validate_spec(self, spec, plan_hashes):
|
||||
if not isinstance(spec, dict) or set(spec) - _FIELDS:
|
||||
raise TaskCenterError("schedule_fields", "schedule contains unsupported fields")
|
||||
ids = _ids(spec.get("task_ids"))
|
||||
if not isinstance(spec.get("priority", "normal"), str) or spec.get("priority", "normal") not in _PRIORITY:
|
||||
raise TaskCenterError("schedule_priority", "schedule priority is invalid")
|
||||
before = _utc(spec.get("not_before"), required=True)
|
||||
due = _utc(spec.get("due_at"))
|
||||
if due and due < before:
|
||||
raise TaskCenterError("schedule_datetime", "due time cannot precede not-before time")
|
||||
dependencies = _ids(spec.get("dependencies", []), required=False)
|
||||
if set(ids) & set(dependencies):
|
||||
raise TaskCenterError("schedule_dependency", "schedule cannot depend on itself")
|
||||
if not isinstance(spec.get("auto_start", False), bool) or not isinstance(spec.get("idle_only", True), bool):
|
||||
raise TaskCenterError("schedule_fields", "schedule switches must be booleans")
|
||||
title = spec.get("title", "")
|
||||
if not isinstance(title, str) or len(title) > 200 or "\x00" in title:
|
||||
raise TaskCenterError("schedule_title", "schedule title is invalid")
|
||||
if not isinstance(plan_hashes, dict) or set(plan_hashes) != set(ids) or any(
|
||||
not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value) for value in plan_hashes.values()
|
||||
):
|
||||
raise TaskCenterError("schedule_plan", "frozen plan hashes are invalid")
|
||||
return ids, dict(plan_hashes), spec.get("priority", "normal"), before, due, dependencies, bool(spec.get("auto_start", False)), bool(spec.get("idle_only", True)), title
|
||||
|
||||
def _check_cycles(self, db, ids, dependencies):
|
||||
graph = {}
|
||||
for stored in db.execute("SELECT * FROM schedules WHERE status IN ('pending', 'claimed')").fetchall():
|
||||
row = self._row(stored)
|
||||
for task_id in row["task_ids"]:
|
||||
graph.setdefault(task_id, set()).update(row["dependencies"])
|
||||
for task_id in ids:
|
||||
graph.setdefault(task_id, set()).update(dependencies)
|
||||
def visit(node, active, seen):
|
||||
if node in active:
|
||||
return True
|
||||
if node in seen:
|
||||
return False
|
||||
seen.add(node); active.add(node)
|
||||
if any(visit(dep, active, seen) for dep in graph.get(node, ())):
|
||||
return True
|
||||
active.remove(node)
|
||||
return False
|
||||
if any(visit(node, set(), set()) for node in graph):
|
||||
raise TaskCenterError("schedule_dependency_cycle", "schedule dependencies contain a cycle")
|
||||
|
||||
def preview(self, spec, plan_hashes):
|
||||
"""Normalize a native confirmation draft without saving or granting authority."""
|
||||
ids, _, priority, before, due, deps, auto_start, idle_only, title = self._validate_spec(spec, plan_hashes)
|
||||
with self._connect() as db:
|
||||
self._check_cycles(db, ids, deps)
|
||||
return {"task_ids": ids, "priority": priority, "not_before": before, "due_at": due,
|
||||
"dependencies": deps, "auto_start": auto_start, "idle_only": idle_only, "title": title}
|
||||
|
||||
def save(self, spec, plan_hashes):
|
||||
ids, hashes, priority, before, due, deps, auto_start, idle_only, title = self._validate_spec(spec, plan_hashes)
|
||||
schedule_id = uuid4().hex
|
||||
stamp = _now().isoformat(timespec="seconds")
|
||||
with self._connect() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
self._check_cycles(db, ids, deps)
|
||||
db.execute("INSERT INTO schedules VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, NULL)",
|
||||
(schedule_id, json.dumps(ids), json.dumps(hashes, sort_keys=True), priority, before, due,
|
||||
json.dumps(deps), int(auto_start), int(idle_only), title, "pending", stamp, stamp))
|
||||
db.execute("COMMIT")
|
||||
return self.get(schedule_id)
|
||||
|
||||
def cancel(self, schedule_id):
|
||||
with self._connect() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
row = db.execute("SELECT status FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
|
||||
if row is None:
|
||||
db.execute("ROLLBACK"); raise TaskCenterError("schedule_missing", "schedule does not exist")
|
||||
if row["status"] != "pending":
|
||||
db.execute("ROLLBACK"); raise TaskCenterError("schedule_owned", "claimed or finished schedules cannot be cancelled")
|
||||
db.execute("UPDATE schedules SET status = 'cancelled', updated_utc = ? WHERE schedule_id = ?", (_now().isoformat(timespec="seconds"), schedule_id))
|
||||
db.execute("COMMIT")
|
||||
return self.get(schedule_id)
|
||||
|
||||
def claim(self, schedule_id):
|
||||
with self._connect() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
row = db.execute("SELECT status FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
|
||||
if row is None:
|
||||
db.execute("ROLLBACK"); raise TaskCenterError("schedule_missing", "schedule does not exist")
|
||||
if row["status"] != "pending":
|
||||
db.execute("ROLLBACK"); raise TaskCenterError("schedule_claimed", "schedule is already claimed or finished")
|
||||
stamp = _now().isoformat(timespec="seconds")
|
||||
db.execute("UPDATE schedules SET status = 'claimed', claimed_utc = ?, updated_utc = ? WHERE schedule_id = ?", (stamp, stamp, schedule_id))
|
||||
db.execute("COMMIT")
|
||||
return self.get(schedule_id)
|
||||
|
||||
def finish(self, schedule_id, status, **values):
|
||||
if status not in {"completed", "failed", "interrupted", "cancelled"}:
|
||||
raise TaskCenterError("schedule_status", "schedule finish status is invalid")
|
||||
with self._connect() as db:
|
||||
db.execute("BEGIN IMMEDIATE")
|
||||
row = db.execute("SELECT status FROM schedules WHERE schedule_id = ?", (schedule_id,)).fetchone()
|
||||
if row is None:
|
||||
db.execute("ROLLBACK"); raise TaskCenterError("schedule_missing", "schedule does not exist")
|
||||
if row["status"] != "claimed":
|
||||
db.execute("ROLLBACK"); raise TaskCenterError("schedule_status", "only a claimed schedule can finish")
|
||||
stamp = _now().isoformat(timespec="seconds")
|
||||
db.execute("UPDATE schedules SET status = ?, updated_utc = ?, finished_utc = ?, run_id = ?, result = ? WHERE schedule_id = ?",
|
||||
(status, stamp, stamp, values.get("run_id"), json.dumps(values, ensure_ascii=False), schedule_id))
|
||||
db.execute("COMMIT")
|
||||
return self.get(schedule_id)
|
||||
|
||||
def _completed(self, service, task_id):
|
||||
try:
|
||||
context = service.task_context(task_id)
|
||||
progress = context.progress
|
||||
return context.task.status.value == "completed" and not context.interrupted and bool(progress.queue_complete) and not getattr(progress, "failed_items", 0)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def evaluate(self, service, *, now=None, busy=False):
|
||||
when = now or _now()
|
||||
if when.tzinfo is None:
|
||||
raise TaskCenterError("schedule_datetime", "evaluation time timezone is required")
|
||||
rows = []
|
||||
from ..trial_task_center.task_queue import _plan_hash
|
||||
for row in self.list_schedules():
|
||||
blockers = []
|
||||
if row["status"] == "claimed": blockers.append("already_claimed")
|
||||
elif row["status"] != "pending": blockers.append("finished")
|
||||
if datetime.fromisoformat(row["not_before"]) > when.astimezone(timezone.utc): blockers.append("not_due")
|
||||
if busy: blockers.append("worker_busy")
|
||||
try:
|
||||
for task_id in row["task_ids"]:
|
||||
if service.task_context(task_id).task.status.value == "paused":
|
||||
blockers.append("task_paused")
|
||||
if _plan_hash(service.for_project_task(task_id), task_id) != row["plan_hashes"][task_id]:
|
||||
blockers.append("plan_changed")
|
||||
except Exception:
|
||||
blockers.append("task_unavailable")
|
||||
try:
|
||||
from .task_lifecycle import preflight
|
||||
check = preflight(service, row["task_ids"])
|
||||
if not check["ready"]:
|
||||
blockers.append("preflight_blocked")
|
||||
except Exception:
|
||||
blockers.append("preflight_unavailable")
|
||||
if row["dependencies"] and not all(self._completed(service, task_id) for task_id in row["dependencies"]): blockers.append("dependency_incomplete")
|
||||
blockers = list(dict.fromkeys(blockers))
|
||||
rows.append({**row, "blockers": blockers, "ready": not blockers,
|
||||
"requires_confirmation": True, "dispatchable": False,
|
||||
"scope": {"task_ids": row["task_ids"], "plan_hashes": row["plan_hashes"]}})
|
||||
rows.sort(key=lambda item: (-_PRIORITY[item["priority"]], item["not_before"], item["created_utc"]))
|
||||
return rows
|
||||
@@ -40,7 +40,7 @@ def fingerprint(service, ids):
|
||||
return _digest([asdict(_context(service, key)) for key in ids])
|
||||
|
||||
|
||||
def preflight(service, task_ids):
|
||||
def preflight(service, task_ids, *, allow_completed=False):
|
||||
from ..trial_task_center.ui.execution_state import execution_state
|
||||
from ..trial_task_center.task_queue import _plan_hash
|
||||
if not isinstance(task_ids, list) or not 1 <= len(task_ids) <= 20 or len(set(task_ids)) != len(task_ids):
|
||||
@@ -51,7 +51,9 @@ def preflight(service, task_ids):
|
||||
context = _context(service, task_id)
|
||||
state = execution_state(context)
|
||||
blockers = []
|
||||
if not state.execute:
|
||||
finished = (allow_completed and context.task.status is TaskStatus.COMPLETED
|
||||
and context.progress.queue_complete and not context.progress.failed_items and not context.interrupted)
|
||||
if not state.execute and not finished:
|
||||
blockers.append(state.message)
|
||||
if context.phase == 'retry':
|
||||
blockers.append('存在失败项,请先核对证据并准备失败项重试。')
|
||||
@@ -76,7 +78,9 @@ def preflight(service, task_ids):
|
||||
'phase': context.phase, 'blockers': list(dict.fromkeys(blockers)),
|
||||
'saved_items': context.progress.saved_items, 'failed_items': context.progress.failed_items,
|
||||
'no_match_items': context.progress.no_match_items})
|
||||
return {'ready': all(not t['blockers'] for t in tasks), 'tasks': tasks,
|
||||
from .impact import execution_impact
|
||||
impact = execution_impact(service, task_ids)
|
||||
return {'ready': all(not t['blockers'] for t in tasks), 'tasks': tasks, 'impact': impact,
|
||||
'plan_hashes': hashes, 'fingerprint': fingerprint(service, task_ids),
|
||||
'cad_connection_checked': False,
|
||||
'message': '已核对保存的配置和执行证据;CAD 连接、备份与保存核验由正式执行流程完成。'}
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Read-only tracking of the fixed issue associated with an existing incident."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from .evidence import scrub, write_json
|
||||
from .git_issues import GitIssuePublisher, NoRedirect
|
||||
from .issue_credentials import issue_target
|
||||
|
||||
|
||||
_IDENTIFIER = re.compile(r"^[0-9a-f]{24}$")
|
||||
_MAX_COMMENTS = 20
|
||||
_MAX_BYTES = 2 * 1024 * 1024
|
||||
|
||||
|
||||
class TicketTracker:
|
||||
def __init__(self, data_root):
|
||||
self.data_root = Path(data_root)
|
||||
self.incidents = self.data_root / "dsh" / "incidents"
|
||||
self.cache_root = self.data_root / "dsh" / "ticket-cache"
|
||||
self.config_path = self.data_root / "dsh" / "issue-config.json"
|
||||
|
||||
def refresh(self, incident_id: str) -> dict:
|
||||
if not isinstance(incident_id, str) or not _IDENTIFIER.fullmatch(incident_id):
|
||||
raise ValueError("invalid_incident_id")
|
||||
incident_path = self.incidents / incident_id / "incident.json"
|
||||
local = self._read_json(incident_path)
|
||||
if not isinstance(local, dict) or local.get("incident_id") != incident_id:
|
||||
return self._unavailable(incident_id, "incident_unavailable")
|
||||
ticket = local.get("ticket")
|
||||
if not isinstance(ticket, dict):
|
||||
return self._unavailable(incident_id, "ticket_unavailable")
|
||||
try:
|
||||
target = issue_target(self.config_path)
|
||||
except (OSError, ValueError, TypeError):
|
||||
return self._unavailable(incident_id, "invalid_issue_config")
|
||||
expected = self._target_url(target, ticket)
|
||||
if expected is None:
|
||||
return self._unavailable(incident_id, "invalid_ticket_target")
|
||||
# Strict local target checks complete before credentials are obtained.
|
||||
try:
|
||||
config, auth, source = GitIssuePublisher(self.config_path).connection()
|
||||
except Exception as error:
|
||||
return self._unavailable(incident_id, type(error).__name__)
|
||||
if not auth:
|
||||
return self._unavailable(incident_id, source)
|
||||
if self._target_url(config, ticket) != expected:
|
||||
return self._unavailable(incident_id, "invalid_ticket_target")
|
||||
try:
|
||||
owner, repo = config["repository"].split("/", 1)
|
||||
parsed = urllib.parse.urlsplit(config["server"])
|
||||
api = f"{parsed.scheme}://{parsed.netloc}/api/v1/repos/{owner}/{repo}/issues/{ticket['number']}"
|
||||
opener = urllib.request.build_opener(NoRedirect())
|
||||
issue = self._get(opener, api, auth)
|
||||
if not isinstance(issue, dict) or not self._remote_matches(issue, incident_id, expected, ticket["number"]):
|
||||
return self._unavailable(incident_id, "ticket_identity_mismatch")
|
||||
count = issue.get("comments", 0)
|
||||
page = max(1, (count - 1) // _MAX_COMMENTS + 1) if type(count) is int and 0 <= count <= 10**7 else 1
|
||||
comments = self._get(opener, api + "/comments?" + urllib.parse.urlencode({"page": page, "limit": _MAX_COMMENTS}), auth)
|
||||
if not isinstance(comments, list):
|
||||
comments = []
|
||||
comments = [scrub(self._comment(row)) for row in comments[:_MAX_COMMENTS] if isinstance(row, dict)]
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
result = scrub({"incident_id": incident_id, "number": ticket["number"], "url": expected,
|
||||
"state": str(issue.get("state", "unknown"))[:32],
|
||||
"title": str(issue.get("title", ""))[:300], "updated_at": issue.get("updated_at"),
|
||||
"comments": comments, "status": "synced", "last_sync_at": now, "last_attempt_at": now,
|
||||
"credential_source": source, "locally_verified": False})
|
||||
self._save_cache(incident_id, result)
|
||||
return result
|
||||
except Exception as error:
|
||||
return self._unavailable(incident_id, type(error).__name__)
|
||||
|
||||
def list_tickets(self) -> list[dict]:
|
||||
try:
|
||||
target = issue_target(self.config_path)
|
||||
except (OSError, ValueError, TypeError):
|
||||
return []
|
||||
rows = []
|
||||
if not self.incidents.is_dir():
|
||||
return rows
|
||||
# Discover tickets from the existing incident binding, not cache filenames
|
||||
# or a caller-provided URL. Listing is entirely local and does not obtain auth.
|
||||
for directory in sorted(self.incidents.iterdir(), key=lambda value: value.name):
|
||||
identity = directory.name
|
||||
if not _IDENTIFIER.fullmatch(identity) or not directory.is_dir() or directory.is_symlink():
|
||||
continue
|
||||
incident = self._read_json(directory / "incident.json")
|
||||
if not isinstance(incident, dict) or incident.get("incident_id") != identity:
|
||||
continue
|
||||
ticket = incident.get("ticket")
|
||||
if not isinstance(ticket, dict):
|
||||
continue
|
||||
expected = self._target_url(target, ticket)
|
||||
if expected is None:
|
||||
continue
|
||||
binding = {"incident_id": identity, "number": ticket["number"], "url": expected,
|
||||
"status": "not_synced", "last_sync_at": None, "locally_verified": False}
|
||||
value = self._read_json(self.cache_root / f"{identity}.json")
|
||||
if (not isinstance(value, dict) or value.get("incident_id") != identity
|
||||
or value.get("number", ticket["number"]) != ticket["number"]
|
||||
or value.get("url", expected) != expected):
|
||||
value = {}
|
||||
rows.append(scrub(binding | value))
|
||||
if len(rows) >= 100:
|
||||
break
|
||||
return rows
|
||||
|
||||
def _target_url(self, config: dict, ticket: dict):
|
||||
number = ticket.get("number")
|
||||
url = ticket.get("url") or ticket.get("html_url")
|
||||
if isinstance(number, bool) or not isinstance(number, int) or number <= 0 or number > 2**31:
|
||||
return None
|
||||
if not isinstance(url, str):
|
||||
return None
|
||||
try:
|
||||
server = urllib.parse.urlsplit(str(config.get("server", "")))
|
||||
value = urllib.parse.urlsplit(url)
|
||||
owner, repo = str(config.get("repository", "")).split("/", 1)
|
||||
if (server.scheme != "https" or not server.hostname or server.username or server.password
|
||||
or server.path not in {"", "/"} or server.query or server.fragment
|
||||
or not all(re.fullmatch(r"[\w.-]+", part) and part not in {".", ".."} for part in (owner, repo))):
|
||||
return None
|
||||
expected = f"{server.scheme}://{server.netloc}/{owner}/{repo}/issues/{number}"
|
||||
if (value.scheme, value.netloc, value.path, value.query, value.fragment, value.username, value.password) != (
|
||||
server.scheme, server.netloc, f"/{owner}/{repo}/issues/{number}", "", "", None, None):
|
||||
return None
|
||||
return expected
|
||||
except (ValueError, TypeError):
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _remote_matches(issue, incident_id, expected, number):
|
||||
return (issue.get("number") == number and issue.get("html_url") == expected
|
||||
and (f"[DSH:{incident_id}]" in str(issue.get("title", ""))
|
||||
or f"[DSH:{incident_id}]" in str(issue.get("body", ""))))
|
||||
|
||||
@staticmethod
|
||||
def _comment(row):
|
||||
return {"id": row.get("id"), "body": str(row.get("body", ""))[:4000],
|
||||
"created_at": row.get("created_at"), "updated_at": row.get("updated_at"),
|
||||
"user": {"login": str((row.get("user") or {}).get("login", ""))[:128]}}
|
||||
|
||||
@staticmethod
|
||||
def _get(opener, url, auth):
|
||||
request = urllib.request.Request(url, headers=auth | {"Accept": "application/json"}, method="GET")
|
||||
with opener.open(request, timeout=25) as response:
|
||||
return json.loads(response.read(_MAX_BYTES))
|
||||
|
||||
def _unavailable(self, incident_id, error):
|
||||
cached = self._read_json(self.cache_root / f"{incident_id}.json")
|
||||
result = dict(cached) if isinstance(cached, dict) else {"incident_id": incident_id}
|
||||
result.update(status="unavailable", error=error, last_attempt_at=datetime.now(timezone.utc).isoformat())
|
||||
# Exception text can contain credentials or URLs. Keep only the typed error.
|
||||
result = scrub(result)
|
||||
self._save_cache(incident_id, result)
|
||||
return result
|
||||
|
||||
def _save_cache(self, incident_id, value):
|
||||
self.cache_root.mkdir(parents=True, exist_ok=True)
|
||||
write_json(self.cache_root / f"{incident_id}.json", value)
|
||||
|
||||
@staticmethod
|
||||
def _read_json(path):
|
||||
try:
|
||||
if not path.is_file() or path.is_symlink():
|
||||
return None
|
||||
with path.open("rb") as stream:
|
||||
raw = stream.read(_MAX_BYTES + 1)
|
||||
return json.loads(raw) if len(raw) <= _MAX_BYTES else None
|
||||
except (OSError, ValueError, TypeError):
|
||||
return None
|
||||
Reference in new issue
Block a user