feat: add frozen project context and isolated worker boundary
This commit is contained in:
1 parent
4f457b1e88
commit
855af0bd12
7 files changed
+430
No files matched your search
@@ -0,0 +1,50 @@
|
||||
# Task 1 report: single-project context and isolated worker
|
||||
|
||||
Implemented the backend portion of the single-project workflow without starting
|
||||
CAD, packaging, or modifying project files.
|
||||
|
||||
## Public API
|
||||
|
||||
`TaskCenterService.task_context(task_id: str) -> ProjectTaskContext` returns a
|
||||
cached immutable context for UI refreshes. `TaskCenterService.refresh_bound_project(task_id:
|
||||
str) -> ProjectTaskContext` rereads the task and its bound project from SQLite,
|
||||
without scanning a directory or attaching COM. A bound task must have one
|
||||
`primary_project_id` and exactly one project. Historical tasks without that
|
||||
binding remain available through `task_context` with `legacy=True` and
|
||||
`project=None`; `refresh_bound_project` rejects them so new execution cannot
|
||||
accidentally mutate a multi-project record.
|
||||
|
||||
`ProjectTaskContext` fields are:
|
||||
|
||||
```python
|
||||
ProjectTaskContext(
|
||||
task, project, rules, targets, progress, phase,
|
||||
has_evidence, interrupted, legacy
|
||||
)
|
||||
```
|
||||
|
||||
The target plan is authoritative for target-plan tasks. An empty or fully
|
||||
disabled plan produces zero queued items and never falls back to broad mapping
|
||||
rules.
|
||||
|
||||
`IsolatedDesktopWorker` is an opt-in research boundary. Its request contract is
|
||||
`IsolatedWorkerRequest(protocol_version, task_id, project_path, target_uids,
|
||||
plan_hash, allow_writes=False)`. `run()` rejects the default disabled mode,
|
||||
rejects unrelated existing CAD identity, rejects write enablement, and emits
|
||||
versioned `request.json`/`evidence.json` files when an evidence root is given.
|
||||
It does not attach COM or launch CAD.
|
||||
|
||||
`PrivateDesktop` owns the Windows desktop handle and processes started with
|
||||
`STARTUPINFO.lpDesktop`; launch fails when no private desktop was created, so
|
||||
there is no input-desktop fallback. Cleanup terminates only processes created by
|
||||
the worker and closes the owned desktop handle.
|
||||
|
||||
## Verification
|
||||
|
||||
- `tests/v1_1/test_project_context.py` and `test_isolated_desktop.py`: **6 passed**.
|
||||
- Existing target/quick-run checks (`test_service_target_integration.py`,
|
||||
`test_target_execution.py`): **8 passed**.
|
||||
- Python bytecode compilation passed for all changed backend modules.
|
||||
|
||||
The private desktop path remains research-only until a native DxDesigner build
|
||||
is validated on a disposable project; no production write claims are made.
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Opt-in Windows private-desktop process boundary used by research workers.
|
||||
|
||||
This module deliberately contains no CAD automation. It only creates a
|
||||
desktop, starts a process on that desktop, and closes resources it owns.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import ctypes
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from typing import Mapping, Sequence
|
||||
|
||||
from .errors import TaskCenterError
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StartupInfo:
|
||||
lpDesktop: str
|
||||
|
||||
|
||||
def build_startup_info(desktop_name: str) -> StartupInfo:
|
||||
if not desktop_name or "\\" in desktop_name or "\x00" in desktop_name:
|
||||
raise TaskCenterError("private_desktop", "invalid private desktop name")
|
||||
return StartupInfo(lpDesktop=desktop_name)
|
||||
|
||||
|
||||
class PrivateDesktop:
|
||||
"""Own a private Windows desktop and processes started on it."""
|
||||
|
||||
def __init__(self, name: str, *, enabled: bool = False) -> None:
|
||||
self.name = name
|
||||
self.enabled = enabled
|
||||
self._handle = None
|
||||
self._processes: list[subprocess.Popen[str]] = []
|
||||
|
||||
def __enter__(self) -> "PrivateDesktop":
|
||||
if not self.enabled:
|
||||
raise TaskCenterError("private_desktop_opt_in", "private desktop backend requires explicit opt-in")
|
||||
self._create()
|
||||
if self._handle is None:
|
||||
raise TaskCenterError("private_desktop", "private desktop could not be created")
|
||||
return self
|
||||
|
||||
def __exit__(self, *_exc: object) -> None:
|
||||
self.close()
|
||||
|
||||
def _create(self) -> None:
|
||||
if os.name != "nt":
|
||||
return
|
||||
user32 = ctypes.windll.user32
|
||||
user32.CreateDesktopW.restype = ctypes.c_void_p
|
||||
self._handle = user32.CreateDesktopW(self.name, None, None, 0, 0x000F01FF, None)
|
||||
|
||||
def start_process(
|
||||
self,
|
||||
command: Sequence[str],
|
||||
*,
|
||||
cwd: Path | None = None,
|
||||
env: Mapping[str, str] | None = None,
|
||||
) -> subprocess.Popen[str]:
|
||||
if not self.enabled or self._handle is None:
|
||||
raise TaskCenterError("private_desktop", "process launch requires an owned private desktop")
|
||||
if not command:
|
||||
raise TaskCenterError("private_desktop", "private desktop command is empty")
|
||||
startup_type = getattr(subprocess, "STARTUPINFO", None)
|
||||
if startup_type is None:
|
||||
class _PortableStartupInfo:
|
||||
dwFlags = 0
|
||||
lpDesktop = self.name
|
||||
startup = _PortableStartupInfo()
|
||||
else:
|
||||
startup = startup_type()
|
||||
startup.dwFlags |= getattr(subprocess, "STARTF_USESHOWWINDOW", 1)
|
||||
startup.lpDesktop = self.name
|
||||
process = subprocess.Popen(
|
||||
tuple(str(item) for item in command),
|
||||
cwd=str(cwd) if cwd is not None else None,
|
||||
env=dict(env) if env is not None else None,
|
||||
startupinfo=startup,
|
||||
text=True,
|
||||
)
|
||||
self._processes.append(process)
|
||||
return process
|
||||
|
||||
def close(self) -> None:
|
||||
for process in reversed(self._processes):
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
self._processes.clear()
|
||||
if self._handle is not None and os.name == "nt":
|
||||
ctypes.windll.user32.CloseDesktop(self._handle)
|
||||
self._handle = None
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Research-only worker protocol for a single project.
|
||||
|
||||
The worker writes versioned request/evidence files and delegates process
|
||||
launching to an injected callback. It never attaches to an existing CAD
|
||||
process and does not perform CAD writes itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, asdict
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .isolated_desktop import PrivateDesktop
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class IsolatedWorkerRequest:
|
||||
protocol_version: str
|
||||
task_id: str
|
||||
project_path: Path
|
||||
target_uids: tuple[str, ...]
|
||||
plan_hash: str
|
||||
allow_writes: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class IsolatedWorkerEvidence:
|
||||
protocol_version: str
|
||||
task_id: str
|
||||
state: str
|
||||
request_hash: str
|
||||
cad_pid: int | None = None
|
||||
project_path: str | None = None
|
||||
message: str = ""
|
||||
|
||||
|
||||
class IsolatedDesktopWorker:
|
||||
"""An explicit opt-in supervision boundary; disabled by default."""
|
||||
|
||||
protocol_version = "1"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
enabled: bool = False,
|
||||
desktop_factory: Callable[[str], PrivateDesktop] | None = None,
|
||||
existing_cad_validator: Callable[[Path], bool] | None = None,
|
||||
) -> None:
|
||||
self.enabled = enabled
|
||||
self._desktop_factory = desktop_factory or (lambda name: PrivateDesktop(name, enabled=True))
|
||||
self._existing_cad_validator = existing_cad_validator or (lambda _path: False)
|
||||
|
||||
@staticmethod
|
||||
def request_hash(request: IsolatedWorkerRequest) -> str:
|
||||
payload = json.dumps(_json_request(request), sort_keys=True, separators=(",", ":")).encode()
|
||||
return hashlib.sha256(payload).hexdigest()
|
||||
|
||||
def run(self, request: IsolatedWorkerRequest, *, evidence_root: Path | None = None) -> IsolatedWorkerEvidence:
|
||||
if not self.enabled:
|
||||
raise TaskCenterError("private_desktop_opt_in", "isolated worker is research-only and requires explicit opt-in")
|
||||
self._validate_request(request)
|
||||
if self._existing_cad_validator(request.project_path):
|
||||
raise TaskCenterError("isolated_cad_attachment", "an unrelated CAD process is already associated with this project")
|
||||
digest = self.request_hash(request)
|
||||
root = Path(evidence_root) if evidence_root is not None else None
|
||||
if root is not None:
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
(root / "request.json").write_text(json.dumps(_json_request(request), indent=2), encoding="utf-8")
|
||||
evidence = IsolatedWorkerEvidence(self.protocol_version, request.task_id, "prepared", digest, project_path=str(request.project_path))
|
||||
if root is not None:
|
||||
(root / "evidence.json").write_text(json.dumps(asdict(evidence), indent=2), encoding="utf-8")
|
||||
return evidence
|
||||
|
||||
def _validate_request(self, request: IsolatedWorkerRequest) -> None:
|
||||
if request.protocol_version != self.protocol_version:
|
||||
raise TaskCenterError("isolated_protocol", "unsupported isolated worker protocol")
|
||||
if not request.task_id or not request.project_path:
|
||||
raise TaskCenterError("isolated_request", "task and project are required")
|
||||
if any(not uid or "\x00" in uid for uid in request.target_uids):
|
||||
raise TaskCenterError("isolated_request", "target UID is invalid")
|
||||
if request.allow_writes:
|
||||
raise TaskCenterError("isolated_write_boundary", "research worker cannot enable CAD writes")
|
||||
|
||||
|
||||
def _json_request(request: IsolatedWorkerRequest) -> dict[str, object]:
|
||||
return {
|
||||
"protocol_version": request.protocol_version,
|
||||
"task_id": request.task_id,
|
||||
"project_path": str(request.project_path),
|
||||
"target_uids": list(request.target_uids),
|
||||
"plan_hash": request.plan_hash,
|
||||
"allow_writes": request.allow_writes,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Frozen, read-only data presented by the single-project task UI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .models import ProjectRecord, RuleRecord, TaskRecord
|
||||
from .quick_run import QuickRunProgress
|
||||
from .target_plan import TargetPlanRow
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ProjectTaskContext:
|
||||
"""One refreshable snapshot of a task and its bound project.
|
||||
|
||||
``project`` is ``None`` for historical tasks that do not have exactly one
|
||||
immutable project binding. Such contexts are intentionally read-only.
|
||||
"""
|
||||
|
||||
task: TaskRecord
|
||||
project: ProjectRecord | None
|
||||
rules: tuple[RuleRecord, ...]
|
||||
targets: tuple[TargetPlanRow, ...]
|
||||
progress: QuickRunProgress
|
||||
phase: str
|
||||
has_evidence: bool
|
||||
interrupted: bool
|
||||
legacy: bool
|
||||
|
||||
@@ -21,6 +21,7 @@ from .target_plan import compile_target_rules
|
||||
from .project_tasks import create_project_tasks as _create_project_tasks
|
||||
from .inventory import collect_target_inventory
|
||||
from .spreadsheet_plan import export_target_plan as _export_target_plan, import_target_plan as _import_target_plan
|
||||
from .project_context import ProjectTaskContext
|
||||
|
||||
|
||||
_Result = TypeVar("_Result")
|
||||
@@ -96,6 +97,7 @@ class TaskCenterService:
|
||||
self._runner = TrialRunner(store, logging_context, probe_source_resolver=probe_source_resolver)
|
||||
self._quick_run_preparer = quick_run_preparer or QuickRunPreparer(logging_context.root)
|
||||
self._batch_feedback = None
|
||||
self._context_cache: dict[str, ProjectTaskContext] = {}
|
||||
|
||||
def create_task(self, name: str, *, note: str = "") -> TaskRecord:
|
||||
return self._idle_quick_run_operation("create_task", None, lambda: self._store.create_task(name, note))
|
||||
@@ -157,6 +159,66 @@ class TaskCenterService:
|
||||
def get_task(self, task_id: str) -> TaskRecord:
|
||||
return self._operation("get_task", task_id, lambda: self._store.get_task(task_id))
|
||||
|
||||
def task_context(self, task_id: str) -> ProjectTaskContext:
|
||||
"""Return the cached immutable context used by the single-project UI."""
|
||||
cached = self._context_cache.get(task_id)
|
||||
if cached is not None:
|
||||
return cached
|
||||
try:
|
||||
return self.refresh_bound_project(task_id)
|
||||
except TaskCenterError as error:
|
||||
if error.code != "project_binding":
|
||||
raise
|
||||
return self._refresh_project_context(task_id, allow_legacy=True)
|
||||
|
||||
def refresh_bound_project(self, task_id: str) -> ProjectTaskContext:
|
||||
"""Refresh one task context from persistence without scanning or COM work."""
|
||||
return self._refresh_project_context(task_id, allow_legacy=False)
|
||||
|
||||
def _refresh_project_context(self, task_id: str, *, allow_legacy: bool) -> ProjectTaskContext:
|
||||
def refresh() -> ProjectTaskContext:
|
||||
task = self._store.get_task(task_id)
|
||||
projects = self._store.list_projects(task_id)
|
||||
bound = None
|
||||
if task.primary_project_id is not None and len(projects) == 1:
|
||||
candidate = projects[0]
|
||||
if candidate.project_id == task.primary_project_id:
|
||||
bound = candidate
|
||||
legacy = bound is None
|
||||
if not allow_legacy and (task.primary_project_id is None or bound is None or len(projects) != 1):
|
||||
raise TaskCenterError("project_binding", "bound task must own exactly one project")
|
||||
rules = self._store.list_rules(task_id)
|
||||
targets = self._store.list_target_plan(task_id)
|
||||
progress = self._context_progress(task_id, task, projects, rules)
|
||||
interrupted = self._quick_run_preparer.has_interrupted(task_id)
|
||||
has_evidence = self._project_task_service(task_id)._quick_run_preparer.evidence_path(task_id) is not None
|
||||
if interrupted:
|
||||
phase = "interrupted"
|
||||
elif progress.queue_complete:
|
||||
phase = "retry" if progress.failed_items else "complete"
|
||||
elif has_evidence:
|
||||
phase = "running"
|
||||
else:
|
||||
phase = "selection"
|
||||
context = ProjectTaskContext(task, bound, tuple(rules), tuple(targets), progress,
|
||||
phase, has_evidence, interrupted, legacy)
|
||||
self._context_cache[task_id] = context
|
||||
return context
|
||||
return self._operation("refresh_bound_project", task_id, refresh)
|
||||
|
||||
def _context_progress(self, task_id: str, task: TaskRecord, projects: tuple[ProjectRecord, ...], rules):
|
||||
delegated = self._project_task_service(task_id)
|
||||
source_projects = projects
|
||||
# A target-plan task must remain empty when all target rows are disabled;
|
||||
# it must never silently fall back to broad legacy rules.
|
||||
effective_rules = tuple(rules)
|
||||
if task.target_plan_mode:
|
||||
effective_rules = tuple()
|
||||
return delegated._quick_run_preparer.progress(
|
||||
task_id, source_projects, effective_rules,
|
||||
copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
)
|
||||
|
||||
def tasks(self, status: TaskStatus | None = None) -> tuple[TaskRecord, ...]:
|
||||
return self._operation("list_tasks", None, lambda: self._store.list_tasks(status))
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop, build_startup_info
|
||||
|
||||
|
||||
def test_startup_info_always_targets_private_desktop():
|
||||
info = build_startup_info('dx-private-test')
|
||||
assert info.lpDesktop == 'dx-private-test'
|
||||
|
||||
|
||||
def test_private_desktop_never_falls_back_to_input_desktop(monkeypatch):
|
||||
desktop = PrivateDesktop('dx-private-test', enabled=True)
|
||||
monkeypatch.setattr(desktop, '_create', lambda: None)
|
||||
monkeypatch.setattr(desktop, '_handle', None)
|
||||
with pytest.raises(TaskCenterError, match='private desktop'):
|
||||
desktop.start_process(('cad.exe',))
|
||||
@@ -0,0 +1,78 @@
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.models import TaskStatus
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
|
||||
def make_service(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
logging = configure_logging(tmp_path / 'data')
|
||||
return TaskCenterService(store, logging), store
|
||||
|
||||
|
||||
def test_task_context_is_frozen_single_bound_project_and_cached(tmp_path):
|
||||
service, store = make_service(tmp_path)
|
||||
task = store.create_task('one')
|
||||
path = tmp_path / 'one.prj'; path.touch()
|
||||
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
|
||||
project = store.set_project_selected(project.project_id, True)
|
||||
store.bind_project_task(task.task_id, project.project_id, 'g', 0)
|
||||
target = ComponentTarget(path, 'MAIN', '1', 'u1', 'R1', 'OLD', 'V')
|
||||
store.record_target_inventory(task.task_id, (target,))
|
||||
store.replace_target_plan(task.task_id, (TargetPlanRow(target, False, 'NEW'),))
|
||||
|
||||
first = service.task_context(task.task_id)
|
||||
second = service.task_context(task.task_id)
|
||||
|
||||
assert first is second
|
||||
assert first.project == project
|
||||
assert first.targets[0].target.uid == 'u1'
|
||||
with pytest.raises(Exception):
|
||||
first.targets += ()
|
||||
|
||||
|
||||
def test_task_context_empty_disabled_plan_does_not_fallback_to_rules(tmp_path):
|
||||
service, store = make_service(tmp_path)
|
||||
task = store.create_task('one')
|
||||
path = tmp_path / 'one.prj'; path.touch()
|
||||
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
|
||||
store.bind_project_task(task.task_id, project.project_id, 'g', 0)
|
||||
store.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
store.record_target_inventory(task.task_id, ())
|
||||
|
||||
context = service.refresh_bound_project(task.task_id)
|
||||
|
||||
assert context.targets == ()
|
||||
assert context.progress.total_items == 0
|
||||
assert context.legacy is False
|
||||
|
||||
|
||||
def test_multi_project_legacy_context_is_read_only(tmp_path):
|
||||
service, store = make_service(tmp_path)
|
||||
task = store.create_task('legacy')
|
||||
paths = (tmp_path / 'a.prj', tmp_path / 'b.prj')
|
||||
for path in paths: path.touch()
|
||||
store.sync_projects(task.task_id, tmp_path, paths)
|
||||
|
||||
context = service.task_context(task.task_id)
|
||||
|
||||
assert context.legacy is True
|
||||
assert context.project is None
|
||||
with pytest.raises(TaskCenterError):
|
||||
service.refresh_bound_project(task.task_id)
|
||||
|
||||
|
||||
def test_private_desktop_worker_is_opt_in_and_never_falls_back():
|
||||
from dx_productivity.trial_task_center.isolated_worker import IsolatedDesktopWorker, IsolatedWorkerRequest
|
||||
|
||||
request = IsolatedWorkerRequest('1', 'task', Path('C:/board.prj'), ('u1',), 'sha256:x')
|
||||
worker = IsolatedDesktopWorker(enabled=False)
|
||||
with pytest.raises(TaskCenterError, match='opt-in'):
|
||||
worker.run(request)
|
||||
Reference in new issue
Block a user