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 技能检索的代码检查问题

wangjiudonga18583213c69
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/execution.py b/jiuwenswarm/agents/harness/flash/skill_selection/execution.py
index 49c94ba30d..a057e2b931 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/execution.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/execution.py
@@ -45,13 +45,13 @@ class StartupLease:
def __init__(self, gate):
self._gate = gate
self._closed = False
+ self._close_lock = threading.Lock()
def close(self):
- with self._gate._condition:
+ with self._close_lock:
if not self._closed:
+ self._gate.release_startup()
self._closed = True
- self._gate._startups -= 1
- self._gate._condition.notify_all()
class StartupGate:
@@ -76,6 +76,12 @@ class StartupGate:
self._startups += 1
return StartupLease(self)
+ def release_startup(self):
+ """Release one lease and wake builders under the gate's own lock."""
+ with self._condition:
+ self._startups -= 1
+ self._condition.notify_all()
+
@contextmanager
def demand(self):
with self._condition:
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/service.py b/jiuwenswarm/agents/harness/flash/skill_selection/service.py
index 6437fb9077..b5e2fa8f82 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/service.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/service.py
@@ -42,6 +42,15 @@ class _PreparedCatalog:
changed: bool
+@dataclass(frozen=True)
+class _QueryWork:
+ query: str
+ keywords: tuple[str, ...]
+ allowed_ids: frozenset[str]
+ submitted_at: float
+ cached_result: SelectionResult | None = None
+
+
class SelectionService:
def __init__(
self,
@@ -335,14 +344,17 @@ class SelectionService:
)
token = budget.set(request_budget)
try:
+ query_work = _QueryWork(
+ query=query,
+ keywords=tuple(keywords),
+ allowed_ids=allowed_ids,
+ submitted_at=time.perf_counter(),
+ cached_result=cached_result,
+ )
work = self.runtime.queries.submit(
self._query,
pipeline,
- query,
- keywords,
- allowed_ids,
- time.perf_counter(),
- cached_result,
+ query_work,
)
finally:
budget.reset(token)
@@ -367,16 +379,18 @@ class SelectionService:
with self._lock:
self._active_requests -= 1
- def _query(self, pipeline, query, keywords, allowed_ids, submitted_at, cached_result=None):
- queue_ms = (time.perf_counter() - submitted_at) * 1000
+ def _query(self, pipeline, work: _QueryWork):
+ queue_ms = (time.perf_counter() - work.submitted_at) * 1000
checkpoint()
- result = cached_result or pipeline.search(query, keywords, allowed_ids=allowed_ids)
+ result = work.cached_result or pipeline.search(
+ work.query, work.keywords, allowed_ids=work.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:
+ if document.id in work.allowed_ids:
document = hydrate_document(document, cache=self._catalog_cache)
candidates.append((document, score))
checkpoint()
diff --git a/jiuwenswarm/agents/harness/flash/skill_selection/startup_lifecycle.py b/jiuwenswarm/agents/harness/flash/skill_selection/startup_lifecycle.py
index 9f58046699..d813c2bb00 100644
--- a/jiuwenswarm/agents/harness/flash/skill_selection/startup_lifecycle.py
+++ b/jiuwenswarm/agents/harness/flash/skill_selection/startup_lifecycle.py
@@ -58,11 +58,11 @@ def preparing(request_id=""):
def bind_instance(instance, request_preparations):
"""Carry the actual request lease through both long-lived SDK workers."""
- if getattr(instance, "_flash_preparation_bound", False):
+ if getattr(instance, "flash_preparation_bound", False):
return
- instance._flash_preparation_bound = True
+ instance.flash_preparation_bound = True
task_preparations = {}
- instance._flash_preparation_tasks = task_preparations
+ instance.flash_preparation_tasks = task_preparations
def wrap(name, factory):
original = getattr(instance, name, None)
@@ -102,7 +102,7 @@ def bind_instance(instance, request_preparations):
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):
+ if scheduler is not None and not getattr(scheduler, "flash_preparation_bound", False):
execute = getattr(scheduler, "execute_task", None)
if callable(execute):
@wraps(execute)
@@ -111,7 +111,7 @@ def bind_instance(instance, request_preparations):
with bind(preparation):
return await execute(task_id, session, *a, **kw)
scheduler.execute_task = execute_task
- scheduler._flash_preparation_bound = True
+ scheduler.flash_preparation_bound = True
else:
logger.warning("[SkillSelection] preparation scheduler hook unavailable")
return result
@@ -132,6 +132,7 @@ def bind_instance(instance, request_preparations):
if preparation is not None:
preparation.close()
return result
- react._apply_llm_call_kwargs = before_model
+ # Keep SDK-version-specific binding dynamic, like the instance hooks above.
+ setattr(react, "_apply_llm_call_kwargs", before_model)
else:
logger.warning("[SkillSelection] preparation model boundary unavailable")
diff --git a/tests/unit_tests/agentserver/test_flash_skill_startup_lifecycle.py b/tests/unit_tests/agentserver/test_flash_skill_startup_lifecycle.py
index e78cc8c385..544227e28e 100644
--- a/tests/unit_tests/agentserver/test_flash_skill_startup_lifecycle.py
+++ b/tests/unit_tests/agentserver/test_flash_skill_startup_lifecycle.py
@@ -56,6 +56,36 @@ def test_gate_has_bounded_wait_even_under_continuous_startup():
lease.close()
+def test_concurrent_lease_close_preserves_other_active_preparation():
+ gate = execution.StartupGate()
+ lease = gate.startup()
+ other = gate.startup()
+ barrier = threading.Barrier(8)
+
+ def close_lease():
+ barrier.wait(timeout=2)
+ lease.close()
+
+ workers = [threading.Thread(target=close_lease) for _ in range(8)]
+ try:
+ for worker in workers:
+ worker.start()
+ for worker in workers:
+ worker.join(2)
+ assert not any(worker.is_alive() for worker in workers)
+ assert gate.stats()["startups"] == 1
+ other.close()
+ assert gate.stats()["startups"] == 0
+ finally:
+ barrier.abort()
+ for worker in workers:
+ if worker.ident is not None:
+ worker.join(2)
+ lease.close()
+ other.close()
+ gate.close()
+
+
def test_demand_wakes_a_build_and_releases_on_exception():
gate = execution.StartupGate(max_pause_s=5)
lease = gate.startup()
@@ -187,7 +217,7 @@ async def test_first_and_continuation_bind_actual_request_without_timing(monkeyp
requests.pop(request_id)
assert instance.observed == [("first", 1), ("model", 0),
("continuation", 1), ("model", 0)]
- assert not instance._flash_preparation_tasks
+ 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"))
@@ -210,7 +240,7 @@ async def test_failure_before_model_releases_lease_and_task_mapping(monkeypatch)
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
+ assert not instance.flash_preparation_tasks
finally:
await instance.stop()
@@ -287,7 +317,7 @@ async def test_real_sdk_reused_scheduler_releases_each_request_before_model(monk
assert outcome.error_code is None
assert gate.stats()["startups"] == 0
assert controller.task_scheduler is scheduler
- assert not agent._flash_preparation_tasks
+ assert not agent.flash_preparation_tasks
assert observed == ["first", "continuation"]
finally:
await agent._force_cleanup_controller()