Utility
The small shared helpers under every kit package: canonical JSON and fingerprints, atomic files, strict parsing, refusals, JSON logging, test helpers and the catalog of single-purpose modules.
Different packages should agree on what the same record means. If two services serialize the same object differently, a fingerprint or duplicate check can disagree. The utility layer provides small dependency-free building blocks for deterministic JSON and fingerprints, atomic writes, strict parsing of untrusted bodies, coded refusals, logging and tests. The core owner is recohut_kit.json, described in the kit source as imported by over a thousand modules.
Most of these modules are a page long. They exist so that "hash this request", "write this file without a torn read" and "refuse a repeated JSON key" mean the same thing everywhere in the kit, and so that you can use the same behaviour in your own code.
Where the layer starts and stops
| The utility layer owns | It does not own |
|---|---|
| How JSON is encoded for hashing and how a fingerprint is formed | What a fingerprint is used for (cache keys, approval digests, idempotency) |
| Atomic, private file publication and advisory file locks | Directory permissions above the file, retention and backup |
| Strict parsing: no duplicate keys, no NaN, timestamps as UTC | The schema of the body you parse |
| A base class for refusals that carry a stable machine-readable code | The refusal codes of your own domain |
| JSON log records with correlation fields and no exception values | Where logs go and how long they are kept |
| Throwaway SQLite and Postgres databases for tests | Your schema, migrations and seed data |
Some modules filed under this layer in the kit's tier file belong to a bigger workflow and are documented with it: the governed_*, publication* and retrieval_* modules are the governed retrieval workflow, knowledge* are knowledge-base helpers, and runtime, serving, streams, ui_spec and ui_stream are covered in Serving.
How the pieces fit
json uses nothing else in the kit. files uses only json. That order matters: higher layers can depend on both without creating a cycle.
Owners
Core
| Import path | What it is for |
|---|---|
recohut_kit.json | JsonValue, as_json_value, canonical_json, fingerprint, file_digest, utf8_safe, jsonl_lines. Canonical JSON has sorted keys, compact separators, no ASCII escaping and no NaN. A fingerprint is the SHA-256 of that text. |
Supported
| Import path | What it is for |
|---|---|
recohut_kit.files | atomic_write, atomic_private_json, file_sha256, file_lock, safe_filename. |
recohut_kit.testing | testing.sqlite.sqlite_database and sqlite_fixtures; testing.postgres.postgres_database and postgres_fixtures, which need the testing extra and Docker or a server URL you name. |
recohut_kit.evidence | EvidenceReference: a portable provenance envelope, independent of domain truth. |
recohut_kit.interactions | Restricted application-declared edits and server-owned continuation context. |
recohut_kit.inspection | Session-local execution inspection: bounded spans, sanitized payloads, a FastAPI view. |
recohut_kit.deliverables | Linear immutable documents, server digests and pinned approval proofs. |
recohut_kit.quality | read_coverage and require_coverage: parse a coverage report; never runs tests. |
Catalog
| Import path | What it is for |
|---|---|
recohut_kit.json_pairs | reject_duplicate_keys: an object_pairs_hook that raises on the first repeated key. |
recohut_kit.json_values | parse_json_object: parse a JSON object or raise your error, rejecting duplicate keys and non-finite numbers. |
recohut_kit.json_strings | map_strings: apply a function to every string leaf of a JSON-like tree. |
recohut_kit.time_values | parse_utc_time: ISO-8601, datetime or optional epoch to an aware UTC datetime. |
recohut_kit.refusal, recohut_kit.refusal_codes | CodedRefusal (a ValueError with .code and .detail), ReasonRefusal, and shared code spellings such as stale and replayed. |
recohut_kit.logging_json | JSONFormatter and bind_context: one bounded JSON object per record with request, session, run and tool ids. |
recohut_kit.artifacts | manifest, verify_manifest, read_jsonl: fingerprint chosen files and read bounded JSONL. |
recohut_kit.dag_order | dependency_order: dependency waves for a declared DAG, with no scheduler. |
recohut_kit.principal | Principal (subject, tenant, authority): construct only after the host authenticates. |
recohut_kit.secrets | SecretReader protocol, AWSSecretsManager, DatabricksSecrets, SealedFileStore. No discovery of environment or profile. |
recohut_kit.parameters | read_parameter: an explicitly injected SSM Parameter Store read. |
recohut_kit.tokens | count and TiktokenTokenizer behind the tokens extra. |
recohut_kit.telemetry | Caller-owned OpenTelemetry providers and metadata-only usage spans. |
recohut_kit.operation_receipts | Metadata-only receipts for deterministic tools. |
recohut_kit.cited_lines | refuse_uncited_lines: every line of a report must cite a known reference. |
recohut_kit.http_deadline | RequestDeadlineMixin: a wall-clock deadline for http.server handlers. |
recohut_kit.restraint | silent_content and is_silent_content: the shared "no reply needed" result. |
recohut_kit.plugins | A small trusted-plugin Registry and entry-point discover. |
recohut_kit.charts, recohut_kit.bounded | Bounded static charts with exact decimals; recoverable result slices. |
recohut_kit.local_containers | Exact-identity ownership of one throwaway Docker container. |
recohut_kit.skillpacks | Build and verify a client-installable skill pack with a SHA-256 manifest. |
recohut_kit.concurrency | Bounded thread and semaphore admission, task groups, a blocking guard, durable SQLite jobs. |
recohut_kit.capability_index | Query the generated capability index (standard library only). |
Worked examples
Canonical JSON and fingerprints
Two dictionaries with the same content in a different key order produce the same fingerprint. NaN and infinity are refused, because they have no JSON form.
from recohut_kit.json import as_json_value, canonical_json, fingerprint, jsonl_lines
a = {"b": 2, "a": [1, {"z": None}]}
b = {"a": [1, {"z": None}], "b": 2}
print(canonical_json(a)) # {"a":[1,{"z":null}],"b":2}
print(fingerprint(a) == fingerprint(b)) # True
canonical_json({"x": float("nan")}) # ValueError: not JSON compliant
print(as_json_value({"tags": {"b", "a"}}, sets=True)) # {'tags': ['a', 'b']}
# JSONL is split on \n and \r\n only, so U+2028 inside a string stays in its record.
print(jsonl_lines('{"a":1}\r\n{"b":"x
y"}\n'))fingerprint does not decide scope. If two tenants can send the same request, put the tenant in the value you hash. storage.cache.JsonCache does this for you with its scope argument.
Atomic files and a manifest
atomic_write writes to a temporary file in the same directory, flushes, fsyncs and renames, so a reader sees the old file or the new one and never a partial one. Files are created with mode 0600.
from pathlib import Path
from recohut_kit.artifacts import manifest, verify_manifest
from recohut_kit.files import atomic_private_json, atomic_write, file_lock, file_sha256
root = Path("out")
atomic_write(root / "a.txt", b"hi")
atomic_private_json(Path("priv") / "x.json", {"k": 1}) # parent directory created 0700
with file_lock(Path("out/.lock")): # POSIX advisory lock
records = manifest(root, ["a.txt"]) # path, sha256, size_bytes
verify_manifest(root, records) # passes
(root / "a.txt").write_text("changed")
verify_manifest(root, records) # ValueError: Artifact fingerprint mismatch: a.txtmanifest takes an explicit list of relative paths. It never recurses and never picks up files you did not name.
Strict parsing of an untrusted body
A repeated key lets two readers of one signed body see different values. parse_json_object refuses it, along with NaN and Infinity, and never chains the original exception, so no body content leaks into an error.
from recohut_kit.json_values import parse_json_object
from recohut_kit.time_values import parse_utc_time
class BadBody(Exception):
pass
print(parse_json_object('{"a":1}', error=BadBody, not_json="invalid JSON")) # {'a': 1}
parse_json_object('{"a":1,"a":2}', error=BadBody, not_json="invalid JSON") # raises BadBody
print(parse_utc_time("2026-11-07T10:00:00Z", lambda code, detail: ValueError(code)))
# 2026-11-07 10:00:00+00:00Coded refusals and dependency order
from recohut_kit.dag_order import dependency_order
from recohut_kit.refusal import CodedRefusal
error = CodedRefusal("stale", "record changed")
print(error.code, "|", error) # stale | stale: record changed
steps = [("b", ["a"]), ("a", []), ("c", ["a", "b"])]
print(dependency_order(steps, name=lambda s: s[0], dependencies=lambda s: s[1]))
# (('a', []), ('b', ['a']), ('c', ['a', 'b']))
cycle = [("a", ["b"]), ("b", ["a"])]
dependency_order(cycle, name=lambda s: s[0], dependencies=lambda s: s[1])
# ValueError: DAG cycle or unknown dependencyJSON logs with correlation ids
JSONFormatter writes the event name and the bound context, and drops exception values and positional arguments. Log stable event names, not interpolated data.
import logging
from recohut_kit.logging_json import JSONFormatter, bind_context
handler = logging.StreamHandler()
handler.setFormatter(JSONFormatter())
log = logging.getLogger("demo")
log.addHandler(handler)
log.setLevel(logging.INFO)
with bind_context(request_id="req-1", run_id="run-9"):
log.info("tool.completed")
# {"level":"INFO","logger":"demo","message":"tool.completed","request_id":"req-1",
# "run_id":"run-9","timestamp":"..."}A throwaway database per test
sqlite_database creates a uniquely named file, runs your schema step, yields it, and removes the file and its -wal, -shm and -journal side files even when setup or the test fails.
import sqlite3
from pathlib import Path
from recohut_kit.testing.sqlite import sqlite_database
def schema(path: Path) -> None:
sqlite3.connect(path).executescript("CREATE TABLE notes(body TEXT);")
def test_notes() -> None:
with sqlite_database(schema=schema) as database:
connection = sqlite3.connect(database.path)
connection.execute("INSERT INTO notes VALUES ('hello')")
connection.commit()
connection.close()
assert database.url.startswith("sqlite:///")For pytest fixtures, assign the result of sqlite_fixtures(schema=...) to sqlite_template, sqlite_database in your own conftest.py. The Postgres counterpart is recohut_kit.testing.postgres.postgres_database with pip install 'recohut-kit[testing]'.
Choosing between owners
| You need | Use | Why |
|---|---|---|
| A stable key or digest for a request, approval or cache entry | json.fingerprint | One encoding for the whole kit, so digests agree across packages. |
| To write a file other processes read | files.atomic_write | No torn reads, private by default. |
| To hash a large file | files.file_sha256 | Bounded reads. json.file_digest reads the whole file into memory. |
| A list of files with hashes you can re-check | artifacts.manifest | Explicit paths, no recursion. |
| To accept a JSON body from outside | json_values.parse_json_object | Refuses repeated keys and non-finite numbers. |
| A typed error callers can branch on | refusal.CodedRefusal | A stable .code and free-text .detail. |
| A secret from a store | secrets.AWSSecretsManager or DatabricksSecrets | A reader is passed in; nothing is discovered. |
| A database for a test | testing.sqlite or testing.postgres | Owned lifetime and guaranteed cleanup. |
Failure behaviour, limits and gotchas
- Fingerprints do not carry scope. Equal values hash equal. Include the tenant, account or permission context in what you hash.
canonical_jsonis strict. It raisesValueErrorfor NaN and infinity andTypeErrorfor values that are not JSON. Useas_json_valuefirst when you need sets or enums normalised.atomic_writepromises no directory durability. It fsyncs the file, then renames. It does not promise the directory entry survives a crash. An existing parent directory keeps its permissions; only a directory created byatomic_private_jsonis set to0700.file_lockis POSIX advisory. A lock file existing does not mean someone holds the lock, and Windows is unsupported: the function raisesImportErrorwhen called.safe_filenameraisesValueErrorwith the codeinvalid_filenamefor names containing separators, colons or control characters, for.or.., or for names longer than 255 characters.- Logging drops data on purpose.
JSONFormatternever callsgetMessageor formats exception values. A record with positional arguments getsarguments_omitted. Identity values you bind should already be safe public identifiers. - Postgres test databases need Docker or a named server URL. The helper reads only the environment variable you name in
PostgresConfig, and fails clearly when it is unset. Principalis not a verifier. Construct it only after your host has authenticated the caller. Never deserialize one from a request.
How is this page?
Last updated on