"""Minimal run audit — one record per call, results NEVER stored. Records who called which endpoint, with how many identifiers and what status. Neither the identifiers nor the payload are written (the ADR-0008 posture of the sibling specialists — orchestrator persistence stores results in ITS private index; the specialist's sink stays result-free). Failure to write never fails a call. Destination is the configured sink (``LOG_SINK``, see :mod:`logging_sink`): ``local`` by default, ``hf`` on the deployed Spaces so the trail survives a rebuild (2026-10-13; the temp-dir JSONL this replaced was erased by every rebuild). The ``hf`` upload runs on a daemon thread: the answer never waits on HuggingFace. A slow or failing hub (HF git returned 500s for minutes on 2026-10-13) must not push a call past the orchestrator's 120 s budget. The cost is that a record still uploading when the container is killed is lost — seconds, against the whole trail before. """ from __future__ import annotations import datetime import secrets import threading from access import access_enforced, role_for from logging_sink import get_log_sink, persist_trace_safe def record_run( tool: str, *, username: str | None, n_identifiers: int | None, status: str, run_id: str | None = None, ) -> threading.Thread | None: """Build and persist one audit record. Returns the upload thread for the ``hf`` sink. ``run_id`` is the payload's own id (None for denials and input errors). The record's storage key is that id, or a fresh one when there is none, so no record overwrites another. Fail-open: any error building or writing the record is swallowed. """ try: now = datetime.datetime.now(datetime.UTC) key = run_id or f"{now:%Y%m%d_%H%M%S}_{secrets.token_hex(4)}_{status}" record = { "run_id": run_id, "timestamp": now.isoformat(), "tool": tool, "status": status, "n_identifiers": n_identifiers, "principal": username or "anonymous", "role": role_for(username), "enforced": access_enforced(), } sink = get_log_sink() if sink.name != "hf": persist_trace_safe(sink, key, record) return None upload = threading.Thread( target=persist_trace_safe, args=(sink, key, record), name="audit-upload", daemon=True ) upload.start() return upload except Exception as e: # noqa: BLE001 — auditing must never crash a request print(f"[audit] record_run failed: {e}") return None