37.1 Usage policy at the gateway
The agent now reaches users through the gateway, and its tool gates cannot prevent every harmful inference request. Something has to sit where every request passes and decide, for each one, whether the service will answer it. That something is a usage policy: a contract with your users that says what the service is for, what it refuses, and what happens on a violation. A policy layer gives operators a place to set model, tenant, token, and classifier restrictions, and gives users a consistent explanation when a request is blocked.
Concepts from other sections (7)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- Model card: the model’s interface documentation: details, intended and out-of-scope use, evaluation with uncertainty, limitations, and data. Read more: 35.1 Datasheet and model card
- Dot product: ; it measures how much two vectors point the same way, and it is zero exactly when they are perpendicular. Read more: Chapter 10: Calculus 3 in Mathematics
- logits: unnormalized log-scores that softmax turns into probabilities; here the table stores . Read more: 6.1 Byte bigram: counts, logits, safetensors v0
- stable softmax: softmax computed after subtracting the largest logit, so
expnever overflows. Read more: 25.6 Usage policy enforcement - Request id: a caller-chosen id that makes a signal idempotent; stored in run state rebuilt from history. Read more: 7.8 Signals, cancellation, and sagas in Systems Engineering
- Fail open: on an error in a control such as a router, let everything run; suited to review or analysis fan-out, where the worst case is a known cost rather than silent loss of coverage. Read more: 24.5 Routing implementations and selection
- first-match semantics: the first rule whose conditions all hold decides; later rules are not consulted. Read more: 25.6 Usage policy enforcement
Policy without enforcement is a wish, and enforcement without policy is arbitrary. In this section the usage policy states its rules in a machine-readable file; the gateway evaluates each request against it, with a measured classifier where exact checks are not enough; and the audit log records each decision so it can be reviewed and appealed. The policy describes permitted use. It does not claim that a classifier can determine intent or replace human review.
The section configures enforcement that is built in Usage policy enforcement in AI Engineering. Its classifier is the linear head fitted and exported in Fine-tuning heads and the linear-head export from AI Engineering, and its audit rules reuse the privacy detector categories of PII scrub with typed placeholders and audit spans. The solution is the policy document course/solutions/docs/USAGE_POLICY.md and the ordered rules course/solutions/entry/deploy/policy.v1.yaml, enforced by the evaluator in go/gateway/policy/policy.go (Check, Probabilities, Middleware), against the contracts policy.v1.schema.json and linear-head.schema.json. A shorter worked example of such a policy document sits next to this section as USAGE_POLICY.md.
Learning objectives
- Order policy rules so that exact metadata checks run before statistical ones, under first-match-wins semantics.
- Compute a linear head’s class probability from an embedding and apply a probability threshold.
- Explain why a classifier or embeddings failure must fail closed with 503.
- Design deny responses and audit events that are explainable and never hold prompt text.
- Write a policy document that owns its process: owner, revision, review cadence, appeal path, and limitations.
Policy as configuration
Section titled “Policy as configuration”The policy document is configuration, not a promise that a model is safe. Keep rules narrow, explain their scope, and review false positives and false negatives. Rules come in two kinds. Model and tenant restrictions are explicit checks on request metadata. Classifier rules use the engine’s embedding endpoint and a versioned linear head.
Classification is cheap when you reuse what you built. The linear head scores normalized embeddings using ; the softmax probability for class is . Its training labels, threshold, embedding model, and held-out metrics belong in the model card, because every classifier errs: publish the measured false-positive and false-negative rates on a labelled set, and choose the threshold on purpose. The Go gateway evaluates the exported head as a dot product, so Python is not in the request path. The symbols are:
| Symbol | Meaning |
|---|---|
normalized embedding returned by engine /v1/embeddings | |
| classifier weights, one row per class | |
| one bias per class | |
| class logits | |
| probability threshold that activates a classifier rule |
Working it by hand
Section titled “Working it by hand”Two requests show the two kinds of decision. Suppose a request has max_tokens = 2048, tenant free, and matches a rule capped at 1024 tokens. That rule denies before any classifier call. For a separate request, logits [0, 2] give unsafe probability ; with threshold 0.9, that classifier rule allows it. The red-team fixtures exercise both cases, including the embeddings service failing.
The artifact
Section titled “The artifact”USAGE_POLICY.md states scope, responsible owner, appeal path, review cadence, model and data limitations, and the actions users can expect. The ordered rules follow the schema and include model restrictions, a token cap, and the fitted classifier head at models/smol-135m/heads/usage.json. The document explains why each red-team fixture is denied without copying sensitive user content into audit logs.
Building the policy step by step
Section titled “Building the policy step by step”Try to predict each decision before reading it. Six principles drive the design.
Order rules from cheap and certain to expensive and statistical. A model restriction and a token cap are exact checks on request metadata; a classifier needs an embedding call and gives a probability. Putting the exact checks first means a request they deny never pays for, or depends on, the classifier, as in the first hand-worked case.
First match wins, so targeted denies come before anything broad. With ordered evaluation the meaning of a rule depends on its position; a broad allow above a targeted deny would silently disable the deny.
Threshold the probability, not the logit. The head’s threshold is a probability in ; a raw logit has no fixed scale. The evaluator normalizes the embedding, computes logits, applies a stable softmax, and compares the class probability with .
Fail closed. If the embedding service or the head is unavailable, the classifier rule cannot be evaluated, so the request is refused with 503 (a temporary error) rather than allowed: a timeout is not evidence that a prompt is safe.
A deny is explainable and private. Each deny returns 451 with a stable rule id and a user-safe reason; the audit event records identifiers (request, tenant, model, rule, outcome, time) and never the prompt, the completion, or the embedding.
The document owns the process. Rules change; the policy names an owner, a revision, a review cadence, an appeal path, and what the classifier cannot do (infer intent, replace human review).
The rules, annotated
Section titled “The rules, annotated”version: 1default_action: allow # the policy names what is denied; everything else passesrules: - id: restricted-model # exact metadata check: cheapest, first match: model: ["experimental-unsafe"] action: deny reason: "This model is not available through the public gateway" - id: free-token-cap # exact metadata check, before any classifier call match: tenant: ["free"] max_tokens: 1024 # matches when the request asks for MORE than 1024 action: deny reason: "Requested output limit exceeds the free tier" - id: unsafe-prompt # statistical check: last, and fails closed match: {} # every request that reached this rule classifier: head: "models/smol-135m/heads/usage.json" # versioned head, fitted in L6.5 class: "unsafe" threshold: 0.9 # a probability, not a logit action: deny reason: "The request was blocked by the usage policy"default_action: allow is a deliberate choice for a public inference gateway: the rules enumerate what is not permitted. The reasons are short and safe to show a user; they say which policy blocked the request without revealing classifier details. The full file is policy.v1.yaml. The local-services variant, policy.local.yaml, keeps the same rule ids and order but uses a head fitted on hash16 vectors, because no embedding model runs in PR CI.
The evaluator, annotated
Section titled “The evaluator, annotated”The YAML only means something through the code that enforces it. Here is the core of Check:
for _, rule := range p.Document.Rules { // in file order: first match wins if !matches(rule.Match, principal, req, maxTokens) { continue } if rule.Classifier != nil { head, ok := p.Heads[rule.Classifier.Head] if !ok || p.Embedder == nil { return Decision{}, ErrEmbeddingUnavailable // no head or embedder: an error, never an allow } emb, err := p.Embedder.Embed(ctx, head.EmbeddingModel, text) if err != nil { return Decision{}, ErrEmbeddingUnavailable // step 4: fail closed } probs, err := Probabilities(head, emb) // normalize, W e + b, stable softmax // ... error handling; resolve the class index (the rule's class, or the head's last class) threshold := head.Threshold if rule.Classifier.Threshold != nil { threshold = *rule.Classifier.Threshold // the rule may tighten or loosen the head's default } if probs[idx] < threshold { continue // below τ: this rule does not match } } decision := Decision{Allow: rule.Action == "allow", RuleID: rule.ID, Reason: rule.Reason} if !decision.Allow { p.audit(ctx, AuditEvent{RequestID: requestID, Tenant: principal.Tenant, Model: req.Model, RuleID: rule.ID, Reason: rule.Reason, Outcome: "deny", At: p.now()}) // no prompt field exists } return decision, nil}// ... no rule matched: default_action decidesMatching is a conjunction:
func matches(m Match, principal auth.Principal, req *route.InferenceRequest, maxTokens int) bool { if len(m.Model) > 0 && !contains(m.Model, req.Model) { return false } if len(m.Tenant) > 0 && !contains(m.Tenant, principal.Tenant) { return false } if m.MaxTokens != nil && maxTokens <= *m.MaxTokens { return false // within the cap: the cap rule does not match } return true // empty match {}: matches everything}Every condition present must hold, and an absent condition is no restriction, so match: {} matches every request. The hand-worked free-tier request with max_tokens = 2048 matches free-token-cap (tenant free, ) and is denied before the classifier is consulted.
The probability comes from the exported head:
// Probabilities applies the exported linear head to a normalized embedding.func Probabilities(h Head, embedding []float64) ([]float64, error) { // ... shape checks: len(embedding) == h.Dim, one W row and one bias per class norm := 0.0 for _, v := range embedding { norm = math.Hypot(norm, v) // overflow-safe Euclidean norm } // ... x = embedding / norm (left at zero for a zero vector) // ... logits[c] = h.B[c] + sum_j W[c][j] * x[j], tracking the maximum for i, z := range logits { logits[i] = math.Exp(z - max) // subtract the max: no overflow sum += logits[i] } for i := range logits { logits[i] /= sum } return logits, nil}The head was fitted on normalized embeddings, so the gateway normalizes again: a head applied to unnormalized vectors would see logits on a different scale. For logits [0, 2] the unsafe probability is , so unsafe-prompt does not match and the request falls through to default_action: allow.
Middleware turns decisions into HTTP. An error from Check writes 503 policy_unavailable and audits a classifier-unavailable deny; a deny writes 451 with rule_id: reason; an allow passes the request on. The middleware sits before routing in the handler chain, and its comment states the privacy rule as a design constraint: the prompt text is deliberately not part of AuditEvent; only non-content identifiers are kept. The full evaluator is policy.go.
The policy document, annotated
Section titled “The policy document, annotated”The reference USAGE_POLICY.md opens with ownership and process, not rules:
Owner: Gateway Safety Review (gateway maintainers and the privacy lead) · Revision:
usage-policy-2026-10-09.1· Review cadence: before each model or classifier change, and at least every 90 days · Appeal: users can request review through the support channel with the request ID; include no prompt text in the ticket unless the user chooses to provide it.
Then it scopes itself honestly: it “does not certify that a model is safe, infer a user’s intent, or replace human review.” Its sections cover four things. Decision order lists each rule in order with what it does, the fail-closed rule for classifier errors, and the change rule: a change to rule order, model, head, or threshold requires a revision bump and a red-team review. User outcome and review says the response carries the rule id, a reason, and a request id; appeals are reviewed against the policy revision and rule id without copying prompt content into logs or tickets; emergency changes need a named approver and a follow-up within one business day. Privacy-safe audit fields are request id, policy revision, rule id, decision, timestamp, model id, and classifier version; never prompt text, completions, credentials, or raw embeddings; decision metadata is kept 30 days, and de-identified aggregate counts up to 13 months to detect drift. Limitations and monitoring says the threshold trades false positives for false negatives and is not a measure of certainty or intent; deny rates are monitored by rule and model; and the classifier rule is suspended if its dependency or calibration is unhealthy.
Why this design
Section titled “Why this design”Ordered first-match beats a scoring system. A weighted score across rules is harder to explain to a user and to audit; first-match gives every decision exactly one rule id, which is what the response, the audit, and the appeal all refer to.
Fail closed beats fail open. Failing open would make the classifier rule disappear whenever the embedding service is slow, which is precisely when an attacker would want it gone. The cost is availability: a 503 during an embedding outage. The document makes that tradeoff explicit and gives operators a way to suspend the rule deliberately.
A linear head in Go beats a Python classifier in the path. The head is a small matrix exported to JSON; evaluating it in the gateway adds microseconds and no new service. A full classifier would be more accurate but adds latency, a dependency, and another failure mode on every request.
The design accepts tradeoffs. A linear head on embeddings will misclassify some prompts in both directions; the policy says so, keeps the threshold reviewable, and provides an appeal path rather than claiming accuracy it does not have.
What can go wrong
Section titled “What can go wrong”A correct solution handles four cases:
| Case | Why it exists | Expected result |
|---|---|---|
| schema and rule order | Rejects ambiguous or misspelled rules | First matching deny wins |
| red-team prompts denied | Checks configured refusals at the policy boundary | Every blocked fixture returns 451 with its rule id |
| no PII in audit examples | Avoids retaining prompt PII in logs | Rule id and request id only; redact detector matches |
| classifier dependency down | A timeout is not evidence of safety | 503, and a classifier-unavailable audit event |
Four pitfalls map onto those cases. Putting a broad allow rule before a targeted deny silently disables the deny; in the reference, targeted denies come first, there is no broad allow rule, and default_action: allow applies only when nothing matched. Logging the prompt in a deny event turns the audit log into a store of user data; AuditEvent has no prompt field, and only identifiers are recorded. Applying the threshold to a raw logit gives the threshold a different meaning for every head; Probabilities applies the softmax and the rule compares probs[idx] with .
Warning: Treating an embeddings timeout as safe lets anyone bypass the classifier by making its dependency slow.
CheckreturnsErrEmbeddingUnavailableandMiddlewareanswers 503.
Where this leads
Section titled “Where this leads”Looking back, this policy configures the enforcement in Usage policy enforcement; the exported head it names is fitted and represented as described in Fine-tuning heads and the linear-head export; and its safe audit examples reuse the detector categories of PII scrub with typed placeholders and audit spans. Looking forward, the agent’s end-to-end run, built across Agent SDK, exercises the configured policy matrix, the red-team fixture set, the audit log, and gateway behavior; and Answering the security questionnaire in Field Engineering uses this policy in a customer security review.
Production policy systems add policy version rollout, appeals, jurisdiction-specific rules, monitoring for drift, and human review for high-impact decisions. Keep each addition traceable to an owner and an observed failure mode.
Further reading
Section titled “Further reading”- NIST, AI Risk Management Framework 1.0, especially the Govern and Measure functions.
- OWASP, Top 10 for LLM Applications.
- Inan et al., Llama Guard.
Key terms
Section titled “Key terms”- Usage policy: a contract with users stating what the service is for, what it refuses, and what happens on a violation.
- First match wins: ordered evaluation in which the first rule whose conditions all hold decides the request.
- Linear head: a weight matrix and bias vector that map a normalized embedding to class logits, .
- Threshold: the class probability at or above which a classifier rule matches.
- Fail closed: refusing a request (503) when a check cannot be evaluated, rather than allowing it.
- Audit event: a record of a decision holding identifiers only, never prompt text, completions, or embeddings.
Summary
Section titled “Summary”- Policy rules are ordered and the first matching rule wins, so exact metadata checks come before the classifier.
- Model and tenant restrictions are explicit; classifier rules use the engine embedding endpoint and a versioned linear head evaluated in Go.
- A classifier or embeddings failure fails closed with 503.
- Every deny has a stable rule id, a useful reason, and a privacy-safe audit record.
- The policy describes permitted use; it does not claim the classifier can determine intent or replace human review.
Review questions
Section titled “Review questions”-
Why are
restricted-modelandfree-token-capplaced beforeunsafe-prompt?Answer
They are exact, cheap checks on request metadata. Placed first, a request they deny never triggers an embedding call, so it is decided quickly, does not depend on the embedding service being up, and gets the more specific rule id and reason. With first-match semantics, order also decides which rule is reported, and the most specific explanation should win.
-
What happens when the embeddings endpoint times out, and why is that the right behaviour?
Answer
CheckreturnsErrEmbeddingUnavailable, andMiddlewarewrites a 503policy_unavailableand audits aclassifier-unavailabledeny. The request is not allowed: without the embedding the classifier rule cannot be evaluated, and treating “could not check” as “safe” would let anyone bypass the rule by making the dependency slow. -
Logits
[0, 2]and threshold 0.9: is the request denied? What would change if the threshold were applied to the raw logit?Answer
The unsafe probability is , so the classifier rule does not match and the request is allowed by the default. Comparing the raw logit 2 with 0.9 would deny it, and in general a logit has no fixed scale, so the threshold would mean something different for every head. The threshold is defined on the probability, which is what the head’s held-out metrics describe.
-
Why does the audit event contain the request id but not the prompt?
Answer
The request id lets a reviewer connect an appeal, a response, and the decision without the audit log becoming a store of user prompts, which can contain personal data (see Privacy and PII policy). The policy revision and rule id say why the request was denied; the prompt itself is only seen in an appeal if the user chooses to provide it.
-
Why does a change of threshold require a policy revision bump and a red-team review?
Answer
The threshold decides which prompts are blocked, so changing it changes the policy as much as adding a rule. The revision is recorded in every audit event, so a bump lets reviewers tell which policy made a past decision; the red-team review checks that every fixture that should be denied still is.