Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/guides/optimization-workflow-unification.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,13 @@ profile 或测量确定瓶颈,提交包含 workload 和观测值的 UTF-8 摘
继续使用,瓶颈变化时重新运行 `diagnose`。service-reuse 的 reference epoch 改变后
需要记录新诊断。已有会话按其冻结计划继续。

每次主动查询都有独立的请求 ID。相同交付再次返回时只登记一次。Manager 在会话锁内
核对诊断 ID 和条件轮次,同一条件下重新诊断也会使先前派发的回执失效。
普通会话保留捕获文件的摘要,service-reuse 保留标明已准备交付的记录。
Python 调用者从 `inferrsi.harness.analyzer` 导入 `diagnosis_draft`,从
`inferrsi.harness.indexer` 导入 `resolve_frozen_ranking`。此前后者位于
`inferrsi.harness.optimization`。[组件接口与会话时序](../../src/inferrsi/harness/README.md#managed-session-interfaces)

### 用 profile 解释改进(可选)

端到端时间会随时钟、温度和共享负载整体漂移,单凭数值很难区分真实改进与波动。测量脚本可以在结果 JSON 中额外输出同一步骤的分区域耗时和工作量计数,单位由脚本自定并在各步骤保持一致:
Expand Down
4 changes: 2 additions & 2 deletions src/inferrsi/apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from ...knowledge.research import research_knowledge
from ..host.prepared_environment import inspect_environment
from ..legacy.reporting import write_report
from ..workflows.campaign import capture_context, create_campaign
from ..workflows.campaign import capture_context, create_campaign, prepare_context
from ..workflows.knowledge import knowledge_reader
from ..workflows.knowledge import read as read_knowledge
from .arguments import SUPPLIED, command_parser, device_ids, make_spec, parser
Expand Down Expand Up @@ -46,7 +46,7 @@ def _optimization_session(args, *, task_source=None, report_metadata=None):
"platform": args.cannbot_platform}
external_project = freeze_project(args.repo if args.project_task else None)
return session_command(
args, task_source=task_source, retain_context=capture_context,
args, task_source=task_source, prepare_context=prepare_context,
ranking_policy_for=managed_ranking_policy,
knowledge_reader=KnowledgeReader() if args.session_action == "knowledge" else None,
external_knowledge=settings, external_project=external_project,
Expand Down
46 changes: 33 additions & 13 deletions src/inferrsi/apps/workflows/campaign.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from pathlib import Path

from inferrsi import __version__
from inferrsi.harness import indexer
from inferrsi.harness.records import campaign_records, knowledge_capture
from inferrsi.knowledge._skill_selection import FIND_RELEVANCE, validate_relevance_method
from inferrsi.knowledge.catalog import BACKENDS
Expand Down Expand Up @@ -41,12 +42,27 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "",
sources: tuple[str, ...] = ("package",),
ranking_policy=None,
diagnosis_binding: dict | None = None) -> tuple[Path, str]:
"""Run ``collect`` with a context budget and keep its complete envelope.
"""Collect and retain a context for a standalone campaign capture."""
document = prepare_context(
root, context_id=context_id, reader=reader, query=query, relevance=relevance,
relevance_method=relevance_method, ids=ids, revisions=revisions, kind=kind, repo=repo,
tier=tier, backend=backend, scenario=scenario, limit=limit, context_bytes=context_bytes,
sources=sources, ranking_policy=ranking_policy, diagnosis_binding=diagnosis_binding,
)
return knowledge_capture.store_capture(root, document)

The capture is produced by the same ``collect`` operation the agent uses,
not by a caller narrative. Returns the new campaign-relative file and its
SHA-256.
"""

def prepare_context(root: Path, *, context_id: str, reader, query: str = "",
relevance: str | None = None,
relevance_method: str | None = None,
ids: list[str] | None = None, revisions: dict[str, str] | None = None,
kind: str | None = None, repo: str | None = None, tier: str | None = None,
backend: str | None = None, scenario: str | None = None,
limit: int = 5, context_bytes: int = 65536,
sources: tuple[str, ...] = ("package",),
ranking_policy=None,
diagnosis_binding: dict | None = None) -> dict:
"""Collect and project a context in memory for validation by its caller."""
if revisions and not ids:
raise ValueError("Revision pins require explicit IDs (--id-ref)")
validate_relevance_method(relevance_method)
Expand Down Expand Up @@ -76,15 +92,14 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "",
}
if ranking_policy is not None:
effective = ranking_policy.receipt()
if (observation or {}).get("selection", {}).get("ranking_policy") != effective:
raise ValueError("Delivered ranking policy differs from the frozen session")
indexer.check_returned_ranking(observation, effective)
request["ranking_policy"] = effective
if _supplies_no_observation(result):
# Such a reader gets the record this entry wrote before observations
# existed: the same fields, order and bytes, with no empty provenance.
contexts = _contexts(result)
return knowledge_capture.store_capture(
root, campaign_id=campaign["campaign_id"], context_id=context_id,
return knowledge_capture.prepare_capture(
campaign_id=campaign["campaign_id"], context_id=context_id,
# Only the source categories are kept; store and checkout paths can be private.
request={**request, "ids": ids or []},
selection=result.get("selection"),
Expand All @@ -97,8 +112,8 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "",
assembled_text=assemble_context_text(contexts),
diagnosis_binding=diagnosis_binding,
)
return save_retrieval(root, context_id=context_id, result=result, request=request,
wrapper="campaign capture-context", diagnosis_binding=diagnosis_binding)
return _prepare_retrieval(campaign, context_id, result, request,
"campaign capture-context", diagnosis_binding)


def _supplies_no_observation(result: dict) -> bool:
Expand Down Expand Up @@ -133,6 +148,11 @@ def save_retrieval(root: Path, *, context_id: str, result: dict,
hashes attest bytes, not publication permission or actual model use.
"""
campaign = knowledge_capture.capture_campaign(root, context_id)
document = _prepare_retrieval(campaign, context_id, result, request, wrapper, diagnosis_binding)
return knowledge_capture.store_capture(root, document)


def _prepare_retrieval(campaign, context_id, result, request, wrapper, diagnosis_binding):
retrieval = result.get("retrieval")
if isinstance(retrieval, dict):
retrieval = {**retrieval}
Expand All @@ -147,8 +167,8 @@ def save_retrieval(root: Path, *, context_id: str, result: dict,
"revision": view.get("revision")
or observations.get(ref, {}).get("revision")})
contexts = _contexts(result)
return knowledge_capture.store_capture(
root, campaign_id=campaign["campaign_id"], context_id=context_id,
return knowledge_capture.prepare_capture(
campaign_id=campaign["campaign_id"], context_id=context_id,
# Only the source categories are kept; store and checkout paths can be private.
request=request,
selection=result.get("selection"),
Expand Down
16 changes: 9 additions & 7 deletions src/inferrsi/harness/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,12 @@ The agent chooses a hypothesis and edits a candidate between rounds.

- **Manager** owns the session ledger, round and time budgets, pending work, recovery and final
retests. These operations currently share the [round controller](optimization.py).
- **Analyzer** validates the bottleneck and measured evidence supplied by the caller.
[Diagnosis recording](optimization.py) binds them to the session. The performance-ceiling
- **Analyzer** [validates the reported bottleneck and measurement summary](analyzer/__init__.py).
[Manager](optimization.py) records the diagnosis ID, time and condition epoch. The performance-ceiling
analysis skill lives in Knowledge.
- **Indexer** validates managed deliveries. Knowledge [ranks matches](../knowledge/knowledge_find.py)
- **Indexer** [checks managed deliveries](indexer/__init__.py) against the frozen ranking.
Apps injects the ordinary in-memory capture callback or the service context reader.
Knowledge [ranks matches](../knowledge/knowledge_find.py)
and assembles context within the requested byte budget. The capture records delivered material,
revisions and omissions. A new session can use `--ranking-policy applicability` to raise the
applicability weight from 2 to 3. The default keeps the original six weights.
Expand Down Expand Up @@ -83,15 +85,15 @@ sequenceDiagram
participant V as Evaluator
C->>M: Operation, options and dependencies
opt Register a diagnosis
M->>A: Current conditions, reported bottleneck and evidence
M->>A: Reported bottleneck and measurement evidence
A-->>M: Diagnosis draft for Manager to bind and record
end
opt Request a managed knowledge delivery
M->>I: Request ID, diagnosis ID, condition epoch and frozen ranking
I->>K: Read via the injected capture callback or service reader
K-->>I: Returned ranking, references and revisions
I-->>M: Validated delivery receipt and snapshot references
M->>M: Check request, diagnosis and epoch under the lock, then record once
K-->>I: Prepared content, observed request and ranking
I-->>M: Checked request, content and receipt
M->>M: Check ID, diagnosis and epoch under lock, retain context and register once
end
alt Recover an existing attempt
alt Ordinary session
Expand Down
20 changes: 20 additions & 0 deletions src/inferrsi/harness/analyzer/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""Validate measured bottleneck evidence supplied to a managed session."""

from pathlib import Path


def diagnosis_draft(bottleneck: str, evidence: Path) -> dict:
"""Read the caller's measurement summary before Manager records a diagnosis."""
bottleneck = bottleneck.strip()
if not bottleneck or len(bottleneck) > 4096:
raise ValueError("Bottleneck must be a nonempty description of at most 4096 characters")
if evidence.is_symlink() or not evidence.is_file():
raise ValueError("Diagnosis evidence must be a regular UTF-8 measurement summary")
with evidence.open("rb") as stream:
raw = stream.read(65537)
if len(raw) > 65536:
raise ValueError("Diagnosis evidence exceeds 64 KiB; provide a measurement summary")
summary = raw.decode("utf-8").strip()
if not summary or "\x00" in summary:
raise ValueError("Diagnosis evidence must contain a nonempty UTF-8 measurement summary")
return {"bottleneck": bottleneck, "measurement_summary": summary}
99 changes: 99 additions & 0 deletions src/inferrsi/harness/indexer/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Check the knowledge delivered for a managed request against its frozen policy."""

import hashlib

from ..records import knowledge_capture


def require_ranking_policy(recorded, effective):
if (not isinstance(recorded, dict) or not isinstance(effective, dict)
or type(recorded.get("version")) is not int
or not isinstance(recorded.get("weights"), dict)
or any(type(value) not in (int, float) for value in recorded["weights"].values())
or recorded != effective):
raise ValueError("Frozen ranking policy changed or is incomplete, use its original runtime")


def resolve_frozen_ranking(plan, ranking_policy_for, *, read_only=False):
if read_only and "ranking_policy" not in plan:
return None
recorded = plan.get("ranking_policy")
if not isinstance(recorded, dict) or not isinstance(recorded.get("id"), str):
raise ValueError("Missing frozen ranking policy, use the original runtime to resume")
if ranking_policy_for is None:
raise ValueError("A resolver for the frozen ranking policy is required")
policy = ranking_policy_for(recorded["id"])
effective = (policy.configuration() if plan.get("evaluation_mode") == "service_reuse"
else policy.receipt())
require_ranking_policy(recorded, effective)
return policy


def check_context_ranking(plan, context):
if "ranking_policy" in plan:
request = context.get("request") if isinstance(context, dict) else None
recorded = request.get("ranking_policy") if isinstance(request, dict) else None
require_ranking_policy(recorded, plan["ranking_policy"])


def check_returned_ranking(observation, effective):
selection = observation.get("selection") if isinstance(observation, dict) else None
recorded = selection.get("ranking_policy") if isinstance(selection, dict) else None
try:
require_ranking_policy(recorded, effective)
except ValueError as error:
raise ValueError("Delivered ranking policy differs from the frozen session") from error


def _check_dispatched_request(recorded, expected, lane):
if not isinstance(recorded, dict) or any(
key not in recorded or type(recorded[key]) is not type(value) or recorded[key] != value
for key, value in expected.items()
):
raise ValueError(f"{lane} knowledge receipt differs from its dispatched request")


def ordinary_delivery(root, plan, *, context_id, binding, reader, prepare_context, **request):
"""Validate the prepared capture and its underlying retrieval before Manager retains it."""
context = prepare_context(root, context_id=context_id, reader=reader,
diagnosis_binding=binding, **request)
if (not isinstance(context, dict) or context.get("context_id") != context_id
or context.get("diagnosis_binding") != binding):
raise ValueError("Knowledge capture differs from its dispatched request")
expected = {key: request[key] for key in ("query", "relevance", "scenario", "limit",
"context_bytes")}
expected["relevance_method"] = request["relevance_method"] or "find-lexical-v1"
_check_dispatched_request(context.get("request"), expected, "Ordinary")
observation = context.get("retrieval")
_check_dispatched_request(observation.get("request") if isinstance(observation, dict) else None,
expected, "Ordinary")
check_context_ranking(plan, context)
if "ranking_policy" in plan:
check_returned_ranking(observation, plan["ranking_policy"])
reference = {"path": f"knowledge/{context_id}.json",
"sha256": hashlib.sha256(knowledge_capture.capture_bytes(context)).hexdigest(),
"kind": "delivered_context"}
return {"reference": reference, "context": context}


def service_delivery(plan, *, context_id, binding, reader, query, relevance_method, limit,
context_bytes, ranking_policy):
"""Validate a fingerprint-free service receipt from the injected reader."""
Comment thread
Dong1017 marked this conversation as resolved.
Resolved
method = "find-lexical-v1" if relevance_method is None else relevance_method
context = reader.collect_service_context(
query, relevance_method=method, limit=limit, context_bytes=context_bytes,
ranking_policy=ranking_policy,
)
check_context_ranking(plan, context)
expected = {"relevance": query, "relevance_method": method, "limit": limit,
"context_bytes": context_bytes}
recorded = context.get("request") if isinstance(context, dict) else None
_check_dispatched_request(recorded, expected, "Service")
if "diagnosis_binding" in context and context["diagnosis_binding"] != binding:
raise ValueError("Knowledge capture differs from its dispatched request")
if context.get("prepared_not_consumed") is not True:
raise ValueError("Service knowledge delivery requires a prepared context")
if binding:
context = {**context, "diagnosis_binding": binding}
return {"reference": {"path": f"knowledge/{context_id}.json", "kind": "delivered_context",
"prepared_not_consumed": True}, "context": context}
Loading
Loading