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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions docs/guides/knowledge/knowledge-layout.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ To reproduce the #516 search comparison, use the baseline and candidate checkout

## Atomic library for domain authors and Apps

The atomic library accepts JSON descriptors for atoms and compositions. An
author works under `src/inferrsi/knowledge/atoms/` or `compositions/`. For a
The atomic library accepts JSON descriptors for atoms and compositions. Pin
existing bodies from `src/inferrsi/knowledge/data/skill_library/` in `atoms/`.
Use `compositions/` to select and order the pinned atoms. For a
clean build, pass that Knowledge root and a separate, new installation directory
to `inferrsi.knowledge.atomic.build.build_generation(source, target, permits=...,
source_roots=...)`. Supply physical source snapshots keyed by the exact Git commit
Expand All @@ -17,14 +18,29 @@ corresponding repository paths after verifying its release digest.
The installed wheel and plugin load the sealed library published with their release.

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
`dependencies`, and a `content` mapping. An Atom resource can use
`{"source_span": true}` to derive its bytes from the pinned source and range in
`metadata.atom.source_span`. Independently authored resources can use
`{"text": "..."}` or `{"path": "inputs/file"}` relative to the descriptor.
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.

To update an Atom backed by InferRSI Git history, land the source edit on `main`
first. The release builder requires the pinned commit to be an ancestor of the
release commit. A squash merge gives the source edit a new commit SHA.

Open the Atom update from `main` and use the landed commit and the file's
SHA-256 in the selected `metadata.sources` entry. Set the half-open byte range
and slice SHA-256 in `metadata.atom.source_span`. For a full file use `[0, size]`
in bytes and the same digest for the file and the slice. Refresh any composition
pins and publication grant that reference the new Bundle revision. In a clean
worktree at a simulated squash onto the current `main`, run
`python tools/stage_release_knowledge.py --commit <squash-sha> --destination <new-dir>`.
Existing revisions resolve to their original bytes in sealed snapshots.

For a Case backed by released files, `case_resources` maps each public resource
name to a pinned L3 node. The builder derives the entrypoint and required
resource order from the original `case.json`, checks relative paths against the
Expand Down
9 changes: 5 additions & 4 deletions src/inferrsi/knowledge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ follow the hit's `read` command with its source and revision.
individual structured findings. `config/`, `skill-index.json` and `_compiled/`
support search, registration and builds.

At the Knowledge package root, `atoms/` defines versioned content and
`compositions/` assembles it. The installed snapshot provides the L0 directory,
optional L1 decision cards, L2 bodies and L3 resources. Installed Task
`SKILL.md` files live under `_atomic/skills/`.
`atoms/` defines versioned content and `compositions/` assembles it. For
source-backed content, [land the source before updating the Atom pin](../../../docs/guides/knowledge/knowledge-layout.md#atomic-library-for-domain-authors-and-apps).
The installed snapshot provides L0 navigation, optional L1 decision cards,
L2 bodies and L3 resources. Installed Task `SKILL.md` files live under
`_atomic/skills/`.

[`atomic/`](atomic/) owns snapshot building, installation and revision-pinned
delivery. CLI and Apps workflows share [`open_catalog_selection`](atomic/catalog.py).
Expand Down
38 changes: 30 additions & 8 deletions src/inferrsi/knowledge/atomic/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
owned_path,
)
from .json import matches_span, member_spans
from .reader import atom_material, permits_operations
from .reader import atom_material, atom_source_span, permits_operations
from .skill_directory import directory_dependencies, export_directory_skill, skill_spans

_PUBLISH = {"read", "retain", "redistribute"}
Expand Down Expand Up @@ -329,6 +329,9 @@ def _authored(directory, path, field, descriptor, material, roots) -> tuple[Atom
safe_path(name)
if isinstance(value, dict) and value.keys() == {"path"}:
content[name] = owned_path(directory, value["path"]).read_bytes()
elif (field == "atom" and isinstance(value, dict)
and value.keys() == {"source_span"} and value["source_span"] is True):
content[name] = _source_span_content(metadata, name, roots)
elif (field == "composition" and metadata["kind"] == "knowledge"
and name == metadata.get("entrypoint") == "record.json"
and isinstance(value, dict) and value.keys() == {"record_node"}):
Expand All @@ -338,7 +341,7 @@ def _authored(directory, path, field, descriptor, material, roots) -> tuple[Atom
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}")
raise ValueError(f"Invalid content binding for {name} in {path.name}")
if "legacy_package_resources" in descriptor:
if (field != "composition" or metadata["kind"] != "knowledge"
or descriptor.get("authority", "package") != "package" or resource_aliases):
Expand Down Expand Up @@ -431,28 +434,47 @@ def _host_skill(bundle: Bundle, nodes: dict, material: dict) -> tuple[str, dict[
return name, output


def _verify_source(body: bytes, record: dict, roots: Mapping[str, Path]) -> bool:
source, path = record["source"], record["source_path"]
def _pinned_source(source: dict, path: str, roots: Mapping[str, Path], *,
embedded_digest: str | None = None) -> bytes | None:
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"]
key = source.get("commit", snapshot)
if key not in roots:
if "commit" not in source and start == 0 and snapshot == record["sha256"]:
return False
if "commit" not in source and snapshot == embedded_digest:
return None
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}")
return original


def _source_span_content(metadata: dict, resource: str, roots: Mapping[str, Path]) -> bytes:
if resource != metadata["atom"].get("resource", metadata.get("entrypoint")):
raise ValueError("Only the declared Atom resource can use a source span binding")
source, path, start, end = atom_source_span(metadata)
original = _pinned_source(source, path, roots)
if original is None or end > len(original):
raise ValueError(f"Atom source range exceeds the pinned file at {path} [{start}, {end})")
return original[start:end]


def _verify_source(body: bytes, record: dict, roots: Mapping[str, Path]) -> bool:
path = record["source_path"]
start, end = record["source_byte_range"]
embedded_digest = record["sha256"] if start == 0 else None
original = _pinned_source(record["source"], path, roots, embedded_digest=embedded_digest)
if original is None:
return False
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 _authored_inputs(directory: Path, field: str, material: dict, roots=None):
def _authored_inputs(directory: Path, field: str, material: dict, roots: Mapping[str, Path]):
for path in sorted(directory.glob("*.json")):
if not re.fullmatch(IDENTITY, path.stem):
raise ValueError(f"Invalid descriptor filename: {path.name}")
Expand Down
29 changes: 19 additions & 10 deletions src/inferrsi/knowledge/atomic/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,9 @@ def _restriction(declaration: dict, actions: set[str], context: Mapping[str, str
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"]
def atom_source_span(view: dict) -> tuple[dict, str, int, int]:
"""Resolve the declared immutable file and its byte range."""
span = view["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")
Expand All @@ -93,16 +88,30 @@ def atom_material(bundle: Bundle, view: dict) -> tuple[bytes, dict]:
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):
if type(start) is not int or type(end) is not int or not 0 <= start <= end:
raise ValueError("Source range must cover the exact bytes of the atom")
return source, safe_path(span["path"]), start, end


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]
source, path, start, end = atom_source_span(view)
if end - start != len(body):
raise ValueError("Source range must cover the exact bytes of the atom")
span = atom["source_span"]
digest = hashlib.sha256(body).hexdigest()
if span["sha256"] != digest or view["resources"][resource] != digest:
raise ValueError("Atom does not match the declared source digest")
if atom["layer"] not in LAYERS:
raise ValueError("Invalid atom disclosure layer")
return body, {
"resource": resource,
"layer": atom["layer"], "source": dict(source), "source_path": safe_path(span["path"]),
"layer": atom["layer"], "source": dict(source), "source_path": path,
"source_byte_range": [start, end], "source_sha256": span["sha256"],
"sha256": digest, "bytes": len(body),
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,6 @@
}
},
"content": {
"guide.md": {
"path": "engines/sglang-omni/directory-guide.md"
}
"guide.md": {"source_span": true}
}
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@
}
},
"content": {
"body.md": {
"path": "task-accuracy-acceptance.md"
}
"body.md": {"source_span": true}
}
}
5 changes: 0 additions & 5 deletions src/inferrsi/knowledge/atoms/task-accuracy-acceptance.md

This file was deleted.

44 changes: 44 additions & 0 deletions tests/knowledge/test_atomic_generation.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,50 @@ 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 use_pinned_source(root: Path, atom: str) -> Path:
path = root / "atoms" / f"{atom}.json"
author = json.loads(path.read_bytes())
resource, local = next(iter(author["content"].items()))
(path.parent / local["path"]).unlink()
author["content"][resource] = {"source_span": True}
write_json(path, author)
return path


def test_pinned_source_bindings_preserve_complete_file_and_fragment(author_root, tmp_path):
baseline = tmp_path / "baseline"
expected = build_release(author_root, baseline, permits=allow)

use_pinned_source(author_root, "ceiling-l1")
use_pinned_source(author_root, "ceiling-l3")
derived = tmp_path / "derived"
assert build_release(author_root, derived, permits=allow) == expected
assert file_bytes(derived) == file_bytes(baseline)


@pytest.mark.parametrize("failure", ["missing-root", "range", "digest"])
def test_pinned_source_binding_rejects_bad_inputs(author_root, tmp_path, failure):
path = use_pinned_source(author_root, "ceiling-l1")
author = json.loads(path.read_bytes())
span = author["metadata"]["atom"]["source_span"]
roots = {RELEASE: RELEASE_ROOT}
if failure == "missing-root":
roots.clear()
message = "Missing pinned source root"
elif failure == "range":
span["byte_range"][1] = (RELEASE_ROOT / span["path"]).stat().st_size + 1
message = "Atom source range exceeds the pinned file"
else:
span["sha256"] = "0" * 64
message = "Atom does not match the declared source digest"
write_json(path, author)

target = tmp_path / "installed"
with pytest.raises(ValueError, match=message):
build_generation(author_root, target, source_roots=roots, permits=allow)
assert not target.exists()


def test_selected_skill_registry_requires_its_exact_original(author_root, tmp_path):
write_json(author_root / "skill-registry.json", {
"ref": "package:skill-library.index", "revision": "sha256:" + "0" * 64,
Expand Down
12 changes: 8 additions & 4 deletions tests/knowledge/test_atomic_research_engine_guides.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
from tests.knowledge.test_atomic_generation import RELEASE_ROOT, make_author_root
from tests.knowledge.test_atomic_reader import RELEASE, allow

ATOMS = Path(__file__).resolve().parents[2] / "src/inferrsi/knowledge/atoms"
ROOT = Path(__file__).resolve().parents[2]
ATOMS = ROOT / "src/inferrsi/knowledge/atoms"
COMPOSITIONS = ATOMS.parent / "compositions"
LIBRARY = "src/inferrsi/knowledge/data/skill_library/"
RESEARCH = "workflows/research/inference-engine-research"
Expand Down Expand Up @@ -51,11 +52,14 @@ def reference(engine):

def copy_original(source, release, descriptor, original, checksum):
author = json.loads((ATOMS / descriptor).read_bytes())
local = author["content"]["guide.md"]["path"]
body = (ATOMS / local).read_bytes()
local = author["content"]["guide.md"].get("path")
body = (ATOMS / local if local else ROOT / LIBRARY / original).read_bytes()
assert hashlib.sha256(body).hexdigest() == checksum
shutil.copyfile(ATOMS / descriptor, source / "atoms" / descriptor)
for path in (source / "atoms" / local, release / LIBRARY / original):
paths = [release / LIBRARY / original]
if local:
paths.append(source / "atoms" / local)
for path in paths:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(body)
return body
Expand Down
6 changes: 4 additions & 2 deletions tests/knowledge/test_model_sol_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,7 +597,9 @@ def test_complete_index_groups_and_separate_tail(length, complete, rounded):

def test_h200_tp4_pinned_analysis_from_cli():
driver = OWNER / "scripts/qwen38_h200_tp4.py"
result = json.loads(subprocess.check_output([sys.executable, str(driver)]))
# Other workers build Catalog snapshots from this shared Skill directory.
command = [sys.executable, "-B", str(driver)]
result = json.loads(subprocess.check_output(command))
assert result["text_tensor_count"] == 1294
weights = result["rank_weight_bytes_by_family"]
assert weights["routed"] == 48 * 512 * 3 * 2560 * 640 * 2 // 4
Expand All @@ -620,7 +622,7 @@ def test_h200_tp4_pinned_analysis_from_cli():
== pytest.approx(1000)
assert result["whole_model"]["qualified_bound_s"] is None
single = json.loads(subprocess.check_output(
[sys.executable, str(driver), "--prompt-tokens", "1", "--output-tokens", "1"],
[*command, "--prompt-tokens", "1", "--output-tokens", "1"],
))
assert len(single["prefill"]) == 1
assert single["decode_steps"] == 0 and single["first_decode"] is single["last_decode"] is None
Loading