Skip to main content

4. Reviewing and running the pipeline

Question: How are results reviewed, recorded and repeated on new data?

Rationale​

An explanation from a language model is a hypothesis, and the decision about a flagged value belongs to a person who knows the indicator and the country. The pipeline therefore ends in a review. A reviewer reads each explanation next to the series, decides whether the value is an error, an event, or a revision, and the decision is recorded. Without the record, the pipeline produces text that nobody has verified, and the next cycle cannot tell which values were already examined.

Statistical series are updated every year, so the pipeline runs again on new data. A repeat run is only useful when it can be compared with the earlier one. The team needs to know which options and which version of the data produced a result, and which flags are new since the last cycle. Detection standardises each series, so that a new year changes the baseline of the whole series, and an earlier flag can appear or disappear although no earlier value has changed. A comparison of the two runs shows these changes, and the reviewer starts with the new flags.

This chapter covers the review in the reviewer application, the record of a run, and the comparison of two runs. It closes the sequence of the guide, from the prepared series of Chapter 1 to the decisions on the flagged values.

Target state​

  • Every explanation has been read by a reviewer, and every item has a verdict in a record that can be exported.
  • Each run has a record of the data file, the methods, the options, and the software version, so that the run can be repeated.
  • A repeat run on a new release is compared with the earlier run, and the review starts from the flags that are new.

Maturity levels​

LevelSteps
FoundationalOpen the review file in the reviewer application, record a verdict for each item, and export the verdicts.
AI-readyWrite a run record with every run, check that every item has a verdict, and compare each new run with the earlier one.
AI-nativeFeed the verdicts back into the next cycle, for example as the labelled examples with which the thresholds or the prompts are tested, and keep the model and the prompt with each explanation.
Running example

This chapter opens the review file of Chapter 3 for the fictional panel and summarises a set of fictional reviewer decisions. It then adds a fictional year, 2025, to the panel, repeats the run, and compares the two runs. The reviewer decisions in feedback_example.csv and the values of 2025 in indicator_panel_2025.csv are invented for the example.

Recipes​

Recipe

4.1 Review the explanations and record the verdicts

Level
Foundational
Skills
Data steward or subject-matter reviewer
Indicative time
2 hours for the example, and longer for a large run

Result: Each item of the review file has a verdict, the reviewer's comment, and where the explanation is wrong, a suggested classification, and a summary states how many items remain without a verdict.

The reviewer application is a small web application in the repository that loads the review file and stores the reviewers' decisions. It shows a list of the items, one for each indicator, country, and window. For the selected item it shows the series as a chart with the window highlighted, and it shows the explanation of the model with its classification, its confidence, and its evidence. The reviewer sets a verdict for each item. The verdict approved means that the item is acceptable for use as it stands, rejected means that it should not be relied on, and needs_review means that more work is needed before a decision. The reviewer can also add a comment and a suggested classification when the label of the model is wrong. The feedback documentation describes the facet ratings that record which part of an explanation is right.

  1. Start the application with the review file and a file in which to keep the feedback.

    uv run python -m apps.anomaly_review run1/review.json feedback.json

    Open http://localhost:8000 in a browser.

  2. Read each item with the chart. The question for the reviewer is whether the value is an error, a real event, or a revision, and whether the explanation says so with evidence that can be verified.

  3. Set a verdict, and write a comment that states what the next step is, for example to ask the statistical office about the source of a value.

  4. Export the feedback as CSV with curl http://localhost:8000/api/feedback/export. The response is a short JSON message that names the file, and the application writes feedback_export.csv in the folder from which it was started. The CSV is taken from that folder. Redirecting the response to a file would replace the export with the JSON message.

  5. Run the script review_summary.py on the review file and the exported feedback. It counts the verdicts, lists the items that need follow-up, and lists the items without a verdict. A resubmitted verdict for the same item replaces the earlier one.

"""Summarise the reviewers' decisions against the review file.

Purpose: read the review file that `review_export.py` wrote and the feedback
that the review application exports as CSV, and report how many items have a
verdict, how many are still unreviewed, and which items a reviewer wants
followed up. The report is the record that a review cycle is complete.

Usage:
python review_summary.py run1/review.json feedback_example.csv

Requires pandas. Exit status: 0 when every item has a verdict; 1 when a file
cannot be read or lacks the expected columns; 2 when some items have no verdict.

What this does not check: the quality of the verdicts. The script counts
decisions. It does not compare reviewers, and it does not check that a
suggested classification is right.
"""

import argparse
import json
import sys
from pathlib import Path

import pandas as pd

NEEDED = ["indicator_code", "geography_code", "window_str", "verdict"]


def main(argv: list[str] | None = None) -> int:
"""Print the review status.

Parameters
----------
argv : list[str] | None, optional
Command arguments, or the process arguments when omitted.

Returns
-------
int
Zero when every item has a verdict.
"""
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("review", type=Path)
parser.add_argument("feedback", type=Path)
args = parser.parse_args(argv)
try:
items = json.loads(args.review.read_text(encoding="utf-8"))["items"]
feedback = pd.read_csv(args.feedback)
feedback[NEEDED]
except (OSError, KeyError, ValueError) as error:
print(f"Cannot read the inputs: {error}", file=sys.stderr)
return 1

# A resubmitted verdict replaces the earlier one for the same item.
feedback = feedback.drop_duplicates(NEEDED[:3], keep="last")
decided = {
(r.indicator_code, r.geography_code, r.window_str): r
for r in feedback.itertuples()
}
keys = [(i["indicator_code"], i["geography_code"], i["window_str"]) for i in items]
open_items = [k for k in keys if k not in decided]
print(f"items in the review file: {len(keys)}")
print(f"items with a verdict: {len(keys) - len(open_items)}")
counts = pd.Series([decided[k].verdict for k in keys if k in decided])
for verdict, number in counts.value_counts().sort_index().items():
print(f" {verdict}: {number}")
follow_up = [
k for k in keys if k in decided and decided[k].verdict == "needs_review"
]
print("to follow up:")
for key in follow_up:
row = decided[key]
suggestion = row.suggested_classification
suffix = f" (suggested: {suggestion})" if isinstance(suggestion, str) else ""
print(f" {key[0]} {key[1]} {key[2]}{suffix}")
print("without a verdict:")
for key in open_items:
print(f" {key[0]} {key[1]} {key[2]}")
return 2 if open_items else 0


if __name__ == "__main__":
raise SystemExit(main())

Worked example. The file feedback_example.csv holds fictional decisions for five of the eight items, in the layout of the export of the application.

python review_summary.py run1/review.json feedback_example.csv
items in the review file: 8
items with a verdict: 5
approved: 2
needs_review: 2
rejected: 1
to follow up:
EG.ELC.ACCS FFF 2007-2007 (suggested: data_error)
EG.ELC.ACCS EEE 2016-2016 (suggested: data_error)
without a verdict:
SH.MORT.U5 EEE 2010-2010
SH.MORT.U5 GGG 2010-2010
SI.POV.HEAD GGG 2019-2019

The review is incomplete, because three items have no verdict, and the script exits with status 2 so that a scheduled job does not treat the cycle as finished. The reviewer rejected the item for 2017 in the electricity series of Fenmark, because the flag followed from the jump of 2007 and the value lies on the trend. This is the case that Recipe 2.1 describes. The two items that need follow-up carry the suggestion data_error, with the comment to check the source.

What this does not do. The summary counts decisions. It does not show whether the reviewers agree with one another, and the application has no rule for two reviewers who disagree. For a large run, the team decides who reviews which items and who settles a disagreement, and a sample of items is reviewed twice to measure agreement.

Recipe

4.2 Record each run so that it can be repeated

Level
AI-ready
Skills
Data analyst
Indicative time
30 minutes

Result: Every run writes a record of its input file, its methods, its options, the software version, and its counts, and the record is stored with the results.

A run is repeatable when another person can start from the same data file, the same options, and the same software and obtain the same flags. The methods of the suite use a fixed random seed for the isolation forest, so the same inputs give the same flags in the same software version. Without a record, nobody can say later which options produced a result, and a change in the flags between two cycles cannot be traced to its cause.

The script detect_and_shortlist.py of Chapter 2 writes the record run_record.json with every run. The following table lists its fields.

FieldMeaning
input, input_sha256The name of the data file and a checksum of its bytes. A different checksum means that the file has changed, even where the name is the same.
library_versionThe version of the ai4data package that ran.
methods, paramsThe detection methods and the options of each, as in Recipe 2.2.
min_countThe minimum number of agreeing methods that selects a series for explanation.
summaryThe counts of the run: series, observations, imputed values, flags by method, and observations by number of agreeing methods.
shortlisted_series, batch_requestsThe size of the shortlist and the number of requests in the batch file.
  1. Store the record with the detections, the flagged file, the shortlist, and the batch file, in one directory for the run. Name the directory by the date or by the release of the data.
  2. Add what the script cannot know: the name of the model and the provider, the date of the batch, and the version of the prompts. These belong to the explanation step and are kept beside the record.
  3. Keep the data file itself, or a pointer from which it can be fetched again, because the checksum identifies the file and does not store it.
  4. Before a repeat run, compare the new record with the old one. A change of version, options, or checksum is expected, and a change that the team did not intend is a reason to stop.

Worked example. The run of Chapter 2 wrote the following record, which is shown here in part.

{
"input": "indicator_panel.csv",
"input_sha256": "a62b6390d125215baeda90cb827352f16484efc818bc1a92ee514210e95e25b6",
"methods": ["zscore", "tsoutlier", "hampel", "capa", "isotree"],
"params": {"capa": {"robust_scale": true, "beta": 25, "beta_tilde": 18}, "isotree": {"threshold": 0.65}},
"min_count": 3,
...
"shortlisted_series": 7,
"batch_requests": 8
}

The checksum identifies the panel file. If a colleague edits one value of the file, the checksum changes, and the record then shows that the second run did not start from the same data.

What this does not do. The record does not store the data or the software, so that a run can be repeated only where both are still available. It does not cover the explanation step, where a hosted model can change without notice and answer differently to the same request, and where the team records the model and the date for itself.

Recipe

4.3 Repeat the run on a new release and compare it with the last one

Level
AI-ready
Skills
Data analyst
Indicative time
1 hour

Result: A new run on the next release of the data is compared with the earlier run, and a list states which flags are new, which persist, and which no longer appear.

A new release adds a year, and it can also revise earlier values. The team runs the same pipeline with the same options on the new file. The new flags are the ones that need review first, because the earlier flags have a verdict in the record of Recipe 4.1. The script compare_runs.py reads the flagged files of two runs and reports the observations that are flagged by at least a minimum count of methods in each.

"""Compare the flagged observations of two runs of the detection script.

Purpose: when the pipeline is repeated on a new release of the data, list which
flagged observations are new, which persist, and which no longer appear, so
that the reviewer starts with the new ones and the team sees how much the new
data changed the earlier flags.

Usage:
python compare_runs.py run1/flagged.csv run2/flagged.csv --min-count 3

Requires pandas. Exit status: 0 after the comparison; 1 when a file cannot be
read or lacks the columns indicator_id, geography_id, period, and
outlier_count.

What this does not check: why a flag appeared or disappeared. Detection
standardises each series, so one new year changes the baseline of the whole
series, and an earlier flag can drop out without any earlier value changing.
The script also does not detect revisions of earlier values.
"""

import argparse
import sys
from pathlib import Path

import pandas as pd

KEY = ["indicator_id", "geography_id", "period"]


def keys(path: Path, min_count: int) -> set[tuple]:
"""Return the keys of the observations flagged by enough methods.

Parameters
----------
path : Path
A `flagged.csv` file of the detection script.
min_count : int
Number of methods that must flag an observation.

Returns
-------
set[tuple]
Tuples of indicator, geography, and period.
"""
table = pd.read_csv(path)
keep = table[table["outlier_count"] >= min_count]
return set(keep[KEY].itertuples(index=False, name=None))


def main(argv: list[str] | None = None) -> int:
"""Print the new, persisting, and resolved flags.

Parameters
----------
argv : list[str] | None, optional
Command arguments, or the process arguments when omitted.

Returns
-------
int
Zero after the comparison.
"""
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("earlier", type=Path)
parser.add_argument("later", type=Path)
parser.add_argument("--min-count", type=int, default=3)
args = parser.parse_args(argv)
try:
before = keys(args.earlier, args.min_count)
after = keys(args.later, args.min_count)
except (OSError, KeyError) as error:
print(f"Cannot compare the files: {error}", file=sys.stderr)
return 1
print(
f"flags at {args.min_count} methods or more: "
f"{len(before)} earlier, {len(after)} later"
)
print(f"persisting: {len(before & after)}")
for label, group in (
("new", after - before),
("no longer flagged", before - after),
):
print(f"{label}: {len(group)}")
for indicator, geography, period in sorted(group):
print(f" {indicator} {geography} {period}")
return 0


if __name__ == "__main__":
raise SystemExit(main())
  1. Obtain the new release in the same layout as the earlier file, and run detect_and_shortlist.py on it with the same options, in a new directory.
  2. Run compare_runs.py with the flagged files of the two runs and the same minimum count as the shortlist.
  3. Send the new flags to the explanation step and the review. Carry the verdicts of the earlier flags that persist.
  4. Read the flags that no longer appear. A flag can drop out because a revision corrected the value, or because the new year changed the baseline of the series, and the first reading is to check which of the two applies.
  5. Store the comparison with the run record of the new run.

Worked example. The script extend_panel.py adds the fictional year 2025 to every series of the example panel, with a planted jump in two series. The following commands build the new file, run the pipeline on it, and compare the runs.

python extend_panel.py indicator_panel.csv indicator_panel_2025.csv
wrote 812 rows to indicator_panel_2025.csv
python detect_and_shortlist.py indicator_panel_2025.csv --outdir run2
32 series, 832 observations (20 imputed)
flagged by at least one method: 49 (5.9%)
flags by method: zscore 11, tsoutlier 15, hampel 9, capa 46, isotree 13
shortlist at 3 methods: 11 series
batch requests: 11
python compare_runs.py run1/flagged.csv run2/flagged.csv
flags at 3 methods or more: 8 earlier, 11 later
persisting: 7
new: 4
EG.ELC.ACCS HHH 2009
SE.PRM.NENR DDD 2022
SH.MORT.U5 BBB 2025
SI.POV.HEAD FFF 2025
no longer flagged: 1
EG.ELC.ACCS FFF 2017

Of the eight observations flagged by three or more methods in the first run, seven persist and one drops out. The one that drops out is the value of 2017 in the electricity series of Fenmark, which the reviewer rejected in Recipe 4.1 as a side effect of the jump of 2007. Four observations are new. The two planted jumps of 2025, in the mortality series of Brenvale (code BBB) and the poverty series of Fenmark, appear among them. The two others, electricity access in Halvern (code HHH) in 2009 and primary enrolment in Dovenia (code DDD) in 2022, concern earlier years whose values did not change, so that the new year changed the flags of those series. The reviewer examines four items, and the shortlist grows from 7 series to 11.

What this does not do. The comparison matches observations by indicator, geography, and year. It does not detect a revision of an earlier value, and it does not say why a flag appeared or disappeared. A team that expects revisions compares the two data files first and lists the changed values.

Implementation options​

  • The reviewer application runs on a laptop for a small run. For several reviewers, the team runs it on a server and exports the feedback file regularly, and the stable key of an item (indicator, geography, and window) lets resubmitted verdicts replace earlier ones.
  • A team that records its decisions elsewhere, for example in a data quality tracker, can use the review file and the feedback export as the exchange format and keep its own system for the workflow.
  • A scheduled job can run the detection and the comparison at each release, and use the exit statuses of the scripts to stop where a series is dropped, where the review is incomplete, or where the input is unreadable.
  • The feedback can become labelled data. A set of verdicts on flagged values is a test set for a change of thresholds, or for a change of prompts, in the next cycle.

World Bank examples​

Resources​

  • The reviewer feedback documentation explains the review file, the verdicts, and the export, and is used in Recipe 4.1.
  • The detection reference lists the options that a run record has to carry, and is used in Recipe 4.2.
  • The demonstration notebook runs the sequence of the guide on the fictional panel and is the best place to see the pictures that these recipes describe.

Common mistakes​

  • Closing a cycle with unreviewed items leaves flagged values without a decision, and the next cycle cannot tell them from values that were never flagged.
  • Comparing two runs that used different options reports changes that come from the options and not from the data.
  • Reviewing the earlier flags again at every release wastes the time of the reviewers, and the verdicts that already exist are carried forward.
  • Treating a flag that drops out as a resolved problem can hide the fact that a new year moved the baseline of the series.

Verification​

  • Check the status. The summary of Recipe 4.1 exits with status 0, which means that every item has a verdict.
  • Check the record. The run record names the data file by checksum, and the options are those that the team intended.
  • Check the comparison. The comparison of two runs lists every new flag, and a reviewer has seen each of them before the cycle closes.

Checklist​

0 of 5 done

Ticks are saved in this browser only.