Skip to content

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 bridge spine(df, *, entity, decision_time, y) that lifts a user frame into the guarded (leakage-checked) world.

  • align() — the composition verb align(spine, *sources) (as-of join + leakage guard) that the domain training_table() verbs are built on.

  • DeferredSource — the deferred-source builder for BYO leakage-safe joins (the escape hatch that composes user data through align()).

  • contributor() — register a covariate contributor. A contributor is one function contribute(entity, window, grain) -> {key: {prefixed_col: value}} plus declared metadata (prefix namespace, archive_class, injection_point, and the columns it emits). Registered contributors compose into dataset() via the features=[...] selector without any core change. The FIRST third-party registration emits an ExperimentalFeatureWarning. 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 a contribute() 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 declared key tuple (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.

Unique registry key (also the value used in features=[...]).

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 "_".

"refetchable" | "ledger" (source-identity §5).

"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").

RESERVED. v1 contributors are "daily"; a future contributor may declare "observation" to supply per-report rows.

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.

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.

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.

The SourceContract the materialized frame conforms to (prefix / point_in_time_fidelity / entity_key).

The entity (station) the deferred builder will fetch.

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.

Run the deferred builder over [from_date, to_date] (inclusive).

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).

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) – The contribute callable. Omitted in decorator form (the decorated function becomes fn).
    • key (tuple[str, str]) – Returned-frame key tuple (default the v1 weather key). The contribute() 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 carry prefix) so a failed / empty contribute() 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.
  • Raises: ValueError – duplicate name, malformed / label-colliding prefix, a third-party contributor claiming a reserved built-in prefix, or a third-party contributor that omits columns / declares a column outside its prefix namespace.
  • 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).

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 canonical station key).
    • 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 to decision_time when unmapped (conservative, non-leaking).
  • Return type: DataFrame
  • Returns: A SpineContract-valid frame (station, decision_time, label_available_time, *y).
  • Raises: ContractError – a mapped column (entity / decision_time / a y) is absent from the frame (— the mapping is never guessed).