diff --git a/src/inferrsi/knowledge/atomic_skill_directory.py b/src/inferrsi/knowledge/atomic_skill_directory.py index 2b5f5932d..6ea7704ed 100644 --- a/src/inferrsi/knowledge/atomic_skill_directory.py +++ b/src/inferrsi/knowledge/atomic_skill_directory.py @@ -8,8 +8,8 @@ from ._skill_selection import skill_procedure from .atomic_composition import AtomPin, select_routes -from .atomic_generation import digest, directory_skill_path, owned_path -from .knowledge_operations import Bundle, _tree, safe_path +from .atomic_generation import directory_skill_path, owned_path +from .knowledge_operations import Bundle, _checkout_skill_resources, safe_path from .skill_catalog import _effective, _frontmatter_parts @@ -70,24 +70,19 @@ def directory_dependencies(metadata, bindings, content, origins, material, roots if (source != metadata["sources"][0] or original.parts[-len(entry.parts):] != entry.parts or not roots or source.get("commit") not in roots): raise ValueError("Skill directory requires its pinned source root") + library_prefix = PurePosixPath(*original.parts[:-len(entry.parts)]) for name, origin in origins.items(): - if (not PurePosixPath(name).is_relative_to(entry.parent) - or source.get("repo") != origin.get("repo") - or source["commit"] != origin.get("commit") - or original.parent / PurePosixPath(name).relative_to(entry.parent) - != PurePosixPath(origin["path"])): + if (source.get("repo") != origin.get("repo") or source["commit"] != origin.get("commit") + or library_prefix / name != PurePosixPath(origin["path"])): raise ValueError(f"Skill resource differs from its original relative source: {name}") root = roots[source["commit"]] directory = owned_path(root, original.parent.as_posix()) - released = _tree(directory, entry.parent.as_posix(), root=root) + library = root / library_prefix + released, dependencies = _checkout_skill_resources( + library, directory, _effective(directory).get("references", []), + ) if content != released or metadata["required_resources"] != sorted(released): raise ValueError("Skill directory bindings must cover the complete original directory") - dependencies = {} - for reference in _effective(directory).get("references", []): - path = (entry.parent / safe_path(reference)).as_posix() - if path not in released: - raise ValueError(f"Missing declared Skill reference: {path}") - dependencies[path] = "sha256:" + digest(released[path]) _verify_directory_routes(metadata["composition"], bindings, content[entry.as_posix()], source, material, dependencies) return dependencies diff --git a/src/inferrsi/knowledge/atoms/dense-performance-evidence.original.json b/src/inferrsi/knowledge/atoms/dense-performance-evidence.original.json new file mode 100644 index 000000000..1348df890 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/dense-performance-evidence.original.json @@ -0,0 +1,102 @@ +{ + "authority": "checkout", + "metadata": { + "id": "dense-performance-evidence.original", + "kind": "knowledge", + "entrypoint": "guide.md", + "title": "Taxonomy of performance evidence an optimization agent needs, ordered by collection cost and diagnostic power. Maps evidence types to the questions they answer and the claims they can support. Use to decide which evidence to collect next, avoid over-claiming from cheap evidence, and structure a measurement campaign.\n", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/dense-performance-evidence/SKILL.md", + "sha256": "8fc261fce4be42ef66b3f98cf35bf3b5f8ee6f622494083ddb343f2645d6bf15" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "applicability": { + "scope": "Deciding which performance evidence to collect next and which claim each evidence level supports, from correctness through microbenchmark, component profile, isolated scenario benchmark and multi-regime serving benchmark to a production A/B experiment; also structuring a measurement campaign", + "prerequisites": "Level 0 correctness evidence is collected before any performance measurement; a Level 5 experiment needs production infrastructure, traffic splitting and statistical power", + "input_contract": "The claim to be made or the question to answer, and the evidence already collected with its level, workload, hardware/software context and controls", + "produced_artifact": "The minimum evidence level each claim requires, the next evidence to collect under the escalation rule, and negative-result records with hypothesis, evidence level, the metric that did not improve, context and the reason if known; a classification of evidence, not a measurement", + "failure_modes": [ + "An md5 match or a test pass is read as semantically correct output or as support for a performance claim", + "A microbenchmark improvement is reported as an inference throughput gain", + "Absolute kernel durations or single collective latencies are compared across devices or sessions", + "A win on one fixed workload or concurrency is generalized to production traffic", + "Worse metrics, per-task regressions or negative results are discarded, or a shared task budget is taken as equal total cost" + ], + "refusal_point": "Withholds any claim above the level its evidence reaches, leaves an unresolved source protocol or denominator mismatch unresolved, and lets neither upstream scores nor local packaging checks promote an InferRSI candidate" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "attribution": [], + "empirical_validation": "not_run", + "atom": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "layer": "L3", + "source_span": { + "source_index": 0, + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/dense-performance-evidence/SKILL.md", + "byte_range": [ + 0, + 11935 + ], + "sha256": "8fc261fce4be42ef66b3f98cf35bf3b5f8ee6f622494083ddb343f2645d6bf15" + } + } + }, + "content": { + "guide.md": { + "path": "playbooks/dense-performance-evidence.md" + } + }, + "parts": { + "navigation": { + "skill_section": "navigation", + "layer": "L0", + "byte_range": [ + 0, + 374 + ], + "sha256": "71957962f1d8b81d103c9363b75416e4e1e78ff154ec397623610f6a9b0e3482" + }, + "decision": { + "skill_section": "decision", + "layer": "L1", + "byte_range": [ + 0, + 3952 + ], + "sha256": "afb53132d61cca90784fede1d338ef8606ca32e8f88724a7f79f35046f7b0bd8" + }, + "procedure": { + "skill_section": "procedure", + "layer": "L2", + "byte_range": [ + 3952, + 11935 + ], + "sha256": "6ef436a8047e19ca02251ca9e3df2c46667fb75d31de812228c01fb676dade76" + } + } +} diff --git a/src/inferrsi/knowledge/atoms/playbooks/dense-performance-evidence.md b/src/inferrsi/knowledge/atoms/playbooks/dense-performance-evidence.md new file mode 100644 index 000000000..c206cfb71 --- /dev/null +++ b/src/inferrsi/knowledge/atoms/playbooks/dense-performance-evidence.md @@ -0,0 +1,227 @@ +--- +name: dense-performance-evidence +description: 'Taxonomy of performance evidence an optimization agent needs, ordered by collection cost and diagnostic power. Maps evidence types to the questions they answer and the claims they can support. Use to decide which evidence to collect next, avoid over-claiming from cheap evidence, and structure a measurement campaign. + + ' +metadata: + inferrsi: | + { + "tags": [ + "performance", + "evidence", + "profiling", + "measurement" + ], + "status": "candidate", + "profile": "local-skill-v1", + "schema_version": 1, + "kind": "skill", + "origin": [ + "external" + ], + "empirical_validation": "not_run", + "applicability": { + "scope": "Deciding which performance evidence to collect next and which claim each evidence level supports, from correctness through microbenchmark, component profile, isolated scenario benchmark and multi-regime serving benchmark to a production A/B experiment; also structuring a measurement campaign", + "prerequisites": "Level 0 correctness evidence is collected before any performance measurement; a Level 5 experiment needs production infrastructure, traffic splitting and statistical power", + "input_contract": "The claim to be made or the question to answer, and the evidence already collected with its level, workload, hardware/software context and controls", + "produced_artifact": "The minimum evidence level each claim requires, the next evidence to collect under the escalation rule, and negative-result records with hypothesis, evidence level, the metric that did not improve, context and the reason if known; a classification of evidence, not a measurement", + "failure_modes": [ + "An md5 match or a test pass is read as semantically correct output or as support for a performance claim", + "A microbenchmark improvement is reported as an inference throughput gain", + "Absolute kernel durations or single collective latencies are compared across devices or sessions", + "A win on one fixed workload or concurrency is generalized to production traffic", + "Worse metrics, per-task regressions or negative results are discarded, or a shared task budget is taken as equal total cost" + ], + "refusal_point": "Withholds any claim above the level its evidence reaches, leaves an unresolved source protocol or denominator mismatch unresolved, and lets neither upstream scores nor local packaging checks promote an InferRSI candidate" + }, + "recommendations": [ + "Collect Level 0 first and profile at Level 2 before implementing; escalate to Level 3 only after a promising Level 2 result, and to Level 4 only after a Level 3 win worth validating across regimes.", + "Collect a Level 1 microbenchmark only for an isolated-kernel question after Level 2 has confirmed that kernel is on the critical path.", + "For a Level 1 claim, pin input shape and dtype, exclude warmup, synchronize before timing, run at least 10 repetitions and report median and IQR; for a Level 3 claim, match hardware, software stack, model revision and inputs, run at least 3 repetitions and alternate A/B/A order.", + "Read the admission/drain occupancy case when interpreting finite service cohorts; phase-selected occupancy is not end-to-end gain." + ], + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets." + ], + "provenance_readsets": [], + "references": [ + "../../../casebooks/inference/inference-optimization-casebook/cases/admission-drain-occupancy.md", + "../../../casebooks/inference/inference-optimization-casebook/cases/admission-drain-occupancy.json" + ], + "consumption_mode": "packaged" + } +--- + +# Dense Performance Evidence Taxonomy + +Status: candidate. Source-grounded from TensorRT-LLM @ f33e0e5f and MindIE-SD +@ 8481d39b. + +An optimization agent must not conflate different evidence levels. This skill +defines what each level proves and what it cannot prove. + +## Evidence hierarchy + +Listed from cheapest to most expensive to collect. + +### Level 0 — Correctness + +**What it is:** Output matches expected (test pass, md5 match, output schema valid). + +**What it proves:** The change does not break the declared output contract. + +**What it does NOT prove:** Any performance claim. A change can pass all tests +and be slower. An md5 match does not mean the output is semantically correct +(it could match a wrong baseline). + +**When to collect:** Always, before any performance measurement. + +**Key discipline:** md5 ≠ correct output. Verify the content of the output, +not just its hash. +Source: `perf-gate/SKILL.md` @ 8481d39b (§md5-blind-spot). + +### Level 1 — Microbenchmark + +**What it is:** Single-kernel or single-operation timing with controlled inputs, +warmup, and repetitions. Examples: CUDA event timing, torch.utils.benchmark, +CANN single-op timing. + +**What it proves:** Whether a specific low-level operation is faster in isolation. + +**What it does NOT prove:** E2E inference throughput. A kernel that is 20% faster +in isolation may have no E2E impact if it was not on the critical path, or may +be masked by a different bottleneck. + +**Required for a valid claim:** pinned input shape/dtype, warmup excluded, +≥10 repetitions, hardware synchronized before timing, reported as median ± IQR. + +**Common mistake:** reporting microbench improvement as inference throughput gain. +Source: TRT-LLM AGENTS.md ("Microbench ≠ service/E2E gain"). + +### Level 2 — Component profile + +**What it is:** Profiler output over a representative workload. nsys timeline +(system-level), ncu (kernel-level), CANN msprof/torch_npu.profiler. Shows: +- Per-kernel time distribution +- SOL% (speed-of-light %) or AI Core utilization ratio +- Memory bandwidth utilization +- Communication time and overlap + +**What it proves:** Which kernel or stage is the bottleneck, and whether it is +compute-bound vs memory-bound. + +**What it does NOT prove:** E2E serving throughput under real load patterns +(batching, queueing, request mix, concurrent users). + +**Metrics that are reliable:** +- Kernel call counts (reproducible across runs) +- Aggregate time fractions (reproducible within a session) +- SOL% or utilization ratios (reproducible within a session) + +**Metrics that are NOT reliable across devices or sessions:** +- Absolute kernel duration in ms (may vary ±10% device-to-device) +- Single collective communication latency (may vary ~2× device-to-device) +Source: `profiling-analyze/SKILL.md` @ 8481d39b (§reproducibility). + +### Level 3 — Isolated scenario benchmark + +**What it is:** End-to-end benchmark on a fixed workload (single prompt, fixed +concurrency, fixed sequence length). Produces: throughput tokens/s or frames/s, +TTFA, latency percentiles. + +**What it proves:** That the optimized system is faster on this specific workload +under these specific conditions. + +**What it does NOT prove:** Performance under production traffic (variable +concurrency, mixed request sizes, burstiness). A win at concurrency=1 may +reverse at concurrency=8 if the optimization creates a new bottleneck under load. + +**Required for a valid claim:** same hardware, same software stack, same model +revision, same input distribution, ≥3 repetitions, alternating A/B/A order to +detect drift. + +### Level 4 — Multi-regime serving benchmark + +**What it is:** Benchmark across multiple workload regimes: throughput-saturating +load, low-concurrency latency-sensitive load, and replay of real trace. + +**What it proves:** That the optimization improves goodput (requests that complete +within SLO) across realistic conditions without regressions in any regime. + +**What it does NOT prove:** Production behavior (hardware differences, actual +traffic distributions, long-run stability). + +Source: `vllm-evolve/README.md` @ 43cc82c (§candidate-scoring: goodput across +throughput/latency/replay regimes, `high_variance_inconclusive` if too noisy). + +### Level 5 — A/B production experiment + +**What it is:** Controlled experiment in a live serving system, comparing a +baseline and candidate on real traffic. + +**What it proves:** Actual production impact, including all second-order effects +not captured in benchmarks. + +**Collection cost:** Very high. Requires production infrastructure, traffic +splitting, and statistical power. + +## Claim-evidence matching + +| Claim | Minimum evidence required | +|-------|--------------------------| +| "Kernel X is memory-bound" | Level 2 (SOL%, AI ratio) | +| "Op Y is the bottleneck" | Level 2 (kernel time fraction) | +| "Change Z improves microbench by N%" | Level 1 (microbench with controls) | +| "Optimization improves throughput at concurrency=1" | Level 3 | +| "Optimization improves throughput under production load" | Level 4 | +| "Optimization is safe to deploy" | Level 3 (no regression) + Level 0 | +| "Optimization improves production KPIs" | Level 5 | + +An optimization agent should always state which evidence level supports each +claim and avoid upgrading a lower-level result to a higher-level claim. + +## Methodology cost and evidence boundaries + +For skill/search methods, keep source fidelity, static usability, execution +correctness, behavioral efficacy and transfer as separate checks. Record build, +selection, deployment-context and downstream-task cost separately. State whether +reported changes are absolute points, relative gains, geometric means or rates +with conditional denominators. Preserve worse metrics and per-task regressions; +a shared task budget alone does not prove equal total cost. An unresolved source +protocol/denominator mismatch stays unresolved. + +[Paper-method comparison](../../../workflows/maintenance/npu-skill-factory/references/papers-20261015/COMPARISON.md) +and [protocol details](../../../workflows/maintenance/npu-skill-factory/references/papers-20261015/references/protocol-details.md) +provide the reviewed evidence; neither upstream scores nor local packaging checks +promote an InferRSI candidate. For performance predictions, distinguish physical +bounds, observed envelopes, simulator predictions and measured application results +as in [ceiling analysis](../performance-ceiling-analysis/SKILL.md). + +## Collection escalation rule + +Collect Level 0 before anything. Then: +- Start with Level 2 (profiler) to identify the bottleneck before implementing. +- Only escalate to Level 3 after a promising Level 2 result. +- Only escalate to Level 4 if Level 3 shows a win worth validating across regimes. +- Do not collect Level 1 unless the question is specifically about an isolated + kernel and Level 2 has already confirmed it is the critical path. + +## Evidence for negative results + +Negative results (changes that do not help) are as valuable as positive ones. +Record them with: +- The hypothesis that was tested. +- The evidence level collected. +- The specific metric that did not improve (or regressed). +- The hardware/software/workload context. +- The reason the hypothesis was wrong (if known). + +Do not discard negative evidence. It prevents re-exploring the same path and +bounds the search space for future candidates. +Source: SkillOpt blog/gating-reflection-safe-updates @ 343db229 (negative +evidence preservation in rejected edit records). + +## Scoped internal experience + +Read the single authoritative [admission/drain occupancy case](../../../casebooks/inference/inference-optimization-casebook/cases/admission-drain-occupancy.md) when interpreting finite service cohorts. It separates recorded observation, action and interpretation; phase-selected occupancy is not end-to-end gain. The original frozen evidence remains linked, not copied. This shared reference is included in the packaged skill library; standalone folder export is not supported. diff --git a/src/inferrsi/knowledge/compositions/dense-performance-evidence.json b/src/inferrsi/knowledge/compositions/dense-performance-evidence.json new file mode 100644 index 000000000..9aa5e3a1c --- /dev/null +++ b/src/inferrsi/knowledge/compositions/dense-performance-evidence.json @@ -0,0 +1,127 @@ +{ + "authority": "checkout", + "metadata": { + "id": "dense-performance-evidence", + "kind": "skill", + "entrypoint": "playbooks/measurement/dense-performance-evidence/SKILL.md", + "title": "Taxonomy of performance evidence an optimization agent needs, ordered by collection cost and diagnostic power. Maps evidence types to the questions they answer and the claims they can support. Use to decide which evidence to collect next, avoid over-claiming from cheap evidence, and structure a measurement campaign.\n", + "origin": [ + "external" + ], + "sources": [ + { + "type": "git", + "repo": "https://github.com/InferMatrixLab/InferRSI", + "commit": "e2f3be102c66c358803ed2186ed67bf627ebcbdf", + "path": "src/inferrsi/knowledge/data/skill_library/playbooks/measurement/dense-performance-evidence/SKILL.md", + "sha256": "8fc261fce4be42ef66b3f98cf35bf3b5f8ee6f622494083ddb343f2645d6bf15" + }, + { + "type": "unknown", + "note": "Legacy provenance remains in procedure/readsets" + } + ], + "applicability": { + "scope": "Deciding which performance evidence to collect next and which claim each evidence level supports, from correctness through microbenchmark, component profile, isolated scenario benchmark and multi-regime serving benchmark to a production A/B experiment; also structuring a measurement campaign", + "prerequisites": "Level 0 correctness evidence is collected before any performance measurement; a Level 5 experiment needs production infrastructure, traffic splitting and statistical power", + "input_contract": "The claim to be made or the question to answer, and the evidence already collected with its level, workload, hardware/software context and controls", + "produced_artifact": "The minimum evidence level each claim requires, the next evidence to collect under the escalation rule, and negative-result records with hypothesis, evidence level, the metric that did not improve, context and the reason if known; a classification of evidence, not a measurement", + "failure_modes": [ + "An md5 match or a test pass is read as semantically correct output or as support for a performance claim", + "A microbenchmark improvement is reported as an inference throughput gain", + "Absolute kernel durations or single collective latencies are compared across devices or sessions", + "A win on one fixed workload or concurrency is generalized to production traffic", + "Worse metrics, per-task regressions or negative results are discarded, or a shared task budget is taken as equal total cost" + ], + "refusal_point": "Withholds any claim above the level its evidence reaches, leaves an unresolved source protocol or denominator mismatch unresolved, and lets neither upstream scores nor local packaging checks promote an InferRSI candidate" + }, + "state": "candidate", + "limitations": [ + "Source-derived candidate; no local efficacy validation.", + "Original typed source inventory is not normalized; retain source identities and limits in the procedure/readsets.", + "Checkout-only local skill; no automatic execution or promotion.", + "Only declared references are required; other cross-skill links are navigation.", + "Historical revisions require a matching checkout or a retained store." + ], + "attribution": [], + "empirical_validation": "not_run", + "required_resources": [ + "casebooks/inference/inference-optimization-casebook/cases/admission-drain-occupancy.json", + "casebooks/inference/inference-optimization-casebook/cases/admission-drain-occupancy.md", + "playbooks/measurement/dense-performance-evidence/SKILL.md" + ], + "composition": { + "when": {}, + "license": "Apache-2.0", + "permissions": { + "read": true, + "retain": true, + "redistribute": true + }, + "nodes": { + "navigation": { + "ref": "checkout:dense-performance-evidence.original.navigation", + "revision": "sha256:0c3a19424d0dac7582956661e63625fff275dd682fadf846209c199546d3a2bf" + }, + "decision": { + "ref": "checkout:dense-performance-evidence.original.decision", + "revision": "sha256:db8c99e6ea0ddf94a358fafbcaee83800881e7f7fc6b56ea30b63bfc1509085d" + }, + "procedure": { + "ref": "checkout:dense-performance-evidence.original.procedure", + "revision": "sha256:f7d5b7230629b2c051b3cd9442e81c5b28bbf24829584f5fd7c76df8287479ce", + "requires": [ + "decision" + ] + }, + "case-record": { + "ref": "checkout:case.admission-drain-occupancy.original", + "revision": "sha256:2b53c58c066e63a9b86c71be3c0306b6fd3097a3ef0d2baad634d080363893d5" + }, + "case-guide": { + "ref": "checkout:case.admission-drain-occupancy.guide", + "revision": "sha256:e44d3cf8be60a00fd4878283026d001f3b4008639494d2d916ee61d36f89deaa" + }, + "original": { + "ref": "checkout:dense-performance-evidence.original", + "revision": "sha256:79a73ea91c8c2bfe4db5659537d925a95ce0b77f5e5fb3c6c47e0bfccba36694" + } + }, + "routes": { + "navigation": { + "layer": "L0", + "required": [ + "navigation" + ] + }, + "decision": { + "layer": "L1", + "required": [ + "decision" + ] + }, + "procedure": { + "layer": "L2", + "required": [ + "procedure", + "case-guide", + "case-record" + ] + }, + "originals": { + "layer": "L3", + "required": [ + "case-record", + "case-guide", + "original" + ] + } + } + } + }, + "directory_resources": { + "casebooks/inference/inference-optimization-casebook/cases/admission-drain-occupancy.json": "case-record", + "casebooks/inference/inference-optimization-casebook/cases/admission-drain-occupancy.md": "case-guide", + "playbooks/measurement/dense-performance-evidence/SKILL.md": "original" + } +} diff --git a/src/inferrsi/knowledge/knowledge_operations.py b/src/inferrsi/knowledge/knowledge_operations.py index 9a94c8eb0..02ce36b2b 100644 --- a/src/inferrsi/knowledge/knowledge_operations.py +++ b/src/inferrsi/knowledge/knowledge_operations.py @@ -324,6 +324,22 @@ def _tree( return result +def _checkout_skill_resources( + root: Path, directory: Path, references: list[str], +) -> tuple[dict[str, bytes], dict[str, str]]: + """Read an owner's directory and its explicitly declared files within the same library.""" + from .skill_catalog import _reference_path + + content = _tree(directory, directory.relative_to(root).as_posix(), root=root) + dependencies = {} + for reference in references: + path = _reference_path(root, directory, reference) + name = path.relative_to(root).as_posix() + content[name] = path.read_bytes() + dependencies[name] = "sha256:" + _hash(content[name]) + return content, dependencies + + class KnowledgeReader: def collect_service_context( self, cue, *, relevance_method, limit, context_bytes, @@ -656,19 +672,15 @@ def _knowledge(self, identity: str) -> Bundle: ) def _skill(self, identity: str) -> Bundle: - from .skill_catalog import _effective, _reference_path, skill_directory + from .skill_catalog import _effective, skill_directory root = self.skill_root directory = skill_directory(root, identity) metadata = _effective(directory) prefix = directory.relative_to(root).as_posix() - content = _tree(directory, prefix, root=root) - dependencies = {} - for reference in metadata.get("references", []): - path = _reference_path(root, directory, reference) - key = path.relative_to(root).as_posix() - content[key] = path.read_bytes() - dependencies[key] = "sha256:" + _hash(content[key]) + content, dependencies = _checkout_skill_resources( + root, directory, metadata.get("references", []), + ) return Bundle( { "id": identity, diff --git a/tests/knowledge/test_atomic_dense_evidence.py b/tests/knowledge/test_atomic_dense_evidence.py new file mode 100644 index 000000000..856af6f40 --- /dev/null +++ b/tests/knowledge/test_atomic_dense_evidence.py @@ -0,0 +1,148 @@ +"""Replay a released Playbook whose two required files belong to a separate Casebook.""" + +import json +import shutil + +import pytest + +from inferrsi.knowledge.atomic_build import build_generation +from inferrsi.knowledge.atomic_generation import InstalledGeneration +from inferrsi.knowledge.catalog import _skill_search_source +from inferrsi.knowledge.decision_cards import DecisionSource +from tests.knowledge.test_atomic_casebooks import ( + ATOMS, + FIXTURES, + RELEASE_COMMIT, + assert_empty, + canonical, + digest, + select, +) +from tests.knowledge.test_atomic_generation import RELEASE_ROOT, make_author_root, write_json +from tests.knowledge.test_atomic_reader import allow + +NAME = "dense-performance-evidence" +REF = "checkout:" + NAME +LIBRARY = "src/inferrsi/knowledge/data/skill_library/" +RELEASE = json.loads((FIXTURES / "playbook-domain-v0.3.4.json").read_bytes())["refs"][REF] +COMPOSITIONS = ATOMS.parent / "compositions" + + +def stage_atom(author, release, logical, pin): + descriptor = ATOMS / (pin["ref"].removeprefix("checkout:") + ".json") + shutil.copyfile(descriptor, author / "atoms" / descriptor.name) + (resource,) = json.loads(descriptor.read_bytes())["content"].values() + raw = (ATOMS / resource["path"]).read_bytes() + for dest in (author / "atoms" / resource["path"], release / LIBRARY / logical): + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_bytes(raw) + return digest(raw) + + +def dense_sources(root): + author = make_author_root(root) + release = root / "pinned" + shutil.copytree(RELEASE_ROOT, release) + path = author / "compositions" / (NAME + ".json") + shutil.copyfile(COMPOSITIONS / path.name, path) + spec = json.loads(path.read_bytes()) + nodes = spec["metadata"]["composition"]["nodes"] + hashes = {logical: stage_atom(author, release, logical, nodes[node]) + for logical, node in spec["directory_resources"].items()} + assert hashes == RELEASE["required_resources"] + return author, release, path, spec + + +def test_dense_playbook_delivers_both_declared_case_files_with_the_original_card(tmp_path): + author, release, _, _ = dense_sources(tmp_path) + target = tmp_path / "installed" + generation = build_generation(author, target, permits=allow, + source_roots={RELEASE_COMMIT: release}) + reader = InstalledGeneration(target, expected=generation) + _, bundle = reader.read_resolved(REF, revision=reader.catalog[REF]["revision"]) + assert bundle.view()["resources"] == RELEASE["required_resources"] + assert bundle.dependencies == RELEASE["dependencies"] + assert bundle.metadata["empirical_validation"] == "not_run" + assert bundle.metadata["origin"] == ["external"] and bundle.metadata["attribution"] == [] + assert NAME not in reader.skills + linked = {row["path"] for row in RELEASE["relative_guide_links"].values()} + navigation = linked - bundle.dependencies.keys() + assert len(navigation) == 3 and navigation.isdisjoint(bundle.content) + layers = {} + for level in ("L0", "L1", "L2", "L3"): + delivery = select(reader, REF, level, 100_000) + assert delivery.receipt["status"] == "delivered" + size = sum(map(len, delivery.bodies)) + assert delivery.receipt["body_bytes"] == size + assert select(reader, REF, level, size) == delivery + short = select(reader, REF, level, size - 1) + assert_empty(short, "over_budget") + assert short.receipt["required_bytes"] == size + stale = select(reader, REF, level, size, revision=RELEASE["revision"]) + assert_empty(stale, "unavailable_revision") + assert_empty(select(reader, REF, level, size, permits=lambda pin, op: pin.ref != REF), + "permission_denied") + for item, body in zip(delivery.receipt["delivered"], delivery.bodies, strict=True): + start, end = item["source_byte_range"] + assert item["source_path"].startswith(LIBRARY) + assert item["source"]["commit"] == RELEASE_COMMIT + assert item["source_range_verification"] == "verified_at_build" + assert body == bundle.content[item["source_path"].removeprefix(LIBRARY)][start:end] + denied_ref = item["ref"] + denied = select(reader, REF, level, size, permits=lambda pin, op: pin.ref != denied_ref) + assert_empty(denied, "permission_denied") + layers[level] = delivery.bodies + entry = RELEASE["entrypoint"] + assert bundle.content[entry].startswith(layers["L0"][0]) + (decision,) = layers["L1"] + _, fields = _skill_search_source(decision.decode()) + card = DecisionSource(REF, RELEASE["revision"], "skill", entry, entry, fields).project()["card"] + assert card["status"] == "partial" and card["missing_fields"] == ["validation"] + assert len(canonical(card)) == RELEASE["card_bytes"] + assert digest(canonical(card)) == RELEASE["card_sha256"] + record, guide = sorted(RELEASE["dependencies"]) + assert record.endswith(".json") and guide.endswith(".md") + assert layers["L2"][0] == decision and b"".join(layers["L2"][:2]) == bundle.content[entry] + assert layers["L2"][2:] == (bundle.content[guide], bundle.content[record]) + assert layers["L3"] == tuple(bundle.content[path] for path in sorted(bundle.content)) + + +@pytest.mark.parametrize(("change", "error"), [ + ("omit declared file", "complete original directory"), + ("reverse declared order", "L2 must deliver its declared original references"), + ("add navigation-only file", "complete original directory"), + ("rename original path", "differs from its original relative source"), +]) +def test_compiler_rejects_changed_cross_directory_contract(tmp_path, change, error): + author, release, path, spec = dense_sources(tmp_path) + bindings = spec["directory_resources"] + metadata = spec["metadata"] + composition = metadata["composition"] + procedure = composition["routes"]["procedure"]["required"] + originals = composition["routes"]["originals"]["required"] + case_record = next(name for name, node in bindings.items() if node == "case-record") + if change == "omit declared file": + del bindings[case_record] + originals.remove("case-record") + procedure.remove("case-record") + del composition["nodes"]["case-record"] + elif change == "reverse declared order": + procedure[-2:] = reversed(procedure[-2:]) + elif change == "add navigation-only file": + link = next(row for row in RELEASE["relative_guide_links"].values() + if row["path"].endswith("COMPARISON.md")) + target = json.loads((COMPOSITIONS / "npu-skill-factory.json").read_bytes()) + node = target["directory_resources"][link["path"]] + pin = target["metadata"]["composition"]["nodes"][node] + assert stage_atom(author, release, link["path"], pin) == link["sha256"] + bindings[link["path"]] = "navigation-target" + composition["nodes"]["navigation-target"] = pin + originals.append("navigation-target") + else: + bindings["casebooks/copied-case.json"] = bindings.pop(case_record) + metadata["required_resources"] = sorted(bindings) + write_json(path, spec) + target = tmp_path / "installed" + with pytest.raises(ValueError, match=error): + build_generation(author, target, permits=allow, source_roots={RELEASE_COMMIT: release}) + assert not target.exists()