API

store

Store: the example store treated as versioned model state.

A Store is immutable. Every edit returns a new Store with a new content hash, so a store version can be diffed, bisected, and pinned the way a code commit can. Rows carry provenance (who, when, under which taxonomy version) and an optional scope that bounds the blast radius of an edit.

class Row(text, label, id='', scope=None, created_at=<factory>, author=None, taxonomy_version=None, embedding=None, metadata=<factory>, embedding_model=None)[source]

One labeled example with immutable JSON metadata and an optional vector.

Parameters:
  • text (str)

  • label (str)

  • id (str)

  • scope (str | None)

  • created_at (datetime | None)

  • author (str | None)

  • taxonomy_version (str | None)

  • embedding (ndarray | None)

  • metadata (Mapping[str, Any])

  • embedding_model (str | None)

text

Example text supplied to retrieval and classification.

Type:

str

label

Taxonomy label identifier.

Type:

str

id

Stable identifier, derived from text and label when omitted.

Type:

str

scope

Optional partition used by scope-aware retrieval.

Type:

str | None

created_at

Creation time, or None if unknown; naive times mean UTC.

Type:

datetime.datetime | None

author

Author or source responsible for the example.

Type:

str | None

taxonomy_version

Label definition version reviewed by the author.

Type:

str | None

embedding

Optional finite vector, copied into read-only storage.

Type:

numpy.ndarray | None

metadata

Immutable JSON-compatible provenance or application fields.

Type:

collections.abc.Mapping[str, Any]

embedding_model

Embedder identity; None means externally supplied vectors.

Type:

str | None

with_(**changes)[source]

Return a replacement row with the requested fields changed.

Parameters:

**changes (Any) – Replacement field values.

Returns:

a replacement row with the requested fields changed.

Return type:

Row

to_dict()[source]

Return a JSON-compatible record.

Returns:

a JSON-compatible record.

Return type:

dict[str, Any]

classmethod from_dict(d)[source]

Load a record from its serialized fields.

Parameters:

d (dict[str, Any]) – Serialized record fields.

Returns:

Load a record from its serialized fields.

Return type:

Row

content_id(text, label)[source]

Derive a stable identifier from the text and label.

Parameters:
  • text (str) – Example text.

  • label (str) – Reference label identifier.

Returns:

Derive a stable identifier from the text and label.

Return type:

str

class StoreDiff(added, removed, changed)[source]

Added, removed, and edited rows between two stores.

Parameters:
property touched_ids: frozenset[str]

Return identifiers added, removed, or edited.

Returns:

identifiers added, removed, or edited.

property touched_scopes: frozenset[str | None]

Return scopes affected before or after the change.

Returns:

scopes affected before or after the change.

is_empty()[source]

Return whether the diff contains no changes.

Returns:

whether the diff contains no changes.

Return type:

bool

class Store(rows=(), name='store')[source]

An immutable, content-addressed collection of Rows.

Parameters:
  • rows (Iterable[Row])

  • name (str)

property rows: tuple[Row, ...]

Return the stored rows in insertion order.

Returns:

the stored rows in insertion order.

get(row_id)[source]

Look up a row, returning None when absent.

Parameters:

row_id (str) – Stable identifier of the row.

Returns:

Look up a row, returning None when absent.

Return type:

Row | None

property version: str

Content hash over all serialized row fields, independent of row order.

Returns:

the content-derived version.

add(*rows)[source]

Return a new store containing the additional rows.

Parameters:

*rows (Row) – Rows to include in the store.

Returns:

a new store containing the additional rows.

Return type:

Store

remove(*row_ids)[source]

Return a new store without the specified row identifiers.

Parameters:

*row_ids (str) – Row identifiers to inspect or remove.

Returns:

a new store without the specified row identifiers.

Raises:

KeyError – If a requested row identifier is absent.

Return type:

Store

edit(row_id, **changes)[source]

Return a new store with one row replaced, keeping its identifier.

Parameters:
  • row_id (str) – Stable identifier of the row.

  • **changes (Any) – Replacement field values.

Returns:

a new store with one row replaced, keeping its identifier.

Raises:

ValueError – If inputs violate the documented constraints.

Return type:

Store

filter(pred)[source]

Return a store containing only rows accepted by the predicate.

Parameters:

pred (Callable[[Row], bool]) – Predicate deciding which rows to retain.

Returns:

a store containing only rows accepted by the predicate.

Return type:

Store

scope(scope)[source]

Return a store containing only the requested scope.

Parameters:

scope (str | None) – Scope to select; None denotes unscoped rows.

Returns:

a store containing only the requested scope.

Return type:

Store

diff(other)[source]

Rows that differ between self (before) and other (after).

Parameters:

other (Store) – Candidate store to compare with this baseline.

Returns:

Added and removed rows and ordered before/after pairs for edits.

Return type:

StoreDiff

embeddings()[source]

Stacked embeddings; raises if any row lacks one.

Returns:

A matrix with one vector per row in store order.

Raises:

ValueError – If inputs violate the documented constraints.

Return type:

ndarray

embed(embedder, overwrite=False)[source]

Return a Store where every row carries an embedding.

Parameters:
  • embedder (Embedder) – Text embedding implementation.

  • overwrite (bool) – Whether existing embeddings should be recomputed.

Returns:

Map the text batch to a matrix with one vector per text.

Raises:

ValueError – If inputs violate the documented constraints.

Return type:

Store

to_jsonl(path)[source]

Write records as UTF-8 JSON Lines.

Parameters:

path (str) – Input or output file path.

Return type:

None

classmethod from_jsonl(path, name=None)[source]

Read records from a UTF-8 JSON Lines file.

Parameters:
  • path (str) – Input or output file path.

  • name (str | None) – Human-readable collection or slice name.

Returns:

Read records from a UTF-8 JSON Lines file.

Return type:

Store

taxonomy

Taxonomy: the type system for rows.

Each label has a definition. The hash of that definition is the label’s version. A row records the label version its author saw; when the definition changes, rows written under the old definition become orphans and the TaxonomyValidity check flags them for re-review.

class LabelDef(id, definition, examples_of_boundary=(), deprecated=False)[source]

A label definition and its review boundary examples.

Parameters:
property version: str

Return the content-derived version.

Returns:

the content-derived version.

class Taxonomy(labels, name='taxonomy')[source]

Named label definitions with content-derived versions.

Parameters:
property ids: list[str]

Return all label identifiers.

Returns:

all label identifiers.

property active_ids: list[str]

Return identifiers of labels that are not deprecated.

Returns:

identifiers of labels that are not deprecated.

property version: str

Return the content-derived version.

Returns:

the content-derived version.

label_version(label_id)[source]

Return a label definition version, or None if unknown.

Parameters:

label_id (str) – Label identifier to look up.

Returns:

a label definition version, or None if unknown.

Return type:

str | None

to_json(path)[source]

Serialize the report or taxonomy as JSON.

Parameters:

path (str) – Input or output file path.

Return type:

None

classmethod from_json(path)[source]

Load label definitions from a JSON file.

Parameters:

path (str) – Input or output file path.

Returns:

Load label definitions from a JSON file.

Return type:

Taxonomy

retriever

Retriever and Embedder protocols, plus reference implementations.

The retriever is the function from (query, store) to the evidence the decider sees. Everything the dynamic tier does is expressed through this interface, so a production retriever (dense + lexical + rerank) plugs in by implementing retrieve.

class Embedder(*args, **kwargs)[source]

Interface for mapping text batches into equal-width vectors.

property name: str

Return a stable identity including all embedding configuration.

embed(texts)[source]

Map the text batch to a matrix with one vector per text.

Parameters:

texts (Sequence[str]) – Text batch to embed.

Returns:

The result defined by the protocol.

Return type:

np.ndarray

class Retriever(*args, **kwargs)[source]

Interface for retrieving ordered evidence for a query.

retrieve(query, store, k=None, *, scope=None)[source]

Return up to k examples ranked by similarity to the query.

Parameters:
  • query (str) – Text to classify.

  • store (Store) – Example store to inspect.

  • k (int | None) – Maximum number of neighbors.

  • scope (str | None) – Optional partition used by scope-aware retrievers.

Returns:

The result defined by the protocol.

Return type:

list[Row]

class HashingEmbedder(dim=1024, stopwords=None)[source]

Dependency-free bag-of-words hashing embedder for tests and demos.

Swap for a real sentence embedder in production. The name field is the pinned dependency: changing it invalidates every stored embedding.

Parameters:
property name: str

Return an identity covering hashing dimensions and stopwords.

embed(texts)[source]

Map the text batch to a matrix with one vector per text.

Parameters:

texts (Sequence[str]) – Text batch to embed.

Returns:

Map the text batch to a matrix with one vector per text.

Return type:

np.ndarray

cosine_matrix(a, b)[source]

Return pairwise cosine similarities, treating zero vectors as zero.

Parameters:
  • a (ndarray) – First matrix, with one vector per row.

  • b (ndarray) – Second matrix, with matching vector width.

Returns:

pairwise cosine similarities, treating zero vectors as zero.

Raises:

ValueError – If inputs violate the documented constraints.

Return type:

ndarray

class EmbeddingRetriever(embedder, k=5, scope_aware=False)[source]

Dense kNN over row embeddings with optional scope restriction.

Parameters:
retrieve(query, store, k=None, scope=None)[source]

Return up to k examples ranked by similarity to the query.

Parameters:
  • query (str) – Text to classify.

  • store (Store) – Example store to inspect.

  • k (int | None) – Maximum number of neighbors.

  • scope (str | None) – Scope to select; None denotes unscoped rows.

Returns:

up to k examples ranked by similarity to the query.

Return type:

list[Row]

decider

Decider: the function from (query, evidence) to a label.

In production this is an LLM call. The dynamic tier treats it as opaque and expensive, so it is memoized on the query and full ordered evidence. A case whose retrieved context did not change between two store versions never triggers a second call.

class Decider(*args, **kwargs)[source]

Interface for predicting a label from ordered evidence.

decide(query, examples)[source]

Predict a label from the query and ordered examples.

Parameters:
  • query (str) – Text to classify.

  • examples (Sequence[Row]) – Retrieved evidence in presentation order.

Returns:

The result defined by the protocol.

Return type:

str

class MajorityVoteDecider(fallback='unknown')[source]

kNN decision rule. Deterministic; useful for tests and as a floor.

Parameters:

fallback (str)

decide(query, examples)[source]

Predict a label from the query and ordered examples.

Parameters:
  • query (str) – Text to classify.

  • examples (Sequence[Row]) – Retrieved evidence in presentation order.

Returns:

Predict a label from the query and ordered examples.

Return type:

str

class CallableDecider(fn)[source]

Wrap any function(query, examples) -> label, e.g. an LLM prompt.

Parameters:

fn (Callable[[str, Sequence[Row]], str])

decide(query, examples)[source]

Predict a label from the query and ordered examples.

Parameters:
  • query (str) – Text to classify.

  • examples (Sequence[Row]) – Retrieved evidence in presentation order.

Returns:

Predict a label from the query and ordered examples.

Return type:

str

class MemoizedDecider(inner)[source]

Cache deterministic decisions on full ordered evidence and count real calls.

Parameters:

inner (Decider)

decide(query, examples)[source]

Predict a label from the query and ordered examples.

Parameters:
  • query (str) – Text to classify.

  • examples (Sequence[Row]) – Retrieved evidence in presentation order.

Returns:

Predict a label from the query and ordered examples.

Return type:

str

evalset

EvalSet: the cases that define the decision problem.

Three kinds of case, per the operating post: representative labeled traffic (overall performance), tagged slices (where aggregates hide regressions), and challenge cases (boundaries and high-cost errors). Cases used to discover a change should be split from those used to validate it; split() supports that.

class Case(id, text, label, slices=frozenset({}), challenge=False, cost=1.0, scope=None, metadata=<factory>)[source]

A labeled evaluation query with slices and error cost.

Parameters:
to_dict()[source]

Return a JSON-compatible record.

Returns:

a JSON-compatible record.

Return type:

dict[str, Any]

classmethod from_dict(d)[source]

Load a record from its serialized fields.

Parameters:

d (dict[str, Any]) – Serialized record fields.

Returns:

Load a record from its serialized fields.

Return type:

Case

class EvalSet(cases, name='evalset')[source]

An ordered collection of uniquely identified evaluation cases.

Parameters:
property slices: list[str]

Return the sorted slice names represented by evaluation cases.

Returns:

the sorted slice names represented by evaluation cases.

slice(name)[source]

Return cases belonging to the named slice.

Parameters:

name (str) – Human-readable collection or slice name.

Returns:

cases belonging to the named slice.

Return type:

EvalSet

property challenge: EvalSet

Return the challenge cases.

Returns:

the challenge cases.

split(dev_frac=0.5, seed=0, *, group_key=None)[source]

Split independent groups into discovery and validation cases.

Equal text after Unicode, case, and whitespace normalization stays together. An optional metadata key also joins related cases, including transitive links through duplicate text. The fraction applies to groups, so case counts can differ substantially from the requested proportion.

Parameters:
  • dev_frac (float) – Fraction of independent groups assigned to discovery.

  • seed (int) – Seed for reproducible pseudorandom sampling.

  • group_key (str | None) – Optional metadata field identifying independent groups.

Returns:

Discovery and holdout sets retaining original case order. With at least two groups and an interior fraction, both sets are nonempty.

Raises:

ValueError – If group_key is not a nonempty string when supplied.

Return type:

tuple[EvalSet, EvalSet]

assert_disjoint(other, *, group_key=None)[source]

Reject shared IDs, normalized text, or declared groups between sets.

Parameters:
  • other (EvalSet) – Cases used for the other data role.

  • group_key (str | None) – Optional metadata field identifying independent groups.

Raises:

ValueError – If either set lacks a requested group or the sets overlap.

Return type:

None

to_jsonl(path)[source]

Write records as UTF-8 JSON Lines.

Parameters:

path (str) – Input or output file path.

Return type:

None

classmethod from_jsonl(path, name=None)[source]

Read records from a UTF-8 JSON Lines file.

Parameters:
  • path (str) – Input or output file path.

  • name (str | None) – Human-readable collection or slice name.

Returns:

Read records from a UTF-8 JSON Lines file.

Return type:

EvalSet

objective

Objective: what a store change is judged against.

A primary metric to improve, subject to bounds: minimum accuracy on named slices and a cap on right-to-wrong transitions. A custom primary metric can measure total error cost. Similarity, novelty, and class balance are hypothesis generators, so they live in checks, never here.

accuracy(outcomes)[source]

Return the fraction of correct predictions, or NaN for no cases.

Parameters:

outcomes (Sequence[Outcome]) – Reference cases paired with predicted labels.

Returns:

the fraction of correct predictions, or NaN for no cases.

Return type:

float

weighted_error_cost(outcomes)[source]

Return the total error cost of incorrectly predicted cases.

Parameters:

outcomes (Sequence[Outcome]) – Reference cases paired with predicted labels.

Returns:

the total error cost of incorrectly predicted cases.

Return type:

float

class Objective(primary=<function accuracy>, primary_name='accuracy', higher_is_better=True, min_slice_metric=<factory>, max_right_to_wrong=None, max_right_to_wrong_frac=None, max_right_to_wrong_cost=None, max_slice_metric=<factory>, min_slice_cases=<factory>, min_primary_delta=0.0)[source]

Metric improvement and regression limits required of a candidate.

Parameters:
  • primary (Callable[[Sequence[Outcome]], float])

  • primary_name (str)

  • higher_is_better (bool)

  • min_slice_metric (dict[str, float])

  • max_right_to_wrong (int | None)

  • max_right_to_wrong_frac (float | None)

  • max_right_to_wrong_cost (float | None)

  • max_slice_metric (dict[str, float])

  • min_slice_cases (dict[str, int])

  • min_primary_delta (float)

primary()

Return the fraction of correct predictions, or NaN for no cases.

Parameters:

outcomes (Sequence[Outcome]) – Reference cases paired with predicted labels.

Returns:

the fraction of correct predictions, or NaN for no cases.

Return type:

float

improved(baseline, candidate)[source]

Return whether the metric change meets the required improvement.

Parameters:
  • baseline (float) – Reference store or metric value.

  • candidate (float) – Proposed store or metric value.

Returns:

whether the metric change meets the required improvement.

Return type:

bool

report

Findings and reports: the output of every check.

class Severity(*values)[source]

Finding levels in increasing order of impact.

class Finding(check, severity, message, row_ids=(), case_ids=(), data=<factory>)[source]

One diagnostic with affected rows, cases, and structured details.

Parameters:
to_dict()[source]

Return a JSON-compatible record.

Returns:

a JSON-compatible record.

Return type:

dict[str, Any]

class Report(findings=<factory>, context=<factory>)[source]

Collected findings and the state against which checks ran.

Parameters:
extend(findings)[source]

Append findings to this report.

Parameters:

findings (Iterable[Finding]) – Findings to append.

Return type:

None

by_severity(s)[source]

Return findings at the specified severity.

Parameters:

s (Severity) – Severity to select.

Returns:

findings at the specified severity.

Return type:

list[Finding]

property errors: list[Finding]

Return error findings.

Returns:

error findings.

property warnings: list[Finding]

Return warning findings.

Returns:

warning findings.

passed(fail_on=Severity.ERROR)[source]

Return whether no finding meets or exceeds the failure threshold.

Parameters:

fail_on (Severity) – Minimum finding severity that fails the gate.

Returns:

whether no finding meets or exceeds the failure threshold.

Return type:

bool

by_check()[source]

Group findings by check name.

Returns:

Group findings by check name.

Return type:

dict[str, list[Finding]]

summary()[source]

Return a readable summary of the recorded results.

Returns:

a readable summary of the recorded results.

Return type:

str

to_json(path=None)[source]

Serialize the report or taxonomy as JSON.

Parameters:

path (str | None) – Input or output file path.

Returns:

Serialize the report or taxonomy as JSON.

Return type:

str

pipeline

Application inputs, snapshot references, and observed predictions.

class Query(text, scope=None, metadata=<factory>)[source]

Application input without reference labels, evaluation slices, or costs.

Metadata must contain only inputs available to the application at runtime.

Parameters:
class Snapshot(name, revision, metadata=<factory>)[source]

Reference to an immutable external dataset/index revision.

The application must route to this exact revision. Storecheck records the descriptor but cannot verify the contents of the external service. Metadata may identify collections, index revisions, or namespaces; omit credentials.

Parameters:
to_dict()[source]

Return the external snapshot descriptor.

Returns:

Name, revision, and detached JSON metadata.

Return type:

dict[str, Any]

classmethod from_json(path)[source]

Read a snapshot descriptor from a JSON file.

Parameters:

path (str | Path) – Descriptor file, not a dump of database rows.

Returns:

Validated external snapshot reference.

Raises:

ValueError – If the file does not contain a descriptor object.

Return type:

Snapshot

class Prediction(label, evidence=(), trace=<factory>)[source]

Observed label, final ordered evidence, and optional application trace.

Evidence should be what the application actually used after filtering, fusion, reranking, and truncation. Trace can retain scores, formatted context, and nonsecret provider/configuration details. Empty evidence is permitted when an application cannot expose it; no evidence diagnosis is then possible.

Parameters:
class Pipeline(run, identity)[source]

One synchronous application callable plus its nonsecret configuration.

The callable accepts Query and Store or Snapshot, and returns Prediction. It owns all retrieval and decision behavior. Identity should include code, model, prompt, retrieval, and sampling revisions. Calls are never memoized by the comparison engine; one paired run does not estimate stochastic risk.

Parameters:

comparison

Reproducible comparison artifacts shared by the Python API and CLI.

class ComparisonReport(_json)[source]

An immutable JSON snapshot of a completed comparison.

Parameters:

_json (str)

to_dict()[source]

Return an independent copy of the artifact.

Returns:

Manifest, findings, metrics, and all paired case results.

Return type:

dict[str, Any]

to_json(path=None)[source]

Serialize the artifact, optionally writing it as UTF-8.

Parameters:

path (str | Path | None) – Optional output file.

Returns:

Strict JSON with unavailable metrics represented as null.

Return type:

str

property exit_code: int

Return the process status for this result.

Returns:

Zero for pass, one for fail, or two for unevaluable.

summary()[source]

Describe the verdict, sample size, costs, and failed requirements.

Returns:

Human-readable CLI output.

Return type:

str

compare_stores(baseline, candidate, evalset, *, pipeline, objective=None, taxonomy=None, discovery=None, group_key=None)[source]

Run the customer’s application against both revisions for every case.

No prediction is reused, even for unchanged evidence or duplicate queries. External snapshots are caller-declared immutable references; the application must honor their revisions. This is one observed paired run, not a statistical guarantee about future or stochastic behavior. Runtime metadata must not contain reference answers. Input validation completes before application calls.

Parameters:
  • baseline (Store | Snapshot) – Current local data or external snapshot reference.

  • candidate (Store | Snapshot) – Proposed local data or external snapshot reference.

  • evalset (EvalSet) – Fixed labeled evaluation cases.

  • pipeline (Pipeline) – Application callable and its complete nonsecret configuration.

  • objective (Objective | None) – Gate requirements; defaults to nondecreasing accuracy.

  • taxonomy (Taxonomy | None) – Optional label definitions for validation and run identity.

  • discovery (EvalSet | None) – Optional nonempty, disjoint cases used to select the edit.

  • group_key (str | None) – Optional metadata field for discovery/validation overlap checks.

Returns:

Immutable comparison artifact with a pass, fail, or unevaluable verdict.

Raises:

ValueError – If inputs, reference labels, or application outputs are invalid.

Return type:

ComparisonReport

config

Strict TOML configuration and adapter factories for comparison runs.

compare_from_config(baseline, candidate, path)[source]

Load a TOML configuration and execute the shared comparison engine.

Data paths are relative to the configuration file. Custom factories are imported Python code; run only configurations and adapters you trust.

Parameters:
  • baseline (Store | Snapshot) – Current data or immutable external snapshot reference.

  • candidate (Store | Snapshot) – Proposed data or immutable external snapshot reference.

  • path (str | Path) – Configuration file with schema_version, evalset, and pipeline.

Returns:

The same comparison artifact produced by the Python API.

Raises:

ValueError – If settings are unknown, missing, or inconsistent.

Return type:

ComparisonReport

runner

Run a list of checks against a store and collect a Report.

run_checks(store, checks, taxonomy=None, embedder=None)[source]

Run each check against the supplied store and collect findings.

Parameters:
  • store (Store) – Example store to inspect.

  • checks (Iterable[Check]) – Checks to run; None selects the default static checks.

  • taxonomy (Taxonomy | None) – Current label definitions, when available.

  • embedder (Embedder | None) – Text embedding implementation.

Returns:

Run each check against the supplied store and collect findings.

Return type:

Report

run_static(store, taxonomy=None, embedder=None, checks=None)[source]

Run the configured static diagnostics against a store.

Parameters:
  • store (Store) – Example store to inspect.

  • taxonomy (Taxonomy | None) – Current label definitions, when available.

  • embedder (Embedder | None) – Text embedding implementation.

  • checks (Iterable[Check] | None) – Checks to run; None selects the default static checks.

Returns:

Run the configured static diagnostics against a store.

Return type:

Report

testing

Helpers for using storecheck inside pytest.

from storecheck.testing import assert_clean def test_store_is_clean(): report = run_static(store, taxonomy, embedder) assert_clean(report)

assert_clean(report, fail_on=Severity.ERROR)[source]

Raise AssertionError when findings reach the failure threshold.

Parameters:
  • report (Report) – Report whose findings must meet the failure threshold.

  • fail_on (Severity) – Minimum finding severity that fails the gate.

Raises:

AssertionError – If findings reach the failure threshold.

Return type:

None

checks.base

Check protocol shared by all tiers.

class CheckContext(store, taxonomy=None, embedder=None)[source]

Context shared by checks.

Static checks use the store, taxonomy, and embedder. Dynamic checks receive an evaluator when constructed.

Parameters:
class Check(*args, **kwargs)[source]

Interface implemented by static, dynamic, and mutation checks.

run(ctx)[source]

Return findings for the supplied check context.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings produced by the check.

Return type:

list[Finding]

checks.static

Static tier: diagnostics that do not call the decider.

These are the lint layer. They catch rows that are malformed, out of type (label missing or redefined), redundant, stale, leaky, or sitting in a neighborhood that disagrees with their label. None of them can say whether a row helps decisions; that is the dynamic tier’s job.

class SchemaCheck(min_chars=3, max_chars=4000, require_scope=False, require_author=False)[source]

Required fields present, text within length bounds, label well formed.

Parameters:
  • min_chars (int)

  • max_chars (int)

  • require_scope (bool)

  • require_author (bool)

run(ctx)[source]

Check text length, label presence, and required provenance fields.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class TaxonomyValidityCheck[source]

Check label existence, deprecation, and definition versions.

run(ctx)[source]

Check unknown, deprecated, and outdated label definitions.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class ExactDuplicateCheck[source]

Same normalized text appearing more than once.

Same label: redundancy (WARN); redundant rows crowd better evidence out of a fixed context. Different labels: contradiction (ERROR); the store is telling the decider two things about one input.

run(ctx)[source]

Group normalized identical texts and flag label conflicts.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class NearDuplicateCheck(threshold=0.95, conflict_threshold=None, max_pairs=200)[source]

Pairs above a cosine threshold.

Conflicting labels across a near-duplicate pair are the cheapest signal of a mislabel or a taxonomy distinction the representation cannot see.

Parameters:
  • threshold (float)

  • conflict_threshold (float | None)

  • max_pairs (int)

run(ctx)[source]

Inspect the highest-similarity pairs for redundancy or conflict.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class StalenessCheck(ttl=datetime.timedelta(days=365), now=None)[source]

Rows older than a TTL.

Age is a hypothesis generator: old rows may describe products, policies, or

phrasings that traffic no longer uses.

Parameters:
  • ttl (timedelta)

  • now (datetime | None)

run(ctx)[source]

Find examples older than the configured age limit.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class PIICheck(patterns=None)[source]

Patterns that should never sit in an example store.

Extend patterns for domain identifiers (order numbers, member ids).

Parameters:

patterns (dict[str, re.Pattern] | None)

run(ctx)[source]

Find rows matching configured identifier patterns.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class NeighborhoodPurityCheck(k=5, min_purity=0.4)[source]

Measure the fraction of neighbors sharing each row label.

Low purity means one of three things: the row is mislabeled, it sits on a real boundary (keep it; it is doing work), or the embedding collapses a distinction the taxonomy draws. The check cannot tell these apart; the dynamic tier’s row-influence check can.

Parameters:
run(ctx)[source]

Measure each row’s same-label fraction among nearest neighbors.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class ScopeBalanceCheck(min_per_label=3)[source]

Report rows per scope and per label.

Flag labels with fewer than min_per_label examples. Class balance is a hypothesis generator, so this is INFO/WARN.

Parameters:

min_per_label (int)

run(ctx)[source]

Report scope and label counts and flag underrepresented labels.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

checks.dynamic

Dynamic tier: checks that run retrieval and (sparingly) the decider.

Core operation: hold the eval set fixed, change the store, and compare. Retrieval runs for both store versions; the decider runs only on cases whose retrieved context changed. The MemoizedDecider makes that automatic.

class CaseResult(case, evidence, predicted, trace=<factory>)[source]

Prediction and ordered retrieved evidence for one labeled query.

Parameters:
property correct: bool

Return whether the predicted label equals the reference label.

Returns:

whether the predicted label equals the reference label.

property evidence_ids: tuple[str, ...]

Return retrieved identifiers in evidence order.

Returns:

retrieved identifiers in evidence order.

class EvalRun(store_version, results)[source]

Predictions and evidence recorded against one store version.

Parameters:
property outcomes: list[tuple[Case, str]]

Return paired reference cases and predictions.

Returns:

paired reference cases and predictions.

metric(fn=<function accuracy>)[source]

Evaluate the requested metric on the recorded outcomes.

Parameters:

fn (Callable[[Sequence[Outcome]], float]) – Callable used to compute the result.

Returns:

Evaluate the requested metric on the recorded outcomes.

Return type:

float

by_slice(fn=<function accuracy>)[source]

Summarize results separately for each represented slice.

Parameters:

fn (Callable[[Sequence[Outcome]], float]) – Callable used to compute the result.

Returns:

Summarize results separately for each represented slice.

Return type:

dict[str, float]

retrieval_counts()[source]

Count how many times each row appears in retrieved evidence.

Returns:

Count how many times each row appears in retrieved evidence.

Return type:

dict[str, int]

class Transition(case, before, after, evidence_before, evidence_after)[source]

A case prediction before and after a store change.

Parameters:
property kind: str

Classify the before/after prediction transition.

Returns:

Classify the before/after prediction transition.

class Comparison(baseline, candidate, context_changed, decider_calls, transitions=<factory>)[source]

Paired runs and prediction transitions caused by a store change.

Parameters:
count(kind)[source]

Count transitions of the specified kind.

Parameters:

kind (str) – Transition kind to count.

Returns:

Count transitions of the specified kind.

Return type:

int

property wrong_to_right: list[Transition]

Return cases corrected by the candidate.

Returns:

cases corrected by the candidate.

property right_to_wrong: list[Transition]

Return cases broken by the candidate.

Returns:

cases broken by the candidate.

by_slice()[source]

Summarize results separately for each represented slice.

Returns:

Summarize results separately for each represented slice.

Return type:

dict[str, dict[str, int]]

summary()[source]

Return a readable summary of the recorded results.

Returns:

a readable summary of the recorded results.

Return type:

str

class Evaluator(retriever, decider, evalset)[source]

Runs an EvalSet against a Store through a Retriever and Decider.

Parameters:
run(store, cases=None)[source]

Retrieve evidence and predict a label for each selected case.

Parameters:
  • store (Store) – Example store to inspect.

  • cases (Iterable[Case] | None) – Labeled evaluation cases.

Returns:

Predictions and retrieved evidence in case order.

Return type:

EvalRun

compare(baseline, candidate, baseline_run=None)[source]

Retrieval runs on both stores; the decider only where context differs.

Parameters:
  • baseline (Store) – Reference store or metric value.

  • candidate (Store) – Proposed store or metric value.

  • baseline_run (EvalRun | None) – Optional previously computed reference run.

Returns:

Paired results, transitions, context changes, and additional decider calls.

Raises:

ValueError – If inputs violate the documented constraints.

Return type:

Comparison

judge(cmp, objective, check_name='regression')[source]

Turn a Comparison into findings against an Objective.

Parameters:
  • cmp (Comparison) – Paired evaluation results.

  • objective (Objective) – Metric and transition requirements.

  • check_name (str) – Name attached to emitted findings.

Returns:

Informational comparison details and any violated objective requirements.

Return type:

list[Finding]

class RowInfluence(row, comparison)[source]

Observed effect of removing one row from a fixed store.

Parameters:
property net: int

Return cases fixed minus cases broken by removing the row.

Positive values indicate observed net harm on these cases.

Returns:

Cases fixed minus cases broken when the row is removed.

property helps: int

Return cases broken when this row is removed.

Returns:

cases broken when this row is removed.

property hurts: int

Return cases corrected when this row is removed.

Returns:

cases corrected when this row is removed.

property retrieved_for: int

Return the number of cases whose context changed after removal.

Returns:

the number of cases whose context changed after removal.

row_influence(evaluator, store, row_ids=None, baseline_run=None)[source]

Leave-one-out influence of each row on the eval set.

Cost: one retrieval pass per row, plus decider calls only on cases whose evidence changed. Rows never retrieved are skipped only when the retriever declares deletion_stable=True: removing an unretrieved row cannot change its ranked results. Other retrievers inspect every row.

Parameters:
  • evaluator (Evaluator) – Configured retrieval and decision evaluator.

  • store (Store) – Example store to inspect.

  • row_ids (Sequence[str] | None) – Row identifiers to inspect or remove.

  • baseline_run (EvalRun | None) – Optional previously computed reference run.

Returns:

Row-removal comparisons sorted by decreasing net cases fixed.

Raises:

ValueError – If the supplied baseline run belongs to another store.

Return type:

list[RowInfluence]

class RowInfluenceCheck(evaluator, min_net_harm=1, row_ids=None)[source]

Flags rows whose removal fixes more cases than it breaks.

Parameters:
run(ctx)[source]

Flag rows whose removal fixes more cases than it breaks.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class RegressionCheck(evaluator, baseline, objective=None)[source]

Judge a candidate against a baseline using fixed labeled cases.

Parameters:
run(ctx)[source]

Compare the candidate with the baseline and enforce the objective.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class CoverageCheck(traffic, embedder, min_similarity=0.3, max_uncovered_frac=0.1, scopes=None)[source]

Empty neighborhoods: traffic queries whose nearest store example is far.

Coverage is measured against traffic, the way code coverage is measured against execution, so it needs a sample of production inputs (unlabeled is fine). Reports the fraction uncovered overall and per scope.

Parameters:
  • traffic (Sequence[str])

  • embedder (Embedder)

  • min_similarity (float)

  • max_uncovered_frac (float)

  • scopes (Sequence[str | None] | None)

run(ctx)[source]

Measure traffic queries lacking a close example in their scope.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class DeadRowCheck(evaluator, traffic=())[source]

Rows never retrieved for any eval case or traffic query.

Parameters:
run(ctx)[source]

Find rows absent from evaluation and traffic retrieval results.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]

class DecisionLayerCheck(evaluator, baseline_run=None)[source]

Cases where the evidence was right and the decision was wrong.

This is a triage heuristic: a majority of gold-labeled examples does not establish evidence quality or isolate the cause of an error.

Parameters:
run(ctx)[source]

Flag prediction errors despite majority-gold retrieved labels.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Raises:

ValueError – If the supplied baseline run belongs to another store.

Return type:

list[Finding]

checks.meta

Meta tier: mutation testing for the evaluator.

Perturb a copy of a store and compare the observed effect with a declared expectation. Default expectations are diagnostic hypotheses, not guarantees that a particular perturbation damages every classifier.

class Mutation(name, apply, expect)[source]

A store perturbation with a caller-specified expected signal.

Parameters:
flip_influential_label(store, evaluator)[source]

Relabel the most-retrieved row to a different label present in the store.

Parameters:
  • store (Store) – Example store to inspect.

  • evaluator (Evaluator) – Configured retrieval and decision evaluator.

Returns:

A new store with one influential label changed, or the original if inapplicable.

Return type:

Store

inject_redundancy(store, evaluator, copies=5)[source]

Duplicate the most-retrieved row several times (crowds context).

Parameters:
  • store (Store) – Example store to inspect.

  • evaluator (Evaluator) – Configured retrieval and decision evaluator.

  • copies (int) – Number of redundant copies to inject.

Returns:

A store with copies of the most-retrieved row, or the original if empty.

Return type:

Store

remove_label_region(store, evaluator)[source]

Drop every example of the most common label (an uncovered region).

Parameters:
  • store (Store) – Example store to inspect.

  • evaluator (Evaluator) – Configured retrieval and decision evaluator.

Returns:

A store without examples of its most frequent label.

Return type:

Store

shuffle_labels(store, evaluator, seed=0)[source]

Permute store labels using a reproducible random seed.

Parameters:
  • store (Store) – Example store to inspect.

  • evaluator (Evaluator) – Configured retrieval and decision evaluator.

  • seed (int) – Seed for reproducible pseudorandom sampling.

Returns:

Permute store labels using a reproducible random seed.

Return type:

Store

class MutationCheck(evaluator, mutations=[Mutation(name='flip_influential_label', apply=<function flip_influential_label>, expect='degrade'), Mutation(name='inject_redundancy', apply=<function inject_redundancy>, expect='change'), Mutation(name='remove_label_region', apply=<function remove_label_region>, expect='degrade'), Mutation(name='shuffle_labels', apply=<function shuffle_labels>, expect='degrade')], min_transitions=1)[source]

Each mutation must produce the expected signal in the Comparison.

Parameters:
run(ctx)[source]

Compare each store mutation with its declared expected signal.

Parameters:

ctx (CheckContext) – Store and optional taxonomy and embedder for this check.

Returns:

Findings with affected identifiers and diagnostic values.

Return type:

list[Finding]