Skip to Content
Recodocs

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.

8 min read

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 ownsIt does not own
How JSON is encoded for hashing and how a fingerprint is formedWhat a fingerprint is used for (cache keys, approval digests, idempotency)
Atomic, private file publication and advisory file locksDirectory permissions above the file, retention and backup
Strict parsing: no duplicate keys, no NaN, timestamps as UTCThe schema of the body you parse
A base class for refusals that carry a stable machine-readable codeThe refusal codes of your own domain
JSON log records with correlation fields and no exception valuesWhere logs go and how long they are kept
Throwaway SQLite and Postgres databases for testsYour 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 pathWhat it is for
recohut_kit.jsonJsonValue, 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 pathWhat it is for
recohut_kit.filesatomic_write, atomic_private_json, file_sha256, file_lock, safe_filename.
recohut_kit.testingtesting.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.evidenceEvidenceReference: a portable provenance envelope, independent of domain truth.
recohut_kit.interactionsRestricted application-declared edits and server-owned continuation context.
recohut_kit.inspectionSession-local execution inspection: bounded spans, sanitized payloads, a FastAPI view.
recohut_kit.deliverablesLinear immutable documents, server digests and pinned approval proofs.
recohut_kit.qualityread_coverage and require_coverage: parse a coverage report; never runs tests.

Catalog

Import pathWhat it is for
recohut_kit.json_pairsreject_duplicate_keys: an object_pairs_hook that raises on the first repeated key.
recohut_kit.json_valuesparse_json_object: parse a JSON object or raise your error, rejecting duplicate keys and non-finite numbers.
recohut_kit.json_stringsmap_strings: apply a function to every string leaf of a JSON-like tree.
recohut_kit.time_valuesparse_utc_time: ISO-8601, datetime or optional epoch to an aware UTC datetime.
recohut_kit.refusal, recohut_kit.refusal_codesCodedRefusal (a ValueError with .code and .detail), ReasonRefusal, and shared code spellings such as stale and replayed.
recohut_kit.logging_jsonJSONFormatter and bind_context: one bounded JSON object per record with request, session, run and tool ids.
recohut_kit.artifactsmanifest, verify_manifest, read_jsonl: fingerprint chosen files and read bounded JSONL.
recohut_kit.dag_orderdependency_order: dependency waves for a declared DAG, with no scheduler.
recohut_kit.principalPrincipal (subject, tenant, authority): construct only after the host authenticates.
recohut_kit.secretsSecretReader protocol, AWSSecretsManager, DatabricksSecrets, SealedFileStore. No discovery of environment or profile.
recohut_kit.parametersread_parameter: an explicitly injected SSM Parameter Store read.
recohut_kit.tokenscount and TiktokenTokenizer behind the tokens extra.
recohut_kit.telemetryCaller-owned OpenTelemetry providers and metadata-only usage spans.
recohut_kit.operation_receiptsMetadata-only receipts for deterministic tools.
recohut_kit.cited_linesrefuse_uncited_lines: every line of a report must cite a known reference.
recohut_kit.http_deadlineRequestDeadlineMixin: a wall-clock deadline for http.server handlers.
recohut_kit.restraintsilent_content and is_silent_content: the shared "no reply needed" result.
recohut_kit.pluginsA small trusted-plugin Registry and entry-point discover.
recohut_kit.charts, recohut_kit.boundedBounded static charts with exact decimals; recoverable result slices.
recohut_kit.local_containersExact-identity ownership of one throwaway Docker container.
recohut_kit.skillpacksBuild and verify a client-installable skill pack with a SHA-256 manifest.
recohut_kit.concurrencyBounded thread and semaphore admission, task groups, a blocking guard, durable SQLite jobs.
recohut_kit.capability_indexQuery 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.

fingerprint.py
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.

files.py
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.txt

manifest 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.

strict_parse.py
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:00

Coded refusals and dependency order

refusals.py
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 dependency

JSON 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.

logging_setup.py
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.

test_notes.py
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 needUseWhy
A stable key or digest for a request, approval or cache entryjson.fingerprintOne encoding for the whole kit, so digests agree across packages.
To write a file other processes readfiles.atomic_writeNo torn reads, private by default.
To hash a large filefiles.file_sha256Bounded reads. json.file_digest reads the whole file into memory.
A list of files with hashes you can re-checkartifacts.manifestExplicit paths, no recursion.
To accept a JSON body from outsidejson_values.parse_json_objectRefuses repeated keys and non-finite numbers.
A typed error callers can branch onrefusal.CodedRefusalA stable .code and free-text .detail.
A secret from a storesecrets.AWSSecretsManager or DatabricksSecretsA reader is passed in; nothing is discovered.
A database for a testtesting.sqlite or testing.postgresOwned 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_json is strict. It raises ValueError for NaN and infinity and TypeError for values that are not JSON. Use as_json_value first when you need sets or enums normalised.
  • atomic_write promises 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 by atomic_private_json is set to 0700.
  • file_lock is POSIX advisory. A lock file existing does not mean someone holds the lock, and Windows is unsupported: the function raises ImportError when called.
  • safe_filename raises ValueError with the code invalid_filename for names containing separators, colons or control characters, for . or .., or for names longer than 255 characters.
  • Logging drops data on purpose. JSONFormatter never calls getMessage or formats exception values. A record with positional arguments gets arguments_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.
  • Principal is 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