aiml

Lesson 16 of 21Module 5

Stage a candidate with an explicit traffic decision

Route a repeatable subset of observation IDs to a candidate bundle, retain routing generations and reject stale configuration updates.

Prerequisites

Complete the preceding course lessons in the shared user-return lab; keep their work/ outputs. Python functions and local CLI commands.

Preparation and term definitions

By the end, you can

  • Keep registry selection separate from traffic configuration.
  • Route an observation repeatably under a stable hash policy.
  • Refuse stale updates using an expected routing generation.
Runtime
Python 3.12+; local CPU
Dependencies
Pinned MLflow, Prefect and FastAPI dependencies in requirements-platform.txt

Lab code, tests and fixtures (ZIP, 1.6 MB)Quiz check your understanding

Progress is saved in this browser.

Select a small, repeatable subset of requests for the candidate and keep each routing change as a transaction.

Problem

When you need this. Registering a candidate does not require every request to use it immediately. Before changing the analyst’s whole batch, the application can route a controlled subset to the candidate while the stable bundle serves the rest.

This workshop uses a local routing table and the same Predictor class for both versions. It first sends all requests to the stable bundle, then sends buckets below 25 to the candidate and finally commits a full-candidate selection for the rollback drill.

Concepts

A canary rollout sends a limited part of eligible traffic to a candidate. This router hashes each observation ID into a bucket from 0 to 99. Buckets below the selected percentage use the candidate. The assignment is repeatable for that observation; a new daily observation ID may receive a different assignment.

A bucket percentage is a routing rule, not a guarantee that exactly that percentage of a small batch is selected. The result reports the actual counts from the 48 requests.

A routing generation is one configuration row: the stable bundle, the candidate bundle, the percentage and a reason. Each change inserts a new row; the code does not edit old rows. A separate head row selects the active generation. stage() opens the transaction with BEGIN IMMEDIATE and compares the caller’s expected generation with the head. If another update moved the head first, the call fails and the newer selection stays.

Both bundles pass loading and compatibility checks before the transaction. The two training runs have equal fitted parameters, so this exercise tests routing and operational control, not a quality gain.

Architecture

Observation IDstable hash bucketRouting generationcandidate buckets < 25Stable bundle34 observed requestsCandidate bundle14 observed requestsObservation IDstable hash bucketRouting generationcandidate buckets < 25Stable bundle34 observed requestsCandidate bundle14 observed requests
The 25-bucket rule selected 14 of the 48 observations for the candidate in this actual run. These are local calls, not a deployed load balancer.

Working code

Download the shared application and tests, unzip it and enter mlops-return-workflow/. Keep the same directory throughout the course. Create the environment once. Install the pinned platform dependencies for this workshop.

Create the local environmentTerminal · bash
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-platform.txt

On PowerShell, activate with .venv\Scripts\Activate.ps1.

Continue from Produce daily predictions and expose an optional HTTP interface; keep the same lab directory and outputs.

Commit a complete routing configuration

The transaction inserts the generation and updates the head together. Readers cannot observe a head pointing to a configuration that was never committed.

Source excerpt: RoutingSource · pythonDownload
class Routing:
    def __init__(self,path):
        self.db=sqlite3.connect(path)
        self.db.row_factory=sqlite3.Row
        self.db.execute('CREATE TABLE IF NOT EXISTS releases (generation INTEGER PRIMARY KEY,stable TEXT NOT NULL,candidate TEXT NOT NULL,percent INTEGER NOT NULL,reason TEXT NOT NULL)')
        self.db.execute('CREATE TABLE IF NOT EXISTS head (singleton INTEGER PRIMARY KEY CHECK(singleton=1), generation INTEGER NOT NULL)')
        self.db.commit()

    def close(self):self.db.close()

    def current(self):
        row=self.db.execute('SELECT r.* FROM releases r JOIN head h ON r.generation=h.generation').fetchone()
        if row is None:raise ValueError('no routing release selected')
        return dict(row)

    def stage(self,stable,candidate,percent,expected_generation,reason='stage'):
        if type(percent) is not int or not 0<=percent<=100:raise ValueError('percent must be an integer from 0 to 100')
        for path in [stable,candidate]:
            _,_,decision=release.load_bundle(path)
            if not decision['passed']:raise ValueError('gate failure prevents routing')
        self.db.execute('BEGIN IMMEDIATE')
        try:
            row=self.db.execute('SELECT generation FROM head WHERE singleton=1').fetchone()
            old=row[0] if row else 0
            if expected_generation!=old:raise ValueError('routing changed; reload before editing')
            generation=old+1
            self.db.execute('INSERT INTO releases VALUES (?,?,?,?,?)',(generation,str(Path(stable).resolve()),str(Path(candidate).resolve()),percent,reason))
            self.db.execute('INSERT INTO head VALUES (1,?) ON CONFLICT(singleton) DO UPDATE SET generation=excluded.generation',(generation,))
            self.db.commit();return self.current()
        except Exception:self.db.rollback();raise

    def predict(self,value):
        # Invalid requests cannot influence routing or create prediction records.
        value=serving.request(value);state=self.current()
        bucket=int(hashlib.sha256(value['id'].encode()).hexdigest()[:8],16)%100
        chosen=state['candidate'] if bucket<state['percent'] else state['stable']
        result=serving.Predictor(chosen).predict(value)
        return dict(result,generation=state['generation'],route='candidate' if bucket<state['percent'] else 'stable',bucket=bucket)

    def rollback(self,target_generation,expected_generation):
        row=self.db.execute('SELECT * FROM releases WHERE generation=?',(target_generation,)).fetchone()
        if row is None:raise ValueError('unknown rollback generation')
        # Revalidate target bytes and code compatibility before changing the head.
        return self.stage(row['stable'],row['candidate'],row['percent'],expected_generation,'rollback to '+str(target_generation))

The same class resolves the selected bundle and attaches generation, route and bucket to each prediction. It does not change a registry alias: the registry alias selects a model version, and this table selects which requests reach each bundle.

Observe the selected subset

The command predicts the shared requests under the 25-bucket rule, records the observed routes and then creates the full-candidate generation used by the next drill.

Source excerpt: rollout_reportSource · pythonDownload
def rollout_report(root):
    need(root,'predictions.json');routing=rollout.Routing(root/'routing.sqlite')
    try:
        first=routing.stage(root/'bundle-v1',root/'bundle-v1',0,0)
        canary=routing.stage(root/'bundle-v1',root/'bundle-v2',25,first['generation'])
        predictions=[routing.predict(row) for row in rows(root)]
        counts=dict(__import__('collections').Counter(p['route'] for p in predictions))
        if len(counts)!=2:raise ValueError('fixture did not exercise both routes')
        full=routing.stage(root/'bundle-v1',root/'bundle-v2',100,canary['generation'])
        w.save(root/'routed-predictions.json',{'predictions':predictions})
        return {'staged_generation':canary['generation'],'candidate_bucket_percent':25,'observed_routes':counts,
                'full_candidate_generation':full['generation'],'routing':'local calls through one transactional routing table',
                'quality_improvement_claimed':False}
    finally:routing.close()
Observe the selected subsetTerminal · bash
python course.py rollout --workspace work/course
Actual local application outputRecorded output · jsonDownload
{
  "staged_generation": 2,
  "candidate_bucket_percent": 25,
  "observed_routes": {
    "stable": 34,
    "candidate": 14
  },
  "full_candidate_generation": 3,
  "routing": "local calls through one transactional routing table",
  "quality_improvement_claimed": false
}

The output reports how many requests each route received. Stable and candidate probabilities remain equal because the candidate was rebuilt from the same training data.

This output is from a saved local run in recorded-platform/; your commands write to work/. Read the actual command records. Use a fresh work directory for another attempt: the command refuses to overwrite an existing rollout.json (topic output already exists), so earlier outputs are preserved.

Failure cases

test_staging_is_atomic_and_rollback_retains_history attempts an update using an old generation. The operation fails and the active generation remains unchanged. The test then rolls back to generation 1, which inserts a new generation instead of editing the old rows.

The router loads each selected bundle before predicting. A missing or changed bundle causes a visible failure; the router does not retry a failed request on another model.

Run the application failure checksTerminal · bash
python -m unittest -v test_platform.py

Running and scaling the workshop

The routing table and predictions run in one local process with SQLite. The workshop does not measure a load-balanced service rollout.

At larger scale, release an immutable compatible application image with its model, resolve bundle state once per worker and coordinate configuration updates. Define error and quality stop criteria before sending real users to a candidate.

Key takeaways

  • A registry alias and a traffic configuration have separate jobs.
  • Stable hashing produces repeatable observation assignments.
  • A transaction and expected generation prevent partial or stale routing updates.

Best practices

Record the actual routed counts as well as the configured percentage.

Check bundle compatibility before changing the routing head.

Pass the generation you just read as the expected generation. When stage() reports routing changed; reload before editing, read the new head and decide whether your change still applies before you stage again.

Check your understanding

Why might a 25-bucket rule route a count other than 12 out of 48 requests to the candidate?

Show the explanation

The hash assigns each observation to one of 100 buckets. The rule sets eligibility, while a small batch can have a different observed fraction.

A router allocates 25% of its hash buckets to a candidate. Must exactly 25% of a finite sample use it?

Choose one answer, then check your reasoning.

Read the explanation

The policy allocates hash buckets, not an exact quota in each finite sample. Report the observed stable and candidate counts.

References

Written by Arjun Prabhulal.

Module 5

Release the model