decision-cascade

Local engine for typed, calibrated decisions for AI agents.

View the Project on GitHub slavabars/decision-cascade

Stability: what 1.x promises and what stays beta

English · Русский

The project has been stable since 1.0.0. Every exit criterion is closed and has been checked automatically ever since, not just claimed: the API contract, the pack format and the meaning of DECISION_* variables do not break inside the 1.x line — changes land only in a major, with a two-minor deprecation window.

Stability is about the contract and reproducibility, not about universality: some surfaces (the option-scoring head, encoder fine-tuning and feedback retraining) remain beta — they are measured, but they depend on the domain and may change in minor releases. The risk-aware cascade is stable since 1.1: its contract is described in §7. The benefit cascade is stable since 1.6: its contract is described in §8. The conformal cascade is stable since 1.7: its contract is described in §9. The full list is in §2.

1. What “stable” means for this project

Three promises that 1.0 makes:

  1. The API contract does not break. POST /decisions, /decisions/batch, /v1/systemone, /v1/feedback, GET /info and schema_version = "1" change only with a major bump and a deprecation window (2 minor versions).
  2. Artifacts stay readable. A pack (heads.pt + metadata.json + temperature.json) and a checkpoint written under schema_version are read by every version of the 1.x line.
  3. The published numbers reproduce. Any figure from benchmarks.md is produced by a command from the documentation on Ubuntu 22.04+ with a 16 GB GPU, not “on the author’s laptop”.

Stability does not mean: universality (zero-shot), beating LLMs in open domains, or a cloud SLA. This is a local decision engine, and the promise covers only the contract, reproducibility and behaviour on your own domain.

2. What is already stable and what is experimental

Surface Status Comment
/decisions, /decisions/batch stable schema schema_version = "1", contract tests
/v1/systemone stable external Jev/TypeSafe protocol, must not change
Media images/videos beta paths inside DECISION_MEDIA_ROOT or bytes/data: URIs; video requires ffmpeg/ffprobe 4.4+, DECISION_VIDEO, DECISION_VIDEO_MAX_SECONDS, DECISION_VIDEO_TIMEOUT; contract in docs/en/deploy.md, docs/en/troubleshooting.md
/v1/feedback stable (beta policy) transport is fixed; the meaning depends on the cascade
decision_id in responses stable since 1.9 dec_<uuid4.hex>; batch — decision_ids, SystemOne — X-Decision-Id
Decision audit log (DECISION_DECISION_LOG) beta JSONL, state opt-in with AES-256-GCM, TTL/deletion; §11
OpenTelemetry traces (DECISION_OTEL) beta HTTP, encoder, heads and remote call; no state; contract docs/en/observability.md §7
policy/abstain beta §12; abstain is a flag, not a replaced decision
GET /v1/stats beta aggregates without state/names; §14
GET /v1/questions beta question catalog from packs: name, type, signature, packs, examples, ECE, gate (ok/rejected/unknown); no state or paths
GET /console beta local HTML console, form -> /decisions; no external assets and no state on the server
POST /decisions/batch/jobs, GET /decisions/batch/jobs/{id} beta async batch jobs: in-memory queue, TTL, limits; no state; §17 contract
explain=true in /decisions beta options, nearest examples and calibration without state; §16 contract
Feedback by decision_id beta §15
GET /info stable the key set only grows, never shrinks
GET /health, GET /ready stable liveness/readiness for systemd and load balancers; 503 while not ready
Pack heads.pt + metadata.json + temperature.json stable reading older versions is mandatory
DECISION_* variables from the README stable new ones are added, old ones keep their meaning
Python SDK (api.sdk.client) beta sync/async DecisionClient, canonical_state, schema and distribution validation; §18 contract
TypeScript SDK (sdk/typescript) beta ESM client + index.d.ts, canonicalState, the same response validation
CLI decision beta serve, serve --dry-run, doctor and pack list/install/verify/update/rollback; dry-run loads no model and uses no network, doctor prints PASS/WARN/FAIL with hints, pack verify works offline, feedback stats reads the journal, pack init builds a pack from 10–50 examples with a gate, batch supports resume and shards, mcp --stdio and opt-in mcp --http (loopback) start a local MCP server; eval report/calibration/latency/competitors and train heads/calibrate run the existing eval.*/training.recipe.* entry points without duplicating their CLIs
Confidence threshold (DECISION_CASCADE_THRESHOLD) stable the default policy
Risk-aware cascade (DECISION_CASCADE_RISK_BUDGET) stable since 1.1 §7 contract: variables, /info, usage.reason, /v1/feedback, hard gate
Benefit cascade (DECISION_CASCADE_POLICY=benefit) stable since 1.6 §8 contract: variables, /info, usage.reason, /v1/feedback, precedence over the risk budget
Conformal cascade (DECISION_CASCADE_POLICY=conformal) stable since 1.7 §9 contract: conformal.json certificate, /info, usage.reason, hard gate, no feedback; threshold selection fixed in 1.8, legacy certificates are rejected
Feedback journal (DECISION_FEEDBACK_PATH) stable since 1.8 JSONL v1 by default, unknown versions are skipped; SQLite (DECISION_FEEDBACK_BACKEND=sqlite) is beta: WAL, dedup, retention; §7–§8 contract
Question router (DECISION_QUESTION_ROUTER) beta paraphrase transfer to a known question; off by default
Exploratory escalation (DECISION_CASCADE_EXPLORE) beta IPS estimate of q; default 0, behaviour unchanged
Hub packs (DECISION_PACK_REPO, DECISION_PACK_CACHE, DECISION_PACK_REQUIRE_SIGNATURE) beta cache, manifest, sha256 and Ed25519 signature verification; mutually exclusive with DECISION_CHECKPOINT_DIR
Option-scoring head beta option transfer is measured, not used in the published packs
Encoder fine-tuning (finetune_encoder) beta measured (+5 pp), weights ship as a release asset
Feedback retraining (training.feedback) beta “do not harm” gate and drift numbers — ../drift.md
eval/*, judge, benchmark scripts no guarantees internal tooling

3. Exit criteria for 1.0 (all met)

Each item is verifiable, not a “feeling of maturity”.

# Criterion Now What was left
1 No breaking changes for 3 minor releases in a row 0.10 → 0.15 without breaking the contract —
2 Deprecation policy published published in §5, registry api/server/deprecation.py —
3 Contract tests for every endpoint and the SDK present for every endpoint — (reference pack 0.8 in tests/fixtures/)
4 Coverage of src + api ≥ 90% 94% — (gate --cov-fail-under=90 in CI)
5 CI: ruff, shellcheck, pytest, build and smoke of the installed wheel all of the above — (scripts/smoke_wheel.sh)
6 Quality regression pinned in CI nightly job on release packs, 1 pp threshold; p50/p95 latency budget — (eval/nightly.py)
7 Data reproducibility RouterBench and AG News pinned by revision, uv.lock present —
8 Operations: liveness/readiness, timeouts, graceful shutdown /health, /ready, budget and retry, SIGTERM test —
9 Security: threat model, no PII in logs, dependency audit SECURITY.md, log test, pip-audit in CI —
10 Documentation: quick start in a clean environment, Ubuntu/CentOS deploy, upgrade/rollback deploy.md, troubleshooting.md, automatic rollback — (a live VM run follows the checklist)
11 Measurements published with raw data and commands benchmarks.md + release assets —
12 Two releases in a row without a fire (a hotfix for breaking behaviour) 0.13 → 0.15 clean —

Items 1 and 12 were closed by the 0.10 → 0.15 series: there were no breaking contract changes and no hotfixes for breaking behaviour. By 1.0.0 all twelve items were closed, and each one keeps being checked: contract tests and coverage in CI, the nightly regression on the current release packs, deploy and rollback by tests and the deploy.md checklist. If a criterion stops holding, CI or the nightly job will show it, not a user after a release.

4. How we got to 1.0

P0 — done in 0.13.0 (contract and operations)

  1. ✅ /health (liveness, always answers) and /ready (readiness: encoder, readable heads, degraded on a cascade with an unreachable fallback). 503 while the service is not ready.
  2. ✅ A DECISION_BACKEND_TIMEOUT budget for the whole external call, one retry (DECISION_BACKEND_RETRIES) for network/429/5xx and 502 BACKEND_UNAVAILABLE once retries are exhausted. 4xx is not retried.
  3. ✅ Coverage gate --cov-fail-under=90 in pyproject.toml + CI and a smoke test of the installed wheel (scripts/smoke_wheel.sh: clean venv, /health, /ready, POST /decisions).
  4. ✅ AG News pinned by revision (AG_NEWS_REVISION), uv.lock added; CI checks it is current with uv lock --check.
  5. ✅ tests/test_logging_privacy.py: state, images and /v1/feedback bodies never reach the logs; external backend errors do not contain the request body.

P1 — done in 0.14.0 (contract stability)

  1. ✅ Deprecation policy published (§5): registry api/server/deprecation.py, Deprecation/Sunset/Link headers, a warning in the log once per process, and a “not earlier than +2 minor” check at startup and in tests.
  2. ✅ Reference pack tests/fixtures/pack_v0.8.0.pt (built by the v0.8.0 tag) is read by the current version and serves decisions — tests/test_pack_compat.py.
  3. ✅ Nightly job .github/workflows/nightly.yml: packs from the latest release, AG News and RouterBench on pinned revisions and seeds, failure on a regression above 1 pp, plus a p50/p95 latency budget (--latency fail) and a run on push to main when decision code paths change (eval/nightly.py, eval/nightly_baseline.json). A separate GPU run, .github/workflows/nightly-gpu.yml, checks the same regression on CUDA against the gpu_latency budget.
  4. ✅ Upgrade/rollback: deploy/upgrade.sh (backup → git pull → venv → restart → /ready, automatic rollback of data and code), deploy/backup.sh, deploy/restore.sh; Ubuntu/CentOS parity is checked by distro_from_release on temporary os-release files, and the full cycle was run live on Ubuntu 24.04 and CentOS Stream 9 (deploy.md §5).
  5. ✅ Troubleshooting: troubleshooting.md — every API error code, /ready 503, missing q, choice_head/dim mismatch.
  6. ✅ Graceful shutdown: KillSignal=SIGTERM, TimeoutStopSec=30, --timeout-graceful-shutdown 30; the contract is pinned by tests/test_graceful_shutdown.py.
  7. ✅ pip-audit -r requirements.txt in CI: no known vulnerabilities.

P2 — done in 0.15.0

  1. ✅ The fine-tuned encoder was published as the v0.12.0-encoder-routerbench-bert.tar.gz asset (405 MB) in release v0.12.0; routerbench.md was updated, the recipe remains for reproduction.
  2. ✅ Prometheus metrics (GET /metrics) and structured logs with X-Request-ID (DECISION_LOG_FORMAT=json) — api/server/metrics.py, api/server/observability.py, observability.md.
  3. ✅ Weak labeling: python -m training.labeling.run labels unlabeled texts with SystemOne teacher answers and writes a dataset that train_heads accepts — weak-labeling.md.
  4. ✅ Multi-domain packs: the service looks for */heads.pt + metadata.json and picks a pack by questions_signature; duplicate signatures are resolved by the first in sort order with a WARNING, and the source is visible in GET /info — tests/test_multidomain.py.

1.0.0 — stable status

Functionally 1.0.0 is identical to 0.16.0: there are no new features, only status and promises change. The package carries the 5 - Production/Stable classifier, the README and this document; the API contract, pack format and meaning of DECISION_* are frozen by the rules of §5. After that, minor versions add features, patches fix bugs, and breaking changes happen only in a major.

5. Deprecation policy (in effect since 1.0)

The mechanism is the DEPRECATIONS registry in api/server/deprecation.py:

Deprecation(
    item="/decisions",          # path, response field or DECISION_* name
    since="1.0.0",              # where it is announced
    remove_in="1.2.0",          # where it disappears: not earlier than +2 minor
    alternative="/v2/decisions",
    sunset="Tue, 01 Sep 2026 00:00:00 GMT",
)

What this gives a client and operations:

Signal Where it is visible
Deprecation: true response header on a deprecated path (RFC 9745)
Sunset: <date> header when a shutdown date is announced (RFC 8594)
Link: <...>; rel="deprecation" header with a link to the replacement
WARNING deprecated ... decision.deprecation log, once per process lifetime
### Deprecated CHANGELOG of the release where it is announced

The registry is validated at startup (validate_registry) and by a test: a remove_in earlier than two minor versions ahead is an error, not a warning. A surface may only be removed in a major, after it has lived through the announced period.

6. Risks that remain after 1.0

1.0 is a promise about the contract, not about universality. These limitations remain after the release, and no version can “close” them:

  1. Labels. All value starts after a few thousand labeled examples per domain. Weak labeling (weak-labeling.md) lowers the entry price but does not replace validation on real labels.
  2. Zero-shot. Competitors work out of the box; we do not. Positioning must admit this, otherwise the first comparison without labels devalues the project.
  3. Domain drift. Heads age without new examples. The answer is measured (drift.md): retraining with replay and a gate gives a limited gain, and a change of the class set requires a separate pack. “Stable” refers to the contract, not to quality on the cut-off date.
  4. One person. Bus factor: documentation, reproducibility and artifacts are the only insurance; that is why they are in the exit criteria rather than “later”.

7. Risk-aware cascade contract (stable since 1.1)

Enabled by the pair DECISION_BACKEND=cascade + DECISION_CASCADE_RISK_BUDGET. Everything below is a promise of the 1.x line: it can only change in a major.

Environment variables

Variable Meaning Allowed values Default
DECISION_CASCADE_RISK_BUDGET share of errors we are willing to accept locally 0…1 — (mode off)
DECISION_RISK_MODEL_PATH file of the P(error) estimator path <DECISION_CHECKPOINT_DIR>/risk.json
DECISION_RISK_FEW_SHOT_N how many own examples before retraining >= 2 enables; 0/1 disables 10
DECISION_RISK_GATE_DELTA tolerance for the hard gate certificate > 0 relaxes, < 0 tightens 0.0
DECISION_FEEDBACK_PATH feedback journal (JSONL): few-shot examples and q counters path; empty — memory only — (memory)
DECISION_FEEDBACK_BACKEND journal backend: jsonl or sqlite jsonl; SQLite is opt-in and does not migrate old JSONL automatically jsonl

An invalid value (budget outside [0, 1], not a number) is a startup error, not silently different behaviour. A missing risk.json with the budget enabled is also a startup error with a hint on how to train the model.

GET /info -> engine

Key Type When present
risk_budget float always with the risk cascade
risk_gate "ok" / "rejected" always
risk_gate_delta float always
risk_few_shot_n int when few-shot is enabled
risk_few_shot list of question names when few-shot is enabled
feedback_path string when DECISION_FEEDBACK_PATH is set
feedback_restored int when DECISION_FEEDBACK_PATH is set: how many events were restored from disk

Keys may be added, but never renamed or removed.

usage in the decision response

POST /v1/feedback

200 with accepted and questions[], where each question has question, accepted, examples, reference, retrained. If few-shot is off — 409 FEEDBACK_UNSUPPORTED, and the same is visible in GET /info -> accepts_feedback.

Feedback journal (DECISION_FEEDBACK_PATH)

By default examples and counters live only in process memory: a restart returns the service to the state captured at deployment. With DECISION_FEEDBACK_PATH set, feedback survives a restart.

The feedback_path and feedback_restored keys in GET /info -> engine show whether the journal is enabled and how many events were restored at startup.

Hard gate

A rejected certificate (risk.json -> gate.accepted = false) is not relaxed: the risk rule is not applied, escalation follows DECISION_CASCADE_THRESHOLD, reason = "risk_gate". The gate can only be relaxed with an explicit DECISION_RISK_GATE_DELTA > 0; this is written to the log and visible in /info.

risk.json

Fields weights, bias, feature_names, gate. The default feature names are confidence, entropy, margin. Files without gate are read as “no measurements were made” (the gate does not reject).

The contract is pinned by tests/test_risk_contract.py, which also checks that the documentation and the code have not drifted apart.

8. Benefit cascade contract (stable since 1.6)

Enabled by DECISION_BACKEND=cascade + DECISION_CASCADE_POLICY=benefit. The policy answers not “how confident is the local head” but “is it worth paying for the external model”: escalation pays off when p < q - C / (1 + D), where p is the calibrated confidence of the local decision, q is the measured accuracy of the external model on this question, D is the error cost and C is the escalation cost in “correct answer = 1” units. If the external model is weaker than the local one on a question, the cascade does not escalate at all. Everything below is a 1.x promise: changing it requires a major.

Environment variables

Variable Meaning Accepted values Default
DECISION_CASCADE_POLICY escalation policy ""/threshold/confidence — threshold; benefit/benefit-aware — benefit "" (threshold)
DECISION_CASCADE_REMOTE_ACCURACY external accuracy q: a number, a JSON path or the JSON itself a number in (0, 1] or fit_remote_accuracy JSON — (required for benefit)
DECISION_CASCADE_REMOTE_ACCURACY_BOUND which q estimate to take from JSON point — point estimate, lower — Wilson lower bound point
DECISION_CASCADE_ESCALATION_COST external call cost C; wins over the table price >= 0 0.05 or the model price from DECISION_PRICE_TABLE
DECISION_PRICE_TABLE per-call prices for external models, used by usage.cost_usd and as the default C JSON file or inline JSON: models and default_per_call_usd — (price unknown)
DECISION_CASCADE_ERROR_COST error cost D >= 0 1.0
DECISION_CASCADE_FEEDBACK_SHRINKAGE prior q weight in pseudo-observations W > 0 50
DECISION_CASCADE_EXPLORE share of decisions the policy would keep local that still go outside for an honest q estimate 0…1 0 (off)
DECISION_CASCADE_EXPLORE_SEED generator seed for exploratory escalations integer — (random)
DECISION_FEEDBACK_PATH feedback journal (JSONL): q counters survive a restart (shared variable with the risk cascade) path; empty — memory only — (memory)
DECISION_FEEDBACK_BACKEND journal backend shared with the risk cascade jsonl; SQLite is opt-in and does not migrate old JSONL automatically jsonl

An unknown policy, an invalid q bound, q outside (0, 1], negative costs, W <= 0 and explore outside [0, 1] are startup errors, not a silent fallback to the confidence threshold. DECISION_CASCADE_POLICY=benefit takes precedence over DECISION_CASCADE_RISK_BUDGET: when both are set, benefit runs and no risk.json is needed.

Exploratory escalations. Feedback arrives for answers that went outside, that is, for hard cases; without exploration q is estimated on a biased sample. With DECISION_CASCADE_EXPLORE > 0 a share of decisions the policy would keep local is still sent outside, and observations are weighted by the escalation probability (IPS): policy escalation weighs 1, exploratory escalation weighs 1 / epsilon capped at 20. The probability is written to the DECISION_FEEDBACK_PATH journal, so IPS sums are restored after a restart. Bias and cost measurements — exploration.md.

GET /info -> engine

Key Type When present
policy "benefit" always with the benefit cascade
remote_accuracy float or “question → q” mapping always; same shape as configured
remote_accuracy_default float always: q for a question outside the mapping (the mean of the configured ones)
escalation_cost float always
error_cost float always
feedback_shrinkage float always
benefit_threshold float always: threshold p for a question outside the mapping
benefit_thresholds “question → threshold” mapping always; empty when q is a number
benefit_feedback “question → total observations” mapping always; empty until feedback arrives
explore_rate float always: configured share of exploratory escalations
explore_calls int always: how many exploratory calls this process made
feedback_path string when DECISION_FEEDBACK_PATH is set
feedback_restored int when DECISION_FEEDBACK_PATH is set: how many observations were restored from disk

Keys may be added, but never renamed or removed.

usage in the decision response

POST /v1/feedback

Same transport as the risk cascade, different meaning: the model is not retrained (retrained = false), q for the question is refined instead. Each question in the response has question, accepted, examples, reference, retrained, remote_accuracy — the updated q. Only decisions that actually went to the external model count: local head answers do not change q, and repeated feedback for the same returned decision is not counted twice. The estimate shifts in a Bayesian way: q_new = (q_prior * W + correct) / (W + total). Counters are stored in the DECISION_FEEDBACK_PATH journal (see §7) and restored at startup, while the ledger of handed-out decision fingerprints is not: feedback about escalations is effective within the process lifetime. With exploration, total is a sum of weights: a policy escalation weighs 1, an exploratory one weighs 1 / epsilon capped at 20. A backend without feedback support returns 409 FEEDBACK_UNSUPPORTED, and the same is visible in GET /info -> accepts_feedback.

How q is obtained

q is measured on a held-out slice of the domain, not on the same test where the gain is computed (python -m eval.competitors.fit_remote_accuracy). The JSON may contain accuracy (a single number) and per_question (a mapping), and with ..._BOUND=lower — accuracy_lower and per_question_lower; if the lower bounds are missing, the point estimates are used. A question outside the mapping falls back to the mean over the configured questions.

The contract is pinned by tests/test_benefit_contract.py, which also checks that the documentation and the code have not drifted apart.

9. Conformal cascade contract (stable since 1.7)

Enabled by the pair DECISION_BACKEND=cascade + DECISION_CASCADE_POLICY=conformal. The policy answers a question that neither the confidence threshold nor the error budget asks: with what probability the share of errors among locally accepted decisions stays below alpha on new data. The threshold comes not from a wish but from the conformal.json certificate fitted on a held-out calibration split: split conformal plus the exact Clopper–Pearson upper bound. The promise is given for every question simultaneously (the delta level is split between questions by Bonferroni), because decisions on different questions for the same state are correlated. Everything below is a 1.x promise: changing it requires a major.

Environment variables

Variable Meaning Allowed values Default
DECISION_CASCADE_POLICY escalation policy conformal enables the mode "" (threshold)
DECISION_CONFORMAL_PATH certificate file path <DECISION_CHECKPOINT_DIR>/conformal.json
DECISION_RISK_MODEL_PATH file of the P(error) estimator path <DECISION_CHECKPOINT_DIR>/risk.json
DECISION_CASCADE_THRESHOLD confidence threshold the rejected certificate falls back to 0…1 0.6

The conformal cascade needs both files: the certificate sets the threshold, the estimator computes P(error) for every decision. A missing file is a startup error with a hint on how to train the model and fit the certificate, not a silent fallback to the confidence threshold. DECISION_CASCADE_POLICY=conformal takes precedence over DECISION_CASCADE_RISK_BUDGET but yields to benefit: policy precedence is benefit > conformal > risk budget.

GET /info -> engine

Key Type When present
policy "conformal" always with the conformal cascade
conformal_alpha float always
conformal_delta float always
conformal_threshold float always: threshold on P(error)
conformal_coverage float always: coverage on the calibration split
conformal_risk float or null always: empirical error share on calibration
conformal_upper_bound float always: Clopper–Pearson upper bound
conformal_calibration_n int always: decisions in calibration
conformal_gate "ok" / "rejected" always
conformal_gate_worse list of strings always; empty when "ok"
conformal_test mapping when the certificate carried a test gate slice

conformal_test contains n, coverage, risk, accuracy, baseline_risk and groups — per-question n, accepted, coverage, risk. Keys may be added, but never renamed or removed; risk keys (risk_budget, risk_gate, …) do not appear in the /info of a conformal cascade.

usage in the decision response

Hard gate

The certificate carries the “do no harm” verdict measured on the held-out test: coverage is at least min_coverage, risk is at most alpha with a tolerance and no worse than ranking by confidence at the same coverage. If the verdict is accepted = false, the conformal threshold is not applied: escalation follows DECISION_CASCADE_THRESHOLD, reason = "conformal_gate". The gate cannot be relaxed by an environment variable — only by refitting the certificate on data where it passes.

POST /v1/feedback

The conformal cascade does not accept feedback: the certificate is a property of the calibration sample, and “retraining” the threshold without recomputing the bound would break the promise. The endpoint returns 409 FEEDBACK_UNSUPPORTED, and GET /info -> accepts_feedback shows false.

conformal.json

Fields schema_version = "1", method = "split_conformal_fixed_sequence_clopper_pearson", score = "p_error", alpha, delta, n, min_coverage, selection (fixed-sequence: grid_points, min_group_n), threshold, accepted, coverage, empirical_risk, upper_bound, groups (per-question calibration statistics) and gate (test verdict). The certificate is fitted by python -m eval.conformal.run; production only reads the finished file and does no statistics on the inference path. With zero coverage the certificate honestly refuses: threshold = -1.0, no decision is accepted locally.

The contract is pinned by tests/test_conformal_contract.py, which also checks that the documentation and the code have not drifted apart.

10. decision_id (additive since 1.9)

decision_id is an opaque per-request identifier (dec_ + 32 hex chars) with no state inside. /decisions and /decisions/batch return it (decision_ids in results order); /v1/systemone returns it in the X-Decision-Id header without changing the protocol body. The field is additive, schema_version stays 1; it is not an authenticator, but it grants deletion/feedback for the record — do not log the header at a proxy.

11. Decision audit log (additive since 1.9)

DECISION_DECISION_LOG enables a JSONL audit log with one line per decision: v, decision_id, ts, questions (name → type), decisions, usage, trained, backend, policy (when supplied). state is not written unless DECISION_DECISION_LOG_STATE=1; images and feedback bodies are never written. The file is 600 and its directory 700; DECISION_DECISION_LOG_TTL_HOURS (168), DECISION_DECISION_LOG_MAX_EVENTS (100000) and DECISION_DECISION_LOG_MAX_BYTES (50 MB) bound the log. DELETE /v1/decisions/{decision_id} removes an entry; without the log — 409 DECISION_LOG_DISABLED, unknown id — 404 DECISION_NOT_FOUND, and DECISION_STATS_TOKEN requires Authorization: Bearer.

With DECISION_DECISION_LOG_STATE=1 and DECISION_DECISION_LOG_KEY_FILE set, state is stored only encrypted: the record carries state_enc (v, alg, key_id, nonce, ct) and no plaintext state. AES-256-GCM uses a fresh nonce per record and binds the AAD to decision_id, so moving a block between decisions fails authentication. get/get_many and feedback by decision_id decrypt state transparently; a wrong key or tampered ciphertext returns the entry without state instead of breaking the log. The key file holds one 32-byte key per line in hex or base64, allows # comments and must not be group/world accessible (otherwise startup fails). The first line is the current key, the rest are previous keys for rotation: old records stay readable, new ones use the current key. Keep the key separate from the log and its backups: without it state cannot be recovered, while the other fields remain readable. Only state is encrypted: the remaining fields are not authenticated, and their integrity rests on the 600 file and directory permissions. DECISION_DECISION_LOG_STATE=1 without a key still writes plaintext state and warns at startup.

12. policy and abstain (additive since 1.9)

POST /decisions, /decisions/batch and /v1/systemone accept an optional policy: mode (off, abstain, risk, conformal), risk_budget, max_cost_units, max_cost_usd, latency_ms. off is the default; abstain flags decisions with confidence < DECISION_ABSTAIN_CONFIDENCE (0.6); risk needs a risk model and a budget (client budget is capped by the cascade’s budget); conformal needs a conformal cascade with an accepted certificate. The typed DecisionResult is unchanged: abstain means “review”, not “no decision”. Flags live in usage.abstained and usage.abstentions (confidence, risk_budget, conformal, cost_budget, latency); cost_budget means the actual cost exceeded max_cost_units or max_cost_usd, latency means the delay exceeded latency_ms. max_cost_usd is compared with usage.cost_usd (in a batch — with the total cost of all states) and needs DECISION_PRICE_TABLE with a price for the external model; without it an external backend returns 409 POLICY_UNSUPPORTED, while the zero-cost local path works without a table. A configured table must cover the external backend’s model, otherwise the service does not start. Server limits are DECISION_MAX_RISK_BUDGET, DECISION_MAX_COST_UNITS, DECISION_MAX_COST_USD, DECISION_MAX_LATENCY_MS; exceeding them returns 422 POLICY_LIMIT_EXCEEDED, an unsupported mode returns 409 POLICY_UNSUPPORTED.

13. usage.route/cost_units/latency_ms (additive since 1.9)

Decision responses carry usage. route is local, fallback, mixed, transferred or option_scoring; cost_units is the total escalation cost: escalation_cost × escalated (the number of escalated questions; 0 on the local path). Normally these are abstract units, not dollars; when the benefit cascade takes escalation_cost from DECISION_PRICE_TABLE, cost_units is computed per call and matches cost_usd, so it cannot diverge from the actual bill. cost_usd is the actual cost of external calls in dollars from DECISION_PRICE_TABLE: the model’s per-call price times the number of fallback calls (one call per state, not per question), and always 0.0 on the local path. The SystemOne protocol does not return token counts, so the table prices a call. Without a table cost_usd is absent — that is neither an error nor zero; a configured table must cover the external backend’s model, otherwise the service does not start. usage.fallback is a sanitized external backend response: its cost_usd/route/latency_ms/abstain flags are not echoed and are not treated as server-computed values. latency_ms is the measured backend call latency; for a batch it is the whole batch. For HttpSystemOneBackend, route is fallback and cost_usd appears only when the model has a price. When the router transfers a paraphrase without escalation, route="transferred" and usage.transferred is the number of transferred questions. If option_scoring and the router fire together, route="option_scoring" takes priority while usage.transferred still carries the transfer count. Fields are additive; usage can be null for older clients.

14. GET /v1/stats (additive since 1.9)

The endpoint returns process aggregates: decisions, abstained/abstain_rate, escalated/escalation_rate, routes (local/fallback/mixed/transferred/option_scoring), feedback (events, questions, coverage), cache (size/limit of the heads LRU), packs (loaded/trained) and calibration (questions only for pack questions: examples — accumulated feedback, ece, gate, retrained (true/false/null, where null means the backend has no few-shot); retraining_threshold — cascade threshold or null; unpacked — question/example count and retrained count outside packs, without names; drift — drift aggregates: ece_threshold, min_examples, questions (pack questions: examples, accuracy, ece, drift — true/false once min_examples is reached, otherwise null) and unpacked (question/example count outside packs, without names)). User strings and state are not returned; counters reset on restart. DECISION_STATS_TOKEN enables Authorization: Bearer <token>; without it the endpoint is open like the rest of the local service. The drift threshold is DECISION_DRIFT_ECE (default 0.15), the minimum example count is DECISION_DRIFT_MIN_EXAMPLES (20); drift is null for a backend that keeps no risk-cascade examples.

15. Feedback by decision_id (additive since 1.9)

POST /v1/feedback accepts either examples or items (decision_id, correct, optional question), never both. items requires DECISION_DECISION_LOG: the server loads the record, checks TTL and reconstructs the DecisionResult. A multi-question decision requires question (422 QUESTION_REQUIRED); unknown id — 404 DECISION_NOT_FOUND, expired — 410 DECISION_EXPIRED, log disabled — 409 DECISION_LOG_DISABLED. The risk cascade keeps at most 256 unique questions and retrains the few-shot model not on every request but after DECISION_RISK_FEW_SHOT_N new examples; exceeding the question limit is 422 FEEDBACK_LIMIT_EXCEEDED. idempotency_key caches a successful response for 24 hours in process memory (at most 256 entries); a repeated key with a different body returns 409 IDEMPOTENCY_CONFLICT; the cache is empty after restart.

16. explain=true in /decisions (additive since 1.11)

A request with "explain": true adds explanations per question. For the local backend this is options (variant probabilities; yes/no for noul), neighbors (up to 5 nearest labelled pack examples) and calibration (pack ece, head temperature, threshold from DECISION_CASCADE_THRESHOLD or null). A neighbour carries only question, correct (its label matches the current decision) and distance (cosine distance); example texts and state are not returned. If the pack has no dataset.jsonl, neighbors is absent — not an error. External and cascade backends return no explanations. Explanations are auxiliary: a failure does not break the decision. Fields are additive, explain defaults to false.

17. Asynchronous batch jobs (additive since 1.13)

POST /decisions/batch/jobs accepts states (up to DECISION_ASYNC_MAX_STATES, default 10000) and questions, returns 202 and a job_id; states × questions is bounded by DECISION_ASYNC_MAX_PAIRS (65536) and the worker chunks states. GET /decisions/batch/jobs/{job_id} returns status (queued/running/done/failed), total, completed, created_at, updated_at, error (exception class only) and results (decisions and usage per state). Jobs live in process memory, bounded by DECISION_ASYNC_MAX_JOBS (32) and the DECISION_ASYNC_TTL_SECONDS TTL (3600 s); finished jobs are evicted first. state never appears in status or results; async decisions are not written to the audit log or /v1/stats (deliberate limitation), and usage stays a sanitized backend response without route/cost_usd/latency_ms and abstain flags (including usage.fallback), which only the synchronous layer adds. Unknown id — 404 JOB_NOT_FOUND, limit exceeded — 422 REQUEST_INVALID, active queue overflow — 429 JOB_QUEUE_FULL.

18. state and option order (clarified in 1.13)

state is an opaque string: the server does not parse it as JSON, sort its keys or normalize whitespace. The string goes into the encoder prompt as is, so a client that sends JSON must serialize it canonically (sort_keys, compact separators); the helper is api.sdk.client.canonical_state, and DecisionClient.decisions accepts str | Mapping. Option order is part of the question contract too: it enters the prompt and questions_signature, and a linear head binds logits to option positions, so a trained pack must keep its order; option_scoring accepts a different option set, but embeddings are computed in the order sent. This is a clarification, not a behaviour change: the server still accepts any string within the limit and never rewrites it.