Skip to main content

keble-data-infra-contract

The pyproject.toml version is authoritative. The release owner assigns the next available release number before the immutable wheel is built. The distribution is built and consumed locally from the workspace, not PyPI.

This package is the provider-neutral search contract shared by provider packages, keble-data-infra-api, and Data Platform. It owns canonical entity identities, one kind-specific query per entity kind plus the result envelope, searcher capabilities and Protocols, raw-response evidence, typed failures and errors, and the retained source-material read authorities. It is framework-free: no FastAPI, database, HTTP client, provider SDK, Platform, resolver, or Idea dependency. Provider packages own implementations and native DTOs; the Data Infra API owns persistence, routing, and spend.

Modules

Module Owns
entities.py Provider-neutral identities and entity contracts: SourceSubject, ObjectKind, Channel, ExternalIdentity, Provenance, MetricObservation, Product, Store, Creator, Content, Comment, Keyword, Contact, PlatformDefinedCategory, MediaRef, relationships, and placements.
queries.py One query per kind (ProductQuery ... ContactQuery, PlatformDefinedCategoryQuery) over shared QueryBase controls (ids, ANDed atomic clauses, bounded any_of groups, paging, cache mode), plus Entities[T], PageInfo, RankingWindow, and SearchTicket.
searchers.py Caller-owned SearcherCapability/RegisteredCapability, per-input PublicationWindowSupport declarations and publication_window_of, the seven searcher Protocols (PlatformDefinedCategorySearcher, ProductSearcher ... ContactSearcher) that provider packages implement, and their shared RegisteredSearcher union.
canonical.py The single canonicalizer per identity and term fact (terminology, handles, URLs, ASINs, domains, and Amazon seller Stores) used by Data Infra guards, providers, and Data Platform labels.
seams.py The shared session seam: DataInfraSession, MediaEnrichmentProtocol, WebhookProtocol (register, list, unregister), SourceBytesProtocol (including the RevisionListingOrder clock selector), notification/ack envelopes, the registration selector and its removal receipt, retained refs and change records.
content_ref.py The content-addressed byte-reference vocabulary — StoreOwner, Sha256Hex, ObjectKey and ContentRef — owned below both entities.py and seams.py, which re-export it, so MediaRef.capture needs no import cycle.
pacing.py The read-only pacing snapshot Data Platform relays to the admin Data section: PacingAccountStatus (configured numbers, signed finite bucket level, unsigned month usage and supplier hold) and its timestamped PacingReport. Only level accepts debt, within ±99999999999999999999999999.999999999999 (38 digits / 12 decimals). DI has no console.
subjects.py canonical_subject (the one text-to-identity entry) and the non-raising persisted-subject decoders decode_source_subject / decode_change_subject.
changes.py CONTRACT_CHANGES: the 0.53 stored-shape change list the DI store migration reads (temporary; deleted at the next contract release).
plugins.py Provider-owned ProviderPlugin bundles, account-scoped ProviderRow declarations with their PacingDeclaration supplier facts (including the shared supplier limit), typed environment options/values, and PageWeight.
plugin_kit.py Provider-free declaration/read-mask checks, PluginCase and one frozen PluginViolation vocabulary; no pytest dependency.
testing/census.py Field-census vocabulary (FieldCensusRow, FieldDisposition, NotKeptReason) and the unclassified_paths / dangling_destinations walkers.
failures.py The sanitized DataInfraFailure payload plus origin, payment-evidence, disposition, and operator-action enums.
errors.py Typed API-boundary errors (DataInfraError, DataInfraFailureError, duplicate/unsupported/provider/request/idempotency rejections) and failure_from_contract_error.
evidence.py Durable source evidence: SourceArtifactRef, SourceShareabilityEvidence, SourceResultEvidence, retention/rights/consumption enums, and bundle validation.
retry.py parse_retry_after, the single parser for HTTP Retry-After hints.
models/base.py ContractModel (frozen, extra=forbid, snake-case fields with camel-case wire aliases), bounded scalar aliases, and public-envelope measurement.
models/identity.py ProviderId, the open provider identity used by plugin rows and internal discovery errors.
models/video_enrichment.py Video Enrichment notification and projection contracts; a consumer-owned query projection, never a second source of truth.
protocols/failure_adapter.py ProviderFailureAdapterProtocol, the provider-owned native-failure adapter seam.
protocols/page_sources.py The provider-neutral public page-source seam: PageSourceProtocol[PayloadT], PageKind, PageAddress, PageReadHandle, PageReadOutcome, and PageRead[PayloadT] (one outcome validator).
protocols/source_artifact.py The provider-owned exact raw-response durability boundary (capture protocol, attempts, contexts, recovered responses) and the pure RawResponseRemapProtocol.
source_material/artifact_read.py SourceArtifactExactReadRequest, the authority for one exact retained source-artifact read.
source_material/media_read.py The provider-neutral authority contracts for one exact retained source-media read.
source_material/image_processing_authority.py The authority to process one already-retained standalone source image.
source_sync/main.py Retained source change vocabulary: SourceChangeGroup and build_source_object_key.

keble_data_infra_contract/__init__.py is the package facade and re-exports the public surface; import public names from the package root.

Amazon seller-Store identity (0.80.0)

The canonical contract owns the existing Amazon seller Store key: amzstore1:<market-length>:<native-market>:<seller-id-length>:<seller-id>. Its market token stays Amazon-native (UK, not GB), and identity uses the seller ID, never a display name. parse_amazon_store_external_id returns that market and seller ID as AmazonStoreScope; Store.external_id remains opaque outside the Amazon provider edge. canonical.try_build_amazon_store_external_id is the non-raising twin (same bytes, None for an input the builder refuses), which DI's scraper Amazon product mapper uses to turn a parsed Buy Box seller= id into Product.store_ref plus SOLD_BY, matching keble-amz's Keepa key. This is an identity-codec move only: no entity schema or serialized value changes.

History listing and sealed part size (0.79.0)

A consumer that pulls retained material (DP) can now list the history-chunk revisions on the existing listing, and producers write smaller sealed parts.

  • list_revisions(metric_history=True, ...) (wire body field metricHistory) selects the history family: each listed revision's subject is a MetricHistoryKey and its body is one MetricHistoryChunk. Exactly one of kind, relation_kind and metric_history=True selects a family. RETAINED_AT (optional channel, cursor bound to the family) and OBSERVED_AT serve it; CHECKED_AT refuses it as INVALID_REQUEST. The default False keeps every existing request and page byte for byte; an older DI ignores the field, sees no family and refuses the request, so the lane idles.
  • OBSERVED_AT pages carry neither resume_cursor nor retained_through; next_cursor=None ends the pass, and resuming a cursor requires the same family selector, channel, since and until.
  • A newer revision of one MetricHistoryKey is not a superset of an older one (the 1,024-point re-split shrinks part 0 once); consumers keep each listed history revision and deduplicate by point (owner, metric, period, change, at), never by key.
  • H-1/H-3 add no model field; the 0.79.0 pins rotate for rows 23/43/82.
  • HISTORY_PART_POINTS = 1024 is the part size a producer writes; the read bound MAX_HISTORY_CHUNK_POINTS = 8192 is unchanged, so every stored part still validates. A re-fetch rewrites only the last part (at most 1,024 points); sealed parts re-fetch Unchanged. MetricHistoryKey identity is unchanged.

Checked-at confirmation lane (0.78.0)

A consumer that pulls retained material (DP) also needs the confirming checks that advance an unchanged subject's "last checked" clock. The existing listing now serves them, pulled by cursor, with no new collection or request parameter.

  • order=RevisionListingOrder.CHECKED_AT with an entity kind (optional channel) lists the entity subject heads whose latest check is later than the capture of the material revision they hold, ordered (head check time, subject head key). Each listed key is that material revision; page.observations carries one SourceObservation per key, aligned 1:1. Latest wins: a head re-checked after the cursor reappears later.
  • Rounds mirror RETAINED_AT: since iff cursor is None; next_cursor continues a round under DI's clamped horizon, and the page that closes it carries resume_cursor and retained_through.
  • relation_kind, history heads and exact subjects are not served by this lane: they are typed INVALID_REQUEST refusals. An older DI refuses the unknown order the same way, so the consumer's lane idles.

Opt-in revision records (0.77.0)

This change is additive: the existing keys-only listing may now also carry the revisions it just read, so a consumer stops re-reading every listed key through get_revision.

  • RevisionPage.revisions (revisions) is the optional record list. Unset means the caller asked for keys only, and the field is then omitted from the wire, so every existing listing keeps its exact earlier JSON bytes. When requested, it holds one RevisionRef per listed key, in revision_keys order, bounded at 500; a requested page that found nothing states [], which is a real answer rather than the absent field. The model owner refuses a record set that is missing, extra, reordered or foreign to the listed keys, so one page can never publish two disagreeing halves.
  • SourceBytesProtocol.list_revisions gains the keyword-only include_revisions parameter, defaulting to False. The default keeps today's keys-only page byte for byte, so no existing reader repins merely because the records exist. True requires limit at most 500; DI answers an oversized request as a typed INVALID_REQUEST refusal before it reads, never as a silently truncated page.
  • A consumer that asks for records uses them instead of per-key GETs. A consumer that asked for records and does not receive them (an older server, or a page produced without them) falls back to get_revision for the keys it needs: absence means "not carried", never a missing-data refusal and never permission to skip listed revisions.

Source-declared market need (0.76.0)

SearcherCapability.market_required_inputs names the query inputs whose routes the source refuses without a market (for example text on a region-scoped live search). Per input, like publication_window; empty means no input needs one, and the field is then omitted from the wire. It discloses, it does not enforce: the source's own validate_query keeps the refusal. Data Platform derives CatalogCell.requires_market from it. Additive only.

Creator listing page kinds (0.73.0)

PageKind.YOUTUBE_CHANNEL_VIDEOS and PageKind.INSTAGRAM_PROFILE_POSTS name one creator's own content listing, read page by page through the plugin's own continuation. ContentQuery.creator_refs selects them; Data Infra pages each creator to its list end. Additive only.

Media skip reason (0.72.1)

MediaSkipReason.NOT_DECLARED is the typed DataInfraFailure.upstream_code of Data Infra's $0 enrichment refusal when no media rule declares how a subject's video is enriched. It rides the existing expected media refusal (INVALID_REQUEST + PERMANENT + NONE), so a caller closes it as its existing skipped outcome and counts it apart from "not a video" by code.

ASR transcript versions (0.72.0)

This minor is additive: a stored transcript can now name which declared ASR version produced it, so every model's transcript is kept rather than replaced, and switching back to a model never re-transcribes a video it already covered.

  • AsrVersionKey is the one label vocabulary (asr.azure-whisper.v1, asr.azure-gpt-4o-mini-transcribe.v1). The pattern refuses a deployment name such as whisper or a catalog key, because a version is a declared identity and must never be re-derived from a routing key. The ASR service mints the labels and owns what each one means; this contract carries and compares them.
  • SocialTextTrack.asr_version and VideoTranscript.asr_version name the run that produced that transcript. None means a source-provided transcript or a track captured before 0.72.0 — never a guessed version. A later model's transcript is stored beside the earlier one; a silent video still records the version that ran and found no speech (text="").
  • SocialTextTrack.enrichment_owned is the single, computed ownership rule: TRANSCRIPT plus a Result id in provenance.artifact_ids. It is a property, not a field, so there is no second copy to drift; Data Infra's is_enrichment_transcript and Data Platform's selected_track read it.
  • MediaEnrichmentRequest.asr_versions carries the purchase pair only: [0] is bought, [1] is the receiver's capacity fallback, at most two. The choices are declared by the requester, so a service-local default can no longer decide which model runs. The pair is part of the request body, so two different pairs are two different requests, never one replay.
  • Every added value is omitted while absent, so a legacy body re-dumps its exact bytes and digest. Readers repin to 0.72.0 before a producer stamps a version, because ContractModel is extra="forbid".

Retained revision delivery lane (0.71.0)

This minor is additive: a listing may now walk DI's own append clock instead of the payload's observation clock, and the page that ends a delivery round says where the next round starts.

  • RevisionListingOrder names the clock. OBSERVED_AT is today's lane: the payload observed_at, ordered (observed_at, revision_key), with since required whether or not a cursor is sent. RETAINED_AT is the provider-neutral DELIVERY lane: DI's own append clock, ordered (retained_at, revision_key) inside one channel only, for a consumer that must receive every retained revision once regardless of what the payload says. There is no cross-channel order promise.
  • SourceBytesProtocol.list_revisions gains the keyword-only order parameter, defaulting to OBSERVED_AT, and since becomes optional at the type level. Each lane states its own requirement as a refusal instead of a silent reinterpretation: OBSERVED_AT refuses a request without since; RETAINED_AT requires relation_kind and since iff cursor is None, and refuses an entity kind, a non-empty subjects, a channel filter, since together with a cursor, and a cursor minted for another kind or version.
  • RevisionPage.resume_cursor is the opaque cursor that opens the next delivery round once the current one has no unwalked position left, and RevisionPage.retained_through is the exclusive upper retained-time bound that round covered, for operator evidence. The consumer treats the cursor as opaque and never derives a bound from the timestamp.
  • Both page fields are omitted while None, so an OBSERVED_AT page keeps its exact 0.70.0 JSON key set. Readers repin to 0.71.0 before a caller sends order=RETAINED_AT, because ContractModel is extra="forbid".

Relations-only nudge registrations (0.70.0)

This minor is additive: a registration may now say which RelationKinds it wants instead of which entity subjects, and it can be retired.

  • WebhookRegistration.relation_kinds (relationKinds) is the optional relations-only selector. Unset keeps today's subject matching exactly, and it is omitted from the wire while unset, so every stored registration and every pre-0.70 producer body keeps its exact bytes. A non-empty list matches only RELATIONSHIP revisions of those kinds — never entity or history revisions — and requires an empty subjects selector, because one list cannot mean both. An empty list is refused instead of storing a registration that can never fire.
  • UnregisterRegistration and RegistrationRemoval are the operator brake: the request names one registration_key, and the receipt answers removed (false for an idempotent rerun on an absent key) plus removed_claims, the PENDING and LEASED claims deleted with it. SETTLED and DEAD_LETTERED claims stay as history; nothing is lost because retained revisions remain, so a pull, a backfill or replay_retained_revisions.py can re-offer them.
  • WebhookProtocol.unregister declares the new member beside register and list_registrations.

Readers must repin to 0.70.0 before an operator sends relationKinds, because ContractModel is extra="forbid".

Store media (0.69.0)

This minor is additive: Store.media carries a store's own brand imagery (logo or icon, og image, seller cover) as MediaRef items under the existing shared entity media cap of 256, the same shape Product, Creator and Content already carry. It defaults to empty but is not omitted while empty, so a pre-0.69 Store body re-dumps with "media":[] and its canonical revision digest rotates on the next write. Readers repin to 0.69.0 or later before any emitter sets the field, because pre-0.69 strict parsers reject the unknown key.

Durable media references (0.67.0)

This minor is additive: MediaRef.expires_at records the instant a signed media URL is known dead and MediaRef.capture carries DI's stored copy of the bytes as a ContentRef. Both are omitted while None, so a body that states neither keeps every pre-0.67 canonical byte, revision digest and MEDIA group digest. Ownership is split by capability: a provider plugin states expires_at from the URL's own parameters and never sets capture, which only DI attaches after it has stored the bytes; DI refuses a plugin body that sets capture with a typed failure. expires_at is a canonical UTC instant, so an equivalent offset spelling cannot create a second identity. There is no media state enum in the contract: EXPIRED and FAILED stay in the DI capture ledger, and capture holds only a STORED copy. Readers repin before any emitter sets either field, because pre-0.67 strict parsers reject the unknown keys.

Partial collection reads (0.66.0)

This minor is additive: Provenance.partial_fields names valued collections that the observation carries only part of (for example, five of twelve variants). A nonempty marker requires an explicit read_fields mask and must be disjoint from it: read_fields still means completely read. The marker serializes as sorted partialFields and is omitted when empty, including explicitly empty sets, so unmarked 0.65 payload bytes and digest preimages stay unchanged. A partial collection is still FieldState.VALUE; writers fill an empty slot from it, never replace a stored value. There is no fourth state or item-by-item union.

Public collection_fields(entity_type) derives and caches eligible tuple/list attributes from the entity model, excluding identity/observation metadata and metrics. The shared read_mask_violations classifier accepts a valued marked collection without VALUE_NOT_READ, reports scalar, empty-list and metrics markers as PARTIAL_NOT_VALUED_COLLECTION, and checks partial names against declared fills. check_plugin additionally re-validates every case entity's Provenance (including related entities) to catch model_copy bypasses and reports UNMARKED_AT_CAP for a complete collection exactly at its model-declared bound. The cap check is package CI only, never a DI runtime diagnostic.

Adopt in order (i): DPC/DP repin to 0.66 readers first; DI emits last, after all DP tasks converge. A 0.65 strict parser rejects the additive key only when nonempty; an empty marker emits no new key and retains the previous bytes. Rollback DI before downgrading DP readers. This package unit changes no DI API, storage, serving shape or architecture mirror.

Exact-seed physical-call bounds (0.65.0)

SeedCallBound(selector, subject_kind, calls_per_subject_page, max_pages) is a plugin-owned finite upper bound on native physical requests, not actual usage or a token/dollar price. SearcherCapability.seed_call_bounds is omitted when empty; unknown bounds never mean free acquisition. QueryBase.max_source_calls optionally carries the physical-attempt allowance; zero forbids new supplier I/O and omission preserves legacy requests. DI's existing capture owner enforces it across retries and failover. Entities.physical_attempt_count carries only a complete DI-owned total, including failed candidates; None is unknown and omitted, never fake zero.

Store.name can be None for an identity-only Store, with unread profile coverage reported through the existing FieldState/Provenance.read_fields. Blank strings are rejected; identity, observation and provenance remain required. Consumers must install the nullable-name reader before identity-only production is enabled. Shared supplier limits from 0.64.0 remain unchanged.

Nudge-only confirming observations (0.63.0)

SourceObservation travels beside the unchanged ChangeSummary in the existing canonical nudge array. A changed confirming read bundles [change, observation]; an equal-material confirming read sends [observation] for the existing revision. head_observed_at is the genuine capture instant, paired with this read's masks. Provenance.source_changed_at is optional supplier-owned evidence, never a capture fallback; unknown provenance facts are omitted to preserve old bytes. Neither cache reads nor retained replay creates a check. Search, FOUND and StepResult shapes are unchanged.

Companion entity facts

Entities[T].related_entities carries up to 1,000 independently identified, directly anchored companion entities; the retention and routing invariant is owned by Data Infra's arch/record/20261010_related_entities_retention.md. CONTACT_EMAIL_MAX_LENGTH (1,024) is the one public bound for Contact.email, and every ContractModel derives input-free rendered errors, so a refused provider value never reappears in the exception text DI forwards to its failure boundary (CO-607 F1).

Provider field states and freshness scope (next minor)

entities.py owns the one field-state vocabulary: FieldState.VALUE, ABSENT (read and genuinely empty), and NOT_READ. has_value treats None, blank text, empty collections and declared not-read sentinels as no value, while zero and False remain values. Its one private sentinel table holds only ContentSponsorship.UNKNOWN: the platform said nothing (CO-862ir-e-2 b; A21-F1). Plain "UNKNOWN" text and other enums' same-spelled members remain values. field_state(read_fields=..., field=..., value=...) returns VALUE for a real value; otherwise only membership in an explicit mask yields ABSENT. A legacy None mask without a value is always NOT_READ, never evidence of known emptiness. From DIC 0.59.0 every provider reports a request-scoped mask: an option switched off must not claim the fields that option reads.

FreshnessPolicy.fields and .metrics optionally declare what must be fresh. DI evaluates each requested attribute/metric across provider heads; DIC only carries the ask. None keeps whole-record freshness and is omitted from all dumps, preserving pre-0.59 policy/query bytes. Explicit scopes serialize sorted. For example, fields=frozenset({"title", "store_ref"}) asks for fresh evidence of both attributes, not merely a recent record with an unread seller.

RegisteredSearcher now lives in DIC searchers.py, allowing provider-owned registration rows without importing the DI application. DI may re-export that union for its existing callers during the composition migration.

Provider plugins (next minor)

Each provider package exports plugin() -> ProviderPlugin. The bundle has options and rows(values) only; it has no provider, evidence or heavy-bound field. Each row owns its provider, channel, requires, searcher builder, failure adapter, pacing declaration, page weight, remappers and source-evidence requirement. Row identity is (provider, channel, pacing.account_key): several providers may share a package, and an account pool returns one row per account. DI alone owns cross-provider route order and activation. AccountKey retains DI's uppercase pacing-key grammar, including dynamic keys.

HEAVY rows share DI's one process-wide heavy page bound (HEAVY_PAGE_CONCURRENCY in DI); a plugin declares no bound of its own, because deferred cache, cursor and snapshot reads know only the weight (A24-3).

Pacing declarations (0.60.0, A24)

ProviderRow.pacing: PacingDeclaration | None carries the supplier facts the package owns; None is an unpaced row. DI builds its pacing account as the declaration plus its operator knob overrides DI_PACING_<A>_<FIELD> (refill, burst, scheduled share, hold), keyed by template_account or account_key.

Field Meaning
account_key, unit The bucket and its capacity dimension.
unit_cost_per_id (default 1), list_read_unit_cost, board_read_unit_cost, surcharge_per_id (default 0) Prices for routing's work facts: per id, one bounded list read, one cold board read, and the per-id surcharge on exact-id product work. The package derives the surcharge from its own option, so an account that did not opt in prices 0.
debt_policy, debt_evidence PacingDebtPolicy.ONE_BURST requires a cited PacingEvidence(source_url, statement), and evidence without debt is refused. Core checks no account name; a DI override may lower the policy, never raise it.
monthly_quota, monthly_scheduled_cap The supplier's total meter and the scheduled allowance; the cap never exceeds the quota.
template_account Set on a pool member: the account whose knob overrides apply. It never repeats account_key.
default_knobs PacingKnobs, the package's recommended knob defaults (DI's defaults when omitted).
shared_limit PacingSharedLimit(limit_key, refill_per_minute, burst): one supplier limit several accounts share, declared once by every member. Both numbers size one shared bucket counted in the member's unit; both None shares 429 holds only. limit_key names neither the member nor its template, and a shared member keeps NO_DEBT. DI owns the effective values (DI_PACING_<limit_key>_{BURST,REFILL_PER_MINUTE}) and the startup consistency checks.

Several rows may declare one account (one supplier behind several packages); DI requires those declarations to be equal at startup. A pooled package returns one row per parsed account:

PacingDeclaration(
    account_key=f"POOL_{account.label}",
    unit=UpstreamCapacityDimension.REQUEST,
    monthly_quota=account.quota,
    monthly_scheduled_cap=account.quota,
    template_account="POOL",
    default_knobs=PacingKnobs(refill_per_minute=Decimal(60), burst=Decimal(200)),
)

ProviderOption(env=EnvName("API_TOKEN"), secret=True) declares a name, never a value; it has no required flag. Only a row's requires gates that row. DI passes ProviderOptionValues(secrets={EnvName("API_TOKEN"): SecretStr("test")}, values={}) to the package, which parses its own values. Plugins may share an env name; DI must reject conflicting secret flags across plugins at startup.

Package tests replay their own mapper fixtures (including options-off cases):

violations = check_plugin(plugin=plugin(), values=test_values, cases=((case, page),))
assert violations == ()

PluginCase names a provider/channel row, its query and expected_not_read. The kit builds rows/searchers with its private no-op usage recorder but never executes a search. Packages stub any construction I/O. Every entity, related ones included, is checked against the union of that row's capability fills. Valued attributes must be read; read attributes must be declared. Identity/observation metadata are not attributes and confer no exemption to names in the mask. An unreported mask is UNREPORTED, never evidence of ABSENT. read_mask_violations is the same pure classifier DI coverage uses; plugin_declaration_violations is the pure startup check for undeclared requirements and duplicate account-scoped rows.

ProviderRawResponseCaptureProtocol.aread_exact_response(operation=..., occurrence=..., expected=...) reads and verifies retained exact bytes or returns DataInfraFailure. It creates no attempt and emits no usage. It reuses the existing physical-identity, occurrence and recovered-response types; packages rebuild their own envelopes. No codec Protocol is needed. Implementations and test doubles must add this new member without changing any existing capture signature.

0.62.0 minor cut (local build, unpublished)

Additive on 0.61.0: no existing payload field or serialized value changes. The new capability map is omitted when empty, and Content.market is omitted when None; literal 0.61.0 capability, registration and content dumps retain byte-identical output without caller-side exclusions.

  • searchers.py: PublicationWindowSupport has NATIVE (exact source filter), COARSE (covering source window then exact local trim), AFTER_FETCH (buy first, trim locally) and NONE (no bound). COARSE's A4 law is: "never refuses a lower bound; past the widest native window sends all-time and filters exactly". There is no provider max-lookback field, wrapper model or clamp helper.
  • SearcherCapability.publication_window maps the existing RequiredInput vocabulary directly to the support enum. publication_window_of(capability, query) reuses prerequisite detection across AND/OR clauses. The weakest used input wins (NATIVE > COARSE > AFTER_FETCH > NONE). Any undeclared used input, no input, or a kind mismatch resolves to NONE. There is no provider-specific selector precedence: ids NONE plus text COARSE is NONE; sort is a used input too. The helper never changes a publication bound.
  • capability_refusal refuses ContentQuery.published_after/before when a nonempty, opted-in map resolves to NONE. Empty legacy maps keep provider validation unchanged while making no new support promise. This preserves staged adoption: DP never adds a policy bound for an undeclared searcher.
  • entities.py: optional Content.market reuses Market (observed ISO 3166-1 alpha-2; UK canonicalizes to GB). It is only a source-stated post country, never the requested market, an inferred country or a creator inheritance.
  • Both new public names (support enum and lookup helper) are facade exports.
  • Reader-first adoption: new non-default fields still require 0.62 readers (extra=forbid). Deploy DP and its backend readers before DI/plugins emit declarations or observed content markets. This unit does not change DI core, plugin declarations, mappings or DP policy compilation. In DI P5 a plugin may declare COARSE only in the same release that implements A4. In particular, TikTok keyword bounds older than 180 days must send all-time (0) and trim exactly, not clamp or refuse. That plugin patch is outside this library unit.
  • Offline tests prove both 365-day and three-year COARSE bounds remain accepted and unchanged through the shared feasibility check and query serialization.
from keble_data_infra_contract import ObjectKind, PublicationWindowSupport, SearcherCapability

capability = SearcherCapability(
    kind=ObjectKind.CONTENT,
    publication_window={"text": PublicationWindowSupport.COARSE},
)

0.61.0 minor cut (unreleased)

Candidate wheel: 0.61.0; the release owner assigns the version at the tag. Wire value change for video-enrichment lifecycle timestamps (CO-TZ-1-a).

  • models/video_enrichment.py: every lifecycle timestamp is CanonicalUtcDatetime instead of BoundedAwareDatetime, so an equivalent offset is normalized to the canonical UTC instant instead of being rejected. Fields: VideoEnrichmentAssetRef.fetched_at/expires_at, SourceMediaEnrichmentSubmitRequestV2.requested_at (and its build parameter), SourceMediaEnrichmentAdmissionRequestV2.requested_at, VideoEnrichmentJobAnalysisOperationAttempt.recorded_at, VideoEnrichmentJob.created_at/started_at/finished_at/updated_at, StreamCompletionEvent.occurred_at, VideoEnrichmentProjection.source_completed_at/ingested_at, VideoEnrichmentIngestionRecord.received_at/completed_at, ResultArtifactRef.created_at/expires_at, and VideoEnrichmentResult.started_at/finished_at.
  • Wire value change: those fields serialize as UTC Z; a producer that sent 2026-10-18T12:00:00+08:00 is read and returned as 2026-10-18T04:00:00Z for the same instant. A +08:00 input is still accepted and normalized, a Z value round-trips unchanged, and a naive timestamp is still rejected.
  • The three per-field UTC validators (recorded_at, occurred_at, and the Result started_at/finished_at) are deleted; they rejected exactly what the canonical type now normalizes.
  • Compatibility and pin order: no repin order is required. KVE keeps contract 0.49.0 and is outside this wave. The wire reads in both directions: a 0.61.0 producer emits the canonical Z value from either a +08:00 or a Z input, and Data Platform's five video-enrichment read models (VideoEnrichmentResult, VideoEnrichmentJob, StreamCompletionEvent, VideoEnrichmentProjection, VideoEnrichmentIngestionRecord) parse all 10 emitted samples (five models, each emitted from a +08:00 and a Z input) under 0.58.0 in Data Platform 0.68.2's environment, and under 0.60.0; evidence is wirecompat/emit_061.py with wirecompat/parse_old.py under tmp/contract-wave/dic-0610/. A 0.61.0 consumer likewise reads every older producer's value, because CanonicalUtcDatetime is BoundedAwareDatetime plus a normalizing AfterValidator (models/base.py:438-452): an offset or a Z input still validates and is returned as the same UTC instant.
  • protocols/source_artifact.py: ProviderRecoveredRawResponse.object_key: str | None is additive (provider-fields A31). It echoes the original artifact's content-addressed key when the reader knows it, so a provider package rebuilds its own exact receipt through the generic exact read instead of re-reading an occurrence it cannot see. The default is None and an absent key is omitted from the dump, so a 0.60.0 producer's envelope keeps its exact pre-0.61 bytes. Recovery never infers the key from the bytes: the storage-owned prefix is not derivable from the digest. Data Infra fills it from the occurrence the bytes came from; the retained Keepa delegate keeps its own occurrence lookup until its separate deletion unit.

0.58.0 minor cut (in progress)

Candidate wheel: 0.58.0.dev2; the release owner assigns final 0.58.0 after review. This cut narrows capability declarations and pre-I/O feasibility checks.

  • searchers.py: exported BROAD_TEXT_FIELD = "text" is the one broad-text capability key. SEARCH/PHRASE keys must be this constant or a TextField; legacy clauses/keyword declarations are rejected at construction.
  • SearcherCapability.requires is frozenset[RequiredInput], a closed any-of vocabulary: a nonempty declaration needs at least one input present. Empty means no prerequisite. Explicit ids=() is present (an intentional empty selection); other selectors must be nonempty and unavailable per-kind selectors are absent. text means a broad TextClause, category a CategoryClause (including in OR groups), and sort a supplied Sort.
  • capability_refusal keeps existing refusal precedence, then checks text operators, metric/instant sorts, filter metrics, price operators, brand and category support, OR support and required inputs across AND and OR atoms. Refusals retain the typed field and zero attempts. fields is not a general allow-list; the existing date/finder rules and instant-sort check still read it.
  • Providers rename invalid text keys and correct declarations before adopting the wheel, proving existing accepted-query cases are not newly refused. DI serving 0.58 capabilities goes live before any DP on 0.58. On rollback, roll DP back before DI; a 0.58 reader rejects legacy capability text aliases.

0.57.1 patch cut

Additive widening on 0.57.0 (CO-862gf-b): only PacingAccountStatus.level becomes signed at the existing Decimal representation bound, so real admission, measured and adopted debt reports without failure. Costs, refill, burst, share and month fields are unchanged. DI API consumes the 0.57.1 wheel; DP stays on 0.55.0 because it has no pacing code consumer.

0.57.0 minor cut

In progress; this section becomes the release note at the tag. Additive on 0.56.0; every pre-0.57 dump is byte-identical.

  • pacing.py (new): PacingAccountStatus and PacingReport, the read-only snapshot DI serves at its seam so Data Platform can relay DI's per-account pacing to the admin Data section. DI keeps no console.

0.56.0 minor cut

Additive on 0.55.0; every pre-0.56 dump is byte-identical.

  • queries.py: AcquisitionMode.PUBLIC_PAGE reads the public page through a page source; it is dumped (own cache and attempt keys) while LIVE stays omitted. snapshot_limit is now forbidden with every non-SNAPSHOT mode.
  • entities.py: Provenance.read_fields (the attributes one observation read; None = no coverage reported, omitted from the dump; a set dumps sorted). FieldName now lives here and is re-exported unchanged by queries.py. Entity observed_at means the source observation time (the provider's fetch or capture), never storage or download time.
  • protocols/page_sources.py: the page-source seam above. PageRead carries observed_at/payload iff FOUND/EMPTY and failure iff NOT_FOUND/FAILED. A new PageKind member ships only with its mapper. PageKind gains SHOPIFY_STORE_PRODUCTS (one store's product listing, keyed by domain), and PageAddress gains an opaque cursor for cursor-paged page types; it is omitted when None and refused unless page == 1.
  • queries.py: StoreDomainAlias and ProductQuery.store_domains (at most one alias per store_refs entry; omitted when empty). store_ref stays the identity; domain is a reference alias, never a key input. For STORE on SHOPIFY, market is the merchant country (StoreLeads f:cc).

0.55.0 minor cut

0.55.0 is additive on 0.54.0: no existing field or serialized value changed.

  • queries.py: AcquisitionMode (LIVE, SNAPSHOT); QueryBase.acquisition (default LIVE) and QueryBase.snapshot_limit, with one validator requiring the limit exactly for SNAPSHOT. SNAPSHOT is the explicit opt-in to buy a provider dataset slice; the row-cap policy is a DI Setting, not the contract. Both keys are omitted from a dump at their defaults, so a pre-0.55 LIVE query's bytes (and DI's cache key and continuation fingerprint) are unchanged; a SNAPSHOT query dumps both keys.
  • queries.py: the TextField vocabulary gains community (the post's community/subreddit name; matching follows the executing searcher's declared capability). ContentQuery.community still selects one exact community.
  • searchers.py: SearcherCapability.acquisition_modes (default {LIVE}) declares the acquisition paths a source supports; DI's shared capability_refusal reads it and refuses a query whose acquisition mode the searcher does not list, before reservation or provider I/O.

0.53.0 breaking cut (contract unification, P0-U2)

One contract change set for the DP/DI gap-closing program. Breaking for every provider that constructs Product.price, FOLLOWER_GROWTH or a SCORE-unit rating, and for DI api / DP code that uses the deleted scheduler family.

  • Canonical input (K-02/K-03): Market is ISO 3166-1 alpha-2, upper case, through canonicalize_market (UK decodes as GB; non-country values are refused). canonicalize_gtin gives GTIN-14 or None. canonical_subject (subjects.py) is the one text-to-identity entry; decode_source_subject / decode_change_subject decode persisted subjects without raising. is_external_id / EXTERNAL_ID_MAX_LENGTH own the external-id rule. amz1/amzkw1 key formats are frozen by golden tests. Stored Amazon keys keep their native marketplace token (amz1:2:UK:… stays UK; bare UK/GB inputs build the UK key, L-10); only the Market value is GB. A creator handle or profile URL becomes a subject only when the channel's id is that text (YouTube UC… id, TikTok numeric id); handle-to-id resolution is a provider/stored lookup (L-17). Sort.change orders by a change series (L-16); changes.count_value_or_none owns the COUNT value move (L-15).
  • Timestamps (K-04): Product.published_at (listed), released_at (maker release), first_tracked_at (provider tracking start); Store.published_at. An instant later than observed_at + 1 day is refused.
  • Neutral facts (K-05/K-06): Product.url/features/attributes; ProductVariant.ref/price/available; Content.language/mentioned_refs/ sponsorship (ContentSponsorship, default UNKNOWN); Creator.verified; Comment.author_ref; one LanguageTag alias.
  • Relations (K-07, K-37): BELONGS_TO_CATEGORY (PRODUCT -> PLATFORM_DEFINED_CATEGORY; RANK = rank in that category) and COMPETES_WITH (PRODUCT -> PRODUCT), both SAME_CHANNEL_AND_MARKET.
  • Quantities (K-08): one MetricUnit (+RATING, +DURATION_MS; RATIO is a fraction), CurrencyBasis (required exactly for MONEY), total METRIC_SPECS (unit + level bounds) replacing the partial unit table; new PRICE, LIST_PRICE, OFFER_COUNT, KEYWORD_INTERSECTIONS, AVG_SEARCH_POSITION. Deleted: Product.price (now a PRICE metric), MetricKind.FOLLOWER_GROWTH (now FOLLOWER_COUNT with change=True), and the "CPC requires market" rule (Money carries the currency). Stored bodies migrate in place per CONTRACT_CHANGES (DI step, P1).
  • History (K-09, D-40): MetricObservation.origin (ObservationOrigin) and change; full supplier histories as MetricHistoryChunk revisions keyed by MetricHistoryKey(owner, metric, period, change, part) (sealed blocks of 8,192 points) in Entities.histories; the payload/change/unchanged subject unions widen to include MetricHistoryKey.
  • Raw reference and remap (K-10/K-14): ContentRef.of_artifact; RawResponseRemapProtocol (pure bytes -> typed page).
  • Capability truth (K-11): SearcherCapability.max_page_size/max_values, capability_refusal; CategoryClause.op (IN/NOT_IN), ClauseOperator NOT_IN, DateClause, PriceClause.average_days; ProductQuery.one_variant_per_parent, buy_box_fulfilled_by_marketplace (finder filter only, never stored) and competitor_refs.
  • Actionable refusal field (L-90(2)): DataInfraFailure.field: str | None is the optional provider-neutral (DI-native) name of the one query field a refusal rejects; capability_refusal sets it. Consumers map it to their own public field name, and legacy failures omit it.
  • Census (K-12): testing/census.py.
  • Deleted (K-13): VideoEnrichmentOperation (use MediaOperation, now owned by models/video_enrichment.py), SourceMediaKind (use MediaKind), ModuleId, pull/push, HandlingReceipt (DI-internal; leaves the wire), and the scheduler family SyncPlanCommand, SyncPlanRef, PlanQuery, PlanRead, PlanPage, PlanSubject, ScheduleProtocol, DataInfraSession.schedule, RunQuery, RunRead, RunPage, RunStatus, RunState (DP's saved discoveries are the one clock, D-25). RunRef and RunRevisionRead stay.
  • Alert policy (K-15): is_alert_worthy.

0.52.0 minor cut

0.52.0 is additive on 0.51.0: no existing field or serialized value changed.

  • searchers.py: SearcherCapability gains markets: frozenset[Market] (default empty). Markets are source-owned (R61): each provider package copies the set from its own upstream region table in code, never from stored rows. An empty set means the searcher is market-agnostic. A call that needs a market and carries none stays a typed INVALID_REQUEST refusal naming market.

0.51.0 minor cut

0.51.0 is additive on 0.50.0: no existing field or serialized value changed, and every persisted pre-0.51.0 fact validates unchanged.

  • seams.py: UsageEvidence (the sanitized settlement fact carried in MediaResult.usage and HandlingReceipt.usage) gains quantity_unknown: bool = false. A real provider call whose billable quantity the producer could not measure (KVE USAGE_ONLY) is retained as an explicit unknown-spend fact: quantity_unknown=true with no unit_count / unit_quantity, so it can never become a measured zero or a free call. A known fact keeps exactly one quantity carrier and keeps its exact previous wire bytes, because the false (default) marker is excluded from serialization.

0.50.0 minor cut

0.50.0 is additive on 0.49.0: every change is an addition, and no existing field or enum member changed.

  • queries.py: Entities gains usage: tuple[UsageAccountingEvent, ...] (default (), max 256), the bounded per-query usage facts Data Infra returns to Data Platform on the service seam.
  • evidence.py: ProviderExecutionIdentity gains optional operation_id (1–256 chars) carrying the caller's X-Keble-Operation-Id for audit correlation without changing physical-attempt identity or fingerprints. The new optional field serializes as operationId null inside stored exact-response evidence, so the canonical-byte goldens were intentionally re-pinned in the same change.

0.49.0 minor cut

0.49.0 lands the discovery + motif contract work additively; every change below is an addition, and no existing field, enum member or serialized value changed.

New platform-defined categories (D1-DI):

  • entities.py: ObjectKind gains PLATFORM_DEFINED_CATEGORY (the sixth→seventh kind); new PlatformDefinedCategory entity with fields kind, channel, external_id, name (1–2048 chars), parent_ref: SourceSubject | None (must be a same-channel category, never itself), path: tuple[EntityLabel, ...] (max 64), market, metrics and observed_at/provenance; Entity adds the variant.
  • queries.py: new PlatformDefinedCategoryQuery (query_type PLATFORM_DEFINED_CATEGORY, parent_refs) with kind/channel reference validation; SearchQuery adds the variant.
  • searchers.py: new PlatformDefinedCategorySearcher Protocol (capability(), validate_query(), search()).
  • seams.py: DataInfraSession gains search_platform_defined_categories(q, actor).

Query bound (discovery P11):

  • queries.py: ContentQuery gains published_before (exclusive upper bound on the provider publish/create time) and the validate_published_window check requiring an ascending or open window; searchers that cannot honor a supplied bound must refuse in validate_query.

Frame retention (motif KVE seam):

  • seams.py: new FrameRetainRequest (result_ref: ContentRef, unique artifact_ids of 1–6 VideoIdentifiers), RetainedFrame (artifact_id, timestamp_ms, optional width/height, content: ContentRef), RetainedFrames (1–6 frames in request order) and the FrameRetainProtocol seam with retain_frames(...).
  • models/video_enrichment.py: new DerivedFrameReadFailureReason enum (UNAUTHORIZED, NOT_FOUND, AUTHORITY_MISMATCH, RETENTION_EXPIRED, CORRUPT, TEMPORARY_UNAVAILABLE) and DerivedFrameReadFailureV1 (reason, schema_version="1").

All new names are re-exported from the package facade.

0.48.2 patch cut

0.48.2 fixes FW5 additively. canonical.py adds try_build_amazon_keyword_external_id, a non-raising builder that returns the stored amzkw1 key or None when the market/term is not representable; build_amazon_keyword_external_id delegates to it and still raises ValueError. keble-amz uses the non-raising builder for its typed refusal and deletes its duplicated representability checks, so the contract is the single owner of that rule.

0.48.1 patch cut

0.48.1 fixes two review findings additively. canonical.py adds parse_amazon_product_external_id and parse_amazon_keyword_external_id, which return the decoded AmazonProductScope/AmazonKeywordScope or None for a value that is not a valid amz1/amzkw1 key; the existing raising decoders delegate to them and still raise ValueError. seams.py names the run lifecycle once as RunState next to RunStatus, and RunStatus.state references it; the serialized shape and the six wire codes are unchanged.

0.48.0 breaking cut

0.48.0 closes the W3 interface gaps. Every RelationKind declares an endpoint scope in RELATION_ENDPOINT_SCOPE: RANKED_FOR and VARIANT_OF require one channel and one market decoded from the endpoint identity codecs, SOLD_BY and PUBLISHED_BY require one channel, and FEATURES_PRODUCT and PROMOTES keep provider-supplied cross-channel facts. The amzkw1 market-scoped keyword key codec moves into canonical.py beside amz1, and the producerless MEMBER_OF_FAMILY kind is deleted. KeywordQuery gains an explicit DateWindow for trend reads, SearchPlacementType.AMAZON_RECOMMENDED becomes AMAZON_CHOICE, canonicalize_youtube_handle percent-decodes before dropping one @ and enforces the documented 30-character bound, Reddit communities enforce the 21-character bound, and the shared entity media cap rises to 256.

0.47.0 breaking cut

0.47.2 retains every returned relationship record by its own RelationSubject identity (relation kind + subject + object on one channel), lets SourceMaterialPayload.subject be an entity subject or a relationship identity, and adds the mutually exclusive relation_kind selector to SourceBytesProtocol.list_revisions (R72).

0.47.1 aligns SourceMaterialPayload with the target design (subject, body_ref, raw_ref, field_digests keyed by SourceChangeGroup, observed_at; no payload_kind/schema_version), filters list_revisions by kind, makes entities.StableKey the single owner and renames ProductStatus to ListingStatus.

0.47.0 deletes the legacy family layout and rebuilds the contract around one entity/query/searcher vocabulary. Deleted: the business_read, amazon_research, delivery, social, material_fingerprints, source_revision, source_retention, media_result_ready, providers, and schemas families, the old source_sync page/financial/admin modules, source_material/normalized_payload.py, and protocols/video_enrichment.py. There is no compatibility layer and no deprecated alias: consumers move to the modules above in the same release wave. Ledger A1-A22 records every deletion, rename, and replacement in the Keble workspace plan docs/plans/20260922_DI_DP_UNIFICATION_REWORK/02_DELETION_AND_RENAME_LEDGER.md.

Local checks

uv run pytest -q tests
npx --yes pyright .
uv build

Metadata

Release files for keble-data-infra-contract 0.80.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for keble-data-infra-contract 0.80.0
File Interpreter ABI Platform Actions
keble_data_infra_contract-0.80.0-py3-none-any.whl Python 3 none any Details for keble_data_infra_contract-0.80.0-py3-none-any.whl

Release files / keble_data_infra_contract-0.80.0-py3-none-any.whl

Download URL keble_data_infra_contract-0.80.0-py3-none-any.whl
Size 195.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bccc8dc6eca74f2982e2a751386d2f559cf007fd4f6dc90d9b86b57a72611785
BLAKE2b-256 checksum
How to use checksums
9a37299dbc77d784bca724434b99b9c5a512a33bbca9c4c23fde9663718df2b7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.10.9 {"installer":{"name":"uv","version":"0.10.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for keble-data-infra-contract 0.80.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page