Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

优化 Flash 技能检索启动性能

wangjiudongb187e98931c6
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/capability_metadata.py b/jiuwenswarm/agents/harness/flash/skill_selection/capability_metadata.py
index 16fb9a56d3..43de384a49 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/capability_metadata.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/capability_metadata.py
@@ -1,6 +1,7 @@
"""Static, unverified capability metadata for the main LLM; never a selection gate."""
from dataclasses import dataclass
import re
+from .execution import checkpoint
_FORMAT_QUANTITY = r"(?=[0-90-9]+\s*(?:页|张|份|pages?\b|slides?\b|sheets?\b))"
@@ -128,14 +129,17 @@ def declared_contract(description, sources=()):
# Sources are separate: a format in an unrelated reference never supplies
# an object for an action in the description or another reference.
for raw in (description, *sources):
+ checkpoint()
text = _clean(raw)
clauses = []
for sentence in _SPLIT.split(text):
+ checkpoint()
# "Generate DOCX, cannot read DOC" has two different assertions.
boundaries = [m.start() for m in _CAPABILITY_NEGATIVE.finditer(sentence) if m.start()]
starts = [0, *boundaries, len(sentence)]
clauses.extend(sentence[a:b].strip(' ,,') for a, b in zip(starts, starts[1:]))
for clause in clauses:
+ checkpoint()
# Workflow prohibitions ("do not bypass this Skill using openpyxl")
# are not statements that the Skill lacks workbook creation.
if _NEGATIVE.search(clause) and not _CAPABILITY_NEGATIVE.search(clause):
@@ -171,6 +175,7 @@ def declared_contract(description, sources=()):
continuation = text[scope.end():scope.end() + 650]
if fs and re.search(r'This includes|——|—', continuation, re.I):
for clause in _SPLIT.split(continuation):
+ checkpoint()
if _NEGATIVE.search(clause):
continue
# Only broad objects from the declared file family.
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/catalog.py b/jiuwenswarm/agents/harness/flash/skill_selection/catalog.py
index e13d8817ec..cff576a2d3 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/catalog.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/catalog.py
@@ -1,9 +1,11 @@
-"""Build bounded retrieval texts at startup/refresh, not on each query."""
+"""Index root documents once; enrich only the candidates the model will see."""
from __future__ import annotations
+import hashlib
import logging
-from dataclasses import asdict
+import os
+from dataclasses import asdict, replace
from pathlib import Path
from typing import Sequence
@@ -13,14 +15,19 @@ from .types import SkillDocument
from .cards import capability_card
from .sources import read_sources, source_fingerprint
from .capability_metadata import declared_contract
+from .catalog_cache import CatalogCache
+from .execution import SelectionBusy, checkpoint
+from .freshness import file_stamp, iter_skill_files, sources_unchanged
logger = logging.getLogger(__name__)
+class CatalogChanged(SelectionBusy):
+ """A candidate no longer belongs to the indexed, consistently read version."""
+
+
def directory_id(directory: str | Path) -> str:
# Resolve symlinks and normalize Windows casing so scope comparisons agree.
- import os
-
return os.path.normcase(str(Path(directory).resolve()))
@@ -39,82 +46,145 @@ def _descriptions(metadata: dict) -> tuple[str, ...]:
return tuple(descriptions)
-def read_catalog(
- roots: Sequence[Path], *, text_max_chars: int, text_mode: str = "full",
+def _root_version(document):
+ checkpoint()
+ path = Path(document.directory) / 'SKILL.md'
+ root = Path(document.catalog_root or document.directory)
+ try:
+ resolved = path.resolve()
+ if not resolved.is_relative_to(root):
+ raise CatalogChanged('Skill root now resolves outside its registered directory')
+ stamp = file_stamp(path)
+ if stamp is None or stamp[1] > 1024 * 1024:
+ raise CatalogChanged('Skill root was removed or exceeds the indexing limit')
+ return str(resolved), stamp
+ except (OSError, RuntimeError) as exc:
+ if isinstance(exc, CatalogChanged):
+ raise
+ raise CatalogChanged('Skill root is no longer readable') from exc
+
+
+def hydrate_document(
+ document: SkillDocument, *, cache: CatalogCache | None = None,
observed_files: dict | None = None,
+) -> SkillDocument:
+ """Return the original full candidate fields, after validating its sources.
+
+ Root changes cannot silently alter an existing ranking snapshot. References
+ are independent of ranking and can refresh just this candidate's details.
+ """
+ if not document.root_sha256:
+ # Legacy callers can still construct complete SkillDocument values.
+ return document
+ before = _root_version(document)
+ raw = None
+ if before != document.root_stamp:
+ try:
+ raw = (Path(document.directory) / 'SKILL.md').read_text(encoding='utf-8-sig')
+ except (OSError, UnicodeError) as exc:
+ raise CatalogChanged('Skill root changed or is unreadable') from exc
+ if hashlib.sha256(raw.encode()).hexdigest() != document.root_sha256:
+ raise CatalogChanged('Skill root content changed since indexing')
+ key = (document.id, document.root_sha256, document.capability_description)
+ cached = cache.get_details(key) if cache is not None else None
+ if cached is not None:
+ observed = dict(cached.observed_files)
+ if sources_unchanged(observed) and _root_version(document) == before:
+ if observed_files is not None:
+ observed_files.update(observed)
+ return replace(document, fingerprint=cached.document.fingerprint,
+ capability_record=cached.document.capability_record, root_raw='')
+ checkpoint()
+ if raw is None:
+ raw = document.root_raw or (cache.get_root(document.id, document.root_sha256)
+ if cache is not None else None)
+ if raw is None:
+ try:
+ raw = (Path(document.directory) / 'SKILL.md').read_text(encoding='utf-8-sig')
+ except (OSError, UnicodeError) as exc:
+ raise CatalogChanged('Skill root changed or is unreadable') from exc
+ if hashlib.sha256(raw.encode()).hexdigest() != document.root_sha256:
+ raise CatalogChanged('Skill root content changed since indexing')
+ observed = {}
+ sources = read_sources(document.directory, raw, observed_files=observed)
+ record = asdict(declared_contract(document.capability_description, sources))
+ record = {k: sorted(v) if isinstance(v, frozenset) else v for k, v in record.items()}
+ if _root_version(document) != before or not sources_unchanged(observed):
+ raise CatalogChanged('Skill material changed while preparing its candidate')
+ hydrated = replace(document, fingerprint=source_fingerprint('', sources),
+ capability_record=record, root_raw='')
+ if cache is not None:
+ cache.put_root(document.id, document.root_sha256, raw)
+ cache.put_details(key, hydrated, observed)
+ if observed_files is not None:
+ observed_files.update(observed)
+ return hydrated
+
+
+def _read_document(root, directory, parent, resolved, stamp, *, text_mode, text_max_chars):
+ path = parent / 'SKILL.md'
+ if stamp[1] > 1024 * 1024:
+ raise ValueError('SKILL.md exceeds the 1 MiB local indexing limit')
+ raw = path.read_text(encoding='utf-8-sig')
+ metadata: dict = {}
+ body = raw
+ lines = raw.splitlines()
+ if lines and lines[0].strip() == '---':
+ end = next((i for i in range(1, len(lines)) if lines[i].strip() == '---'), None)
+ if end is not None:
+ metadata = yaml.safe_load('\n'.join(lines[1:end])) or {}
+ body = '\n'.join(lines[end + 1:])
+ if not isinstance(metadata, dict):
+ raise ValueError('Skill front matter must be a mapping')
+ name = str(metadata.get('name') or directory.name)
+ headings = '\n'.join(line for line in body.splitlines() if line.startswith('#'))
+ descriptions = _descriptions(metadata)
+ description = '\n'.join(descriptions)
+ parts = ((name, description) if text_mode == 'description' and description.strip()
+ else (name, description, headings, body))
+ text = ('\n'.join((capability_card(name, descriptions[0] if descriptions else '', body),
+ *(" ".join(value.split())[:600] for value in descriptions[1:])))
+ if text_mode == 'capability' else '\n'.join(parts))[:text_max_chars]
+ document = SkillDocument(
+ os.path.normcase(str(parent)), name, str(parent), text, '', description[:4000], {},
+ root_sha256=hashlib.sha256(raw.encode()).hexdigest(),
+ root_stamp=(str(resolved), stamp), root_raw=raw,
+ capability_description=description[:16384], catalog_root=str(root),
+ )
+ # Files may be replaced while being read. Do not cache a mixed version.
+ if _root_version(document) != document.root_stamp:
+ raise CatalogChanged('Skill root changed while indexing')
+ return document
+
+
+def read_catalog(
+ roots: Sequence[Path], *, text_max_chars: int, text_mode: str = 'full',
+ observed_files: dict | None = None, lightweight: bool = False,
+ cache: CatalogCache | None = None,
) -> tuple[SkillDocument, ...]:
+ """Keep the full legacy result by default; lightweight skips candidate details."""
documents: dict[str, SkillDocument] = {}
- for root in roots:
- root = root.resolve()
- if not root.is_dir():
- continue
- for directory in sorted(root.iterdir()):
- path = directory / "SKILL.md"
- if directory.name.startswith((".", "_")) or not path.is_file():
- continue
- # Shared roots must be registered explicitly, not reached by escaping links.
- if not path.resolve().is_relative_to(root):
- continue
- try:
- identity = directory_id(directory)
- if identity not in documents and len(documents) >= 10000:
- raise RuntimeError(
- "Local skill catalog exceeds the 10000 entry indexing limit"
- )
- if path.stat().st_size > 1024 * 1024:
- raise ValueError("SKILL.md exceeds the 1 MiB local indexing limit")
- raw = path.read_text(encoding="utf-8-sig")
- metadata: dict = {}
- body = raw
- lines = raw.splitlines()
- if lines and lines[0].strip() == "---":
- end = next(
- (i for i in range(1, len(lines)) if lines[i].strip() == "---"),
- None,
- )
- if end is not None:
- metadata = yaml.safe_load("\n".join(lines[1:end])) or {}
- body = "\n".join(lines[end + 1:])
- if not isinstance(metadata, dict):
- raise ValueError("Skill front matter must be a mapping")
- name = str(metadata.get("name") or directory.name)
- # Headings retain later capabilities even when the body is very long.
- headings = "\n".join(
- line for line in body.splitlines() if line.startswith("#")
- )
- descriptions = _descriptions(metadata)
- description = "\n".join(descriptions)
- parts = (
- (name, description)
- if text_mode == "description" and description.strip()
- else (name, description, headings, body)
- )
- text = (
- "\n".join(
- (
- capability_card(name, descriptions[0] if descriptions else "", body),
- # Separate bounds keep the original three-sentence
- # excerpt from dropping the other language fields.
- *(" ".join(value.split())[:600] for value in descriptions[1:]),
- )
- )
- if text_mode == "capability"
- else "\n".join(parts)
- )[:text_max_chars]
- sources = read_sources(directory, raw, observed_files=observed_files)
- record = asdict(declared_contract(description[:16384], sources))
- record = {k: sorted(v) if isinstance(v, frozenset) else v for k, v in record.items()}
- documents[identity] = SkillDocument(
- identity,
- name,
- str(directory.resolve()),
- text,
- source_fingerprint('', sources),
- description[:4000],
- record,
- )
- except (OSError, ValueError, yaml.YAMLError) as exc:
- logger.warning(
- "[SkillSelection] skipping unreadable skill %s: %s", path, exc
- )
+ for root, directory, parent, resolved, stamp in iter_skill_files(roots):
+ checkpoint()
+ path = parent / 'SKILL.md'
+ try:
+ identity = os.path.normcase(str(parent))
+ if identity not in documents and len(documents) >= 10000:
+ raise RuntimeError('Local skill catalog exceeds the 10000 entry indexing limit')
+ version = (str(resolved), stamp)
+ key = (str(root), str(directory), text_mode, text_max_chars)
+ document = cache.get_document(key, version) if cache is not None else None
+ if document is None:
+ document = _read_document(root, directory, parent, resolved, stamp,
+ text_mode=text_mode, text_max_chars=text_max_chars)
+ if cache is not None:
+ cache.put_root(document.id, document.root_sha256, document.root_raw)
+ cache.put_document(key, version, replace(document, root_raw=''))
+ if not lightweight:
+ document = hydrate_document(document, cache=cache, observed_files=observed_files)
+ # A pipeline must not keep every SKILL.md alive outside the bounded
+ # cache. Only the few selected candidates may reload evicted roots.
+ documents[identity] = replace(document, root_raw='') if document.root_raw else document
+ except (OSError, ValueError, yaml.YAMLError) as exc:
+ logger.warning('[SkillSelection] skipping unreadable skill %s: %s', path, exc)
return tuple(documents.values())
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/catalog_cache.py b/jiuwenswarm/agents/harness/flash/skill_selection/catalog_cache.py
new file mode 100644
index 0000000000..c9e110c1c8
--- /dev/null
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/catalog_cache.py
@@ -0,0 +1,89 @@
+"""Bounded content caches; authorization and request choices never live here."""
+
+from collections import OrderedDict
+from dataclasses import dataclass, fields, is_dataclass
+import sys
+import threading
+
+
+def _size(value, seen=None):
+ """Account for retained strings and records, including nested capability data."""
+ seen = set() if seen is None else seen
+ if id(value) in seen:
+ return 0
+ seen.add(id(value))
+ size = sys.getsizeof(value)
+ if is_dataclass(value) and not isinstance(value, type):
+ return size + sum(_size(getattr(value, f.name), seen) for f in fields(value))
+ if isinstance(value, dict):
+ return size + sum(_size(k, seen) + _size(v, seen) for k, v in value.items())
+ if isinstance(value, (tuple, list, set, frozenset)):
+ return size + sum(_size(item, seen) for item in value)
+ return size
+
+
+@dataclass(frozen=True)
+class CachedDetails:
+ document: object
+ observed_files: tuple
+
+
+class CatalogCache:
+ """Thread-safe LRU bounded by both entry count and retained memory.
+
+ Validation stays outside the lock; immutable entries can safely outlive eviction.
+ Versions include file identity, so same-mtime atomic replacement is not a hit.
+ """
+
+ def __init__(self, max_entries=1024, max_bytes=64 * 1024 * 1024):
+ if max_entries < 1 or max_bytes < 1:
+ raise ValueError('Catalog cache bounds must be positive')
+ self.max_entries, self.max_bytes = max_entries, max_bytes
+ self._entries = OrderedDict()
+ self._bytes = 0
+ self._lock = threading.Lock()
+
+ def _get(self, key, version):
+ with self._lock:
+ entry = self._entries.get(key)
+ if entry is None or entry[0] != version:
+ return None
+ self._entries.move_to_end(key)
+ return entry[1]
+
+ def _put(self, key, version, value):
+ size = _size((key, version, value))
+ with self._lock:
+ old = self._entries.pop(key, None)
+ if old is not None:
+ self._bytes -= old[2]
+ if size > self.max_bytes:
+ return
+ self._entries[key] = (version, value, size)
+ self._bytes += size
+ while len(self._entries) > self.max_entries or self._bytes > self.max_bytes:
+ _, discarded = self._entries.popitem(last=False)
+ self._bytes -= discarded[2]
+
+ def get_document(self, key, version):
+ return self._get(('document', key), version)
+
+ def put_document(self, key, version, document):
+ self._put(('document', key), version, document)
+
+ def get_root(self, identity, digest):
+ return self._get(('root', identity), digest)
+
+ def put_root(self, identity, digest, raw):
+ self._put(('root', identity), digest, raw)
+
+ def get_details(self, key):
+ return self._get(('details', key), None)
+
+ def put_details(self, key, document, observed_files):
+ self._put(('details', key), None, CachedDetails(document, tuple(observed_files.items())))
+
+ def clear(self):
+ with self._lock:
+ self._entries.clear()
+ self._bytes = 0
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/execution.py b/jiuwenswarm/agents/harness/flash/skill_selection/execution.py
index cb6d589883..49c94ba30d 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/execution.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/execution.py
@@ -34,12 +34,89 @@ budget: ContextVar[WorkBudget | None] = ContextVar(
"flash_selection_budget", default=None
)
background: ContextVar[bool] = ContextVar("flash_selection_background", default=False)
+build_gate: ContextVar[StartupGate | None] = ContextVar(
+ "flash_selection_build_gate", default=None
+)
+
+
+class StartupLease:
+ """An idempotent lease; the model boundary and finally may both close it."""
+
+ def __init__(self, gate):
+ self._gate = gate
+ self._closed = False
+
+ def close(self):
+ with self._gate._condition:
+ if not self._closed:
+ self._closed = True
+ self._gate._startups -= 1
+ self._gate._condition.notify_all()
+
+
+class StartupGate:
+ """Let speculative builds yield to Flash preparation, without starvation.
+
+ This is cooperative scheduling, not thread cancellation or an I/O barrier.
+ A worker already reading/parsing one item finishes that item before yielding.
+ Every checkpoint has a bounded wait; an actual search waiting for an index
+ bypasses the gate so another session cannot indefinitely block that search.
+ """
+
+ def __init__(self, *, max_pause_s=1.0):
+ if max_pause_s < 0:
+ raise ValueError("max_pause_s must be non-negative")
+ self.max_pause_s = max_pause_s
+ self._condition = threading.Condition()
+ self._startups = self._demands = 0
+ self._closed = False
+
+ def startup(self):
+ with self._condition:
+ self._startups += 1
+ return StartupLease(self)
+
+ @contextmanager
+ def demand(self):
+ with self._condition:
+ self._demands += 1
+ self._condition.notify_all()
+ try:
+ yield
+ finally:
+ with self._condition:
+ self._demands -= 1
+ self._condition.notify_all()
+
+ def checkpoint(self):
+ deadline = time.monotonic() + self.max_pause_s
+ with self._condition:
+ while self._startups and not self._demands and not self._closed:
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ self._condition.wait(remaining)
+
+ def close(self):
+ with self._condition:
+ self._closed = True
+ self._condition.notify_all()
+
+ def stats(self):
+ with self._condition:
+ return {"startups": self._startups, "demands": self._demands,
+ "closed": self._closed}
def checkpoint():
current = budget.get()
if current is not None:
current.check()
+ gate = build_gate.get()
+ if gate is not None:
+ gate.checkpoint()
+ if current is not None:
+ current.check()
class BoundedExecutor:
@@ -160,7 +237,9 @@ class SelectionRuntime:
build_queue=8,
max_requests=64,
max_catalogs=16,
+ gate=None,
):
+ self.gate = gate if gate is not None else StartupGate()
self.queries = BoundedExecutor(
query_workers, query_queue, "flash-skill-query"
)
@@ -200,12 +279,20 @@ class SelectionRuntime:
}
def shutdown(self):
+ # A build can be paused at a checkpoint while shutdown joins workers.
+ self.gate.close()
self.queries.shutdown()
self.builds.shutdown()
_runtime = None
_runtime_lock = threading.Lock()
+_startup_gate = StartupGate()
+
+
+def get_startup_gate():
+ """The Flash entry needs no executor/runtime when selection is disabled."""
+ return _runtime.gate if _runtime is not None else _startup_gate
def get_runtime() -> SelectionRuntime:
@@ -213,6 +300,7 @@ def get_runtime() -> SelectionRuntime:
with _runtime_lock:
if _runtime is None:
_runtime = SelectionRuntime(
+ gate=_startup_gate,
query_workers=_limit("QUERY_WORKERS", 2, 32),
query_queue=_limit("QUERY_QUEUE", 16, 1024),
build_workers=_limit("BUILD_WORKERS", 1, 4),
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/freshness.py b/jiuwenswarm/agents/harness/flash/skill_selection/freshness.py
index f46344279c..5e174be636 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/freshness.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/freshness.py
@@ -1,9 +1,12 @@
"""Cheap filesystem snapshots; no polling thread or persistent index cache."""
from pathlib import Path
+from dataclasses import dataclass
import os
import stat
+from .execution import checkpoint
+
def file_stamp(path: Path):
"""Include file identity to detect atomic replacements retaining mtime."""
@@ -24,17 +27,40 @@ def _is_link(value):
or bool(getattr(value, 'st_file_attributes', 0) & 0x400))
-def catalog_signature(roots):
- """Scan only root SKILL.md entries, with the same containment policy as indexing."""
- entries = []
+@dataclass(frozen=True)
+class SourceStamp:
+ target: str
+ link: tuple | None
+ file: tuple | None
+
+
+def source_stamp(path: Path):
+ """Track missing references and link retargeting as well as target contents."""
+ checkpoint()
+ path = Path(path)
+ try:
+ target = path.resolve()
+ value = path.lstat()
+ link = _stamp(value)
+ except (FileNotFoundError, NotADirectoryError):
+ return SourceStamp(str(path.resolve()), None, None)
+ return SourceStamp(str(target), link, file_stamp(target) if _is_link(value) else link)
+
+
+def iter_skill_files(roots):
+ """Yield checked files without repeatedly resolving ordinary child paths."""
for root in roots:
+ checkpoint()
root = Path(root).resolve()
try:
with os.scandir(root) as scan:
- directories = sorted(scan, key=lambda entry: entry.name)
+ # Match sorted(Path.iterdir()): Windows paths compare without
+ # case, while POSIX paths retain case-sensitive ordering.
+ directories = sorted(scan, key=lambda entry: os.path.normcase(entry.name))
except (FileNotFoundError, NotADirectoryError):
continue
for directory in directories:
+ checkpoint()
if directory.name.startswith(('.', '_')):
continue
try:
@@ -49,8 +75,6 @@ def catalog_signature(roots):
continue
path = parent / 'SKILL.md'
value = path.lstat()
- # Ordinary directories/files are already under the resolved
- # root. Avoid opening every full path just to resolve it again.
resolved = path.resolve() if _is_link(value) else path
if not resolved.is_relative_to(root):
continue
@@ -58,13 +82,24 @@ def catalog_signature(roots):
value = resolved.stat()
except (FileNotFoundError, NotADirectoryError):
continue
- if not stat.S_ISREG(value.st_mode):
- continue
- entries.append((str(Path(directory.path) / 'SKILL.md'), str(resolved), _stamp(value)))
- if len(entries) > 10000:
- raise RuntimeError('Local skill catalog exceeds the 10000 entry indexing limit')
+ if stat.S_ISREG(value.st_mode):
+ yield root, Path(directory.path), parent, resolved, _stamp(value)
+
+
+def catalog_signature(roots):
+ """Scan only root SKILL.md entries, with the same containment policy as indexing."""
+ entries = []
+ for _, directory, _, resolved, value in iter_skill_files(roots):
+ entries.append((str(directory / 'SKILL.md'), str(resolved), value))
+ if len(entries) > 10000:
+ raise RuntimeError('Local skill catalog exceeds the 10000 entry indexing limit')
return tuple(entries)
def sources_unchanged(observed):
- return all(file_stamp(path) == value for path, value in observed.items())
+ for path, value in observed.items():
+ checkpoint()
+ current = source_stamp(path) if isinstance(value, SourceStamp) else file_stamp(path)
+ if current != value:
+ return False
+ return True
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/rail.py b/jiuwenswarm/agents/harness/flash/skill_selection/rail.py
index c9c007c9a3..82b504901d 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/rail.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/rail.py
@@ -15,7 +15,7 @@ from uuid import uuid4
from openjiuwen.harness.prompts import PromptSection
from openjiuwen.harness.rails.base import DeepAgentRail
-from .catalog import directory_id
+from .catalog import CatalogChanged, directory_id
from .config import SelectionSettings
from .execution import SelectionBusy, SelectionTimedOut
from .diagnostics import emit, selection_trace
@@ -323,7 +323,17 @@ class SkillSelectionRail(DeepAgentRail):
settings = SelectionSettings.from_config(self._config_provider())
async with asyncio.timeout(settings.query_timeout_s):
async with state.lock:
- return await self._search_once(query, keywords, ctx, state)
+ for attempt in range(3):
+ try:
+ return await self._search_once(query, keywords, ctx, state)
+ except CatalogChanged:
+ # Never pair old ranking text with newly edited
+ # candidate details. Refresh and recompute permissions.
+ state.results.clear()
+ state.tickets.clear()
+ if attempt == 2:
+ raise
+ self._service.refresh(force=True)
except (TimeoutError, SelectionTimedOut):
self.use_default(ctx, 'timeout')
return self.response('timeout', '检索超时,尚未加载技能;下一轮恢复原生目录与工具。')
@@ -386,9 +396,9 @@ class SkillSelectionRail(DeepAgentRail):
result = state.results.get(cache_key(generation))
cache_hit = result is not None
- if result is None:
- result = await service.search(query, keywords, allowed_ids=allowed, snapshot=snapshot)
- RequestState.remember(state.results, cache_key(result.generation), result)
+ result = await service.search(query, keywords, allowed_ids=allowed, snapshot=snapshot,
+ cached_result=result)
+ RequestState.remember(state.results, cache_key(result.generation), result)
# A disable or catalog/permission switch during background work invalidates this response.
current = SelectionSettings.from_config(self._config_provider())
context_changed = (current.identity() != settings.identity() or service is not self._service
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/service.py b/jiuwenswarm/agents/harness/flash/skill_selection/service.py
index 2de39ddd8d..6437fb9077 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/service.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/service.py
@@ -11,7 +11,8 @@ from pathlib import Path
import threading
import time
-from .catalog import read_catalog
+from .catalog import CatalogChanged, hydrate_document, read_catalog
+from .catalog_cache import CatalogCache
from .config import SelectionSettings
from .freshness import catalog_signature, sources_unchanged
from .diagnostics import configuration_metadata, emit
@@ -21,6 +22,7 @@ from .execution import (
SelectionTimedOut,
WorkBudget,
background,
+ build_gate,
budget,
checkpoint,
get_runtime,
@@ -50,6 +52,7 @@ class SelectionService:
):
self.roots, self.settings = roots, settings
self.runtime = runtime or get_runtime()
+ self._catalog_cache = CatalogCache()
self._lock = threading.RLock()
self._build: Future | None = None
self._pipeline: SelectionPipeline | None = None
@@ -86,6 +89,7 @@ class SelectionService:
def _submit_build(self):
background_token = background.set(True)
budget_token = budget.set(None)
+ gate_token = build_gate.set(self.runtime.gate)
try:
self._building_forced = self._force_refresh
self._build = self.runtime.builds.submit(
@@ -97,6 +101,7 @@ class SelectionService:
self._retry_at = time.monotonic() + 1
raise
finally:
+ build_gate.reset(gate_token)
budget.reset(budget_token)
background.reset(background_token)
# The callback may run synchronously for an already completed Future.
@@ -150,6 +155,7 @@ class SelectionService:
self._pipeline = None
self._signature = None
self._source_files = {}
+ self._catalog_cache.clear()
self._ready = False
return True
@@ -161,7 +167,11 @@ class SelectionService:
# A continuously changing directory fails boundedly; a later search retries.
for _ in range(3):
observed = {}
- pipeline = self._prepare(observed)
+ try:
+ pipeline = self._prepare(observed)
+ except CatalogChanged:
+ current = catalog_signature(self.roots)
+ continue
after = catalog_signature(self.roots)
if current == after and sources_unchanged(observed):
return _PreparedCatalog(pipeline, after, observed, True)
@@ -172,7 +182,7 @@ class SelectionService:
started = time.perf_counter()
documents = read_catalog(
self.roots, text_max_chars=self.settings.text_max_chars, text_mode="capability",
- observed_files=observed_files,
+ observed_files=observed_files, lightweight=True, cache=self._catalog_cache,
)
catalogued = time.perf_counter()
if not documents:
@@ -264,8 +274,9 @@ class SelectionService:
try:
# A hot change may need the same full build as startup. Keep
# the shorter query deadline for BM25 execution, not indexing.
- async with asyncio.timeout(self.settings.startup_timeout_s):
- return await self._snapshot(allow_stale=allow_stale)
+ with self.runtime.gate.demand():
+ async with asyncio.timeout(self.settings.startup_timeout_s):
+ return await self._snapshot(allow_stale=allow_stale)
except TimeoutError as exc:
self.runtime.timeout()
raise SelectionTimedOut('Skill catalog refresh timed out') from exc
@@ -275,6 +286,7 @@ class SelectionService:
async def search(
self, query: str, keywords=(), *, allowed_ids: frozenset[str], snapshot=None,
+ cached_result: SelectionResult | None = None,
) -> SelectionResult:
if len(query) > self.settings.max_query_chars:
raise ValueError("Skill query exceeds max_query_chars")
@@ -303,8 +315,11 @@ class SelectionService:
snapshot_started = time.perf_counter()
# The rail may already have validated a snapshot before
# refreshing native permissions and checking its result cache.
- pipeline, generation = snapshot if snapshot is not None else await self._snapshot()
+ with self.runtime.gate.demand():
+ pipeline, generation = snapshot if snapshot is not None else await self._snapshot()
snapshot_ms = (time.perf_counter() - snapshot_started) * 1000
+ if cached_result is not None and cached_result.generation != generation:
+ cached_result = None
if pipeline is None:
return SelectionResult(
generation=generation,
@@ -327,6 +342,7 @@ class SelectionService:
keywords,
allowed_ids,
time.perf_counter(),
+ cached_result,
)
finally:
budget.reset(token)
@@ -351,14 +367,23 @@ class SelectionService:
with self._lock:
self._active_requests -= 1
- @staticmethod
- def _query(pipeline, query, keywords, allowed_ids, submitted_at):
+ def _query(self, pipeline, query, keywords, allowed_ids, submitted_at, cached_result=None):
queue_ms = (time.perf_counter() - submitted_at) * 1000
checkpoint()
- result = pipeline.search(query, keywords, allowed_ids=allowed_ids)
+ result = cached_result or pipeline.search(query, keywords, allowed_ids=allowed_ids)
+ # Ranking can be reused, but file-backed details must be revalidated
+ # before every response/ticket, including repeated queries in one turn.
+ candidates = []
+ for document, score in result.candidates:
+ checkpoint()
+ if document.id in allowed_ids:
+ document = hydrate_document(document, cache=self._catalog_cache)
+ candidates.append((document, score))
checkpoint()
return replace(
- result, diagnostics={**result.diagnostics, "queue_wait_ms": queue_ms}
+ result,
+ candidates=tuple(candidates),
+ diagnostics={**result.diagnostics, "queue_wait_ms": queue_ms},
)
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/sources.py b/jiuwenswarm/agents/harness/flash/skill_selection/sources.py
index 1c82ccf2cd..38fae9ce69 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/sources.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/sources.py
@@ -3,10 +3,13 @@ import hashlib
import json
from pathlib import Path
import re
-from .freshness import file_stamp
+import stat
+from .execution import checkpoint
+from .freshness import source_stamp
def read_sources(directory, raw=None, *, observed_files=None):
+ checkpoint()
root = Path(directory).resolve()
path = root / 'SKILL.md'
if raw is None:
@@ -19,16 +22,21 @@ def read_sources(directory, raw=None, *, observed_files=None):
# Only local Markdown references actually named by the root document.
references = dict.fromkeys(re.findall(r'(?:\]\(|`)([^`\s()]+\.md)(?:\)|`)', raw, re.I))
for reference in list(references)[:8]:
- target = (root / reference).resolve()
- if not target.is_relative_to(root) or target == path or target.suffix.lower() != '.md':
- continue
+ checkpoint()
try:
+ reference_path = root / reference
+ stamp = source_stamp(reference_path)
+ target = Path(stamp.target)
if observed_files is not None:
# Missing references are tracked too: creating one changes the catalog.
# Keep the referenced path so retargeting an in-root link is
# detected as well as changing the original target's content.
- observed_files[root / reference] = file_stamp(target)
- if target.is_file() and target.stat().st_size <= 65536:
+ observed_files[reference_path] = stamp
+ if not target.is_relative_to(root) or target == path or target.suffix.lower() != '.md':
+ continue
+ # The recorded target metadata already includes size; avoid opening
+ # each path twice more for is_file() and stat().
+ if stamp.file is not None and stat.S_ISREG(stamp.file[0]) and stamp.file[1] <= 65536:
sources.append(target.read_text(encoding='utf-8-sig'))
except (OSError, UnicodeError):
continue
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/startup_lifecycle.py b/jiuwenswarm/agents/harness/flash/skill_selection/startup_lifecycle.py
new file mode 100644
index 0000000000..9f58046699
--- /dev/null
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/startup_lifecycle.py
@@ -0,0 +1,137 @@
+"""Flash-owned preparation scopes across the SDK's reusable worker tasks.
+
+This module schedules optional background work; it is independent of diagnostic
+logging. Wrappers are installed on one Flash instance, never on SDK classes or
+shared model clients. A model boundary closes the lease; finally closes it again
+on every exit path, including cancellation and streams closed before a model.
+"""
+
+from contextlib import contextmanager
+from contextvars import ContextVar
+from dataclasses import dataclass
+from functools import wraps
+import logging
+
+from .execution import get_startup_gate
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass
+class Preparation:
+ request_id: str
+ lease: object
+
+ def close(self):
+ self.lease.close()
+
+
+_current: ContextVar[Preparation | None] = ContextVar(
+ "flash_skill_startup_preparation", default=None
+)
+
+
+@contextmanager
+def bind(preparation):
+ token = _current.set(preparation)
+ try:
+ yield preparation
+ finally:
+ _current.reset(token)
+
+
+@contextmanager
+def preparing(request_id=""):
+ """Nested facade/session creation shares the lease for the same request."""
+ current = _current.get()
+ request_id = str(request_id or "")
+ if current is not None and (not request_id or current.request_id == request_id):
+ yield current
+ return
+ preparation = Preparation(request_id, get_startup_gate().startup())
+ with bind(preparation):
+ try:
+ yield preparation
+ finally:
+ preparation.close()
+
+
+def bind_instance(instance, request_preparations):
+ """Carry the actual request lease through both long-lived SDK workers."""
+ if getattr(instance, "_flash_preparation_bound", False):
+ return
+ instance._flash_preparation_bound = True
+ task_preparations = {}
+ instance._flash_preparation_tasks = task_preparations
+
+ def wrap(name, factory):
+ original = getattr(instance, name, None)
+ if callable(original):
+ setattr(instance, name, factory(original))
+ else:
+ logger.warning("[SkillSelection] preparation hook unavailable: %s", name)
+
+ def round_wrapper(original):
+ @wraps(original)
+ async def execute_round(work, *args, **kwargs):
+ preparation = request_preparations.get(getattr(work, "request_id", None))
+ # An unrelated/background task must not retain the context which
+ # happened to create the SDK supervisor.
+ with bind(preparation):
+ try:
+ return await original(work, *args, **kwargs)
+ finally:
+ if preparation is not None:
+ preparation.close()
+ return execute_round
+
+ def run_wrapper(original):
+ @wraps(original)
+ async def run_round(work, task_id, session, *args, **kwargs):
+ preparation = _current.get()
+ if preparation is not None:
+ task_preparations[task_id] = preparation
+ try:
+ return await original(work, task_id, session, *args, **kwargs)
+ finally:
+ task_preparations.pop(task_id, None)
+ return run_round
+
+ def setup_wrapper(original):
+ @wraps(original)
+ async def setup(*args, **kwargs):
+ result = await original(*args, **kwargs)
+ scheduler = getattr(result[1], "task_scheduler", None)
+ if scheduler is not None and not getattr(scheduler, "_flash_preparation_bound", False):
+ execute = getattr(scheduler, "execute_task", None)
+ if callable(execute):
+ @wraps(execute)
+ async def execute_task(task_id, session, *a, **kw):
+ preparation = task_preparations.get(task_id)
+ with bind(preparation):
+ return await execute(task_id, session, *a, **kw)
+ scheduler.execute_task = execute_task
+ scheduler._flash_preparation_bound = True
+ else:
+ logger.warning("[SkillSelection] preparation scheduler hook unavailable")
+ return result
+ return setup
+
+ wrap("_execute_round", round_wrapper)
+ wrap("run_one_round", run_wrapper)
+ wrap("_setup_task_loop", setup_wrapper)
+ react = getattr(instance, "react_agent", None)
+ apply_kwargs = getattr(react, "_apply_llm_call_kwargs", None)
+ if callable(apply_kwargs):
+ @wraps(apply_kwargs)
+ def before_model(*args, **kwargs):
+ result = apply_kwargs(*args, **kwargs)
+ # SDK calls this after BEFORE_MODEL_CALL rails, context-window
+ # preparation and KV bookkeeping, immediately before invoke/stream.
+ preparation = _current.get()
+ if preparation is not None:
+ preparation.close()
+ return result
+ react._apply_llm_call_kwargs = before_model
+ else:
+ logger.warning("[SkillSelection] preparation model boundary unavailable")
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/types.py b/jiuwenswarm/agents/harness/flash/skill_selection/types.py
index 9091096af7..2c9a908f93 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/types.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/types.py
@@ -12,6 +12,13 @@ class SkillDocument:
fingerprint: str
description: str = ''
capability_record: dict = field(default_factory=dict)
+ # A lightweight index keeps the exact root material that produced its text.
+ # Candidate enrichment must never silently combine another root version with it.
+ root_sha256: str = ''
+ root_stamp: tuple | None = None
+ root_raw: str = ''
+ capability_description: str = ''
+ catalog_root: str = ''
@dataclass(frozen=True)
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
index ab0162d52a..312501822a 100644
--- a/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_flash.py
@@ -75,11 +75,18 @@ from __future__ import annotations
import copy
import logging
import os
+from contextlib import contextmanager
from typing import Any
from openjiuwen.core.foundation.store.base_embedding import EmbeddingConfig
from openjiuwen.harness.rails import SkillUseRail
+try:
+ from jiuwenswarm.agents.harness.flash.skill_selection import startup_lifecycle
+except ImportError:
+ # Skill selection remains an optional, removable Flash extension.
+ startup_lifecycle = None
+
from jiuwenswarm.agents.harness.common.memory.config import (
get_embed_config,
is_proactive_memory,
@@ -285,6 +292,51 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
service_id: str | None = None,
) -> None:
super().__init__(workspace_dir=workspace_dir, agent_id=agent_id, service_id=service_id)
+ self._flash_startup_preparations = {}
+
+ @contextmanager
+ def _prepare_flash_startup(self, request=None):
+ if startup_lifecycle is None:
+ yield
+ return
+ request_id = getattr(request, "request_id", "")
+ preparations = getattr(self, "_flash_startup_preparations", None)
+ if preparations is None:
+ preparations = self._flash_startup_preparations = {}
+ with startup_lifecycle.preparing(request_id) as preparation:
+ previous = preparations.get(request_id)
+ if request_id:
+ preparations[request_id] = preparation
+ try:
+ yield
+ finally:
+ if request_id:
+ if previous is None:
+ preparations.pop(request_id, None)
+ else:
+ preparations[request_id] = previous
+
+ async def process_message_stream_impl(self, request, inputs):
+ with self._prepare_flash_startup(request):
+ stream = super().process_message_stream_impl(request, inputs)
+ try:
+ async for chunk in stream:
+ yield chunk
+ finally:
+ await stream.aclose()
+
+ async def process_message_impl(self, request, inputs):
+ with self._prepare_flash_startup(request):
+ return await super().process_message_impl(request, inputs)
+
+ def _bind_subagent_model_resolver(self):
+ instance = self._instance
+ if instance is not None and startup_lifecycle is not None:
+ preparations = getattr(self, "_flash_startup_preparations", None)
+ if preparations is None:
+ preparations = self._flash_startup_preparations = {}
+ startup_lifecycle.bind_instance(instance, preparations)
+ return super()._bind_subagent_model_resolver()
def _build_web_tools(self, agent_id: str, cache: Any | None = None) -> list[Any]:
"""Expose the single ``web_flash`` card only for the Flash profile."""
@@ -680,11 +732,13 @@ class JiuwenSwarmFlashAdapter(JiuWenSwarmDeepAdapter):
自己的字段,故 flash 的 ``enable_task_loop=false`` 等配置一路传到
``_resolve_enable_task_loop`` 与 ``_build_agent_rails``。
"""
- resolved = _resolve_instance_config_base(config_base)
- resolved = self._apply_flash_react_override(resolved)
- await super().create_instance(
- config=config, mode=mode, sub_mode=sub_mode, config_base=resolved
- )
+ request = config.get("request") if isinstance(config, dict) else None
+ with self._prepare_flash_startup(request):
+ resolved = _resolve_instance_config_base(config_base)
+ resolved = self._apply_flash_react_override(resolved)
+ await super().create_instance(
+ config=config, mode=mode, sub_mode=sub_mode, config_base=resolved
+ )
async def _apply_reload_config_snapshot(
self,
diff --git a/tests/unit_tests/agentserver/test_flash_skill_selection.py b/tests/unit_tests/agentserver/test_flash_skill_selection.py
index 4df795c0d5..5231d6496c 100644
--- a/tests/unit_tests/agentserver/test_flash_skill_selection.py
+++ b/tests/unit_tests/agentserver/test_flash_skill_selection.py
@@ -1148,12 +1148,14 @@ async def test_direct_answers_do_not_trigger_automatic_search(harness, text, mon
async def test_stale_candidate_file_change_is_rejected(harness):
h = harness
await warm_catalog(h)
- write_skill(h.root, 'slides', 'changed body after snapshot')
ctx = context()
await h.rail.before_model_call(ctx)
await h.rail.after_model_call(ctx)
result = await h.rail.handle_action(
SkillSearchInput(action='search', query='制作幻灯片', keywords=['slides']), ctx)
+ # Search now refreshes stale ranking before issuing a ticket. A change
+ # after that ticket must still be rejected before native execution.
+ write_skill(h.root, 'slides', 'changed body after candidate was issued')
assert (await load(h, result['search_id'], 'slides', ctx))['status'] == 'changed'
h.abilities.execute.assert_not_awaited()
@@ -1546,6 +1548,55 @@ async def test_two_round_warm_query_does_not_rescan_and_revocation_is_live(harne
h.abilities.execute.assert_not_awaited()
+async def test_repeated_query_revalidates_details_without_reranking(harness, monkeypatch):
+ h = harness
+ path = h.root / 'slides' / 'SKILL.md'
+ path.write_text(path.read_text(encoding='utf-8') + '\n[Limits](limits.md)\n', encoding='utf-8')
+ reference = path.parent / 'limits.md'
+ reference.write_text('Supports creating PPTX presentations.', encoding='utf-8')
+ await warm_catalog(h)
+ pipeline = h.rail.service._pipeline
+ original_search = pipeline.search
+ calls = 0
+
+ def count_search(*args, **kwargs):
+ nonlocal calls
+ calls += 1
+ return original_search(*args, **kwargs)
+
+ monkeypatch.setattr(pipeline, 'search', count_search)
+ ctx = context()
+ await h.rail.before_model_call(ctx)
+ first = await h.rail._search_from_model('制作幻灯片', ['slides'], ctx)
+ state = ctx.extra[h.rail.REUSE]
+ first_document = state.tickets[first['search_id']]['result'].candidates[0][0]
+ reference.write_text('Cannot create PPTX. Only supports creating PDF.', encoding='utf-8')
+ second = await h.rail._search_from_model('制作幻灯片', ['slides'], ctx)
+ second_document = state.tickets[second['search_id']]['result'].candidates[0][0]
+ assert calls == 1
+ assert first_document.fingerprint != second_document.fingerprint
+ assert first_document.capability_record != second_document.capability_record
+ assert (await load(h, first['search_id'], 'slides', ctx))['status'] == 'changed'
+ h.abilities.execute.assert_not_awaited()
+
+
+async def test_search_refreshes_root_changed_after_ranking_snapshot(harness):
+ h = harness
+ await warm_catalog(h)
+ old_generation = h.rail.service.generation
+ write_skill(h.root, 'slides', 'Only supports creating PDF presentation slides.')
+ ctx = context()
+ await h.rail.before_model_call(ctx)
+ result = await h.rail._search_from_model('presentation', ['slides'], ctx)
+ assert result['status'] == 'candidates'
+ ticket = ctx.extra[h.rail.REUSE].tickets[result['search_id']]
+ document = ticket['result'].candidates[0][0]
+ assert document.description == 'Only supports creating PDF presentation slides.'
+ assert ticket['result'].generation > old_generation
+ assert document.fingerprint and document.capability_record
+ assert not ctx.extra.get(h.rail.FALLBACK)
+
+
async def test_two_round_timeout_restores_all_tools_and_catalog(harness, monkeypatch):
h = harness
h.config['flash']['skill_selection']['query_timeout_s'] = 0.1
diff --git a/tests/unit_tests/agentserver/test_flash_skill_selection_cold_start.py b/tests/unit_tests/agentserver/test_flash_skill_selection_cold_start.py
new file mode 100644
index 0000000000..b72cc7f744
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_flash_skill_selection_cold_start.py
@@ -0,0 +1,343 @@
+"""Cold catalog preparation preserves retrieval and native-loading evidence."""
+from __future__ import annotations
+
+from collections import Counter
+from pathlib import Path
+import os
+
+import pytest
+import yaml
+
+from jiuwenswarm.agents.harness.flash.skill_selection import catalog, execution, service
+from jiuwenswarm.agents.harness.flash.skill_selection.config import SelectionSettings
+from jiuwenswarm.agents.harness.flash.skill_selection.pipeline import SelectionPipeline
+from jiuwenswarm.agents.harness.flash.skill_selection.presentation import candidate_view
+
+
+def write_skill(root, name, *, reference=True, create_reference=True):
+ directory = root / name
+ directory.mkdir(parents=True, exist_ok=True)
+ metadata = {
+ "name": name,
+ "description": "Create PowerPoint presentation slides and export PPTX.",
+ "description_zh": "制作演示文稿;不能编辑 XLSX。",
+ "description_en": "Create editable slides for a science festival.",
+ }
+ body = "# Presentation workflow\nCreate PPTX from the supplied content.\n"
+ if reference:
+ body += "Read [format policy](references/formats.md).\n"
+ (directory / "SKILL.md").write_text(
+ "---\n" + yaml.safe_dump(metadata, allow_unicode=True, sort_keys=False)
+ + "---\n" + body,
+ encoding="utf-8",
+ )
+ if reference and create_reference:
+ path = directory / "references" / "formats.md"
+ path.parent.mkdir()
+ path.write_text("Cannot create PDF. Outputs: PPTX only.\n", encoding="utf-8")
+ return directory
+
+
+def legacy_fields(document):
+ """New cache bookkeeping must not change any existing public output field."""
+ return tuple(getattr(document, name) for name in (
+ "id", "name", "directory", "text", "fingerprint", "description", "capability_record",
+ ))
+
+
+def prepare(roots, *, cache=None, lightweight=False):
+ return catalog.read_catalog(
+ roots, text_max_chars=2000, text_mode="capability", cache=cache,
+ lightweight=lightweight,
+ )
+
+
+def pipeline(documents):
+ result = SelectionPipeline(SelectionSettings(enabled=True))
+ result.prepare(documents)
+ return result
+
+
+def rank(index, allowed):
+ return index.search("Create science festival presentation slides", ("PPTX", "演示文稿"),
+ allowed_ids=frozenset(allowed))
+
+
+def observe_reads(monkeypatch):
+ reads = Counter()
+ read_text = Path.read_text
+
+ def recorded(path, *args, **kwargs):
+ reads[os.path.normcase(os.path.abspath(path))] += 1
+ return read_text(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", recorded)
+ return reads
+
+
+def read_count(reads, path):
+ return reads[os.path.normcase(os.path.abspath(path))]
+
+
+def changed_text(path, text):
+ previous = path.stat()
+ path.write_text(text, encoding="utf-8")
+ # Explicitly advance the version; do not depend on filesystem clock resolution.
+ os.utime(path, ns=(previous.st_atime_ns, previous.st_mtime_ns + 2_000_000_000))
+
+
+def replace_preserving_mtime(path, text):
+ previous = path.stat()
+ replacement = path.with_name(path.name + ".replacement")
+ replacement.write_text(text, encoding="utf-8")
+ os.utime(replacement, ns=(previous.st_atime_ns, previous.st_mtime_ns))
+ replacement.replace(path)
+
+
+def make_symlink(path, target, *, directory=False):
+ try:
+ path.symlink_to(target, target_is_directory=directory)
+ except (OSError, NotImplementedError) as exc:
+ pytest.skip(f"This host does not permit creating test symlinks: {exc}")
+
+
+def test_cold_catalog_defers_references_and_contracts_until_allowed_top_five(tmp_path, monkeypatch):
+ root = tmp_path / "skills"
+ directories = [write_skill(root, f"slides-{number:02d}") for number in range(9)]
+ expected = prepare([root])
+ original_contract = catalog.declared_contract
+ contracts = []
+
+ def counted_contract(*args, **kwargs):
+ contracts.append(args)
+ return original_contract(*args, **kwargs)
+
+ monkeypatch.setattr(catalog, "declared_contract", counted_contract)
+ reads = observe_reads(monkeypatch)
+ cache = catalog.CatalogCache()
+ lightweight = prepare([root], cache=cache, lightweight=True)
+
+ assert contracts == []
+ assert all(read_count(reads, directory / "references" / "formats.md") == 0
+ for directory in directories)
+ assert [(d.id, d.name, d.text, d.description) for d in lightweight] == [
+ (d.id, d.name, d.text, d.description) for d in expected
+ ]
+ assert all(not document.fingerprint and not document.capability_record
+ for document in lightweight)
+ assert all(not document.root_raw for document in lightweight)
+
+ # Exclude the first sorted skill, so a pre-filter top K would be incorrect.
+ allowed = {document.id for document in expected[1:]}
+ eager_result = rank(pipeline(expected), allowed)
+ light_result = rank(pipeline(lightweight), allowed)
+ assert [(d.id, score) for d, score in light_result.candidates] == [
+ (d.id, score) for d, score in eager_result.candidates
+ ]
+ assert len(light_result.candidates) == 5
+ hydrated = [catalog.hydrate_document(document, cache=cache)
+ for document, _ in light_result.candidates]
+ assert [legacy_fields(d) for d in hydrated] == [
+ legacy_fields(d) for d, _ in eager_result.candidates
+ ]
+ assert [candidate_view(d) for d in hydrated] == [
+ candidate_view(d) for d, _ in eager_result.candidates
+ ]
+ assert len(contracts) == 5
+ selected_ids = {document.id for document in hydrated}
+ for directory in directories:
+ assert read_count(reads, directory / "references" / "formats.md") == (
+ 1 if catalog.directory_id(directory) in selected_ids else 0
+ )
+
+ counts = reads.copy()
+ for document, _ in light_result.candidates:
+ catalog.hydrate_document(document, cache=cache)
+ assert len(contracts) == 5
+ assert reads == counts
+
+
+def test_unchanged_catalog_reuses_documents_and_only_changed_root_is_reparsed(tmp_path, monkeypatch):
+ root = tmp_path / "skills"
+ directories = [write_skill(root, f"slides-{number}") for number in range(3)]
+ cache = catalog.CatalogCache()
+ first = prepare([root], cache=cache, lightweight=True)
+ reads = observe_reads(monkeypatch)
+ second = prepare([root], cache=cache, lightweight=True)
+ assert [(d.id, d.text) for d in first] == [(d.id, d.text) for d in second]
+ assert all(read_count(reads, directory / "SKILL.md") == 0 for directory in directories)
+
+ changed = directories[1] / "SKILL.md"
+ raw = changed.read_text(encoding="utf-8")
+ changed_text(changed, raw.replace("science festival", "school exhibition"))
+ reads.clear()
+ third = prepare([root], cache=cache, lightweight=True)
+ assert [read_count(reads, directory / "SKILL.md") for directory in directories] == [0, 1, 0]
+ assert third[0].text == first[0].text and third[2].text == first[2].text
+ assert third[1].text != first[1].text
+ eager = prepare([root])
+ assert [legacy_fields(catalog.hydrate_document(d, cache=cache)) for d in third] == [
+ legacy_fields(d) for d in eager
+ ]
+
+
[email protected]("change", ["modify", "create", "replace_same_mtime"])
+def test_reference_changes_refresh_details_without_changing_index_text(tmp_path, change):
+ root = tmp_path / "skills"
+ directory = write_skill(root, "slides", create_reference=change != "create")
+ cache = catalog.CatalogCache()
+ document, = prepare([root], cache=cache, lightweight=True)
+ before = catalog.hydrate_document(document, cache=cache)
+ reference = directory / "references" / "formats.md"
+ new_policy = "Cannot create PNG. Outputs: PPTX only.\n"
+ if change == "create":
+ reference.parent.mkdir()
+ reference.write_text(new_policy, encoding="utf-8")
+ elif change == "replace_same_mtime":
+ replace_preserving_mtime(reference, new_policy)
+ else:
+ changed_text(reference, new_policy)
+
+ after = catalog.hydrate_document(document, cache=cache)
+ eager, = prepare([root])
+ assert after.text == before.text == document.text
+ assert after.fingerprint != before.fingerprint
+ assert after.capability_record != before.capability_record
+ assert legacy_fields(after) == legacy_fields(eager)
+
+
[email protected]("change", ["modify", "replace_same_mtime"])
+def test_changed_root_cannot_mix_old_ranking_with_new_candidate_details(tmp_path, change):
+ root = tmp_path / "skills"
+ directory = write_skill(root, "slides")
+ cache = catalog.CatalogCache()
+ stale, = prepare([root], cache=cache, lightweight=True)
+ # Exercise the rich-cache hit path too: it must still detect later changes.
+ catalog.hydrate_document(stale, cache=cache)
+ path = directory / "SKILL.md"
+ updated = path.read_text(encoding="utf-8").replace("science festival", "science workshop")
+ if change == "replace_same_mtime":
+ replace_preserving_mtime(path, updated)
+ else:
+ changed_text(path, updated)
+ with pytest.raises(catalog.CatalogChanged):
+ catalog.hydrate_document(stale, cache=cache)
+
+ fresh, = prepare([root], cache=cache, lightweight=True)
+ eager, = prepare([root])
+ assert legacy_fields(catalog.hydrate_document(fresh, cache=cache)) == legacy_fields(eager)
+
+
+def test_deleted_root_does_not_return_cached_candidate(tmp_path):
+ root = tmp_path / "skills"
+ directory = write_skill(root, "slides")
+ cache = catalog.CatalogCache()
+ document, = prepare([root], cache=cache, lightweight=True)
+ catalog.hydrate_document(document, cache=cache)
+ (directory / "SKILL.md").unlink()
+ with pytest.raises(catalog.CatalogChanged):
+ catalog.hydrate_document(document, cache=cache)
+ assert prepare([root], cache=cache, lightweight=True) == ()
+
+
+def test_directory_links_cannot_import_a_skill_from_outside_root(tmp_path):
+ root = tmp_path / "skills"
+ root.mkdir()
+ outside = write_skill(tmp_path / "outside", "slides")
+ make_symlink(root / "escaped", outside, directory=True)
+ assert prepare([root], cache=catalog.CatalogCache(), lightweight=True) == ()
+
+
+def test_cached_root_cannot_be_replaced_with_an_escaping_file_link(tmp_path):
+ root = tmp_path / "skills"
+ directory = write_skill(root, "slides")
+ cache = catalog.CatalogCache()
+ document, = prepare([root], cache=cache, lightweight=True)
+ catalog.hydrate_document(document, cache=cache)
+ path = directory / "SKILL.md"
+ outside = tmp_path / "outside-skill.md"
+ # Identical contents are insufficient: the location is no longer allowed.
+ outside.write_text(path.read_text(encoding="utf-8"), encoding="utf-8")
+ path.unlink()
+ make_symlink(path, outside)
+ with pytest.raises(catalog.CatalogChanged):
+ catalog.hydrate_document(document, cache=cache)
+ assert prepare([root], cache=cache, lightweight=True) == ()
+
+
[email protected]("initially_outside", [False, True])
+def test_reference_link_retarget_invalidates_details_and_cannot_escape_skill(tmp_path, initially_outside):
+ root = tmp_path / "skills"
+ directory = write_skill(root, "slides", create_reference=False)
+ reference = directory / "references" / "formats.md"
+ reference.parent.mkdir()
+ permitted = directory / "local-policy.md"
+ permitted.write_text("Cannot create PDF.\n", encoding="utf-8")
+ outside = tmp_path / "outside-policy.md"
+ outside.write_text("Create secret DOCX.\n", encoding="utf-8")
+ make_symlink(reference, outside if initially_outside else permitted)
+ cache = catalog.CatalogCache()
+ document, = prepare([root], cache=cache, lightweight=True)
+ before = catalog.hydrate_document(document, cache=cache)
+ reference.unlink()
+ make_symlink(reference, permitted if initially_outside else outside)
+ after = catalog.hydrate_document(document, cache=cache)
+ eager, = prepare([root])
+ assert before.fingerprint != after.fingerprint
+ assert legacy_fields(after) == legacy_fields(eager)
+ assert ("create", "docx") not in after.capability_record.get("supported", ())
+
+
+def test_catalog_preserves_platform_path_order(tmp_path):
+ root = tmp_path / 'skills'
+ for name in ('z-slides', 'B-slides', 'aa-slides'):
+ write_skill(root, name)
+ documents = prepare([root], lightweight=True)
+ assert [d.name for d in documents] == [path.name for path in sorted(root.iterdir())]
+
+
+def test_bounded_cache_eviction_preserves_catalog_and_details(tmp_path):
+ root = tmp_path / "skills"
+ for number in range(3):
+ write_skill(root, f"slides-{number}")
+ cache = catalog.CatalogCache(max_entries=1)
+ documents = prepare([root], cache=cache, lightweight=True)
+ assert all(not document.root_raw for document in documents)
+ expected = {d.id: d for d in prepare([root])}
+ for document in [*documents, documents[0]]:
+ assert legacy_fields(catalog.hydrate_document(document, cache=cache)) == legacy_fields(
+ expected[document.id]
+ )
+
+
+async def test_service_first_search_returns_complete_authorized_candidates(tmp_path, monkeypatch):
+ root = tmp_path / "skills"
+ directories = [write_skill(root, f"slides-{number:02d}") for number in range(8)]
+ expected = prepare([root])
+ allowed = frozenset(d.id for d in expected[1:])
+ eager = rank(pipeline(expected), allowed)
+ reads = observe_reads(monkeypatch)
+ runtime = execution.SelectionRuntime()
+ instance = service.SelectionService((root,), SelectionSettings(enabled=True), runtime=runtime)
+ try:
+ snapshot = await instance.current_snapshot()
+ assert all(not d.root_raw for d in snapshot[0].documents.values())
+ assert all(read_count(reads, directory / "references" / "formats.md") == 0
+ for directory in directories)
+ result = await instance.search(
+ "Create science festival presentation slides", ("PPTX", "演示文稿"),
+ allowed_ids=allowed, snapshot=snapshot,
+ )
+ assert [(d.id, score) for d, score in result.candidates] == [
+ (d.id, score) for d, score in eager.candidates
+ ]
+ assert [legacy_fields(d) for d, _ in result.candidates] == [
+ legacy_fields(d) for d, _ in eager.candidates
+ ]
+ assert all(d.fingerprint and d.capability_record for d, _ in result.candidates)
+ assert read_count(reads, directories[0] / "references" / "formats.md") == 0
+ assert sum(read_count(reads, directory / "references" / "formats.md")
+ for directory in directories) == 5
+ finally:
+ runtime.shutdown()
diff --git a/tests/unit_tests/agentserver/test_flash_skill_startup_lifecycle.py b/tests/unit_tests/agentserver/test_flash_skill_startup_lifecycle.py
new file mode 100644
index 0000000000..e78cc8c385
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_flash_skill_startup_lifecycle.py
@@ -0,0 +1,293 @@
+"""Background build scheduling must not depend on diagnostic instrumentation."""
+
+import asyncio
+import threading
+import time
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import pytest
+
+from jiuwenswarm.agents.harness.flash.skill_selection import execution
+from jiuwenswarm.agents.harness.flash.skill_selection import startup_lifecycle as lifecycle
+
+
+def test_preparation_does_not_create_runtime_when_selection_disabled(monkeypatch):
+ gate = execution.StartupGate()
+ monkeypatch.setattr(execution, "_runtime", None)
+ monkeypatch.setattr(execution, "_startup_gate", gate)
+ with lifecycle.preparing("disabled"):
+ assert gate.stats()["startups"] == 1
+ assert execution._runtime is None
+ assert gate.stats()["startups"] == 0
+
+
+def test_gate_yields_until_lease_closed_and_close_is_idempotent():
+ gate = execution.StartupGate(max_pause_s=5)
+ lease = gate.startup()
+ entered, finished = threading.Event(), threading.Event()
+
+ def run():
+ entered.set()
+ gate.checkpoint()
+ finished.set()
+
+ worker = threading.Thread(target=run)
+ worker.start()
+ try:
+ assert entered.wait(1)
+ assert not finished.wait(0.03)
+ lease.close()
+ lease.close()
+ assert finished.wait(1)
+ assert gate.stats()["startups"] == 0
+ finally:
+ gate.close()
+ worker.join(1)
+
+
+def test_gate_has_bounded_wait_even_under_continuous_startup():
+ gate = execution.StartupGate(max_pause_s=0.025)
+ lease = gate.startup()
+ started = time.monotonic()
+ gate.checkpoint()
+ assert time.monotonic() - started >= 0.02
+ assert gate.stats()["startups"] == 1
+ lease.close()
+
+
+def test_demand_wakes_a_build_and_releases_on_exception():
+ gate = execution.StartupGate(max_pause_s=5)
+ lease = gate.startup()
+ finished = threading.Event()
+ worker = threading.Thread(target=lambda: (gate.checkpoint(), finished.set()))
+ worker.start()
+ try:
+ assert not finished.wait(0.03)
+ with pytest.raises(RuntimeError):
+ with gate.demand():
+ assert finished.wait(1)
+ raise RuntimeError("cancelled search")
+ assert gate.stats()["demands"] == 0
+ finally:
+ lease.close()
+ gate.close()
+ worker.join(1)
+
+
+def test_running_build_is_cooperative_and_runtime_shutdown_wakes_it():
+ runtime = execution.SelectionRuntime(build_workers=1, build_queue=0)
+ runtime.gate.max_pause_s = 60
+ lease = runtime.gate.startup()
+ entered = threading.Event()
+
+ def work():
+ entered.set()
+ execution.checkpoint()
+ return "complete"
+
+ token = execution.build_gate.set(runtime.gate)
+ try:
+ future = runtime.builds.submit(work)
+ finally:
+ execution.build_gate.reset(token)
+ stopped = threading.Event()
+ shutdown = threading.Thread(target=lambda: (runtime.shutdown(), stopped.set()))
+ try:
+ assert entered.wait(1)
+ # Running Python code cannot be paused or stopped by Future.cancel().
+ assert not future.cancel()
+ assert not future.done()
+ shutdown.start()
+ assert stopped.wait(2)
+ assert future.result() == "complete"
+ finally:
+ runtime.gate.close()
+ if shutdown.ident is not None:
+ shutdown.join(2)
+ else:
+ runtime.shutdown()
+ lease.close()
+
+
+class _React:
+ def _apply_llm_call_kwargs(self, ctx, kwargs):
+ return kwargs
+
+
+class _Instance:
+ """Reuse a worker task whose ContextVars were copied during the first round."""
+
+ def __init__(self, gate):
+ self.gate = gate
+ self.react_agent = _React()
+ self.controller = SimpleNamespace(task_scheduler=SimpleNamespace(execute_task=self.execute))
+ self.queue = asyncio.Queue()
+ self.worker = None
+ self.observed = []
+ self.fail = False
+
+ async def _setup_task_loop(self):
+ if self.worker is None:
+ self.worker = asyncio.create_task(self.consume())
+ return None, self.controller
+
+ async def consume(self):
+ while True:
+ task_id, completed = await self.queue.get()
+ try:
+ result = await self.controller.task_scheduler.execute_task(task_id, None)
+ except BaseException as exc:
+ completed.set_exception(exc)
+ else:
+ completed.set_result(result)
+
+ async def _execute_round(self, work):
+ return await self.run_one_round(work, work.request_id + "-task", None)
+
+ async def run_one_round(self, work, task_id, session):
+ await self._setup_task_loop()
+ completed = asyncio.get_running_loop().create_future()
+ await self.queue.put((task_id, completed))
+ return await completed
+
+ async def execute(self, task_id, session):
+ preparation = lifecycle._current.get()
+ self.observed.append((preparation.request_id if preparation else None,
+ self.gate.stats()["startups"]))
+ if self.fail:
+ raise RuntimeError("before model failed")
+ kwargs = self.react_agent._apply_llm_call_kwargs(None, {"unchanged": True})
+ self.observed.append(("model", self.gate.stats()["startups"]))
+ return kwargs
+
+ async def stop(self):
+ if self.worker:
+ self.worker.cancel()
+ await asyncio.gather(self.worker, return_exceptions=True)
+
+
+async def test_first_and_continuation_bind_actual_request_without_timing(monkeypatch):
+ monkeypatch.setenv("FLASH_STARTUP_TIMING", "0")
+ gate = execution.StartupGate()
+ monkeypatch.setattr(lifecycle, "get_startup_gate", lambda: gate)
+ requests = {}
+ instance = _Instance(gate)
+ original_class_method = _React._apply_llm_call_kwargs
+ lifecycle.bind_instance(instance, requests)
+ lifecycle.bind_instance(instance, requests) # Idempotent on reload.
+ try:
+ for request_id in ("first", "continuation"):
+ with lifecycle.preparing(request_id) as preparation:
+ requests[request_id] = preparation
+ result = await instance._execute_round(SimpleNamespace(request_id=request_id))
+ assert result == {"unchanged": True}
+ assert gate.stats()["startups"] == 0
+ requests.pop(request_id)
+ assert instance.observed == [("first", 1), ("model", 0),
+ ("continuation", 1), ("model", 0)]
+ assert not instance._flash_preparation_tasks
+ assert _React._apply_llm_call_kwargs is original_class_method
+ # An unrelated task must not inherit the first request from the worker.
+ await instance._execute_round(SimpleNamespace(request_id="background"))
+ assert instance.observed[-2:] == [(None, 0), ("model", 0)]
+ finally:
+ await instance.stop()
+
+
+async def test_failure_before_model_releases_lease_and_task_mapping(monkeypatch):
+ gate = execution.StartupGate()
+ monkeypatch.setattr(lifecycle, "get_startup_gate", lambda: gate)
+ requests = {}
+ instance = _Instance(gate)
+ instance.fail = True
+ lifecycle.bind_instance(instance, requests)
+ try:
+ with lifecycle.preparing("failed") as preparation:
+ requests["failed"] = preparation
+ with pytest.raises(RuntimeError, match="before model failed"):
+ await instance._execute_round(SimpleNamespace(request_id="failed"))
+ assert gate.stats()["startups"] == 0
+ assert not instance._flash_preparation_tasks
+ finally:
+ await instance.stop()
+
+
+async def test_cancellation_releases_preparation(monkeypatch):
+ gate = execution.StartupGate()
+ monkeypatch.setattr(lifecycle, "get_startup_gate", lambda: gate)
+ entered = asyncio.Event()
+
+ async def prepare():
+ with lifecycle.preparing("cancelled"):
+ entered.set()
+ await asyncio.Event().wait()
+
+ task = asyncio.create_task(prepare())
+ await entered.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert gate.stats()["startups"] == 0
+
+
+def test_nested_creation_keeps_outer_lease_until_model_boundary(monkeypatch):
+ gate = execution.StartupGate()
+ monkeypatch.setattr(lifecycle, "get_startup_gate", lambda: gate)
+ with lifecycle.preparing("request") as outer:
+ with lifecycle.preparing("request") as inner:
+ assert outer is inner
+ assert gate.stats()["startups"] == 1
+ assert gate.stats()["startups"] == 1
+ assert gate.stats()["startups"] == 0
+
+
+async def test_real_sdk_reused_scheduler_releases_each_request_before_model(monkeypatch):
+ """Exercise the actual SDK controller with a local model double, no network."""
+ from openjiuwen.core.single_agent import AgentCard, create_agent_session
+ from openjiuwen.harness.deep_agent import DeepAgent
+ from openjiuwen.harness.schema.interaction import RoundWorkItem
+
+ monkeypatch.setenv("FLASH_STARTUP_TIMING", "0")
+ gate = execution.StartupGate()
+ monkeypatch.setattr(lifecycle, "get_startup_gate", lambda: gate)
+ agent = DeepAgent(AgentCard(name="flash-startup-gate-test"))
+ session = create_agent_session(session_id="flash-startup-gate", card=agent.card)
+ observed = []
+
+ async def model_invoke(inputs, sdk_session, **kwargs):
+ preparation = lifecycle._current.get()
+ observed.append(preparation.request_id)
+ assert gate.stats()["startups"] == 1
+ agent.react_agent._apply_llm_call_kwargs(None, {})
+ assert gate.stats()["startups"] == 0
+ await asyncio.sleep(0)
+ return {"result_type": "answer", "output": "test"}
+
+ agent._react_agent = SimpleNamespace(
+ invoke=model_invoke,
+ write_invoke_result_to_stream=AsyncMock(),
+ _apply_llm_call_kwargs=lambda ctx, kwargs: kwargs,
+ )
+ lifecycle.bind_instance(agent, {})
+ try:
+ with lifecycle.preparing("old-worker-context"):
+ _, controller = await agent.prepare_interaction_task_loop(session)
+ scheduler = controller.task_scheduler
+ for request_id in ("first", "continuation"):
+ with lifecycle.preparing(request_id):
+ outcome = await asyncio.wait_for(agent.run_one_round(
+ RoundWorkItem.user(request_id=request_id, inputs={"query": "test"}),
+ request_id + "-task", session,
+ ), timeout=5)
+ assert outcome.error_code is None
+ assert gate.stats()["startups"] == 0
+ assert controller.task_scheduler is scheduler
+ assert not agent._flash_preparation_tasks
+ assert observed == ["first", "continuation"]
+ finally:
+ await agent._force_cleanup_controller()