Help us shape the future of Go! Take the 2026 Go Developer Survey

examples

package
v1.0.0-alpha.26 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 25, 2026 License: MIT Imports: 12 Imported by: 0

README

Pulse Examples

Runnable JSON request files organized by topic. Every example resolves its cohort from the shared fixture set under fixtures/ so adding a new example is just authoring JSON — no new CSV, schema, or build step.

Layout

internal/examples/
├── README.md                  # this file
├── fixtures/                  # shared CSVs + schemas + generator + build script
│   ├── gen.go                 # deterministic CSV generator (run once)
│   ├── build.sh               # CSV -> .pulse importer (writes ./.data)
│   ├── *.csv                  # checked-in source data
│   └── schemas/*.json         # hand-tuned schemas with descriptions
├── aggregations/              # AGG_* aggregations, incl. vector aggregators (21)
├── attributes/                # ATTR_* per-record derivations (23)
├── compose/                   # Compose batches: sweeps, fits, populations, the MMM decay sweep, the SEM invariance ladder, SEM scores from a bound fit (10)
├── crosstab/                  # Crosstab tables, margins and inference (17)
├── facet/                     # Facet requests (3)
├── features/                  # FEAT_* feature engineering (12)
├── filterers/                 # FILTER_* row-level predicates (9)
├── groupers/                  # GROUP_* partitioning (11)
├── matrices/                  # MAT_* matrix operators over virtual vectors (16)
├── overlays/                  # OVERLAY_* layers on Request / Compose / Facet hosts (48)
├── regression/                # REG_* regressions (18)
├── synth/                     # synth specs (7)
├── tests/                     # TEST_* tier-1 and tier-2 statistical tests (37)
├── windows/                   # WIN_* per-row analytics (12)
└── <new-category>/            # each: README.md + run-all.sh + *.json

One-time setup

Build the binary, generate fixtures, import to .pulse:

make build
./internal/examples/fixtures/build.sh

That writes transactions.pulse, customers.pulse, orders.pulse, training_data.pulse, all_types.pulse, experiment.pulse, repeated_measures.pulse, card_issuers.pulse, tier_migrations.pulse, survey.pulse, subscribers.pulse, warehouse_orders.pulse, plan_history.pulse, plan_history_wide.pulse, battery.pulse, intake.pulse, mmm_weekly.pulse and brand_survey.pulse into .data/ at the repo root, plus the point-lookup index on experiment.pulse (id). Every example request has cohort.data_dir = ".data" so the requests run unmodified.

Available cohorts

File Fields
transactions.pulse id (u32), amount (f64)
customers.pulse id (u32), age (u8), income (f64), region (categorical), city (categorical)
orders.pulse id (u32), order_date (date), revenue (f64), ordered_at (datetime)
training_data.pulse id (u32), region/occupation/category (categorical), label (u8 binary), price/income (f64), signup_date (date)
all_types.pulse One column for every one of the 17 supported types (u8/u16/u32/u64, f32/f64, nullable_bool/u4/u8/u16, date, packed_bool, categorical_u8/u16/u32, decimal128, nullable_decimal128). Hand-curated 5-row CSV — exists so a single fixture exercises every type-aware code path.
experiment.pulse A/B test cohort: id (u32), treatment/region/segment/converted (categorical), revenue/session_minutes (f64), period (date). Planted effects across treatment, region, segment, and time so every TEST_* example produces a meaningful, non-trivial result.
survey.pulse A six-item rating battery: id (u32), panel (categorical, a / b), q1-q6 (f64). Two correlated factors (q1-q3 service, q4-q6 value; q3 / q6 cross-load) for factor-analysis, rotation, vector-fit and population examples.
subscribers.pulse 48 subscriber accounts with binary outcomes stored as flags: id (u32), arm / plan (categorical), converted / churned / defaulted (packed_bool, read as levels "0" / "1"), late_payment (u8 0/1), signup_date / first_repeat_order (date), revenue / cost (decimal128, cents). Every value is a closed-form function of the row index (fixtures/gen.go), so the flag tests, the logistic fit, calendar retention and exact money examples have hand-derivable answers (showcase_flags_money_test.go).
warehouse_orders.pulse 8 orders across four warehouses: id (u32), warehouse_tz (categorical, IANA zone names), ordered_at (datetime, UTC instants straddling local midnights), revenue (f64). The per-row-zone example (groupers/13_date_per_row_zone.json) reads warehouse_tz through time_zone_field.
plan_history.pulse A long panel of 15 customers at three month-end snapshots (45 rows, not sorted by customer): id (u32), customer_id (u32), seen_at (date), plan (categorical, basic / plus / pro). Hand-curated; attributes/24_previous_state_transitions.json reads each row's previous plan (ATTR_PREVIOUS_STATE) for a from-plan × to-plan crosstab.
plan_history_wide.pulse The wide twin of plan_history: one row per move between two consecutive snapshots (30 rows): id (u32), customer_id (u32), moved_at (date, the later snapshot), plan_before / plan_after (categorical). overlays/55_crosstab_previous_state_flows.json runs Markov, symmetry and retention on the long panel; TestExamples_PreviousStateFlowsMatchWideTwin holds its answer to the same request over this file.
battery.pulse A one-trait engagement battery (300 respondents): id (u32), bat_energy / bat_proud / bat_absorbed / bat_recommend / bat_time_flies (u8, 1-5, positively keyed) and bat_dread (u8, 1-5, reverse-keyed). Every item loads on one latent trait (fixtures/gen.go), so the reliability example's omega is defined and the PCA example has one dominant component (TestExamples_BatteryMeasuresOneTrait).
intake.pulse 300 sign-up intake forms, 100 per channel, with planted nulls: id (u32), channel (categorical, web / phone / paper), age (u8, nullable, blank on a few forms in every channel) and income (f64, nullable, blank far more often on paper than on web). The one fixture with real nulls: a blank CSV cell in a nullable numeric column imports as a null in the per-record bitmap, never as zero, so the null-count and null-filter examples report non-zero, channel-dependent gaps (TestExamples_IntakeNullsArePlanted). To plant nulls in a new fixture, declare the field "nullable": true in its schema and write an empty cell (fixtures/gen.go writeIntake, which draws from its own seeded source so every other CSV stays byte-identical).
mmm_weekly.pulse A weekly media-mix series, two markets x 104 weeks (208 rows): market (categorical, east / west), week (u16), tv / radio / search / social spend, price / promo controls and sales (f64). Sales carry a TRUE geometric adstock decay of 0.5 on every channel plus a Hill saturation, so compose/08_mmm_decay_sweep.json ranks decay 0.5 first (TestExamples_MMMDecaySweepRanksTrueDecayFirst). Rows come from internal/mmmfixture (fixtures/gen.go writeMMMWeekly), the one source the acceptance suites share.
brand_survey.pulse A two-wave brand-perception survey (1200 respondents, 600 per wave): id (u32), wave (categorical, wave1 / wave2), q1-q3 (quality), v1-v3 (value), s1-s3 (service) (u8, 1-5) and recommend (u8, 0-10). Three correlated factors; wave 2's latent means are PLANTED — value −0.30 and service +0.70 factor SD (−0.24 / +0.525 in marker units), quality 0 — so a scalar-invariant multi-group MAT_SEM recovers the shift (matrices/16_sem_multigroup.json, compose/09_sem_invariance_sweep.json, TestExamples_SEMInvarianceLadderSweep); per-row latent scores from that fit average to the same shift by wave and drive recommend in an OLS (attributes/25_sem_score.json, compose/10_sem_fit_scores.json, TestExamples_SEMFitScoresFeedRegression); the ratings fitted as ordinal (WLSMV) recover the shift too (matrices/18_sem_ordinal.json, attributes/26_sem_ordinal_score.json, TestExamples_SEMOrdinalRecipe). Row for row the lavaan oracles' data: internal/brandfixture over internal/sem/testdata/brand_spec.json (fixtures/gen.go writeBrandSurvey).

The generator (fixtures/gen.go) is deterministic — re-running with the same seed produces byte-identical CSVs. Re-generate from scratch:

go run internal/examples/fixtures/gen.go
./internal/examples/fixtures/build.sh

Running

A category-specific runner exercises everything in its folder:

./internal/examples/attributes/run-all.sh
./internal/examples/features/run-all.sh
./internal/examples/filterers/run-all.sh
./internal/examples/groupers/run-all.sh
./internal/examples/windows/run-all.sh
./internal/examples/tests/run-all.sh

Or invoke individual requests:

bin/pulse api predict --request internal/examples/features/01_log_transform.json --json
bin/pulse api process --request internal/examples/features/01_log_transform.json --json

The _meta block

Every example JSON carries a top-level _meta object; it is stripped before the body is served or run (examples.Get), and request decoding ignores it.

Key Required Meaning
name yes unique example ID (pulse_examples_get name=...)
category yes must equal the parent directory
description yes one-sentence summary served by search
tags yes drawn from CanonicalTags
operators yes (may be []) exactly the "type": "AGG_/ATTR_/FILTER_/GROUP_/WIN_/FEAT_/TEST_/REG_..." values in the body (TestExamples_OperatorsMatchBody); overlay kinds ride overlays[].kind instead
intents expected a LIST of intent-taxonomy IDs (TestExamples_IntentsFromTaxonomy), even for one intent: ["describe"]
capabilities optional non-operator feature names in feature-profile spelling (capability:stream), for capabilities the body carries no structural signal for
question story only the plain-language question the example answers; declared together with interpretation
interpretation story only a qualitative reading of the result — no digit 0–9; the figures live in the story's golden

capabilities exists so an example is joined to every capability it needs by an explicit edge in the discovery graph rather than by a scan of its prose. The graph builder (internal/descriptor/ontology_examples.go) already DETECTS capability:crosstab (a crosstab key), capability:compose (a root requests), capability:process_chain (a root stages), capability:joins (a joins key) and capability:facet (category or tag facet) from the body, plus every overlays[].kind; declare the rest — capability:stream, watch, shard, index, sample, labels, range_tables, filter_to_file — in capabilities. An example with an empty operators list must declare at least one capability. Gates (internal/descriptor): TestExamples_CapabilitiesFromFeatures (every value is a known non-operator feature), TestExamples_EdgeCoverage (every operator a body or description names is an edge; a declared capability never contradicts its detector), and TestExamples_EmptyOperatorExamplesDeclareCapabilities.

Story examples

An example is a story iff its _meta declares both question and interpretation; one without the other is refused. A story's request sets "return": {"precision": 4} (examples.StoryPrecision, four significant digits), so a float's last few ulps — which differ between amd64 and arm64 — never reach its output. Rules: examples.StoryProblems, gated by TestStories_LibraryHoldsTheRules. They bind the shipped library only: an embedder example (Extensions.Examples) may declare question / interpretation, and pulse.New serves them as declared without applying these rules.

Each story's response is pinned by a harness-produced golden, testdata/stories/<name>.json — the response exactly as json.MarshalIndent writes it. The root package's TestExamples_StoryGoldens builds the fixture cohorts, runs every story and fails on a missing, extra or differing golden. Never hand-edit one; regenerate after changing a story or a fixture:

go test -count=1 . -run TestExamples_StoryGoldens -update

The goldens are embedded: examples.StoryGolden(name) returns one, so the generated docs quote real figures without executing a request.

Adding a new example category

  1. Pick a category name (e.g. windows, aggregation, attributes).
  2. Create internal/examples/<category>/ with a README.md and request *.json files.
  3. Each JSON sets cohort.data_dir = ".data" and references one of the shared cohort filenames above.
  4. If your category needs a field that's not in any shared cohort, add it to fixtures/gen.go and the matching schema in fixtures/schemas/. Re-run the generator and check in the new CSV.
  5. Drop in a run-all.sh for the category (copy from features/ and adjust the glob).
  6. Optionally add an end-to-end test in examples_test.go mirroring TestFeatureExamples_RunEndToEnd.

CI coverage

TestExamples_RunEndToEnd (in examples_test.go) builds the shared fixtures into a temp directory and runs every example across every category through pulse.Process, asserting no errors. Adding a new category is one line in the test's categories slice.

go test -run TestExamples -v .

One sub-test runs per example file, grouped by category.

Documentation

Overview

Package examples embeds the catalogue of runnable Pulse request JSON files and exposes a search/get API over them.

Every embedded JSON carries a top-level _meta block describing the example's name, category, taxonomy tags, the operators it uses, and a one-sentence description. Pulse's types.Request unmarshaler ignores unknown fields by default, so _meta is invisible at execution time — the examples remain runnable verbatim.

Get returns the example with the _meta block stripped, so callers can hand the JSON straight to pulse_process / pulse_predict.

Index

Constants

View Source
const StoryGoldenDir = "testdata/stories"

StoryGoldenDir is the directory, relative to this package, holding one harness-produced golden per story: <name>.json, the story response as json.MarshalIndent writes it. The root package's TestExamples_StoryGoldens writes it (-update) and compares it; never hand-edit one.

View Source
const StoryPrecision = 4

StoryPrecision is the `return.precision` (significant digits) every story request sets, so its golden is identical on every architecture: a few-ulp difference in a float's tail never reaches the wire.

Variables

View Source
var CanonicalTags = []string{

	"time-series", "cohort-analysis", "experiment-analysis", "correlation-analysis",
	"comparison", "before-after", "top-n", "distribution-shape", "cross-tabulation",
	"proportion-analysis", "trend-detection", "outlier-detection", "cardinality-analysis",
	"data-quality", "financial", "feature-engineering",

	"hypothesis-test", "t-test", "parametric", "nonparametric", "paired", "one-sample",
	"two-sample", "k-sample", "repeated-measures", "post-hoc",
	"normality-test", "homogeneity-test", "exact-test",

	"regression", "ecological",
	"ols", "glm", "logistic", "bayesian",
	"regularization", "ridge", "lasso", "elasticnet",
	"polynomial", "resampling", "jackknife", "selection", "stepwise",

	"tier-1-test", "tier-2-test", "composed", "pre-filter", "feature-pipeline",
	"window-operator", "streaming-friendly", "buffered-pipeline",

	"matrix", "covariance", "multivariate",

	"leakage-risk", "small-sample",

	"facet",

	"sharded", "anchor",

	"overlay",
	"byte-equal-test",
	"compose",
	"crosstab",
	"welch",
	"welford-triple",
	"z",
}

CanonicalTags is the curated taxonomy every annotated example must draw from. Kept here (rather than embedded in a separate file) so the validation gate can compare directly without round-tripping through a disk asset.

View Source
var ErrNoMeta = errors.New("missing _meta block")

ErrNoMeta is Parse's error for a JSON object without a _meta block.

Functions

func AllCategories

func AllCategories() []string

AllCategories returns every directory the library indexes, sorted alphabetically.

func AllTags

func AllTags() []string

AllTags returns every taxonomy tag the library currently uses, sorted alphabetically. Derived from the indexed examples — not the canonical allowlist — so callers see exactly what is tagged today.

func Capabilities

func Capabilities() map[string][]string

Capabilities returns every example's optional _meta.capabilities, keyed by example name; an example without the key is absent. Values are feature-profile spellings of non-operator features (`capability:stream`), validated by internal/descriptor (TestExamples_CapabilitiesFromFeatures), which this package cannot import. The key exists for capabilities a request body carries no structural signal for; internal/descriptor's ontology builder turns each value into an `example requires_capability <feature>` edge.

func Count

func Count() int

Count returns the number of embedded examples.

func DeriveOperators

func DeriveOperators(body []byte) []string

DeriveOperators returns the sorted, distinct operator names a body carries as a `"type"` value — what `_meta.operators` must equal (TestExamples_OperatorsMatchBody; embedder examples at pulse.New).

func Intents

func Intents() map[string][]string

Intents returns every example's optional _meta.intents, keyed by example name; an example without the key is absent. Values are validated against the intent taxonomy by internal/descriptor (TestExamples_IntentsFromTaxonomy), which this package cannot import.

func IsCanonicalTag

func IsCanonicalTag(tag string) bool

IsCanonicalTag reports whether tag belongs to the curated taxonomy.

func Parse

func Parse(data []byte, strict bool) (*Example, Meta, error)

Parse reads one example file: a JSON object carrying a _meta block plus the request body. It returns the Example — Body is the object minus _meta, re-marshaled deterministically — and the parsed Meta. strict refuses an unknown _meta key (embedder examples); the embedded library parses leniently. Parse does not validate Meta's values.

func Stories

func Stories() []string

Stories returns the name of every embedded story example, sorted alphabetically.

func StoryGolden

func StoryGolden(name string) ([]byte, bool)

StoryGolden returns the committed golden response of the named story example — read by the generated docs, which never execute a request. Returns false when no golden carries the name.

func StoryGoldenNames

func StoryGoldenNames() []string

StoryGoldenNames returns the name of every embedded story golden, sorted alphabetically.

func StoryProblems

func StoryProblems(m Meta, body []byte) []string

StoryProblems returns every way an example's _meta and request body break the story rules, empty when they hold. An example is a story iff it declares both question and interpretation; one without the other is a problem. A story's interpretation is qualitative — it carries no digit, the figures live in the golden — and its request sets `return.precision` to StoryPrecision. A non-story is never a problem.

func Tokenize

func Tokenize(s string) []string

Tokenize lower-cases s and splits it on every character that is not an ASCII letter or digit. No stemming; empty tokens are dropped.

Types

type Example

type Example struct {
	Name        string   `json:"name"`
	Category    string   `json:"category"`
	Tags        []string `json:"tags"`
	Operators   []string `json:"operators"`
	Description string   `json:"description"`
	// Intents is the example's _meta.intents (intent-taxonomy IDs);
	// absent on the wire when the example declares none.
	Intents []string `json:"intents,omitempty"`
	// Question and Interpretation are the example's _meta.question and
	// _meta.interpretation; both present makes it a story (Stories).
	Question       string          `json:"question,omitempty"`
	Interpretation string          `json:"interpretation,omitempty"`
	Body           json.RawMessage `json:"body"`
}

Example is the full record returned by Get. Body carries the request JSON with the _meta block stripped, so it can be handed verbatim to pulse_process / pulse_predict.

func All

func All() []*Example

All returns a copy of every embedded example, sorted by name.

func Get

func Get(name string) (*Example, bool)

Get returns the example with the given name. The returned Body is the request JSON minus the _meta field, runnable verbatim against pulse.Process. Returns false when no example carries the name.

type ExampleSummary

type ExampleSummary struct {
	Name        string   `json:"name"`
	Category    string   `json:"category"`
	Tags        []string `json:"tags"`
	Operators   []string `json:"operators"`
	Description string   `json:"description"`
	// Intents is the example's _meta.intents (intent-taxonomy IDs);
	// absent on the wire when the example declares none.
	Intents []string `json:"intents,omitempty"`
	// Question is the example's _meta.question: the plain-language
	// question a story example answers. Absent unless declared.
	Question string `json:"question,omitempty"`
	// Interpretation is the example's _meta.interpretation: a
	// qualitative reading of the story's result. Absent unless declared.
	Interpretation string `json:"interpretation,omitempty"`
}

ExampleSummary is the lightweight projection used by Search results.

func Search(query string, tags []string, category string) []ExampleSummary

Search returns summaries matching all three filters. An empty filter is treated as "no constraint" for that dimension. It is SearchQuery over the embedded library with no synonym tables; SearchQuery documents the matching rules. Never nil.

func SearchIn

func SearchIn(lib []*Example, query string, tags []string, category string) []ExampleSummary

SearchIn is Search over lib, which must be sorted by name (the no-query order and the score tie-break). An instance serving embedder examples searches the merged library through it.

func SearchLibrary

func SearchLibrary(q Query, opts Options) []ExampleSummary

SearchLibrary is SearchQuery over the embedded library.

func SearchQuery

func SearchQuery(lib []*Example, q Query, syn Options) []ExampleSummary

SearchQuery returns the summaries of lib matching q, ranked. lib must be sorted by name (the no-query order and the score tie-break).

Matching runs as ordered tiers; the first tier with any hit wins:

  1. exact — a query that is a single plain word (letters and digits only) keeps the legacy rule: a case-insensitive substring of the name, the description or any operator, so a one-word query answers exactly as before. Any other query is tokenized (lower-cased, split on non-alphanumerics, no stemming, common stop words dropped) and an example matches when every query token is an exact token of at least one of its fields (name, description, operators, intents, tags); a field counts when it holds any query token.
  2. synonym — a query phrase that is a Purpose.KnownAs alias expands the query to that operator, and a query phrase found inside an intent's Sound expands it to that intent. An example matches when its operators or intents carry an expansion; the fields matched by the expansions and by any query token count.
  3. fuzzy — typo tolerance, the last resort: every content query token (stop words and placeholders dropped) must match some field token either exactly or, when both tokens are fuzzable (longer than three characters), within fuzzyEdits(len(query token)) edits — insertions, deletions, substitutions and adjacent transpositions. "regon" finds "region"; a short token ("sum", "agg") never fuzzes.

Score = distinct matched fields; ties break alphabetically by name. No query lists every example passing the filters, alphabetically. Returns a non-nil empty slice when nothing matches.

type Meta

type Meta struct {
	Name        string   `json:"name"`
	Category    string   `json:"category"`
	Tags        []string `json:"tags"`
	Operators   []string `json:"operators"`
	Description string   `json:"description"`
	// Intents is optional; every value must be an intent-taxonomy ID
	// (validated by internal/descriptor's TestExamples_IntentsFromTaxonomy,
	// since this package cannot import the taxonomy).
	Intents []string `json:"intents,omitempty"`
	// Capabilities is optional; every value must be a non-operator
	// feature name (validated by internal/descriptor's
	// TestExamples_CapabilitiesFromFeatures).
	Capabilities []string `json:"capabilities,omitempty"`
	// Question is optional: the plain-language question the example
	// answers. Declared together with Interpretation (a story example);
	// in the shipped library one without the other fails StoryProblems
	// (CI only — an embedder example is never refused for it).
	Question string `json:"question,omitempty"`
	// Interpretation is optional: a qualitative reading of the result —
	// no digits, the figures live in the story's golden.
	Interpretation string `json:"interpretation,omitempty"`
}

Meta mirrors the _meta block every example JSON carries — built-in and embedder (pulse.Extensions.Examples) alike.

type Options

type Options struct {
	// Aliases maps a Purpose.KnownAs alias to the operator declaring it.
	Aliases map[string]string
	// Sounds maps an intent Sound to its intent ID.
	Sounds map[string]string
	// KeepIntent, when set, drops every _meta.intents value it refuses
	// from matching and from the returned summaries (an intent the
	// instance hides). Nil keeps all.
	KeepIntent func(id string) bool
	// KeepExample, when set, drops every example it refuses before any
	// tier runs, so a hidden example never decides which tier answers.
	KeepExample func(name string) bool
}

Options carries an instance's view into a search: the synonym tables of the synonym match tier and the visibility filters. Every table key is in internal/descriptor's FoldAlias form (lower-cased, whitespace collapsed, punctuation kept). The zero value searches the whole library with the synonym tier disabled.

type Query

type Query struct {
	Query    string   `json:"query,omitempty"`
	Tags     []string `json:"tags,omitempty"`
	Category string   `json:"category,omitempty"`
	Intent   string   `json:"intent,omitempty"`
}

Query is one example search: every filter optional, all ANDed.

  • Query is matched against an example's name, description, operators, _meta.intents and tags (see SearchQuery for the match tiers).
  • Tags is ANDed: an example must carry every requested tag.
  • Category is an exact directory match.
  • Intent is an intent-taxonomy ID the example's _meta.intents must carry. This package does not validate it (it cannot import the taxonomy); internal/descriptor refuses an unknown or hidden one before searching.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL