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
178 changes: 110 additions & 68 deletions docs/guides/knowledge-factory-workflow.md

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions sdk/python/examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,9 @@ check the SDK contracts; no captured live output is supplied. See the

## knowledge_factory.py

One correction of a published definition, from a failed report through an administrator's
approval of the exact text to a fresh run that is served it. Three tokens, a disposable
One correction of a published definition, from a failed report and the problem report
filed against the revision it read, through an administrator's approval of the exact
text, to a fresh run that is served it. Three tokens, a disposable
org and one command; the script exits 0 when every check passes and writes a result
document that lists every check and each stage's request ids. The reporter,
the curator, the reviewer and the grader are scripted, and no call is answered by a
Expand Down
155 changes: 125 additions & 30 deletions sdk/python/examples/knowledge_factory.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
"""Run the knowledge factory loop against a disposable Loom deployment with three tokens:
a weekly report fails on an outdated definition, a writer prepares a correction from the
source document, an administrator approves the exact text, and a fresh run is served the
published definition and passes on other numbers.
a weekly report fails on an outdated definition, the reporter files a problem report
against the revision it read, a writer prepares a correction from the source document,
an administrator approves the exact text and resolves the report with the published
revision, and a fresh run is served the published definition and passes on other numbers.

python knowledge_factory.py run --result kf-result.json
python knowledge_factory.py cleanup --result kf-result.json --accept-org-cache-loss
Expand Down Expand Up @@ -63,6 +64,9 @@
SOURCE_URI = "urn:loom:example:kf:data-dictionary"
QUESTION = "What is an active account?"
GOAL = "Prepare the weekly account report"
# What the reporter saw, in run 1's reflection and in its report: not the fix, so no
# column name and no figure.
PROBLEM = "The definition names a column the numbers source does not have."
GRADER = "fixture-grader"
OWNER = "kf-example@loom.test"
MARKER = "kf-example-run:"
Expand Down Expand Up @@ -129,6 +133,18 @@
"memory.lineage": ["memory_key", "scope"],
"knowledge.upsert": ["source_uri", "title", "content"],
"knowledge.get": ["source_uri"],
"knowledge.reports.submit": [
"run_id",
"kind",
"target_kind",
"target_key",
"target_version",
"target_sha256",
"problem",
"evidence",
],
"knowledge.reports.get": ["report_id"],
"knowledge.reports.update": ["report_id", "action", "resolution_revision"],
"procedure.add": ["name", "situation", "steps"],
"run.begin": ["goal"],
"memory.search": ["query", *(name for name in COPY if name not in ("agent", "session_id"))],
Expand Down Expand Up @@ -162,12 +178,12 @@ def _entry(kind: str, exercised: bool, gates: bool = True, **more: Any) -> dict[
return {"kind": kind, "exercised": exercised, "gates_qualified": gates, **more}


# What this version exercises: the one source for the result's `coverage`, for the
# stages rendered as `not_exercised` and for `qualified`. An entry is switched to
# exercised by the change that adds its calls and checks, never at run time.
# What this version exercises: the one source for the result's `coverage` and for
# `qualified`. An entry is switched to exercised by the change that adds its calls and
# checks, never at run time.
COVERAGE: dict[str, dict[str, Any]] = {
"run_1": _entry("stage", True),
"report": _entry("stage", False, needs="knowledge_reports"),
"report": _entry("stage", True),
"investigation": _entry("stage", True),
"review": _entry("stage", True),
"publication": _entry("stage", True),
Expand All @@ -176,7 +192,7 @@ def _entry(kind: str, exercised: bool, gates: bool = True, **more: Any) -> dict[
"control_question": _entry("criterion", True),
"curation_pass": _entry("criterion", False, needs="curation_pass"),
"revision_receipts": _entry("criterion", True),
"repeated_report": _entry("criterion", False, needs="knowledge_reports"),
"repeated_report": _entry("criterion", True),
"interrupted_pass_retry": _entry("criterion", False, needs="curation_pass"),
"stale_source_refusal": _entry("criterion", False, needs="curation_pass"),
"duplicate_publication_guard": _entry("criterion", False, needs="curation_pass"),
Expand Down Expand Up @@ -254,6 +270,9 @@ class Held:
doc_id: Any = None
# Setup, then publication: the version of the shared copy the last promotion wrote.
copy: str = ""
# Report: its id, and what the reviewer hands the curator: the target and the id.
report_id: str = ""
handoff: dict[str, Any] = field(default_factory=dict)
# Investigation: the candidate's hash and the revision of the document it names.
candidate_sha256: str = ""
document_revision: Any = None
Expand Down Expand Up @@ -425,11 +444,6 @@ def copy_version(found: dict[str, Any], approved: dict[str, Any]) -> str:


def new_result(args: argparse.Namespace, run_id: str) -> dict[str, Any]:
stages = []
for name in STAGES:
entry = COVERAGE.get(name, {"exercised": True})
stage = {"stage": name, "status": "not_run" if entry["exercised"] else "not_exercised"}
stages.append(stage if entry["exercised"] else {**stage, "needs": entry["needs"]})
return {
"mode": MODE,
"status": "running",
Expand All @@ -443,7 +457,7 @@ def new_result(args: argparse.Namespace, run_id: str) -> dict[str, Any]:
"reporter_namespace": args.reporter_namespace,
"subjects": {},
},
"stages": stages,
"stages": [{"stage": name, "status": "not_run"} for name in STAGES],
"runs": {},
"links": [],
"observations": {},
Expand Down Expand Up @@ -632,6 +646,13 @@ def refusal(self, name: str, answer: Answer) -> bool:
"""A check that passes when Loom refused the call for the caller's role."""
return self.check(name, answer.denied, answer.text, answer.request_id)

def unrevised(self, name: str, answer: Answer, reported: str) -> bool:
"""A check that passes when the server refused a resolution because the target
holds no revision newer than `reported`, which the refusal names."""
named = f"reported revision {reported}" in str(answer.detail.get("message"))
refused = answer.status == 422 and answer.code == "VALIDATION_FAILED" and named
return self.check(name, refused, answer.text, answer.request_id)

def superseded(self, name: str, answer: Answer, current: str) -> bool:
"""A check that passes when the server refused a call that names a hash the row
no longer holds, and named the hash it holds."""
Expand Down Expand Up @@ -1026,9 +1047,7 @@ async def reporting_run(self, number: int, approved: dict[str, Any]) -> None:
report = produced["report"]
closing: dict[str, Any] = {"memories_used": [DEFINITION_KEY, PROCEDURE_KEY]}
if report and report["active_rate"] is None:
# The reporter records what it saw, not the fix: no column name, no figure.
failed = "The definition names a column the numbers source does not have."
closing["reflection"] = {"what_failed": [failed], "evidence": [DEFINITION_KEY]}
closing["reflection"] = {"what_failed": [PROBLEM], "evidence": [DEFINITION_KEY]}
closed = await self.call(
REPORTER,
"run.complete",
Expand Down Expand Up @@ -1167,15 +1186,77 @@ async def run_2(self) -> None:
unaffected = same and first["grade"] == second["grade"] == "pass"
self.check("control_unaffected_by_the_correction", unaffected)

# ---- stage 3: report ---------------------------------------------------------------

async def report(self) -> None:
"""The reporter reads the definition's source row and files a report against
that revision, citing run 1 and its reflection. Sent a second time, the report
is the same one. The reviewer takes it, and its resolution is refused while the
row holds no newer revision. Only its reporter and an administrator read a
report, so the reviewer reads it and hands the curator the target it names and
its id."""
row = await self.definition_until(REPORTER, self.held.first_sha256)
read = revision(row, self.team, DEFINITION_KEY, "memory.get before the report")
run_1 = self.result["runs"]["run_1"]["run_id"]
cited = [f"run:{run_1}", f"reflection:{run_1}"]
# `run_id` names the run that met the problem. The SDK fills an unset one with
# "-", which the op reads as a run and refuses as one it cannot find.
filing = {
"agent": "-",
"run_id": run_1,
"kind": "outdated",
"target_kind": "memory",
"target_key": DEFINITION_KEY,
"target_version": read["version"],
"target_sha256": read["sha256"],
"problem": PROBLEM,
"evidence": cited,
}
filed = await self.call(REPORTER, "knowledge.reports.submit", **filing)
named = {"report_id": str(filed.get("report_id") or "")}
opened = (filed.get("state"), filed.get("version")) == ("open", 1)
self.check("report_filed_open", bool(named["report_id"]) and opened)
again = await self.call(REPORTER, "knowledge.reports.submit", **filing)
self.check("second_submit_returns_the_same_report", again == filed)
took = await self.call(REVIEWER, "knowledge.reports.update", action="take", **named)
taken = (took.get("state"), took.get("version")) == ("taken", 2)
self.check("report_taken_by_the_reviewer", taken)
early = await self.send(
REVIEWER,
"knowledge.reports.update",
action="resolve",
resolution_revision=read["version"],
**named,
)
self.unrevised("resolve_before_publication_refused", early, read["version"])
# Not repeated, here or in `evidence`: Loom reads a report with sequential
# consistency, so the read shows the last acknowledged change without a wait.
got = (await self.call(REVIEWER, "knowledge.reports.get", **named)).get("report") or {}
target = {"kind": got.get("target_kind"), "namespace": self.team}
target.update(key=got.get("target_key"), version=got.get("target_version_text"))
same = target == {name: read[name] for name in target}
unchanged = got.get("target_changed") is False and got.get("evidence") == cited
self.check("report_names_the_revision_that_was_read", same and unchanged)
kept = (got.get("state"), got.get("version"), got.get("resolution_revision"))
self.check("report_unchanged_by_the_refused_resolve", kept == ("taken", 2, ""))
self.held.report_id = named["report_id"]
self.held.handoff = {**named, "target": target}
self.result["ids"].update(named)
self.entry().update(revision=read, handoff=self.held.handoff)

# ---- stage 4: investigation --------------------------------------------------------

async def investigation(self) -> None:
"""The curator reads the definition and the source document, then writes the
candidate against the revision it read, naming the document. This direct write
stands in for a curation pass. Sent a second time, the write names a revision
the row no longer holds, and the server refuses it."""
"""The curator reads the revision of the definition the reviewer handed it and
the source document, then writes the candidate against the revision it read,
naming the document. This direct write stands in for a curation pass. Sent a
second time, the write names a revision the row no longer holds, and the server
refuses it."""
held = self.held
read = await self.definition_until(CURATOR, held.first_sha256)
handed = held.handoff["target"]
reported = (handed["key"], handed["version"]) == (DEFINITION_KEY, read.get("version_text"))
self.check("curator_read_the_reported_revision", reported)
document, _, found = await self.until(
lambda: self.call(CURATOR, "knowledge.get", source_uri=SOURCE_URI), is_found
)
Expand Down Expand Up @@ -1407,8 +1488,9 @@ async def publication(self) -> None:
"""After the refused approval the reviewer reads the row again, compares it with
the text it accepts and approves the hash of that read. The hash a refusal
carried is never sent back unseen. A read that must show the curator's amendment
or the promotion is repeated until it does. The last read is of the shared copy
the promotion wrote."""
or the promotion is repeated until it does. The reviewer then resolves the
report with the revision it published. The last read is of the shared copy the
promotion wrote."""
amended = self.fixture["curation.json"]["amended"]

def read() -> Awaitable[dict[str, Any]]:
Expand Down Expand Up @@ -1443,13 +1525,22 @@ def read() -> Awaitable[dict[str, Any]]:
held.event, held.promote_request_id, held.published = event, request_id, published
held.author, held.promoted_by = after.get("actor"), lineage.get("promoted_by")
self.result["ids"]["promotion_events"].append(event)
resolved = await self.call(
REVIEWER,
"knowledge.reports.update",
report_id=held.report_id,
action="resolve",
resolution_revision=published["version"],
)
closed = resolved.get("state") == "resolved"
self.check("report_resolved_with_the_published_revision", closed)
self.entry()["copy"] = await self.shared_copy(amended)

# ---- stage 8: evidence ---------------------------------------------------------------

async def evidence(self) -> None:
"""Read back, as the reporter, what Loom holds for each run and for the source
of the correction, and label every link between the stages."""
"""Read back, as the reporter, what Loom holds for each run, for the source of
the correction and for the report, and label every link between the stages."""
want = [DEFINITION_KEY, PROCEDURE_KEY]
for name, run in self.result["runs"].items():
grade = self.fixture["expected.json"]["runs"][name]["grade"]
Expand All @@ -1474,19 +1565,26 @@ async def evidence(self) -> None:
)
linked = provenance.get("source_resource_id") == self.held.doc_id
self.check("correction_names_the_source_document", linked)
named = {"report_id": self.held.report_id}
report = (await self.call(REPORTER, "knowledge.reports.get", **named)).get("report") or {}
resolution = (report.get("state"), report.get("resolution_revision"))
published = resolution == ("resolved", self.held.published["version"])
self.check("report_names_the_published_revision", published)
self.result["links"] = self.links()

def links(self) -> list[dict[str, Any]]:
"""Each link between the stages, with who holds it and the read that shows it."""
held, runs = self.held, self.result["runs"]
run_1, run_2 = runs["run_1"]["run_id"], runs["run_2"]["run_id"]
document = {"kind": "document", "source_uri": SOURCE_URI, "doc_id": held.doc_id}
report = {"kind": "report", "report_id": held.report_id}
report["resolution_revision"] = held.published["version"]
review = {"kind": "promotion", "promotion_event": held.event}
review.update(promoted_by=held.promoted_by, audit_request_id=held.promote_request_id)
published = {name: value for name, value in held.published.items() if name != "read"}
rows = [
("problem", {"kind": "run", "run_id": run_1}, "loom"),
("problem_to_correction", {"kind": "text", "field": "rationale"}, "client"),
("problem_to_correction", report, "loom"),
("source_evidence", {**document, "revision": held.document_revision}, "loom"),
("correction", {**published, "author": held.author}, "loom"),
("review", review, "loom"),
Expand All @@ -1496,7 +1594,7 @@ def links(self) -> list[dict[str, Any]]:
]
reads = {
"problem": "run.get: grade; memory.get: reflection:<run_id>",
"problem_to_correction": "memory.lineage: rationale, text that names run 1",
"problem_to_correction": "knowledge.reports.get: state, resolution_revision",
"source_evidence": "memory.provenance: source_resource_id; knowledge.get: doc_id",
"correction": "memory.get: content_sha256, version_text, actor",
"review": "memory.lineage: promoted_by, promotion_event; audit.list: actor",
Expand All @@ -1515,9 +1613,6 @@ async def run(self) -> None:
try:
for name in STAGES:
entry = self.entry(name)
if entry["status"] == "not_exercised":
say(f"{name}: not exercised (needs {entry['needs']})")
continue
self.stage = name
await self.run_stage(name, entry)
# After preflight, so before the first write, and after every stage:
Expand Down
Loading
Loading