aiml

Lesson 6 of 21Module 3

Reconstruct the feature used by an earlier prediction

Store feature publication history and reconstruct the count available to an earlier return prediction, without applying later corrections.

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

  • Reconstruct the feature available to an earlier prediction.
  • Distinguish known zero activity from an unknown user.
  • Compare stored historical counts with the manual assembler.
Runtime
Python 3.12+; local CPU
Dependencies
Python standard library and SQLite

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

Progress is saved in this browser.

Store feature publication history and choose the version that was available at prediction time.

Problem

When you need this. A feature table containing only today’s corrected value cannot explain a prediction made last week. The return application must retain what it knew then, even when a later backfill changes an old event count.

This lesson connects the existing SQLite feature-history store to all 240 observations in the shared fixture. The code first checks every stored historical count against the manual assembler. It then publishes a later correction and reads the original prediction again.

Concepts

A feature cutoff ends the event window being counted. A publication time records when a precomputed, stored feature value became available. The two times answer different questions: which activity is summarized, and when could an application read that summary?

A point-in-time lookup keeps only rows whose cutoff and publication time are both at or before prediction time. From those rows, it picks the newest cutoff, then the newest publication. The store can keep a later correction as a new row without replacing the row that an earlier prediction could read.

The shared feature name is recent_event_count. The reused store keeps its internal key, user_events_1d@v1; both names refer to the declared one-day count in this adapter. The mapping is explicit so that the old storage identifier cannot silently change the model’s feature order.

The application already knows its users from the observation list. For a known user with no earlier activity, the adapter stores a count of zero. An unknown user has no row, so the lookup returns nothing for it. This keeps a storage miss from turning into a made-up zero-activity value.

Publication times in this lab are authored fixture times supplied to a trusted local writer. A production writer must derive availability from its real publication event; an operator must not backdate a value to improve a historical evaluation.

Architecture

Original publicationcount 2, January 8Feature historyretained vintagesLater correctioncount 3, January 16Prediction timeJanuary 8 at noonEligible SQL lookupcutoff + publicationHistorical valuecount 2Original publicationcount 2, January 8Later correctioncount 3, January 16Feature historyboth versions retainedPrediction timeJanuary 8 at noonEligible SQL lookupcutoff + publicationHistorical valuecount 2
For user-00-day-08, the later correction changes the count from 2 to 3 for the same cutoff. The earlier prediction still reads 2.

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. This workshop uses the standard library.

Create the local environmentTerminal · bash
python3.12 -m venv .venv
source .venv/bin/activate

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

Publish the original feature snapshots

Create a new database. For each prediction date, the writer counts events under the same arrival rule as the manual baseline. The comparison must cover every observation before the history can feed later training.

Source excerpt: ReturnHistorySource · pythonDownload
class ReturnHistory(History):
    """Retain the old history behavior; explicitly include known users with zero activity."""
    def publish(self, fixture, cutoff, published_at, mode='as_known'):
        key=self.materialize(fixture['events'],cutoff,published_at,mode)
        known=sorted({o['entity'] for o in fixture['observations']})
        with self.db:
            for entity in known:
                inserted=self.db.execute('INSERT OR IGNORE INTO history VALUES (?,?,?,?,?)',(key,entity,cutoff,published_at,0)).rowcount
                if inserted:
                    self.db.execute('''INSERT INTO online VALUES (?,?,?,?,?) ON CONFLICT(feature,entity) DO UPDATE SET cutoff=excluded.cutoff,published_at=excluded.published_at,value=excluded.value WHERE excluded.cutoff>online.cutoff OR (excluded.cutoff=online.cutoff AND excluded.published_at>online.published_at)''',(key,entity,cutoff,published_at,0))
        return key
Source excerpt: publish_historySource · pythonDownload
def publish_history(source, database):
    path=Path(database)
    if path.exists(): raise FileExistsError('use a fresh history database')
    path.parent.mkdir(parents=True,exist_ok=True)
    fixture=w.strict_json(source);w.availability.validate(fixture['observations'],fixture['events'],fixture['labels'])
    store=ReturnHistory(path)
    try:
        for cutoff in sorted({minute(o['predict_at']) for o in fixture['observations']}):
            store.publish(fixture,cutoff,cutoff)
        rows=store.join(fixture['observations'],'user_events_1d@v1')
        expected={r['id']:r['feature_count'] for r in w.prepare(source)['rows']}
        matches=sum(row['feature']['value']==expected[row['id']] for row in rows)
        return {'feature':w.FEATURE,'storage_key':'user_events_1d@v1','observations':len(rows),
                'matching_assembled_counts':matches,'known_users':len({o['entity'] for o in fixture['observations']}),'known_zero_counts_are_materialized':True}
    finally: store.close()
Publish the original feature snapshotsTerminal · bash
python adapt.py history --work work/adaptations
Actual local application outputRecorded output · jsonDownload
{
  "initial_materialization": {
    "feature": "recent_event_count",
    "storage_key": "user_events_1d@v1",
    "observations": 240,
    "matching_assembled_counts": 240,
    "known_users": 24,
    "known_zero_counts_are_materialized": true
  },
  "late_correction": {
    "observation": "user-00-day-08",
    "original": 2,
    "historical_after_correction": 2,
    "later_correction_for_same_cutoff": 3,
    "original_view_preserved": true,
    "latest_eligible_cutoff_at_later_read": 19440
  }
}

The run reports 240 matching counts. For user-00-day-08, the original count is two. A correction published later yields three for that same old cutoff, but querying at the original prediction time still returns two.

Read the eligible vintage

The reused SQL lookup filters on both time fields. The diagnostic reads the later correction with its own query, so it stays separate from the feature available to the old prediction.

Source excerpt: history_reportSource · pythonDownload
def history_report(source, database):
    fixture=w.strict_json(source);store=ReturnHistory(database)
    try:
        o=next(o for o in fixture['observations'] if o['id']=='user-00-day-08')
        cutoff=minute(o['predict_at']);key='user_events_1d@v1'
        original=store.point_in_time(key,o['entity'],cutoff)
        store.publish(fixture,cutoff,minute('2026-01-16T13:00:00Z'),'corrected')
        historical=store.point_in_time(key,o['entity'],cutoff)
        corrected=store.point_in_time(key,o['entity'],minute('2026-01-16T14:00:00Z'))
        # point_in_time selects the newest eligible cutoff, not an arbitrary old cutoff.
        vintage=store.db.execute('SELECT value FROM history WHERE feature=? AND entity=? AND cutoff=? ORDER BY published_at DESC LIMIT 1',(key,o['entity'],cutoff)).fetchone()[0]
        return {'observation':o['id'],'original':original['value'],'historical_after_correction':historical['value'],
                'later_correction_for_same_cutoff':vintage,'original_view_preserved':original==historical,
                'latest_eligible_cutoff_at_later_read':corrected['cutoff']}
    finally:store.close()

A lookup at a much later time selects the newest eligible cutoff, not necessarily the corrected old cutoff. To read the value for one old cutoff, pin that cutoff in a separate query instead of moving the lookup time forward.

The saved run wrote its outputs to recorded-adaptations/; your commands write to work/. Read the actual command records. Use a fresh work directory for another attempt: publish_history refuses a database file that already exists.

Failure cases

Run test_history_reconstructs_all_manual_features and test_historical_prediction_survives_later_correction. The first compares every stored count with the shared assembler. The second publishes a backfill and checks that the earlier prediction still reads its original count.

The reused store rejects a changed feature definition under an existing version. It also refuses a publication time earlier than the latest one it has stored. Hashes and supplied timestamps do not prove who wrote a row, so this local exercise assumes a trusted application process.

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

Running and scaling the workshop

The lab uses a local SQLite file and one writer. That is enough to inspect persistence and time-based queries. It says nothing about the capacity of a distributed feature store.

The writer computes one snapshot per prediction date, each from the same bundled events. For a long history, add incremental computation and indexes, but keep the same cutoff and publication filters. Measure the actual query and materialization workload before you change storage.

Key takeaways

  • Retain publication history instead of overwriting the feature used by earlier predictions.
  • Known zero activity and an unknown user are different cases.
  • The stored features reproduce the manual application before they become another training input.

Best practices

Keep backfills as later publications.

Use the same availability and feature-version rules in training and prediction lookups.

After any change to the writer, rerun test_history_reconstructs_all_manual_features. It fails if a stored count differs from the manual assembler for any observation.

Check your understanding

Why can the later correction contain three events while the original prediction still reads two?

Show the explanation

The correction became available after the original prediction. The historical query excludes that later publication and returns the earlier eligible vintage.

A feature was corrected after a historical prediction. Which value belongs to that prediction?

Choose one answer, then check your reasoning.

Read the explanation

A historical prediction must use the eligible publication available at that time. A correction published later cannot rewrite its input.

References

Written by Arjun Prabhulal.

Module 3

Make the workflow reproducible