Code

API reference

Spanfold API reference.

Static reference for the public package surface across C# and Python. Python keeps the same core capabilities as the C# package while using idiomatic snake-case names and dataclass result models.

dotnet add package Spanfold
dotnet add package Spanfold.Testing
cd packages/python
python -m pip install -e ".[dev]"

The Python package includes the core runtime, comparison, export, testing, and fixture CLI surfaces.

python package

Python parity surface

The Python package mirrors the C# core library with idiomatic naming: builders expose build(), validate(), prepare(), run(), and run_live(); prepared comparisons expose align(); results expose deterministic JSON, JSON Lines, Markdown, debug HTML, and LLM context exports.

Python memberC# equivalent
Spanfold.for_events()Spanfold.For<TEvent>()
WindowComparisonBuilder.prepare()WindowComparisonBuilder.Prepare()
PreparedComparison.align()PreparedComparison.Align()
ComparisonComparatorCatalog.is_known_declaration(...)ComparisonComparatorCatalog.IsKnownDeclaration(...)
ComparisonResult.export_llm_context(...)ComparisonResult.ExportLlmContext(...)
ComparisonDebugHtmlOptions.to_file(...)ComparisonDebugHtmlOptions.ToFile(...)
ComparisonLlmContextOptions.to_file(...)ComparisonLlmContextOptions.ToFile(...)
python -m spanfold.cli compare fixture.jsonspanfold compare fixture.json
from spanfold import ComparisonLlmContextOptions

result = (
    history.compare("Provider QA")
    .target("provider-a")
    .against("provider-b")
    .within(window_name="DeviceOffline")
    .using("overlap", "residual", "coverage")
    .run(ComparisonLlmContextOptions.to_file("artifacts/provider-qa.llm.json"))
)

prepared = result.prepared
aligned = prepared.align() if prepared is not None else None

static class

Spanfold

Entry point for configuring a Spanfold event pipeline.

MemberPurpose
For<TEvent>()Creates an `EventPipelineBuilder<TEvent>` for the event type.

sealed class

EventPipelineBuilder<TEvent>

Top-level builder for windows, callbacks, event time, and history recording.

MemberPurpose
Window(...)Adds a source window and returns a `WindowPipelineBuilder<TEvent>`.
TrackWindow(...)Builds a pipeline for one state-driven source window.
RecordWindows()Enables recording of open and closed windows during ingestion.
WithEventTime(...)Sets the event timestamp selector.
OnEmission(...)Registers a callback for emitted transitions.
Build()Builds the configured `EventPipeline<TEvent>`.

sealed class

WindowPipelineBuilder<TEvent>

Builder returned after adding a window. It keeps window and roll-up concepts close together.

MemberPurpose
Window(...)Adds another independent source window.
RollUp(...)Adds a parent window derived from child activity.
RecordWindows()Enables recorded history.
WithEventTime(...)Configures timestamps.
Build()Builds the pipeline.

sealed class

EventPipeline<TEvent>

Runtime pipeline that ingests events and exposes recorded history.

MemberPurpose
HistoryRecorded `WindowHistory` for direct queries, annotations, snapshots, and comparison.
MetadataConfigured event type and window hierarchy metadata.
Ingest(event)Processes one event without source context.
Ingest(event, source)Processes one event with source/lane context.
Ingest(event, source, partition)Processes one event with source and partition context.
IngestMany(events)Processes events sequentially.

sealed class

WindowDefinitionBuilder<TEvent>

Defines one state window: key, active predicate, segments, tags, and callbacks.

MemberPurpose
Named(name)Sets the public window name.
Key(...)Selects the logical key that owns state.
ActiveWhen(...)Predicate that keeps the window active.
Segment(name, ...)Adds a boundary-aware segment dimension.
Tag(name, ...)Captures descriptive metadata when a window opens.
OnOpened(...) / OnClosed(...)Registers transition callbacks.

sealed class

SegmentBuilder<TEvent>

Builds segment dimensions, including nested segment hierarchies.

MemberPurpose
Value(...)Selects the segment value from the event.
Child(name, ...)Adds a child segment under this segment.

record

WindowEmission<TEvent>

Represents an emitted window transition from ingestion.

MemberPurpose
WindowName, Key, EventIdentity and source event for the transition.
Kind`Opened` or `Closed`.
Source, PartitionLane and partition context.
Segments, TagsAnalytical context captured with the emission.

abstract record

WindowRecord, OpenWindow, ClosedWindow

Recorded temporal evidence created from emissions.

MemberPurpose
WindowName, Key, Source, PartitionScope identity.
StartPosition, EndPositionProcessing-position bounds.
StartTime, EndTimeTimestamp bounds when event time is configured.
Segments, TagsContext for filtering, grouping, and debug output.
IdStable `WindowRecordId` derived from the window identity.

sealed class

WindowHistory

Recorded open and closed windows plus query, annotation, snapshot, and comparison entry points.

MemberPurpose
ClosedWindows / OpenWindows / WindowsMaterialized recorded history.
Query()Direct read-only history query.
SnapshotAt(horizon)Read-only horizon snapshot.
Compare(name)Starts a staged comparison.
Annotate(...)Append-only late metadata.
CompareSources(...), CompareHierarchy(...)Source matrix and hierarchy explanation helpers.

sealed class

WindowHistoryQuery

Filters recorded history by window, key, source/lane, partition, segment, and tag.

MemberPurpose
Window(...), Key(...), Lane(...)Restrict query scope.
Segment(...), Tag(...)Require context values.
Windows(), ClosedWindows(), OpenWindows()Materialize matching records.
WindowsAt(...), OpenWindowsAt(...)Evaluate at a horizon.
LatestWindow() / LatestWindowAt(...)Return the latest matching record.

sealed class

WindowHistorySnapshot

Read-only view of recorded history at an explicit horizon.

MemberPurpose
HorizonThe point used to evaluate open and closed windows.
Query()Starts a `WindowSnapshotQuery` over snapshot records.

records

WindowAnnotation and WindowAnnotationTarget

Append-only metadata attached after a window opens or closes.

MemberPurpose
Name, Value, KnownAtAnnotation payload and point-in-time safety.
RevisionAppend order for repeated annotation names.
WindowAnnotationTarget.From(window)Stable target based on the window start identity.

sealed class

WindowComparisonBuilder

Staged comparison flow for target, against, scope, normalization, comparator selection, and execution.

var result = pipeline.History
    .Compare("Provider QA")
    .Target("provider-a", s => s.Source("provider-a"))
    .Against("provider-b", s => s.Source("provider-b"))
    .Within(scope => scope.Window("DeviceOffline"))
    .Using(c => c.Overlap().Residual().Missing())
    .Run();
result = (
    pipeline.history.compare("Provider QA")
    .target("provider-a")
    .against("provider-b")
    .within(window_name="DeviceOffline")
    .using("overlap", "residual", "missing")
    .run()
)

Python exposes the same comparison stages with snake-case method names.

MemberPurpose
Target(...), Against(...)Select comparison sides.
AgainstCohort(...)Compare against a derived cohort side.
Within(...)Set scope.
Normalize(...)Set temporal normalization policy.
Using(...)Select comparator row families.
Prepare(), Run(), RunLive(...)Materialize stages or execute comparison.

sealed class

ComparisonSelectorBuilder

Creates serializable or runtime selectors for target and comparison sides.

MemberPurpose
WindowName(...), Key(...), Source(...)Select by identity.
Sources(...)Select multiple source identities.
Partition(...)Select a partition.
PositionRange(...), TimeRange(...)Select temporal ranges.
Runtime(...)Creates a runtime-only predicate selector.

sealed class

ComparisonCohortBuilder and CohortActivity

Collapses several sources into one derived comparison side before comparators run.

MemberPurpose
Sources(...)Declares cohort members.
Activity(CohortActivity)Sets when the cohort is active.
CohortActivity.Any() / All() / None()Basic activity rules.
AtLeast(n), AtMost(n), Exactly(n)Threshold rules.

sealed class

ComparisonNormalizationBuilder

Makes temporal policies explicit before alignment.

MemberPurpose
RequireClosedWindows()Rejects open windows for historical comparison.
ClipOpenWindowsTo(horizon)Clips open windows to a live horizon.
OnPosition() / OnEventTime()Selects processing-position or timestamp analysis.
KnownAtPosition(...) / KnownAt(...)Prevents future leakage.
CoalesceAdjacentWindows(), RejectDuplicateWindows()Optional normalization policies.

sealed class

ComparisonComparatorBuilder

Selects result row families.

MemberPurpose
Overlap()Both sides active.
Residual()Target active without comparison coverage.
Missing()Comparison active without target coverage.
Coverage()Coverage rows and summaries.
Gap(), SymmetricDifference(), Containment()Additional shape and invariant checks.
LeadLag(...), AsOf(...)Transition timing drift and point-in-time lookup.

sealed class

ComparisonResult

Structured comparison artifact containing diagnostics, stages, rows, summaries, finality, and metadata.

MemberPurpose
Prepared, AlignedComparison stages when execution reached them.
OverlapRows, ResidualRows, MissingRowsCore row families.
CoverageRows, GapRows, LeadLagRows, AsOfRowsAdditional row families.
DiagnosticsValidation and execution diagnostics.
RowFinalitiesFinal or provisional status for live rows.
IsValidTrue when no error diagnostics are present.

static class

ComparisonExportExtensions

Deterministic export helpers for plans and results.

MemberPurpose
ExportJson()Stable JSON for plans or results.
ExportJsonLines()Lazy JSON Lines for result rows.
ExportMarkdown()Deterministic Markdown explanation.
ExportDebugHtml()Self-contained visual comparison document.
ExportLlmContext()Agent-readable JSON with instructions, summary, Markdown orientation, full result data, and row documents.
ComparisonDebugHtmlOptions.ToFile(...)Configuration-driven debug output from `Run()` or `RunLive()`.
ComparisonLlmContextOptions.ToFile(...)Configuration-driven LLM context output from `Run()` or `RunLive()`.

readonly record struct

TemporalPoint

Explicit point on a temporal axis.

MemberPurpose
ForPosition(long)Processing-position point.
ForTimestamp(DateTimeOffset, clock)Timestamp point.
CompareTo(...), IsBefore(...), IsAfter(...)Axis-safe comparison helpers.

readonly record struct

TemporalRange

Half-open range used by windows, aligned segments, and result rows.

MemberPurpose
Closed(start, end)Known-ended range.
Open(start)Open range for ongoing windows.
WithEffectiveEnd(...)Clips or evaluates the range at an effective end.
GetPositionLength(), GetTimeDuration()Measures range magnitude.
Overlaps(...), Contains(...)Range predicates.

sealed class

LaneLivenessTracker

Converts sparse observations into liveness signals that can be recorded as ordinary windows.

MemberPurpose
ForLanes(...)Creates a deterministic tracker for expected lanes.
Observe(lane, observedAt)Records that a lane reported.
Check(horizon)Emits silence or recovery signals at a horizon.
LaneLivenessSignalEvent shape for recording silence windows.

Spanfold.Testing sealed class

WindowHistoryFixtureBuilder

Builds compact recorded histories for comparator and contract tests.

MemberPurpose
AddClosedWindow(...)Adds a closed fixture window.
AddOpenWindow(...)Adds an open fixture window.
Build()Creates a `WindowHistory` fixture.

Spanfold.Testing static class

SpanfoldAssert

Framework-neutral assertions for comparison artifacts.

MemberPurpose
IsValid(...)Asserts that a comparison result has no error diagnostics.
HasNoDiagnostics(...)Asserts that no diagnostics were emitted.
HasDiagnostic(...)Returns a matching diagnostic code or fails.
HasRowCount(...)Asserts an expected row count for a named row family.

Spanfold.Testing static class

SpanfoldSnapshot

Snapshot helpers for deterministic JSON and Markdown artifacts.

MemberPurpose
Normalize(...)Normalizes line endings, trailing whitespace, and deterministic record IDs.
AssertEqual(...)Compares two normalized snapshot strings.