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:
- created_at¶
Creation time, or None if unknown; naive times mean UTC.
- Type:
datetime.datetime | 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]
- class StoreDiff(added, removed, changed)[source]¶
Added, removed, and edited rows between two stores.
- property touched_ids: frozenset[str]¶
Return identifiers added, removed, or edited.
- Returns:
identifiers added, removed, or edited.
- class Store(rows=(), name='store')[source]¶
An immutable, content-addressed collection of Rows.
- property rows: tuple[Row, ...]¶
Return the stored rows in insertion order.
- Returns:
the stored rows in insertion order.
- property version: str¶
Content hash over all serialized row fields, independent of row order.
- Returns:
the content-derived version.
- edit(row_id, **changes)[source]¶
Return a new store with one row replaced, keeping its identifier.
- Parameters:
- Returns:
a new store with one row replaced, keeping its identifier.
- Raises:
ValueError – If inputs violate the documented constraints.
- Return type:
- 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:
- Returns:
Map the text batch to a matrix with one vector per text.
- Raises:
ValueError – If inputs violate the documented constraints.
- Return type:
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.
- class Taxonomy(labels, name='taxonomy')[source]¶
Named label definitions with content-derived versions.
- property active_ids: list[str]¶
Return identifiers of labels that are not deprecated.
- Returns:
identifiers of labels that are not deprecated.
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.
- class Retriever(*args, **kwargs)[source]¶
Interface for retrieving ordered evidence for a query.
- 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.
- 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
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 MajorityVoteDecider(fallback='unknown')[source]¶
kNN decision rule. Deterministic; useful for tests and as a floor.
- Parameters:
fallback (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:
- class EvalSet(cases, name='evalset')[source]¶
An ordered collection of uniquely identified evaluation cases.
- property slices: list[str]¶
Return the sorted slice names represented by evaluation cases.
- Returns:
the sorted slice names represented by evaluation 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:
- 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:
- assert_disjoint(other, *, group_key=None)[source]¶
Reject shared IDs, normalized text, or declared groups between sets.
- Parameters:
- Raises:
ValueError – If either set lacks a requested group or the sets overlap.
- Return type:
None
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:
- 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:
- 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()¶
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:
report¶
Findings and reports: the output of every check.
- class Finding(check, severity, message, row_ids=(), case_ids=(), data=<factory>)[source]¶
One diagnostic with affected rows, cases, and structured details.
- Parameters:
- class Report(findings=<factory>, context=<factory>)[source]¶
Collected findings and the state against which checks ran.
- extend(findings)[source]¶
Append findings to this report.
- Parameters:
findings (Iterable[Finding]) – Findings to append.
- Return type:
None
- passed(fail_on=Severity.ERROR)[source]¶
Return whether no finding meets or exceeds the failure threshold.
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.
- 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.
- 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:
- 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.
- 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.
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)
- 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:
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:
- Returns:
The same comparison artifact produced by the Python API.
- Raises:
ValueError – If settings are unknown, missing, or inconsistent.
- Return type:
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:
- Returns:
Run each check against the supplied store and collect findings.
- Return type:
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:
- 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.
- 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:
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.
- 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:
- 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:
- 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:
- 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.
- 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:
- 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:
- 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:
- 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.
- 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:
- 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:
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.
- class EvalRun(store_version, results)[source]¶
Predictions and evidence recorded against one store version.
- Parameters:
store_version (str)
results (list[CaseResult])
- property outcomes: list[tuple[Case, str]]¶
Return paired reference cases and predictions.
- Returns:
paired reference cases and predictions.
- class Transition(case, before, after, evidence_before, evidence_after)[source]¶
A case prediction before and after a store change.
- Parameters:
- class Comparison(baseline, candidate, context_changed, decider_calls, transitions=<factory>)[source]¶
Paired runs and prediction transitions caused by a store change.
- Parameters:
- 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.
- class Evaluator(retriever, decider, evalset)[source]¶
Runs an EvalSet against a Store through a Retriever and Decider.
- compare(baseline, candidate, baseline_run=None)[source]¶
Retrieval runs on both stores; the decider only where context differs.
- Parameters:
- Returns:
Paired results, transitions, context changes, and additional decider calls.
- Raises:
ValueError – If inputs violate the documented constraints.
- Return type:
- 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:
- class RowInfluence(row, comparison)[source]¶
Observed effect of removing one row from a fixed store.
- Parameters:
row (Row)
comparison (Comparison)
- 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.
- 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:
- Returns:
Row-removal comparisons sorted by decreasing net cases fixed.
- Raises:
ValueError – If the supplied baseline run belongs to another store.
- Return type:
- class RowInfluenceCheck(evaluator, min_net_harm=1, row_ids=None)[source]¶
Flags rows whose removal fixes more cases than it breaks.
- 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:
- class RegressionCheck(evaluator, baseline, objective=None)[source]¶
Judge a candidate against a baseline using fixed labeled cases.
- 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:
- 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:
- 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:
- class DeadRowCheck(evaluator, traffic=())[source]¶
Rows never retrieved for any eval case or traffic query.
- 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:
- 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.
- 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:
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.
- flip_influential_label(store, evaluator)[source]¶
Relabel the most-retrieved row to a different label present in the store.
- inject_redundancy(store, evaluator, copies=5)[source]¶
Duplicate the most-retrieved row several times (crowds context).
- remove_label_region(store, evaluator)[source]¶
Drop every example of the most common label (an uncovered region).
- shuffle_labels(store, evaluator, seed=0)[source]¶
Permute store labels using a reproducible random seed.
- 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.
- 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: