AI System DesignAI System Design FundamentalsModule 01 — Architecture fundamentals
Turning Business Requirements into Measurable AI Objectives and Release Criteria
Question 15 of 47 · Updated
On this page
- 1. Begin with a business problem, not a model metric
- 2. Stakeholders, scope and authority
- 3. Build the requirements hierarchy
- 4. Functional versus non-functional requirements
- 5. Distinguish business KPIs, system objectives and model metrics
- 6. Define the measurement contract
- 7. Select model metrics that support the actual task
- 8. Understand SLIs, SLOs and SLAs
- 9. Error budgets as a release constraint
- 10. Define acceptance thresholds before evaluation
- 11. Build representative evaluation datasets
- 12. Statistical confidence: why the sample size matters
- 13. Worked scenario: support assistant acceptance record
- 14. Practical implementation: evaluate an acceptance decision
- 15. Requirement traceability from need to test and monitor
- 16. Safety guardrails and non-negotiable constraints
- 17. Production release lifecycle
- 18. Second worked scenario: inventory forecasting and replenishment
- 19. Common failure modes and corrective design
- 20. A reusable requirement specification
- 21. Interview-ready summary
- References and research transparency
Translate the business goal into an observable user or operational outcome, derive the required system behavior and constraints, define precise measurement contracts, then agree on the evidence and decision rules that will determine whether the system may launch or continue operating. A good AI requirement is not "use a high-accuracy model." It connects an intended benefit to an accountable workflow, an eligible population, measurable outcomes, acceptable failure modes, test datasets, safety boundaries, ownership and production acceptance criteria.
Original curriculum question: How do you translate business requirements into measurable AI system objectives and acceptance criteria?
Module 01 — Architecture fundamentals | ASD-002. ASD-001 compared architecture choices under agreed constraints. This lesson establishes where those constraints come from and how to turn them into testable requirements and release decisions. The existing Machine Learning articles on framing prediction problems, target definition and model-quality SLOs, as well as the AI Agents lesson on error budgets, are supporting prerequisites. We do not repeat their specialized treatment of conditional recall, delayed-label burn-rate alerting or agent orchestration. The distinctive objective here is a traceable product-wide agreement from stakeholder need through acceptance evidence, operational obligations and accountable launch decisions. ASD-003 develops capacity and resource sizing; ASD-065 and the production assurance module develop testing architecture in greater detail.
All stakeholder names, performance results, thresholds, volumes and financial values in the worked scenarios are fictional educational assumptions, not measured production outcomes, universal industry standards or legal requirements.
1. Begin with a business problem, not a model metric#
Suppose a retailer says, "We want an AI assistant that reduces the time needed to answer order and return questions."
That statement identifies a desired direction but leaves important details unresolved. Is the goal less staff time, faster customer resolution, fewer repeat contacts, a higher share of self-service answers, better customer experience, or some combination? Does a fast but incorrect answer count as success? Can the assistant change an order or only explain its status? What happens when the return policy is ambiguous?
A model accuracy target alone cannot answer these questions. Instead, establish the full chain:
- Business outcome: what improvement is meaningful to the organization and users?
- User task: what must the person be able to accomplish?
- System behavior: what should the product do, and what must it never do?
- Measurement: how can success and failure be observed consistently?
- Acceptance: what evidence, threshold and review are required for a release?
- Operational commitment: how will quality be measured and maintained after launch?
The system may meet its engineering metrics and still fail the business goal. A low-latency assistant that sends customers to the wrong department increases work rather than reducing it. A classifier that detects a problem with high recall may have no useful intervention attached to it. An apparent improvement in average handling time may result from difficult cases being transferred to a queue that is excluded from reporting.
A requirement must therefore describe both the desired outcome and the decision or action that connects the AI component to that outcome.
2. Stakeholders, scope and authority#
Interview stakeholders who experience the system's behavior or own its consequences. Their requirements often conflict legitimately, so capture the conflict instead of letting the model team implicitly decide.
| Stakeholder | Example concern | Required contribution |
|---|---|---|
| Product owner | Faster, useful customer resolution | Primary outcome and target population |
| Customers and support staff | Correct answers, accessibility, smooth handoffs | Real tasks, failure cases and qualitative evidence |
| Domain or policy owner | Current applicable return rules | Authoritative facts, permitted actions, exceptions |
| Security and privacy owners | No unauthorized order disclosure | Non-negotiable access and data-use controls |
| ML and evaluation team | Representative evidence, honest uncertainty | Labels, rubrics, statistical evaluation design |
| Software and SRE teams | Availability, deadlines, recoverability | Service measurement and operational feasibility |
| Finance and operations | Sustainable cost and staffing | Accounting boundary, baseline and approved budget |
| Release owner | Accountable deployment decision | Sign-off process, stop rules and escalation |
Define what is in scope and out of scope. In the initial support example, the assistant answers read-only questions about current orders and applicable return policy, and offers a staffed escalation path. It does not issue refunds, alter shipping addresses or initiate financial transactions. A later request to execute refunds is a scope change requiring separate authority, requirements and release evidence, not merely a prompt enhancement.
Document assumptions and unresolved requirements. A target without an accountable owner is a proposal, not a commitment. A vague request for perfect factual accuracy may need to be decomposed into precise invariants, representative evaluation thresholds and safe behavior when facts cannot be established. Never negotiate away authorization or mandatory safety merely to reach a product KPI.
3. Build the requirements hierarchy#
Each level answers a different question. The business objective describes value; functional requirements describe required behavior; non-functional requirements describe characteristics of that behavior; metrics are measurement instruments; acceptance criteria specify how evidence is judged.
A complete hierarchy also includes constraints from law, contracts, user permissions, organization policy and physical limitations. Those constraints should be evaluated by the relevant qualified owners. Some apply to every request regardless of the aggregate performance target.
Use stable identifiers and requirement versions. Requirements may evolve, but evaluation should never silently switch definitions midway through an experiment or use a looser denominator just because a candidate fails.
4. Functional versus non-functional requirements#
Functional requirements specify observable actions or responses. A useful template is: given a defined actor, input and precondition, the system shall produce a defined outcome or explicitly permitted alternative.
For the read-only support assistant:
| ID | Functional requirement | Example acceptance evidence |
|---|---|---|
| FR-01 | Retrieve order facts only for an authenticated principal with current access | Ownership and permission fixtures, including denied cases |
| FR-02 | Answer applicable policy questions using approved, current sources | Human-reviewed task set and source applicability checks |
| FR-03 | When evidence is missing or conflicting, abstain or hand off according to policy | Missing-source and contradiction fixtures |
| FR-04 | Preserve context in an authorized escalation without claiming an action succeeded | Integration test against support queue and acknowledgement contract |
| FR-05 | Perform no order-changing or refund transaction in read-only mode | Capability inspection, denied tool calls and integration tests |
Non-functional requirements describe how well the system delivers the behavior and the constraints under which it operates:
| ID | Non-functional requirement | Illustrative target |
|---|---|---|
| NFR-01 | Useful answer quality | Conservative lower bound of 95% on a defined representative audit |
| NFR-02 | Timely completion | At least 99% of eligible offered tasks receive the required valid response within 3 seconds |
| NFR-03 | Availability | At least 99.9% of eligible logical requests receive a technically usable response over a rolling 30 days |
| NFR-04 | Cost | Total attributable cost at most $0.10 per successfully resolved task over the agreed reporting window |
| NFR-05 | Data protection | Mandatory isolation and authorized source access controls pass independent verification |
| NFR-06 | Operability | Named owners, version lineage, safe fallback, incident procedures and tested rollback |
These values are illustrative and do not prescribe a production target. The same 3-second deadline may be inappropriate for a long asynchronous document task. A 95% aggregate quality goal cannot justify incorrect answers on a mandatory safety case. A compliant system may still incur incidents; test evidence is not proof of universal security.
Some requirements span both categories: an authorization denial is functional behavior and a safety invariant. What matters is precise evidence and ownership, not perfect categorization.
Write requirements at the user-visible boundary before allocating budgets to components. A model call within 500 ms does not imply an application response within 500 ms. Component budgets and resource choices belong to downstream architecture and capacity planning.
5. Distinguish business KPIs, system objectives and model metrics#
A key performance indicator (KPI) is a chosen measure of progress toward an important business or user outcome. An AI metric measures a particular model or workflow property. A service-level indicator measures defined service behavior. These categories can overlap in implementation, but they serve different decisions.
| Measurement | Example | Decision supported |
|---|---|---|
| Business KPI | Repeat-contact rate within 7 days | Is customer resolution improving? |
| User outcome | Correctly resolved eligible task within agreed time | Is the entire workflow useful? |
| Model metric | Intent classification recall by class | Does the model support the workflow? |
| Grounding metric | Applicable-source-supported answers / audited answers | Are answer claims supported? |
| Operational SLI | Valid responses within deadline / eligible requests | Is the service meeting its responsiveness objective? |
| Safety invariant | No unauthorized order access | Is a mandatory boundary being respected? |
| Cost metric | Attributable total cost / successfully resolved tasks | Is the service economically sustainable? |
A metric is not automatically a useful KPI because it is easy to collect. Tokens generated, agent tool calls, inference throughput, retrieval similarity and click counts are usually diagnostic signals rather than direct evidence of a fulfilled task.
For a hypothetical baseline of 8 minutes per eligible support task, a stakeholder might aim for a 20% reduction in mean handling time, implying 6.4 minutes. Define whether this means active staff time, elapsed customer time or total end-to-end labor, including transfers and reopened tickets. An observed decrease from 8 to 6.4 minutes is a 1.6-minute absolute improvement and a 20% relative improvement, not a reduction of 20 percentage points.
Require a non-harm condition for customer outcomes and verify that the apparent benefit is not created by excluding unresolved work. For an illustrative 10,000 eligible cases per month, a true mean reduction of 1.6 staff minutes across all cases would represent about 16,000 minutes, or 266.7 staff hours. That is a workload estimate, not necessarily realized payroll savings; staffing constraints, review effort, adoption and the distribution of case difficulty matter.
6. Define the measurement contract#
A metric name such as answer accuracy is insufficient. Specify what is measured, how it is counted, when it is final and how unknown outcomes are handled. A versioned measurement contract should be machine-readable where practical and intelligible to stakeholders.
Example contract for task resolution quality:
| Field | Example definition |
|---|---|
| Metric ID | Q-01, resolution_quality_v1 |
| Population | All eligible offered read-only order and return tasks, under a fixed product scope |
| Observation unit | One logical task ID, regardless of internal retries |
| Good outcome | Independently judged correct, complete and authorized resolution, including only handoffs defined as successful by the task rubric |
| Denominator | Representative audited mature tasks sampled from the eligible population |
| Bad outcome | Incorrect, incomplete, unsupported, unsafe or unresolved according to rubric |
| Unknown | Pending adjudication or missing evidence; reported separately and not counted as correct |
| Time boundary | Task acceptance timestamp; outcome assessed within defined horizon |
| Slices | Task type, language, difficulty, source availability, product/channel |
| Provenance | Request ID, artifact version, source/policy version, rubric and reviewer version |
| Owner | Product and independent evaluation leads |
| Decision rule | Prespecified quality bound, sample sufficiency and mandatory guardrails |
An audit based on a representative random sample estimates the relevant offered-task population; a sample of only completed and answered requests does not. If escalations are excluded from automated-answer quality, publish that conditional metric alongside coverage and whole-task resolution. If the audit is stratified disproportionately, apply appropriate weights or report stratum-specific estimates rather than treating all sampled rows as a simple random sample.
Missing outcomes require particular care. Report offered tasks, audited tasks, mature outcomes, unresolved cases and excluded cases. Define cancellation before launch: a user-initiated cancellation may be legitimately excluded from a specified service SLI under an agreed policy, but timeouts or system failures should not be reclassified as user cancellations to improve the number.
For online serving, count logical request IDs once rather than each attempt. For a user task spanning multiple requests, preserve a separate task ID. A request-level SLO and a task-level business KPI do not necessarily have the same denominator.
7. Select model metrics that support the actual task#
There is no universal AI quality metric. Select metrics based on task type and error consequences.
| Task | Candidate technical metrics | Important caveat |
|---|---|---|
| Binary classification | Precision, recall, PR-AUC, calibration | Class imbalance and action policy affect meaning |
| Regression | MAE, RMSE, prediction interval coverage | Average error may hide expensive tail errors |
| Forecasting | Horizon-specific error, weighted absolute error, bias | Demand may be censored by stockouts |
| Retrieval and ranking | Recall@K, MRR, NDCG | Incomplete judgments and eligibility matter |
| Generative answers | Factual correctness, groundedness, completeness, useful abstention | Fluent text and valid schema do not prove correctness |
| Document extraction | Field accuracy, critical-field exact match, structural validity | Overall token accuracy may hide wrong totals |
| Integrated workflow | End-to-end completion, correctness, safety and deadline attainment | Component success is not equivalent to task success |
In the support example, an intent classifier with 98% accuracy may still route nearly all rare urgent cases incorrectly. Inspect class-specific recall, confusion patterns and severity. If there is a confidence-based escalation mechanism, compare calibration and the cost of review, and report the fraction of requests the system can handle without escalation. Avoid treating an arbitrary confidence score as a calibrated probability.
For a generated policy answer, define a rubric with separate dimensions: applicable policy, factual correctness, completeness for the requested task, grounded support, authorized information access, and appropriate fallback. A judge should distinguish an unsupported claim from an omission and from a justified refusal. A single average rating can hide a mandatory violation.
For a hybrid system, use component metrics to locate defects and task-level metrics to decide usefulness. An accurate retrieved passage can still be used incorrectly by the generator. A correct answer can still be delivered too late. A successful tool call can still be unauthorized. This is why requirements must extend beyond model evaluation.
8. Understand SLIs, SLOs and SLAs#
These terms represent different levels of commitment:
- A service-level indicator (SLI) is an observed, precisely defined measurement of service quality.
- A service-level objective (SLO) is a target for an SLI over a stated population and time window.
- A service-level agreement (SLA) is an agreement with a customer or other party that can define obligations, exclusions, remedies or consequences. Not every internal SLO is an SLA.
For an internal objective of 99% of eligible requests completing with a valid response within 3 seconds, the SLI is the fraction of eligible logical requests meeting that deadline and result contract. An HTTP success code with unusable output is not necessarily a good event. Define whether technical error responses, approved abstentions or handoffs meet each particular SLI. Report task correctness separately if an operational indicator does not include semantic correctness.
Measure at the service boundary that reflects user experience. If a request traverses multiple tools and models, internal timers may diagnose latency but cannot substitute for end-to-end elapsed time. A product may also track first-response or first-token latency; those do not imply final useful completion.
A 99.9% availability SLO should name the reporting window, eligible request population and acceptable technical response. If the service uses a time-based uptime objective instead of event-based availability, its error budget has units of time, not request failures. Do not combine these without a documented conversion and appropriate assumptions.
For formal contractual commitments, use the approved agreement and qualified review rather than assuming the internal SLO is legally binding. A model-quality SLO can have a different maturity horizon from latency; the dedicated Machine Learning SLO lesson covers that case in depth.
9. Error budgets as a release constraint#
An event-count error budget is the allowance for failures of an explicitly defined binary good-event SLO. If the target is s and the final eligible event count is N:
allowed bad-event fraction = 1 - s
allowed bad events = (1 - s) * N
observed bad-event ratio = B / N
burn rate = (B / N) / (1 - s)Here B is the number of observed bad events. The rate is undefined if no eligible events occurred; do not label an empty window perfectly healthy. If the resulting allowance is fractional, only the integer number of actual bad events that fits within that allowance is permissible. Use a consistent final-window count; forecasts in an open window are provisional.
For the fictional 99.9% technically usable-response SLO, assume 100,000 eligible logical requests in a completed window. The allowance is 100 bad events. If 35 bad events occurred, 65 remain relative to that fixed denominator, and the observed burn rate is 0.35 times the allowed failure rate. A separate 10,000-event observation window with 40 bad events has a 0.4% error ratio, four times the 0.1% allowance. Those windows may overlap; do not add their budgets as if independent.
The release policy must state what happens when reliability deteriorates. An exhausted budget may pause risk-increasing changes under an agreed policy; an independently verified severe privacy incident may require immediate containment even when ordinary budgets are healthy. Error budget is not permission to perform unauthorized or harmful actions.
Do not apply the simple count-budget equation to arbitrary continuous metrics such as RMSE, aggregate satisfaction scores or AUC. An explicit good/bad event definition or a separate appropriate objective is required. Model-quality SLOs with delayed or selective labels and detailed burn-rate alerts are covered in the specialist curricula. Here the architectural concern is mapping each budget to the right requirement, decision owner and release policy without letting an unrelated healthy metric conceal a failure.
10. Define acceptance thresholds before evaluation#
Acceptance criteria are explicit conditions for a defined candidate to be considered ready for a particular stage. The criterion must include metric version, threshold, population, window, required evidence and owner. Separate offline readiness, pilot expansion, general availability and ongoing operation.
Examples:
| Gate | Threshold or condition | Evidence |
|---|---|---|
| G-01 Scope | All read-only task behaviors and forbidden action tests pass | Functional integration suite |
| G-02 Quality | One-sided 95% Wilson lower bound at least 0.95 on an eligible fixed audit of at least 1,000 independent tasks | Frozen holdout and adjudicated outcomes |
| G-03 Timeliness | At least 99% of at least 1,000 offered test tasks meet valid-response deadline | Representative load and fault scenarios |
| G-04 Severe incidents | No observed critical violations in required suites and approved control assessment | Independent adversarial and authorization tests |
| G-05 Cost | Attributable cost per successful task meets budget with representative workload evidence | Cost report, including reviews and retries |
| G-06 Operations | Alerts, ownership, fallback, recovery and rollback verified | Operational readiness review |
| G-07 Product benefit | Prespecified controlled pilot supports meaningful improvement without unacceptable harm | Experiment analysis and stakeholder review |
These example gates are conjunctive: all mandatory conditions for a stage must pass. A high mean quality score cannot buy a waiver of G-04. The zero-observed-critical-events condition is only one gate among controls and review, not proof of zero risk.
Use a three-valued status to distinguish PASS, FAIL and HOLD (insufficient or unreliable evidence). A missing evaluation report is not a pass. Some failures warrant containment regardless of sample sufficiency. A release can pass offline gates and still be held pending a controlled pilot; a pilot success does not replace security evidence.
Thresholds should be selected from user needs, risk analysis, baseline performance, feasible engineering and uncertainty. Do not choose them retrospectively to match a candidate's results. If stakeholders approve a legitimate change, create a new version, record the reason, and reassess the baseline and candidate on a comparable basis.
11. Build representative evaluation datasets#
An evaluation dataset is part of the requirements contract, not just a folder of convenient examples. Design it to estimate the intended production quantity and exercise unacceptable failure modes.
Use distinct datasets or suites for distinct purposes:
| Dataset or suite | Purpose |
|---|---|
| Development set | Tune prompts, models, rules and heuristics |
| Frozen representative holdout | Estimate performance on the agreed population |
| Critical-case suite | Exercise mandatory boundaries and severe error cases |
| Shift and robustness suite | Test missing inputs, changed formats, unusual languages and dependency failures |
| Integration fixtures | Verify state, identity, policy versions and side effects |
| Production audit sample | Monitor real outcomes under the current policy |
| Pilot or experiment population | Estimate user/business outcomes using valid design |
A targeted adversarial suite is useful for finding weaknesses but is not generally an unbiased sample of real-world incident frequency. Keep representative statistical evidence separate from intentionally oversampled severe cases. If rare cases are oversampled for a population estimate, use a valid sampling design and weighting.
For the fictional support assistant, create a task manifest with request text, permitted account context, source documents and versions, expected or acceptable outcomes, difficulty, policy scope, answer rubric and review status. Include exact lookups, ambiguous requests, incomplete evidence, policy exceptions and authorization denials. Capture realistic languages and accessibility needs without inferring sensitive traits unnecessarily.
Hold out cases by appropriate entity or time when related records would leak information across splits. Use point-in-time sources for historical tasks. Freeze the candidate configuration and evaluator version before the final run. Keep reference answers and labels restricted to appropriate evaluation environments; do not train or tune on the final holdout and then report it as untouched.
Human annotators need shared guidance and adjudication for disagreement. Some answers have several valid phrasings. Evaluate substantive correctness and evidence rather than exact string equality for open-ended text. An LLM evaluator can help triage examples only after its reliability against trusted judgments is established; it should not independently establish a sensitive release boundary simply because it produces confident scores.
12. Statistical confidence: why the sample size matters#
A 97% observed success rate from 100 tasks is not equally informative as 97% from 1,000 tasks. A release requirement concerns an underlying task population, so estimate uncertainty with a method appropriate to the data and sampling design.
For independent identically distributed Bernoulli trials, a one-sided approximate Wilson lower confidence bound for success probability can be written as:
p_hat = k / n
d = 1 + z^2 / n
lower = (p_hat + z^2/(2n)
- z * sqrt(p_hat*(1-p_hat)/n + z^2/(4n^2))) / dHere k is successful audited tasks, n is the number of trials, and z is the appropriate normal quantile. For an approximately 95% one-sided bound, z is about 1.64485. This is not the same as the lower endpoint of a two-sided 95% interval, which uses about 1.96. Wilson intervals have good practical coverage behavior relative to naive Wald intervals, but coverage is approximate, not a guarantee for every n and underlying probability.
In the illustrative gate G-02:
- 970 successes in 1,000 independent tasks gives an observed rate of 97% and a lower bound of approximately 95.978%. The lower bound exceeds 95%.
- 97 successes in 100 tasks also gives 97%, but a substantially lower bound, below 95%; it additionally fails the example minimum sample rule.
- 950 successes in 1,000 tasks gives an observed 95%, but the lower bound is below 95%; a candidate with a true success rate near the target does not reliably demonstrate superiority to that target on a finite sample.
This gate addresses a narrowly defined outcome on a representative fixed audit. Real user tasks may be correlated within accounts, sessions, regions or time periods. Use cluster-aware intervals or a justified bootstrap/design-based approach as appropriate. Stratified weighting, delayed adjudication and nonrandom missing outcomes require corresponding methods. A simple Wilson calculation cannot correct selection bias.
Prespecify sample size using expected baseline and effect size, desired uncertainty or power, and the risk of incorrect promotion. The illustrative 1,000-task minimum is not a universal sample-size rule. If monitoring many cohorts or repeatedly inspecting an experiment for success, account for multiplicity and sequential testing. A fixed-sample interval used repeatedly without adjustment is not automatically a valid anytime confidence procedure.
For rare critical events, absence of observed failures is especially weak evidence. Under an ideal independent sample with zero failures in 1,000 trials, an exact one-sided 95% upper bound on failure probability is 1 - 0.05^(1/1000), approximately 0.299%. That does not guarantee the system is safe at a much lower required incident rate. Use defense in depth, direct invariants, authorization tests, threat analysis and independent review. Sampled model performance is not a substitute for mandatory controls.
13. Worked scenario: support assistant acceptance record#
Consider a fictional readiness review where a candidate is assessed against the previous requirements. The point of the example is to keep incomplete evidence visible.
| Requirement | Example result | Status |
|---|---|---|
| FR-01 to FR-05 | Required ownership, abstention, handoff and no-write tests pass | PASS |
| NFR-01 / G-02 | 970 of 1,000 audited independent tasks correct; one-sided lower bound 95.978% | PASS |
| NFR-02 / G-03 | 995 of 1,000 offered test tasks valid within 3 seconds; observed 99.5% | PASS |
| G-04 | Zero observed critical failures in defined suites; independent control review passes | PASS for this gate only |
| NFR-04 / G-05 | $82 attributable cost for 970 successful tasks: about $0.0845 per success | PASS under example budget |
| NFR-06 / G-06 | Required rollback and fallback exercises completed | PASS |
| G-07 | Business benefit pilot not yet complete | HOLD |
The quality and latency populations can be different suites; the cost illustration assumes a single specified 1,000-task costing run with 970 successes and comparable accounting. Do not multiply marginal pass rates to invent a joint task success count. If the contract requires correct AND timely AND authorized completion, count the intersection directly from linked outcomes.
The candidate may qualify for an approved limited pilot under a stage-specific policy, but general availability remains on HOLD until the required product-benefit evidence is reviewed. A 99.5% point estimate for the load-test timeliness gate is not a long-term SLO guarantee or a confidence-bound claim. Ongoing 30-day availability and deadline attainment must be measured independently in operation.
If the pilot detects an unacceptable privacy violation, stop or contain affected exposure according to policy without waiting for the business metric to mature. If the latency gate fails under realistic workload, investigate system behavior before relaxing the target. ASD-003 will develop workload and resource sizing methods; this lesson defines the demand and evidence contract that those methods must serve.
14. Practical implementation: evaluate an acceptance decision#
The following Python program implements a deliberately limited subset of the example release gates: a fixed-audit one-sided Wilson lower bound, an observed good-response deadline fraction, independent mandatory-control and observed-critical-event checks, and an exact fractional event-budget calculation. It distinguishes insufficient evidence from a failed threshold.
It assumes the evidence has already been authenticated, deduplicated, scoped to the correct candidate and evaluated under the approved sampling design. It does not perform model inference, test authorization, calculate a causal business effect, assess statistical dependence or approve actual deployments. A PASS means only the four coded gates pass, not general availability.
PYTHONfrom math import sqrt, isfinite from fractions import Fraction def wilson_lower(k, n, z=1.6448536269514722): if type(k) is not int or type(n) is not int or not 0 <= k <= n or n == 0: raise ValueError('invalid binomial counts') if not isfinite(z) or z <= 0: raise ValueError('invalid z') p = k / n d = 1 + z*z/n return max(0., (p + z*z/(2*n) - z*sqrt(p*(1-p)/n + z*z/(4*n*n))) / d) def budget(total, bad, target=Fraction(999, 1000)): if type(total) is not int or type(bad) is not int or not 0 <= bad <= total: raise ValueError('invalid event counts') if not isinstance(target, Fraction) or not 0 < target < 1: raise ValueError('invalid target') allowance = (1-target)*total return allowance, allowance-bad, None if total == 0 else Fraction(bad, total)/(1-target) def release(correct, audited, fast, offered, critical, controls): if any(type(v) is not int or v < 0 for v in (correct, audited, fast, offered, critical)): raise ValueError('invalid counts') if correct > audited or fast > offered or type(controls) is not bool: raise ValueError('invalid evidence') if critical or not controls: return 'FAIL' if audited < 1000 or offered < 1000: return 'HOLD' if wilson_lower(correct, audited) < .95 or Fraction(fast, offered) < Fraction(99,100): return 'FAIL' return 'PASS' assert .95 < wilson_lower(970, 1000) < .97 assert wilson_lower(97, 100) < .95 assert release(970, 1000, 995, 1000, 0, True) == 'PASS' assert release(950, 1000, 995, 1000, 0, True) == 'FAIL' assert release(970, 1000, 989, 1000, 0, True) == 'FAIL' assert release(970, 1000, 995, 1000, 1, True) == 'FAIL' assert release(970, 1000, 995, 1000, 0, False) == 'FAIL' assert release(97, 100, 995, 1000, 0, True) == 'HOLD' assert release(0, 0, 0, 0, 0, True) == 'HOLD' assert budget(100000, 35) == (100, 65, Fraction(35,100)) assert budget(10000, 40) == (10, -30, 4) assert budget(0, 0) == (0, 0, None) for fn in [lambda: wilson_lower(101, 100), lambda: budget(10, 11), lambda: release(1001, 1000, 995, 1000, 0, True), lambda: release(970, 1000, 995, 1000, -1, True)]: try: fn() except ValueError: pass else: raise AssertionError('invalid evidence accepted') print('16 checks passed') print(f'Wilson lower bound: {wilson_lower(970,1000):.6f}')
Observed local execution, Python 3.13.5:
16 checks passed
Wilson lower bound: 0.959780The twelve direct assertions cover uncertainty at different sample sizes, passing evidence, point-estimate quality failure, deadline failure, a critical incident, failed independent controls, insufficient data, empty observations and exact error-budget arithmetic. Four further assertions check rejection of malformed evidence.
The release function treats every counted audited outcome as a success or a failure. It assumes unresolved or selectively missing labels have been handled by the evidence contract before this call; a production evaluator should carry explicit label-maturity and sampling-validity statuses rather than drop unresolved cases. A control review that has not occurred should produce HOLD in a complete evidence system unless a known violation already warrants FAIL. The toy interface uses a Boolean only for completed review evidence. It checks severity and control failure before sample sufficiency because those mandatory failures are not repaired by gathering more ordinary successes.
Fraction avoids binary floating-point boundary artifacts for the simple rational latency and event-budget targets. The Wilson calculation uses floating-point arithmetic appropriate to the teaching example; it is not an exact interval. The calculations are constant-size operations with O(1) arithmetic-operation complexity for fixed-size numeric inputs. A real event-aggregation service must process, deduplicate, reconcile and validate N events; its cost is not represented by this helper.
Use the example as a small executable specification for a review gate. In a production system, acceptance records should also identify the candidate artifact digest, dataset and evaluator versions, scope, time, threshold version, named owners and all required evidence. Do not embed an unreviewable hardcoded threshold into a deployment pipeline without an agreed change-control mechanism.
15. Requirement traceability from need to test and monitor#
Traceability makes an architecture review auditable. A requirement traceability matrix links each business objective to functional or quality requirements, verification evidence, operational measures and owners. Many-to-many relationships are normal: multiple requirements may support one objective, and one security control may protect several objectives.
Example:
| Business objective | Requirement IDs | Acceptance evidence | Production signal | Owner |
|---|---|---|---|---|
| B-01 Reduce handling effort | FR-02, FR-03, NFR-01, NFR-04 | Holdout rubric, cost accounting, controlled pilot | Handling time, successful resolution, review hours | Product/operations |
| B-02 Improve response speed | NFR-02, NFR-03 | Load and failure scenarios | Valid deadline fraction, availability | SRE/service team |
| B-03 Preserve customer trust | FR-01, FR-05, NFR-05 | Authorization and no-write tests, review | Access-denial audit, critical incident reports | Security/policy |
| B-04 Handle ambiguity safely | FR-03, FR-04 | Missing/conflicting evidence fixtures | Escalation coverage and quality | Support/domain owner |
| B-05 Maintain service continuity | NFR-06 | Recovery and rollback exercise | Incident recovery evidence | Release/SRE owners |
A traceability row should point to actual versioned artifacts rather than simply say "tested." For example, FR-01 could reference an access-control fixture suite, the exact deployment candidate, the approved authorization specification and a result digest. An independent approver should be able to reproduce or inspect the result without guessing which configuration was evaluated.
Use automated checks for coverage: every mandatory requirement must have a verification plan and an accountable owner; every required acceptance test must map to a requirement; each required production objective must have appropriate telemetry and an operational owner. Coverage of the matrix is not coverage of all possible failures. It detects missing obligations and makes omissions visible.
Changes to requirements may invalidate previous test results. A prompt change, model upgrade, data-source modification, policy update, different deployment region or user-facing scope change may require partial or full revalidation. Define impact assessment rules and record which evidence is still applicable.
16. Safety guardrails and non-negotiable constraints#
Safety requirements need both preventive enforcement and evidence of enforcement. Consider a read-only assistant with access to customer orders. The model should not be the authority deciding whether one account may read another account's order.
A defensible design includes:
- Authentication and current object-level authorization before retrieving data.
- Purpose-limited access to approved sources and minimal necessary context.
- No write capability in the read-only task surface.
- Independent validation of retrieved facts, generated claims and permitted actions where required.
- Approved fallback or handoff for missing evidence and uncertain cases.
- Logging and incident response that preserve privacy and allow investigation.
Convert these into precise invariants, such as: any response containing a protected order field must have a valid authorization decision for that field's owner and request context. Verify positive and negative cases, capability configurations, stale context and authorization failures. Define who can approve policy exceptions and whether a particular control permits any exception at all.
The requirement "zero unauthorized disclosures" is a normative invariant and an incident trigger, not a statistically demonstrated guarantee. Zero observed failures on finite testing does not prove impossibility. Use multiple layers of protection, audit the actual architecture and maintain a response plan.
Fairness, accessibility and privacy guardrails should reflect the affected user population and domain. Audit performance for relevant languages and request types; handle insufficient evidence transparently. Where sensitive group auditing is appropriate and lawfully authorized, use restricted governance and avoid inferring traits for convenience. Do not hide a severe or systematically disadvantaged cohort behind aggregate quality.
These obligations apply regardless of the selected architecture. They should be stated before building or optimizing the model.
17. Production release lifecycle#
A shadow run can compare candidate outputs without exposing them to users, but cannot establish how users would respond to outputs they never saw. An approved limited pilot can collect product outcomes with appropriate consent, assignment and safeguards. Distinguish offline readiness from exposure readiness and general-availability approval.
Before the pilot, define the primary outcome, minimum practically meaningful improvement, guardrails, assignment unit, population, duration or sample size, analysis method and stop rules. For support workflows, repeated customers or shared staff queues can create dependence or interference. Assigning by request may contaminate treatments if the same staff handle both or a customer returns. Choose a defensible unit and account for clustering.
Analyze all eligible assigned tasks under the specified intent-to-treat approach rather than only successful self-service cases. A lower handling time among AI-completed tasks may simply reflect easy-case selection. Report observed review and transfer effort and any impact on repeat contacts. A candidate that increases automation rate but worsens resolution quality may fail the business objective.
If a severe mandatory incident occurs, follow the preapproved containment policy immediately. If ordinary quality evidence is inconclusive, hold expansion and collect appropriate evidence without claiming success. Avoid repeatedly checking ordinary significance and stopping at the first favorable result unless the design supports sequential decisions.
During rollout, track candidate version, routing assignment, dependency health, workload mix, label maturity and outcome metrics. Define the conditions for a freeze, rollback or scoped fallback, the responsible owner, and evidence that recovery actually restored the service. An API reporting "rollback succeeded" does not establish quality recovery.
18. Second worked scenario: inventory forecasting and replenishment#
A retailer wants to "reduce out-of-stock items without overbuying." This objective is different from support automation and illustrates why requirements must include the downstream decision.
Business requirements may include reduced stockout exposure and no unacceptable increase in excess inventory, waste or working capital. The forecasting component predicts demand over a replenishment horizon; a deterministic or optimization-based component recommends quantities subject to inventory, lead time, shelf-life and purchasing constraints. The model does not directly define the amount that may be ordered.
Define the unit as a SKU-location-horizon at a specified prediction time. Observed sales are not always demand: stockouts, substitutions and promotions affect observed quantities. Maintain the correct evidence definition and account for censoring where appropriate.
A proposed traceability fragment:
| Requirement | Metric or invariant | Example evidence |
|---|---|---|
| B-10 Improve availability | Stockout exposure relative to an agreed baseline | Controlled or otherwise defensible business evaluation |
| FR-10 Provide horizon-specific forecast | Valid prediction and uncertainty contract | Schema tests and temporal evaluation |
| FR-11 Recommend feasible quantity | Quantity respects approved capacity, lead time and ordering limits | Constraint tests and replay |
| NFR-10 Forecast quality | Approved horizon-weighted error and signed bias gates | Rolling historical evaluation on valid targets |
| NFR-11 Timely delivery | Forecast and proposal delivered before purchasing cutoff | Job completion telemetry |
| G-10 Avoid material harm | Approved waste and overstock guardrails | Pilot outcome review |
A forecast with lower MAE can still produce poorer replenishment decisions if it underestimates high-demand products or ignores constraints. Compare the complete ordering policy using representative outcomes and a suitable counterfactual or pilot strategy. Do not label a simulated inventory improvement a measured causal production gain.
Define the time horizon before selecting metrics. A one-day prediction that is highly accurate may not help a supplier order with a four-week lead time. Keep historical as-of features, future realized outcomes and allowable decision inputs distinct. Cost and capacity calculations for the chosen implementation follow later; these criteria establish what the implementation must achieve.
19. Common failure modes and corrective design#
| Failure mode | Why it is misleading | Correction |
|---|---|---|
| "95% accuracy" with no denominator | Different teams count different events | Freeze measurement and inclusion contract |
| Model metric used as business KPI | Component improvement need not help users | Define task outcome and business validation |
| Evaluate only answered tasks | Hides abstentions and unresolved work | Report conditional quality, coverage and full-task outcome |
| Treat missing labels as success | Inflates measured quality | Report unresolved evidence and HOLD when necessary |
| Use a test set for tuning and final evidence | Optimistic evaluation | Separate development and final holdout |
| Average p95 across components | Percentiles do not combine that way | Observe end-to-end deadline and latency distribution |
| Mix request failures and class-specific label misses | Incompatible units | Keep separate service and model-quality budgets |
| Pass on a point estimate with tiny sample | Uncertain population performance | Prespecify uncertainty and sufficiency rules |
| Ignore rare severe errors | Aggregate averages conceal risk | Independent safety invariants and critical suites |
| Confuse zero observed incidents with zero risk | Finite test evidence cannot establish perfection | Control design, bounded scope and monitoring |
| Treat SLO as an external SLA | Confuses target and contractual obligation | Verify approved agreement separately |
| Approve every candidate that passes offline tests | Missing real-world outcome evidence | Stage-specific gates and accountable pilot |
| Change target after a failed test | Undermines decision integrity | Version, approve and re-evaluate changed requirements |
A useful review question is: if this metric improves dramatically, could the intended user experience still get worse? If yes, add the necessary complementary outcome or guardrail, or reconsider the metric's role.
20. A reusable requirement specification#
Use a concise, versioned specification for each material requirement:
requirement_id: NFR-01
version: 1
business_goal: B-01
actor_and_scope: eligible read-only support tasks
expected_behavior: correct, complete, authorized resolution
measurement_contract: resolution_quality_v1
threshold: one-sided 95% lower bound >= 0.95
evidence: representative fixed audit, at least 1000 eligible tasks
assumptions: valid independent sampling; adjudication complete
mandatory_guardrails: no critical violations; reviewed controls
missing_evidence: HOLD
verification_owner: evaluation lead
approval_owner: release owner with required policy/security signoff
production_monitor: task-quality audit and label coverage
failure_response: contain if severe; otherwise hold expansion and investigate
change_control: version and approve; revalidate affected evidenceThe example is a human-readable pseudo-configuration, not a deployable schema or actual customer contract. A production requirements repository may use structured records and CI checks, while sensitive evidence remains in governed stores. The important property is that an auditor can trace a release decision back to the requirement, candidate version, test design and owner.
This specification should be established before detailed architecture choices are finalized. The next capacity-planning lesson will translate request populations, response objectives, workload shapes and retention requirements into throughput, storage, compute and infrastructure estimates.
21. Interview-ready summary#
I would first establish the user problem, primary business outcome, baseline, scope, stakeholders and unacceptable failures. I would turn those into functional requirements and measurable quality, latency, availability, cost and safety constraints. Each metric would define its population, numerator, denominator, observation unit, time window, source and ownership. I would distinguish business KPIs from component model metrics and from operational SLIs, SLOs and contractual SLAs.
I would then create a traceability matrix that links the requirements to representative evaluation data, mandatory invariants, integration tests, acceptance thresholds and production monitoring. I would prespecify statistical confidence and sample sufficiency where population performance is estimated, and keep missing evidence as HOLD rather than PASS. Error budgets would inform release policy for the relevant SLO but would never override mandatory safety and authorization controls.
Finally, I would require stage-specific offline evidence, approved pilot outcomes, operational readiness and accountable sign-off before expanding rollout. The key is to make success and failure independently observable before choosing or optimizing the implementation, so the team can demonstrate that the entire AI system achieves the intended outcome rather than merely improving an isolated model score.
References and research transparency#
The authorized offline research exception was applied. The references below identify established technical guidance and primary research; their live availability and current contents and the current Supabase changelog were not verified. All three diagrams use standard triple-backtick Mermaid fences and were reviewed structurally; a local Mermaid parser was not available and website rendering was not tested. The Python example was executed locally in Python 3.13.5 with all 16 checks passing. The performance figures, business results, sample sizes, acceptance thresholds and service commitments in the scenarios are synthetic and not evidence of real deployment performance or compliance.
- Google SRE — Service Level Objectives
- Google SRE Workbook — Implementing SLOs
- Google SRE Workbook — Error Budget Policy
- Google — Rules of Machine Learning
- Breck et al. — The ML Test Score
- Wilson (1927) — Probable Inference, the Law of Succession, and Statistical Inference
- Brown, Cai and DasGupta — Interval Estimation for a Binomial Proportion
- Kohavi, Tang and Xu — Trustworthy Online Controlled Experiments
- NIST — AI Risk Management Framework 1.0
- NIST — Generative AI Profile
- Mitchell et al. — Model Cards for Model Reporting
References
- 1.Google SRE — Service Level Objectivessre.google
- 2.Google SRE Workbook — Implementing SLOssre.google
- 3.
- 4.Google — Rules of Machine Learningdevelopers.google.com
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.NIST — Generative AI Profiledoi.org
- 11.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython