mostlyright.experimental
mostlyright.experimental — public-experimental, semver-exempt surfaces.
Everything re-exported here is EXPERIMENTAL: its API, semantics, and existence
may change in ANY minor release until it graduates. Pin your mostlyright
version if you depend on it.
The pattern mirrors pandas’ pandas.api.extensions namespace — a documented,
importable home for plugin surfaces that are stable enough to build on but not yet
frozen under the semver contract.
Current surface:
-
spine()— the BYO bridgespine(df, *, entity, decision_time, y)that lifts a user frame into the guarded (leakage-checked) world. -
align()— the composition verbalign(spine, *sources)(as-of join + leakage guard) that the domaintraining_table()verbs are built on. -
DeferredSource— the deferred-source builder for BYO leakage-safe joins (the escape hatch that composes user data throughalign()). -
contributor()— register a covariate contributor. A contributor is one functioncontribute(entity, window, grain) -> {key: {prefixed_col: value}}plus declared metadata (prefixnamespace,archive_class,injection_point, and thecolumnsit emits). Registered contributors compose intodataset()via thefeatures=[...]selector without any core change. The FIRST third-party registration emits anExperimentalFeatureWarning. The labels-only firewall is UNCONDITIONAL — a contributor can NEVER emit or override a label /obs_*/cli_*column.A third-party contributor MUST declare
columns=(its prefixed column set) so that acontribute()which RAISES or covers zero days still yields an all-NaN prefix block instead of silently dropping the columns. The returned mapping may be keyed by a plain local-standard-date string OR by the declaredkeytuple(entity, local_standard_date); both bucket to the local standard day.
Example:
from mostlyright.experimental import contributor
@contributor( "era5_ssrd", "ssrd_", "refetchable", injection_point="post_join", columns=("ssrd_mean",),)def era5_ssrd(entity, window, grain, *, tz_override=None): from_date, to_date = window # ... fetch + aggregate to one row per LST local standard day ... # keyed by the documented (station, local_standard_date) tuple: return {(entity, "2025-01-06"): {"ssrd_mean": 12.3}, ...}
table = mostlyright.weather.training_table("KNYC", "2025-01-06", "2025-01-08", features=["era5_ssrd"])# table now carries an additive ssrd_mean column; label columns untouched.class mostlyright.experimental.ContributorSpec(name, prefix, archive_class, injection_point, fn, key=(‘station’, ‘local_standard_date’), native_grain=‘daily’, columns=(), builtin=False, kind=‘source’)
Section titled “class mostlyright.experimental.ContributorSpec(name, prefix, archive_class, injection_point, fn, key=(‘station’, ‘local_standard_date’), native_grain=‘daily’, columns=(), builtin=False, kind=‘source’)”Bases: object
An immutable registry entry describing one contributor.
- Parameters:
- name (str)
- prefix (str)
- archive_class (Literal [ ‘refetchable’ , ‘ledger’ ])
- injection_point (Literal [ ‘pre_aggregation’ , ‘post_join’ ])
- fn (Callable [ [ … ] , dict [str , dict [str , Any ] ] ])
- key (tuple [str , str ])
- native_grain (Literal [ ‘daily’ , ‘observation’ ])
- columns (tuple [str , … ])
- builtin (bool)
- kind (Literal [ ‘source’ , ‘label’ ])
Unique registry key (also the value used in features=[...]).
prefix
Section titled “prefix”Column namespace this contributor owns (e.g. "sat_"). Every
column it emits MUST start with this prefix; the prefix must be
non-empty and end with "_".
archive_class
Section titled “archive_class”"refetchable" | "ledger" (source-identity §5).
injection_point
Section titled “injection_point”"pre_aggregation" | "post_join" — where the
columns land in the dataset() pipeline.
The contribute(entity, window, grain, **kw) callable.
The key tuple the returned frame is keyed by. Default
("station", "local_standard_date") (v1 weather vertical); the
earnings vertical will register with e.g. ("ticker", "call_date").
native_grain
Section titled “native_grain”RESERVED. v1 contributors are "daily"; a future
contributor may declare "observation" to supply per-report rows.
columns
Section titled “columns”The declared prefixed column set this contributor emits. REQUIRED for third-party contributors (so a contribute() that RAISES or covers zero days still yields an all-NaN prefix block instead of vanishing — the failure-semantics contract). Built-ins derive it lazily (their columns are the covariate-helper output), so it may be empty for them; when empty the aligner falls back to the first-seen-across-days universe.
builtin
Section titled “builtin”True for the four migrated built-ins (exempt from the
ExperimentalFeatureWarning + third-party-prefix guard).
"source" (feature / X frame) | "label" (settlement target /
y frame). Additive; every existing
registration defaults to "source" so the four built-ins
stay byte-stable. mr.registry.source() / mr.registry.label()
write this axis and enforce the .label. path invariant.
archive_class: Literal['refetchable', 'ledger']
Section titled “archive_class: Literal['refetchable', 'ledger']”builtin: bool
Section titled “builtin: bool”columns: tuple[str, ...]
Section titled “columns: tuple[str, ...]”fn: Callable[..., dict[str, dict[str, Any]]]
Section titled “fn: Callable[..., dict[str, dict[str, Any]]]”injection_point: Literal['pre_aggregation', 'post_join']
Section titled “injection_point: Literal['pre_aggregation', 'post_join']”kind: Literal['source', 'label']
Section titled “kind: Literal['source', 'label']”native_grain: Literal['daily', 'observation']
Section titled “native_grain: Literal['daily', 'observation']”prefix: str
Section titled “prefix: str”class mostlyright.experimental.DeferredSource(contract, entity, builder)
Section titled “class mostlyright.experimental.DeferredSource(contract, entity, builder)”Bases: object
A source whose fetch window is deferred until align (R-02).
A source builder invoked WITHOUT a window (e.g. weather.observations('KNYC'))
returns this instead of eagerly fetching, so the training-table desugaring
align(spine, weather.observations('KNYC')) never raises TypeError. align is
the single place the fetch window is inferred — from the spine’s copy of the
source’s equality-join key (contract.event_time_col, e.g. the day key
local_standard_date) when present, else the decision_time min/max — and it calls
materialize() to turn the deferred source into a concrete
(frame, SourceContract) source.
- Parameters:
contract
Section titled “contract”The SourceContract the
materialized frame conforms to (prefix / point_in_time_fidelity / entity_key).
entity
Section titled “entity”The entity (station) the deferred builder will fetch.
builder
Section titled “builder”A callable (entity, from_date, to_date) -> pd.DataFrame that
re-enters the eager fetch path with the align-inferred window. The
from_date/to_date are inclusive ISO YYYY-MM-DD strings.
builder: Callable[[str | list[str] | tuple[str, ...], str, str], DataFrame]
Section titled “builder: Callable[[str | list[str] | tuple[str, ...], str, str], DataFrame]”materialize(from_date, to_date)
Section titled “materialize(from_date, to_date)”Run the deferred builder over [from_date, to_date] (inclusive).
- Return type:
tuple[DataFrame,SourceContract] - Parameters:
mostlyright.experimental.align(spine, *sources)
Section titled “mostlyright.experimental.align(spine, *sources)”As-of join each source onto spine.
Signature FROZEN at two concepts: (spine, *sources) — no policy
kwargs. A source is EITHER a pre-materialized (frame, SourceContract) pair
(BYO / rung-1; an optional 3rd tuple element overrides the prefix) OR a
DeferredSource — a window-deferred builder call that align
materializes over the spine’s local-standard-day key (the source’s
event_time_col) when the spine carries it, else the decision_time
min/max (R-02).
Per source: refuse latest_only (R-18) → collapse by revision_order
authority → namespace non-key columns under the source prefix with a hard
collision ContractError (R-09/R-24, never pandas _x/_y) → join
(equality or backward as-of, inferred from the spine’s shape) → per-source
leakage audit (R-22). Returns a plain pd.DataFrame stamped
attrs["source"] = "align", plus per-column attrs["provenance"] (source
id) and attrs["coverage"] (source valid_from/coverage edge) so an
all-NaN column prefix is explainable via mr.provenance(frame).
- Return type:
DataFrame - Parameters:
- spine (DataFrame)
- sources (tuple *[*DataFrame , SourceContract ] | DeferredSource)
mostlyright.experimental.contributor(name, prefix, archive_class, , injection_point, fn=None, key=(‘station’, ‘local_standard_date’), native_grain=‘daily’, columns=None, _builtin=False)
Section titled “mostlyright.experimental.contributor(name, prefix, archive_class, , injection_point, fn=None, key=(‘station’, ‘local_standard_date’), native_grain=‘daily’, columns=None, _builtin=False)”Register a contributor. Usable as a decorator or a direct call.
EXPERIMENTAL / semver-exempt until it graduates. The public entry point is
mostlyright.experimental.contributor(). The registry is module-level and
shared by dataset/markets/reconcile; the returned spec is also the
decorated function (so @contributor(...) leaves the original callable
bound in the caller’s namespace).
Decorator form:
@contributor("era5_ssrd", "ssrd_", "refetchable", injection_point="post_join")def era5_ssrd(entity, window, grain, *, tz_override=None): ... return {("KNYC", "<local_standard_date>"): {"ssrd_mean": 12.3}, ...}Direct form (used by the built-in migrations):
contributor("satellite", "sat_", "refetchable", injection_point="post_join", fn=_sat_contribute, _builtin=True)- Parameters:
- name (
str) – Unique registry key +features=[...]token. - prefix (
str) – Column namespace (non-empty, ends with"_", not a label prefix). Third-party contributors may not claim a built-in prefix. - archive_class (
Literal['refetchable','ledger']) –"refetchable"|"ledger"(source-identity §5). - injection_point (
Literal['pre_aggregation','post_join']) –"pre_aggregation"|"post_join". - fn (
Callable[...,dict[str,dict[str,Any]]] |None) – Thecontributecallable. Omitted in decorator form (the decorated function becomesfn). - key (
tuple[str,str]) – Returned-frame key tuple (default the v1 weather key). Thecontribute()return mapping may be keyed by a plain local-standard-date string OR by this tuple(entity, local_standard_date); both bucket to the local standard day (the tuple’s last element). - native_grain (
Literal['daily','observation']) – RESERVED grain declaration (v1 ="daily"). - columns (
tuple[str,...] |list[str] |None) – The prefixed column set the contributor emits. REQUIRED for third-party contributors (each column must carryprefix) so a failed / emptycontribute()still yields an all-NaN prefix block instead of silently dropping the columns. Built-ins may omit it (they derive their columns from the covariate-helper output). - _builtin (
bool) – Internal — set by the four built-in migrations to bypass the ExperimentalFeatureWarning + third-party-prefix guard.
- name (
- Raises:
ValueError – duplicate
name, malformed / label-collidingprefix, a third-party contributor claiming a reserved built-in prefix, or a third-party contributor that omitscolumns/ declares a column outside itsprefixnamespace. - Return type:
Any - Returns:
The registered
ContributorSpec(direct form) or a decorator that registers then returns the decorated function (decorator form).
mostlyright.experimental.list_contributors()
Section titled “mostlyright.experimental.list_contributors()”Return the sorted registered contributor names.
mostlyright.experimental.registered_contributors()
Section titled “mostlyright.experimental.registered_contributors()”Return a shallow copy of the registry (name → spec).
- Return type:
dict[str,ContributorSpec]
mostlyright.experimental.spine(df, , entity, decision_time, y, label_available_time=None)
Section titled “mostlyright.experimental.spine(df, , entity, decision_time, y, label_available_time=None)”Map a BYO frame into the canonical guarded spine shape.
- Parameters:
- df (
DataFrame) – The user-built target frame. - entity (
str) – The column naming the entity (renamed to the canonicalstationkey). - decision_time (
str) – The column holding the per-row point-in-time cutoff. If it is absent as a column but lives in a datetime / date-named index, the index is lifted into a column first (reusing_coerce_date_column). - y (
str|list[str] |tuple[str,...]) – The target column name(s). A spine with no target is meaningless. - label_available_time (
str|None) – Optional column naming when the label became known; defaults todecision_timewhen unmapped (conservative, non-leaking).
- df (
- Return type:
DataFrame - Returns:
A
SpineContract-valid frame(station, decision_time, label_available_time, *y). - Raises:
ContractError – a mapped column (
entity/decision_time/ ay) is absent from the frame (— the mapping is never guessed).