Reuse validated task-local project discovery through public preparer APIs

This commit is contained in:
阿白叔 committed 2026-10-15 09:30:10 +08:00
1 parent 1719683fc3
commit 44b4f5be48
4 files changed
+337 -5

No files matched your search

@@ -0,0 +1,108 @@
"""Conservative, bounded process-local reuse of read-only CAD discovery.
Metadata fingerprints cover every project-tree file except generated logs and
explicit tool data. Links, unreadable paths and changing discovery are misses.
This is an optimization, never a replacement for execution identity checks.
"""
from __future__ import annotations
from collections import OrderedDict
from copy import deepcopy
import os
from pathlib import Path
import stat
from threading import RLock
from .errors import TaskCenterError
def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
try:
project = Path(project).absolute()
root = project.parent
excluded = excluded_root.resolve()
if _unsafe(root.lstat()):
return None
# A project inside the evidence directory cannot be safely excluded.
if project.resolve().is_relative_to(excluded):
return None
rows = []
def fail(error):
raise error
for current, dirs, files in os.walk(root, onerror=fail, followlinks=False):
current = Path(current)
kept = []
for name in sorted(dirs):
path = current / name
if path.resolve() == excluded or name.casefold() == '.git':
continue
info = path.lstat()
if _unsafe(info):
return None
kept.append(name)
dirs[:] = kept
for name in sorted(files):
path = current / name
if path.suffix.casefold() == '.log':
continue
info = path.lstat()
if _unsafe(info) or not stat.S_ISREG(info.st_mode):
return None
rows.append((str(path.relative_to(root)), info.st_dev, info.st_ino,
info.st_size, info.st_mtime_ns, info.st_ctime_ns))
if not project.is_file():
return None
return (str(project.resolve()), tuple(sorted(rows)))
except (OSError, ValueError, RuntimeError):
return None
def _unsafe(info):
return stat.S_ISLNK(info.st_mode) or bool(
getattr(info, 'st_file_attributes', 0) & getattr(stat, 'FILE_ATTRIBUTE_REPARSE_POINT', 0x400))
class DiscoveryCache:
"""One preparer owns one cache; the lock also serializes cache discovery."""
def __init__(self, data_root: Path, capacity: int = 32):
self.data_root = data_root
self.capacity = capacity
self.lock = RLock()
self._entries = OrderedDict()
def invalidate(self, project: Path):
with self.lock:
self._entries.pop(_key(project), None)
def discover(self, project, parts, collect_components, loader):
with self.lock:
key = _key(project)
requested = frozenset(part.casefold() for part in parts)
before = project_fingerprint(project, self.data_root)
entry = self._entries.pop(key, None)
if entry is not None:
stamp, covered, has_components, discovery = entry
if (before is not None and before == stamp and requested <= covered
and (not collect_components or has_components)):
self._entries[key] = entry
return deepcopy(discovery)
discovery = loader()
after = project_fingerprint(project, self.data_root)
if before is not None and before != after:
raise TaskCenterError("quick_run_sheet_discovery",
"project contents changed during discovery; retry read-only discovery")
# Refuse incomplete inventories and bound both projects and row count.
sheets = getattr(discovery, 'sheets', ())
matches = getattr(discovery, 'matched_old_parts', {})
if (before is not None and before == after and sheets
and set(sheets) == set(matches)
and (len(getattr(discovery, 'components', ())) + len(sheets)
+ sum(len(parts) for parts in matches.values())) <= 100000):
self._entries[key] = (after, requested, collect_components, deepcopy(discovery))
while len(self._entries) > self.capacity:
self._entries.popitem(last=False)
return discovery
def _key(project):
return os.path.normcase(os.path.abspath(str(project)))
@@ -44,6 +44,4 @@ def collect_target_inventory(preparer, project_path: Path,
old_part_numbers: tuple[str, ...]) -> tuple[ComponentTarget, ...]:
if not old_part_numbers:
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
discovery = preparer._discover_project_sheets(project_path, old_part_numbers,
collect_components=True)
return discovery.components
return preparer.collect_inventory(project_path, old_part_numbers)
@@ -82,12 +82,16 @@ class QuickRunProgress:
@dataclass(frozen=True, slots=True)
class _ProjectDiscovery:
class ProjectDiscovery:
sheets: tuple[tuple[str, str], ...]
matched_old_parts: dict[tuple[str, str], frozenset[str]]
components: tuple = ()
# Preserve callers that injected the original discovery boundary.
_ProjectDiscovery = ProjectDiscovery
@dataclass(slots=True)
class QuickRunBatchSession:
task_id: str
@@ -136,6 +140,8 @@ class QuickRunPreparer:
self._process_runner = process_runner or _run_process
self._cscript_resolver = cscript_resolver or _resolve_cscript
self._sheet_discoverer = sheet_discoverer
from .discovery_cache import DiscoveryCache
self._discovery_cache = DiscoveryCache(self._data_root)
def prepare(
self,
@@ -246,7 +252,7 @@ class QuickRunPreparer:
if before_sheet_discovery is not None:
before_sheet_discovery(project.path)
if self._sheet_discoverer is None:
discovery = self._discover_project_sheets(project.path, old_part_numbers)
discovery = self.discover_project(project.path, old_part_numbers)
targets = discovery.sheets
assert discovery_matches is not None
discovery_matches[_path_key(project.path)] = discovery.matched_old_parts
@@ -426,6 +432,7 @@ class QuickRunPreparer:
batch_request.unlink(missing_ok=True)
from .worker_monitor import WorkerMonitorError
self.invalidate_discovery(Path(selected_command[2]))
try:
completed = self._process_runner(command, IDLE_PROGRESS_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired as error:
@@ -793,6 +800,40 @@ class QuickRunPreparer:
self.vbs_root_compatible,
)
@property
def data_root(self) -> Path:
"""Task evidence root, exposed without private configuration coupling."""
return self._data_root
def for_data_root(self, data_root: Path) -> QuickRunPreparer:
"""Clone executor configuration with an independent task-local cache."""
return type(self)(data_root, script_source=self._script_source,
run_token_factory=self._run_token_factory, process_runner=self._process_runner,
cscript_resolver=self._cscript_resolver, sheet_discoverer=self._sheet_discoverer)
def invalidate_discovery(self, project_path: Path) -> None:
"""Discard read-only evidence before any potentially mutating worker."""
self._discovery_cache.invalidate(project_path)
def discover_project(self, project_path: Path, old_part_numbers: tuple[str, ...], *,
collect_components: bool = False) -> ProjectDiscovery:
def load():
if collect_components:
return self._discover_project_sheets(project_path, old_part_numbers,
collect_components=True)
return self._discover_project_sheets(project_path, old_part_numbers)
return self._discovery_cache.discover(
Path(project_path), old_part_numbers, collect_components, load)
def collect_inventory(self, project_path: Path, old_part_numbers: tuple[str, ...]) -> tuple:
"""Collect validated component targets, retaining reusable sheet evidence."""
if not old_part_numbers:
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
requested = {part.casefold() for part in old_part_numbers}
return tuple(component for component in self.discover_project(
project_path, old_part_numbers, collect_components=True).components
if component.old_part_number.casefold() in requested)
def _discover_project_sheets(
self,
project_path: Path,