From c89623c0df9d89fbc9b4e71d1fd9efead2a6dc2d Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:32:43 +0800 Subject: [PATCH 1/8] Read authorized groups of atoms at their pinned revisions Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- .gitattributes | 2 + src/inferrsi/knowledge/atomic_reader.py | 174 +++++++++++++++ .../atomic-reader/roofline-example.json | 72 +++++++ tests/fixtures/atomic-reader/rule.md | 17 ++ tests/fixtures/atomic-reader/steps.md | 24 +++ tests/knowledge/test_atomic_reader.py | 201 ++++++++++++++++++ 6 files changed, 490 insertions(+) create mode 100644 src/inferrsi/knowledge/atomic_reader.py create mode 100644 tests/fixtures/atomic-reader/roofline-example.json create mode 100644 tests/fixtures/atomic-reader/rule.md create mode 100644 tests/fixtures/atomic-reader/steps.md create mode 100644 tests/knowledge/test_atomic_reader.py diff --git a/.gitattributes b/.gitattributes index 7b797e8c4..8ccba34df 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,6 +4,8 @@ # Preserve recorded evidence and historical validator bytes across checkouts. /evidence/** -text /tests/fixtures/legacy/** -text +# The frozen atom ranges include their terminating paragraph separators. +/tests/fixtures/atomic-reader/** -text whitespace=-blank-at-eof # A session started by an older runtime keeps its exact bytes; its plan pins file hashes. /tests/fixtures/optimization-session/pre-infra-removal-session/** -text /tests/fixtures/optimization-session/pre-trials-rename-session/** -text diff --git a/src/inferrsi/knowledge/atomic_reader.py b/src/inferrsi/knowledge/atomic_reader.py new file mode 100644 index 000000000..192ec2d18 --- /dev/null +++ b/src/inferrsi/knowledge/atomic_reader.py @@ -0,0 +1,174 @@ +"""Read a required group of pinned atoms from one authorized Knowledge source view.""" + +from __future__ import annotations + +import hashlib +import re +from collections.abc import Callable, Iterable, Mapping +from dataclasses import dataclass +from typing import Protocol + +from .knowledge_operations import ( + AUTHORITIES, + IDENTITY, + Bundle, + IdentityError, + UnavailableRevision, + safe_path, +) + +_DIGEST = re.compile(r"[0-9a-f]{64}") +_OPERATIONS = frozenset({"read", "retain", "redistribute"}) + + +@dataclass(frozen=True) +class AtomPin: + ref: str + revision: str + + def __post_init__(self) -> None: + if not isinstance(self.ref, str) or not isinstance(self.revision, str): + raise ValueError("Atom reference and revision must be strings") + authority, _, identity = self.ref.partition(":") + if authority not in AUTHORITIES or not re.fullmatch(IDENTITY, identity): + raise ValueError("A pinned atom needs an authority-qualified reference") + if not re.fullmatch(r"sha256:[0-9a-f]{64}", self.revision): + raise ValueError("A pinned atom needs a complete Bundle revision") + + +@dataclass(frozen=True) +class AtomUse: + """One path through a composition to the requested atom.""" + + pin: AtomPin + path: tuple[str, ...] + + def __post_init__(self) -> None: + if (not isinstance(self.path, tuple) or not self.path + or not all(isinstance(step, str) and step for step in self.path)): + raise ValueError("A dependency path must name each step") + + +class PinnedSource(Protocol): + def read_resolved(self, reference: str, *, revision: str) -> tuple[str, Bundle]: ... + + +@dataclass(frozen=True) +class GroupDelivery: + """Bodies and their corresponding public receipt records in delivery order.""" + + bodies: tuple[bytes, ...] + receipt: dict + + +def _refused(reason: str, *, required_bytes: int | None = None) -> GroupDelivery: + receipt = {"status": reason, "body_bytes": 0, "delivered": []} + if required_bytes is not None: + receipt["required_bytes"] = required_bytes + return GroupDelivery((), receipt) + + +def applies(when: Mapping[str, list[str]], context: Mapping[str, str]) -> bool: + """All named dimensions must match one of their explicitly allowed values.""" + if not isinstance(when, Mapping) or any( + not isinstance(key, str) or not key or not isinstance(values, list) or not values + or not all(isinstance(value, str) and value for value in values) + for key, values in when.items() + ): + raise ValueError("Conditions must map dimensions to nonempty lists of values") + return all(context.get(key) in values for key, values in when.items()) + + +def _provenance(view: dict, atom: dict, body: bytes) -> dict: + span = atom["source_span"] + index = span["source_index"] + if type(index) is not int or not 0 <= index < len(view["sources"]): + raise ValueError("Atom source_span must select a declared source") + source = view["sources"][index] + commit = source.get("commit") + snapshot = source.get("sha256") + if not ( + (isinstance(commit, str) and re.fullmatch(r"[0-9a-f]{40}", commit)) + or (isinstance(snapshot, str) and _DIGEST.fullmatch(snapshot)) + ): + raise ValueError("An atom needs an immutable source snapshot") + start, end = span["byte_range"] + if type(start) is not int or type(end) is not int or start < 0 or end - start != len(body): + raise ValueError("Source range must cover the exact bytes of the atom") + digest = hashlib.sha256(body).hexdigest() + if span["sha256"] != digest or view["resources"][view["entrypoint"]] != digest: + raise ValueError("Atom does not match the declared source digest") + if atom["layer"] not in ("L0", "L1", "L2", "L3"): + raise ValueError("Invalid atom disclosure layer") + return { + "layer": atom["layer"], "source": dict(source), "source_path": safe_path(span["path"]), + "source_byte_range": [start, end], "source_sha256": span["sha256"], + "sha256": digest, "bytes": len(body), + } + + +class AtomicReader: + """The caller supplies a snapshot reader and grants for the current project.""" + + def __init__(self, source: PinnedSource, *, permits: Callable[[AtomPin, str], bool]): + self.source = source + self.permits = permits + + def read_group( + self, uses: Iterable[AtomUse], *, max_bytes: int, context: Mapping[str, str], + operations: Iterable[str] = (), + ) -> GroupDelivery: + """Resolve and authorize every required path before releasing any body.""" + if type(max_bytes) is not int or max_bytes < 0: + raise ValueError("Body budget must be a nonnegative integer") + actions = {"read", *operations} + if not actions <= _OPERATIONS: + raise ValueError("Unknown atom operation") + paths: dict[AtomPin, list[list[str]]] = {} + for use in uses: + via = list(use.path) + seen = paths.setdefault(use.pin, []) + if via not in seen: + seen.append(via) + if not paths: + return _refused("not_applicable") + if any(not self.permits(pin, action) for pin in paths for action in actions): + return _refused("permission_denied") + + bodies, delivered = [], [] + for pin, via_paths in paths.items(): + try: + qualified, bundle = self.source.read_resolved(pin.ref, revision=pin.revision) + except UnavailableRevision: + return _refused("unavailable_revision") + except IdentityError as exc: + if exc.code != "unknown_identity": + raise + return _refused("unavailable_revision") + if qualified != pin.ref or bundle.metadata.get("id") != pin.ref.partition(":")[2]: + return _refused("unavailable_revision") + view = bundle.view() + if view["revision"] != pin.revision: + return _refused("unavailable_revision") + atom = view["atom"] + if not all(atom["permissions"].get(action) is True for action in actions): + return _refused("permission_denied") + license_id = atom.get("license") + if "redistribute" in actions and ( + not isinstance(license_id, str) + or license_id.strip().lower() in {"", "unknown", "none", "noassertion"} + ): + return _refused("permission_denied") + if not applies(atom["when"], context): + return _refused("not_applicable") + body = bundle.content[view["entrypoint"]] + record = _provenance(view, atom, body) + bodies.append(body) + delivered.append({"ref": pin.ref, "revision": pin.revision, + "paths": via_paths, **record}) + + total = sum(map(len, bodies)) + if total > max_bytes: + return _refused("over_budget", required_bytes=total) + return GroupDelivery(tuple(bodies), {"status": "delivered", "body_bytes": total, + "delivered": delivered}) diff --git a/tests/fixtures/atomic-reader/roofline-example.json b/tests/fixtures/atomic-reader/roofline-example.json new file mode 100644 index 000000000..de06fdbdf --- /dev/null +++ b/tests/fixtures/atomic-reader/roofline-example.json @@ -0,0 +1,72 @@ +{ + "workload": { + "workload_id": "synthetic-component-v1", + "shape": "one synthetic matrix operation", + "boundary": "one invocation; stated compute and HBM traffic only", + "hardware_id": "synthetic-reference", + "resource_scope": "logical-device-0", + "operation": { + "dtype": "bfloat16", + "accumulator_dtype": "float32", + "op_class": "matrix", + "sparsity": "dense", + "fma_flops": 2 + }, + "work": { + "value": 600, + "unit": "FLOP", + "source": { + "kind": "synthetic", + "locator": "fixture:roofline-example", + "revision": "v1", + "time_unknown_reason": "Undated synthetic arithmetic fixture" + } + }, + "traffic": { + "value": 100, + "unit": "byte", + "tier": "HBM", + "source": { + "kind": "synthetic", + "locator": "fixture:roofline-example", + "revision": "v1", + "time_unknown_reason": "Undated synthetic arithmetic fixture" + } + }, + "assumptions": ["Counts are synthetic and apply only to this stated invocation."] + }, + "hardware": { + "hardware_id": "synthetic-reference", + "resource_scope": "logical-device-0", + "device_count": 1, + "operation": { + "dtype": "bfloat16", + "accumulator_dtype": "float32", + "op_class": "matrix", + "sparsity": "dense", + "fma_flops": 2 + }, + "peak_compute": { + "value": 100, + "unit": "FLOP/s", + "source": { + "kind": "synthetic", + "locator": "fixture:roofline-example", + "revision": "v1", + "time_unknown_reason": "Undated synthetic arithmetic fixture" + } + }, + "bandwidth": { + "value": 10, + "unit": "byte/s", + "tier": "HBM", + "source": { + "kind": "synthetic", + "locator": "fixture:roofline-example", + "revision": "v1", + "time_unknown_reason": "Undated synthetic arithmetic fixture" + } + }, + "assumptions": ["Rates are synthetic references, not measured or rated device facts."] + } +} diff --git a/tests/fixtures/atomic-reader/rule.md b/tests/fixtures/atomic-reader/rule.md new file mode 100644 index 000000000..efd07fbe9 --- /dev/null +++ b/tests/fixtures/atomic-reader/rule.md @@ -0,0 +1,17 @@ +## When to use this skill + +Use this skill before modifying an inference serving system when you need to +answer: *does meaningful headroom exist, where is it, and is a requested +speedup such as 2× plausible?* + +When preparing a task, preserve user-provided acceptance criteria. If none were +supplied, follow [acceptance-criteria preparation](references/acceptance-criteria.md) +to derive and freeze targets from this analysis. Preserve partial requirements, +label derived fields and retain evidence gaps; a theoretical ceiling alone does +not establish an attainable target or a quality tolerance. + +Do not use it to benchmark or compare two already-built candidates — that is +the job of InferRSI's AB/BA harness and `rsi-evidence` skill. + +For whole-model prefill and decode composition, use [model-sol-analysis](../model-sol-analysis/SKILL.md). + diff --git a/tests/fixtures/atomic-reader/steps.md b/tests/fixtures/atomic-reader/steps.md new file mode 100644 index 000000000..22a65fc75 --- /dev/null +++ b/tests/fixtures/atomic-reader/steps.md @@ -0,0 +1,24 @@ +## Select the source + +1. Read the user's request and any referenced acceptance issue or frozen plan. + **Use supplied criteria unchanged:** retain metrics, units, timing boundaries, + statistics, workload coverage, thresholds and quality/resource constraints. + An estimate may flag an infeasible target but must not replace or relax it. + Conflicting requests and frozen records need resolution by their authorized + owner; do not choose whichever target is easier to pass. +2. If criteria are absent, use [performance-ceiling-analysis](../SKILL.md) to + formulate workload-specific acceptance criteria before candidate search. + Retain partial requirements: derive only missing performance targets and + measurement details, labelling each derived field separately. An unspecified + primary objective that cannot be resolved from task context is a missing + input, not permission to optimize a different objective. +3. Reuse the target's existing correctness/quality contract and retain baseline + semantics. Hardware ceilings cannot determine quality tolerances, an + application SLO or permission to change precision, steps or useful work. + Resolve missing quality requirements from the task and reference validators; + if still unknown, record the gap rather than invent a tolerance. + +Do not add a confirmation round when the user has already delegated goal +formulation and campaign preparation. Use the existing freeze authority; record +agent-derived targets as such, never as user-supplied or user-confirmed numbers. + diff --git a/tests/knowledge/test_atomic_reader.py b/tests/knowledge/test_atomic_reader.py new file mode 100644 index 000000000..4aa0f98f9 --- /dev/null +++ b/tests/knowledge/test_atomic_reader.py @@ -0,0 +1,201 @@ +import hashlib +from pathlib import Path + +import pytest + +from inferrsi.knowledge.atomic_reader import AtomicReader, AtomPin, AtomUse +from inferrsi.knowledge.knowledge_operations import Bundle, UnavailableRevision +from inferrsi.knowledge.knowledge_store import KnowledgeStore + +# Exact UTF-8 byte ranges in the v0.3.4 release, frozen in #713. +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "atomic-reader" +UPSTREAM = ( + "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/" +) +RELEASE = "e2f3be102c66c358803ed2186ed67bf627ebcbdf" +EXCERPTS = { + "L1": ( + "rule.md", "SKILL.md", 10266, 11111, + "b4e6bdffe5cf990a6be96b6ae8d1b442cf61b47f63bcd8949aae6650ab538089", + ), + "L2": ( + "steps.md", "references/acceptance-criteria.md", 252, 1790, + "b1c9caafde8ac6912a5e4678bd11212a68016fb685a633970c69ad4977d9134a", + ), + "L3": ( + "roofline-example.json", "references/roofline-example.json", 0, 2015, + "597cd3205df043cff3ae9d15924c77934e8d8eb300c00c4840f6bb2921f90faf", + ), +} + + +def excerpt(layer): + filename, path, start, end, digest = EXCERPTS[layer] + return Bundle( + { + "id": "ceiling-" + layer.lower(), "kind": "knowledge", "entrypoint": filename, + "state": "candidate", "applicability": {}, "limitations": [], + "sources": [{ + "type": "git", "url": "https://github.com/InferMatrixLab/InferRSI", + "commit": RELEASE, + }], + "attribution": "InferMatrixLab/InferRSI", + "atom": { + "layer": layer, "license": "Apache-2.0", "when": {}, + "permissions": {"read": True, "retain": True, "redistribute": True}, + "source_span": { + "source_index": 0, "path": UPSTREAM + path, + "byte_range": [start, end], "sha256": digest, + }, + }, + }, + {filename: (FIXTURES / filename).read_bytes()}, {}, + ) + + +class Snapshots: + def __init__(self): + self.items = {} + self.reads = [] + + def add(self, bundle, authority="package"): + pin = AtomPin(f"{authority}:{bundle.metadata['id']}", bundle.revision) + self.items[pin] = (pin.ref, bundle) + return pin + + def read_resolved(self, reference, *, revision): + pin = AtomPin(reference, revision) + self.reads.append(pin) + if pin not in self.items: + raise UnavailableRevision(reference) + return self.items[pin] + + +def allow(pin, operation): + return True + + +def test_required_paths_share_bytes_and_receipts_reopen_the_exact_version(): + source = Snapshots() + rule, steps = (source.add(excerpt(level)) for level in ("L1", "L2")) + uses = [AtomUse(rule, ("rule",)), AtomUse(rule, ("prerequisite", "rule")), + AtomUse(steps, ("steps",))] + reader = AtomicReader(source, permits=allow) + result = reader.read_group(uses, max_bytes=2383, context={}) + assert result.receipt["status"] == "delivered" + assert result.receipt["body_bytes"] == sum(map(len, result.bodies)) == 2383 + assert source.reads == [rule, steps] + records = result.receipt["delivered"] + assert [record["paths"] for record in records] == [ + [["rule"], ["prerequisite", "rule"]], [["steps"]], + ] + for (pin, level), record, body in zip([(rule, "L1"), (steps, "L2")], records, result.bodies): + filename, path, start, end, digest = EXCERPTS[level] + assert record["ref"] == pin.ref and record["revision"] == pin.revision + assert record["layer"] == level and record["bytes"] == end - start + assert record["source"]["commit"] == RELEASE and record["source_path"] == UPSTREAM + path + assert record["source_byte_range"] == [start, end] + assert record["source_sha256"] == record["sha256"] == hashlib.sha256(body).hexdigest() + assert record["sha256"] == digest + _, pinned = source.read_resolved(record["ref"], revision=record["revision"]) + assert body == pinned.content[filename] == (FIXTURES / filename).read_bytes() + short = reader.read_group(uses, max_bytes=2382, context={}) + assert short.bodies == () + assert short.receipt == { + "status": "over_budget", "body_bytes": 0, "delivered": [], "required_bytes": 2383, + } + + +@pytest.mark.parametrize("level,size", [("L2", 1538), ("L3", 2015)]) +def test_layer_budget_counts_the_last_byte(level, size): + source = Snapshots() + uses = [AtomUse(source.add(excerpt(level)), ("direct",))] + reader = AtomicReader(source, permits=allow) + complete = reader.read_group(uses, max_bytes=size, context={}) + assert complete.receipt["body_bytes"] == len(complete.bodies[0]) == size + short = reader.read_group(uses, max_bytes=size - 1, context={}) + assert short.receipt["status"] == "over_budget" and short.bodies == () + + +def test_authorities_cannot_lend_each_other_bytes_revisions_or_grants(): + source = Snapshots() + original = excerpt("L1") + first = source.add(original, "package") + second = source.add(original, "checkout") + uses = [AtomUse(pin, ("rule",)) for pin in (first, second)] + reader = AtomicReader(source, permits=allow) + result = reader.read_group(uses, max_bytes=1690, context={}) + assert [r["ref"] for r in result.receipt["delivered"]] == [first.ref, second.ref] + assert len(result.bodies) == 2 and result.receipt["body_bytes"] == 1690 + source.reads.clear() + denied = AtomicReader(source, permits=lambda pin, op: pin == first) + result = denied.read_group(uses, max_bytes=1690, context={}) + assert source.reads == [] + assert result.bodies == () and result.receipt == { + "status": "permission_denied", "delivered": [], "body_bytes": 0, + } + del source.items[second] + updated = excerpt("L1") + updated.metadata["limitations"] = ["Fixture revision B"] + source.add(updated, "checkout") + result = reader.read_group(uses, max_bytes=1690, context={}) + assert result.bodies == () and result.receipt == { + "status": "unavailable_revision", "delivered": [], "body_bytes": 0, + } + + +def test_operation_rights_and_conditions_apply_before_any_body_is_delivered(): + source = Snapshots() + steps = excerpt("L2") + steps.metadata["atom"].update( + permissions={"read": True, "retain": False, "redistribute": True}, + license="NOASSERTION", when={"engine": ["v0.4", "v0.5"], "backend": ["gpu"]}, + ) + uses = [AtomUse(source.add(excerpt("L1")), ("rule",)), AtomUse(source.add(steps), ("steps",))] + reader = AtomicReader(source, permits=allow) + matching = {"engine": "v0.5", "backend": "gpu"} + result = reader.read_group(uses, max_bytes=2383, context=matching) + assert result.receipt["status"] == "delivered" + for operation in ("retain", "redistribute"): + result = reader.read_group(uses, max_bytes=2383, context=matching, operations=[operation]) + assert result.bodies == () and result.receipt["status"] == "permission_denied" + for context in ({}, {"engine": "v0.4"}, {**matching, "engine": "v0"}): + result = reader.read_group(uses, max_bytes=2383, context=context) + assert result.bodies == () and result.receipt["status"] == "not_applicable" + + +@pytest.mark.parametrize("change", ["digest", "range", "locator", "unstable", "condition"]) +def test_invalid_source_declaration_cannot_mint_a_receipt(change): + source = Snapshots() + bundle = excerpt("L2") + atom = bundle.metadata["atom"] + if change == "digest": + atom["source_span"]["sha256"] = "0" * 64 + elif change == "range": + atom["source_span"]["byte_range"][1] += 1 + elif change == "locator": + atom["source_span"]["path"] = "../outside.md" + elif change == "unstable": + bundle.metadata["sources"][0]["commit"] = RELEASE[:7] + else: + atom["when"] = {"engine": "v0.5"} + pin = source.add(bundle) + with pytest.raises(ValueError): + AtomicReader(source, permits=allow).read_group( + [AtomUse(pin, ("steps",))], max_bytes=1538, context={"engine": "v0"}, + ) + + +def test_existing_knowledge_store_can_reopen_old_atom_after_metadata_update(tmp_path): + store = KnowledgeStore(tmp_path, skill_root=None) + old = excerpt("L2") + pin = AtomPin("store:" + old.metadata["id"], store.create(old)) + latest = excerpt("L2") + latest.metadata["limitations"] = ["For the matching engine only"] + assert store.update(latest, expected=pin.revision, reason="Clarify bounds", evidence=[]) != ( + pin.revision + ) + reader = AtomicReader(store.reader(), permits=allow) + result = reader.read_group([AtomUse(pin, ("historical",))], max_bytes=1538, context={}) + assert result.bodies == (old.content["steps.md"],) + assert result.receipt["delivered"][0]["revision"] == pin.revision From 44124d0b520e5c1eca5acf207a8d23ed30d14d47 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:43:45 +0800 Subject: [PATCH 2/8] Match pinned atom applicability against numeric release bounds Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/knowledge/atomic_reader.py | 54 ++++++++++++++++++++----- tests/knowledge/test_atomic_reader.py | 44 +++++++++++++++++++- 2 files changed, 86 insertions(+), 12 deletions(-) diff --git a/src/inferrsi/knowledge/atomic_reader.py b/src/inferrsi/knowledge/atomic_reader.py index 192ec2d18..f99047f2e 100644 --- a/src/inferrsi/knowledge/atomic_reader.py +++ b/src/inferrsi/knowledge/atomic_reader.py @@ -68,15 +68,45 @@ def _refused(reason: str, *, required_bytes: int | None = None) -> GroupDelivery return GroupDelivery((), receipt) -def applies(when: Mapping[str, list[str]], context: Mapping[str, str]) -> bool: - """All named dimensions must match one of their explicitly allowed values.""" - if not isinstance(when, Mapping) or any( - not isinstance(key, str) or not key or not isinstance(values, list) or not values - or not all(isinstance(value, str) and value for value in values) - for key, values in when.items() - ): - raise ValueError("Conditions must map dimensions to nonempty lists of values") - return all(context.get(key) in values for key, values in when.items()) +def _release_number(value: object) -> tuple[int, ...] | None: + if not isinstance(value, str) or not re.fullmatch(r"v?[0-9]+(?:\.[0-9]+)*", value): + return None + parts = [int(part) for part in value.removeprefix("v").split(".")] + while parts and parts[-1] == 0: + parts.pop() + return tuple(parts) + + +def _matches(condition: object, actual: str | None) -> bool: + if isinstance(condition, list): + if not condition or not all(isinstance(value, str) and value for value in condition): + raise ValueError("An exact-match condition requires nonempty strings") + return actual in condition + if not isinstance(condition, Mapping) or not condition or condition.keys() - {"min", "before"}: + raise ValueError("Expected an allowlist or a release range with min and/or before") + lower = _release_number(condition.get("min")) + upper = _release_number(condition.get("before")) + if ("min" in condition and lower is None) or ("before" in condition and upper is None): + raise ValueError("Release bounds must be dotted numeric release strings") + if lower is not None and upper is not None and lower >= upper: + raise ValueError("Release range must contain at least one release") + release = _release_number(actual) + return (release is not None and (lower is None or lower <= release) + and (upper is None or release < upper)) + + +def applies(when: Mapping[str, object], context: Mapping[str, str]) -> bool: + """Match every dimension: exact allowlists or [min, before) dotted release ranges.""" + if not isinstance(when, Mapping): + raise ValueError("Conditions must map named dimensions to constraints") + matches = True + for key, condition in when.items(): + if not isinstance(key, str) or not key: + raise ValueError("Conditions must name a dimension") + # Validate later declarations even if an earlier dimension did not match. + if not _matches(condition, context.get(key)): + matches = False + return matches def _provenance(view: dict, atom: dict, body: bytes) -> dict: @@ -138,15 +168,17 @@ def read_group( bodies, delivered = [], [] for pin, via_paths in paths.items(): try: - qualified, bundle = self.source.read_resolved(pin.ref, revision=pin.revision) + qualified, held = self.source.read_resolved(pin.ref, revision=pin.revision) except UnavailableRevision: return _refused("unavailable_revision") except IdentityError as exc: if exc.code != "unknown_identity": raise return _refused("unavailable_revision") - if qualified != pin.ref or bundle.metadata.get("id") != pin.ref.partition(":")[2]: + if qualified != pin.ref or held.metadata.get("id") != pin.ref.partition(":")[2]: return _refused("unavailable_revision") + # Bind the receipt and bytes to one snapshot of the mutable source mappings. + bundle = Bundle(held.metadata, dict(held.content), dict(held.dependencies)) view = bundle.view() if view["revision"] != pin.revision: return _refused("unavailable_revision") diff --git a/tests/knowledge/test_atomic_reader.py b/tests/knowledge/test_atomic_reader.py index 4aa0f98f9..9322fec14 100644 --- a/tests/knowledge/test_atomic_reader.py +++ b/tests/knowledge/test_atomic_reader.py @@ -3,7 +3,7 @@ import pytest -from inferrsi.knowledge.atomic_reader import AtomicReader, AtomPin, AtomUse +from inferrsi.knowledge.atomic_reader import AtomicReader, AtomPin, AtomUse, applies from inferrsi.knowledge.knowledge_operations import Bundle, UnavailableRevision from inferrsi.knowledge.knowledge_store import KnowledgeStore @@ -199,3 +199,45 @@ def test_existing_knowledge_store_can_reopen_old_atom_after_metadata_update(tmp_ result = reader.read_group([AtomUse(pin, ("historical",))], max_bytes=1538, context={}) assert result.bodies == (old.content["steps.md"],) assert result.receipt["delivered"][0]["revision"] == pin.revision + + +def test_release_bounds_route_only_matching_numeric_versions_and_keep_exact_names(): + source = Snapshots() + steps = excerpt("L2") + steps.metadata["atom"]["when"] = { + "engine": {"min": "v0.5", "before": "1.0"}, "backend": ["gpu"], + } + uses = [AtomUse(source.add(steps), ("release-steps",))] + reader = AtomicReader(source, permits=allow) + for version in ("0.5", "v0.5.0", "v0.10", "0.99.2"): + context = {"engine": version, "backend": "gpu"} + result = reader.read_group(uses, max_bytes=1538, context=context) + assert result.bodies == (steps.content["steps.md"],) + for version in ("0.4.99", "1", "v1.0.0", "nightly", "v0.5rc1"): + context = {"engine": version, "backend": "gpu"} + result = reader.read_group(uses, max_bytes=1538, context=context) + assert result.bodies == () and result.receipt["status"] == "not_applicable" + assert applies({"engine": {"min": "0.0"}}, {"engine": "v0"}) + assert applies({"engine": {"before": "0.5"}}, {"engine": "v0.4"}) + assert not applies({"engine": {"before": "0.5"}}, {}) + assert applies({"engine": ["v0.5rc1", "nightly"]}, {"engine": "nightly"}) + + +@pytest.mark.parametrize("condition", [ + {}, {"min": "nightly"}, {"before": None}, {"min": 0.5}, + {"min": "0.5", "before": "0.5.0"}, {"min": "0.10", "before": "0.5"}, + {"unknown": "0.5"}, [], +]) +def test_invalid_release_range_is_reported_even_after_an_unmatched_condition(condition): + with pytest.raises(ValueError): + applies({"backend": ["gpu"], "engine": condition}, {}) + + +def test_receipt_retains_its_pinned_provenance_when_source_metadata_is_edited(): + source = Snapshots() + rule = excerpt("L1") + rule.metadata["sources"][0]["upstream_refs"] = ["release"] + uses = [AtomUse(source.add(rule), ("rule",))] + result = AtomicReader(source, permits=allow).read_group(uses, max_bytes=845, context={}) + rule.metadata["sources"][0]["upstream_refs"].append("latest") + assert result.receipt["delivered"][0]["source"]["upstream_refs"] == ["release"] From 7c991e84f208476070764e7b7b12b69634ed4091 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:23:09 +0800 Subject: [PATCH 3/8] Resolve pinned composition routes and retain verified finding deliveries Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/apps/workflows/campaign.py | 17 +- src/inferrsi/apps/workflows/knowledge.py | 6 + src/inferrsi/harness/optimization.py | 45 ++- .../harness/records/atomic_capture.py | 108 +++++++ .../harness/records/knowledge_capture.py | 14 +- src/inferrsi/knowledge/atomic_composition.py | 188 ++++++++++++ src/inferrsi/knowledge/atomic_reader.py | 281 ++++++++++-------- src/inferrsi/knowledge/context_projection.py | 3 +- src/inferrsi/knowledge/decision_cards.py | 6 +- tests/apps/test_optimization_session.py | 124 ++++++++ tests/fixtures/atomic_composition.py | 76 +++++ tests/knowledge/test_atomic_composition.py | 91 ++++++ 12 files changed, 814 insertions(+), 145 deletions(-) create mode 100644 src/inferrsi/harness/records/atomic_capture.py create mode 100644 src/inferrsi/knowledge/atomic_composition.py create mode 100644 tests/fixtures/atomic_composition.py create mode 100644 tests/knowledge/test_atomic_composition.py diff --git a/src/inferrsi/apps/workflows/campaign.py b/src/inferrsi/apps/workflows/campaign.py index 3340eca2d..52dd2cd38 100644 --- a/src/inferrsi/apps/workflows/campaign.py +++ b/src/inferrsi/apps/workflows/campaign.py @@ -11,8 +11,10 @@ from pathlib import Path from inferrsi import __version__ -from inferrsi.harness.records import campaign_records, knowledge_capture +from inferrsi.harness import optimization +from inferrsi.harness.records import atomic_capture, campaign_records, knowledge_capture from inferrsi.knowledge._skill_selection import FIND_RELEVANCE, validate_relevance_method +from inferrsi.knowledge.atomic_reader import AtomicReader, PinnedSource from inferrsi.knowledge.catalog import BACKENDS from inferrsi.knowledge.context_projection import ( PROVENANCE_FIELDS, @@ -31,6 +33,14 @@ def create_campaign(root: Path, campaign_id: str, *, target: float | None = None ) +def capture_selection(root: Path, source: PinnedSource, reference: str, *, + permits, **request) -> dict: + """Supply the same Reader as an ordinary read to the managed campaign.""" + return optimization.capture_selection(root, AtomicReader(source, permits=permits), + reference=reference, assemble_text=assemble_context_text, + **request) + + def capture_context(root: Path, *, context_id: str, reader, query: str = "", relevance: str | None = None, relevance_method: str | None = None, @@ -177,6 +187,11 @@ def verify_capture(raw: bytes) -> tuple[dict | None, str]: document, state = knowledge_capture.verify_capture(raw) if document is None: return None, state + if document["request"].get("mode") == "pinned_selection": + try: + atomic_capture.verify_stored(document) + except (KeyError, TypeError, ValueError, AttributeError): + return None, "atomic_receipt_mismatch" if assemble_context_text(document["contexts"]) != document["assembled_text"]: return None, "assembly_mismatch" return document, "verified" diff --git a/src/inferrsi/apps/workflows/knowledge.py b/src/inferrsi/apps/workflows/knowledge.py index f6adedd1b..c5936af81 100644 --- a/src/inferrsi/apps/workflows/knowledge.py +++ b/src/inferrsi/apps/workflows/knowledge.py @@ -2,6 +2,7 @@ from pathlib import Path +from inferrsi.knowledge.atomic_reader import AtomicReader, GroupDelivery, PinnedSource from inferrsi.knowledge.knowledge_operations import KnowledgeReader, safe_path from inferrsi.knowledge.knowledge_store import KnowledgeStore @@ -40,3 +41,8 @@ def read( raise ValueError(f"Unknown resource: {path}") view.update(content=bundle.content[path].decode("utf-8"), content_resource=path) return qualified, view["revision"], view + + +def read_selection(source: PinnedSource, reference: str, *, permits, **request) -> GroupDelivery: + """Ordinary Apps read of a fixed composition using this project's grants.""" + return AtomicReader(source, permits=permits).read_selection(reference, **request) diff --git a/src/inferrsi/harness/optimization.py b/src/inferrsi/harness/optimization.py index 00611e55d..059a280ba 100644 --- a/src/inferrsi/harness/optimization.py +++ b/src/inferrsi/harness/optimization.py @@ -11,6 +11,7 @@ from . import attempt_recovery, candidates from .artifact_primitives import digest, file_lock, sha256 from .atomic_json import atomic_write_json, durable_write_json +from .records import atomic_capture from .records.evidence import bounded_record_bytes, sanitized_text from .records.knowledge_capture import MAX_CONTEXT_CAPTURE_BYTES from .task_protocol import TaskProtocolError @@ -442,6 +443,37 @@ def _store_knowledge(root, kind, number, record): "kind": kind, "round": number} +def _register_context(root, state, number, binding, path, fingerprint, *, selected=False): + reference = {"path": path.relative_to(root).as_posix(), "sha256": fingerprint, + "kind": "delivered_context"} + document = _read_context(root, reference) + if selected and document["selection"]["status"] != "delivered": + reference["kind"] = "knowledge_refusal" + retained = {**reference, "round": number} if number is not None else dict(reference) + if binding: + retained["diagnosis_id"] = binding["diagnosis_id"] + state["contexts"].append(retained) + return {"reference": reference, "context": document} + + +def capture_selection(root: Path, reader, *, assemble_text, **request) -> dict: + """Retain an explicit pin in a managed optimization campaign with its current diagnosis.""" + with _locked(root): + plan, state = _load(root) + if plan.get("evaluation_mode") == "service_reuse": + raise ValueError("Service-reuse sessions require their fingerprint-free capture format") + number = _knowledge_round(plan, state) + binding = _context_diagnosis(plan, state) + path, fingerprint = atomic_capture.retain_selection( + root, reader=reader, context_id="context-" + uuid.uuid4().hex, + diagnosis_binding=binding, ranking_policy=plan.get("ranking_policy"), + assemble_text=assemble_text, **request, + ) + response = _register_context(root, state, number, binding, path, fingerprint, selected=True) + atomic_write_json(root / "state.json", state) + return response + + def capture_context(root: Path, reader, *, retain_context, external_provider=None, external_provider_for=None, **request) -> dict: with _locked(root): @@ -457,14 +489,7 @@ def capture_context(root: Path, reader, *, retain_context, external_provider=Non binding = _context_diagnosis(plan, state) path, fingerprint = retain_context(root, context_id="context-" + uuid.uuid4().hex, reader=reader, diagnosis_binding=binding, **request) - reference = {"path": path.relative_to(root).as_posix(), "sha256": fingerprint, - "kind": "delivered_context"} - # Keep the local tool response compatible with stored Codex trace verification. - retained = {**reference, "round": number} if number is not None else reference - if binding: - retained = {**retained, "diagnosis_id": binding["diagnosis_id"]} - state["contexts"].append(retained) - response = {"reference": reference, "context": _read_context(root, reference)} + response = _register_context(root, state, number, binding, path, fingerprint) if settings: remaining = _knowledge_time(plan, state) if remaining > 0: @@ -474,7 +499,7 @@ def capture_context(root: Path, reader, *, retain_context, external_provider=Non limit=request["limit"], timeout=remaining) else: result = {"state": "timeout", "items": [], "count": 0} - search = {**result, **settings, "context_ref": reference["path"]} + search = {**result, **settings, "context_ref": response["reference"]["path"]} search_ref = _store_knowledge(root, "external_search", number, search) state["contexts"].append(search_ref) response["external"] = {**search, "reference": search_ref} @@ -524,7 +549,7 @@ def _validate_knowledge_refs(root, contexts, refs): if len(set(refs)) != len(refs): raise ValueError("Cite unique delivered knowledge references") delivered = {entry["path"]: entry for entry in contexts - if entry["kind"] != "external_search"} + if entry["kind"] not in ("external_search", "knowledge_refusal")} for ref in refs: path, separator, item = ref.partition("#") reference = delivered.get(path) diff --git a/src/inferrsi/harness/records/atomic_capture.py b/src/inferrsi/harness/records/atomic_capture.py new file mode 100644 index 000000000..81c5f1497 --- /dev/null +++ b/src/inferrsi/harness/records/atomic_capture.py @@ -0,0 +1,108 @@ +"""Verify bytes returned by an injected Reader and retain the selected delivery or refusal.""" + +from __future__ import annotations + +import base64 +import hashlib +from pathlib import Path + +from inferrsi import __version__ + +from . import knowledge_capture + +_REFUSALS = {"over_budget", "unavailable_revision", "permission_denied", + "not_applicable", "conflict"} + + +def _verify_receipt(receipt, bodies, request): + selection = receipt["selection"] + if any(selection[key] != request[key] for key in ("ref", "revision", "layer", "finding")): + raise ValueError("Reader receipt belongs to a different selection") + records = receipt["delivered"] + if not isinstance(records, list) or len(records) != len(bodies): + raise ValueError("Reader receipt must enumerate exactly the delivered bodies") + status = receipt["status"] + if status == "delivered": + if not records: + raise ValueError("Successful delivery requires at least one atom") + elif status not in _REFUSALS or records: + raise ValueError("Invalid Reader refusal or nonempty refused delivery") + seen = set() + for body, record in zip(bodies, records): + pin = (record["ref"], record["revision"]) + if pin in seen: + raise ValueError("An atom may occur only once in a delivery") + seen.add(pin) + if not isinstance(body, bytes): + raise ValueError("The Reader must supply the original bytes") + digest = hashlib.sha256(body).hexdigest() + if (record["sha256"] != digest or record["source_sha256"] != digest + or type(record["bytes"]) is not int or record["bytes"] != len(body)): + raise ValueError("Delivered bytes differ from the Reader receipt") + span = record["source_byte_range"] + if (not isinstance(span, list) or len(span) != 2 + or not all(type(offset) is int for offset in span) + or span[0] < 0 or span[1] - span[0] != len(body)): + raise ValueError("Source range differs from the delivered bytes") + total = sum(map(len, bodies)) + if (type(receipt["body_bytes"]) is not int or receipt["body_bytes"] != total + or total > request["max_bytes"]): + raise ValueError("Invalid delivered byte count or budget") + + +def _resource(body, record): + resource = {"path": record["source_path"], "sha256": record["sha256"]} + try: + resource["content"] = body.decode("utf-8") + except UnicodeDecodeError: + resource.update(content=base64.b64encode(body).decode("ascii"), content_encoding="base64") + return resource + + +def verify_stored(document): + """Check a retained atomic receipt against the resources a caller can actually recover.""" + request, receipt = document["request"], document["selection"] + records, contexts = receipt["delivered"], document["contexts"] + if len(records) != len(contexts) or len(records) != len(document["items"]): + raise ValueError("Atomic capture does not match the delivered atom count") + bodies = [] + for record, context, item in zip(records, contexts, document["items"]): + identity = {"ref": record["ref"], "revision": record["revision"]} + if item != identity or any(context[key] != value for key, value in identity.items()): + raise ValueError("Retained atom does not match its receipt") + resource, = context["resources"] + if resource["path"] != record["source_path"] or resource["sha256"] != record["sha256"]: + raise ValueError("Retained resource differs from its receipt") + bodies.append(knowledge_capture.resource_bytes(resource)) + _verify_receipt(receipt, bodies, request) + if (document["context_bytes_used"] != receipt["body_bytes"] + or document["context_budget"] != request["max_bytes"]): + raise ValueError("Atomic capture accounting differs from its request") + + +def retain_selection(root: Path, *, reader, context_id, reference, revision, layer, max_bytes, + context, assemble_text, finding=None, diagnosis_binding=None, + ranking_policy=None): + campaign = knowledge_capture.capture_campaign(root, context_id) + request = {"mode": "pinned_selection", "ref": reference, "revision": revision, "layer": layer, + "finding": finding, "max_bytes": max_bytes, "context": dict(context), + "operations": ["read", "retain"]} + if ranking_policy is not None: + # Session provenance. This operation reopens an explicit pin without ranking it again. + request["ranking_policy"] = ranking_policy + delivery = reader.read_selection(reference, revision=revision, layer=layer, finding=finding, + max_bytes=max_bytes, context=context, operations=("retain",)) + receipt, bodies = delivery.receipt, delivery.bodies + _verify_receipt(receipt, bodies, request) + items = [{"ref": record["ref"], "revision": record["revision"]} + for record in receipt["delivered"]] + contexts = [{**item, "resources": [_resource(body, record)], "omissions": []} + for item, body, record in zip(items, bodies, receipt["delivered"])] + return knowledge_capture.store_capture( + root, campaign_id=campaign["campaign_id"], context_id=context_id, request=request, + selection=receipt, items=items, omissions=receipt.get("omissions", []), + context_omissions=[], + context_budget=max_bytes, context_bytes_used=receipt["body_bytes"], contexts=contexts, + assembled_text=assemble_text(contexts), diagnosis_binding=diagnosis_binding, + captured_by=f"inferrsi pinned knowledge read {__version__}", + ) diff --git a/src/inferrsi/harness/records/knowledge_capture.py b/src/inferrsi/harness/records/knowledge_capture.py index caabd9d54..8ea7feefa 100644 --- a/src/inferrsi/harness/records/knowledge_capture.py +++ b/src/inferrsi/harness/records/knowledge_capture.py @@ -11,6 +11,7 @@ from __future__ import annotations +import base64 import hashlib import json import os @@ -102,6 +103,15 @@ def store_capture(root: Path, *, campaign_id: str, context_id: str, request: dic return target, hashlib.sha256(payload).hexdigest() +def resource_bytes(resource: dict) -> bytes: + encoding = resource.get("content_encoding", "utf-8") + if encoding == "utf-8": + return resource["content"].encode("utf-8") + if encoding == "base64": + return base64.b64decode(resource["content"], validate=True) + raise ValueError("Unknown captured resource encoding") + + def verify_capture(raw: bytes) -> tuple[dict | None, str]: """Check the stored bytes of a capture. @@ -140,7 +150,7 @@ def verify_capture(raw: bytes) -> tuple[dict | None, str]: if not all(isinstance(resource.get(key), str) for key in ("path", "sha256", "content")): return None, "invalid_format" - actual = hashlib.sha256(resource["content"].encode("utf-8")).hexdigest() + actual = hashlib.sha256(resource_bytes(resource)).hexdigest() if resource["sha256"].lower() != actual: return None, "resource_hash_mismatch" for omission in context["omissions"]: @@ -156,7 +166,7 @@ def verify_capture(raw: bytes) -> tuple[dict | None, str]: labels += [omission["path"], omission["reason"]] for label in labels: label.encode("utf-8") - except (KeyError, TypeError, AttributeError, UnicodeError): + except (KeyError, TypeError, AttributeError, ValueError): return None, "invalid_format" try: digest = hashlib.sha256(document["assembled_text"].encode("utf-8")).hexdigest() diff --git a/src/inferrsi/knowledge/atomic_composition.py b/src/inferrsi/knowledge/atomic_composition.py new file mode 100644 index 000000000..b9317fa39 --- /dev/null +++ b/src/inferrsi/knowledge/atomic_composition.py @@ -0,0 +1,188 @@ +"""Resolve the authored branches and dependency paths of one pinned composition.""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from dataclasses import dataclass + +from .decision_cards import DecisionSource, UnknownFinding +from .knowledge_operations import AUTHORITIES, IDENTITY + +LAYERS = ("L0", "L1", "L2", "L3") + + +@dataclass(frozen=True) +class AtomPin: + ref: str + revision: str + + def __post_init__(self) -> None: + if not isinstance(self.ref, str) or not isinstance(self.revision, str): + raise ValueError("Atom reference and revision must be strings") + authority, _, identity = self.ref.partition(":") + if authority not in AUTHORITIES or not re.fullmatch(IDENTITY, identity): + raise ValueError("A pinned atom needs an authority-qualified reference") + if not re.fullmatch(r"sha256:[0-9a-f]{64}", self.revision): + raise ValueError("A pinned atom needs a complete Bundle revision") + + +@dataclass(frozen=True) +class AtomUse: + """One path through a composition to the requested atom.""" + + pin: AtomPin + path: tuple[str, ...] + + def __post_init__(self) -> None: + if (not isinstance(self.path, tuple) or not self.path + or not all(isinstance(step, str) and step for step in self.path)): + raise ValueError("A dependency path must name each step") + + +def _release_number(value: object) -> tuple[int, ...] | None: + if not isinstance(value, str) or not re.fullmatch(r"v?[0-9]+(?:\.[0-9]+)*", value): + return None + parts = [int(part) for part in value.removeprefix("v").split(".")] + while parts and parts[-1] == 0: + parts.pop() + return tuple(parts) + + +def _matches(condition: object, actual: str | None) -> bool: + if isinstance(condition, list): + if not condition or not all(isinstance(value, str) and value for value in condition): + raise ValueError("An exact-match condition requires nonempty strings") + return actual in condition + if not isinstance(condition, Mapping) or not condition or condition.keys() - {"min", "before"}: + raise ValueError("Expected an allowlist or a release range with min and/or before") + lower = _release_number(condition.get("min")) + upper = _release_number(condition.get("before")) + if ("min" in condition and lower is None) or ("before" in condition and upper is None): + raise ValueError("Release bounds must be dotted numeric release strings") + if lower is not None and upper is not None and lower >= upper: + raise ValueError("Release range must contain at least one release") + release = _release_number(actual) + return (release is not None and (lower is None or lower <= release) + and (upper is None or release < upper)) + + +def applies(when: Mapping[str, object], context: Mapping[str, str]) -> bool: + """Match every dimension: exact allowlists or [min, before) dotted release ranges.""" + if not isinstance(when, Mapping): + raise ValueError("Conditions must map named dimensions to constraints") + matches = True + for key, condition in when.items(): + if not isinstance(key, str) or not key: + raise ValueError("Conditions must name a dimension") + # Validate later declarations even if an earlier dimension did not match. + if not _matches(condition, context.get(key)): + matches = False + return matches + + +@dataclass(frozen=True) +class RouteSelection: + required: tuple[AtomUse, ...] = () + optional: tuple[tuple[AtomUse, ...], ...] = () + routes: tuple[str, ...] = () + finding: str | None = None + refusal: str | None = None + + +def _names(values: object, targets: Mapping, field: str) -> tuple[str, ...]: + if not isinstance(values, list) or not all(isinstance(name, str) and name in targets + for name in values): + raise ValueError(f"{field} must list names declared in the composition") + if len(set(values)) != len(values): + raise ValueError(f"Duplicate name in {field}") + return tuple(values) + + +def _acyclic(edges: dict[str, tuple[str, ...]], relation: str) -> None: + visited = set() + active = set() + + def visit(name): + if name in active: + raise ValueError(f"Cycle in composition {relation} at {name}") + if name not in visited: + active.add(name) + for other in edges[name]: + visit(other) + active.remove(name) + visited.add(name) + + for name in edges: + visit(name) + + +def select_routes(composition: dict, *, layer: str, context: Mapping[str, str], + case: DecisionSource | None, finding: str | None) -> RouteSelection: + """Select one disclosure layer and expand applicable routes in authored dependency order.""" + if layer not in LAYERS: + raise ValueError("Select one of L0, L1, L2 and L3") + selected_finding = None + if finding is not None: + if not isinstance(finding, str) or case is None: + return RouteSelection(refusal="not_applicable") + try: + selected_finding = case.finding_locator(case.finding(finding)[0]) + except UnknownFinding: + return RouteSelection(refusal="not_applicable") + elif case is not None and layer == "L1": + return RouteSelection(refusal="not_applicable") + + nodes, routes = composition["nodes"], composition["routes"] + if not all(isinstance(group, dict) and group and all( + isinstance(key, str) and key and isinstance(value, dict) for key, value in group.items() + ) for group in (nodes, routes)): + raise ValueError("A composition must declare named nodes and routes") + pins = {name: AtomPin(node["ref"], node["revision"]) for name, node in nodes.items()} + requires = {name: _names(node.get("requires", []), nodes, "requires") + for name, node in nodes.items()} + _acyclic(requires, "requires") + supersedes = {} + conflicts = {} + required = {} + optional = {} + matches = set() + for name, route in routes.items(): + if route["layer"] not in LAYERS: + raise ValueError(f"Invalid disclosure layer for route {name}") + required[name] = _names(route["required"], nodes, "required") + optional[name] = _names(route.get("optional", []), nodes, "optional") + if not required[name] or set(required[name]).intersection(optional[name]): + raise ValueError(f"Route {name} needs distinct required and optional roots") + supersedes[name] = _names(route.get("supersedes", []), routes, "supersedes") + conflicts[name] = _names(route.get("conflicts", []), routes, "conflicts") + if name in conflicts[name]: + raise ValueError(f"Route {name} conflicts with itself") + selector = route.get("finding") + if selector is not None: + if case is None or not isinstance(selector, str): + raise ValueError("Only a Case route may declare a finding selector") + selector = case.finding_locator(case.finding(selector)[0]) + applicable = applies(route.get("when", {}), context) + if applicable and layer == route["layer"] and selector == selected_finding: + matches.add(name) + _acyclic(supersedes, "supersedes") + # A newer declaration can retire another only inside their common applicable scope. + chosen = matches.difference(other for name in matches for other in supersedes[name]) + if not chosen: + return RouteSelection(finding=selected_finding, refusal="not_applicable") + if any(chosen.intersection(conflicts[name]) for name in chosen): + return RouteSelection(finding=selected_finding, refusal="conflict") + + def expand(node, path): + via = (*path, node) + for child in requires[node]: + yield from expand(child, via) + yield AtomUse(pins[node], via) + + ordered = tuple(sorted(chosen)) + return RouteSelection( + tuple(use for name in ordered for node in required[name] for use in expand(node, (name,))), + tuple(tuple(expand(node, (name,))) for name in ordered for node in optional[name]), + ordered, selected_finding, + ) diff --git a/src/inferrsi/knowledge/atomic_reader.py b/src/inferrsi/knowledge/atomic_reader.py index f99047f2e..8cbda3594 100644 --- a/src/inferrsi/knowledge/atomic_reader.py +++ b/src/inferrsi/knowledge/atomic_reader.py @@ -8,9 +8,9 @@ from dataclasses import dataclass from typing import Protocol +from .atomic_composition import LAYERS, AtomPin, AtomUse, applies, select_routes +from .decision_cards import DecisionSource from .knowledge_operations import ( - AUTHORITIES, - IDENTITY, Bundle, IdentityError, UnavailableRevision, @@ -21,34 +21,6 @@ _OPERATIONS = frozenset({"read", "retain", "redistribute"}) -@dataclass(frozen=True) -class AtomPin: - ref: str - revision: str - - def __post_init__(self) -> None: - if not isinstance(self.ref, str) or not isinstance(self.revision, str): - raise ValueError("Atom reference and revision must be strings") - authority, _, identity = self.ref.partition(":") - if authority not in AUTHORITIES or not re.fullmatch(IDENTITY, identity): - raise ValueError("A pinned atom needs an authority-qualified reference") - if not re.fullmatch(r"sha256:[0-9a-f]{64}", self.revision): - raise ValueError("A pinned atom needs a complete Bundle revision") - - -@dataclass(frozen=True) -class AtomUse: - """One path through a composition to the requested atom.""" - - pin: AtomPin - path: tuple[str, ...] - - def __post_init__(self) -> None: - if (not isinstance(self.path, tuple) or not self.path - or not all(isinstance(step, str) and step for step in self.path)): - raise ValueError("A dependency path must name each step") - - class PinnedSource(Protocol): def read_resolved(self, reference: str, *, revision: str) -> tuple[str, Bundle]: ... @@ -68,48 +40,45 @@ def _refused(reason: str, *, required_bytes: int | None = None) -> GroupDelivery return GroupDelivery((), receipt) -def _release_number(value: object) -> tuple[int, ...] | None: - if not isinstance(value, str) or not re.fullmatch(r"v?[0-9]+(?:\.[0-9]+)*", value): - return None - parts = [int(part) for part in value.removeprefix("v").split(".")] - while parts and parts[-1] == 0: - parts.pop() - return tuple(parts) - - -def _matches(condition: object, actual: str | None) -> bool: - if isinstance(condition, list): - if not condition or not all(isinstance(value, str) and value for value in condition): - raise ValueError("An exact-match condition requires nonempty strings") - return actual in condition - if not isinstance(condition, Mapping) or not condition or condition.keys() - {"min", "before"}: - raise ValueError("Expected an allowlist or a release range with min and/or before") - lower = _release_number(condition.get("min")) - upper = _release_number(condition.get("before")) - if ("min" in condition and lower is None) or ("before" in condition and upper is None): - raise ValueError("Release bounds must be dotted numeric release strings") - if lower is not None and upper is not None and lower >= upper: - raise ValueError("Release range must contain at least one release") - release = _release_number(actual) - return (release is not None and (lower is None or lower <= release) - and (upper is None or release < upper)) - - -def applies(when: Mapping[str, object], context: Mapping[str, str]) -> bool: - """Match every dimension: exact allowlists or [min, before) dotted release ranges.""" - if not isinstance(when, Mapping): - raise ValueError("Conditions must map named dimensions to constraints") - matches = True - for key, condition in when.items(): - if not isinstance(key, str) or not key: - raise ValueError("Conditions must name a dimension") - # Validate later declarations even if an earlier dimension did not match. - if not _matches(condition, context.get(key)): - matches = False - return matches - - -def _provenance(view: dict, atom: dict, body: bytes) -> dict: +def _selected(delivery: GroupDelivery, request: dict) -> GroupDelivery: + return GroupDelivery(delivery.bodies, {**delivery.receipt, "selection": request}) + + +def _actions(max_bytes: int, operations: Iterable[str]) -> set[str]: + if type(max_bytes) is not int or max_bytes < 0: + raise ValueError("Body budget must be a nonnegative integer") + actions = {"read", *operations} + if not actions <= _OPERATIONS: + raise ValueError("Unknown atom operation") + return actions + + +def permits_operations(declaration: dict, actions: set[str]) -> bool: + """Check each declared grant and the explicit license required for redistribution.""" + if not all(declaration["permissions"].get(action) is True for action in actions): + return False + license_id = declaration.get("license") + if "redistribute" in actions and (not isinstance(license_id, str) or + license_id.strip().lower() in {"", "unknown", "none", "noassertion"}): + return False + return True + + +def _restriction(declaration: dict, actions: set[str], context: Mapping[str, str]) -> str | None: + if not permits_operations(declaration, actions): + return "permission_denied" + if not applies(declaration["when"], context): + return "not_applicable" + return None + + +def atom_material(bundle: Bundle, view: dict) -> tuple[bytes, dict]: + """Recover and verify the authored byte span, including a binary attachment.""" + atom = view["atom"] + resource = safe_path(atom.get("resource", view["entrypoint"])) + if resource not in bundle.content: + raise ValueError("Atom resource is missing from the pinned Bundle") + body = bundle.content[resource] span = atom["source_span"] index = span["source_index"] if type(index) is not int or not 0 <= index < len(view["sources"]): @@ -126,11 +95,12 @@ def _provenance(view: dict, atom: dict, body: bytes) -> dict: if type(start) is not int or type(end) is not int or start < 0 or end - start != len(body): raise ValueError("Source range must cover the exact bytes of the atom") digest = hashlib.sha256(body).hexdigest() - if span["sha256"] != digest or view["resources"][view["entrypoint"]] != digest: + if span["sha256"] != digest or view["resources"][resource] != digest: raise ValueError("Atom does not match the declared source digest") - if atom["layer"] not in ("L0", "L1", "L2", "L3"): + if atom["layer"] not in LAYERS: raise ValueError("Invalid atom disclosure layer") - return { + return body, { + "resource": resource, "layer": atom["layer"], "source": dict(source), "source_path": safe_path(span["path"]), "source_byte_range": [start, end], "source_sha256": span["sha256"], "sha256": digest, "bytes": len(body), @@ -144,63 +114,114 @@ def __init__(self, source: PinnedSource, *, permits: Callable[[AtomPin, str], bo self.source = source self.permits = permits + def _snapshot(self, pin: AtomPin) -> tuple[Bundle, dict] | None: + try: + qualified, held = self.source.read_resolved(pin.ref, revision=pin.revision) + except UnavailableRevision: + return None + except IdentityError as exc: + if exc.code != "unknown_identity": + raise + return None + if qualified != pin.ref or held.metadata.get("id") != pin.ref.partition(":")[2]: + return None + # Bind metadata, digest and delivered bytes to the same source snapshot. + bundle = Bundle(held.metadata, dict(held.content), dict(held.dependencies)) + view = bundle.view() + return (bundle, view) if view["revision"] == pin.revision else None + + def _materialize(self, required, optional, *, max_bytes, context, actions) -> GroupDelivery: + cached: dict[AtomPin, tuple[bytes, dict]] = {} + paths: dict[AtomPin, list[list[str]]] = {} + omissions = [] + used_bytes = 0 + + def include(group: Iterable[AtomUse]) -> GroupDelivery | None: + nonlocal used_bytes + proposed: dict[AtomPin, list[list[str]]] = {} + for use in group: + via = list(use.path) + if via not in proposed.setdefault(use.pin, []): + proposed[use.pin].append(via) + if not proposed: + return _refused("not_applicable") + if any(not self.permits(pin, op) for pin in proposed for op in actions): + return _refused("permission_denied") + for pin in proposed: + if pin in cached: + continue + snapshot = self._snapshot(pin) + if snapshot is None: + return _refused("unavailable_revision") + bundle, view = snapshot + atom = view.get("atom") + if not isinstance(atom, dict): + raise ValueError("A composition node must reference an atom") + reason = _restriction(atom, actions, context) + if reason: + return _refused(reason) + cached[pin] = atom_material(bundle, view) + total = used_bytes + sum(len(cached[pin][0]) for pin in proposed if pin not in paths) + if total > max_bytes: + return _refused("over_budget", required_bytes=total) + for pin, vias in proposed.items(): + seen = paths.setdefault(pin, []) + seen.extend(via for via in vias if via not in seen) + used_bytes = total + return None + + refusal = include(required) + if refusal is not None: + return refusal + for group in optional: + refusal = include(group) + if refusal is not None: + omissions.append({"path": list(group[-1].path), + "reason": refusal.receipt["status"]}) + records = [{"ref": pin.ref, "revision": pin.revision, "paths": via, **cached[pin][1]} + for pin, via in paths.items()] + receipt = {"status": "delivered", "body_bytes": used_bytes, "delivered": records} + if omissions: + receipt["omissions"] = omissions + return GroupDelivery(tuple(cached[pin][0] for pin in paths), receipt) + def read_group( self, uses: Iterable[AtomUse], *, max_bytes: int, context: Mapping[str, str], operations: Iterable[str] = (), ) -> GroupDelivery: """Resolve and authorize every required path before releasing any body.""" - if type(max_bytes) is not int or max_bytes < 0: - raise ValueError("Body budget must be a nonnegative integer") - actions = {"read", *operations} - if not actions <= _OPERATIONS: - raise ValueError("Unknown atom operation") - paths: dict[AtomPin, list[list[str]]] = {} - for use in uses: - via = list(use.path) - seen = paths.setdefault(use.pin, []) - if via not in seen: - seen.append(via) - if not paths: - return _refused("not_applicable") - if any(not self.permits(pin, action) for pin in paths for action in actions): - return _refused("permission_denied") - - bodies, delivered = [], [] - for pin, via_paths in paths.items(): - try: - qualified, held = self.source.read_resolved(pin.ref, revision=pin.revision) - except UnavailableRevision: - return _refused("unavailable_revision") - except IdentityError as exc: - if exc.code != "unknown_identity": - raise - return _refused("unavailable_revision") - if qualified != pin.ref or held.metadata.get("id") != pin.ref.partition(":")[2]: - return _refused("unavailable_revision") - # Bind the receipt and bytes to one snapshot of the mutable source mappings. - bundle = Bundle(held.metadata, dict(held.content), dict(held.dependencies)) - view = bundle.view() - if view["revision"] != pin.revision: - return _refused("unavailable_revision") - atom = view["atom"] - if not all(atom["permissions"].get(action) is True for action in actions): - return _refused("permission_denied") - license_id = atom.get("license") - if "redistribute" in actions and ( - not isinstance(license_id, str) - or license_id.strip().lower() in {"", "unknown", "none", "noassertion"} - ): - return _refused("permission_denied") - if not applies(atom["when"], context): - return _refused("not_applicable") - body = bundle.content[view["entrypoint"]] - record = _provenance(view, atom, body) - bodies.append(body) - delivered.append({"ref": pin.ref, "revision": pin.revision, - "paths": via_paths, **record}) - - total = sum(map(len, bodies)) - if total > max_bytes: - return _refused("over_budget", required_bytes=total) - return GroupDelivery(tuple(bodies), {"status": "delivered", "body_bytes": total, - "delivered": delivered}) + return self._materialize(uses, (), max_bytes=max_bytes, context=context, + actions=_actions(max_bytes, operations)) + + def read_selection( + self, reference: str, *, revision: str, layer: str, max_bytes: int, + context: Mapping[str, str], finding: str | None = None, operations: Iterable[str] = (), + ) -> GroupDelivery: + """Read one pinned composition by layer and, for a Case, one original finding.""" + pin = AtomPin(reference, revision) + actions = _actions(max_bytes, operations) + if layer not in LAYERS: + raise ValueError("Select one of L0, L1, L2 and L3") + requested = {"ref": reference, "revision": revision, "layer": layer, "finding": finding} + if not all(self.permits(pin, action) for action in actions): + return _selected(_refused("permission_denied"), requested) + snapshot = self._snapshot(pin) + if snapshot is None: + return _selected(_refused("unavailable_revision"), requested) + bundle, view = snapshot + composition = view.get("composition") + if not isinstance(composition, dict): + raise ValueError("Expected a pinned composition") + reason = _restriction(composition, actions, context) + if reason: + return _selected(_refused(reason), requested) + case = None + if view["kind"] == "case": + case = DecisionSource.from_bundle(reference, bundle, view) + plan = select_routes(composition, layer=layer, context=context, case=case, finding=finding) + if plan.refusal: + return _selected(_refused(plan.refusal), requested) + delivery = self._materialize(plan.required, plan.optional, max_bytes=max_bytes, + context=context, actions=actions) + return _selected(delivery, {**requested, "canonical_finding": plan.finding, + "routes": list(plan.routes)}) diff --git a/src/inferrsi/knowledge/context_projection.py b/src/inferrsi/knowledge/context_projection.py index 0c5660bce..63a5aa8bc 100644 --- a/src/inferrsi/knowledge/context_projection.py +++ b/src/inferrsi/knowledge/context_projection.py @@ -12,9 +12,10 @@ def assemble_context_text(contexts: list[dict]) -> str: for context in contexts: for resource in context["resources"]: content = resource["content"] + encoding = " [base64]" if resource.get("content_encoding") == "base64" else "" lines.append( f"--- begin context {context['ref']} @ {context['revision']} " - f"{resource['path']} ---\n" + f"{resource['path']}{encoding} ---\n" ) lines.append(content if content.endswith("\n") else content + "\n") lines.append(f"--- end context {resource['path']} ---\n") diff --git a/src/inferrsi/knowledge/decision_cards.py b/src/inferrsi/knowledge/decision_cards.py index 69c513ea7..fe435d00f 100644 --- a/src/inferrsi/knowledge/decision_cards.py +++ b/src/inferrsi/knowledge/decision_cards.py @@ -38,6 +38,10 @@ def project_decision_card( ) +class UnknownFinding(ValueError): + """The requested selector does not identify one finding in this revision.""" + + @dataclass(frozen=True) class DecisionSource: ref: str @@ -110,7 +114,7 @@ def finding(self, selector: str) -> tuple[int, dict]: match = re.fullmatch(r"case\.json#/findings/(0|[1-9][0-9]*)", selector) if match and (index := int(match[1])) < len(findings): return index, findings[index] - raise ValueError(f"Unknown or ambiguous finding at {self.revision}: {selector}") + raise UnknownFinding(f"Unknown or ambiguous finding at {self.revision}: {selector}") def project( self, *, finding: str | None = None, max_bytes: int | None = None, compact: bool = False, diff --git a/tests/apps/test_optimization_session.py b/tests/apps/test_optimization_session.py index 30557fdae..d1886dbf4 100644 --- a/tests/apps/test_optimization_session.py +++ b/tests/apps/test_optimization_session.py @@ -1709,3 +1709,127 @@ def scoreless(*args, **kwargs): assert assessment["status"] == "infrastructure_failure" and assessment["score"] is None assert "finite positive score" in assessment["reason"] assert view["best"]["kind"] == "baseline" + + +def test_pinned_case_finding_matches_ordinary_read_and_registers_only_returned_bytes( + session, capsys, tmp_path, +): + from inferrsi.apps.workflows import campaign, knowledge + from inferrsi.harness.records.knowledge_capture import resource_bytes + from inferrsi.knowledge.knowledge_store import KnowledgeStore + from tests.fixtures.atomic_composition import case_fixture + + store_root = tmp_path / "atomic-store" + store_root.mkdir() + store = KnowledgeStore(store_root, skill_root=None) + pin, expected = case_fixture(store) + reader = store.reader() + + def permits(pin, op): + return op in ("read", "retain") + + for index, selector in ((0, "id:target"), (1, "case.json#/findings/1")): + assert main(["read", pin.ref, "--store", str(store_root), "--layer", "L1", + "--revision", pin.revision, "--finding", selector]) == 0 + old_card = json.loads(capsys.readouterr().out)["card"] + assert old_card["atom"]["selector"] == selector + for layer in ("L0", "L1", "L2", "L3"): + atom_pin, body = expected[index, layer] + request = dict(revision=pin.revision, layer=layer, max_bytes=len(body), + context={}, finding=f"case.json#/findings/{index}") + ordinary = knowledge.read_selection(reader, pin.ref, permits=permits, **request) + assert ordinary.bodies == (body,) + result = campaign.capture_selection(session, reader, pin.ref, permits=permits, + **request) + record, reference = result["context"], result["reference"] + assert reference["kind"] == "delivered_context" + assert record["diagnosis_binding"]["diagnosis_id"] + assert record["selection"] == ordinary.receipt + assert record["selection"]["selection"]["canonical_finding"] == selector + assert record["items"] == [{"ref": atom_pin.ref, "revision": atom_pin.revision}] + resource, = record["contexts"][0]["resources"] + assert resource_bytes(resource) == body + if layer == "L1": + assert json.loads(body) == old_card["declared"]["finding"] + if layer == "L3": + assert resource["content_encoding"] == "base64" + assert record["context_bytes_used"] == len(body) + raw = (session / reference["path"]).read_bytes() + assert hashlib.sha256(raw).hexdigest() == reference["sha256"] + assert campaign.verify_capture(raw) == (record, "verified") + record["selection"]["delivered"][0]["ref"] = "store:sibling" + assert campaign.verify_capture(json.dumps(record).encode())[1] == ( + "atomic_receipt_mismatch" + ) + state = json.loads((session / "state.json").read_text(encoding="utf-8")) + assert len(state["contexts"]) == 8 + optimization.status(session) + + +def test_required_selection_refusals_remain_uncitable_in_the_running_session(session, tmp_path): + from inferrsi.apps.workflows import campaign, knowledge + from inferrsi.knowledge.knowledge_store import KnowledgeStore + from tests.fixtures.atomic_composition import case_fixture + + store = KnowledgeStore(tmp_path, skill_root=None) + pin, expected = case_fixture(store) + atom, body = expected[0, "L1"] + for reason in ("over_budget", "permission_denied", "unavailable_revision", "not_applicable"): + request = dict(revision="sha256:" + "0" * 64 if reason == "unavailable_revision" + else pin.revision, layer="L1", context={}, + max_bytes=len(body) - (reason == "over_budget"), + finding="id:missing" if reason == "not_applicable" else "id:target") + + def permits(selected, op): + return reason != "permission_denied" or selected != atom or op != "retain" + + if reason == "permission_denied": + ordinary = knowledge.read_selection(store.reader(), pin.ref, permits=permits, **request) + assert ordinary.bodies == (body,) + result = campaign.capture_selection(session, store.reader(), pin.ref, permits=permits, + **request) + record, ref = result["context"], result["reference"] + assert ref["kind"] == "knowledge_refusal" + assert record["selection"]["status"] == reason + assert record["selection"]["delivered"] == record["contexts"] == record["items"] == [] + assert record["context_bytes_used"] == 0 and record["assembled_text"] == "" + state = json.loads((session / "state.json").read_text(encoding="utf-8")) + assert state["contexts"][-1]["path"] == ref["path"] + with pytest.raises(ValueError, match="Cite a delivered context"): + optimization._validate_knowledge_refs(session, state["contexts"], [ref["path"]]) + optimization.status(session) + + +@pytest.mark.parametrize("damage", ["bytes", "selection", "count", "span"]) +def test_managed_reader_rejects_mismatched_receipt_before_writing(tmp_path, damage): + from types import SimpleNamespace + + from inferrsi.harness.records.atomic_capture import retain_selection + from inferrsi.knowledge.atomic_reader import AtomicReader, GroupDelivery + from inferrsi.knowledge.knowledge_store import KnowledgeStore + from tests.fixtures.atomic_composition import case_fixture + + store = KnowledgeStore(tmp_path, skill_root=None) + pin, _ = case_fixture(store) + reader = AtomicReader(store.reader(), permits=lambda pin, op: True) + request = dict(revision=pin.revision, layer="L1", finding="id:target", + max_bytes=1024, context={}) + valid = reader.read_selection(pin.ref, **request) + receipt = valid.receipt + if damage == "bytes": + receipt["delivered"][0]["sha256"] = "0" * 64 + elif damage == "selection": + receipt["selection"]["revision"] = "sha256:" + "0" * 64 + elif damage == "span": + receipt["delivered"][0]["source_byte_range"][1] += 1 + else: + receipt["delivered"].clear() + root = tmp_path / "managed" + root.mkdir() + (root / "campaign.json").write_text('{"campaign_id":"test"}', encoding="utf-8") + forged = SimpleNamespace(read_selection=lambda *args, **kwargs: + GroupDelivery(valid.bodies, receipt)) + with pytest.raises(ValueError): + retain_selection(root, reader=forged, context_id="example", reference=pin.ref, + assemble_text=lambda contexts: "", **request) + assert [p.name for p in root.iterdir()] == ["campaign.json"] diff --git a/tests/fixtures/atomic_composition.py b/tests/fixtures/atomic_composition.py new file mode 100644 index 000000000..cff715184 --- /dev/null +++ b/tests/fixtures/atomic_composition.py @@ -0,0 +1,76 @@ +"""Pinned input for ordinary and managed Reader contract tests.""" + +import hashlib +import json + +from inferrsi.knowledge.atomic_reader import AtomPin +from inferrsi.knowledge.knowledge_operations import Bundle + + +def metadata(identity, kind, entrypoint, source): + return {"id": identity, "kind": kind, "entrypoint": entrypoint, "state": "candidate", + "applicability": {}, "limitations": [], "sources": [source], + "attribution": "Synthetic Reader contract fixture"} + + +def composition(nodes, routes, *, findings=None): + path = "case.json" if findings is not None else "navigation.json" + data = json.dumps({"findings": findings} if findings is not None else {}, + ensure_ascii=False).encode() + source = {"type": "fixture", "sha256": hashlib.sha256(data).hexdigest()} + kind = "case" if findings is not None else "skill" + fields = metadata("selection-fixture", kind, path, source) + fields["composition"] = { + "nodes": nodes, "routes": routes, "when": {}, "license": "Apache-2.0", + "permissions": {"read": True, "retain": True, "redistribute": True}, + } + return Bundle(fields, {path: data}, {}) + + +def node(pin, *requires): + return {"ref": pin.ref, "revision": pin.revision, "requires": list(requires)} + + +def case_fixture(store): + findings = [ + {"id": "target", "reason": "范围 A", "outcome": "one"}, + {"reason": "sibling scope B", "outcome": "two"}, + ] + document = json.dumps({"findings": findings}, ensure_ascii=False).encode() + attachment = bytes([0xff, 0, 0xef, 0x7f]) + nodes, routes, expected = {}, {}, {} + for index, finding in enumerate(findings): + key = f"finding-{index}" + for layer in ("L0", "L1", "L2", "L3"): + name = key + "-" + layer.lower() + if layer == "L3": + path = f"assets/{key}.bin" + body = attachment + bytes([index]) + source, start = body, 0 + else: + # A byte span from the original JSON, pinned before content projection. + path = "case.json" + body = json.dumps(finding, ensure_ascii=False).encode() + source = document + start = source.index(body) + digest = hashlib.sha256(body).hexdigest() + fields = metadata(name, "knowledge", "body", + {"type": "fixture", "sha256": hashlib.sha256(source).hexdigest()}) + fields["atom"] = { + "layer": layer, "when": {}, "license": "Apache-2.0", + "permissions": {"read": True, "retain": True, "redistribute": True}, + "source_span": {"source_index": 0, "path": path, "sha256": digest, + "byte_range": [start, start + len(body)]}, + } + content = {"body": body} + if layer == "L3": + fields["atom"]["resource"] = path + content = {"body": b"Attachment", path: body} + pin = AtomPin(f"store:{name}", store.create(Bundle(fields, content, {}))) + nodes[name] = node(pin) + routes[name] = {"layer": layer, "required": [name], + "finding": f"case.json#/findings/{index}"} + expected[index, layer] = (pin, body) + bundle = composition(nodes, routes, findings=findings) + pin = AtomPin("store:" + bundle.metadata["id"], store.create(bundle)) + return pin, expected diff --git a/tests/knowledge/test_atomic_composition.py b/tests/knowledge/test_atomic_composition.py new file mode 100644 index 000000000..5d99355fb --- /dev/null +++ b/tests/knowledge/test_atomic_composition.py @@ -0,0 +1,91 @@ +import pytest + +from inferrsi.knowledge.atomic_reader import AtomicReader +from tests.fixtures.atomic_composition import composition, node +from tests.knowledge.test_atomic_reader import Snapshots, allow, excerpt + + +def read(source, pin, layer, budget, **context): + return AtomicReader(source, permits=allow).read_selection( + pin.ref, revision=pin.revision, layer=layer, max_bytes=budget, context=context, + ) + + +def test_required_closure_deduplicates_multiple_paths_and_accounts_for_optional_groups(): + source = Snapshots() + rule, steps, evidence = [source.add(excerpt(layer)) for layer in ("L1", "L2", "L3")] + nodes = {"rule": node(rule), "steps": node(steps, "rule"), "evidence": node(evidence, "rule")} + acceptance = {"layer": "L2", "required": ["rule", "steps"], "optional": ["evidence"]} + pin = source.add(composition(nodes, {"acceptance": acceptance})) + result = read(source, pin, "L2", 2383) + assert result.receipt["body_bytes"] == sum(map(len, result.bodies)) == 2383 + records = result.receipt["delivered"] + assert [r["ref"] for r in records] == [rule.ref, steps.ref] + assert records[0]["paths"] == [["acceptance", "rule"], ["acceptance", "steps", "rule"]] + assert result.receipt["omissions"] == [{"path": ["acceptance", "evidence"], + "reason": "over_budget"}] + assert source.reads.count(rule) == 1 + short = read(source, pin, "L2", 2382) + assert (short.bodies, short.receipt["status"], short.receipt["required_bytes"]) == ( + (), "over_budget", 2383, + ) + complete = read(source, pin, "L2", 4398) + assert [r["bytes"] for r in complete.receipt["delivered"]] == [845, 1538, 2015] + assert ["acceptance", "evidence", "rule"] in complete.receipt["delivered"][0]["paths"] + + +def test_query_and_layer_select_the_frozen_release_excerpts(): + source = Snapshots() + nodes, routes = {}, {} + for layer, query in (("L1", "acceptance criteria"), ("L2", "acceptance criteria"), + ("L3", "roofline example")): + nodes[layer] = node(source.add(excerpt(layer))) + routes[layer] = {"layer": layer, "required": [layer], "when": {"query": [query]}} + pin = source.add(composition(nodes, routes)) + examples = [("L1", 845, "acceptance criteria"), ("L2", 1538, "acceptance criteria"), + ("L3", 2015, "roofline example")] + for layer, size, query in examples: + assert read(source, pin, layer, size, query=query).receipt["body_bytes"] == size + assert read(source, pin, layer, size - 1, query=query).receipt["status"] == "over_budget" + assert read(source, pin, "L3", 9000, query="acceptance criteria").receipt["status"] == ( + "not_applicable" + ) + + +def test_only_applicable_supersession_changes_current_routes_and_history_stays_pinned(): + source = Snapshots() + old = source.add(excerpt("L1")) + revised = excerpt("L1") + revised.metadata["id"] = "current-rule" + new = source.add(revised) + nodes = {"old": node(old), "new": node(new)} + routes = {"X": {"layer": "L1", "required": ["old"], "when": {"query": ["current"]}}} + original = source.add(composition(nodes, routes)) + routes["Y"] = {"layer": "L1", "required": ["new"], "when": {"engine": {"min": "0.5"}}, + "supersedes": ["X"], "conflicts": ["X"]} + current = source.add(composition(nodes, routes)) + for pin, engine, expected in [(current, "v0.4", old), (current, "v0.5", new), + (original, "v0.5", old)]: + result = read(source, pin, "L1", 3000, engine=engine, query="current") + assert [r["ref"] for r in result.receipt["delivered"]] == [expected.ref] + routes["Y"].pop("supersedes") + conflicting = source.add(composition(nodes, routes)) + source.reads.clear() + conflict = read(source, conflicting, "L1", 3000, engine="v0.5", query="current") + assert conflict.receipt["status"] == "conflict" and not conflict.bodies + assert source.reads == [conflicting] + + +@pytest.mark.parametrize("bad", ["cycle", "dangling", "supersedes cycle"]) +def test_invalid_composition_fails_before_releasing_any_atom(bad): + source = Snapshots() + nodes = {"leaf": node(source.add(excerpt("L1")))} + routes = {"selected": {"layer": "L1", "required": ["leaf"]}} + if bad == "supersedes cycle": + routes["selected"]["supersedes"] = ["selected"] + else: + nodes["leaf"]["requires"] = ["missing" if bad == "dangling" else "leaf"] + pin = source.add(composition(nodes, routes)) + with pytest.raises(ValueError, match="Cycle|names declared"): + read(source, pin, "L1", 1) + assert source.reads == [pin] From bd611c3ee9cc609d23f6f54c2f05c1113e31566e Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:37:11 +0800 Subject: [PATCH 4/8] Build reproducible Knowledge generations and their host skill entries Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/guides/knowledge/knowledge-layout.md | 56 ++++++ src/inferrsi/knowledge/atomic_build.py | 172 ++++++++++++++++++ src/inferrsi/knowledge/atomic_generation.py | 104 +++++++++++ src/inferrsi/knowledge/atomic_reader.py | 11 +- tests/knowledge/test_atomic_composition.py | 9 + tests/knowledge/test_atomic_generation.py | 190 ++++++++++++++++++++ 6 files changed, 540 insertions(+), 2 deletions(-) create mode 100644 src/inferrsi/knowledge/atomic_build.py create mode 100644 src/inferrsi/knowledge/atomic_generation.py create mode 100644 tests/knowledge/test_atomic_generation.py diff --git a/docs/guides/knowledge/knowledge-layout.md b/docs/guides/knowledge/knowledge-layout.md index 8caf9ec7f..1c6cd1659 100644 --- a/docs/guides/knowledge/knowledge-layout.md +++ b/docs/guides/knowledge/knowledge-layout.md @@ -4,6 +4,62 @@ The diagrams and counts record the layout migration in [#516](https://github.com To reproduce the #516 search comparison, use the baseline and candidate checkouts from that migration on the same machine. The [search comparison](../../../tools/compare_find_layouts.py) checks ordered results across both trees and times the end-to-end CLI. The [task queries and acceptance criteria](../../../tests/fixtures/find/layout-queries.json) define the workload. +## Atomic candidate for domain authors and Apps + +The shared candidate accepts one JSON descriptor per atom or composition. An +author works under `src/inferrsi/knowledge/atoms/` or `compositions/`. For a +clean build, pass that Knowledge root and a separate, new installation directory +to `inferrsi.knowledge.atomic_build.build_generation(source, target, permits=...)`. +The existing wheel and plugin continue to load the published library during +candidate review. + +Each descriptor carries normalized Bundle `metadata`, optional in-bundle +`dependencies`, and a `content` mapping. A resource is either `{"text": "..."}` +or `{"path": "inputs/file"}` relative to its descriptor directory. The default +authority is `package`. An explicit `authority` preserves a different source's +identity and requires its own grants. A navigation composition can omit its +entrypoint and content. The builder derives its navigation record. A Case +provides the original `case.json` so a finding can be reopened by stable ID or +by its JSON pointer at the requested revision. + +- `metadata.atom` declares its L0–L3 layer, applicability (`when`), license, + separate read/retain/redistribute grants, and a `source_span` with source + index, path, half-open byte range and SHA-256. The atom reads the entrypoint + or its explicit `resource` for an attachment. Its Bundle revision covers all + metadata and resource bytes. +- `metadata.composition` declares named `nodes` (qualified ref, exact revision, + required prerequisite nodes), `routes` (layer, required and optional roots, + conditions, finding, conflicts and superseded routes), and its grants and + license. An exportable composition adds `skill` with `name`, `description`, + an L0 node called out by `body`, and a mapping from public relative resource + paths to pinned nodes. Each of the seven public task names has one owner. + The [executable authoring example](../../../tests/knowledge/test_atomic_generation.py) + builds all seven entries and a supporting skill. +- The installer writes `knowledge/{atoms,compositions}/`, the generated catalog + and file digests in `knowledge/generation.json`, and `skills//SKILL.md` + with the declared references, assets and scripts. Two builds of the same + input yield the same generation ID. `InstalledGeneration(root, expected=...)` + verifies the complete installed tree before exposing its `tasks`, `skills`, + `catalog` or `read_resolved` interface. A prior generation directory can + reopen its own receipts. +- Ordinary callers use `apps.workflows.knowledge.read_selection(source, ref, + permits=..., revision=..., layer=..., finding=..., context=..., max_bytes=...)`. + Managed optimization uses `apps.workflows.campaign.capture_selection(root, + source, ref, ...)` with the same selection and the additional retain grant. + The response binds original bytes, digests, source ranges and dependency + paths to the chosen revision. A required-group refusal delivers zero + bodies. Optional omissions carry a reason. + +Project-service reuse has a separate receipt format that excludes content +fingerprints. The pinned-finding capture above covers ordinary managed +optimization. For `evaluation_mode=service_reuse`, use the service's own +receipt path. In the [#709 CLI](https://github.com/InferMatrixLab/InferRSI/pull/709), +`find --session` retains the source at search time and its returned `read_args` +open and page that retained version, including relative resources. The new +pinned capture rejects this mode before reading or writing session state. +Atomic finding selection for this mode needs a service-compatible receipt +and belongs to the subsequent Reader adaptation. + ## 1. Task layers and evidence ```mermaid diff --git a/src/inferrsi/knowledge/atomic_build.py b/src/inferrsi/knowledge/atomic_build.py new file mode 100644 index 000000000..74e29ad46 --- /dev/null +++ b/src/inferrsi/knowledge/atomic_build.py @@ -0,0 +1,172 @@ +"""Build the candidate Knowledge and host skill trees from the same authored inputs.""" + +from __future__ import annotations + +import json +import re +from collections.abc import Callable +from pathlib import Path, PurePosixPath +from tempfile import TemporaryDirectory + +from .atomic_composition import AtomPin, applies, select_routes +from .atomic_generation import PUBLIC_TASKS, SEAL, InstalledGeneration, digest, owned_path +from .atomic_reader import atom_material, permits_operations +from .decision_cards import DecisionSource +from .knowledge_operations import IDENTITY, Bundle, _json, safe_path + +_PUBLISH = {"read", "retain", "redistribute"} + + +def _authored(directory: Path, path: Path, field: str) -> tuple[AtomPin, Bundle]: + descriptor = json.loads(owned_path(directory, path.name).read_bytes()) + metadata = descriptor["metadata"] + if field not in metadata or ("atom" in metadata and "composition" in metadata): + raise ValueError(f"{path.name} must declare one {field}") + content = {} + for name, value in descriptor.get("content", {}).items(): + safe_path(name) + if isinstance(value, dict) and value.keys() == {"path"}: + content[name] = owned_path(directory, value["path"]).read_bytes() + elif (isinstance(value, dict) and value.keys() == {"text"} + and isinstance(value["text"], str)): + content[name] = value["text"].encode() + else: + raise ValueError(f"Expected one text or relative path for {name} in {path.name}") + if field == "composition" and "entrypoint" not in metadata and metadata["kind"] != "case": + metadata["entrypoint"] = "navigation.json" + if "navigation.json" in content: + raise ValueError("Explicit navigation content must declare its entrypoint") + content["navigation.json"] = _json(metadata[field]) + bundle = Bundle(metadata, content, descriptor.get("dependencies", {})) + ref = descriptor.get("authority", "package") + ":" + metadata["id"] + return AtomPin(ref, bundle.revision), bundle + + +def _host_skill(declaration: dict, nodes: dict, material: dict) -> tuple[str, dict[str, bytes]]: + name, description = declaration["name"], declaration["description"] + if (not isinstance(name, str) or len(name) > 64 + or not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", name)): + raise ValueError(f"Invalid host skill name: {name}") + if not isinstance(description, str) or not 1 <= len(description.strip()) <= 1024: + raise ValueError(f"Invalid host skill description: {name}") + if declaration["body"] not in nodes: + raise ValueError(f"Undeclared navigation node for host skill {name}") + navigation, record = material[nodes[declaration["body"]]] + if record["layer"] != "L0": + raise ValueError(f"Host skill {name} must start at an L0 navigation atom") + markdown = navigation.decode("utf-8") + quoted = json.dumps(description, ensure_ascii=False) + header = f"---\nname: {json.dumps(name)}\ndescription: {quoted}\n---\n\n".encode() + output = {f"skills/{name}/SKILL.md": header + navigation} + resources = declaration.get("resources", {}) + for relative, node in resources.items(): + if safe_path(relative).partition("/")[0] not in {"references", "assets", "scripts"}: + raise ValueError(f"Unsupported host skill resource: {relative}") + if "/" not in relative: + raise ValueError(f"Expected a file inside a host resource directory: {relative}") + if node not in nodes: + raise ValueError(f"Undeclared resource node {node} for host skill {name}") + output[f"skills/{name}/{relative}"] = material[nodes[node]][0] + # Check direct Markdown resource links in the generated navigation, including fragments. + links = re.findall(r"\]\(#?]+)", markdown) + if any(link not in resources for link in links): + raise ValueError(f"Navigation links to an undeclared resource in host skill {name}") + return name, output + + +def _prepare(source: Path, permits: Callable[[AtomPin, str], bool]): + files, entries, material, compositions = {}, {}, {}, {} + skills = {} + for family, field in (("atoms", "atom"), ("compositions", "composition")): + directory = owned_path(source, family) + if not directory.is_dir(): + raise ValueError(f"Missing authored {family} directory") + for path in sorted(directory.glob("*.json")): + if not re.fullmatch(IDENTITY, path.stem): + raise ValueError(f"Invalid descriptor filename: {path.name}") + pin, bundle = _authored(directory, path, field) + if pin.ref in entries: + raise ValueError(f"Duplicate qualified reference: {pin.ref}") + view = bundle.view() + declaration = view[field] + if (not all(permits(pin, operation) for operation in _PUBLISH) + or not permits_operations(declaration, _PUBLISH)): + raise PermissionError(f"Publication denied for {pin.ref}") + applies(declaration["when"], {}) + prefix = f"knowledge/{family}/{path.stem}" + files[prefix + ".json"] = _json(bundle.manifest()) + files.update({prefix + "/" + name: data for name, data in bundle.content.items()}) + entry = {"revision": pin.revision, "manifest": prefix + ".json", "kind": view["kind"]} + for key in ("title", "summary"): + if isinstance(view.get(key), str): + entry[key] = view[key] + if field == "atom": + material[pin] = atom_material(bundle, view) + entry["layer"] = declaration["layer"] + else: + compositions[pin] = bundle + entries[pin.ref] = entry + + for pin, bundle in compositions.items(): + view = bundle.view() + declaration = view["composition"] + case = DecisionSource.from_bundle(pin.ref, bundle, view) if view["kind"] == "case" else None + # Validates every route, edge, condition and original finding, including inactive routes. + select_routes(declaration, layer="L0", context={}, case=case, finding=None) + nodes = {key: AtomPin(node["ref"], node["revision"]) + for key, node in declaration["nodes"].items()} + for node in nodes.values(): + if node not in material: + raise ValueError(f"Missing pinned atom {node.ref} at {node.revision} for {pin.ref}") + for route in declaration["routes"].values(): + layers = {material[nodes[name]][1]["layer"] for name in route["required"]} + if route["layer"] not in layers: + raise ValueError(f"No required root supplies {route['layer']} for {pin.ref}") + if "skill" in declaration: + name, output = _host_skill(declaration["skill"], nodes, material) + if name in skills: + raise ValueError(f"Multiple compositions export host skill {name}") + skills[name] = pin.ref + files.update(output) + missing = PUBLIC_TASKS - skills.keys() + if missing: + raise ValueError(f"Missing public task compositions: {', '.join(sorted(missing))}") + # Collisions on case-insensitive filesystems must fail on all build hosts. + portable = {name.casefold() for name in files} + parents = (p.as_posix().casefold() for name in files for p in PurePosixPath(name).parents) + if len(portable) != len(files) or any(p in portable for p in parents): + raise ValueError("Generation contains colliding resource paths") + seal = {"format": 1, "entries": entries, "skills": skills, + "files": {name: digest(data) for name, data in files.items()}} + generation = "sha256:" + digest(_json(seal)) + files[SEAL] = _json({**seal, "generation": generation}) + return generation, files + + +def build_generation(source: Path, target: Path, *, permits: Callable[[AtomPin, str], bool]) -> str: + """Stage and verify a complete new generation; repeat installs must have identical bytes.""" + source = Path(source).resolve(strict=True) + target = Path(target).absolute() + if target.is_symlink() or target.resolve() != target: + raise ValueError("Generation target must be a physical directory") + if target.is_relative_to(source) or source.is_relative_to(target): + raise ValueError("Separate the authored and installed generation roots") + generation, files = _prepare(source, permits) + if target.exists(): + return InstalledGeneration(target, expected=generation).generation + target.parent.mkdir(parents=True, exist_ok=True) + with TemporaryDirectory(prefix=".atomic-build-", dir=target.parent) as staging: + root = Path(staging) / "generation" + for name, data in files.items(): + path = root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + InstalledGeneration(root, expected=generation) + try: + root.rename(target) + except OSError: + if not target.is_dir(): + raise + # Another builder may have published the same immutable destination first. + return InstalledGeneration(target, expected=generation).generation + return generation diff --git a/src/inferrsi/knowledge/atomic_generation.py b/src/inferrsi/knowledge/atomic_generation.py new file mode 100644 index 000000000..d8a8fde26 --- /dev/null +++ b/src/inferrsi/knowledge/atomic_generation.py @@ -0,0 +1,104 @@ +"""Open one immutable installed Knowledge generation and resolve only its exact pins.""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +from .atomic_composition import AtomPin +from .knowledge_operations import Bundle, UnavailableRevision, _json, safe_path + +PUBLIC_TASKS = frozenset({ + "task-day-0", "task-performance", "task-debug", "task-accuracy", "task-version-alignment", + "task-derived-engine", "task-independent-engine", +}) +SEAL = "knowledge/generation.json" + + +def digest(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def owned_path(root: Path, name: str) -> Path: + """Resolve a portable resource within its owner, rejecting links and Windows junctions.""" + path = root + for part in safe_path(name).split("/"): + path = path / part + if path.is_symlink() or path.resolve() != path: + raise ValueError(f"Linked generation resource: {name}") + return path + + +def inventory(root: Path) -> dict[str, bytes]: + result = {} + for family in ("knowledge", "skills"): + directory = owned_path(root, family) + if not directory.is_dir(): + raise ValueError(f"Missing generation directory: {family}") + for path in directory.rglob("*"): + name = path.relative_to(root).as_posix() + owned_path(root, name) + if path.is_file() and name != SEAL: + result[name] = path.read_bytes() + return result + + +class InstalledGeneration: + """A verified snapshot. An open reader keeps its bytes across later installations.""" + + def __init__(self, root: Path, *, expected: str | None = None): + root = Path(root).resolve(strict=True) + seal = json.loads(owned_path(root, SEAL).read_bytes()) + generation = seal.pop("generation") + if seal.get("format") != 1 or generation != "sha256:" + digest(_json(seal)): + raise ValueError("Invalid Knowledge generation seal") + if expected is not None and expected != generation: + raise UnavailableRevision(f"Requested generation is unavailable: {expected}") + files = inventory(root) + if {path: digest(data) for path, data in files.items()} != seal["files"]: + raise ValueError("Installed Knowledge and skills differ from the sealed generation") + self.generation = generation + self._catalog = seal["entries"] + self._skills = seal["skills"] + self._bundles = {} + exports = {} + for ref, entry in self._catalog.items(): + pin = AtomPin(ref, entry["revision"]) + path = safe_path(entry["manifest"]) + manifest = json.loads(files[path]) + content = {name: files[path.removesuffix(".json") + "/" + safe_path(name)] + for name in manifest["resources"]} + bundle = Bundle(manifest["metadata"], content, manifest["dependencies"]) + if (ref.partition(":")[2] != bundle.metadata["id"] or bundle.manifest() != manifest + or bundle.revision != pin.revision): + raise ValueError(f"Installed Bundle differs from its catalog entry: {ref}") + self._bundles[pin] = bundle + skill = bundle.metadata.get("composition", {}).get("skill") + if skill is not None: + name = skill["name"] + if name in exports or f"skills/{name}/SKILL.md" not in files: + raise ValueError(f"Invalid host skill export: {name}") + exports[name] = ref + if exports != self._skills or PUBLIC_TASKS - exports.keys(): + raise ValueError("Installed skill catalog differs from the public composition exports") + + @property + def catalog(self) -> dict: + return {ref: dict(entry) for ref, entry in self._catalog.items()} + + @property + def skills(self) -> dict[str, str]: + """Generated host skill name to its owning composition.""" + return dict(self._skills) + + @property + def tasks(self) -> dict[str, str]: + return {name: self._skills[name] for name in sorted(PUBLIC_TASKS)} + + def read_resolved(self, reference: str, *, revision: str) -> tuple[str, Bundle]: + pin = AtomPin(reference, revision) + if pin not in self._bundles: + raise UnavailableRevision(f"Revision unavailable in {self.generation}: {pin.ref}") + bundle = self._bundles[pin] + return pin.ref, Bundle(bundle.metadata, dict(bundle.content), dict(bundle.dependencies)) diff --git a/src/inferrsi/knowledge/atomic_reader.py b/src/inferrsi/knowledge/atomic_reader.py index 8cbda3594..d348da270 100644 --- a/src/inferrsi/knowledge/atomic_reader.py +++ b/src/inferrsi/knowledge/atomic_reader.py @@ -130,7 +130,8 @@ def _snapshot(self, pin: AtomPin) -> tuple[Bundle, dict] | None: view = bundle.view() return (bundle, view) if view["revision"] == pin.revision else None - def _materialize(self, required, optional, *, max_bytes, context, actions) -> GroupDelivery: + def _materialize(self, required, optional, *, max_bytes, context, actions, + layer=None) -> GroupDelivery: cached: dict[AtomPin, tuple[bytes, dict]] = {} paths: dict[AtomPin, list[list[str]]] = {} omissions = [] @@ -173,6 +174,12 @@ def include(group: Iterable[AtomUse]) -> GroupDelivery | None: refusal = include(required) if refusal is not None: return refusal + if layer is not None: + routes = {via[0] for vias in paths.values() for via in vias} + supplied = {via[0] for pin, vias in paths.items() if cached[pin][1]["layer"] == layer + for via in vias if len(via) == 2} + if routes != supplied: + raise ValueError(f"Selected route has no required root supplying {layer}") for group in optional: refusal = include(group) if refusal is not None: @@ -222,6 +229,6 @@ def read_selection( if plan.refusal: return _selected(_refused(plan.refusal), requested) delivery = self._materialize(plan.required, plan.optional, max_bytes=max_bytes, - context=context, actions=actions) + context=context, actions=actions, layer=layer) return _selected(delivery, {**requested, "canonical_finding": plan.finding, "routes": list(plan.routes)}) diff --git a/tests/knowledge/test_atomic_composition.py b/tests/knowledge/test_atomic_composition.py index 5d99355fb..5fc8c83ba 100644 --- a/tests/knowledge/test_atomic_composition.py +++ b/tests/knowledge/test_atomic_composition.py @@ -52,6 +52,15 @@ def test_query_and_layer_select_the_frozen_release_excerpts(): ) +def test_each_selected_route_must_supply_its_declared_layer(): + source = Snapshots() + nodes = {"rule": node(source.add(excerpt("L1"))), "asset": node(source.add(excerpt("L3")))} + routes = {name: {"layer": "L1", "required": [name]} for name in nodes} + pin = source.add(composition(nodes, routes)) + with pytest.raises(ValueError, match="supplying L1"): + read(source, pin, "L1", 9000) + + def test_only_applicable_supersession_changes_current_routes_and_history_stays_pinned(): source = Snapshots() old = source.add(excerpt("L1")) diff --git a/tests/knowledge/test_atomic_generation.py b/tests/knowledge/test_atomic_generation.py new file mode 100644 index 000000000..a7f42965f --- /dev/null +++ b/tests/knowledge/test_atomic_generation.py @@ -0,0 +1,190 @@ +import hashlib +import json +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +import pytest + +from inferrsi.apps.workflows.knowledge import read_selection +from inferrsi.knowledge.atomic_build import build_generation +from inferrsi.knowledge.atomic_generation import PUBLIC_TASKS, SEAL, InstalledGeneration, digest +from inferrsi.knowledge.atomic_reader import AtomPin +from inferrsi.knowledge.knowledge_operations import Bundle, UnavailableRevision, _json +from tests.fixtures.atomic_composition import composition, metadata, node +from tests.knowledge.test_atomic_reader import allow, excerpt + + +def write_json(path, obj): + path.write_text(json.dumps(obj, ensure_ascii=False), encoding="utf-8") + + +def local_atom(name, layer, body): + sha = hashlib.sha256(body).hexdigest() + fields = metadata(name, "knowledge", "body", {"type": "fixture", "sha256": sha}) + fields["atom"] = { + "layer": layer, "when": {}, "license": "Apache-2.0", + "permissions": {"read": True, "retain": True, "redistribute": True}, + "source_span": {"source_index": 0, "byte_range": [0, len(body)], + "path": "sample", "sha256": sha}, + } + return Bundle(fields, {"body": body}, {}) + + +@pytest.fixture +def author_root(tmp_path): + root = tmp_path / "source" + atoms, compositions = root / "atoms", root / "compositions" + (atoms / "inputs").mkdir(parents=True) + compositions.mkdir() + nav = local_atom("navigation", "L0", b"See [criteria](references/criteria.md).\n") + binary = local_atom("attachment", "L3", bytes([0xff, 0x00, 0x22])) + nodes = {} + for bundle in [nav, binary, *(excerpt(level) for level in ("L1", "L2", "L3"))]: + identity = bundle.metadata["id"] + name, data = next(iter(bundle.content.items())) + if identity == "navigation": + source = {"text": data.decode()} + else: + relative = "inputs/" + identity + (atoms / relative).write_bytes(data) + source = {"path": relative} + write_json(atoms / (identity + ".json"), + {"metadata": bundle.metadata, "content": {name: source}}) + nodes[identity] = node(AtomPin("package:" + identity, bundle.revision)) + nodes["ceiling-l2"]["requires"] = ["ceiling-l1"] + routes = { + "navigate": {"layer": "L0", "required": ["navigation"]}, + "rules": {"layer": "L1", "required": ["ceiling-l1"]}, + "steps": {"layer": "L2", "required": ["ceiling-l1", "ceiling-l2"], + "optional": ["ceiling-l3"], "when": {"query": ["acceptance criteria"]}}, + "attachment": {"layer": "L3", "required": ["attachment"]}, + } + for skill_name in sorted(PUBLIC_TASKS | {"analysis-example"}): + fields = composition(nodes, routes).metadata + fields["id"] = "entry-" + skill_name + del fields["entrypoint"] # Single authored file for a navigation composition. + fields["composition"]["skill"] = { + "name": skill_name, "description": "Inspect the fixture.", + "body": "navigation", "resources": {"references/criteria.md": "ceiling-l2", + "assets/example.bin": "attachment"}, + } + write_json(compositions / (skill_name + ".json"), {"metadata": fields}) + return root + + +def file_bytes(root: Path): + return {p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()} + + +def test_same_source_builds_byte_identical_catalog_skills_and_pinned_reader(author_root, tmp_path): + first, second = tmp_path / "install-a", tmp_path / "install-b" + generation = build_generation(author_root, first, permits=allow) + assert build_generation(author_root, second, permits=allow) == generation + assert file_bytes(first) == file_bytes(second) + assert build_generation(author_root, first, permits=allow) == generation + assert not list(author_root.rglob("SKILL.md")) + assert not list(first.rglob("skill-index.json")) + installed = InstalledGeneration(first, expected=generation) + assert set(installed.tasks) == PUBLIC_TASKS + assert set(installed.skills) == PUBLIC_TASKS | {"analysis-example"} + for name, ref in installed.skills.items(): + host = first / "skills" / name + header = (host / "SKILL.md").read_text(encoding="utf-8") + assert header == (f'---\nname: "{name}"\ndescription: "Inspect the fixture."\n---\n\n' + "See [criteria](references/criteria.md).\n") + assert (host / "references/criteria.md").read_bytes() == next( + iter(excerpt("L2").content.values())) + assert (host / "assets/example.bin").read_bytes() == bytes([0xff, 0, 0x22]) + entry = installed.catalog[ref] + request = dict(revision=entry["revision"], layer="L2", max_bytes=2383, + context={"query": "acceptance criteria"}, permits=allow) + chosen = read_selection(installed, ref, **request) + assert [len(body) for body in chosen.bodies] == [845, 1538] + assert chosen.receipt["body_bytes"] == 2383 + short = read_selection(installed, ref, **{**request, "max_bytes": 2382}) + assert short.receipt["status"] == "over_budget" and not short.bodies + with pytest.raises(UnavailableRevision): + installed.read_resolved(ref.replace("package:", "checkout:"), + revision=entry["revision"]) + + +@pytest.mark.parametrize("change", [ + "missing task", "missing revision", "retain", "license", "policy", "outside", + "alias", "wrong layer", "incomplete skill", "missing relative link", +]) +def test_invalid_candidate_publishes_no_partial_tree(author_root, tmp_path, change): + descriptor = author_root / "compositions/task-debug.json" + spec = json.loads(descriptor.read_bytes()) + dec = spec["metadata"]["composition"] + if change == "missing task": + descriptor.unlink() + elif change == "outside": + spec["content"] = {"source": {"path": "../sibling"}} + elif change == "missing revision": + dec["nodes"]["navigation"]["revision"] = "sha256:" + "0" * 64 + elif change == "retain": + dec["permissions"]["retain"] = False + elif change == "license": + dec["license"] = "NOASSERTION" + elif change == "wrong layer": + dec["routes"]["rules"]["required"] = ["attachment"] + elif change == "incomplete skill": + dec["skill"]["resources"]["assets/missing"] = "not-declared" + elif change == "missing relative link": + del dec["skill"]["resources"]["references/criteria.md"] + elif change == "alias": + dec["skill"]["resources"]["assets/Example.bin"] = "attachment" + if descriptor.exists(): + write_json(descriptor, spec) + + def policy(pin, op): + return not (change == "policy" and pin.ref == "package:ceiling-l1" and op == "redistribute") + + with pytest.raises((ValueError, PermissionError)): + build_generation(author_root, tmp_path / "generation", permits=policy) + assert not (tmp_path / "generation").exists() + + +def test_pinned_history_survives_new_build_and_mixed_install_is_rejected(author_root, tmp_path): + first, second = tmp_path / "release-a", tmp_path / "release-b" + old_id = build_generation(author_root, first, permits=allow) + original = InstalledGeneration(first) + spec = author_root / "compositions/task-debug.json" + obj = json.loads(spec.read_bytes()) + obj["metadata"]["limitations"] = ["revision B"] + write_json(spec, obj) + new_id = build_generation(author_root, second, permits=allow) + assert new_id != old_id + with pytest.raises(UnavailableRevision): + build_generation(author_root, first, permits=allow) + new = InstalledGeneration(second) + ref = original.tasks["task-debug"] + revision = original.catalog[ref]["revision"] + assert original.read_resolved(ref, revision=revision)[1].revision == revision + with pytest.raises(UnavailableRevision): + new.read_resolved(ref, revision=revision) + (first / SEAL).write_bytes((second / SEAL).read_bytes()) + with pytest.raises(ValueError, match="differ"): + InstalledGeneration(first) + assert original.read_resolved(ref, revision=revision)[1].revision == revision + + +def test_concurrent_identical_builders_share_one_complete_destination(author_root, tmp_path): + destination = tmp_path / "generation" + with ThreadPoolExecutor(max_workers=2) as pool: + first, second = [pool.submit(build_generation, author_root, destination, permits=allow) + for _ in range(2)] + assert first.result() == second.result() == InstalledGeneration(destination).generation + + +def test_installed_catalog_must_match_the_exporter_even_if_resealed(author_root, tmp_path): + destination = tmp_path / "generation" + build_generation(author_root, destination, permits=allow) + path = destination / SEAL + seal = json.loads(path.read_bytes()) + del seal["generation"] + seal["skills"]["task-debug"] = seal["skills"]["task-accuracy"] + seal["generation"] = "sha256:" + digest(_json(seal)) + path.write_bytes(_json(seal)) + with pytest.raises(ValueError, match="composition exports"): + InstalledGeneration(destination) From a92c1bb63fdef209054d323618d4bea4ed08c5a0 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:09:53 +0800 Subject: [PATCH 5/8] Preserve full host procedures from pinned atom sections Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/apps-module-migrations.json | 1 + docs/guides/knowledge/knowledge-layout.md | 6 +++- src/inferrsi/knowledge/atomic_build.py | 20 ++++++++---- tests/knowledge/test_atomic_generation.py | 38 ++++++++++++++++++++--- 4 files changed, 53 insertions(+), 12 deletions(-) diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index 9256effd3..44f9c3879 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -549,6 +549,7 @@ "src/inferrsi/apps/cli/__init__.py", "tests/apps/test_apps_context_provider.py", "tests/apps/test_apps_knowledge.py", + "tests/apps/test_optimization_session.py", "tests/harness/test_harness_generation_seal.py" ], "status": "retired", diff --git a/docs/guides/knowledge/knowledge-layout.md b/docs/guides/knowledge/knowledge-layout.md index 1c6cd1659..e54050e07 100644 --- a/docs/guides/knowledge/knowledge-layout.md +++ b/docs/guides/knowledge/knowledge-layout.md @@ -32,7 +32,11 @@ by its JSON pointer at the requested revision. conditions, finding, conflicts and superseded routes), and its grants and license. An exportable composition adds `skill` with `name`, `description`, an L0 node called out by `body`, and a mapping from public relative resource - paths to pinned nodes. Each of the seven public task names has one owner. + paths to pinned nodes. For a host that loads a complete procedure, list its + additional pinned text nodes in `skill.sections` in reading order. The + builder appends their original bytes, including whitespace, to the L0 body. + A Reader request for L0 still returns the composition's L0 route. Each of + the seven public task names has one owner. The [executable authoring example](../../../tests/knowledge/test_atomic_generation.py) builds all seven entries and a supporting skill. - The installer writes `knowledge/{atoms,compositions}/`, the generated catalog diff --git a/src/inferrsi/knowledge/atomic_build.py b/src/inferrsi/knowledge/atomic_build.py index 74e29ad46..edd9b7919 100644 --- a/src/inferrsi/knowledge/atomic_build.py +++ b/src/inferrsi/knowledge/atomic_build.py @@ -51,13 +51,21 @@ def _host_skill(declaration: dict, nodes: dict, material: dict) -> tuple[str, di raise ValueError(f"Invalid host skill description: {name}") if declaration["body"] not in nodes: raise ValueError(f"Undeclared navigation node for host skill {name}") - navigation, record = material[nodes[declaration["body"]]] - if record["layer"] != "L0": + sections = declaration.get("sections", []) + if not isinstance(sections, list) or not all(isinstance(key, str) and key in nodes + for key in sections): + raise ValueError(f"Host skill {name} must declare each procedure section as a node") + pins = [nodes[key] for key in (declaration["body"], *sections)] + if material[pins[0]][1]["layer"] != "L0": raise ValueError(f"Host skill {name} must start at an L0 navigation atom") - markdown = navigation.decode("utf-8") + if len(set(pins)) != len(pins): + raise ValueError(f"Repeated host skill section in {name}") + # Authored spans own their whitespace. Preserve the exact procedure in declared order. + body = b"".join(material[pin][0] for pin in pins) + markdown = body.decode("utf-8") quoted = json.dumps(description, ensure_ascii=False) header = f"---\nname: {json.dumps(name)}\ndescription: {quoted}\n---\n\n".encode() - output = {f"skills/{name}/SKILL.md": header + navigation} + output = {f"skills/{name}/SKILL.md": header + body} resources = declaration.get("resources", {}) for relative, node in resources.items(): if safe_path(relative).partition("/")[0] not in {"references", "assets", "scripts"}: @@ -67,10 +75,10 @@ def _host_skill(declaration: dict, nodes: dict, material: dict) -> tuple[str, di if node not in nodes: raise ValueError(f"Undeclared resource node {node} for host skill {name}") output[f"skills/{name}/{relative}"] = material[nodes[node]][0] - # Check direct Markdown resource links in the generated navigation, including fragments. + # Check direct Markdown resource links throughout the generated skill, including fragments. links = re.findall(r"\]\(#?]+)", markdown) if any(link not in resources for link in links): - raise ValueError(f"Navigation links to an undeclared resource in host skill {name}") + raise ValueError(f"Undeclared resource linked from host skill {name}") return name, output diff --git a/tests/knowledge/test_atomic_generation.py b/tests/knowledge/test_atomic_generation.py index a7f42965f..a6bedd55d 100644 --- a/tests/knowledge/test_atomic_generation.py +++ b/tests/knowledge/test_atomic_generation.py @@ -5,10 +5,9 @@ import pytest -from inferrsi.apps.workflows.knowledge import read_selection from inferrsi.knowledge.atomic_build import build_generation from inferrsi.knowledge.atomic_generation import PUBLIC_TASKS, SEAL, InstalledGeneration, digest -from inferrsi.knowledge.atomic_reader import AtomPin +from inferrsi.knowledge.atomic_reader import AtomicReader, AtomPin from inferrsi.knowledge.knowledge_operations import Bundle, UnavailableRevision, _json from tests.fixtures.atomic_composition import composition, metadata, node from tests.knowledge.test_atomic_reader import allow, excerpt @@ -85,6 +84,7 @@ def test_same_source_builds_byte_identical_catalog_skills_and_pinned_reader(auth assert not list(author_root.rglob("SKILL.md")) assert not list(first.rglob("skill-index.json")) installed = InstalledGeneration(first, expected=generation) + reader = AtomicReader(installed, permits=allow) assert set(installed.tasks) == PUBLIC_TASKS assert set(installed.skills) == PUBLIC_TASKS | {"analysis-example"} for name, ref in installed.skills.items(): @@ -97,20 +97,42 @@ def test_same_source_builds_byte_identical_catalog_skills_and_pinned_reader(auth assert (host / "assets/example.bin").read_bytes() == bytes([0xff, 0, 0x22]) entry = installed.catalog[ref] request = dict(revision=entry["revision"], layer="L2", max_bytes=2383, - context={"query": "acceptance criteria"}, permits=allow) - chosen = read_selection(installed, ref, **request) + context={"query": "acceptance criteria"}) + chosen = reader.read_selection(ref, **request) assert [len(body) for body in chosen.bodies] == [845, 1538] assert chosen.receipt["body_bytes"] == 2383 - short = read_selection(installed, ref, **{**request, "max_bytes": 2382}) + short = reader.read_selection(ref, **{**request, "max_bytes": 2382}) assert short.receipt["status"] == "over_budget" and not short.bodies with pytest.raises(UnavailableRevision): installed.read_resolved(ref.replace("package:", "checkout:"), revision=entry["revision"]) +def test_host_procedure_assembles_pinned_sections_without_changing_l0(author_root, tmp_path): + descriptor = author_root / "compositions/task-debug.json" + spec = json.loads(descriptor.read_bytes()) + skill = spec["metadata"]["composition"]["skill"] + skill["sections"] = ["ceiling-l1", "ceiling-l2"] + skill["resources"]["references/acceptance-criteria.md"] = "ceiling-l2" + write_json(descriptor, spec) + destination = tmp_path / "install" + build_generation(author_root, destination, permits=allow) + installed = InstalledGeneration(destination) + ref = installed.tasks["task-debug"] + navigation = AtomicReader(installed, permits=allow).read_selection( + ref, revision=installed.catalog[ref]["revision"], layer="L0", context={}, max_bytes=100, + ) + assert navigation.bodies == (b"See [criteria](references/criteria.md).\n",) + host = (destination / "skills/task-debug/SKILL.md").read_bytes() + assert host.split(b"\n---\n\n", 1)[1] == navigation.bodies[0] + b"".join( + next(iter(excerpt(layer).content.values())) for layer in ("L1", "L2") + ) + + @pytest.mark.parametrize("change", [ "missing task", "missing revision", "retain", "license", "policy", "outside", "alias", "wrong layer", "incomplete skill", "missing relative link", + "undeclared section", "repeated section", "missing section link", ]) def test_invalid_candidate_publishes_no_partial_tree(author_root, tmp_path, change): descriptor = author_root / "compositions/task-debug.json" @@ -132,6 +154,12 @@ def test_invalid_candidate_publishes_no_partial_tree(author_root, tmp_path, chan dec["skill"]["resources"]["assets/missing"] = "not-declared" elif change == "missing relative link": del dec["skill"]["resources"]["references/criteria.md"] + elif change == "undeclared section": + dec["skill"]["sections"] = ["absent"] + elif change == "repeated section": + dec["skill"]["sections"] = ["navigation"] + elif change == "missing section link": + dec["skill"]["sections"] = ["ceiling-l1"] elif change == "alias": dec["skill"]["resources"]["assets/Example.bin"] = "attachment" if descriptor.exists(): From 0e67a95c23c58876e222ef1c5999a7181c402d65 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:37:39 +0800 Subject: [PATCH 6/8] Verify atomic source ranges against the pinned original file Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- .gitattributes | 1 - docs/guides/knowledge/knowledge-layout.md | 15 +- .../harness/records/atomic_capture.py | 1 - src/inferrsi/knowledge/atomic_build.py | 40 +- src/inferrsi/knowledge/atomic_composition.py | 2 - src/inferrsi/knowledge/atomic_generation.py | 3 +- src/inferrsi/knowledge/atomic_reader.py | 17 +- .../performance-ceiling-analysis/SKILL.md | 605 ++++++++++++++++++ .../references/acceptance-criteria.md | 94 +++ .../references/roofline-example.json | 72 +++ tests/fixtures/atomic_composition.py | 1 - tests/knowledge/test_atomic_generation.py | 69 +- tests/knowledge/test_atomic_reader.py | 9 +- 13 files changed, 886 insertions(+), 43 deletions(-) create mode 100644 tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/SKILL.md create mode 100644 tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/references/acceptance-criteria.md create mode 100644 tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/references/roofline-example.json diff --git a/.gitattributes b/.gitattributes index 8ccba34df..e7fb3e682 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4,7 +4,6 @@ # Preserve recorded evidence and historical validator bytes across checkouts. /evidence/** -text /tests/fixtures/legacy/** -text -# The frozen atom ranges include their terminating paragraph separators. /tests/fixtures/atomic-reader/** -text whitespace=-blank-at-eof # A session started by an older runtime keeps its exact bytes; its plan pins file hashes. /tests/fixtures/optimization-session/pre-infra-removal-session/** -text diff --git a/docs/guides/knowledge/knowledge-layout.md b/docs/guides/knowledge/knowledge-layout.md index e54050e07..9accaa348 100644 --- a/docs/guides/knowledge/knowledge-layout.md +++ b/docs/guides/knowledge/knowledge-layout.md @@ -9,7 +9,11 @@ To reproduce the #516 search comparison, use the baseline and candidate checkout The shared candidate accepts one JSON descriptor per atom or composition. An author works under `src/inferrsi/knowledge/atoms/` or `compositions/`. For a clean build, pass that Knowledge root and a separate, new installation directory -to `inferrsi.knowledge.atomic_build.build_generation(source, target, permits=...)`. +to `inferrsi.knowledge.atomic_build.build_generation(source, target, permits=..., +source_roots=...)`. Supply physical source snapshots keyed by the exact Git commit +or, for a content-addressed source, the complete file SHA-256. Use the original +source paths within each snapshot. A release wheel can be staged under the +corresponding repository paths after verifying its release digest. The existing wheel and plugin continue to load the published library during candidate review. @@ -24,9 +28,12 @@ by its JSON pointer at the requested revision. - `metadata.atom` declares its L0–L3 layer, applicability (`when`), license, separate read/retain/redistribute grants, and a `source_span` with source - index, path, half-open byte range and SHA-256. The atom reads the entrypoint - or its explicit `resource` for an attachment. Its Bundle revision covers all - metadata and resource bytes. + index, path, half-open byte range and SHA-256. Publication checks the whole + file against `sources[index].sha256` and compares the declared slice with the + atom's actual bytes. A content-addressed atom containing its complete file at + offset zero carries its own snapshot. The reader records `verified_at_build` + for a sealed format-2 generation and `declared` for source ranges supplied + by a store or another reader. Its Bundle revision covers metadata and resources. - `metadata.composition` declares named `nodes` (qualified ref, exact revision, required prerequisite nodes), `routes` (layer, required and optional roots, conditions, finding, conflicts and superseded routes), and its grants and diff --git a/src/inferrsi/harness/records/atomic_capture.py b/src/inferrsi/harness/records/atomic_capture.py index 81c5f1497..c3379f63b 100644 --- a/src/inferrsi/harness/records/atomic_capture.py +++ b/src/inferrsi/harness/records/atomic_capture.py @@ -88,7 +88,6 @@ def retain_selection(root: Path, *, reader, context_id, reference, revision, lay "finding": finding, "max_bytes": max_bytes, "context": dict(context), "operations": ["read", "retain"]} if ranking_policy is not None: - # Session provenance. This operation reopens an explicit pin without ranking it again. request["ranking_policy"] = ranking_policy delivery = reader.read_selection(reference, revision=revision, layer=layer, finding=finding, max_bytes=max_bytes, context=context, operations=("retain",)) diff --git a/src/inferrsi/knowledge/atomic_build.py b/src/inferrsi/knowledge/atomic_build.py index edd9b7919..6da6c76c1 100644 --- a/src/inferrsi/knowledge/atomic_build.py +++ b/src/inferrsi/knowledge/atomic_build.py @@ -4,12 +4,12 @@ import json import re -from collections.abc import Callable +from collections.abc import Callable, Mapping from pathlib import Path, PurePosixPath from tempfile import TemporaryDirectory from .atomic_composition import AtomPin, applies, select_routes -from .atomic_generation import PUBLIC_TASKS, SEAL, InstalledGeneration, digest, owned_path +from .atomic_generation import FORMAT, PUBLIC_TASKS, SEAL, InstalledGeneration, digest, owned_path from .atomic_reader import atom_material, permits_operations from .decision_cards import DecisionSource from .knowledge_operations import IDENTITY, Bundle, _json, safe_path @@ -60,7 +60,6 @@ def _host_skill(declaration: dict, nodes: dict, material: dict) -> tuple[str, di raise ValueError(f"Host skill {name} must start at an L0 navigation atom") if len(set(pins)) != len(pins): raise ValueError(f"Repeated host skill section in {name}") - # Authored spans own their whitespace. Preserve the exact procedure in declared order. body = b"".join(material[pin][0] for pin in pins) markdown = body.decode("utf-8") quoted = json.dumps(description, ensure_ascii=False) @@ -75,14 +74,33 @@ def _host_skill(declaration: dict, nodes: dict, material: dict) -> tuple[str, di if node not in nodes: raise ValueError(f"Undeclared resource node {node} for host skill {name}") output[f"skills/{name}/{relative}"] = material[nodes[node]][0] - # Check direct Markdown resource links throughout the generated skill, including fragments. links = re.findall(r"\]\(#?]+)", markdown) if any(link not in resources for link in links): raise ValueError(f"Undeclared resource linked from host skill {name}") return name, output -def _prepare(source: Path, permits: Callable[[AtomPin, str], bool]): +def _verify_source(body: bytes, record: dict, roots: Mapping[str, Path]) -> None: + source, path = record["source"], record["source_path"] + snapshot = source.get("sha256") + if not isinstance(snapshot, str) or not re.fullmatch(r"[0-9a-f]{64}", snapshot): + raise ValueError(f"Missing complete source file digest for {path}") + if source.get("path", path) != path: + raise ValueError(f"Atom path differs from its pinned source path: {path}") + start, end = record["source_byte_range"] + if "commit" not in source and start == 0 and snapshot == record["sha256"]: + return + key = source.get("commit", snapshot) + if key not in roots: + raise ValueError(f"Missing pinned source root for {key} at {path}") + original = owned_path(roots[key], path).read_bytes() + if digest(original) != snapshot: + raise ValueError(f"Complete pinned source file differs at {path}") + if end > len(original) or original[start:end] != body: + raise ValueError(f"Atom bytes differ from pinned source range at {path} [{start}, {end})") + + +def _prepare(source: Path, permits: Callable[[AtomPin, str], bool], roots: Mapping[str, Path]): files, entries, material, compositions = {}, {}, {}, {} skills = {} for family, field in (("atoms", "atom"), ("compositions", "composition")): @@ -110,6 +128,7 @@ def _prepare(source: Path, permits: Callable[[AtomPin, str], bool]): entry[key] = view[key] if field == "atom": material[pin] = atom_material(bundle, view) + _verify_source(*material[pin], roots) entry["layer"] = declaration["layer"] else: compositions[pin] = bundle @@ -119,7 +138,6 @@ def _prepare(source: Path, permits: Callable[[AtomPin, str], bool]): view = bundle.view() declaration = view["composition"] case = DecisionSource.from_bundle(pin.ref, bundle, view) if view["kind"] == "case" else None - # Validates every route, edge, condition and original finding, including inactive routes. select_routes(declaration, layer="L0", context={}, case=case, finding=None) nodes = {key: AtomPin(node["ref"], node["revision"]) for key, node in declaration["nodes"].items()} @@ -139,19 +157,19 @@ def _prepare(source: Path, permits: Callable[[AtomPin, str], bool]): missing = PUBLIC_TASKS - skills.keys() if missing: raise ValueError(f"Missing public task compositions: {', '.join(sorted(missing))}") - # Collisions on case-insensitive filesystems must fail on all build hosts. portable = {name.casefold() for name in files} parents = (p.as_posix().casefold() for name in files for p in PurePosixPath(name).parents) if len(portable) != len(files) or any(p in portable for p in parents): raise ValueError("Generation contains colliding resource paths") - seal = {"format": 1, "entries": entries, "skills": skills, + seal = {"format": FORMAT, "entries": entries, "skills": skills, "files": {name: digest(data) for name, data in files.items()}} generation = "sha256:" + digest(_json(seal)) files[SEAL] = _json({**seal, "generation": generation}) return generation, files -def build_generation(source: Path, target: Path, *, permits: Callable[[AtomPin, str], bool]) -> str: +def build_generation(source: Path, target: Path, *, permits: Callable[[AtomPin, str], bool], + source_roots: Mapping[str, Path] | None = None) -> str: """Stage and verify a complete new generation; repeat installs must have identical bytes.""" source = Path(source).resolve(strict=True) target = Path(target).absolute() @@ -159,7 +177,8 @@ def build_generation(source: Path, target: Path, *, permits: Callable[[AtomPin, raise ValueError("Generation target must be a physical directory") if target.is_relative_to(source) or source.is_relative_to(target): raise ValueError("Separate the authored and installed generation roots") - generation, files = _prepare(source, permits) + roots = {key: Path(path).resolve(strict=True) for key, path in (source_roots or {}).items()} + generation, files = _prepare(source, permits, roots) if target.exists(): return InstalledGeneration(target, expected=generation).generation target.parent.mkdir(parents=True, exist_ok=True) @@ -175,6 +194,5 @@ def build_generation(source: Path, target: Path, *, permits: Callable[[AtomPin, except OSError: if not target.is_dir(): raise - # Another builder may have published the same immutable destination first. return InstalledGeneration(target, expected=generation).generation return generation diff --git a/src/inferrsi/knowledge/atomic_composition.py b/src/inferrsi/knowledge/atomic_composition.py index b9317fa39..80e60a349 100644 --- a/src/inferrsi/knowledge/atomic_composition.py +++ b/src/inferrsi/knowledge/atomic_composition.py @@ -75,7 +75,6 @@ def applies(when: Mapping[str, object], context: Mapping[str, str]) -> bool: for key, condition in when.items(): if not isinstance(key, str) or not key: raise ValueError("Conditions must name a dimension") - # Validate later declarations even if an earlier dimension did not match. if not _matches(condition, context.get(key)): matches = False return matches @@ -167,7 +166,6 @@ def select_routes(composition: dict, *, layer: str, context: Mapping[str, str], if applicable and layer == route["layer"] and selector == selected_finding: matches.add(name) _acyclic(supersedes, "supersedes") - # A newer declaration can retire another only inside their common applicable scope. chosen = matches.difference(other for name in matches for other in supersedes[name]) if not chosen: return RouteSelection(finding=selected_finding, refusal="not_applicable") diff --git a/src/inferrsi/knowledge/atomic_generation.py b/src/inferrsi/knowledge/atomic_generation.py index d8a8fde26..99d4931a2 100644 --- a/src/inferrsi/knowledge/atomic_generation.py +++ b/src/inferrsi/knowledge/atomic_generation.py @@ -14,6 +14,7 @@ "task-derived-engine", "task-independent-engine", }) SEAL = "knowledge/generation.json" +FORMAT = 2 def digest(data: bytes) -> str: @@ -51,7 +52,7 @@ def __init__(self, root: Path, *, expected: str | None = None): root = Path(root).resolve(strict=True) seal = json.loads(owned_path(root, SEAL).read_bytes()) generation = seal.pop("generation") - if seal.get("format") != 1 or generation != "sha256:" + digest(_json(seal)): + if seal.get("format") != FORMAT or generation != "sha256:" + digest(_json(seal)): raise ValueError("Invalid Knowledge generation seal") if expected is not None and expected != generation: raise UnavailableRevision(f"Requested generation is unavailable: {expected}") diff --git a/src/inferrsi/knowledge/atomic_reader.py b/src/inferrsi/knowledge/atomic_reader.py index d348da270..49c2b8f92 100644 --- a/src/inferrsi/knowledge/atomic_reader.py +++ b/src/inferrsi/knowledge/atomic_reader.py @@ -9,6 +9,7 @@ from typing import Protocol from .atomic_composition import LAYERS, AtomPin, AtomUse, applies, select_routes +from .atomic_generation import InstalledGeneration from .decision_cards import DecisionSource from .knowledge_operations import ( Bundle, @@ -59,7 +60,7 @@ def permits_operations(declaration: dict, actions: set[str]) -> bool: return False license_id = declaration.get("license") if "redistribute" in actions and (not isinstance(license_id, str) or - license_id.strip().lower() in {"", "unknown", "none", "noassertion"}): + license_id.strip().lower() in {"", "unknown", "none", "noassertion", "no_license"}): return False return True @@ -86,10 +87,10 @@ def atom_material(bundle: Bundle, view: dict) -> tuple[bytes, dict]: source = view["sources"][index] commit = source.get("commit") snapshot = source.get("sha256") - if not ( - (isinstance(commit, str) and re.fullmatch(r"[0-9a-f]{40}", commit)) - or (isinstance(snapshot, str) and _DIGEST.fullmatch(snapshot)) - ): + if "commit" in source: + if not isinstance(commit, str) or not re.fullmatch(r"[0-9a-f]{40}", commit): + raise ValueError("Invalid immutable source commit") + elif not isinstance(snapshot, str) or not _DIGEST.fullmatch(snapshot): raise ValueError("An atom needs an immutable source snapshot") start, end = span["byte_range"] if type(start) is not int or type(end) is not int or start < 0 or end - start != len(body): @@ -125,7 +126,6 @@ def _snapshot(self, pin: AtomPin) -> tuple[Bundle, dict] | None: return None if qualified != pin.ref or held.metadata.get("id") != pin.ref.partition(":")[2]: return None - # Bind metadata, digest and delivered bytes to the same source snapshot. bundle = Bundle(held.metadata, dict(held.content), dict(held.dependencies)) view = bundle.view() return (bundle, view) if view["revision"] == pin.revision else None @@ -185,7 +185,10 @@ def include(group: Iterable[AtomUse]) -> GroupDelivery | None: if refusal is not None: omissions.append({"path": list(group[-1].path), "reason": refusal.receipt["status"]}) - records = [{"ref": pin.ref, "revision": pin.revision, "paths": via, **cached[pin][1]} + sealed = isinstance(self.source, InstalledGeneration) + records = [{"ref": pin.ref, "revision": pin.revision, "paths": via, + "source_range_verification": "verified_at_build" if sealed else "declared", + **cached[pin][1]} for pin, via in paths.items()] receipt = {"status": "delivered", "body_bytes": used_bytes, "delivered": records} if omissions: diff --git a/tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/SKILL.md b/tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/SKILL.md new file mode 100644 index 000000000..48542c287 --- /dev/null +++ b/tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/SKILL.md @@ -0,0 +1,605 @@ +--- +name: performance-ceiling-analysis +description: 'Estimate optimization headroom before modifying an inference system. Produces a three-level ceiling model (analytical, empirical component, end-to-end) and a prioritized measurement plan. Use to formulate acceptance targets when the user has not supplied them, assess a requested speedup, or identify the binding bottleneck. + + ' +metadata: + inferrsi: | + { + "schema_version": 1, + "status": "candidate", + "sources": [ + { + "url": "https://github.com/NVIDIA/TensorRT-LLM", + "commit": "f33e0e5fd55b", + "paths": [ + ".claude/skills/perf-analysis/SKILL.md", + ".claude/skills/perf-nsight-compute-analysis/references/roofline-analysis.md", + ".claude/skills/perf-workload-profiling/SKILL.md", + ".claude/skills/perf-optimization/SKILL.md", + ".claude/skills/perf-optimization-casebook/SKILL.md", + ".claude/skills/exec-env-check/SKILL.md", + ".claude/skills/exec-remote-slurm/SKILL.md", + ".claude/agents/perf-profiling-specialist.md" + ], + "type": "git", + "revision_precision": "prefix" + }, + { + "url": "https://github.com/hahnyuan/LLM-Viewer", + "commit": "1893e4b5705d", + "paths": [ + "roofline_model.py", + "model_analyzer.py", + "hardwares/hardware_params.py", + "configs/DiT.py" + ], + "type": "git", + "revision_precision": "prefix" + }, + { + "url": "https://github.com/ebugger/Empirical-Roofline-Toolkit", + "commit": "0771fa9621d0", + "paths": [ + "Empirical_Roofline_Tool-1.1.0/README.md", + "Empirical_Roofline_Tool-1.1.0/Drivers/driver1.c", + "Empirical_Roofline_Tool-1.1.0/Kernels/kernel1.c", + "Empirical_Roofline_Tool-1.1.0/Scripts/roofline.py" + ], + "type": "git", + "revision_precision": "prefix" + }, + { + "type": "paper", + "id": "usenix:fast25-qin", + "version": "FAST '25 proceedings, February 25-27, 2025, pp. 155-170", + "url": "https://www.usenix.org/system/files/fast25-qin.pdf", + "content_sha256": "543e56c541523c5e807d2231370f96749b2294bc901266397a7265b18ae2c130", + "sections": [ + "2.2, Table 1, Equations 1-2", + "3.1 and 5.3 (storage-scope limits only)" + ], + "readset": "references/mooncake-prefix-reuse-feasibility.md", + "license": "UNKNOWN" + }, + { + "type": "paper", + "id": "pmlr-v202-sheng23a", + "version": "ICML 2023 official ten-author edition, PMLR 202:31094-31116", + "url": "https://proceedings.mlr.press/v202/sheng23a/sheng23a.pdf", + "content_sha256": "7cd9673c37640011d38ef4b8595f5e1e09a85b1f803a3734f19c97ca66c75b9e", + "sections": [ + "1 and 3; 4.1-4.3, Figures 1-3, Algorithm 1, Equation 1", + "4.4 (scope boundary only); 6 and 6.1, Tables 2-3 (denominators and ablations)", + "Appendix A.3 selected cost/peak-memory formulas, PDF pages 15-17; A.2 ending only (theorem boundary)" + ], + "readset": "references/flexgen-offload-feasibility.md", + "license": "CC-BY-4.0" + }, + { + "type": "git", + "url": "https://github.com/shenh10/HuggingArch", + "commit": "facbbbc96856e558b9084a94a5070b2e2c86cf0b", + "paths": [ + "docs/validation.md", + "backend/arch/validate/_matching.py", + "backend/arch/validate/_weight_ledger.py", + "backend/arch/validate/_ablation.py", + "docs/parallelism.md", + "docs/evaluation_model.md", + "docs/measured_calibration.md", + "docs/known_limitations.md", + "kernel_bench/emit.py", + "backend/inference/op_calibration.py", + "backend/measure/scope.py", + "LICENSE" + ], + "readset": "references/huggingarch-checkpoint-anchor.md", + "identity": "references/huggingarch-source-identity.json", + "license": "MIT" + }, + { + "type": "document", + "url": "https://shenhan.cc/blog/huggingarch", + "displayed_publication_date": "2026-10-08", + "accessed": "2026-11-10", + "sha256": "31d0e0a9bbf9e32723fb6ab09179fbefb2fbba1043863f1475ecc7ea7ce24ed4", + "readset": "references/huggingarch-checkpoint-anchor.md", + "scope": "Live, unversioned companion post; sections 2.5, 2.6, 3.6 and 3.7 read from one retrieval, whose HTML bytes the sha256 identifies. Published before the pinned commit, so not attributable to it; figures absent from the repository are recorded as unverified.", + "license": "UNKNOWN" + }, + { + "type": "git", + "url": "https://github.com/xLLM-AI/xllm", + "commit": "90f6f13ea3d94334d4b5bd73d9fb23fc66bef1e4", + "paths": [ + "LICENSE", + "THIRDPARTYNOTICES.md", + "docs/src/content/docs/en/features/disagg_pd.md", + "docs/src/content/docs/en/hardware/ascend_npu.md", + "tests/core/scheduler/pd_scheduler_test.cpp", + "version.txt", + "xllm/core/disaggregation/pd_scheduler.cpp", + "xllm/core/disaggregation/pd_service_impl.cpp", + "xllm/core/scheduler/scheduler_factory.cpp", + "xllm/core/scheduler/scheduler_factory.h", + "xllm/core/scheduler/scheduler_policy.cpp" + ], + "readset": "references/xllm-pd-handoff.md", + "license": "Apache-2.0 with component-specific notices" + } + ], + "verification": { + "locally_verified": false, + "evidence_level": "source_grounded", + "note": "Historical repository methods plus reviewed paper extensions: references/papers-20261015/READSET.md records exact paper versions and inspection scope. Physical/conditional bounds, observed envelopes, simulator predictions and application measurements remain distinct. The bundled pure helper computes supplied L1 counts only; no automatic workload estimation, local accelerator measurements or E2E qualification. references/huggingarch-checkpoint-anchor.md records the checkpoint gates and the two-threshold rule from HuggingArch at a full commit, with per-file digests and inspection scope in references/huggingarch-source-identity.json; per-rank weight bytes are anchored only after the second gate passes." + }, + "applicability": { + "scope": "inference serving systems (LLM, diffusion, audio)", + "hardware": "any; CUDA examples from sources, NPU adaptation required", + "prerequisites": "profiler access (nsys/ncu or NPU equivalent), or willingness to work at L1 analytical only" + }, + "tags": [ + "performance", + "roofline", + "profiling", + "bottleneck", + "inference" + ], + "profile": "local-skill-v1", + "kind": "skill", + "origin": [ + "external" + ], + "empirical_validation": "not_run", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Acceptance-target preparation is agent guidance: the CLI and pure L1 helper do not infer gates, and unsupported estimates cannot replace user criteria or qualify campaign outcomes.", + "Mooncake's prefix-reuse condition is an analytical approximation; current cache validity, placement, effective rates, overlap and SLO outcomes remain unverified.", + "FlexGen's cross-tier feasibility comparison assumes fitted rates and perfect overlap; relaxed placements may OOM, the printed bls wording remains unresolved, and current compatibility, latency and efficacy are unverified.", + "The HuggingArch checkpoint anchor covers stored weights only. KV size and growth, activation traffic, collectives and end-to-end serving performance stay unanchored by it. Per-rank weight bytes stay unanchored until the second gate passes, and that gate checks the declared layout and format, not the placement a framework uses at run time." + ], + "provenance_readsets": [ + "references/flexgen-offload-feasibility.md", + "references/huggingarch-checkpoint-anchor.md", + "references/huggingarch-source-identity.json", + "references/mooncake-prefix-reuse-feasibility.md", + "references/papers-20261015/cases/decision-cases.md", + "references/papers-20261015/govern-optimization-experiments/procedure.md", + "references/papers-20261015/govern-optimization-experiments/references/source-notes.md", + "references/papers-20261015/INTEGRATION_NOTES.md", + "references/papers-20261015/knowledge/bounds-predictions-and-decisions.md", + "references/papers-20261015/MECHANISMS.md", + "references/papers-20261015/README.md", + "references/papers-20261015/READSET.md", + "references/papers-20261015/redirect-cross-layer-optimization/procedure.md", + "references/papers-20261015/redirect-cross-layer-optimization/references/source-notes.md", + "references/papers-20261015/references/agentic-kernel.md", + "references/papers-20261015/references/flashvector.md", + "references/papers-20261015/references/inferencebench.md", + "references/papers-20261015/references/prior-coverage.md", + "references/papers-20261015/references/vidur.md", + "references/papers-20261015/STATIC_CHECKS.md", + "references/xllm-pd-handoff.md" + ], + "consumption_mode": "packaged", + "recommendations": [ + "Use supplied acceptance criteria unchanged. When absent, follow references/acceptance-criteria.md to derive targets from matching baseline, calibrated attainable performance and uncertainty; retain partial requirements and label derived fields.", + "Read the full procedure and linked resources; preserve the distinction between analytical bounds, observed attainable envelopes, predictions and measured application outcomes." + ] + } +--- + +# Performance Ceiling Analysis + +Status: candidate. Procedures have not been evaluated against a real campaign. + +## When to use this skill + +Use this skill before modifying an inference serving system when you need to +answer: *does meaningful headroom exist, where is it, and is a requested +speedup such as 2× plausible?* + +When preparing a task, preserve user-provided acceptance criteria. If none were +supplied, follow [acceptance-criteria preparation](references/acceptance-criteria.md) +to derive and freeze targets from this analysis. Preserve partial requirements, +label derived fields and retain evidence gaps; a theoretical ceiling alone does +not establish an attainable target or a quality tolerance. + +Do not use it to benchmark or compare two already-built candidates — that is +the job of InferRSI's AB/BA harness and `rsi-evidence` skill. + +For whole-model prefill and decode composition, use [model-sol-analysis](../model-sol-analysis/SKILL.md). + +## Evidence to inspect first + +Before profiling, gather what you can analytically: + +1. Model architecture config (layer counts, hidden dims, attention heads, + batch sizes, sequence/frame lengths, codec/VAE structure). +2. Hardware specification: peak FP16/BF16/INT8 FLOP/s, peak memory bandwidth, + L2 size. For NVIDIA B300: INSUFFICIENT_EVIDENCE (no local datasheet values; + must be resolved via vendor documentation or an empirical measurement). +3. Existing benchmark numbers if available: throughput frames/s, TTFA p50/p95, + RTF mean. Label their provenance (author-reported, local measurement, etc.). +4. The checkpoint, whenever L1 prices weight traffic. Of the two gates in + [checkpoint anchoring](references/huggingarch-checkpoint-anchor.md), pass + Gate 1 before reporting any figure derived from weight bytes, and also + Gate 2 before reporting any per-rank or per-degree weight figure: + - **Gate 1, the per-tensor join.** Every tensor in the safetensors headers + must be selected by a name in the analysis, and every non-buffer name must + select a header tensor. Report both residuals. For each name, sum the stored + tensors that share it and compare physical elements with the header; a packed + format counts its container's elements. Only the byte totals, compared after + the join, switch to bytes. They are a checksum: equal totals do not pass a + join with a residual or a mismatch. + - **Gate 2, the per-rank weight ledger.** Gate 1 needs no layout, so passing + it says nothing about per-rank bytes. Before any per-rank or per-degree + weight figure, every stored weight needs a declared placement per stored axis + (replicated, or split on a named parallel world with its part count) and a + format. A degree that does not divide the part count follows a declared + policy: refuse, co-own or pad. Never substitute a divisor that divides. + Gate 2 checks the declared layout and format, not the placement a framework + uses at run time. + + A gate that cannot be judged, such as an unreadable header or a weight with no + placement, counts as failed; the dependent figure is `INSUFFICIENT_EVIDENCE`. + The anchor covers stored weights only. A sliding-window and a global attention + with the same head dimensions have byte-identical weights, so KV size and + growth need their own evidence. + +## Three-level ceiling model + +### L1 — Analytical ceiling + +Requires model config and a hardware table entry. A figure derived from weight +bytes additionally requires the checkpoint to pass Gate 1, the global per-tensor +join, which needs no parallelism layout. A per-rank or per-degree weight figure +also requires Gate 2, the per-rank weight ledger, which needs a declared layout. +Both gates are in item 4 of *Evidence to inspect first*; a gate that cannot be +judged leaves the dependent figure `INSUFFICIENT_EVIDENCE`. + +For supplied single-resource work/traffic counts, the bundled +[pure helper](scripts/roofline.py) implements the arithmetic under an explicit +[input/output contract and synthetic attachment example](references/roofline-contract.md). +It preserves sources and unknowns; it does not collect hardware facts, estimate +model work or establish attainable speedup, goal acceptance or E2E performance. + +For a remotely reusable input prefix, the +[Mooncake source comparison](references/mooncake-prefix-reuse-feasibility.md) +relates KV loading time to saved prefill work. Its paper-specific inequality +screens a candidate; current cache validity, effective rates, exposed costs and +service outcomes still require evidence. + +For disaggregated prefill and decode, the [xLLM handoff procedure](references/xllm-pd-handoff.md) separates prefill work saved through prefix reuse from decode-side reservation and KV transfer. Account for failed restoration before estimating headroom. + +For throughput-oriented offline inference with CPU/disk offload, use the +[FlexGen feasibility comparison](references/flexgen-offload-feasibility.md) to +check joint weights/KV/activation placement, resident plus working-memory peaks, +and exposed transfer/CPU costs against the latency objective. Its fitted, +overlap-dependent prediction is separate from the L1 helper and requires +current resource and execution evidence before a throughput recommendation. + +**FLOPs per forward pass:** + +For a linear projection of shape (batch × seq, in_channels, out_channels): +``` +FLOPs = 2 × batch × seq × in_channels × out_channels +``` +For multi-head attention QK projection + softmax + SV projection: +``` +FLOPs_QK = 2 × batch × heads × seq² × head_dim +FLOPs_SV = 2 × batch × heads × seq² × head_dim +FLOPs_attn ≈ 4 × batch × heads × seq² × head_dim +``` +For a DiT model, the dominant stages are the attention and MLP blocks inside +each transformer layer, plus the VAE encoder/decoder. LLM-Viewer's +`model_analyzer.py` (function `analyze_model`) walks each layer type and sums +FLOPs using these formulas. +Source: `hahnyuan/LLM-Viewer` @ 1893e4b5, `model_analyzer.py`. + +**Memory traffic per forward pass:** + +Traffic = bytes read (weights + KV) + bytes written (activations). For +inference with a frozen model, weight traffic dominates; KV cache traffic +dominates in decode-heavy workloads. Use bytes_per_element = 2 for FP16/BF16, +1 for INT8/FP8. + +**Arithmetic intensity (AI):** +``` +AI = FLOPs / bytes_transferred +``` + +**Roofline bound:** +``` +perf_roof = min(peak_FLOP_s, AI × peak_bandwidth) +ridge_point = peak_FLOP_s / peak_bandwidth # FLOP/byte +``` +If `AI < ridge_point` → memory-bound; if `AI > ridge_point` → compute-bound. + +**Adding a new hardware entry (NPU or B300):** +LLM-Viewer's `hardware_params.py` uses a flat dict keyed by device name. Each +entry requires: +```python +{ + "name": str, # display name + "peak_flops": float, # theoretical peak FLOP/s (FP16 or target dtype) + "memory_bandwidth": float, # peak DRAM bandwidth (bytes/s) + "memory_capacity": float, # total DRAM (bytes); optional +} +``` +All values must be FP16 (or the dtype you measure at). Use vendor datasheet +peaks. For empirically-measured roofs, see L2 below. +Source: `hahnyuan/LLM-Viewer` @ 1893e4b5, `hardwares/hardware_params.py`. + +**DiT vs decoder LLM differences:** +- DiT models process full-frame tokens in every denoising step, not a growing + KV cache. Sequence length is fixed (number of spatial tokens per frame). +- Each denoising step is a full forward pass; the performance measure is + steps/second × frames/step, or directly frames/second. +- The VAE decoder adds a significant one-time cost per output; it must be + included in the E2E breakdown (see L3). +- For an audio model such as fishaudio/drama-3, add vocoder/codec decode cost. +Source: `hahnyuan/LLM-Viewer` @ 1893e4b5, `configs/DiT.py`, `model_params/DiT.py`. + +**Known L1 limitations:** +- L1 uses vendor datasheet peaks as conditional bounds for a stated algorithm, + dtype, memory hierarchy and work/traffic count. No universal achievable + percentage follows; calibrate a workload-specific attainable envelope in L2. +- L1 treats the full model as one roof; it cannot distinguish kernel-level + variation, mixed operation-class throughput or scheduling overhead. Changing + the algorithm can change both work and traffic, so proximity to the old roof + does not rule out improvement. +- L1 never looks at the model again after counting, so a wrong count reaches the + floor unchallenged. The checkpoint gates (item 4 of *Evidence to inspect first*) anchor stored weight + bytes only. KV size and growth, activation traffic, collectives and achieved + rates stay unanchored by them. + +**Measurements against L1.** Reject a measured row only when it contradicts its +own record: its work over its time exceeds the peak it recorded, so its +numerator or its peak is wrong. A row faster than a separately computed L1 floor +is flagged, not rejected; re-derive the count (through the checkpoint gates) and +the peak (at the clock the device actually ran). Any tolerance for the flag +belongs to the acceptance issue. The source rule and its reading are in +[the two-threshold rule](references/huggingarch-checkpoint-anchor.md#which-bound-may-reject-a-measurement-the-two-threshold-rule). + +### L2 — Empirical component ceiling + +Requires hardware access. All values in this section are REMOTE MEASUREMENTS +to be taken; none can be filled in on a machine with no accelerator. + +**What to measure:** + +| Metric | Method | Required | +|--------|--------|---------| +| Empirical peak FLOP/s | ERT-style kernel sweep (see below) | REMOTE | +| Empirical peak memory bandwidth | ERT-style bandwidth kernel sweep | REMOTE | +| Kernel SOL% (Speed of Light) | nsys + ncu (CUDA) or vendor profiler (NPU) | REMOTE | +| SM/CU occupancy | ncu `sm__warps_active` or vendor equivalent | REMOTE | +| L1/L2/DRAM bandwidth per kernel | ncu hierarchical roofline section | REMOTE | +| Host-GPU/CPU-NPU transfer time | profiler timeline | REMOTE | + +**Empirical peak measurement procedure (ERT method):** +The Empirical Roofline Toolkit (ERT) measures peak FLOP/s by running a FMA +loop kernel with variable trial counts; the alpha-update `alpha *= (1 - 1e-8)` +prevents compiler elimination. Peak is the maximum observed across a sweep of +working-set sizes and GFlops configurations. The config file (`Config/`) must +supply: compiler, GPU/NPU API, working set range, number of ERT trials, output +directory. For NPU, the `driver1.c` CUDA kernel must be ported to the vendor +compute API (CANN, Triton-Ascend, etc.); this is an open design decision. +Source: `ebugger/Empirical-Roofline-Toolkit` @ 0771fa9621d0, +`Empirical_Roofline_Tool-1.1.0/Drivers/driver1.c`, +`Empirical_Roofline_Tool-1.1.0/Scripts/roofline.py`. + +**Bottleneck classification from profiler counters (CUDA / Nsight Compute):** + +| Counter / metric | Bottleneck | +|-----------------|-----------| +| Memory SOL% high, Compute SOL% low | memory-bound | +| Compute SOL% high, Memory SOL% low | compute-bound | +| Both SOL% low, many small kernels, high CPU time | launch-overhead | +| Both SOL% low, significant collective operation time | communication-bound | +| Both SOL% low, excessive CPU-GPU sync events | sync-bound | + +SOL% (Speed of Light %) = actual throughput / hardware peak throughput × 100. +Source: `NVIDIA/TensorRT-LLM` @ f33e0e5f, +`.claude/skills/perf-analysis/SKILL.md`, +`.claude/skills/perf-nsight-compute-analysis/references/roofline-analysis.md`. + +### L3 — End-to-end ceiling + +Requires at minimum wall-clock tracing of each stage. + +**Stage breakdown for a diffusion serving system:** + +| Stage | What to measure | Can be estimated? | +|-------|----------------|-------------------| +| Request scheduling | Time from request arrival to first GPU submission | CPU timer | +| Prefill (prompt encode) | Conditional encode time | profiler | +| Denoising steps | Per-step time × num_steps | profiler | +| Attention per step | QKV projection + attention kernel time | profiler | +| MLP per step | Linear projection time | profiler | +| AdaLN/conditioning | Conditioning injection time | profiler | +| VAE decode | VAE decoder latency | profiler | +| Audio/vocoder | Vocoder/codec decode time | profiler | +| Communication (multi-device) | NCCL/HCCL allreduce time | profiler | +| Serialization/transfer | Token/frame encode, network send time | profiler | +| Idle gaps | GPU idle between requests | profiler | + +**Amdahl-style speedup formula:** + +Given per-stage fractions of total time f_i (Σ f_i = 1), and a speedup s_i +achievable on each stage: +``` +S_total = 1 / Σ_i (f_i / s_i) +``` + +Headroom attributed to stage i: +``` +H_i = f_i × (1 - 1/s_i) # fraction of total time recovered if s_i is achieved +``` + +Example (INSUFFICIENT_EVIDENCE — all values are placeholders): +If denoising steps = 70% of time with achievable speedup 1.4×, VAE = 15% with +1.2×, scheduling = 10% at 1.0×, other = 5% at 1.0×: +``` +S = 1 / (0.70/1.4 + 0.15/1.2 + 0.10/1.0 + 0.05/1.0) = 1.26× +``` +Without real profiling, this formula cannot produce a trustworthy number. + +## Escalation rule: L1 → L2 → L3 + +Escalate from L1 to L2 when: +- The L1 roof predicts headroom but you cannot determine whether the system is + memory-bound or compute-bound analytically (AI is near the ridge point). +- You need to confirm that a specific kernel is the bottleneck before + committing to an optimization. + +Escalate from L2 to L3 when: +- Kernel-level L2 measurements show individual kernels near their ceilings + but E2E throughput is still lower than expected (scheduler, communication, + or serialization losses). +- A single stage (e.g. VAE decode) dominates the Amdahl estimate and you need + its real fraction. + +Do not escalate unless the question requires it. L1 alone is often enough to +decide whether a 2× claim is plausible. + +## How to express uncertainty + +Never report a single speedup number without stating: +- Which ceiling level the estimate comes from (L1/L2/L3). +- The evidence basis: source-grounded analysis, author-reported, CPU test, + device measurement, or end-to-end measurement. +- The assumptions (hardware peaks, stage fractions, whether profiler numbers + came from the actual deployment configuration). +- A range: if stage fractions are ±20%, compute the best-case and worst-case + Amdahl speedup explicitly. + +Mark any empirical field as `INSUFFICIENT_EVIDENCE` when no accelerator +measurement exists. Do not interpolate from a different hardware SKU. + +## Measurement plan: drama-3 / B300 case + +This is a plan only. No empirical values exist on the local machine. +All "REMOTE" fields require execution on the target B300 system. + +```yaml +baseline: + model: fishaudio/drama-3 # diffusion audio/speech model + engines: + - vLLM-Omni (revision: TBD, freeze before measurement) + - SGLang-Omni (revision: TBD, freeze before measurement) + hardware: single NVIDIA B300 + concurrency_levels: [1, 2, 4, 8, 16] # to be determined from capacity + +workload: + metrics: + - throughput_frames_per_s + - ttfa_p50_ms + - ttfa_p95_ms + - rtf_mean + repetitions: ≥3 per concurrency level + warmup: required; exclude from statistics + +analytical_roof: + status: INSUFFICIENT_EVIDENCE + blocker: B300 peak FP16 FLOP/s and memory bandwidth not on this machine + action: resolve from NVIDIA B300 datasheet or measure empirically via ERT + +empirical_roof: + status: INSUFFICIENT_EVIDENCE + action: > + REMOTE: run ERT-style FMA kernel sweep on B300; record empirical peak + FLOP/s and peak memory bandwidth; compare to datasheet; record achievable + fraction for this workload, without assuming a universal percentage. + +stage_breakdown: + status: INSUFFICIENT_EVIDENCE + action: > + REMOTE: run nsys to capture full timeline; extract per-stage wall-clock + fractions for denoising, VAE, conditioning, communication, scheduling, + idle. Report as f_i values for Amdahl formula. + +bottlenecks: + status: INSUFFICIENT_EVIDENCE + action: > + REMOTE: run ncu on the denoising kernel and VAE kernel; record SOL%, + arithmetic intensity, bottleneck classification, occupancy. + +headroom: + speedup_range: INSUFFICIENT_EVIDENCE + action: compute Amdahl S_total from measured f_i and achievable s_i + +target_feasibility: + verdict: INSUFFICIENT_EVIDENCE + note: > + A 2× E2E speedup requires either the dominant stage (likely denoising) + to achieve >2× improvement (which implies near-doubling compute or + memory efficiency), or several stages together to contribute. This is + analytically possible but cannot be confirmed without stage fractions. + +recommended_experiments: + - hypothesis: Denoising step is memory-bound; fusing AdaLN conditioning + reduces memory traffic. + evidence: INSUFFICIENT_EVIDENCE (measure AI and SOL% first) + expected_gain: unknown + measurement: REMOTE — ncu AI vs ridge point on denoising kernel + priority: 1 + + - hypothesis: VAE decode fraction is significant; offloading or tiling + reduces peak latency. + evidence: INSUFFICIENT_EVIDENCE (measure VAE fraction of E2E first) + expected_gain: unknown + measurement: REMOTE — nsys stage fraction for VAE decode + priority: 2 + + - hypothesis: Multi-engine scheduling introduces idle gaps at concurrency>1. + evidence: INSUFFICIENT_EVIDENCE + measurement: REMOTE — nsys idle gap analysis at concurrency 4 and 8 + priority: 3 +``` + +## How to decide whether further optimization is worthwhile + +1. Compare the conditional Amdahl headroom with the actual target and measured + uncertainty. Use nonoverlapping exposed-time fractions; a sum of overlapping + kernel durations is not an end-to-end decomposition. +2. Check the dominant stage against operation-specific attainable envelopes. + High utilization can constrain local tuning of the current algorithm while + fusion, materialization removal, work ownership or a different algorithm + changes its work and traffic. No universal SOL% cutoff establishes saturation. +3. Treat low utilization as a question: distinguish work supply, scalar versus + matrix work, dependency stalls, launch overhead and memory movement before + selecting a change. Occupancy, throughput and utilization are different metrics. +4. Keep four evidence types separate: physical/conditional bound, observed + attainable envelope, empirical simulator prediction, and measured application + outcome. A predictor needs a matching calibration domain and held-out load + coverage, especially near capacity; prediction error does not establish a bound. +5. Redirect when the expected removable time cannot exceed locally measured + noise, or when a change exposes a new owner. Preserve a valid incumbent and + verify the final artifact under the application objective and all SLOs. + +### Reviewed paper resources + +The [modeling comparison](references/papers-20261015/MECHANISMS.md), +[exact readset](references/papers-20261015/READSET.md), +[bounds and predictions](references/papers-20261015/knowledge/bounds-predictions-and-decisions.md), +[cross-layer procedure](references/papers-20261015/redirect-cross-layer-optimization/procedure.md) +and [decision cases](references/papers-20261015/cases/decision-cases.md) retain +paper-specific costs, counter-signals and unresolved metric discrepancies. +Use [simulator calibration](../calibrate-serving-simulation/SKILL.md) for a +prediction-based shortlist and [attention diagnosis](../../../systems/platforms/cuda/diagnose-attention-bottlenecks/SKILL.md) +for algorithm/operation-class changes. These remain candidate guidance, not local +performance measurements. The bundled helper only computes explicitly supplied +L1 inputs under the contract above. + +### Reviewed implementation source + +[Checkpoint anchoring](references/huggingarch-checkpoint-anchor.md) distills the +checkpoint gates and the two-threshold rule from HuggingArch's validator and +measured calibration, read at one full commit. The +[source identity record](references/huggingarch-source-identity.json) gives each +file's digests and the part that was read. Claims carry `[code]`, `[doc]`, +`[tree]` or `[blog]` markers with locators. HuggingArch was not run, and no +predicted figure was compared with a measurement. diff --git a/tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/references/acceptance-criteria.md b/tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/references/acceptance-criteria.md new file mode 100644 index 000000000..9a29ebeda --- /dev/null +++ b/tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/references/acceptance-criteria.md @@ -0,0 +1,94 @@ +# Establish acceptance criteria before search + +Use this procedure when preparing an inference-optimization task. The agent +resolves criteria and writes the campaign contract; the CLI does not invoke a +skill or infer thresholds when a flag is omitted. + +## Select the source + +1. Read the user's request and any referenced acceptance issue or frozen plan. + **Use supplied criteria unchanged:** retain metrics, units, timing boundaries, + statistics, workload coverage, thresholds and quality/resource constraints. + An estimate may flag an infeasible target but must not replace or relax it. + Conflicting requests and frozen records need resolution by their authorized + owner; do not choose whichever target is easier to pass. +2. If criteria are absent, use [performance-ceiling-analysis](../SKILL.md) to + formulate workload-specific acceptance criteria before candidate search. + Retain partial requirements: derive only missing performance targets and + measurement details, labelling each derived field separately. An unspecified + primary objective that cannot be resolved from task context is a missing + input, not permission to optimize a different objective. +3. Reuse the target's existing correctness/quality contract and retain baseline + semantics. Hardware ceilings cannot determine quality tolerances, an + application SLO or permission to change precision, steps or useful work. + Resolve missing quality requirements from the task and reference validators; + if still unknown, record the gap rather than invent a tolerance. + +Do not add a confirmation round when the user has already delegated goal +formulation and campaign preparation. Use the existing freeze authority; record +agent-derived targets as such, never as user-supplied or user-confirmed numbers. + +## Derive a target when none was supplied + +1. Establish the model, exact hardware/resources, workload, objective and timing + boundary. Measure a comparable baseline and its variation; keep profiler runs + separate from acceptance timing. Collect only within the authorized budget. +2. Apply the skill's analytical, empirical-component and end-to-end levels as + needed. Preserve sources, scope, assumptions and unknowns. These ceiling + levels are distinct from the repository's L0–L4 validation ladder. A pure L1 + Roofline result is a conditional bound, not an attainable service target. +3. Estimate an attainable range using matching component measurements and + exposed critical-path costs. For a serial latency decomposition with + nonoverlapping fractions `f_i` and supported stage speedups `s_i`, compute + `S = 1 / sum(f_i / s_i)` across the uncertainty range. Include unchanged + stages with `s_i = 1`. Overlap, queueing and bottleneck migration require the + corresponding critical-path/capacity analysis instead of summing durations. +4. Choose a conservative target supported by that attainable range and separated + from measured baseline noise. Explain the selected point and any margin in + terms of calibration evidence and the task budget; no universal fraction of + peak or fixed improvement percentage applies. For baseline latency `T0` and + a justified target speedup `S_target`, the absolute target is + `T0 / S_target`, and the relative reduction is `100 * (1 - 1 / S_target)`. + State whether the contract requires an absolute target, a relative gain or + both. A throughput target needs evidence for its own workload and load regime; + do not infer it by inverting service latency. +5. Define the per-workload combination rule, quality checks, guard metrics, + repetitions/statistics and stopping conditions. If no positive target can be + distinguished from noise, retain the incumbent and identify the next useful + calibration or report insufficient headroom. Do not turn that into PASS. + +Missing inputs required by the selected analysis or acceptance contract remain +`INSUFFICIENT_EVIDENCE` in the analysis and `INCONCLUSIVE` for campaign acceptance. +For example, analytical work/traffic bounds need model counts; a supported +empirical stage estimate need not. Comparable baseline, calibration, uncertainty +and quality coverage are still needed for a derived acceptance target. List the +missing measurements and their bounded cost. +Continue authorized preparation/calibration, but do not freeze a made-up number +or start candidate search under unresolved gates. Never use a similar SKU, the +CLI's default threshold, a theoretical maximum or a later candidate result to +fill the gap. + +## Record and freeze the contract + +Write the result into the existing acceptance issue and campaign plan, not a +second goal registry. Record: + +- source per criterion: `user` or `ceiling-derived`, with the request/plan + reference; use `mixed` for a contract retaining both; +- metric, unit, direction, statistic, timing boundary and each workload target; +- baseline identity and samples, analysis/skill revision, input sources, + attainable range, uncertainty and the reason for the selected target; +- quality/resource constraints, required validation coverage, evidence gaps, + budget/stop conditions and who has authority to freeze the contract. + +Freeze the resolved contract and validator/input hashes before candidate search. +Existing frozen campaigns retain their criteria. Changing a frozen goal follows +the campaign's revision policy and preserves prior evidence; it cannot +retroactively qualify an earlier result. + +Map a resolved relative primary-metric target to `--metric-key`, `--metric-unit`, +`--direction`, `--comparison-scope` and `--min-improvement-pct`. Put quality and +additional campaign gates in the appropriate validators; the generic evaluator +does not automatically enforce absolute targets or a multi-workload contract. +`plan` is a preview, not a freeze or a full campaign acceptance check. Only +complete measured evidence satisfying the frozen gates can establish PASS. diff --git a/tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/references/roofline-example.json b/tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/references/roofline-example.json new file mode 100644 index 000000000..de06fdbdf --- /dev/null +++ b/tests/fixtures/atomic-reader/release-v0.3.4/src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/references/roofline-example.json @@ -0,0 +1,72 @@ +{ + "workload": { + "workload_id": "synthetic-component-v1", + "shape": "one synthetic matrix operation", + "boundary": "one invocation; stated compute and HBM traffic only", + "hardware_id": "synthetic-reference", + "resource_scope": "logical-device-0", + "operation": { + "dtype": "bfloat16", + "accumulator_dtype": "float32", + "op_class": "matrix", + "sparsity": "dense", + "fma_flops": 2 + }, + "work": { + "value": 600, + "unit": "FLOP", + "source": { + "kind": "synthetic", + "locator": "fixture:roofline-example", + "revision": "v1", + "time_unknown_reason": "Undated synthetic arithmetic fixture" + } + }, + "traffic": { + "value": 100, + "unit": "byte", + "tier": "HBM", + "source": { + "kind": "synthetic", + "locator": "fixture:roofline-example", + "revision": "v1", + "time_unknown_reason": "Undated synthetic arithmetic fixture" + } + }, + "assumptions": ["Counts are synthetic and apply only to this stated invocation."] + }, + "hardware": { + "hardware_id": "synthetic-reference", + "resource_scope": "logical-device-0", + "device_count": 1, + "operation": { + "dtype": "bfloat16", + "accumulator_dtype": "float32", + "op_class": "matrix", + "sparsity": "dense", + "fma_flops": 2 + }, + "peak_compute": { + "value": 100, + "unit": "FLOP/s", + "source": { + "kind": "synthetic", + "locator": "fixture:roofline-example", + "revision": "v1", + "time_unknown_reason": "Undated synthetic arithmetic fixture" + } + }, + "bandwidth": { + "value": 10, + "unit": "byte/s", + "tier": "HBM", + "source": { + "kind": "synthetic", + "locator": "fixture:roofline-example", + "revision": "v1", + "time_unknown_reason": "Undated synthetic arithmetic fixture" + } + }, + "assumptions": ["Rates are synthetic references, not measured or rated device facts."] + } +} diff --git a/tests/fixtures/atomic_composition.py b/tests/fixtures/atomic_composition.py index cff715184..ea4adf806 100644 --- a/tests/fixtures/atomic_composition.py +++ b/tests/fixtures/atomic_composition.py @@ -48,7 +48,6 @@ def case_fixture(store): body = attachment + bytes([index]) source, start = body, 0 else: - # A byte span from the original JSON, pinned before content projection. path = "case.json" body = json.dumps(finding, ensure_ascii=False).encode() source = document diff --git a/tests/knowledge/test_atomic_generation.py b/tests/knowledge/test_atomic_generation.py index a6bedd55d..6f2c337f0 100644 --- a/tests/knowledge/test_atomic_generation.py +++ b/tests/knowledge/test_atomic_generation.py @@ -1,6 +1,7 @@ import hashlib import json from concurrent.futures import ThreadPoolExecutor +from functools import partial from pathlib import Path import pytest @@ -10,7 +11,10 @@ from inferrsi.knowledge.atomic_reader import AtomicReader, AtomPin from inferrsi.knowledge.knowledge_operations import Bundle, UnavailableRevision, _json from tests.fixtures.atomic_composition import composition, metadata, node -from tests.knowledge.test_atomic_reader import allow, excerpt +from tests.knowledge.test_atomic_reader import RELEASE, UPSTREAM, allow, excerpt + +RELEASE_ROOT = Path(__file__).resolve().parents[1] / "fixtures/atomic-reader/release-v0.3.4" +build_release = partial(build_generation, source_roots={RELEASE: RELEASE_ROOT}) def write_json(path, obj): @@ -61,7 +65,7 @@ def author_root(tmp_path): for skill_name in sorted(PUBLIC_TASKS | {"analysis-example"}): fields = composition(nodes, routes).metadata fields["id"] = "entry-" + skill_name - del fields["entrypoint"] # Single authored file for a navigation composition. + del fields["entrypoint"] fields["composition"]["skill"] = { "name": skill_name, "description": "Inspect the fixture.", "body": "navigation", "resources": {"references/criteria.md": "ceiling-l2", @@ -77,10 +81,10 @@ def file_bytes(root: Path): def test_same_source_builds_byte_identical_catalog_skills_and_pinned_reader(author_root, tmp_path): first, second = tmp_path / "install-a", tmp_path / "install-b" - generation = build_generation(author_root, first, permits=allow) - assert build_generation(author_root, second, permits=allow) == generation + generation = build_release(author_root, first, permits=allow) + assert build_release(author_root, second, permits=allow) == generation assert file_bytes(first) == file_bytes(second) - assert build_generation(author_root, first, permits=allow) == generation + assert build_release(author_root, first, permits=allow) == generation assert not list(author_root.rglob("SKILL.md")) assert not list(first.rglob("skill-index.json")) installed = InstalledGeneration(first, expected=generation) @@ -101,6 +105,8 @@ def test_same_source_builds_byte_identical_catalog_skills_and_pinned_reader(auth chosen = reader.read_selection(ref, **request) assert [len(body) for body in chosen.bodies] == [845, 1538] assert chosen.receipt["body_bytes"] == 2383 + assert all(item["source_range_verification"] == "verified_at_build" + for item in chosen.receipt["delivered"]) short = reader.read_selection(ref, **{**request, "max_bytes": 2382}) assert short.receipt["status"] == "over_budget" and not short.bodies with pytest.raises(UnavailableRevision): @@ -116,7 +122,7 @@ def test_host_procedure_assembles_pinned_sections_without_changing_l0(author_roo skill["resources"]["references/acceptance-criteria.md"] = "ceiling-l2" write_json(descriptor, spec) destination = tmp_path / "install" - build_generation(author_root, destination, permits=allow) + build_release(author_root, destination, permits=allow) installed = InstalledGeneration(destination) ref = installed.tasks["task-debug"] navigation = AtomicReader(installed, permits=allow).read_selection( @@ -132,7 +138,7 @@ def test_host_procedure_assembles_pinned_sections_without_changing_l0(author_roo @pytest.mark.parametrize("change", [ "missing task", "missing revision", "retain", "license", "policy", "outside", "alias", "wrong layer", "incomplete skill", "missing relative link", - "undeclared section", "repeated section", "missing section link", + "undeclared section", "repeated section", "missing section link", "no license", ]) def test_invalid_candidate_publishes_no_partial_tree(author_root, tmp_path, change): descriptor = author_root / "compositions/task-debug.json" @@ -148,6 +154,8 @@ def test_invalid_candidate_publishes_no_partial_tree(author_root, tmp_path, chan dec["permissions"]["retain"] = False elif change == "license": dec["license"] = "NOASSERTION" + elif change == "no license": + dec["license"] = "NO_LICENSE" elif change == "wrong layer": dec["routes"]["rules"]["required"] = ["attachment"] elif change == "incomplete skill": @@ -169,22 +177,22 @@ def policy(pin, op): return not (change == "policy" and pin.ref == "package:ceiling-l1" and op == "redistribute") with pytest.raises((ValueError, PermissionError)): - build_generation(author_root, tmp_path / "generation", permits=policy) + build_release(author_root, tmp_path / "generation", permits=policy) assert not (tmp_path / "generation").exists() def test_pinned_history_survives_new_build_and_mixed_install_is_rejected(author_root, tmp_path): first, second = tmp_path / "release-a", tmp_path / "release-b" - old_id = build_generation(author_root, first, permits=allow) + old_id = build_release(author_root, first, permits=allow) original = InstalledGeneration(first) spec = author_root / "compositions/task-debug.json" obj = json.loads(spec.read_bytes()) obj["metadata"]["limitations"] = ["revision B"] write_json(spec, obj) - new_id = build_generation(author_root, second, permits=allow) + new_id = build_release(author_root, second, permits=allow) assert new_id != old_id with pytest.raises(UnavailableRevision): - build_generation(author_root, first, permits=allow) + build_release(author_root, first, permits=allow) new = InstalledGeneration(second) ref = original.tasks["task-debug"] revision = original.catalog[ref]["revision"] @@ -200,14 +208,14 @@ def test_pinned_history_survives_new_build_and_mixed_install_is_rejected(author_ def test_concurrent_identical_builders_share_one_complete_destination(author_root, tmp_path): destination = tmp_path / "generation" with ThreadPoolExecutor(max_workers=2) as pool: - first, second = [pool.submit(build_generation, author_root, destination, permits=allow) + first, second = [pool.submit(build_release, author_root, destination, permits=allow) for _ in range(2)] assert first.result() == second.result() == InstalledGeneration(destination).generation def test_installed_catalog_must_match_the_exporter_even_if_resealed(author_root, tmp_path): destination = tmp_path / "generation" - build_generation(author_root, destination, permits=allow) + build_release(author_root, destination, permits=allow) path = destination / SEAL seal = json.loads(path.read_bytes()) del seal["generation"] @@ -216,3 +224,38 @@ def test_installed_catalog_must_match_the_exporter_even_if_resealed(author_root, path.write_bytes(_json(seal)) with pytest.raises(ValueError, match="composition exports"): InstalledGeneration(destination) + + +def test_same_length_shift_cannot_publish_a_false_source_range(author_root, tmp_path): + descriptor = author_root / "atoms/ceiling-l1.json" + spec = json.loads(descriptor.read_bytes()) + span = spec["metadata"]["atom"]["source_span"] + start, end = span["byte_range"] + original = (RELEASE_ROOT / span["path"]).read_bytes() + body = (author_root / "atoms/inputs/ceiling-l1").read_bytes() + assert original[start:end] == body and original[start + 1:end + 1] != body + span["byte_range"] = [start + 1, end + 1] + write_json(descriptor, spec) + changed = Bundle(spec["metadata"], {"rule.md": body}, {}) + for path in (author_root / "compositions").glob("*.json"): + composition_spec = json.loads(path.read_bytes()) + nodes = composition_spec["metadata"]["composition"]["nodes"] + nodes["ceiling-l1"]["revision"] = changed.revision + write_json(path, composition_spec) + with pytest.raises(ValueError, match="pinned source range"): + build_release(author_root, tmp_path / "install", permits=allow) + assert not (tmp_path / "install").exists() + + +def test_pinned_source_checks_the_complete_file_and_its_immutable_root(author_root, tmp_path): + alternate = tmp_path / "wrong-release" + path = UPSTREAM + "SKILL.md" + old = (RELEASE_ROOT / path).read_bytes() + (alternate / path).parent.mkdir(parents=True) + (alternate / path).write_bytes(b"X" + old[1:]) + destination = tmp_path / "install" + for roots, reason in (({RELEASE: alternate}, "Complete pinned source file differs"), + ({"0" * 40: RELEASE_ROOT}, "Missing pinned source root")): + with pytest.raises(ValueError, match=reason): + build_generation(author_root, destination, source_roots=roots, permits=allow) + assert not destination.exists() diff --git a/tests/knowledge/test_atomic_reader.py b/tests/knowledge/test_atomic_reader.py index 9322fec14..ab6f8a123 100644 --- a/tests/knowledge/test_atomic_reader.py +++ b/tests/knowledge/test_atomic_reader.py @@ -7,12 +7,16 @@ from inferrsi.knowledge.knowledge_operations import Bundle, UnavailableRevision from inferrsi.knowledge.knowledge_store import KnowledgeStore -# Exact UTF-8 byte ranges in the v0.3.4 release, frozen in #713. FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "atomic-reader" UPSTREAM = ( "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/performance-ceiling-analysis/" ) RELEASE = "e2f3be102c66c358803ed2186ed67bf627ebcbdf" +SOURCE_DIGESTS = { + "L1": "baeab73fb1fbf09da6ae0930b380720c66d9dc8085f8ccd1fb61381bb894799f", + "L2": "e96efc42005af591a87b57dd6f1e9bffa8e351bcd023bd093ac37239a0486638", + "L3": "597cd3205df043cff3ae9d15924c77934e8d8eb300c00c4840f6bb2921f90faf", +} EXCERPTS = { "L1": ( "rule.md", "SKILL.md", 10266, 11111, @@ -37,7 +41,7 @@ def excerpt(layer): "state": "candidate", "applicability": {}, "limitations": [], "sources": [{ "type": "git", "url": "https://github.com/InferMatrixLab/InferRSI", - "commit": RELEASE, + "commit": RELEASE, "path": UPSTREAM + path, "sha256": SOURCE_DIGESTS[layer], }], "attribution": "InferMatrixLab/InferRSI", "atom": { @@ -95,6 +99,7 @@ def test_required_paths_share_bytes_and_receipts_reopen_the_exact_version(): assert record["layer"] == level and record["bytes"] == end - start assert record["source"]["commit"] == RELEASE and record["source_path"] == UPSTREAM + path assert record["source_byte_range"] == [start, end] + assert record["source_range_verification"] == "declared" assert record["source_sha256"] == record["sha256"] == hashlib.sha256(body).hexdigest() assert record["sha256"] == digest _, pinned = source.read_resolved(record["ref"], revision=record["revision"]) From b7939b24b868c815786927e96a9a1f90f12ae2b1 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:09:39 +0800 Subject: [PATCH 7/8] Require a caller-pinned release for build-verified source receipts Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/guides/knowledge/knowledge-layout.md | 15 ++++++++------ src/inferrsi/knowledge/atomic_generation.py | 8 +++++++- src/inferrsi/knowledge/atomic_reader.py | 4 ++-- tests/knowledge/test_atomic_generation.py | 22 +++++++++++++++++++++ 4 files changed, 40 insertions(+), 9 deletions(-) diff --git a/docs/guides/knowledge/knowledge-layout.md b/docs/guides/knowledge/knowledge-layout.md index 9accaa348..d8e5d85f6 100644 --- a/docs/guides/knowledge/knowledge-layout.md +++ b/docs/guides/knowledge/knowledge-layout.md @@ -32,8 +32,9 @@ by its JSON pointer at the requested revision. file against `sources[index].sha256` and compares the declared slice with the atom's actual bytes. A content-addressed atom containing its complete file at offset zero carries its own snapshot. The reader records `verified_at_build` - for a sealed format-2 generation and `declared` for source ranges supplied - by a store or another reader. Its Bundle revision covers metadata and resources. + when the caller pins the installed generation to an ID from a trusted release + record. An install opened without that pin, or an ordinary store, returns + `declared`. Its Bundle revision covers metadata and resources. - `metadata.composition` declares named `nodes` (qualified ref, exact revision, required prerequisite nodes), `routes` (layer, required and optional roots, conditions, finding, conflicts and superseded routes), and its grants and @@ -49,10 +50,12 @@ by its JSON pointer at the requested revision. - The installer writes `knowledge/{atoms,compositions}/`, the generated catalog and file digests in `knowledge/generation.json`, and `skills//SKILL.md` with the declared references, assets and scripts. Two builds of the same - input yield the same generation ID. `InstalledGeneration(root, expected=...)` - verifies the complete installed tree before exposing its `tasks`, `skills`, - `catalog` or `read_resolved` interface. A prior generation directory can - reopen its own receipts. + input yield the same generation ID. `InstalledGeneration(root)` verifies the + complete tree against its own seal before exposing `tasks`, `skills`, + `catalog` or `read_resolved`. To attest the build, obtain the expected ID + independently of the installation (for example from the trusted release + record) and open `InstalledGeneration(root, expected=release_id)`. An ID + mismatch refuses the open. A prior generation can reopen its own receipts. - Ordinary callers use `apps.workflows.knowledge.read_selection(source, ref, permits=..., revision=..., layer=..., finding=..., context=..., max_bytes=...)`. Managed optimization uses `apps.workflows.campaign.capture_selection(root, diff --git a/src/inferrsi/knowledge/atomic_generation.py b/src/inferrsi/knowledge/atomic_generation.py index 99d4931a2..30d7b6aa2 100644 --- a/src/inferrsi/knowledge/atomic_generation.py +++ b/src/inferrsi/knowledge/atomic_generation.py @@ -46,7 +46,7 @@ def inventory(root: Path) -> dict[str, bytes]: class InstalledGeneration: - """A verified snapshot. An open reader keeps its bytes across later installations.""" + """An internally consistent snapshot, optionally pinned by its caller's release record.""" def __init__(self, root: Path, *, expected: str | None = None): root = Path(root).resolve(strict=True) @@ -83,6 +83,12 @@ def __init__(self, root: Path, *, expected: str | None = None): exports[name] = ref if exports != self._skills or PUBLIC_TASKS - exports.keys(): raise ValueError("Installed skill catalog differs from the public composition exports") + self._release_pinned = expected is not None + + @property + def release_pinned(self) -> bool: + """Whether this installation matched a generation ID supplied by the caller.""" + return self._release_pinned @property def catalog(self) -> dict: diff --git a/src/inferrsi/knowledge/atomic_reader.py b/src/inferrsi/knowledge/atomic_reader.py index 49c2b8f92..0a44e84ae 100644 --- a/src/inferrsi/knowledge/atomic_reader.py +++ b/src/inferrsi/knowledge/atomic_reader.py @@ -185,9 +185,9 @@ def include(group: Iterable[AtomUse]) -> GroupDelivery | None: if refusal is not None: omissions.append({"path": list(group[-1].path), "reason": refusal.receipt["status"]}) - sealed = isinstance(self.source, InstalledGeneration) + pinned = isinstance(self.source, InstalledGeneration) and self.source.release_pinned records = [{"ref": pin.ref, "revision": pin.revision, "paths": via, - "source_range_verification": "verified_at_build" if sealed else "declared", + "source_range_verification": "verified_at_build" if pinned else "declared", **cached[pin][1]} for pin, via in paths.items()] receipt = {"status": "delivered", "body_bytes": used_bytes, "delivered": records} diff --git a/tests/knowledge/test_atomic_generation.py b/tests/knowledge/test_atomic_generation.py index 6f2c337f0..280707b0b 100644 --- a/tests/knowledge/test_atomic_generation.py +++ b/tests/knowledge/test_atomic_generation.py @@ -114,6 +114,28 @@ def test_same_source_builds_byte_identical_catalog_skills_and_pinned_reader(auth revision=entry["revision"]) +def test_source_attestation_needs_the_callers_release_pin(author_root, tmp_path): + destination = tmp_path / "install" + release_id = build_release(author_root, destination, permits=allow) + pinned = InstalledGeneration(destination, expected=release_id) + unpinned = InstalledGeneration(destination) + ref = pinned.tasks["task-debug"] + request = dict(revision=pinned.catalog[ref]["revision"], layer="L2", max_bytes=2383, + context={"query": "acceptance criteria"}) + attested = AtomicReader(pinned, permits=allow).read_selection(ref, **request) + declared = AtomicReader(unpinned, permits=allow).read_selection(ref, **request) + assert attested.bodies == declared.bodies + assert [len(body) for body in attested.bodies] == [845, 1538] + verified = attested.receipt["delivered"] + assert [item["source_range_verification"] for item in verified] == ["verified_at_build"] * 2 + assert declared.receipt == { + **attested.receipt, + "delivered": [{**item, "source_range_verification": "declared"} for item in verified], + } + with pytest.raises(UnavailableRevision): + InstalledGeneration(destination, expected="sha256:" + "0" * 64) + + def test_host_procedure_assembles_pinned_sections_without_changing_l0(author_root, tmp_path): descriptor = author_root / "compositions/task-debug.json" spec = json.loads(descriptor.read_bytes()) From 495124a2637559a00d1e68a03cc6f7efe8eb0f99 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:48:40 +0800 Subject: [PATCH 8/8] Attest independently verified source ranges per installed atom Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (implementation) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/guides/knowledge/knowledge-layout.md | 7 +++--- src/inferrsi/knowledge/atomic_build.py | 9 ++++--- src/inferrsi/knowledge/atomic_generation.py | 5 ++++ src/inferrsi/knowledge/atomic_reader.py | 6 +++-- tests/knowledge/test_atomic_generation.py | 28 ++++++++++++++++++++- 5 files changed, 45 insertions(+), 10 deletions(-) diff --git a/docs/guides/knowledge/knowledge-layout.md b/docs/guides/knowledge/knowledge-layout.md index d8e5d85f6..43053339d 100644 --- a/docs/guides/knowledge/knowledge-layout.md +++ b/docs/guides/knowledge/knowledge-layout.md @@ -32,9 +32,10 @@ by its JSON pointer at the requested revision. file against `sources[index].sha256` and compares the declared slice with the atom's actual bytes. A content-addressed atom containing its complete file at offset zero carries its own snapshot. The reader records `verified_at_build` - when the caller pins the installed generation to an ID from a trusted release - record. An install opened without that pin, or an ordinary store, returns - `declared`. Its Bundle revision covers metadata and resources. + for each atom whose range the build compared with a separately supplied file + and whose installed generation matches the caller's trusted release ID. + Without either check the receipt records `declared`. Its Bundle revision + covers metadata and resources. - `metadata.composition` declares named `nodes` (qualified ref, exact revision, required prerequisite nodes), `routes` (layer, required and optional roots, conditions, finding, conflicts and superseded routes), and its grants and diff --git a/src/inferrsi/knowledge/atomic_build.py b/src/inferrsi/knowledge/atomic_build.py index 6da6c76c1..1de399a1d 100644 --- a/src/inferrsi/knowledge/atomic_build.py +++ b/src/inferrsi/knowledge/atomic_build.py @@ -80,7 +80,7 @@ def _host_skill(declaration: dict, nodes: dict, material: dict) -> tuple[str, di return name, output -def _verify_source(body: bytes, record: dict, roots: Mapping[str, Path]) -> None: +def _verify_source(body: bytes, record: dict, roots: Mapping[str, Path]) -> bool: source, path = record["source"], record["source_path"] snapshot = source.get("sha256") if not isinstance(snapshot, str) or not re.fullmatch(r"[0-9a-f]{64}", snapshot): @@ -88,16 +88,17 @@ def _verify_source(body: bytes, record: dict, roots: Mapping[str, Path]) -> None if source.get("path", path) != path: raise ValueError(f"Atom path differs from its pinned source path: {path}") start, end = record["source_byte_range"] - if "commit" not in source and start == 0 and snapshot == record["sha256"]: - return key = source.get("commit", snapshot) if key not in roots: + if "commit" not in source and start == 0 and snapshot == record["sha256"]: + return False raise ValueError(f"Missing pinned source root for {key} at {path}") original = owned_path(roots[key], path).read_bytes() if digest(original) != snapshot: raise ValueError(f"Complete pinned source file differs at {path}") if end > len(original) or original[start:end] != body: raise ValueError(f"Atom bytes differ from pinned source range at {path} [{start}, {end})") + return True def _prepare(source: Path, permits: Callable[[AtomPin, str], bool], roots: Mapping[str, Path]): @@ -128,7 +129,7 @@ def _prepare(source: Path, permits: Callable[[AtomPin, str], bool], roots: Mappi entry[key] = view[key] if field == "atom": material[pin] = atom_material(bundle, view) - _verify_source(*material[pin], roots) + entry["source_range_verified"] = _verify_source(*material[pin], roots) entry["layer"] = declaration["layer"] else: compositions[pin] = bundle diff --git a/src/inferrsi/knowledge/atomic_generation.py b/src/inferrsi/knowledge/atomic_generation.py index 30d7b6aa2..f9a1d0cb2 100644 --- a/src/inferrsi/knowledge/atomic_generation.py +++ b/src/inferrsi/knowledge/atomic_generation.py @@ -90,6 +90,11 @@ def release_pinned(self) -> bool: """Whether this installation matched a generation ID supplied by the caller.""" return self._release_pinned + def source_range_verified(self, pin: AtomPin) -> bool: + entry = self._catalog.get(pin.ref, {}) + return (self.release_pinned and entry.get("revision") == pin.revision + and entry.get("source_range_verified") is True) + @property def catalog(self) -> dict: return {ref: dict(entry) for ref, entry in self._catalog.items()} diff --git a/src/inferrsi/knowledge/atomic_reader.py b/src/inferrsi/knowledge/atomic_reader.py index 0a44e84ae..f580e8c4c 100644 --- a/src/inferrsi/knowledge/atomic_reader.py +++ b/src/inferrsi/knowledge/atomic_reader.py @@ -185,9 +185,11 @@ def include(group: Iterable[AtomUse]) -> GroupDelivery | None: if refusal is not None: omissions.append({"path": list(group[-1].path), "reason": refusal.receipt["status"]}) - pinned = isinstance(self.source, InstalledGeneration) and self.source.release_pinned + installed = self.source if isinstance(self.source, InstalledGeneration) else None records = [{"ref": pin.ref, "revision": pin.revision, "paths": via, - "source_range_verification": "verified_at_build" if pinned else "declared", + "source_range_verification": ("verified_at_build" if installed + and installed.source_range_verified(pin) + else "declared"), **cached[pin][1]} for pin, via in paths.items()] receipt = {"status": "delivered", "body_bytes": used_bytes, "delivered": records} diff --git a/tests/knowledge/test_atomic_generation.py b/tests/knowledge/test_atomic_generation.py index 280707b0b..96945c166 100644 --- a/tests/knowledge/test_atomic_generation.py +++ b/tests/knowledge/test_atomic_generation.py @@ -8,7 +8,7 @@ from inferrsi.knowledge.atomic_build import build_generation from inferrsi.knowledge.atomic_generation import PUBLIC_TASKS, SEAL, InstalledGeneration, digest -from inferrsi.knowledge.atomic_reader import AtomicReader, AtomPin +from inferrsi.knowledge.atomic_reader import AtomicReader, AtomPin, AtomUse from inferrsi.knowledge.knowledge_operations import Bundle, UnavailableRevision, _json from tests.fixtures.atomic_composition import composition, metadata, node from tests.knowledge.test_atomic_reader import RELEASE, UPSTREAM, allow, excerpt @@ -136,6 +136,32 @@ def test_source_attestation_needs_the_callers_release_pin(author_root, tmp_path) InstalledGeneration(destination, expected="sha256:" + "0" * 64) +def test_one_read_reports_the_external_source_check_for_each_atom(author_root, tmp_path): + external = tmp_path / "original" + external.mkdir() + body = (author_root / "atoms/inputs/attachment").read_bytes() + (external / "sample").write_bytes(body) + roots = {RELEASE: RELEASE_ROOT, digest(body): external} + target = tmp_path / "installation" + generation = build_generation(author_root, target, permits=allow, source_roots=roots) + installed = InstalledGeneration(target, expected=generation) + uses = [] + for name in ("ceiling-l1", "navigation", "attachment"): + ref = "package:" + name + uses.append(AtomUse(AtomPin(ref, installed.catalog[ref]["revision"]), (name,))) + delivery = AtomicReader(installed, permits=allow).read_group( + uses, context={}, max_bytes=10000, + ) + assert [item["source_range_verification"] for item in delivery.receipt["delivered"]] == [ + "verified_at_build", "declared", "verified_at_build", + ] + assert delivery.bodies[-1] == body + (external / "sample").write_bytes(b"wrong external source") + with pytest.raises(ValueError, match="Complete pinned source file differs"): + build_generation(author_root, tmp_path / "corrupt", permits=allow, source_roots=roots) + assert not (tmp_path / "corrupt").exists() + + def test_host_procedure_assembles_pinned_sections_without_changing_l0(author_root, tmp_path): descriptor = author_root / "compositions/task-debug.json" spec = json.loads(descriptor.read_bytes())