Rust API reference

The spanfold crate.

Public Rust items for recording temporal state, querying evidence, comparing histories, analysing episodes, exporting artifacts, and testing temporal contracts. Fallible builders and ingestion return typed Result values.

cargo add spanfold@0.1.1
cargo install spanfold-cli --version 0.1.1

The crate is pre-1.0 and may change between minor releases.

spanfold::pipeline · crate-root re-exports

Pipeline builders

for_events::<T>() starts an EventPipelineBuilder<T>. Recording must be enabled before history-dependent APIs are useful.

let mut pipeline = spanfold::for_events::<DeviceStatus>()
    .record_windows()
    .with_event_time(|event| event.observed_at)
    .track_window(
        "DeviceOffline",
        |event| event.device_id.clone(),
        |event| !event.is_online,
    )
    .build()?;
ItemPurpose
for_events::<T>()Creates the typed entry builder.
record_windows()Keeps open and closed records in WindowHistory.
with_event_time(...)Supplies timestamps alongside processing positions.
track_window(...)Adds one key selector and active predicate, then returns a buildable window pipeline.
window(...)Adds another definition while retaining builder configuration.
track_window_with_options(...), window_with_options(...)Configure callbacks through WindowOptions.
build(), try_build()Return Result<EventPipeline<T>, EventPipelineBuildError>.
build_or_panic()Explicit panic-on-invalid-definition convenience.

struct

EventPipeline<T>

Owns window runtime state and the recorded history.

ItemPurpose
ingest(event, source, partition)Advances processing position and returns Result<IngestionResult, IngestionError>.
ingest_many(...)Processes an iterator through the same ingestion contract.
history()Borrows the authoritative WindowHistory.
metadata()Returns EventPipelineMetadata and its window definitions.
IngestionResult, WindowEmissionExpose transition emissions and whether an ingest changed a window.

spanfold::records

WindowHistory and query types

The history owns ClosedWindow, OpenWindow, annotations, and borrowed query access. WindowRecord is the common enum view.

ItemPurpose
closed_windows(), open_windows(), windows()Read recorded evidence.
query()Starts WindowHistoryRefQuery without cloning the history.
where_window(...), where_key(...), where_source(...), where_partition(...)Filter record identity.
where_segment(...), where_tag(...)Filter structured metadata.
closed(), open(), latest()Choose window state or most recent evidence.
snapshot_at(...)Creates a known-at WindowHistorySnapshot with its own query API.
annotate(...), annotations_for(...), annotations_known_at(...)Add and query append-only annotations.
summarize_by_segment(...), summarize_by_tag(...)Aggregate record groups.

spanfold::records

WindowHistoryFixture

Constructs compact histories for examples and contract tests.

ItemPurpose
closed_window(...)Adds a closed fixture window.
open_window(...)Adds an open fixture window.
WindowHistoryFixtureWindowConfigures source, partition, known-at position, segments, and tags.
build()Returns a WindowHistory.

crate-root builder

WindowComparisonBuilder

WindowHistory::compare(name) starts the fluent comparison path.

let result = history
    .compare("Provider QA")
    .target_source("provider-a")
    .against_source("provider-b")
    .scope_window("DeviceOffline")
    .overlap()
    .residual()
    .missing()
    .run();
ItemPurpose
target_source(...), against_source(...), against_sources(...)Select common source-based sides.
target_selector(...), against_selector(...), against_cohort(...)Use explicit selector or cohort contracts.
scope_window(...), scope_key(...), scope_partition(...), scope_segment(...), scope_tag(...)Narrow comparison scope.
known_at_position(...), clip_open_windows_to_position(...)Control observable evidence and open-window evaluation.
normalization(...), coalesce_adjacent_windows(), reject_duplicate_windows()Set normalization policy.
validate(), prepare(), align(), run(), run_live(...)Inspect or execute comparison stages.

comparison plan types

ComparisonSelector, ComparisonScope, and normalization

ItemPurpose
ComparisonSelector::for_source(...), for_sources(...)Create serializable source selectors.
for_window_name(...), for_key(...), for_partition(...)Select identity fields.
and(...)Compose selector predicates.
serializable(name, description)Create a portable descriptor that matches every window.
runtime_only(name, description, predicate)Create a process-local custom predicate. Portable exports reject plans that use it.
ComparisonScope, WindowFilterRepresent named-window, identity, metadata, and temporal constraints.
ComparisonNormalizationPolicyControls axis, open windows, null timestamps, known-at filtering, adjacency, and duplicates.
ComparisonPlanPortable description consumed by prepare, align, and compare.

enum and builder methods

Comparator

Builder itemResult
overlap()Intervals active on both sides.
residual(), missing()Target-only and against-only intervals.
coverage()Segment-level coverage rows and grouped summaries.
gap(), symmetric_difference(), containment()Difference shape and containment results.
use_comparator(Comparator::LeadLag { ... })Transition timing differences.
use_comparator(Comparator::AsOf { ... })Point-in-time matching.

comparison output

ComparisonResult and typed rows

rows is the canonical grouped collection. Family fields are zero-copy compatibility views. Row IDs are opaque values assigned by the producing result.

ItemPurpose
overlap_rows, residual_rows, missing_rowsCore typed row families.
coverage_rows, gap_rows, symmetric_difference_rowsAdditional interval result families.
containment_rows, lead_lag_rows, as_of_rowsRelationship and point-in-time families.
diagnostics, comparator_summaries, coverage_summariesExecution diagnostics and aggregates.
*_rows_with_finality()Borrow typed rows with authoritative row ID, finality, version, reason, and supersession metadata.
trace_row(...), trace_typed(...)Trace a result row to contributing records, normalized windows, aligned segments, and exclusions.

crate-root functions

Source matrix and hierarchy analytics

ItemPurpose
compare_sources(...)Produces a SourceMatrixResult across several sources.
SourceMatrixResult::get_cell(...), try_get_cell(...)Read a directed source-pair cell.
compare_hierarchy(...)Produces parent and child comparison rows in HierarchyComparisonResult.

spanfold::episodes · crate-root re-exports

Episode formation and comparison

ItemPurpose
WindowHistory::form_episodes(name)Starts EpisodeFormationBuilder.
from(selector), scope(...), normalization(...)Select and normalize one evidence side.
stitch_gaps_up_to(TemporalTolerance)Sets axis-safe fragment stitching.
WindowHistory::compare_episodes(name)Starts EpisodeComparisonBuilder.
target(name, selector), against(name, selector)Define the two episode sides.
relate_within(TemporalTolerance)Sets the cross-side relation tolerance.
build(), run(), run_live(...)Return typed Result values for plans and results.

episode domain

Episode results, relations, and summaries

ItemPurpose
Episode, EpisodeFragment, EpisodeSetOccurrence identity, evidence fragments, envelope, magnitude, finality, and set summary.
EpisodeRelationKindOneToOne, Split, Merge, Complex, and unmatched classifications.
EpisodeComparisonResultOwns both sets, exhaustive relations, summary, and optional live horizon.
relations_of_kind(...), unmatched_target_episodes(), unmatched_against_episodes()Query relation outcomes.
as_reference()Interprets target as reference and against as detection through EpisodeReferenceScorecard.
EpisodeAnalysisDocument::parse_json(...), execute(...)Run a portable processing-position Episode document.

spanfold::sequences

WindowSequenceBuilder

WindowHistory::match_sequence(name) matches onset-ordered windows for the same lane identity. Selected steps may overlap; completed matches do not reuse source records.

ItemPurpose
step(window_name), then(window_name)Declare the ordered pattern.
run()Returns Result<Vec<WindowSequenceMatch>, WindowSequenceError>.
run_live(evaluation_horizon)Evaluates open evidence at an explicit horizon.

Read the complete ordered sequences guide for matching, lineage, live finality, and release availability.

spanfold::export and crate-root functions

Exports, explain output, and changelogs

ItemPurpose
export_plan_json(...), export_result_json(...)Deterministic JSON artifacts.
export_result_json_lines(...), write_result_json_lines(...)Materialized or streamed JSON Lines.
export_result_markdown(...), export_result_debug_html(...)Human-readable and self-contained visual output.
export_result_llm_context(...)Structured context for agent-assisted auditing.
write_export_files_atomically(...)Writes a set of export files atomically.
run_with_exports(...), run_live_with_exports(...)Execute and write configured artifacts from the comparison builder.
create_changelog(...), replay_changelog(...)Create and replay deterministic row-change entries.

spanfold::temporal and liveness

Temporal types and lane liveness

ItemPurpose
TemporalAxis, TemporalPoint, TemporalRangeAxis-safe processing-position and event-time coordinates.
LaneKey::new(...), LaneKey::with_partition(...)Identify one expected reporting lane.
LaneLivenessTracker::for_lanes(...)Create a deterministic liveness tracker.
observe(...), observe_partition(...), observe_key(...)Record lane observations.
check(horizon)Emit LaneLivenessSignal values for silence and recovery.

crate-root testing helpers

SpanfoldAssert, SpanfoldSnapshot, and VirtualComparisonClock

ItemPurpose
SpanfoldAssert::is_valid(...), has_no_diagnostics(...), has_diagnostic(...)Assert result validity and diagnostics.
has_row_count(...)Assert a typed row-family count.
has_no_provisional_rows(...), has_provisional_rows(...)Assert live finality.
SpanfoldSnapshot::normalize(...), assert_equal(...)Compare deterministic text artifacts.
VirtualComparisonClock::new(...), advance_by(...), advance_to(...)Control processing-position horizons in tests.

spanfold-cli crate · spanfold command

Command-line workflows

CommandPurpose
validate-plan, compare, explainValidate and execute comparison fixtures.
audit, audit-windowsProduce reproducible audit artifacts from fixtures or JSON Lines windows.
import-events, audit-eventsMap JSON Lines or CSV events into windows and audit output.
episodesExecute a versioned Episode analysis document over window JSON Lines.

Run spanfold <command> --help for command-specific arguments.