AI System DesignAI System Design FundamentalsModule 01 — Architecture fundamentals
Separating AI Predictions from Business Decisions and Deterministic Policy Enforcement
Question 19 of 47 · Updated
On this page
- 1. Five different responsibilities
- 2. The architecture: evidence, decision and effect
- 3. Define the predictive contract
- 4. Separate soft objectives from hard constraints
- 5. Worked decision scenario: allocating inventory
- 6. Deterministic policy evaluation and precedence
- 7. Keep decisions and enforcement separate
- 8. Human oversight: scope and authority, not ceremonial approval
- 9. Abstention, confidence and safe degradation
- 10. Practical implementation: transactional reservation
- 11. Version model, policy and business state independently
- 12. Auditability, explanations and recourse
- 13. Production failure handling and monitoring
- 14. A second scenario: an LLM-assisted internal document workflow
- 15. Test the full decision contract
- 16. Scalability and production trade-offs
- 17. Interview-ready answer
- References and research transparency
Treat a model prediction as evidence, never as authority. A model estimates what may happen or proposes what might be useful. A separately governed decision layer determines which actions are eligible, evaluates explicit business objectives and constraints, and decides whether to propose an action, abstain, seek review or deny it. An independently authorized execution service revalidates current permissions and authoritative state at the point of commitment and enforces transactional invariants. A high-confidence prediction cannot grant a permission, override a hard constraint or establish that an external action succeeded.
Original curriculum question: How do you separate probabilistic model predictions from deterministic business decisions and policy enforcement?
Module 01 — Architecture fundamentals | ASD-006. ASD-001 selected computational mechanisms; ASD-002 defined measurable requirements; ASD-003 sized workloads; ASD-004 established execution contracts; ASD-005 considered sourcing. This lesson establishes decision authority and enforcement boundaries across those architectures. The existing Machine Learning lessons on probability calibration and classification thresholds and the MLOps lesson on operationalizing calibration and threshold management are prerequisites. They cover fitting calibrators, threshold selection, drift and statistical release of predictive artifacts. We focus instead on the typed contract between an estimator, policy evaluation, authorization, review and a state-changing transaction. Existing ML rollout guardrails and LLM inference cost-remediation guardrails concern deployment or infrastructure control, not this reusable product decision architecture. The bank fraud and pricing case studies illustrate domain-specific applications; this lesson uses inventory reservation and read-only document workflows to generalize authority and commitment. Later ASD-018 addresses multi-system compensation, ASD-046 addresses cross-system approval queues, ASD-081 response contracts, ASD-090 policy exceptions, ASD-065 end-to-end testing and ASD-072 the wider evidence trail. These are follow-on topics, not repeated in full here.
All thresholds, costs, inventory counts, times, approval roles and scenarios below are fictional illustrations. They are not recommended universal operating settings, actual model calibration results, legal conclusions or production security guarantees.
1. Five different responsibilities#
A prediction is an uncertain statement about a target: for example, the probability that a location will experience a stockout in the next 24 hours if no additional inventory is transferred. A recommendation proposes an action, such as transferring eight units. A decision is a choice among permitted alternatives according to an approved objective. Authorization determines whether a principal has the right to request or execute a particular action on a resource. Execution attempts to change the authoritative system and produces a receipt or an explicit failure.
| Responsibility | Example | Owner |
|---|---|---|
| Prediction | Estimated stockout probability of 0.80 | Model/feature service |
| Recommendation | Propose eight units from an eligible source | Planner or optimization service |
| Decision | Allow proposal under approved risk, quantity and review rules | Versioned policy and accountable business owner |
| Authorization | Current operator can reserve this tenant's inventory | Identity and resource authority |
| Execution | Reserve eight available units exactly once for a logical intent | Transactional inventory service |
The model could be a deterministic function of its inputs and weights. That does not make its prediction certain. Conversely, deterministic business logic may rely on changing time, policy and authoritative state. Determinism here means the same complete validated facts, policy version and execution context give the same decision; it does not mean the world is static or that the rules are necessarily correct.
A model predicting an 80% probability of stockout cannot establish that eight units are available, that the user may reserve them, or that the reservation has been committed. Those facts belong to separate authorities. A model can be replaced independently only if its output semantics and evidence remain compatible with the decision contract.
2. The architecture: evidence, decision and effect#
The policy decision point (PDP) evaluates a request against trusted attributes and rules. The policy enforcement point (PEP) is the trusted component that actually prevents disallowed access or effects. A policy engine can emit an allow response, but it cannot protect a database if the model can bypass the PEP and write directly. Enforce least privilege at the resource and tool boundary as well as at orchestration.
Do not give the model unrestricted database write credentials or an API token able to perform arbitrary operations. Use narrow operations with validated parameters. An LLM's string "approved" is not an approval record. A classifier's high score is not a capability. An agent-generated tool call is a proposed action, not an authenticated instruction.
Decouple model serving from decision evaluation by a versioned interface rather than necessarily by a separate network service. A modular monolith can enforce the same boundaries with separate modules, credentials and transaction APIs. Microservices may provide stronger deployment and failure isolation but introduce network, consistency and operational costs. ASD-007 explores that topology choice.
3. Define the predictive contract#
A score without meaning is not a safe decision input. Specify:
| Field | Example and interpretation |
|---|---|
| Target definition | Stockout within 24 hours under the stated reference operating policy |
| Entity and scope | Canonical SKU, location, tenant, permitted task |
| Prediction time | Timestamp at which eligible features were observed |
| Estimate type | Probability, score, quantile, interval, or categorical suggestion |
| Calibration | Approved mapping/version and applicable population, if relevant |
| Model and feature versions | Compatible approved artifacts and schema |
| Validity | Expiry and conditions that invalidate the prediction |
| Evidence quality | Missing inputs, out-of-distribution indicator, provenance |
| Trace ID | Reference to governed evaluation and prediction metadata |
For a binary prediction, an estimate of 0.8 is a probability only if the output contract establishes the target and probability interpretation. A raw logit or ranking score may not be usable for expected-loss calculations. A well-calibrated classifier assigns probabilities that agree with observed event frequencies among comparable cases, within sampling uncertainty. It cannot guarantee the outcome of any particular case.
Distinguish aleatoric uncertainty (variability inherent in outcomes conditional on available information) from epistemic uncertainty (limited knowledge, model/data gaps). These terms describe sources of uncertainty, not necessarily two quantities that a particular model provides separately. Predictive intervals or ensemble disagreement can be useful with suitable validation; they are not universal proof of reliability. In language generation, token probabilities or a model's stated confidence do not establish claim correctness. Evidence applicability, source verification, structured validation and task-level evaluation are separate checks.
For the stockout case, a model trained under historical replenishment behavior may predict observed stockout under that policy, not stockout if no transfer occurs. If the decision changes the outcome, distinguish descriptive prediction from a counterfactual estimate. Do not assume a predictive probability identifies intervention effects. Estimate action-specific outcome distributions using a suitable causal or experimental design, or conservatively restrict the decision to supported interventions.
4. Separate soft objectives from hard constraints#
A useful formal representation is:
F(s, actor, policy) = set of actions that satisfy mandatory constraints
a* = argmin over a in F of E[Loss(a, Y) | admissible evidence]Here s is current authoritative business state. The feasible set includes only actions allowed by current permissions, mandatory business rules, resource constraints and any required review. The expected loss model is a decision aid, not a source of authority. If F is empty, or evidence is insufficient to compare the remaining actions, abstain or escalate; do not optimize over forbidden actions.
If actions themselves change the outcome Y, the loss calculation must use justified action-specific outcome estimates or a defensible model of action consequences. The simplified cost-sensitive classification formula assumes outcomes and costs appropriate to the reference decision. For a binary event with calibrated probability p, false-positive cost and false-negative cost , zero incremental cost for correct actions and no other constraints, compare (1-p)C_FP with pC_FN. A positive classification is lower-cost when p > C_FP/(C_FP+C_FN). Specify the equality tie rule. This formula is a prerequisite from the MLOps threshold lesson, not the principal policy mechanism.
Real decisions may include a no-action option, review, alternative actions, limits, capacity, and heterogeneous losses. A threshold determines eligibility for a particular action or review route; it does not itself implement that action. Adjust thresholds only through approved policy change, validate against representative evidence and separate model calibration from decision-rule changes.
Hard constraints must not appear merely as small negative terms in a utility function. A business invariant such as available inventory never becoming negative must hold regardless of model score, projected profit or review backlog. Likewise unauthorized data access cannot be made acceptable by a higher expected task-success score.
5. Worked decision scenario: allocating inventory#
Consider a fictional internal stock-transfer reservation. A model estimates risk of stockout at a destination if replenishment is not made, and a planner proposes reserving eight units from a source warehouse. The following simplified expected-loss calculation illustrates why recommendations and commitments are different.
Assume for the sake of the example that a stockout would cost $100 in lost contribution, an eight-unit transfer costs $15 and reduces the stockout probability from 0.8 to 0.2. The post-transfer probability is a separate hypothetical action-specific estimate, not derived automatically from the original classifier.
Expected loss without transfer = 0.80 × $100 = $80
Expected loss with transfer = $15 + 0.20 × $100 = $35
Illustrative expected improvement = $45The expected improvement is positive under these assumptions. But the proposal still must satisfy all controls:
| Condition | Authoritative fact or policy |
|---|---|
| Operator permission | Current inventory reservation grant for source tenant and resource |
| Source availability | 12 transferable units at version 5 |
| Quantity | Positive integer in approved unit of measure |
| Automatic quantity cap | At most 10 units under policy version 3 |
| Risk eligibility | Illustrative calibrated stockout risk at least 0.70 |
| Validity | Prediction/proposal not expired |
| Concurrency | Source stock version still matches at commitment |
| Idempotency | One committed reservation per scoped logical intent |
At the initial state, eight units may be reserved, leaving four. If another valid operation reserves six units before execution, the original proposal is stale and must not be committed against the older snapshot. If permission is revoked, deny even if the probability is 0.99. If the requested quantity is 11, route to authorized review, not an automatic transfer. If the remaining stock is four and the current proposal requests eight, no approval may override the physical availability invariant. A review may choose a smaller feasible quantity through a newly versioned proposal.
The model need not be retrained when the business cap changes from 10 to 5. A policy update changes the decision contract, and compatibility and outcome testing are required. A new model with a changed target, calibration or score direction cannot be swapped in just because its output is also a number between zero and one.
A reservation is not necessarily a completed shipment, purchase order or delivery. External actions would require their own authorized state transitions and receipt. Do not report the ultimate business outcome from the reservation alone.
6. Deterministic policy evaluation and precedence#
Model the decision policy as a pure function of explicit, normalized inputs where possible. Do not conceal network calls, random decisions or time-dependent state inside an apparently reproducible rule. Supply trusted facts, current time and policy version explicitly. The implementation can be application code, a decision table, a rules engine or a policy-as-code system such as Open Policy Agent. The selection is an engineering choice, not a requirement to deploy a specific product.
Define decision outputs precisely:
| Outcome | Meaning |
|---|---|
| DENY | The actor or action is prohibited; no effect |
| INVALID | Input or proposal violates the schema or typed contract |
| UNAVAILABLE | Required trusted evidence or policy is missing |
| STALE | Prediction, policy or authoritative state no longer matches |
| ABSTAIN | Available evidence is not adequate to recommend safely |
| REVIEW | A permitted proposal requires an accountable reviewer |
| ELIGIBLE | Proposal satisfies current precommit checks, not yet an effect |
| COMMITTED | Execution service recorded a successful effect and receipt |
| CONFLICT | The same logical intent key was reused for a different request |
Use precedence that preserves the trust boundary. Authenticate before retrieving protected facts; verify resource-level access before revealing decision details; reject invalid input; check the approved policy and evidence version; enforce non-negotiable feasibility; then determine whether an eligible option needs review. Do not leak private resource existence to an unauthorized caller. Some business systems return a deliberately indistinguishable denied/not-found response for protected objects.
A conservative default is deny for missing permission, abstain for unavailable predictive evidence, and hold or fail closed for missing mandatory policy or transaction preconditions. Choose and test an explicit fallback for each case. An "allow" output from a policy engine is always scoped to a principal, operation, object, constraints, version and validity. A cached allow decision cannot become a permanent universal authorization.
7. Keep decisions and enforcement separate#
A useful pattern is to evaluate an advisory decision on an authorized snapshot, then recheck its validity at the enforcement boundary. The interval between the two is a time-of-check/time-of-use (TOCTOU) risk.
In the actual architecture, the caller cannot assert trusted prediction or decision content merely by supplying a JSON object. Retrieve a server-held immutable proposal by ID or verify an appropriately signed, audience-bound representation issued by a trusted service. Check its canonical payload, issuer, purpose, tenant, entity, expiry and compatible artifact versions. Protect against replay with a stable logical intent and resource-state validation. Signature validity establishes provenance and integrity, not factual correctness or current authorization.
For a single database, one transaction can verify current policy and state, enforce conditional updates and record a receipt. For concurrent PostgreSQL operations, use appropriate row locks, constraints, conditional writes or serializable isolation with bounded retries; a read followed by an unguarded write is not sufficient. Ensure policy changes and grant revocations are coordinated with the chosen consistency boundary. If authority resides in a separate system, a local transaction does not make a remote permission check atomic with the effect. Define the revocation and consistency contract, short-lived scoped grants or resource-owned enforcement, and reconciliation appropriate to the risk.
Database constraints are defense in depth: quantities must be nonnegative, unique logical intents cannot produce duplicate committed receipts, and foreign keys or equivalent checks preserve references. An invariant spanning several rows may need a locked aggregate or serializable transaction rather than a row-local CHECK. Never rely solely on a UI warning or model prompt for a database invariant.
An external destination outside the database transaction requires separate handling: record durable intent, use destination-supported idempotency where available, reconcile ambiguous outcomes and compensate only when authorized and supported. An outbox records intended work, not proof that an external effect occurred. ASD-018 develops those cross-system semantics.
8. Human oversight: scope and authority, not ceremonial approval#
Human review is useful when the evidence is uncertain, the action is consequential, the policy requires approval, or an exception needs domain expertise. Design it as a real decision mechanism.
An approval record should bind the reviewer identity and current role, exact proposal payload or digest, affected resource, approved quantity or limits, policy version, relevant state version, issue time, expiry and reason. A reviewer may approve an eligible proposal within delegated authority, reject it, request additional evidence or propose a modification. A change in amount, target or underlying state can require a new approval.
Separate duties where required: a model cannot approve its own proposal; a requester should not necessarily approve their own exceptional operation. An LLM reviewing another LLM does not constitute accountable human approval. Provide meaningful evidence and uncertainty, sufficient time, clear options and an explicit way to reject or escalate. Avoid presenting a score in a way that pressures reviewers to rubber-stamp it.
Humans do not automatically have unlimited override authority. Distinguish reviewable defaults from hard invariants. An authorized supervisor may approve a quantity above a routine threshold if the policy provides for it, but cannot create nonexistent inventory or bypass a mandatory access restriction. Record the override type and rationale, and recheck at commitment. If approval is revoked or expired, hold the proposal.
Review capacity is an operating constraint. For illustration, 10,000 daily proposals with a 12% review rate generate 1,200 reviews/day. If 10 reviewers can each complete 100 valid reviews/day, aggregate capacity is 1,000/day, giving 200/day excess demand under constant conditions. Reducing reviews by silently authorizing more actions is not an acceptable remedy. Consider limiting admission, increasing review capacity, improving evidence and obtaining approved policy revision. Measure age and outcomes, not merely number of approvals.
9. Abstention, confidence and safe degradation#
A decision system needs a principled path for uncertain or missing evidence. Abstention means the system declines to recommend an action because the permitted evidence does not support it. It is distinct from denial, which means an action is not authorized. A valid refusal to access restricted data is not a model accuracy failure.
For an inventory forecast, a sensor outage, missing lead-time estimate or unsupported product class may invalidate a stockout prediction. A permitted fallback might use a reviewed deterministic reorder rule, or present the current verified inventory without recommending a reservation. A fallback may be usable only for an explicitly narrower task or quantity range.
For a document assistant, retrieving an authorized relevant passage does not guarantee that an LLM answer is supported. Validate claim-source applicability and output scope. If current policy evidence is missing, give an explicit unsupported/unknown state or authorized escalation. Do not allow the model to guess a binding policy decision. An authorization filter applied only after generation cannot undo disclosure to the model or an external service.
Distinguish coverage from conditional risk:
- Coverage is the fraction of eligible offered tasks for which the system emits an automated prediction/action under a defined contract.
- Conditional error is the fraction of automated outputs that fail the rubric.
- Whole-task outcome includes review, abstention, cancellation, delay and unresolved work.
For 1,000 offered tasks, if 800 receive automated outputs and 20 of those are wrong, coverage is 80% and conditional error 2.5%. The 200 abstained tasks need their own outcome accounting; it is incorrect to report 97.5% successful resolution over all tasks from these numbers alone. Calibration and selective prediction need representative evidence, including the cases that the current decision policy excludes. Do not treat model confidence or an arbitrary similarity threshold as proof of safe automation.
10. Practical implementation: transactional reservation#
The following standard-library example deliberately implements only a small internal reservation effect. A trusted upstream service supplies a typed proposal, the authenticated actor and trusted time. A production system must independently authenticate that proposal and bind it to the approved prediction/planner artifacts; this toy does not verify signatures, model provenance, role scope below tenant, input time types, or an actual model. The illustrative risk threshold is assumed to have been approved for this target. No purchase or external shipment is executed.
SQLite's BEGIN IMMEDIATE starts a write transaction before the permission, policy and inventory reads, so the code can enforce the illustrated local state transition with a guarded update and receipt in one database boundary. The example uses a single in-memory connection, no distributed transactions and no claim of a concurrent or crash-recovery benchmark.
PYTHONimport sqlite3 from dataclasses import dataclass, replace from math import isfinite @dataclass(frozen=True) class Proposal: tenant: str sku: str quantity: int risk: float expires: int stock_version: int policy_version: int def reserve(db, actor, key, p, now): # actor and now are supplied by trusted server context. db.execute('BEGIN IMMEDIATE') try: def complete(outcome): db.commit() return outcome allowed = db.execute('SELECT 1 FROM grants WHERE tenant=? AND actor=?', (p.tenant, actor)).fetchone() if not allowed: return complete('DENIED') if (type(p.quantity) is not int or p.quantity <= 0 or not isfinite(p.risk) or not 0 <= p.risk <= 1): return complete('INVALID') fingerprint = repr(p) old = db.execute('SELECT fingerprint FROM receipts WHERE tenant=? AND actor=? AND k=?', (p.tenant, actor, key)).fetchone() if old: return complete('COMMITTED' if old[0] == fingerprint else 'CONFLICT') policy = db.execute('SELECT version, max_qty, min_risk FROM policies WHERE tenant=?', (p.tenant,)).fetchone() stock = db.execute('SELECT available, version FROM stock WHERE tenant=? AND sku=?', (p.tenant, p.sku)).fetchone() if not policy or not stock: return complete('UNAVAILABLE') if now >= p.expires or policy[0] != p.policy_version or stock[1] != p.stock_version: return complete('STALE') if p.quantity > policy[1] or p.risk < policy[2]: return complete('REVIEW') if p.quantity > stock[0]: return complete('INSUFFICIENT') updated = db.execute('UPDATE stock SET available=available-?, version=version+1 ' 'WHERE tenant=? AND sku=? AND version=? AND available>=?', (p.quantity, p.tenant, p.sku, p.stock_version, p.quantity)) if updated.rowcount != 1: return complete('STALE') db.execute('INSERT INTO receipts VALUES (?,?,?,?)', (p.tenant, actor, key, fingerprint)) return complete('COMMITTED') except BaseException: db.rollback() raise def main(): db = sqlite3.connect(':memory:', isolation_level=None) db.executescript('''CREATE TABLE grants(tenant TEXT, actor TEXT, PRIMARY KEY(tenant,actor)); CREATE TABLE policies(tenant TEXT PRIMARY KEY, version INTEGER, max_qty INTEGER, min_risk REAL); CREATE TABLE stock(tenant TEXT, sku TEXT, available INTEGER CHECK(available>=0), version INTEGER, PRIMARY KEY(tenant,sku)); CREATE TABLE receipts(tenant TEXT, actor TEXT, k TEXT, fingerprint TEXT, PRIMARY KEY(tenant,actor,k)); INSERT INTO grants VALUES ('a','operator'); INSERT INTO policies VALUES ('a',3,10,.7); INSERT INTO stock VALUES ('a','widget',12,5);''') p = Proposal('a','widget',8,.8,100,5,3) assert reserve(db,'other','1',p,10) == 'DENIED' assert reserve(db,'operator','1',replace(p,tenant='b'),10) == 'DENIED' assert reserve(db,'operator','1',replace(p,risk=float('nan')),10) == 'INVALID' assert reserve(db,'operator','1',replace(p,quantity=-1),10) == 'INVALID' assert reserve(db,'operator','1',p,100) == 'STALE' assert reserve(db,'operator','1',replace(p,policy_version=2),10) == 'STALE' assert reserve(db,'operator','1',replace(p,risk=.69),10) == 'REVIEW' assert reserve(db,'operator','1',replace(p,quantity=11),10) == 'REVIEW' assert reserve(db,'operator','1',p,10) == 'COMMITTED' assert reserve(db,'operator','1',p,101) == 'COMMITTED' assert reserve(db,'operator','1',replace(p,quantity=7),10) == 'CONFLICT' assert reserve(db,'operator','2',p,10) == 'STALE' assert reserve(db,'operator','2',replace(p,stock_version=6),10) == 'INSUFFICIENT' assert db.execute('SELECT available,version FROM stock').fetchone() == (4,6) assert db.execute('SELECT count(*) FROM receipts').fetchone()[0] == 1 db.execute('DELETE FROM grants') assert reserve(db,'operator','1',p,10) == 'DENIED' db.close() print('16 checks passed') if __name__ == '__main__': main()
Observed local execution on Python 3.13.5:
16 checks passedThe checks cover denied actor, cross-tenant denial, nonfinite probability, negative quantity, expiry boundary, mismatched policy version, low-risk and over-cap review routes, initial commit, retry after expiry, conflicting key reuse, stale stock version, insufficient current stock, final inventory state, unique receipt and revocation before retry. Only the actual reservation decreases available stock. A repeated authorized request with the same committed fingerprint returns the existing outcome even if its original proposal has since expired; it does not execute again. Current access is checked before any receipt is returned. A changed request under a committed key is rejected. Noncommitted outcomes are not persisted in this toy, so a caller may re-evaluate the same key after a transient failure; a real idempotency contract should specify whether and which terminal failures reserve that key.
Several simplifications matter. repr(p) is not a production canonical cryptographic fingerprint. Use a stable, versioned serialization, validate the complete proposal and store its approved immutable identity. A real receipt should carry the resource, amount, authoritative post-state/version, transaction ID, policy and prediction references and a governed audit trail. The toy only records successful commits and not denied attempts, human decisions or reason details. It assumes valid server-controlled grants and policies; administrative changes require their own authorization and validation. The exception handler rolls back an incomplete transaction, but behavior under process death, multiple connections, lock contention and durable file recovery was not tested. A real inventory service would also model source/destination conservation, reservation lifecycle, release, delivery and reconciliation. Do not present this example as deployable security or fulfillment code.
With indexed primary keys, the example performs a fixed number of point lookups and updates per request, with database-dependent index complexity and lock costs. Model inference occurs before the transaction; do not hold a database lock during a slow model call or human review. The decisive architecture property is that current local authoritative constraints and receipt commitment are not delegated to prediction.
11. Version model, policy and business state independently#
A decision depends on several versions with different owners and change rhythms.
| Artifact | Why it matters |
|---|---|
| Model artifact and preprocessing | Determines estimation behavior |
| Calibration and target definition | Establishes meaning and approved probability scale |
| Planner or prompt/tool schema | Defines how proposals are constructed |
| Policy version | Defines allowed and reviewable action rules |
| Authorization revision or capability | Establishes current scoped authority |
| Authoritative state version | Prevents acting on a stale inventory or record snapshot |
| Evaluator and release record | Shows evidence supporting promotion |
Versioning alone does not prove compatibility. A manifest should specify permitted combinations, approval status and validity. For instance, a threshold of 0.70 for stockout within 24 hours cannot automatically be applied to a model estimating stockout within 7 days. A new feature schema or changed unit of measure can invalidate an otherwise valid proposal.
Separate historical reproducibility from live safety. To investigate a historical decision, replay the old policy on the same recorded facts and validated prediction if governance permits. To act now, evaluate current authority, policy and state. Do not replay an old allow response as a live action. A policy rollback must not restore revoked permission or undo a newer mandatory restriction. Review compatibility before reverting a model-calibrator bundle.
Policy changes deserve code review, domain-owner approval, boundary and regression tests, replay of representative historical proposals and controlled release. Show decision differences and affected cohorts. Shadow execution must not actually reserve stock or perform other side effects. Record a change manifest, then promote and monitor through an approved process. Emergency deny rules or containment can restrict scope faster, but their operational authority, expiry and audit should still be explicit.
The manifest governs which combinations may be evaluated. It does not confer resource authorization. Maintain independent resource enforcement even when a manifest is valid.
12. Auditability, explanations and recourse#
Audit the chain of evidence and authority, not merely the model response. Separate records for prediction, proposal, decision, review and execution can be linked by stable identifiers. Record enough to distinguish a permitted recommendation from an actual committed effect.
Example logical decision record (illustrative JSON, not a production schema):
JSON{ "decision_id": "d-123", "proposal_id": "p-456", "tenant": "example-tenant", "prediction_target": "stockout_24h_reference_policy", "model_version": "forecast-v7", "calibrator_version": "cal-v2", "policy_version": 3, "state_version": 5, "reason_codes": ["RISK_ELIGIBLE", "QUANTITY_WITHIN_CAP"], "decision": "ELIGIBLE", "execution_receipt_id": null }
A null receipt is intentional: this record proves neither execution nor completion. A subsequent execution record identifies the authorized commitment or actual failure. Log the trusted decision timestamp, provenance, actor and review authorization, policy effect, correlation ID and any relevant failure reason. Sensitive records need access controls, purpose limitation, retention and appropriate integrity protection. Append-only or tamper-evident logs can support investigation but should not be mistaken for universal immutability or proof that the recorded facts were correct. Use governed references and minimization instead of logging all raw features or prompts.
Explain the action with verifiable reasons. "The proposal exceeded the approved automatic quantity cap and requires review" is more faithful than a generated rationale that invents a justification. Model feature attribution can help explain an estimate, but it does not necessarily describe the policy decision or causal effect. The user should be able to distinguish model uncertainty, policy restriction and execution failure. Where consequential decisions affect people, provide appropriate notice, accessible review and recourse, and use qualified domain and legal governance. Do not infer sensitive attributes, use protected traits or proxies to allocate opportunities unfairly, or let a model score act as unreviewed authority in a high-impact workflow.
ASD-072 will develop a cross-service audit evidence architecture. Here the minimum requirement is traceability across the decision and effect boundary.
13. Production failure handling and monitoring#
Monitor each layer independently. A healthy inference endpoint is not proof of correct decisions, and a healthy policy endpoint is not proof of correctly committed effects.
| Failure | Correct response |
|---|---|
| Invalid score, missing features or incompatible target | Abstain or use an approved bounded fallback |
| Missing policy configuration | Fail closed for effects, alert owner |
| Changed state version | Reject stale intent; re-evaluate with authorized current data |
| Revoked access | Deny current operation and suppress protected result |
| Reviewer unavailable or approval expired | Hold, escalate or expire under defined policy |
| Duplicate delivery | Return scoped existing receipt or reject conflict; no duplicate effect |
| Database transaction fails | Do not claim commitment; retry only according to safe contract |
| External response lost after possible effect | Reconcile actual destination status before retry |
| Policy engine unavailable | Deny affected actions or apply only explicit approved safe policy |
| Suspicious model-generated tool instruction | Treat as untrusted proposal; reject unauthorized tool or parameters |
Track predictive quality (calibration, ranking, label maturity, shift) separately from decision metrics (action distribution, abstention, review rates, utility and cohort effects) and enforcement metrics (denials, invariant violations, stale proposals, idempotency conflicts, receipt reconciliation, actual committed outcomes). Use the appropriate denominators: prediction requests, proposals, reviewed cases, authorized intents, committed actions and matured outcomes are different populations.
A rising stale-proposal rate may indicate excessive queue time, too-short validity, frequent state changes or inefficient snapshot acquisition rather than model degradation. A higher authorization-denial rate may reflect a permission change or an attack attempt. A sudden action rate jump after a model release may reflect a changed probability scale or incompatible policy. Do not automatically adjust a threshold to recover an action rate before understanding the cause.
The policy itself can change the data distribution. If automatic replenishment prevents stockouts, the observed outcome among acted-on cases is not a label for the counterfactual no-replenishment target. Track action and outcome provenance and use defensible evaluation designs; do not retrain on intervention-altered labels as if the action had never happened.
14. A second scenario: an LLM-assisted internal document workflow#
Suppose an employee asks an assistant to summarize an internal policy and prepare a change proposal. The LLM can identify likely relevant sections, draft a summary and suggest structured edits. The authorized retrieval service owns document visibility. A separate policy resolver checks applicability and effective dates. A schema validator checks fields and constraints. A business owner may approve a concrete change. The document management service checks current write permission and document revision before applying an approved patch.
The user might supply text claiming to be an administrator, or a retrieved page might contain instructions to ignore review. Neither is trusted authority. The model is not allowed to choose a different tenant, grant itself credentials or send the draft to a new external destination. A valid structured patch is still untrusted until reviewed and authorized. If the underlying document has changed since review, require reconciliation or a new approval rather than overwriting the new revision.
This design differs from model-output guardrails. Guardrails can detect invalid content, unsupported claims or inappropriate actions, but a filter cannot replace object-level authorization, transactional version checks or approval authority. Put mandatory checks at the actual privileged boundary. Review the full data flow, including retrieval, cached context, external models, tool results and logs; post-generation redaction cannot undo data already sent outside its permitted boundary.
15. Test the full decision contract#
Develop a test matrix derived from ASD-002 requirements. Prediction validation checks the target, representativeness, uncertainty, calibration and performance. Policy tests verify deterministic behavior on fixed inputs. Enforcement tests assert that forbidden effects cannot occur through any exposed action path. Integration tests confirm that expected versions and state transitions are respected. Production evaluation observes downstream consequences.
| Test category | Example |
|---|---|
| Boundary | Exact threshold, quantity cap, zero quantity, expiry equality |
| Contract | NaN, malformed schema, wrong model target, incompatible policy |
| Authorization | Another tenant, wrong resource, revoked grant, stale capability |
| Invariant | Proposed quantity exceeds current stock regardless of confidence |
| Idempotency | Duplicate request, payload conflict, lost response, repeated worker |
| Concurrency | Competing reservations, simultaneous policy update, revoked permission |
| Review | Rejected, expired, modified or replayed approval |
| Recovery | Failed commit, partial external effect, retry and reconciliation |
| Evaluation | Policy replay, cohort metrics, delayed outcomes and selection effects |
| Adversarial | Untrusted model/tool output attempts to bypass action restrictions |
Where feasible, use property-based tests such as: for all valid initial inventory and all allowed request sequences, committed reservations do not make available stock negative. This property depends on the full persistence and concurrency model; a unit test of a pure decision function is not proof of the database property under concurrent access. Test actual deployment isolation, network paths, credential boundaries and fault recovery before relying on them.
Separate simulations, shadow decisions and real controlled exposure. A shadow run cannot demonstrate actual business intervention effectiveness by itself. Test rollback under compatible artifacts and current authority, and provide a kill switch that disables effects without necessarily disabling safe read-only features. A severe invariant breach requires containment and investigation, not a routine threshold-tuning exercise.
16. Scalability and production trade-offs#
A policy embedded in the application can avoid a network round trip and share the same transaction context. A central policy decision service can standardize rules and independently deploy changes, but introduces a dependency, caching and version consistency concerns. A policy-as-code engine can help governance with declarative rules and testability, but cannot enforce its decisions unless resource interfaces use them. Pick the simplest topology that satisfies the boundary.
Do not cache permission results without a defined invalidation and revocation contract. Predictive estimates may be cached within their approved validity and tenant scope, but the authoritative precommit check still needs current state. Cache versioned rule bundles, not indefinite grants. Where high transaction throughput is required, partition by the real invariant boundary (such as SKU and location) and keep transactions short. If one invariant spans several partitions, coordinate its ownership explicitly; a distributed design does not make a global constraint free.
A model call may be slow or expensive, while a policy decision can be inexpensive. This does not mean the full workflow is inexpensive: trusted state lookups, human review and transaction contention can dominate. Measure decision-to-commit delay, queue age and successful task cost alongside inference metrics. When asynchronous jobs resume, revalidate state and authority. Avoid copying a long-lived model-context snapshot into an approval queue and treating it as current indefinitely.
Trade-offs include strict freshness versus repeated proposal generation, centralized consistency versus service availability, independent review versus latency and labor, and finer policy granularity versus governance complexity. Hard constraints remain hard even when availability falls. If required current facts are unreachable, use an approved narrower alternative or decline the action rather than guess. Use deployment-time guardrails for release safety and execution-time controls for business safety; they answer different questions.
17. Interview-ready answer#
I would define the model's target, probability or proposal contract, version, uncertainty and validity. I would separate predictive evidence from a deterministic decision policy that combines current trusted business facts, eligible actions, thresholds, explicit constraints and review requirements. Model confidence would never grant permission or override a hard invariant.
I would separate the policy decision point from the enforcement point at the resource boundary. An approved proposal would be immutable and scoped to the principal, resource, policy and expiry. Before committing any state-changing action, the executor would recheck current authorization, policy compatibility and state; enforce invariants with appropriate transaction isolation, conditional writes and constraints; and record an idempotent receipt. For external effects I would reconcile outcomes rather than claim exactly-once delivery from a local transaction.
I would use explicit abstention, review, denial and failure states, govern model and policy changes separately, preserve a versioned evidence trail, and evaluate prediction quality, policy utility, review workload and actual committed outcomes separately. The core principle is that an AI system can recommend what to do, but only the authorized business system determines what may happen and confirms what did happen.
References and research transparency#
The authorized offline research exception was applied. References identify established primary research, official risk guidance and technical documentation. Current URL availability and contents and the current Supabase changelog were not live-verified. The three diagrams use standard triple-backtick Mermaid fences and received structural review; parser execution and frontend rendering were not tested. The SQLite example was actually run locally on Python 3.13.5 with all 16 assertions passing. It is an in-memory single-connection example, not a production authorization, distributed transaction, concurrency or crash-recovery test. No real prediction model was fitted and all economic, policy and workload values are hypothetical. Current legal requirements and real-world high-impact use require qualified assessment.
- Guo et al. — On Calibration of Modern Neural Networks
- scikit-learn — Tuning the decision threshold for class prediction
- NIST — AI Risk Management Framework 1.0
- NIST — Generative AI Profile
- NIST SP 800-207 — Zero Trust Architecture
- Open Policy Agent — Policy language
- PostgreSQL — Transaction isolation
- SQLite — Transaction documentation
- Amazon Builders' Library — Making retries safe with idempotent APIs
- OWASP — Top 10 for Large Language Model Applications
- Perdomo et al. — Performative Prediction
- Mitchell et al. — Model Cards for Model Reporting
References
- 1.Guo et al. — On Calibration of Modern Neural Networksproceedings.mlr.press
- 2.
- 3.
- 4.NIST — Generative AI Profiledoi.org
- 5.
- 6.Open Policy Agent — Policy languageopenpolicyagent.org
- 7.PostgreSQL — Transaction isolationpostgresql.org
- 8.SQLite — Transaction documentationsqlite.org
- 9.
- 10.OWASP — Top 10 for Large Language Model Applicationsgenai.owasp.org
- 11.Perdomo et al. — Performative Predictionproceedings.mlr.press
- 12.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython