A research prototype for one-pass typed decision models applied to live-chat moderation. Rules are supplied per request; decisions are returned with a gate path. Claims below are scoped to repo measurements unless marked vendor; see BENCHMARKS.md for the current evidence and its limits.
from gatekeeper import moderate
res = moderate(
message="FREE NITRO CLICK HERE!!!",
rules={"no-spam": "no ads, links, self-promo", "be-kind": "no insults"},
)
# -> {'action': 'delete', 'rule': 'no-spam', 'confidence': 0.94}One Router.predict() answers five questions in a single readout:
| qid | type | what |
|---|---|---|
rule |
choice |
which rule violated? criteria = supplied rules + ok (dynamic K=3-12) |
harm |
score |
[safe, sus, harmful] |
hype |
score |
[dead, chill, hyped] |
jailbreak |
noul |
prompt-injection / ignore-instructions? |
escalate |
noul |
needs human? (used for gating) |
Gate: auto-delete if harm≥sus @ conf≥0.85, allow if ok @ conf≥0.85, else escalate to human/LLM.
The design being tested is an interface, not a new learning rule. A typed schema lets rule text and option count change per request without producing a new checkpoint. Whether that trade is worth its accuracy cost is an empirical question: on the template bootstrap in this repository, the regex baseline (0.403) beats zero-shot Laya (0.305), and neither result speaks to open chat. The 0.403 baseline is a template measurement; the 0.305 zero-shot row is marked stale in BENCHMARKS.md; a fine-tuned encoder baseline, adjudicated held-out rules, and out-of-sample thresholds are required before claiming superiority.
Jev is a hosted typed-decision API; the one-pass property comes from scoring fixed labels at one readout. It is not a fast-weight or test-time-weight-update model, and no source links it to those methods. Laya's cheap "learning" path fits a small readout over frozen features. Public speed/architecture shape is listed separately; our receipts are marked separately and missing receipts are not results. See reports/Jev System One research.md and the modernization agenda in section 8.
Flow: typed request, cache/fastpath, typed decision core, counted audit/stats, terminal action. See docs/assets/decision-trace.gif for the engine control flow.
Gate precedence is a fixed order of checks. A terminal outcome is final; margin abstention and quiet hours are post-checks that can only demote allow/delete.
Decision trace produced by scripts/make_readme_visuals.py from four deterministic synthetic-router calls through moderate(). The router scores fixed labels, so the figure shows engine control flow, not model quality or latency. The frame count, input hashes, and SHA-256 are recorded in docs/assets/decision-trace.json.
| approach | cost basis | latency basis |
|---|---|---|
| bouncer (self-hosted Laya) | local compute; no per-request API fee | ~33ms T4 vendor reference, not measured here |
| hosted typed judge (Jev-style) | metered API; include fallback and pre-screen calls in totals | vendor 70–500ms; independent CPU measurement 314/387ms p50/p95 |
| regex | no model call | no model call; measured 0.403 on the template set, blind to paraphrase |
| code | meaning | HTTP |
|---|---|---|
E_RULES_EMPTY/ID/TEXT/COUNT/RESERVED |
bad rule-set (see message) | 422 |
E_RULES_SEVERITY |
severity not low/high or on unknown rule | 422 |
E_CONFIG |
bad gate config (thresholds, timeouts, quiet_hours) | 422 / ValueError |
E_WEBHOOK |
event forward POST failed | exception |
E_SLACK |
malformed Slack event body | exception |
E_INTERNAL |
unexpected server failure (no detail leaked) | 500 |
E_MODEL |
inference failed twice → escalated | 200 + action=escalate |
| 429/413 | rate limited / body too long | as numbered |
Batch: POST /predict/batch takes ≤32 messages (413 beyond), each ≤8000 chars;
context lists cap at 20 items with 8000 chars each (422 beyond). Empty batches
are 422. POST bodies over 1 MB are 413 before they're parsed (T775). 429s carry
Retry-After: 60.
pip install -e .
python -c "
from gatekeeper import moderate, get_preset
print(moderate('FREE NITRO http://x.gg', get_preset('gaming')))
"
# bouncer check "you all suck" --preset gaming
# bouncer serve # API on :8000pip install -e ".[server,demo]"
bouncer check "you all suck" --preset gaming
bouncer check "you all suck" --preset gaming --allow-threshold 0.9 --delete-threshold 0.7
bouncer check --file batch.txt --preset gaming # batch: one message per line, JSONL out, worst action exits
bouncer serve # API on :8000
bouncer demo # Gradio UI
bouncer demo --share # public gradio link: rulebook + messages go public (you get a loud warn)
bouncer watch --preset gaming < chat.log # live tail, colored verdicts
bouncer review # queued flags/escalations
bouncer adjudicate ROW_ID reject # operator verdict; reject = strike amnesty
bouncer amnesty USER # clear a user's strikes after an appeal (--weight N subtracts N)
bouncer config validate # lint bouncer.toml + a gate JSON (E_ADAPTER/E_CONFIG)
bouncer completion bash # shell completion, generated from the parser
bouncer snapshot save snap.json # counters + strikes (T606)
bouncer snapshot load snap.json
bouncer export --out audit.csv # audit log -> CSV
bouncer export --queue --out appeals.csv # review queue -> appeal audit trail
bouncer models; bouncer presets # checkpoints, rule-packsSplit gates: --allow-threshold / --delete-threshold (and the same JSON keys
on POST /predict + /predict/batch) tune the two bars independently;
bare --threshold sets both. Higher allow = fewer auto-allows, more escalations.
Adapters and bouncer doctor read an optional bouncer.toml (stdlib
tomllib) from the working directory — override the path with
BOUNCER_CONFIG. Precedence is always env var > file > default: a
missing file is fine (defaults), a broken one fails closed with E_ADAPTER
naming the file. The full annotated example lives in
src/gatekeeper/adapters/README.md.
bouncer doctor diagnoses the environment without loading the model or the
network — one line per check, three sections, then a summary:
ok env python: 3.12.13 (requires >=3.10)
ok env bouncer: 0.5.0
info env TELEGRAM_TOKEN: telegram_bot: env unset (bouncer.toml may supply it)
warn dep laya: missing — System One router (predicts) unavailable
ok route model[zh]: multilingual
doctor: 30 checks, 4 warn, 0 fail
- env — interpreter floor, package version, config file (broken TOML =
E_ADAPTERnaming the file → hard fault), and everyrequire_env()an adapter wants, reported as presence only: values are never printed. - dep —
find_speclocates, never imports: every core dependency (numpy, laya, fastapi, uvicorn, pydantic, gradio, datasets, huggingface_hub). Missing pieces are warnings — the engine degrades to escalate, it doesn't die. - route — checkpoint per language from the pool (json/os only, T458) and
the
BOUNCER_DEVICEpolicy; the model stays asleep. - Exit
0with warnings (degraded is a documented mode),1only on hard faults: python below the floor, unreadable config.
Routers (one per checkpoint × device) are expensive to build, so bouncer keeps an LRU pool keyed by constructor kwargs:
BOUNCER_POOL_MAX(default2) — slots in the pool. Size it to every checkpoint your traffic actually reaches; fewer slots than hot checkpoints means an eviction storm where every request pays a full reload (eval/bench_pool.pydemonstrates both: 5.4× speedup with hits, ~1× thrashing without).BOUNCER_DEVICE(e.g.cuda,mps,cpu) — default device for pool builds.BOUNCER_MODEL_DIR(e.g./kaggle/working/bouncer-421m) — load a local fine-tuned checkpoint for every request: beats language routing, while an explicitmodel=pin still wins. This is how a Kaggle-trained model (P35) becomes the engine's default (T663); pool builds honor it too (T664).model=— pin a checkpoint per request:moderate(msg, rules, model="multilingual"),POST /predict {"model": "typed-decisions"},bouncer check --model english.None/autoroutes by language hint: non-latin scripts (ar/zh/ru/fa/ur/he) pinmultilingual, latin rides laya's own auto-routing.gatekeeper.release_memory()(T761) — the memory-pressure hook: drops every pooled router and returns the post-drop pool stats for your logs. Call it from your own pressure handling (K8s eviction callback, an RSS watcher, before a big spawn). The next request rebuilds on demand and pays COLD again — that cost is the documented trade, not a surprise.- Memory footprint (T769) ≈
max_n × model size: arithmetic, not a measured RSS — the checkpoint ships at ~1.8GB (421M params fp32, the Run-costs row in BENCHMARKS.md), soBOUNCER_POOL_MAX=2budgets ~3.6GB of resident weights plus unmeasured framework overhead. Every extra slot is another full model in RAM; the COLD half ofeval/bench_warm.pyre-pays that load afterrelease_memory(). - Pool size/hits/evictions appear in
GET /stats,GET /ready, andbouncer models.
A "preset" is just a named rule-pack (bouncer presets lists them with
language tags; bouncer pack init FILE --preset gaming writes one out to edit).
Anywhere bouncer takes rules, it also takes preset — never both:
bouncer check "msg" --preset study·POST /predict {"message": "...", "preset": "es"}GET /presets/{name}returns the pack for inspection.- Passing both exits 4 (CLI) /
422 E_PRESET(API) — packs are single-sourced, mixing silently merges nothing. BOUNCER_DEFAULT_PRESET=studyfills the gap server-side: requests with neitherrulesnorpresetuse it (bad value →E_PRESET).- Presets carry a language tag (
PRESET_LANG): choosinges/fr/aralso hints the language downstream (reason language, model routing).
lang= (API field, --lang CLI flag, per-line "lang" with watch --json-in;
adapters derive theirs from the message script since T857) hints both the
reason language and the model route; omitted (the default) it
infers from the message script (detect_script(): latin vs arabic at minimum).
--lang auto (check/watch, T893) says that same detection out loud: the hint
is filled per message from its script — arabic/cyrillic/cjk become
ar/ru/zh, latin stays unhinted (a script never claims a language).
Presets tagged es/fr/ar autofill the hint. Bad hints (not a short lowercase
slug) are rejected with 422 E_LANG.
Fixtures + wiring check: data/examples_i18n.jsonl and eval/eval_i18n.py.
Honest limit: base-model accuracy outside English is unmeasured — see
BENCHMARKS.md.
When the model misbehaves, the breaker stops wasting latency on it:
breaker_nconsecutive failures open the breaker;breaker_cool_scooldown then allows a half-open trial probe — one success closes it again.- Open-breaker requests short-circuit to
escalatewithcause: breaker-open(never silently allow). BOUNCER_BREAKER=offdisables it entirely; trip state shows inGET /stats,GET /ready, and the demo meters.timeout_s(API field, 0.5–60s;BOUNCER_TIMEOUTenv) bounds each model call — timeouts count toward the failure streak.
Nothing persists by default — bouncer is in-memory per process. Two opt-in files:
- Audit log (
BOUNCER_AUDIT, defaultbouncer-audit.jsonl): one JSON line per decision — timestamp, hashed message (never raw text), action, rule, confidence, latency, plus adjudication context: cause, preset, model, request id (server paths), and the bouncer version that wrote the row.bouncer export --out decisions.csv(also--format json,--since,--action,--limit) reads it back — the CSV carries the same columns.BOUNCER_AUDIT_FSYNC=Nbatches disk syncs for throughput: every line still flushes to the OS (process-crash safe), while only every Nth write pays the fsync syscall (power-loss safe for the last N lines, drained on exit). Unset or 0 keeps the legacy per-call open+close behavior. - Review queue (
BOUNCER_REVIEW, defaultreview-queue.jsonl): flag/escalate rows queued for a human;bouncer review --since/--rule/--action/--prunefilters it,--clear --yesempties it. The demo's flag button writes here too. - Snapshots:
bouncer snapshot save snap.jsonfreezes decision counters + per-user strikes;bouncer snapshot load snap.jsonrestores them (version-mismatch warns, never fails; corrupt files raiseE_SNAPSHOT). Programmatic equivalent:gatekeeper.stats.save()/load()writingBOUNCER_STATS(defaultbouncer-stats.json).
python data/synth_rules.py --n 12000 --out data/gatekeeper-12k.jsonl(needsOPENAI_BASE_URL+key, or--template-only)- Upload
notebooks/finetune_kaggle.pyto Kaggle, run - Pushes to
YOUR_HF/gatekeeper-laya-421m+ eval table in README
See data/README.md for dataset spec, notebooks/README.md for RLCD loop.
- Model-inclusive quality. The rule-accuracy row comes from 200 template rows with a base checkpoint; it is not an estimate of live-chat precision or recall.
- Calibration. Laya's published ECE is 0.466 before out-of-sample temperature fitting. This repository has no held-out calibration split, so its probabilities are not claimed to be calibrated.
- Hosted Jev accuracy or cost. No Jev API receipt is committed here. Vendor latency and savings figures are external claims, not measurements from this project.
- Multilingual quality. The i18n harness checks routing only, not translation quality or held-out accuracy in non-English traffic.
- A comparison against a fine-tuned encoder. The regex floor is the only baseline with a committed number; it is a floor, not evidence that typed readout wins.
uv run --extra dev pytest -q
python eval/gate.py --all --ci
python eval/bench_stub.py 200
python eval/bench_pool.py --json
python scripts/make_readme_visuals.pyThe gate runner skips a metric that is absent from a report; a skip is not a pass. Every report carries a bench, schema, and mode envelope so a stub number cannot be read as a real-model result.
- Rule-writing guide · Threshold tuning
- Architecture · API reference · Gate precedence
- Adapters · Benchmarks · Security · Threat model · Runbook
Template bootstrap (6 message shapes), 3 violation types in v1, English-first, ≤20 options per question, refit temperatures on your data. Full list: BENCHMARKS.md.
| split | acc(rule) | [email protected] | p50 |
|---|---|---|---|
| gatekeeper 200-row, CPU zero-shot (TEMPLATE/STALE) | 0.305 (approximately chance, pinned stale) | 0 gated (abstention) | 1004ms CPU / ~33ms T4 ref |
| gatekeeper-test fine-tuned | not measured | — | — |
These are template-bootstrap numbers from a 200-row CPU kernel, not live-chat results. The zero-shot row is marked STALE in BENCHMARKS.md because reproducing it needs a checkpoint and dataset that are not present in a weightless checkout. The fine-tuned row stays empty until a run produces a receipt; a target is not a measurement.
These are engine-only measurements on an Apple-silicon laptop using a stub router. No model weights were loaded, so none of these rows includes inference time. Method details and the no-invented-numbers rule are in BENCHMARKS.md. Model-inclusive latency is not claimed until a run produces a mode:"real" receipt.
| what | number | measured |
|---|---|---|
import gatekeeper (cold subprocess) |
p50 31.9ms / p95 45.5ms | 2026-10-22, T966 re-run (was 30.4ms at T762) |
bouncer --version cold start |
p50 57.4ms | 2026-10-18, T763 |
GET /stats, 8 threads × 100 req |
p50 8.2ms / p95 11.3ms, ~940 rps | 2026-10-18, T760 |
moderate() end-to-end, 5q vs 3q |
1.4ms / 1.3ms | 2026-10-18, T755 |
| batch sweep, per message | ~0.2ms | 2026-10-17, T753 |
| warm pool vs rebuild-every-time | 5.4× faster | T592 (bench_pool) |
Re-checked against eval/reports/ on 2026-10-22 (T1007): the import row
tracks T966's re-run (31.9ms — the only claim a refreshed bench moved);
the batch row matches the in-tree sweep (~0.2ms at chunk16); the pool
row keeps T592's 5.4× as its dated claim while the in-tree rerun under
lighter params (10 requests, 2 devices) shows 5.0× — same shape, not a
contradiction; stats-load.json is CI's 2-threads × 10-req scaled run,
not a re-measurement of T760's 8 × 100.
Regression-gated: import budget < 200ms (T764) and the per-bench latency
budgets run in CI on every push through eval/gate.py (T766).
