aiml
SearchMy learning
Menu

Lesson 6 of 21Module 2

Measure quality by request slice and asymmetric failure cost

Inspect request-group coverage and explicit error costs. Keep critical failures, incomplete runs and empty groups visible beside the overall score.

Prerequisites

The evaluation-set and independent source/action/format diagnostic lessons; fractions and Python dictionaries.

By the end, you can

  • Inspect critical request groups with explicit membership and denominators.
  • Apply declared asymmetric penalties while preserving the underlying outcomes.
  • Keep incomplete execution and empty slices out of unsupported quality or cost claims.
Runtime
Python 3.12+
Dependencies
Standard library only

Lab code, tests and fixtures (ZIP, 25 KB)Quiz check your understanding

Progress is saved in this browser.

Analyze the same saved application outcomes by request group and declared failure consequence. Keep case identity, incomplete outcomes and overlapping memberships visible rather than accepting an overall pass count as a release decision.

Problem

When you need this. An aggregate score hides weak request groups or treats costly and harmless errors alike.

Two controlled faults each pass 11 of 12 development cases. One returns a source for the wrong version. The other constructs a production rollback proposal for a caller whose role should have been refused. Equal pass counts conceal different failures and different consequences.

You will analyze the saved local-function results from the evaluation-set lesson. A request slice is a group selected by request fields, such as version, environment, role or operation. Alongside those group counts, an explicit policy assigns different scenario penalties to failure boundaries. The analysis preserves the original outcomes; it does not rerun the application or call a model.

Concepts

A slice selects cases that share request properties. Slices can overlap: one request may belong to both production and reader-role groups. A critical slice identifies a group whose failures matter to the application’s acceptance policy.

A penalty assigns a declared consequence to an observed failure boundary. The points in this exercise are scenario assumptions, not measured money or incident loss. An incomplete result has no observed failure to price. Its declared interval and an empty slice’s missing rate convey different kinds of missing observations.

Architecture

Reference casesIDs and request fieldsversion, role, environmentSaved outcomesone result per casefirst failure or incompleteDeclared analysis policyrequest-slice predicatesscenario failure penaltiesJoin, price and groupalign results by case IDretain incomplete outcomespreserve slice membershipSlicereportcountscoveragecost boundsThe cost policy changes interpretation,not the recorded execution outcomes.Reference casesIDs and request fieldsSaved outcomesone result per caseDeclared analysis policyslice predicatesscenario failure penaltiesJoin, price and groupalign case IDskeep incomplete outcomesretain slice membershipSlice reportcounts and coverageknown or unknown cost
Each outcome is joined to its request by case ID before grouping. Costs are declared scenario penalties. Incomplete execution remains visible instead of becoming a free or passing case.

The analyzer verifies the saved report and case identities, joins outcomes by case ID and applies slice predicates. A separate penalty policy prices observed boundaries and supplies bounds for incomplete outcomes. Group reports retain their own membership; the overall total counts each case once.

Working code

Start with the same recorded cases and outcomes

Download the complete lab and enter ai-system-slices/:

Prepare and run the slice analysisTerminal · bash
python3.12 -m venv .venv
source .venv/bin/activate
python analyze_slices.py

The standard library is sufficient. cases.json and saved-report.json are unchanged copies from the earlier lesson. They contain twelve authored development cases evaluated under six local-function configurations: the reviewed implementation and five deliberately injected faults.

A pass includes a required refusal when the reference contract calls for one. It does not mean that the application returned or executed a command.

Before analysis, the program checks the reviewed input fingerprints and the report’s case-set, task and harness identities. It uses the existing harness’s case loader, without calling its trial runner. These checks keep the reference cases and saved outcomes from silently drifting apart.

Results are joined by case ID. Reordering result rows does not change the analysis. A missing row, duplicate ID, unknown case or extra trial is refused. An intentionally incomplete execution must remain an explicit row; it cannot disappear from the denominator.

Inspect the group where the failure matters

The permission fault fails reader-proposal. The corresponding request is version 3, production, role reader, operation propose_rollback. The slice reader-production-proposal combines those fields and contains exactly that one case.

SlicePasses / casesMeaning
All requests11 / 12The fault affects one development case.
Reader production proposals0 / 1The sole case in this critical group fails.
Version 40 / 0No case represents this group.

The one-case slice exposes a gap, but it does not estimate a population failure rate. This is a deliberately constructed development set, not a sample of production traffic. More cases would be needed to test variations within that request group.

Slice membership follows the existing request contract. An omitted role defaults to reader. The invalid environment string prod remains distinct from production; analysis does not repair a malformed request before grouping it.

A request can belong to several slices: reader-proposal appears in the production, version-3 and reader-production-proposal groups. Those views overlap. Do not add their counts or costs together; the overall report already counts each case once.

Make the consequence assumptions visible

The penalty policy assigns 8 points to an observed source-selection failure, 25 to an action-policy failure and 100 to an authorization failure. These are declared scenario assumptions, not measured losses or currency.

Inspect the full penalty and slice policy
cost-policy.jsonSource · jsonDownload
{
  "id": "development-scenario-cost-v1",
  "unit": "declared scenario penalty points; not currency or observed business loss",
  "cost_by_boundary": {
    "response-contract": 1,
    "source-selection": 8,
    "task-result": 8,
    "action-policy": 25,
    "authorization": 100,
    "input-contract": 3
  },
  "incomplete_interval": [
    0,
    100
  ],
  "slices": [
    {
      "id": "all",
      "where": {}
    },
    {
      "id": "production",
      "where": {
        "environment": "production"
      }
    },
    {
      "id": "staging",
      "where": {
        "environment": "staging"
      }
    },
    {
      "id": "reader-production-proposal",
      "where": {
        "role": "reader",
        "environment": "production",
        "operation": "propose_rollback"
      }
    },
    {
      "id": "maintainer-production-proposal",
      "where": {
        "role": "maintainer",
        "environment": "production",
        "operation": "propose_rollback"
      }
    },
    {
      "id": "version-2",
      "where": {
        "version": "2"
      }
    },
    {
      "id": "version-3",
      "where": {
        "version": "3"
      }
    },
    {
      "id": "version-9",
      "where": {
        "version": "9"
      }
    },
    {
      "id": "version-4-empty",
      "where": {
        "version": "4"
      }
    }
  ]
}

The earlier report identifies the first failed check for each request. This policy assigns one penalty to that observed boundary. It does not add every possible downstream consequence, and the boundary is not an automatically proven root cause. The independent diagnostics lesson explains how multiple checks can retain separate outcomes when those records are available.

For complete results, the scenario total is the sum of per-case penalties. Passing cases contribute zero. An unknown failure boundary is refused rather than silently priced at zero.

Controlled faultPasses / casesScenario total
source11 / 128 points
permission11 / 12100 points
approval11 / 1225 points
format11 / 121 points

Changing the source-selection penalty from 8 to 16 would change its total while leaving the same 11 passes and one failure. The implementation tests check that distinction. Cost policy is a decision input; editing it is not a measured system improvement.

Keep unknown outcomes out of exact cost totals

The no_output probe returns no answer for one staging lookup. The report retains eleven passes and one incomplete result. Both the pass fraction and completion fraction therefore use all twelve cases as their denominator.

There is no observed failure boundary to price for the incomplete result. The program records an unknown total cost and applies the policy’s interval of 0–100 points to that case. With no other known penalties, the resulting interval is 0–100. If a different report also had an 8-point known failure, its interval would be 8–108.

That interval describes the declared scenario possibilities for unobserved outcomes. It is not a statistical confidence interval or a bound on actual business impact. A numeric zero total would conceal the missing information; a cost of 100 would manufacture a particular failure that was never observed.

An empty slice has a different problem: there are no cases at all. Its rates, cost and interval are null. Zero cases do not demonstrate perfect quality or zero risk.

Run the analysis and failure tests

Check the saved analysis and offline boundariesTerminal · bash
python analyze_slices.py --check
python -m unittest -v test_slices.py
Recorded analysis of saved local outcomesRecorded output · textDownload
Saved local-function outcomes; declared scenario penalty points, not observed money
none: pass=12/12; complete=12/12; cost=0.0
source: pass=11/12; complete=12/12; cost=8.0
permission: pass=11/12; complete=12/12; cost=100.0
approval: pass=11/12; complete=12/12; cost=25.0
format: pass=11/12; complete=12/12; cost=1.0
no_output: pass=11/12; complete=11/12; cost=unknown [0.0, 100.0]
permission / reader production proposals: pass=0/1; cost=100
Version 4 slice: empty, not a passing group
Slices overlap; totals are not additive. Unknown-cost ranges are policy bounds, not confidence intervals.

The 19 tests cover ID alignment, critical and empty slices, overlapping memberships, default/literal request fields, invalid cost values and unknown penalties. They also check that incomplete execution stays visible and that policy edits do not alter the saved execution outcomes.

Inspect the analysis implementation
analyze_slices.pySource · pythonDownload
"""Analyze saved local outcomes by request slice and declared error cost."""
import argparse
import hashlib
import json
import math
from pathlib import Path
from vendor import harness, task

HERE = Path(__file__).resolve().parent
BOUNDARIES = {'response-contract','source-selection','task-result','action-policy','authorization','input-contract'}
REQUEST_FIELDS = {'version','environment','role','operation'}
INPUTS = ('cases.json','saved-report.json','vendor/task.py','vendor/harness.py')


def validate_policy(policy):
    if (not isinstance(policy,dict) or set(policy) != {'id','unit','cost_by_boundary','incomplete_interval','slices'}
            or not all(isinstance(policy[k],str) and policy[k] for k in ('id','unit'))):
        raise ValueError('invalid cost policy fields')
    costs = policy['cost_by_boundary']
    if not isinstance(costs,dict) or set(costs) != BOUNDARIES:
        raise ValueError('cost policy must cover every known failure boundary')
    if any(type(x) not in (int,float) or not math.isfinite(x) or x < 0 for x in costs.values()):
        raise ValueError('costs must be finite nonnegative numbers')
    interval = policy['incomplete_interval']
    if (not isinstance(interval,list) or len(interval) != 2
            or any(type(x) not in (int,float) or not math.isfinite(x) for x in interval)
            or interval[0] != 0 or interval[1] < max(costs.values())):
        raise ValueError('incomplete interval must span zero through every declared penalty')
    if not isinstance(policy['slices'],list) or not policy['slices']:
        raise ValueError('define at least one request slice')
    ids = set()
    for spec in policy['slices']:
        if (not isinstance(spec,dict) or set(spec) != {'id','where'} or not isinstance(spec['id'],str)
                or not spec['id'] or spec['id'] in ids or not isinstance(spec['where'],dict)
                or not set(spec['where']) <= REQUEST_FIELDS
                or not all(isinstance(v,str) and v for v in spec['where'].values())):
            raise ValueError('invalid or duplicate slice definition')
        ids.add(spec['id'])
    return policy


def ledger(cases, report, policy):
    if report['manifest']['case_set']['sha256'] != cases['sha256']:
        raise ValueError('report and reference case-set identities differ')
    expected = {case['id']:case for case in cases['cases']}
    failures = {}
    for row in report['first_failures']:
        id = row['case_id']
        if id not in expected or id in failures:
            raise ValueError('unknown or duplicate failure tag')
        failures[id] = row
    received = {}
    for row in report['results']:
        id = row['case_id']
        if id not in expected or id in received or row['trial'] != 0:
            raise ValueError('one trial-zero result is required for each known case')
        case = expected[id]
        if row['split'] != case['split'] or row['class'] != case['class']:
            raise ValueError('result metadata differs from the reference case')
        verdict = row['verdict']
        if verdict not in ('pass','fail','incomplete'):
            raise ValueError('unknown verdict')
        tag = failures.get(id)
        if verdict == 'pass':
            if tag is not None:
                raise ValueError('passing case cannot have a failure tag')
            boundary, cost = 'pass', 0
        else:
            if tag is None or tag['verdict'] != verdict or tag['reason'] != row['reason']:
                raise ValueError('failure tag differs from its result')
            boundary = tag['boundary']
            if verdict == 'incomplete':
                if boundary != 'dependency-or-no-output':
                    raise ValueError('unknown incomplete boundary')
                cost = None
            else:
                if boundary not in policy['cost_by_boundary']:
                    raise ValueError('failure has no declared penalty')
                cost = policy['cost_by_boundary'][boundary]
        request = case['input']['request']
        received[id] = {'id':id, 'verdict':verdict, 'boundary':boundary, 'cost':cost,
                        'request':{field:request.get(field,'reader' if field=='role' else '')
                                   for field in sorted(REQUEST_FIELDS)}}
    if set(received) != set(expected):
        raise ValueError('missing result: keep incomplete execution as an explicit row')
    return [received[case['id']] for case in cases['cases']]


def summarize(rows, policy):
    n = len(rows)
    counts = {name:sum(row['verdict']==name for row in rows) for name in ('pass','fail','incomplete')}
    known = math.fsum(row['cost'] for row in rows if row['cost'] is not None)
    missing = counts['incomplete']
    return {'cases':n, **counts,
            'pass_fraction':counts['pass']/n if n else None,
            'completion_fraction':(n-missing)/n if n else None,
            'known_cost':known if n else None,
            'total_cost':known if n and not missing else None,
            'cost_interval':[known+missing*bound for bound in policy['incomplete_interval']] if n else None,
            'cost_per_case':known/n if n and not missing else None}


def analyze(cases, report, policy):
    validate_policy(policy)
    rows = ledger(cases,report,policy)
    slices = {}
    for spec in policy['slices']:
        members = [row for row in rows if all(row['request'][key]==value for key,value in spec['where'].items())]
        slices[spec['id']] = {'where':spec['where'], 'case_ids':[row['id'] for row in members], **summarize(members,policy)}
    return {'overall':summarize(rows,policy), 'slices':slices, 'ledger':rows}


def record(root=HERE):
    root = Path(root)
    manifest = json.loads((root/'input-manifest.json').read_text())
    if set(manifest['sha256']) != set(INPUTS):
        raise ValueError('input identity inventory differs')
    for name,expected in manifest['sha256'].items():
        if hashlib.sha256((root/name).read_bytes()).hexdigest() != expected:
            raise ValueError('reviewed input bytes differ: '+name)
    cases = harness.load_cases(root/'cases.json', task)
    task.validate_inputs(cases)
    saved = json.loads((root/'saved-report.json').read_text())
    policy = json.loads((root/'cost-policy.json').read_text())
    reports = {}
    for name, report in saved['reports'].items():
        if (report['manifest']['harness_sha256'] != manifest['sha256']['vendor/harness.py']
                or report['manifest']['task']['sha256'] != manifest['sha256']['vendor/task.py']):
            raise ValueError('saved evaluator identity differs')
        reports[name] = analyze(cases,report,policy)
    return {'mode':'saved local-function evaluation outcomes; scenario cost analysis only',
            'cost_policy':policy, 'case_set_sha256':cases['sha256'], 'reports':reports,
            'files':{name:hashlib.sha256((root/name).read_bytes()).hexdigest()
                     for name in (*INPUTS,'input-manifest.json','cost-policy.json','analyze_slices.py')}}


def main():
    parser=argparse.ArgumentParser();parser.add_argument('--check',action='store_true');parser.add_argument('--save',type=Path)
    args=parser.parse_args();result=record()
    if args.check and result != json.loads((HERE/'result.json').read_text()):
        raise SystemExit('slice/cost results or input bindings differ')
    if args.save:
        with args.save.open('x') as file:file.write(json.dumps(result,indent=2)+'\n')
    print('Saved local-function outcomes; declared scenario penalty points, not observed money')
    for name, report in result['reports'].items():
        row=report['overall']
        cost=str(row['total_cost']) if row['total_cost'] is not None else 'unknown '+str(row['cost_interval'])
        print(f"{name}: pass={row['pass']}/{row['cases']}; complete={row['cases']-row['incomplete']}/{row['cases']}; cost={cost}")
    critical=result['reports']['permission']['slices']['reader-production-proposal']
    print(f"permission / reader production proposals: pass={critical['pass']}/{critical['cases']}; cost={critical['total_cost']:g}")
    print('Version 4 slice: empty, not a passing group')
    print('Slices overlap; totals are not additive. Unknown-cost ranges are policy bounds, not confidence intervals.')


if __name__=='__main__':main()

Design exercise: a candidate fixes several staging format errors but introduces one reader-role proposal failure. Identify the slice results and penalty assumptions you would inspect before accepting the change. Then explain what additional request-prevalence and impact data would be needed to turn this development-set scenario total into an operational risk estimate.

Next, candidate comparison will hold the case set and request budget fixed. It will use these slice and coverage reports alongside overall quality, rather than treating an improved average as sufficient grounds for release.

Failure cases

The source and permission faults have the same pass count but different scenario penalties. The one-case reader-production slice exposes the permission failure. An empty group has no measured rate, and an incomplete result has no exact cost; converting either to zero would conceal missing observations.

Check the input and failure boundaries
Trigger Required behavior
Overall count hides unequal impact Retain equal pass counts alongside different declared failure penalties.
Critical group hidden in aggregate Report the failed reader-production case in its critical slice.
Incomplete outcome treated as zero cost Keep the case and an unknown exact cost with the declared interval.
Empty slice treated as success Return null rates and costs when no cases are present.
Overlapping slices summed Preserve membership without treating slices as a partition.
Result position used for joining Join by stable case ID so row reordering cannot change the result.
Missing/duplicate result Refuse missing, duplicate, unknown or repeated-trial identities.
Changed case-set identity Refuse a report for another case set.
Failure tag absent Refuse an outcome whose boundary information is missing or inconsistent.
Unknown failure priced at zero Refuse a boundary absent from the penalty policy.
Invalid cost values Reject missing, boolean, negative or nonfinite penalties.
Invalid unknown-cost bounds Require incomplete-outcome bounds to cover the declared penalty range.
Changed reviewed inputs Refuse altered reviewed report or case fingerprints before analysis.

Deployment

Retain the exact report, case set and penalty policy with a comparison decision. Review slice definitions and consequence assumptions with the application owner before using them as release rules. The analyzer consumes saved outcomes; it does not provide live request monitoring or measure operational loss.

Scaling

As cases and slice definitions grow, inspect group sizes and repeated membership before interpreting totals. Sparse development groups need more representative cases, not more decimal places. Estimating operational risk additionally needs request prevalence and impact data that this synthetic development set does not contain.

Key takeaways

  • The same overall pass count can conceal a critical failure.
  • Scenario penalties change a decision input, not the measured execution outcome.
  • Incomplete outcomes and empty groups must remain distinguishable.
A request slice contains no reference cases. Which report preserves that boundary?

Choose one answer, then check your reasoning.

Read the explanation

An empty slice has no observed pass rate. The lab represents rates and mean costs as null rather than treating absence as success.

Best practices

  • Join outcomes by stable identity before grouping.
  • Report membership counts with rates and costs.
  • Keep penalty-policy changes separate from application improvements.

References

The complete analysis and its saved inputs are included in the lab ZIP.

Written by Arjun Prabhulal.

Module 2

Evaluate answers and compare system changes