# Beava SDK reference — full plain-text version Concatenation of all SDK reference pages on beava.dev formatted for LLM agents that want the full surface in one fetch. See also the short structured index at https://beava.dev/sdk/llms.txt Generated by `beava-website/scripts/build-llms-txt.mjs` from the canonical HTML pages under `beava-website/project/sdk/`. Regenerate with `npm run build:llms` after page edits. Total pages: 12 ## Index - Quickstart — https://beava.dev/sdk/python/ - Server configuration — https://beava.dev/sdk/server/ - App client (bv.App) — https://beava.dev/sdk/python/app/ - @bv.event — https://beava.dev/sdk/python/event/ - @bv.table — https://beava.dev/sdk/python/table/ - bv.col / bv.lit — https://beava.dev/sdk/python/col-lit/ - Operator catalogue — https://beava.dev/sdk/python/operators/ - Errors — https://beava.dev/sdk/python/errors/ - POST /push — https://beava.dev/sdk/http/push/ - POST /get — https://beava.dev/sdk/http/get/ - POST /register — https://beava.dev/sdk/http/register/ - Wire spec — https://beava.dev/sdk/http/wire-spec/ ======================================================================== # Quickstart Source: https://beava.dev/sdk/python/ # Install. Push. Query. Install the beava server, install the Python SDK, push your first event and query the feature — in five minutes. ## Pick a path Most readers want the install path below; if you'd rather skip the server entirely and run beava in-process under your Python interpreter, embed mode is a one-line alternative. → **Run beava locally** (#install) — One docker run and you have an HTTP server on :8080. The whole flow fits in your terminal history. → **Use embed mode** (#embed) — bv.App() with no URL spawns a local binary on ephemeral ports. Best for tests and notebooks. **This is the SDK reference.** For the *why* — vision, concepts, recipes — see Docs (/docs/). For tutorials, Learn (/guide/). ## 01 Install beava You install two things: the **server** (the single binary that holds state) and the **Python client** (the SDK that talks to it). ### Server docker cargo from source terminal Copy ``` # persistent volume keeps your features across restarts docker run -d --name beava \ -p 8080:8080 -p 8081:8081 \ -v beava-data:/data \ beavadev/beava:edge # verify curl -X POST http://localhost:8080/ping # → {"pong":true,"registry_version":0} ``` Port `8080` is the HTTP data plane (push, get, batch_get, register, ping). Port `8081` is the framed-TCP fast-path (sub-millisecond JSON). Admin endpoints (`/health`, `/ready`, `/metrics`, `/registry`) live on a separate sidecar port that you opt into via the `--http-addr` / `--config` flags. terminal Copy ``` cargo install --git https://github.com/beava-dev/beava beava-server beava --memory-only # → HTTP listen : 127.0.0.1:8080 # → TCP listen : 127.0.0.1:8081 (enabled=true) ``` Requires Rust 1.74+. `--memory-only` skips the WAL — useful for kicking the tyres. Drop it for production (state lands under `./.beava/` by default). terminal Copy ``` git clone https://github.com/beava-dev/beava cd beava cargo run --release --bin beava ``` ### Python client terminal Copy ``` pip install "git+https://github.com/beava-dev/beava.git#subdirectory=python" ``` PyPI publish lands at v0.0.x — `pip install beava` will work then. For the v0.0.0 cut the SDK installs from the GitHub source above. Both URLs keep working after the PyPI cut. **Tip.** beava ships static. There's no JVM to size, no broker to configure, no schema registry to register against. If `curl -X POST :8080/ping` returns `{"pong":true,"registry_version":0}`, you're done. ## 02 Declare your first feature beava is declarative. You write a Python class for the **event source** and a function for the **table** (the per-entity feature you want to query). Every operator works the same way: `group_by(...).agg(name=bv.(...))`. site_features.py 12 lines ``` import beava as bv @bv.event class PageView: user_id: str path: str @bv.table(key="user_id") def UserStats(pv: PageView): return pv.group_by("user_id").agg( visits=bv.count(window="1h"), ) ``` Register it once. The server picks it up live — no restart. terminal Copy ``` python -c "import beava as bv; from site_features import *; \ bv.App('http://localhost:8080').register(PageView, UserStats)" # → {"status": "ok", "registry_version": 1, "added": ["PageView", "UserStats"]} ``` ## 03 Push events, read the feature beava speaks HTTP — every operation is a single request. You can drive it from Python or from `curl`; the wire is identical. request · push event Copy ``` curl -X POST \ http://localhost:8080/push \ -H "content-type: application/json" \ -d '{ "event": "PageView", "data": { "user_id": "alice", "path": "/home" } }' ``` response · 4 ms 200 OK ``` { "ack_lsn": 62, "idempotent_replay": false, "registry_version": 1 } ``` Now ask beava for the running feature: request · read feature Copy ``` curl -X POST \ http://localhost:8080/get \ -H "content-type: application/json" \ -d '{ "table": "UserStats", "key": "alice" }' ``` response · 0.6 ms 200 OK ``` { "visits": 2 } ``` The `/get` response is the row itself — a flat dict of feature name → value. **Cold-start** (no events for that key) returns `{}`, not an error — a cold key is a key with no data. ## App parameters Every `bv.App(...)` accepts the same shape. Pass an explicit URL or rely on embed mode (no URL → spawn local binary on ephemeral ports). url string | None Server URL. `http://...` / `https://...` for HTTP transport, `tcp://...` for the custom-framed TCP fast-path. `None` (the default) for embed mode — the SDK locates the `beava` binary on `$PATH` and spawns it. default `None` timeout float Per-request transport-level I/O timeout in seconds. default `30.0` test_mode bool Embed-mode only. Sets `BEAVA_TEST_MODE=1` in the spawned binary's env so test-only opcodes (`OP_RESET`) are accepted. Setting `test_mode=True` against a network URL emits a `UserWarning` and is ignored. default `False` ## Common questions Embed mode — what's the lifecycle? `bv.App()` (no URL) spawns the beava binary on ephemeral ports inside a context manager. The subprocess is torn down on `__exit__`. Calling any wire method on an embed-mode `App` outside `with` raises `RuntimeError`. ``` with bv.App() as app: app.register(PageView, UserStats) app.push("PageView", {"user_id": "alice", "path": "/home"}) print(app.get("UserStats", "alice")) ``` Each spawn allocates a unique tmpdir under `$TMPDIR/beava-embed---/`; cleaned up via `atexit`. What does the server hold? Does it persist events? The server holds **per-entity aggregates** — counters, velocities, sketches, last-seen — keyed by entity. It does **not** persist the raw events themselves; it persists the aggregates over them via WAL + periodic snapshot. If you need event replay, keep your raw events somewhere else (S3, your warehouse). beava is the live-feature server, not the event log. Cold-start for an unknown key — is that an error? No. `app.get("UserStats", "newuser")` returns `{}` (empty dict) with HTTP 200 when no events have ever been pushed for that key. This matches the Redis-shaped contract: a cold key is just a key with no data. `unknown_table` IS an error — that means the table name isn't registered. How does this compare to Redis? Redis is a key-value store you can *build* rolling counters on top of (with Lua + ZSETs + a lot of care). beava is a server that already *is* rolling counters — and velocities, leaderboards, last-N-seen, sketches — without you assembling the primitives. ## Where to go next You've got beava running and a counter ticking. Two reasonable next stops: → **All operators** (/sdk/python/operators/) — 55 purpose-built aggregation primitives — counters, sketches, velocities, decay, recency, geo. Same agg(...) shape, different math. → **Concepts** (/docs/) — Events vs tables, embed mode, lifetime aggregation, processing-time semantics, global aggregation. The five ideas you need to be productive. ======================================================================== # Server configuration Source: https://beava.dev/sdk/server/ # Server configuration CLI flags, environment variables, and YAML config — the full surface for spinning up a beava instance. CLI flags win over env vars; env vars win over YAML; YAML wins over the built-in defaults. ## Overview The `beava` binary boots a single-process feature server. With no flags, no env vars, and no config file present, it listens on `127.0.0.1:8080` (HTTP) and `127.0.0.1:8081` (TCP), persists state under `./.beava/`, and accepts events. Three layers tune it: - CLI flags (highest precedence) — every-day knobs for boot scripts and ad-hoc runs. - Environment variables — production-friendly overrides; great for container deployments. - YAML config (lowest precedence; opt-in via --config) — long-form settings you'd rather not encode in a shell command. There's no implicit `./beava.yaml` lookup. If you want to use a YAML config, point at it explicitly with `-c` / `--config`. three boot styles ``` # 1. Built-in defaults (good for first-touch + tests) beava # 2. CLI flags only (good for one-off runs) beava --http-addr 0.0.0.0:8080 --data-dir /var/lib/beava # 3. YAML + flag override (production) beava --config /etc/beava/beava.yaml --memory-only ``` ## CLI flags All flags are global — they work whether you boot the server (default) or run a subcommand like `beava quickstart`. usage ``` beava [OPTIONS] [COMMAND] ``` -c, --config path Load settings from a YAML config file. Optional. There's no implicit `./beava.yaml` lookup; if you want a config, point at one explicitly. The resolved config (which path was loaded — or whether built-in defaults applied) is logged at startup. no default — env + built-in defaults apply when omitted --http-addr host:port Override the HTTP data-plane listener address. Highest precedence — wins over `BEAVA_LISTEN_ADDR` and any `--config` YAML. default `127.0.0.1:8080` --tcp-addr host:port Override the TCP fast-path listener address. Highest precedence — wins over `BEAVA_TCP_HOST` / `BEAVA_TCP_PORT` and YAML. The TCP transport carries the same JSON envelope as HTTP but with sub-millisecond P99 latency on long-lived connections. default `127.0.0.1:8081` --data-dir path Override both WAL and snapshot directories under a single root: WAL lands at `/wal`, snapshots at `/snapshots`. Highest precedence — wins over `BEAVA_WAL_DIR` / `BEAVA_SNAPSHOT_DIR` and YAML. default `./.beava/` (so `./.beava/wal/` + `./.beava/snapshots/`) --memory-only bool flag In-memory only — no WAL writer, no periodic snapshot, no recovery on boot. State is lost on restart. Use for `docker run` smoke tests, demo boots, ephemeral CI runs, and any "I'm just kicking the tyres" workflow that shouldn't leave bytes on disk. default `false` (durable mode) --test-mode bool flag Enable `POST /reset` and `OP_RESET` — the destructive registry-wipe endpoint. Off by default; production deploys leave it off so they can't be wiped by accident. Equivalent to setting `BEAVA_TEST_MODE=1`; the flag wins if both are set. default `false` ## Subcommands When no subcommand is provided, `beava` boots the server. One subcommand is exposed in v0: ### beava quickstart [--no-file] beava quickstart [--no-file] Run the in-process 4-step first-touch demo. Spawns an in-process server on an ephemeral port, registers a `PageView` / `SiteMetrics` pipeline, pushes 5 events, queries the global row, prints a formatted walkthrough, and writes `beava_quickstart.py` to the current working directory. Zero setup, zero dependencies, completes in under 10 seconds. ### Flags - --no-file — don't write beava_quickstart.py. Useful for CI / docker-exec runs where leaving a file behind is noise. ### Example terminal Copy ``` beava quickstart # → 4-step demo runs, beava_quickstart.py lands in cwd beava quickstart --no-file # → demo runs, no file written ``` ## Environment variables Every `BEAVA_*` env var is overridable by a CLI flag of the same scope. Env vars are read once at startup; changes take effect on next boot. ### Listener BEAVA_LISTEN_ADDR HTTP listener address. overridden by `--http-addr` · default `127.0.0.1:8080` BEAVA_TCP_HOST TCP fast-path host. Set together with `BEAVA_TCP_PORT`. overridden by `--tcp-addr` · default `127.0.0.1` BEAVA_TCP_PORT TCP fast-path port. overridden by `--tcp-addr` · default `8081` ### Storage BEAVA_WAL_DIR Directory for the write-ahead log. Created if missing. Beava refuses to start on a network filesystem (NFS / CIFS) — point at local block storage. overridden by `--data-dir` · default `./.beava/wal/` BEAVA_SNAPSHOT_DIR Directory for periodic state snapshots. Recovery on boot replays from the most recent snapshot + WAL tail. overridden by `--data-dir` · default `./.beava/snapshots/` ### WAL tuning Three knobs shape the WAL's latency / durability / throughput tradeoff. Defaults are tuned for typical fraud-shape workloads; tweak only with measurements. BEAVA_WAL_BUFFERS Number of in-flight WAL buffers (active / sealed / flushing rotation). Higher values smooth out fsync tail latency but pin more memory. range `[2, 32]` · default `4` BEAVA_WAL_BUFFER_SIZE_MB Size of each WAL buffer in megabytes. Larger buffers seal less often; smaller buffers fsync more often. range `[4, 256]` · default `32` BEAVA_WAL_TICK_MS Maximum time the writer waits before flushing a partially-filled buffer. Lower values give tighter ack latency at higher fsync overhead. range `[1, 1000]` · default `20` ### Runtime BEAVA_TEST_MODE Set to `1` to enable `/reset` and `OP_RESET`. Equivalent to `--test-mode`; the flag wins if both are set. default *unset* (false) BEAVA_MEMORY_GOV_ENFORCE Whether the per-entity memory governor is enforced. Default `1` (enforced — over-budget pushes are throttled). Set to `0` to disable enforcement (governor still observes; you'll see WARN logs instead of throttling). default `1` BEAVA_IO_THREADS Number of admin-sidecar I/O worker threads. The data-plane runs single-threaded by design (Redis-shaped); this only sizes the admin runtime that serves `/health`, `/ready`, `/metrics`, `/registry`. default `1` BEAVA_LOG_LEVEL One of `trace`, `debug`, `info`, `warn`, `error`. Equivalent to YAML `log_level`. default `info` ### Debug-only Don't set these in production. They exist for incident response, performance profiling, and crash testing. BEAVA_TRACE_APPLY_TIMING Set to `1` to emit per-stage timing for every applied event (parse / validate / route / aggregate / WAL). Adds ~5-15% overhead; expect log volume to spike. BEAVA_CRASH_AT Crash-injection hook for recovery testing. Set to a known checkpoint name to abort the process at that point. ## YAML config The YAML config covers the long-form settings you'd rather not encode in a shell command. v0 keeps it small — listener address and log level. Everything else is set via flag or env. Point at it with `--config`; there's no implicit lookup. beava.yaml ``` # Address and port to bind the HTTP data plane to. listen_addr: "127.0.0.1:8080" # trace | debug | info | warn | error log_level: info ``` An example file lives at `beava.example.yaml` at the repo root. Copy and edit; nothing in the schema is required. ## Precedence When the same setting is configured at multiple layers, beava resolves in this order — first match wins: - CLI flag (e.g. --http-addr 0.0.0.0:8080) - Environment variable (e.g. BEAVA_LISTEN_ADDR=0.0.0.0:8080) - YAML config (e.g. listen_addr: "0.0.0.0:8080") — only loaded if --config is set - Built-in default (e.g. 127.0.0.1:8080) The resolved config is logged at startup. If beava's bound to a port you didn't expect, check the boot log line that names which layer produced the value. ## Default ports and paths With no flags, no env, no YAML: HTTP data plane `127.0.0.1:8080` TCP fast-path `127.0.0.1:8081` Admin sidecar `127.0.0.1:8090` — separate port for `/health`, `/ready`, `/metrics`, `/registry`. Kept off the data-plane port so admin scrapes don't share a runtime with hot-path requests. Working directory `./.beava/` — WAL at `./.beava/wal/`, snapshots at `./.beava/snapshots/`. The directory is created on first boot if missing. ## Common questions Why doesn't beava look for `./beava.yaml` automatically? Because `cargo install beava-server && beava` is the canonical first-touch path, and an implicit lookup would force every fresh install to pre-create a YAML file (or hit "config file not found"). The locked behavior: no YAML unless you ask for one with `-c`. Built-in defaults handle every other case. Can I run beava without writing to disk at all? Yes — `beava --memory-only`. Skips WAL, skips snapshots, skips recovery. State lives in process memory only and is lost on restart. Use it for tests, demos, and CI runs that shouldn't leave bytes behind. How do I bind to all interfaces in a container? Pass `--http-addr 0.0.0.0:8080` (and `--tcp-addr 0.0.0.0:8081` if you want the TCP fast-path reachable). The defaults bind to `127.0.0.1` so a fresh native install isn't accidentally exposed to the network. Why does WAL refuse a network filesystem? Because the WAL writer relies on `O_APPEND` + `fsync()` semantics that NFS / CIFS / FUSE-style mounts don't reliably honor. A successful `fsync()` on a network filesystem can return before bytes hit the persistence layer, breaking the durability contract. Beava detects the FS type at boot and refuses to start on a remote mount; point `--data-dir` at local block storage. Where are the admin endpoints? On a separate sidecar port (default `127.0.0.1:8090`). `/health`, `/ready`, `/metrics`, and `/registry` are served there — kept off the data-plane port so observability scrapes don't share a runtime with the hot-path event apply loop. ## Where to go next You've got beava running. Two reasonable next stops: → **App client** (/sdk/python/app/) — Drive your running server from Python. bv.App(url) + 7 wire-mapped methods. → **Wire spec** (/sdk/http/wire-spec/) — HTTP routes, TCP frame format, opcode table, content-type bytes — the full wire surface. ======================================================================== # App client (bv.App) Source: https://beava.dev/sdk/python/app/ # bv.App() — the client Synchronous Python client for the beava feature server. Seven wire-mapped methods plus a context-manager lifecycle. One transport per `App`; pick HTTP, TCP, or embed at construction time. ## Overview Every interaction with a running beava server flows through a single `bv.App` instance. The constructor picks a transport from the URL scheme; from then on, the seven methods below are 1:1 wire calls. signature ``` bv.App( url: str | None = None, *, timeout: float = 30.0, test_mode: bool = False, ) ``` Three transport modes, picked from the URL scheme: - http:// / https:// — JSON over HTTP/1.1 on the data-plane port (default 8080). - tcp:// — custom-framed TCP fast-path (default 8081). Strict-FIFO, one in-flight request per connection. - None — embed mode. The SDK locates the beava binary on $PATH and spawns it on ephemeral ports for the lifetime of a with block. **Embed mode requires a with block.** The spawned binary is torn down on context exit. Calling any method on an embed-mode `App` outside `with` raises `RuntimeError`. ## Constructor parameters url str | None Server URL. `http://...` / `https://...` for HTTP transport, `tcp://...` for the framed-TCP fast-path. `None` selects embed mode. default `None` timeout float Per-request transport-level I/O timeout in seconds. Applies to both HTTP and TCP transports. default `30.0` test_mode bool Embed-mode only. Sets `BEAVA_TEST_MODE=1` in the spawned binary's env so test-only opcodes (`OP_RESET`) are accepted. Setting `test_mode=True` against a network URL emits a `UserWarning` and is otherwise ignored — server-side configuration controls test mode for shared servers. default `False` An unrecognised URL scheme (anything other than `http` / `https` / `tcp` / `None`) raises `ValueError` at construction time. ## Methods Seven public methods. Each maps 1:1 to a wire opcode; the SDK does not batch, retry, or buffer on your behalf. ### register(*descriptors, force=False, dry_run=False) register(*descriptors: Any, force: bool = False, dry_run: bool = False) -> dict[str, Any] Register one or more event/table descriptors with the server. Hot-reloadable — the server picks up new pipelines without restarting; `registry_version` increments on each successful call. ### Args - *descriptors — descriptor objects produced by @bv.event or @bv.table. May also be plain dicts matching the wire shape (passthrough — used in tests). - force — replace any existing pipeline of the same name. - dry_run — server validates and returns a categorized diff payload ({diff, would_apply: false}) without committing. ### Returns The parsed server response — a flat dict whose shape varies by request: success body ``` { "status": "ok", "registry_version": 1, "added": ["PageView", "UserStats"], "already_present": [], "registered_descriptors": [ /* full registry snapshot */ ] } ``` ### Raises - RegistrationError — a passed descriptor is a raw EventDerivation (a chain expression that wasn't wrapped in @bv.event def F(...)). The error message includes the canonical rewrite. Also raised when the server returns a 4xx/5xx with a structured error body. ### Example register.py Copy ``` import beava as bv @bv.event class PageView: user_id: str path: str @bv.table(key="user_id") def UserStats(pv: PageView): return pv.group_by("user_id").agg( visits=bv.count(window="1h"), ) app = bv.App("http://localhost:8080") result = app.register(PageView, UserStats) print(result["registry_version"]) # → 1 ``` ### push(event_name, fields) push(event_name: str, fields: dict[str, Any]) -> dict[str, Any] Push a single event to the server. Ack-on-write — the server returns a write-ahead-log offset and a registry-version stamp on every push. ### Args - event_name — the registered event type's name (e.g. "PageView"). - fields — event fields as a plain dict. Keys must match the event's schema.fields; types are coerced where possible. ### Returns success body ``` { "ack_lsn": 62, "idempotent_replay": false, "registry_version": 1 } ``` `idempotent_replay` is `true` when the server identified this push as a re-delivery of a prior event (via the event's `dedupe_key`); the underlying state was not mutated. ### Raises - RegistrationError with code="event_not_found" — event_name isn't registered. - RegistrationError with code="schema_mismatch" — fields doesn't match the event's declared schema. - RegistrationError with code="invalid_event" — the request body is malformed JSON or missing required keys. ### Example push.py Copy ``` app.push("PageView", { "user_id": "alice", "path": "/home", }) # → {"ack_lsn": 62, "idempotent_replay": false, "registry_version": 1} ``` ### get(table, key=None, features=None) get( table: str, key: str | list[str | int | bool] | None = None, features: list[str] | None = None, ) -> dict[str, Any] Get a single feature row by entity key. Cold-start (no events for that key) returns `{}`, not an error. ### Args - table — the registered table's name. - key — entity key. Pass a string for single-column keys, a list for composite keys (matching the table's key=[...] declaration). None routes to the empty-string sentinel that addresses the single row of a global table (registered with key=[]). - features — narrow the response to the named subset. None (default) returns the full row. ### Returns A flat dict mapping feature name → value. Examples: request ``` app.get("UserStats", "alice") ``` response ``` { "visits": 2 } ``` cold-start request ``` app.get("UserStats", "newuser") ``` response ``` {} ``` ### Raises - RegistrationError with code="unknown_table" — table isn't registered. ### batch_get(requests) batch_get( requests: list[ tuple[str, str | list[str | int | bool]] | tuple[str, str | list[str | int | bool], list[str] | None] ], ) -> list[dict[str, Any]] Multi-key fetch in a single round-trip. Returns a list of rows in request order; cold-start per-entry is `{}`. ### Args - requests — list of per-entry tuples. Each entry is either (table, key) or (table, key, features). The 2-tuple form returns the full row; the 3-tuple form narrows to the named features. Both shapes can be mixed in the same call. ### Returns `list[dict[str, Any]]` — one row per request, in the order requests were submitted. ### Raises - TypeError — a request entry is neither a 2-tuple nor a 3-tuple. Raised client-side. - RegistrationError — server returned a structured error (e.g. one of the requested tables is unknown). ### Example batch_get.py Copy ``` rows = app.batch_get([ ("UserStats", "alice"), ("UserStats", "bob", ["visits"]), ]) # → [{"visits": 2}, {"visits": 0}] ``` ### reset() reset() -> None Wipe all server state — every registered descriptor, every per-entity aggregate. **Test-mode-gated.** Use it in tests, never in production. ### Behavior - In embed mode, test_mode=True is required at construction time so the spawned binary accepts OP_RESET. - In network mode, the server itself must be running with --test-mode; the SDK has no way to flip the flag remotely. - Returns None on success. ### Raises - RegistrationError with code="reset_disabled" — server is not in test mode. - RuntimeError — embed-mode App used outside its with block. ### Example test_setup.py Copy ``` with bv.App(test_mode=True) as app: app.register(PageView, UserStats) # run a test ... app.reset() # clean slate for the next test ``` ### ping() ping() -> dict[str, Any] Cheap liveness probe on the data plane. Returns the current registry version — useful as a cache-key invalidation / schema-evolution signal on long-lived connections. ### Returns success body ``` { "pong": true, "registry_version": 1 } ``` ### Raises - RegistrationError — non-200 from the server (defensively wrapped so callers don't deal with raw httpx exceptions). ### close() close() -> None Release the underlying transport (closes the HTTP connection pool, the TCP socket, or tears down the embed-mode subprocess). Idempotent — safe to call twice. Calling any wire method after `close()` raises `RuntimeError`. You normally don't call this directly: - __exit__ calls it (so with bv.App(...) is enough). - __del__ calls it (best-effort cleanup; suppressed exceptions). ## Lifecycle Network mode (`http`, `tcp`) is flexible — you can use the `App` as a long-lived module-level singleton or as a context manager. Embed mode **requires** a context manager so the spawned binary is torn down on exit. embed mode (with-required) ``` with bv.App() as app: app.register(PageView, UserStats) app.push("PageView", {...}) # subprocess torn down here ``` network mode (either form) ``` app = bv.App("http://localhost:8080") app.register(PageView, UserStats) # ... use it for the lifetime of the process app.close() # optional — __del__ also closes ``` Each embed-mode spawn allocates a unique tmpdir under `$TMPDIR/beava-embed---/` and registers an `atexit` hook to clean it up if the context manager isn't used. ## Common questions Is `App` thread-safe? The HTTP transport (httpx-backed) is thread-safe. The TCP transport is **not** — strict-FIFO at the protocol layer means one in-flight request per connection; sharing a TCP-mode `App` across threads will interleave frames and corrupt state. If you need TCP from multiple threads, give each thread its own `App`. Does the SDK retry? No. Each method is one wire call; transient transport errors propagate as `httpx`/socket exceptions. Retries belong in your application — beava's contract is that successful pushes are durable (WAL-acked), so you can safely re-push on connection loss. What's the async story? `bv.App` is sync. v0 doesn't ship an async client — wrap calls in `asyncio.to_thread(...)` from your event loop, or open multiple `App` instances in worker threads (HTTP transport is thread-safe). Can I use one `App` against two servers? No — one transport per `App`. Construct two `App` instances if you need to talk to two servers. Their state is independent. ## Where to go next You've got the client. The next thing to learn is what to register: → **@bv.event** (/sdk/python/event/) — Declare event sources — the typed inputs you push into beava. Covers the class form, the def form, and the optional kwargs (dedupe, retention, cold-after). → **@bv.table** (/sdk/python/table/) — Declare per-entity feature tables with group_by(...).agg(...). Composite keys, global tables, and the chain primitives. ======================================================================== # @bv.event Source: https://beava.dev/sdk/python/event/ # @bv.event — declare an event source Decorate a class to declare a typed event source, or a function to derive a new event from existing sources. The decorator carries the schema and optional retention / dedupe knobs onto the wire. ## Overview An **event** in beava is the typed input you push into the server. Every `app.push(...)` call references an event by name, and that name has to be registered first — either as a fresh source (class form) or as a derivation chained on top of an existing one (def form). The decorator has two shapes: - Class form — @bv.event class Click: .... Type annotations on the class body become the wire schema. - Def form — @bv.event def BigClick(click: Click): .... The function body returns a chain expression; the decorator captures it as a stable, addressable derivation. both forms Copy ``` import beava as bv # Class form — declares a fresh event source. @bv.event class Click: user_id: str page: str # Def form — derives a new event from the source above. @bv.event def BigClick(click: Click): return click.filter(bv.col("page") == "/checkout") ``` **Processing-time only.** The server stamps wall-clock time on every push. The decorator rejects an `event_time` class field and the `event_time_field` / `tolerate_delay` kwargs with `TypeError` at decorator time. ## Class form Apply `@bv.event` to a plain Python class. Each annotated attribute becomes a column in the wire schema; types are mapped `str → "str"`, `int → "i64"`, `float → "f64"`, `bool → "bool"`. Anything else is coerced to `"str"`. class form Copy ``` @bv.event class Login: user_id: str success: bool latency_ms: int ``` The decorator returns the same class with chain methods attached as static methods, so you can write `Login.filter(...)` or `Login.group_by(...).agg(...)` directly without instantiating it. The class also gains state attributes (`Login._name`, `Login._schema`, `Login._chain`, ...) that the SDK uses to walk the descriptor tree at register time. When you pass `Login` to `app.register(...)`, it serializes to: register node ``` { "kind": "event", "name": "Login", "schema": { "fields": { "user_id": "str", "success": "bool", "latency_ms": "i64" }, "optional_fields": [] } } ``` Once registered, push events by name: push.sh Copy ``` curl -X POST http://localhost:8080/push \ -H "content-type: application/json" \ -d '{"event": "Login", "data": {"user_id": "alice", "success": true, "latency_ms": 142}}' ``` ## Def form Apply `@bv.event` to a function that takes one or more decorated upstream events as parameters and returns a chain expression. The decorator captures the chain under the function's name, registering it as a derivation node on the wire. def form Copy ``` @bv.event class Click: user_id: str page: str @bv.event def CheckoutClick(click: Click): return click.filter(bv.col("page") == "/checkout") ``` **Why the def form exists.** The chain methods (`filter`, `select`, `with_columns`, ...) return anonymous `EventDerivation` objects with auto-generated names like `Click__derived_1`. Those auto-names are **not addressable** on the wire — the server's apply-time routing index keys derivations by their declared upstream name, and only stable names survive the round-trip. `@bv.event def` wraps a chain into a stable name (`"CheckoutClick"`) so downstream `@bv.table`s can declare it as their upstream and so you can push it by name from the client. If you pass a raw chain expression (e.g. `Click.filter(...).named("X")`) to `app.register(...)`, the SDK raises `RegistrationError` with the canonical rewrite — wrap it in `@bv.event def` instead. ### Constraints on the function body - Must declare at least one parameter; each parameter's annotation must resolve to an @bv.event-decorated class or function. - Must return an EventDerivation (the result of a chain method). Returning anything else raises TypeError. - The function body runs once at decorator time with the upstream descriptors as arguments. It is not invoked per push; the server replays the chain on every event. ## Optional kwargs The decorator-factory shape `@bv.event(...)` accepts per-source knobs. They are stored on the `EventSource` and forwarded to the server at register time. keep_events_for str | None Per-event retention window. Events older than this are eligible for compaction out of the per-entity event log. Accepts duration strings (`"30d"`, `"1h"`, `"15m"`). default `None` (server-wide default applies) cold_after str | None Idle threshold after which an entity that hasn't received this event is considered cold and may be evicted from hot memory. Accepts the same duration strings as `keep_events_for`. default `None` (server-wide default applies) dedupe_key str | None Name of a field whose value uniquely identifies a logical event. Pushes carrying a previously-seen `dedupe_key` within `dedupe_window` return `"idempotent_replay": true` and do not mutate state. default `None` (no dedupe) dedupe_window str | None Lookback window over which `dedupe_key` values are remembered. Required when `dedupe_key` is set. default `None` decorator-factory shape Copy ``` @bv.event( keep_events_for="30d", dedupe_key="id", dedupe_window="5m", ) class Login: id: str user_id: str ``` **Forbidden kwargs.** `event_time_field` and `tolerate_delay` raise `TypeError` at decorator time — v0 has no event-time. A class field literally named `event_time` is also rejected. ## Wire shape At register time the SDK serializes each `@bv.event` descriptor into a JSON node and posts the array as `{"nodes": [...]}` to the server. The class form emits a node with `kind: "event"`; the def form emits `kind: "derivation"` with the upstream's name and the chain ops. class form (event) ``` { "kind": "event", "name": "Click", "schema": { "fields": { "user_id": "str", "page": "str" }, "optional_fields": [] } } ``` def form (derivation) ``` { "kind": "derivation", "name": "CheckoutClick", "output_kind": "event", "upstreams": ["Click"], "ops": [ { "op": "filter", "expr": "page == '/checkout'" } ], "schema": { "fields": {...}, "optional_fields": [] } } ``` The full envelope and per-field semantics are documented at HTTP /register (/sdk/http/register/). ## Common questions Can I add fields after the event is registered? Yes. Re-decorate the class with the new annotation, call `app.register(MyEvent, force=True)`, and the server hot-swaps the schema; `registry_version` increments. Existing on-disk events keep their old schema — the server reconciles missing fields as `null` on read. What happens if I push a field that isn't in the schema? The server rejects the push with `code="schema_mismatch"`. There is no implicit schema-on-write; every field on a push has to be declared on the event. The SDK surfaces this as `RegistrationError` with the structured error body intact. Is `dedupe_key` exact-match? Yes — exact byte-for-byte equality on the value of the named field, scoped to the `dedupe_window`. There's no fuzzy match, no normalization, and no canonicalization. If you need normalized dedupe (e.g. lowercase emails), normalize the field upstream of the push and dedupe on the normalized value. Do I need `@bv.event def` if I already have a derivation chained inline inside a `@bv.table`? Not always. Inline chains inside the `@bv.table` body work for one-shot pipelines because the SDK flattens the chain to the root event source at register time. Use `@bv.event def` when you want a stable, addressable name — e.g. so two tables can share the same upstream derivation, or so you can push events by that name from the client. ## Where to go next You've declared the inputs. The next step is to declare the per-entity feature tables that aggregate them: → **@bv.table** (/sdk/python/table/) — Declare per-entity feature tables with group_by(...).agg(...). Composite keys, global tables, and the chain primitives. → **Operator catalogue** (/sdk/python/operators/) — The 40+ aggregation primitives — counters, velocities, distances, rates, distributions — that go inside an agg(...) block. ======================================================================== # @bv.table Source: https://beava.dev/sdk/python/table/ # @bv.table — declare a feature table A `@bv.table` is a per-entity feature row, keyed on one or more event columns and refreshed on every push. Inside the function you build a chain that ends in `agg(...)`; the decorator captures the key shape and wraps it as a registry-ready descriptor. ## Overview A table is the *output* side of an aggregation. You declare an event source with `@bv.event`, then declare a table that says “group those events by some key column(s) and roll them up into a row of features.” Each unique key gets its own row; `app.get("TableName", "alice")` returns alice’s row at sub-millisecond latency. tiny.py Copy ``` import beava as bv @bv.event class Click: user_id: str path: str @bv.table(key="user_id") def UserClicks(c: Click): return c.group_by("user_id").agg( clicks_1h=bv.count(window="1h"), ) ``` Three things are happening above: - The function UserClicks takes one annotated parameter — that annotation tells the decorator which event source feeds the table. - The body returns a chain expression that must end in agg(...); the decorator validates this. - The key="user_id" kwarg locks in the entity column. Every app.get("UserClicks", ) looks up that row. ## Signature signature ``` @bv.table( *, key: str | list[str] | tuple[str, ...] | None = None, ) def Foo(e: EventName): return e.group_by(...).agg(...) ``` Three call shapes are accepted: - @bv.table(key="user_id") — single-column key. - @bv.table(key=["user_id", "device_id"]) — composite key. - @bv.table (bare) or @bv.table() (empty parens) — global table; no key. Equivalent to key=[]. Anything else for `key=` raises `TypeError` at decorator time — the rejection lists what was passed and what the valid shapes are. **Function form only in v0.** `@bv.table` wraps `def` functions; class form is reserved for `@bv.event`. The body returns a chain — see The chain function (#chain). ## Single-column key The most common shape. Pass `key="col"` as a string; the decorator wraps it as `key_cols=["col"]` internally and emits `table_primary_key: ["col"]` on the wire (always a list, even for a single key). single_key.py Copy ``` @bv.event class Txn: user_id: str amount: float merchant: str @bv.table(key="user_id") def UserTxnFeatures(t: Txn): return t.group_by("user_id").agg( tx_count_1h=bv.count(window="1h"), tx_sum_1h=bv.sum(field="amount", window="1h"), tx_mean_1h=bv.mean(field="amount", window="1h"), tx_unique_merchants_1h=bv.n_unique(field="merchant", window="1h"), ) ``` Look up a row with the key as a plain string: request ``` app.get("UserTxnFeatures", "alice") ``` response ``` { "tx_count_1h": 3, "tx_sum_1h": 42.10, "tx_mean_1h": 14.03, "tx_unique_merchants_1h": 2 } ``` ## Composite key Pass `key=["a", "b", ...]` when one column isn’t enough to uniquely address an entity. The chain’s `group_by(...)` arguments must mirror the key list — they’re what the server uses to bucket events at apply time. composite_key.py Copy ``` @bv.event class Login: user_id: str device_id: str ip: str @bv.table(key=["user_id", "device_id"]) def UserDeviceStats(l: Login): return l.group_by("user_id", "device_id").agg( logins_24h=bv.count(window="24h"), unique_ips_24h=bv.n_unique(field="ip", window="24h"), ) ``` The wire shape carries `table_primary_key` as a list in declaration order, matching the `group_by` column order. To look up a composite-keyed row, pass a list to `app.get`: request ``` app.get("UserDeviceStats", ["alice", "iphone-15"]) ``` response ``` { "logins_24h": 7, "unique_ips_24h": 2 } ``` `tuple` is also accepted (`key=("user_id", "device_id")`) and normalized to a list internally. Order is meaningful — it determines the column order used to compose the entity key at lookup time. ## Global table When you want a single feature row that summarizes *everything* — site-wide rolling counters, fleet-wide error rates, top-line dashboards — declare a global table. Three equivalent forms: global.py Copy ``` # All three forms produce the same descriptor — key_cols=[]. @bv.table def SiteTotals(c: Click): return c.agg(total_clicks_1h=bv.count(window="1h")) @bv.table() def SiteTotals2(c: Click): return c.agg(total_clicks_1h=bv.count(window="1h")) @bv.table(key=[]) def SiteTotals3(c: Click): return c.agg(total_clicks_1h=bv.count(window="1h")) ``` A global table’s single row is addressed by the **empty-string sentinel entity id**. `app.get("SiteTotals")` with no `key` argument routes to that sentinel automatically: request ``` app.get("SiteTotals") ``` response ``` { "total_clicks_1h": 14823 } ``` Pushes flow into a global table the same way they flow into a keyed one — fire-and-forget, processing-time, ack-on-write: push.sh Copy ``` curl http://localhost:8080/push \ -H "content-type: application/json" \ -d '{"event": "Click", "data": {"user_id": "alice", "path": "/"}}' ``` ## The chain function The function body of an `@bv.table` is a *chain builder*. The decorator calls it once at registration time, passing in proxy objects resolved from your parameter annotations, and inspects the returned chain expression. Two contracts: - Every parameter must be annotated with the upstream event class (or a @bv.event-decorated derivation function). Missing annotations raise TypeError at decorator time, pointing straight at the unannotated parameter. - The return value must end in agg(...). Anything else (a bare filter, a dangling with_columns, a non-chain object) raises TypeError with the canonical rewrite hint. chain_with_filter.py Copy ``` @bv.table(key="user_id") def HighValueUserStats(t: Txn): return ( t.filter(bv.col("amount") > 100.0) .group_by("user_id") .agg( big_tx_count_24h=bv.count(window="24h"), big_tx_sum_24h=bv.sum(field="amount", window="24h"), ) ) ``` Chain methods you can compose before the terminal `agg`: `filter`, `select`, `drop`, `rename`, `with_columns`, `cast`, `fillna`, `group_by`. The terminal call must be `agg(...)`; otherwise the descriptor is classified as an event-derivation (`output_kind="event"`) and belongs under @bv.event (/sdk/python/event/), not `@bv.table`. **Processing-time only.** Aggregation windows (`window="1h"`, `"24h"`, `"forever"`, ...) are walltime-relative on the server. Beava v0 does not support event-time / watermarks; declaring an `event_time` field on the upstream `@bv.event` raises `TypeError` at decorator time. ## Wire shape At `app.register(...)` time, every `@bv.table` descriptor is serialized into a node on the registry payload. The shape: node JSON ``` { "kind": "derivation", "name": "UserTxnFeatures", "output_kind": "table", "upstreams": ["Txn"], "ops": [ { "op": "group_by", "keys": ["user_id"], "agg": { "tx_count_1h": { "op": "count", "params": { "window": "1h" } }, "tx_sum_1h": { "op": "sum", "params": { "field": "amount", "window": "1h" } } } } ], "schema": { "fields": { "tx_count_1h": "i64", "tx_sum_1h": "f64" }, "optional_fields": [] }, "table_primary_key": ["user_id"] } ``` Three things to notice: - kind: "derivation" always; output_kind: "table" is the discriminator that says “this lands as a feature row,” not as an event. - table_primary_key is always a list. Single-column keys ship as ["user_id"]; composite keys ship as ["user_id", "device_id"]; global tables ship as []. - upstreams is the list of event sources this derivation reads. The flatten rules in the SDK ensure this is always a root @bv.event source name, never an intermediate __derived_ step. The full registry payload — the wrapper around `nodes`, additional flags like `force` / `dry_run`, the response body — is documented on POST /register (/sdk/http/register/). ## Common questions Can a table key contain dots or slashes? Yes — the column *name* is restricted by your `@bv.event` schema, but the column *value* at lookup time is treated as an opaque string. `app.get("UserClicks", "a.b/c")` works fine. The wire encoding is JSON, so any UTF-8 string is permitted; the empty string is the global-table sentinel and not a valid entity id for keyed tables. What if my key column has nulls? The server treats `null` as a distinct bucket — events with a null key value land in their own row, addressable by passing `None` for that key column. If you’d rather reject them, add a `filter(bv.col("user_id").is_not_null())` step in front of the `group_by`; if you’d rather replace them, use `fillna(user_id="anonymous")` earlier in the chain. Does the table refresh on event arrival or on read? On arrival. Every `app.push(...)` applies the event to every aggregation that names its source as an upstream — atomically, on the data plane, before the push is acked. Reads are pure lookups: `app.get` returns the row as it exists at that instant, no recompute, no fan-out, no quorum. That’s what makes batch-get sub-millisecond. Can one table read from multiple event sources? One upstream per table. The function takes one annotated parameter and the chain builds off that one source. Joins and unions are not part of the v0 surface. ## Where to go next You can declare tables; the next two stops are the operators that fill them and the client that pushes events at them: → **Operator catalogue** (/sdk/python/operators/) — The 40+ aggregation primitives — count, sum, mean, n_unique, quantiles, sketches, velocities, distances. Each one’s wire shape, params, and memory cost. → **App client** (/sdk/python/app/) — The synchronous Python client. register, push, get, batch_get, plus the embed-mode lifecycle for tests. ======================================================================== # bv.col / bv.lit Source: https://beava.dev/sdk/python/col-lit/ # bv.col — column expressions `bv.col` references a schema field; `bv.lit` wraps a Python constant. Together they build the operator-overloaded `_Expr` AST that powers `where=` predicates, `with_columns` derivations, and operator field selection in the chain DSL. ## Overview Every predicate in beava — every `where=` kwarg, every filter clause, every derived-column expression — is built from two primitives: `bv.col(name)` for a field reference, and `bv.lit(value)` for a constant. Combine them with Python operators (`==`, `>`, `&`, `|`, `~`) to produce an `_Expr` AST node. The AST is inert at construction time; the server's expression parser evaluates it at push time. filter on a predicate ``` bv.count( window="1h", where=bv.col("amount") > 100, ) ``` derived column ``` pv.with_columns( is_premium=bv.col("plan") == bv.lit("premium"), ) ``` Both helpers return `_Expr` nodes (subclasses `_Col` and `_Literal`). `_Expr` overloads Python's comparison, arithmetic, and bitwise operators to grow the AST; you never construct nodes by hand. ### bv.col(name) bv.col(name: str) -> _Col Reference a schema field by name. Returns an `_Expr` — an unbound expression node that participates in operator overloads. The lookup is unresolved until the expression reaches the server; `bv.col("nonexistent")` only fails at register / push time when the schema check runs. ### Args - name — the field name as declared on the upstream event class. Composite keys are addressed by their per-column names; there is no nested-field accessor. ### Returns `_Col` — a frozen-dataclass `_Expr` node. Hashable, immutable, safe to reuse across multiple chain expressions. ### Example col.py Copy ``` import beava as bv amount = bv.col("amount") expr = amount > 100 print(expr.to_expr_string()) # → '(amount > 100)' ``` ### bv.lit(value) bv.lit(value: int | float | str | bool | None) -> _Literal Wrap a Python constant as an explicit literal expression. The implicit form (`bv.col("a") > 100`) and the explicit form (`bv.col("a") > bv.lit(100)`) are wire-equivalent inside operator overloads — Python's dispatch coerces the right-hand side automatically. `bv.lit` is required when the literal stands on its own (a constant column in `with_columns`, the left-hand side of an arithmetic expression, or the only operand of a derivation). `bv.lit` is the canonical way to write a comparison-against-constant in any `where=` kwarg — bare strings are rejected (see the where= contract (#where)). ### Args - value — a Python scalar. Accepted types: int, float, str, bool, None. Other types (e.g. list, dict, custom classes) are not supported by the server's expression grammar. ### Returns `_Literal` — a frozen-dataclass `_Expr` node. Renders to the wire-grammar form: single-quoted strings, `true`/`false` for booleans, `null` for `None`. ### Example lit.py Copy ``` import beava as bv bv.lit(42).to_expr_string() # → '42' bv.lit("web").to_expr_string() # → "'web'" bv.lit(None).to_expr_string() # → 'null' bv.lit(True).to_expr_string() # → 'true' ``` ## Expression DSL An `_Expr` grows by operator overload. Every overload returns a new `_Expr` — the AST is immutable, so re-using a node in multiple chains is safe. ### Comparison Each comparison operator emits a `_BinOp` node. Both operands are `_Expr`; bare Python literals on either side are auto-wrapped via `_coerce`. == != _Expr × _Expr → _Expr Equality and inequality. `bv.col("plan") == bv.lit("premium")` renders as `(plan == 'premium')`. < <= > >= _Expr × _Expr → _Expr Ordered comparison. Numeric on both sides; the server rejects ordered comparison of strings. ### Logical combinators Python's `and` / `or` can't be overloaded — they short-circuit on truthiness. Beava overloads `&` / `|` instead and serializes them as the server-grammar keywords `and` / `or`. **Always parenthesize** — Python's bitwise operators bind tighter than comparison. & _Expr × _Expr → _Expr Logical AND. Wire form: `(left and right)`. | _Expr × _Expr → _Expr Logical OR. Wire form: `(left or right)`. ~ _Expr → _Expr Logical NOT. Wire form: `!(operand)`. combinators.py Copy ``` expr = (bv.col("amount") > 100) & (bv.col("plan") == "premium") expr.to_expr_string() # → "((amount > 100) and (plan == 'premium'))" negated = ~(bv.col("path") == "/health") negated.to_expr_string() # → "!((path == '/health'))" ``` ### Methods .cast(target) str → _Expr Cast the operand to one of `"str"`, `"int"`, `"float"`, `"bool"`. Any other target raises `ValueError` at construction time (client-side guard). Wire form: `cast(operand, target)`. .isnull() () → _Expr Null-check. Wire form: `(operand == null)`. Combine with `~` for an "is not null" check: `~bv.col("x").isnull()`. .to_expr_string() () → str Render the AST to its wire-grammar JSON form. Stable string representation; safe to use in tests. ## The where= contract Every kwarg that takes a predicate — every aggregation operator's `where=`, every filter clause — accepts an `_Expr` and only an `_Expr`. Bare strings are rejected. The check lives in `_serialize_where` on every aggregation operator: anything that isn't `None` or an `_Expr` raises `TypeError` client-side, before a single byte hits the wire. rejected — bare string ``` bv.count(where="amount > 0") # TypeError: where= must be an _Expr or None; # got str ``` canonical — _Expr ``` bv.count(where=bv.col("amount") > 0) # wire: where = "(amount > 0)" ``` **Why bare strings are blocked.** A free-form predicate string would force the SDK to either ship a Python-side parser (hidden complexity, divergence risk against the server grammar) or pass the string through unchecked (typos surface only at push-time on the server). The `_Expr` AST removes both failure modes: it parses at construction, renders deterministically, and refactors statically. ## Common questions Why do I need `bv.lit` for constants? Polars does this automatically. Inside an operator overload (e.g. `bv.col("a") > 100`), Python's dispatch *does* auto-coerce the right-hand side via `_coerce`. `bv.lit` is needed when the literal isn't on the right side of an overload — for instance, when assigning a constant column in `with_columns` (no operator to dispatch through). Pick whichever reads better; both render to the same wire form. Can I use Python's `and` / `or`? No — Python forbids overloading `and` / `or` (they short-circuit on truthiness, not on operand types). The SDK overloads `&` / `|` instead and serializes them as the server-grammar keywords `and` / `or`. Always parenthesize each side: `(a == 1) & (b > 0)`, not `a == 1 & b > 0` — Python's bitwise operators bind tighter than comparison. Does `.cast` allow lossy conversions? The client-side guard only validates the target name — one of `"str"`, `"int"`, `"float"`, `"bool"`. The server applies the actual conversion at push time and rejects values that can't be represented (e.g. `cast("not-a-number", int)`). Lossy numeric casts (`float → int`) follow the server's coercion rules; check the operator catalogue's "type coercion" notes for the exact behaviour per call-site. Can I reuse the same `_Expr` in multiple operators? Yes. `_Expr` subclasses are frozen dataclasses — the AST is immutable, so a single expression node can appear inside several aggregations safely. Build it once at module scope and pass it to each `where=` kwarg. ## Where to go next You know how to reference and constrain. The next thing to learn is what to apply expressions to: → **Operator catalogue** (/sdk/python/operators/) — Every aggregation primitive — count, sum, mean, n_unique, top_k, ewma, plus the windowed and time-decay operators — and their where= / field= conventions. → **@bv.table** (/sdk/python/table/) — Per-entity feature tables built with group_by(...).agg(...). Composite keys, global tables, and the chain primitives that consume your bv.col / bv.lit expressions. ======================================================================== # Operator catalogue Source: https://beava.dev/sdk/python/operators/ # Operator catalogue Fifty-five aggregation primitives across seven families. Every operator is a function you call inside `agg(name=bv.(...))`; the family changes what gets remembered, the shape stays the same. ## Overview Every operator is a function in the `bv` namespace that returns an `AggDescriptor`. You never construct one directly — you call it inside the `agg()` step of a chain, and the keyword you bind it to becomes the column name in the resulting feature table. shape ``` import beava as bv @bv.event class PageView: user_id: str spend: float @bv.table(key="user_id") def UserStats(e: PageView): return e.group_by("user_id").agg( visits=bv.count(window="1h"), spend_avg=bv.mean("spend", window="24h"), ) ``` Three argument shapes show up across the catalogue: - Field-bearing — the first positional arg is a string column name (bv.sum("amount", ...)). Passing an _Expr raises RegistrationError(code="schema_mismatch") at register time; build the derived column upstream with with_columns. - Fieldless — counts, recency probes, and ratios that don't reference a column (bv.count(...), bv.first_seen(), bv.has_seen()). - Bound — a memory-bound argument is required: window="" (rolling), half_life="" (exponential decay), or a per-op cap (k=, n=, samples=, buckets=[…]). Durations are strings matching `\d+(ms|s|m|h|d)` or the literal `"forever"`. All optional `where=` kwargs accept a `bv.col(...)` expression and filter the operator's input on a per-event basis. ## At a glance Seven families, grouped by what each one remembers about the entity: | Family | Count | What it remembers | | --- | --- | --- | | Core | 11 | Counts, sums, extremes, the basics. count, sum, mean, min, max, var, std, ratio, n_unique, first, last. | | Sketch | 10 | Bounded-memory shape estimators — quantiles, histograms, top-k, sampled buffers. | | Recency | 10 | Time-since-last-X probes, streaks, ever-seen flags. Cheap, scalar, no per-event memory. | | Decay | 6 | Exponentially-weighted aggregates and time-weighted average. half_life= instead of window=. | | Velocity | 9 | Rate-of-change, trends, residuals, z-scores, burst and outlier counters. | | Buffer | 4 | Bounded ordered buffers — first-N, last-N, lag, delta-from-previous. | | Geo | 4 | Lat/lon-pair operators built on the haversine formula. lat= + lon= name the coordinate columns. | ## Core The basics. Counters, sums, extremes, ratios. Most accept an optional rolling `window=` kwarg; omit it for lifetime-cumulative behavior. ### count(window=None, where=None) count(*, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Number of events in the rolling `window` (or the entity's lifetime when `window=None`). Returns `i64`. - window — rolling window like "1h", "24h", "7d". Optional. - where — optional filter; only matching events are counted. count.pyCopy ``` e.group_by("user_id").agg( visits_1h=bv.count(window="1h"), failed_1h=bv.count(window="1h", where=bv.col("status") == "fail"), ) ``` ### sum(field, window=None, where=None) sum(field: str, *, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Sum of `field` over the window. Returns `f64`. - field — string column name. Passing an expression raises RegistrationError(code="schema_mismatch"). - window — rolling duration; optional. - where — optional row filter. sum.pyCopy ``` e.group_by("user_id").agg( spend_24h=bv.sum("amount", window="24h"), ) ``` ### mean(field, window=None, where=None) mean(field: str, *, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Arithmetic mean of `field`. Returns `f64`. mean.pyCopy ``` e.group_by("user_id").agg( avg_amount_1h=bv.mean("amount", window="1h"), ) ``` ### min(field, window=None, where=None) min(field: str, *, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Smallest value of `field` seen. Output type inherits from the upstream column (`i64` / `f64` / `str`). min.pyCopy ``` e.group_by("user_id").agg( min_amount=bv.min("amount", window="7d"), ) ``` ### max(field, window=None, where=None) max(field: str, *, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Largest value of `field`. Output type inherits from the upstream column. max.pyCopy ``` e.group_by("user_id").agg( max_amount=bv.max("amount", window="7d"), ) ``` ### var(field, window=None, where=None) var(field: str, *, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Population variance of `field`. Returns `f64`. var.pyCopy ``` e.group_by("user_id").agg( spend_var_24h=bv.var("amount", window="24h"), ) ``` ### std(field, window=None, where=None) std(field: str, *, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Standard deviation of `field`. Returns `f64`. std.pyCopy ``` e.group_by("user_id").agg( spend_std_24h=bv.std("amount", window="24h"), ) ``` ### ratio(window=None, where=None) ratio(*, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Server-computed ratio `matched / total` over the window. The `where=` expression filters the numerator only; the denominator is the unfiltered event count. Returns `f64`. ratio.pyCopy ``` e.group_by("user_id").agg( failure_rate_1h=bv.ratio( window="1h", where=bv.col("status") == "fail", ), ) ``` ### n_unique(field, window=None, where=None) n_unique(field: str, *, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Approximate distinct-value count for `field`, computed with HyperLogLog. Returns `i64`. n_unique.pyCopy ``` e.group_by("user_id").agg( distinct_ips_24h=bv.n_unique("ip", window="24h"), ) ``` ### first(field) first(field: str) -> AggDescriptor Value of `field` at the first event seen for the entity. Lifetime only — no `window=`. Output type inherits from the upstream column. first.pyCopy ``` e.group_by("user_id").agg( signup_country=bv.first("country"), ) ``` ### last(field) last(field: str) -> AggDescriptor Value of `field` at the most recent event. Lifetime only. Output type inherits from the upstream column. last.pyCopy ``` e.group_by("user_id").agg( last_country=bv.last("country"), ) ``` ## Sketch Bounded-memory shape estimators. Each carries its own bound — `k=`, `n=`, `samples=`, or a fixed `buckets=` list — so per-entity memory stays predictable. ### quantile(field, q, window=None, where=None) quantile(field: str, *, q: float, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Approximate quantile of `field` at probability `q` (open interval `(0, 1)`). Returns `f64`. - q — required float in (0, 1); e.g. 0.5 for the median, 0.99 for P99. quantile.pyCopy ``` e.group_by("user_id").agg( p99_latency_1h=bv.quantile("latency_ms", q=0.99, window="1h"), ) ``` ### top_k(field, k, window=None, where=None) top_k(field: str, *, k: int, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Top-K most frequent values of `field` (count-min sketch + min-heap). Returns a JSON-string payload of `[{value, count}, ...]`. - k — required positive integer; the heap size. top_k.pyCopy ``` e.group_by("user_id").agg( top_paths_1h=bv.top_k("path", k=5, window="1h"), ) ``` ### bloom_member(field, window=None, where=None) bloom_member(field: str, *, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Bloom-filter membership probe. Server compares the current event's `field` against the filter accumulated for the entity. Returns `bool` (false-positive-bounded). bloom_member.pyCopy ``` e.group_by("user_id").agg( seen_ip_before=bv.bloom_member("ip", window="30d"), ) ``` ### entropy(field, window=None, where=None) entropy(field: str, *, window: str | None = None, where: _Expr | None = None) -> AggDescriptor Shannon entropy of `field`'s value distribution (bits). Returns `f64`. Useful for "is this user spread across many values, or dialed in on a few." entropy.pyCopy ``` e.group_by("user_id").agg( path_entropy_1h=bv.entropy("path", window="1h"), ) ``` ### histogram(field, buckets, where=None) histogram(field: str, *, buckets: list[float], where: _Expr | None = None) -> AggDescriptor Lifetime fixed-bucket count histogram of `field`. Returns a JSON-string payload of bucket counts. Lifetime-only — no `window=`; the bound is the bucket list itself. - buckets — required strictly-increasing list[float] of split points. histogram.pyCopy ``` e.group_by("user_id").agg( spend_dist=bv.histogram("amount", buckets=[10, 100, 1000, 10000]), ) ``` ### hour_of_day_histogram(where=None) hour_of_day_histogram(*, where: _Expr | None = None) -> AggDescriptor Lifetime 24-bucket per-hour event-count histogram (UTC hour). Fieldless. Returns a JSON-string payload. hour_of_day_histogram.pyCopy ``` e.group_by("user_id").agg( activity_by_hour=bv.hour_of_day_histogram(), ) ``` ### dow_hour_histogram(where=None) dow_hour_histogram(*, where: _Expr | None = None) -> AggDescriptor Lifetime 168-bucket histogram keyed by `(day_of_week, hour)`. Fieldless. Returns a JSON-string payload. dow_hour_histogram.pyCopy ``` e.group_by("user_id").agg( weekly_pattern=bv.dow_hour_histogram(), ) ``` ### event_type_mix(field, categories=None, max_categories=256, where=None) event_type_mix( field: str, *, categories: list[str] | None = None, max_categories: int = 256, where: _Expr | None = None, ) -> AggDescriptor Lifetime proportion-per-category sketch over `field`. Returns a JSON-string payload. Bounded by `max_categories`; pass an explicit `categories` allowlist to lock the bucket set. - categories — optional allowlist; takes precedence over the cap-and-drop path. - max_categories — fallback bound when categories is unset (default 256). event_type_mix.pyCopy ``` e.group_by("user_id").agg( action_mix=bv.event_type_mix( "action", categories=["view", "click", "purchase"], ), ) ``` ### most_recent_n(field, n, where=None) most_recent_n(field: str, *, n: int, where: _Expr | None = None) -> AggDescriptor The `n` most recent values of `field`, newest-first. Lifetime, capped at `n`. Returns a JSON-string array. - n — required positive integer; the buffer size. most_recent_n.pyCopy ``` e.group_by("user_id").agg( last_5_paths=bv.most_recent_n("path", n=5), ) ``` ### reservoir_sample(field, samples, where=None) reservoir_sample(field: str, *, samples: int, where: _Expr | None = None) -> AggDescriptor Lifetime Vitter Algorithm-R reservoir sample of `field`. Returns a JSON-string array of length up to `samples`. - samples — required positive integer; the reservoir size. reservoir_sample.pyCopy ``` e.group_by("user_id").agg( amount_sample=bv.reservoir_sample("amount", samples=100), ) ``` ## Recency "How long ago" and "how many in a row." These are scalar probes — they don't keep per-event history, so they're cheap. ### first_seen() first_seen() -> AggDescriptor Wall-clock millisecond timestamp of the first event for the entity. Returns `i64`. Fieldless, no kwargs. first_seen.pyCopy ``` e.group_by("user_id").agg( signup_ts=bv.first_seen(), ) ``` ### last_seen() last_seen() -> AggDescriptor Wall-clock ms timestamp of the most recent event. Returns `i64`. last_seen.pyCopy ``` e.group_by("user_id").agg( last_active_ts=bv.last_seen(), ) ``` ### age() age() -> AggDescriptor Query-time elapsed milliseconds since `first_seen`. Returns `i64`. Computed at `get` time, not at push time. age.pyCopy ``` e.group_by("user_id").agg( account_age_ms=bv.age(), ) ``` ### has_seen(where=None) has_seen(*, where: _Expr | None = None) -> AggDescriptor Boolean flag — has the entity ever produced a matching event? Returns `bool`. Fieldless; the predicate goes in `where=`. has_seen.pyCopy ``` e.group_by("user_id").agg( ever_failed=bv.has_seen(where=bv.col("status") == "fail"), ) ``` ### time_since(where=None) time_since(*, where: _Expr | None = None) -> AggDescriptor Query-time elapsed milliseconds since the most recent matching event. Returns `i64`. time_since.pyCopy ``` e.group_by("user_id").agg( ms_since_failure=bv.time_since(where=bv.col("status") == "fail"), ) ``` ### time_since_last_n(n, where=None) time_since_last_n(*, n: int, where: _Expr | None = None) -> AggDescriptor Query-time elapsed milliseconds since the *n*-th most recent matching event — silence relative to a buried event, not just the latest. Returns `i64`. - n — required positive integer; rank from the latest. time_since_last_n.pyCopy ``` e.group_by("user_id").agg( ms_since_3rd_login=bv.time_since_last_n(n=3), ) ``` ### streak(where=None) streak(*, where: _Expr | None = None) -> AggDescriptor Current run length of consecutive *matching* events. Resets on the first non-match. Returns `i64`. streak.pyCopy ``` e.group_by("user_id").agg( consec_failures=bv.streak(where=bv.col("status") == "fail"), ) ``` ### max_streak(where=None) max_streak(*, where: _Expr | None = None) -> AggDescriptor All-time peak streak length. Returns `i64`. max_streak.pyCopy ``` e.group_by("user_id").agg( worst_failure_run=bv.max_streak(where=bv.col("status") == "fail"), ) ``` ### negative_streak(where=None) negative_streak(*, where: _Expr | None = None) -> AggDescriptor Current run length of consecutive *non-matching* events — the inverse of streak (#streak). Returns `i64`. negative_streak.pyCopy ``` e.group_by("user_id").agg( consec_clean=bv.negative_streak(where=bv.col("status") == "fail"), ) ``` ### first_seen_in_window(window, where=None) first_seen_in_window(*, window: str, where: _Expr | None = None) -> AggDescriptor Boolean — is there a matching event within the past `window`? Returns `bool`. `window=` is required. first_seen_in_window.pyCopy ``` e.group_by("user_id").agg( active_last_24h=bv.first_seen_in_window(window="24h"), ) ``` ## Decay Exponentially-weighted aggregates. Use `half_life=` instead of `window=`: each event's contribution decays by 50% every `half_life` of elapsed time, so old events fade rather than getting evicted. ### ewma(field, half_life, where=None) ewma(field: str, *, half_life: str, where: _Expr | None = None) -> AggDescriptor Exponentially weighted moving average of `field`. Returns `f64`. - half_life — required duration string; e.g. "15m", "1h". ewma.pyCopy ``` e.group_by("user_id").agg( spend_ewma=bv.ewma("amount", half_life="30m"), ) ``` ### ewvar(field, half_life, where=None) ewvar(field: str, *, half_life: str, where: _Expr | None = None) -> AggDescriptor Exponentially weighted variance of `field`. Returns `f64`. ewvar.pyCopy ``` e.group_by("user_id").agg( spend_ewvar=bv.ewvar("amount", half_life="30m"), ) ``` ### ew_zscore(field, half_life, where=None) ew_zscore(field: str, *, half_life: str, where: _Expr | None = None) -> AggDescriptor Z-score of the most recent `field` value against the EWMA / EWVAR baseline at the same half-life. Returns `f64`. ew_zscore.pyCopy ``` e.group_by("user_id").agg( spend_zscore=bv.ew_zscore("amount", half_life="1h"), ) ``` ### decayed_sum(field, half_life, where=None) decayed_sum(field: str, *, half_life: str, where: _Expr | None = None) -> AggDescriptor Time-decayed sum of `field`. Each event contributes its value times `0.5^(age / half_life)`. Returns `f64`. decayed_sum.pyCopy ``` e.group_by("user_id").agg( fading_spend=bv.decayed_sum("amount", half_life="6h"), ) ``` ### decayed_count(half_life, where=None) decayed_count(*, half_life: str, where: _Expr | None = None) -> AggDescriptor Time-decayed event count — fieldless. Returns `f64`. decayed_count.pyCopy ``` e.group_by("user_id").agg( fading_visits=bv.decayed_count(half_life="1h"), ) ``` ### twa(field, window, where=None) twa(field: str, *, window: str, where: _Expr | None = None) -> AggDescriptor Time-weighted average of `field` over `window` — each value contributes proportionally to the duration it was the most recent observation. Returns `f64`. `window=` is required. twa.pyCopy ``` e.group_by("user_id").agg( avg_balance_24h=bv.twa("balance", window="24h"), ) ``` ## Velocity Change-of-rate, trend, residual, and outlier counters. Each requires a `window=` bound (or `baseline_window=` for `z_score`) — there's no lifetime variant; the comparison is always against a rolling reference frame. ### rate_of_change(field, window, where=None) rate_of_change(field: str, *, window: str, where: _Expr | None = None) -> AggDescriptor Slope of `field` versus time across the window — `(latest - earliest) / window_seconds`. Returns `f64`. `window=` is required. rate_of_change.pyCopy ``` e.group_by("user_id").agg( spend_velocity_1h=bv.rate_of_change("amount", window="1h"), ) ``` ### inter_arrival_stats(window, where=None) inter_arrival_stats(*, window: str, where: _Expr | None = None) -> AggDescriptor Mean inter-arrival time (ms) between consecutive matching events in the window. Fieldless. Returns `f64`. inter_arrival_stats.pyCopy ``` e.group_by("user_id").agg( mean_gap_ms_1h=bv.inter_arrival_stats(window="1h"), ) ``` ### burst_count(window, sub_window, where=None) burst_count(*, window: str, sub_window: str, where: _Expr | None = None) -> AggDescriptor Number of `sub_window`-sized buckets inside `window` that had at least one event. Detects clustered activity rather than steady throughput. Returns `i64`. - window — outer bound; required. - sub_window — inner bucket size; required (must also be a valid duration). burst_count.pyCopy ``` e.group_by("user_id").agg( bursts_1h=bv.burst_count(window="1h", sub_window="1m"), ) ``` ### trend(field, window, where=None) trend(field: str, *, window: str, where: _Expr | None = None) -> AggDescriptor OLS slope of `field` versus event timestamp across `window`. Returns `f64`. Distinct from rate_of_change (#rate_of_change): `trend` is a regression slope; `rate_of_change` is endpoint-only. trend.pyCopy ``` e.group_by("user_id").agg( spend_trend_24h=bv.trend("amount", window="24h"), ) ``` ### trend_residual(field, window, where=None) trend_residual(field: str, *, window: str, where: _Expr | None = None) -> AggDescriptor RMS of the residuals from the OLS fit underlying trend (#trend). Returns `f64` — high values mean the trend explains little of the variance. trend_residual.pyCopy ``` e.group_by("user_id").agg( spend_residual_24h=bv.trend_residual("amount", window="24h"), ) ``` ### outlier_count(field, window, sigma=3.0, where=None) outlier_count(field: str, *, window: str, sigma: float = 3.0, where: _Expr | None = None) -> AggDescriptor Number of events where `field` falls outside ±`sigma` standard deviations of the window's mean. Returns `i64`. - sigma — multiplier on the standard deviation. Default 3.0. outlier_count.pyCopy ``` e.group_by("user_id").agg( big_spends_24h=bv.outlier_count("amount", window="24h", sigma=2.5), ) ``` ### value_change_count(field, window, where=None) value_change_count(field: str, *, window: str, where: _Expr | None = None) -> AggDescriptor Number of times `field`'s value differed from its previous value inside the window — a coarse churn indicator. Returns `i64`. value_change_count.pyCopy ``` e.group_by("user_id").agg( device_swaps_24h=bv.value_change_count("device_id", window="24h"), ) ``` ### z_score(field, baseline_window, where=None) z_score(field: str, *, baseline_window: str, where: _Expr | None = None) -> AggDescriptor Z-score of the latest `field` value against the rolling mean / stddev over `baseline_window`. Returns `f64`. Note the kwarg name is `baseline_window=`, not `window=`. z_score.pyCopy ``` e.group_by("user_id").agg( spend_z=bv.z_score("amount", baseline_window="7d"), ) ``` ### seasonal_deviation(field, where=None) seasonal_deviation(field: str, *, where: _Expr | None = None) -> AggDescriptor Lifetime z-score of the latest `field` against the hour-of-day baseline accumulated for the entity. Catches "this user is normally quiet at 3am, why are they spending now." Returns `f64`. Lifetime-only — no `window=`. seasonal_deviation.pyCopy ``` e.group_by("user_id").agg( odd_hour_spend=bv.seasonal_deviation("amount"), ) ``` ## Buffer Bounded ordered buffers — keep a small list of recent values per entity, in the order they arrived. Memory is fixed by the `n=` bound at register time. ### first_n(field, n, where=None) first_n(field: str, *, n: int, where: _Expr | None = None) -> AggDescriptor The first `n` matching values of `field` in insertion order. Once the buffer is full, later events are ignored. Returns a JSON-string array. first_n.pyCopy ``` e.group_by("user_id").agg( first_3_paths=bv.first_n("path", n=3), ) ``` ### last_n(field, n, where=None) last_n(field: str, *, n: int, where: _Expr | None = None) -> AggDescriptor The last `n` matching values of `field`, oldest-to-newest. Sliding ring buffer — the oldest entry is dropped when a new one arrives. Returns a JSON-string array. last_n.pyCopy ``` e.group_by("user_id").agg( recent_paths=bv.last_n("path", n=10), ) ``` ### lag(field, n=1) lag(field: str, *, n: int = 1) -> AggDescriptor The value of `field` from *n* events ago. Output type inherits from the upstream column. `n` defaults to `1` (the immediately previous value). lag.pyCopy ``` e.group_by("user_id").agg( prev_amount=bv.lag("amount"), amount_2_ago=bv.lag("amount", n=2), ) ``` ### delta_from_prev(field, where=None) delta_from_prev(field: str, *, where: _Expr | None = None) -> AggDescriptor Difference between the latest `field` value and the previous one. Output type inherits from the upstream column. delta_from_prev.pyCopy ``` e.group_by("user_id").agg( spend_delta=bv.delta_from_prev("amount"), ) ``` ## Geo Lat/lon-pair operators built on the haversine formula. Each takes `lat=` and `lon=` kwargs naming the latitude / longitude columns on the upstream event; both columns are read on every matching event. ### geo_velocity(lat, lon, where=None) geo_velocity(*, lat: str, lon: str, where: _Expr | None = None) -> AggDescriptor Lifetime maximum km/h between consecutive matching events. Catches "this card was used in two cities five minutes apart." Returns `f64`. geo_velocity.pyCopy ``` e.group_by("user_id").agg( impossible_speed=bv.geo_velocity(lat="lat", lon="lon"), ) ``` ### geo_distance(lat, lon, where=None) geo_distance(*, lat: str, lon: str, where: _Expr | None = None) -> AggDescriptor Lifetime cumulative haversine path length (km) traced by the entity's matching events. Returns `f64`. geo_distance.pyCopy ``` e.group_by("user_id").agg( total_km=bv.geo_distance(lat="lat", lon="lon"), ) ``` ### geo_spread(lat, lon, where=None) geo_spread(*, lat: str, lon: str, where: _Expr | None = None) -> AggDescriptor Lifetime RMS dispersion (km) of matching events around the running centroid — "how spread out is this entity's footprint." Returns `f64`. geo_spread.pyCopy ``` e.group_by("user_id").agg( geo_footprint_km=bv.geo_spread(lat="lat", lon="lon"), ) ``` ### distance_from_home(lat, lon, samples=100, where=None) distance_from_home(*, lat: str, lon: str, samples: int = 100, where: _Expr | None = None) -> AggDescriptor Distance (km) from the current event's coordinates to the centroid of the last `samples` matching events. Returns `f64`. - samples — sliding window of points used to compute the home centroid. Default 100. distance_from_home.pyCopy ``` e.group_by("user_id").agg( km_from_home=bv.distance_from_home(lat="lat", lon="lon", samples=50), ) ``` ## Where to go next You've got the catalogue. The two adjacent pages cover the expression DSL the operators consume and the error codes the server returns: → **bv.col / bv.lit** (/sdk/python/col-lit/) — The column-reference expression DSL. Used inside where=, filter(...), and with_columns(...) chain stages — the way you build the expressions you pass to operators. → **Errors** (/sdk/python/errors/) — Every structured error code the server returns — unknown_table, event_not_found, invalid_event, reset_disabled_in_production, and the rest. Mapped to the SDK's RegistrationError exception. ======================================================================== # Errors Source: https://beava.dev/sdk/python/errors/ # Errors Two layers, one combined surface. The Python SDK raises three exception classes; the server returns structured wire errors under `error.code`. Every non-2xx wire response is rewrapped as a Python exception so `try/except bv.RegistrationError` catches everything that came off the network. ## Overview Beava errors come from two places: - Client-side — the SDK validates inputs before they hit the wire (e.g. raw EventDerivation chains that weren't wrapped in @bv.event) and raises RegistrationError or BinaryNotFoundError directly. ValidationError is the structured per-failure record carried by RegistrationError.errors. - Server-side (wire) — every non-2xx response from the data plane carries a JSON body with a stable error.code. The SDK rewraps that body as RegistrationError(code=..., path=..., message=...); you don't deal with raw httpx bodies. The canonical wire-error envelope is a flat object: wire error response ``` { "error": { "code": "event_not_found", "path": "PageView", "message": "event 'PageView' is not registered" }, "registry_version": 3 } ``` Some errors carry richer payloads — `force_required` includes a structured `diff`, `batch_too_large` includes the offending count, registration validation can return an `errors` list of `{kind, path, message}` tuples. The SDK threads those into `RegistrationError.errors` as `ValidationError` instances when present. HTTP status discipline: `4xx` means client mistake (event not registered, schema mismatch, malformed JSON), `5xx` means server-side trouble (WAL stall, internal serialization bug). `403` is reserved for `reset_disabled_in_production`. The Python SDK does **not** retry — see the FAQ below. Section 1 of 2 ## Python exceptions Three exception classes are exported from the top-level `beava` module. All three are also accessible as `bv.RegistrationError`, `bv.ValidationError`, `bv.BinaryNotFoundError`. ### RegistrationError RegistrationError(*, code: str, path: str = "", message: str = "", errors: list[ValidationError] | None = None) The SDK's general-purpose wire-error wrapper. Raised for every non-2xx response from the data plane. Discriminate on `code`, not on the exception class. ### Attributes - code — the stable wire code (e.g. "event_not_found", "schema_mismatch", "unknown_table", "reset_disabled", "invalid_descriptor"). Catalogued in §Wire error codes below. - path — JSON-pointer-style path to the offending field or descriptor (e.g. "Transaction.amount"). Empty string when the error is global. - message — human-readable description, suitable for logging. - errors — list[ValidationError]. Populated when registration validation returns multiple failures; empty for single-error cases. ### Raised by - Any of the seven App methods (register, push, get, batch_get, reset, ping, close) on a non-2xx server response. - Client-side from app.register(...) when a passed descriptor is a raw EventDerivation chain (code="invalid_descriptor") — does not hit the wire. - Client-side from the transport layer when the server returns a non-JSON body (code="unparseable_error"). ### Example handle_errors.py Copy ``` import beava as bv app = bv.App("http://localhost:8080") try: app.push("PageView", {"user_id": "alice"}) except bv.RegistrationError as e: if e.code == "event_not_found": # PageView wasn't registered yet — register and retry. app.register(PageView) app.push("PageView", {"user_id": "alice"}) elif e.code == "invalid_event": # Schema mismatch — log path + message and surface up. log.error("bad event payload at %s: %s", e.path, e.message) raise else: raise # anything else is a programming bug ``` ### ValidationError ValidationError(kind: str, path: str, message: str) Frozen dataclass carrying a single validation failure. Not raised on its own — it's the type held in `RegistrationError.errors` when registration validation produces multiple failures (e.g. five fields with type mismatches across two descriptors). ### Attributes - kind — one of cycle, missing_upstream, schema_mismatch, bad_return_type, unknown_field_type, table_key_invalid, registration_conflict, duplicate_name. The set is exported as beava._errors.VALIDATION_ERROR_KINDS. - path — JSON-pointer-style path (e.g. "Transaction.event_time"). - message — human-readable description. The dataclass is frozen, so you can use it as a dict key or in sets. Stringification is `"[kind] path: message"`. ### BinaryNotFoundError BinaryNotFoundError Raised by **embed mode** (`bv.App()` with no URL) when the `beava` binary cannot be located. Discovery order: - $BEAVA_BINARY — explicit override. - beava on $PATH — released installs. - ./target/debug/beava — local dev-loop convenience. - If none of the above resolves, the exception fires with an install-guidance message. Network-mode (`http://...`, `tcp://...`) `App`s never raise this — they don't spawn a binary. ### Example embed_or_fail.py Copy ``` try: with bv.App() as app: app.register(PageView) except bv.BinaryNotFoundError as e: print("install beava: cargo install beava OR set BEAVA_BINARY") raise ``` Section 2 of 2 ## Wire error codes Every non-2xx response from the data plane carries a structured `error` object. The Python SDK rewraps each as `RegistrationError(code=...)`. The codes below are stable — clients can branch on them. Codes are grouped by trigger; HTTP status is given per code. ### Push errors ### event_not_found HTTP 404 · POST /push · path: The pushed `event_name` isn't in the registry. Register it first (`app.register(...)`), or check for typos. Catch as `RegistrationError(code="event_not_found")`. ### invalid_event HTTP 400 · POST /push · path: data. (when known) The push body is malformed JSON, fails to deserialize into a `Row`, or violates the registered event schema (missing required fields, wrong types). The single biggest source of `invalid_event`: a field type doesn't match the declared schema. Catch as `RegistrationError(code="invalid_event")`. ### unknown_field_v0 HTTP 400 · POST /push · path: . The push body contains a field not declared on the event's schema (and not in `optional_fields`). Beava is strict-deny on unknown fields in v0. Add the field to your `@bv.event` declaration or strip it from the push payload. ### unknown_field_event_time_v0 HTTP 400 · POST /push · path: .event_time Specialised form of `unknown_field_v0` for the reserved `event_time` / `event_time_ms` field names. v0 is processing-time only — server clock is the timestamp source. Drop the field. ### missing_event_name_in_body HTTP 400 · POST /push (TCP fast-path) The framed-TCP variant of `POST /push` couldn't extract `event_name` from the request frame. Almost always a malformed frame or a stale client. Re-check the SDK version against the server. ### invalid_json_body HTTP 400 · POST /push (any transport) The request body wasn't valid JSON. Distinct from `invalid_event` — the bytes never made it to schema validation. ### Get / batch_get errors ### unknown_table HTTP 404 · GET /get, POST /batch_get · path: The requested `table` isn't in the registry. In `batch_get`, this can appear per-tuple in the response array — the SDK aggregates and re-raises as a single `RegistrationError` when any entry failed. ### key_not_found HTTP 404 · GET /get · path: / The table is registered, but no events have populated this entity-key yet. The SDK normalizes single-row `get` calls so that cold-start returns `{}` rather than raising — you only see `key_not_found` when calling lower-level feature-query endpoints directly. ### key_parse_failure HTTP 400 · GET /get, POST /batch_get · path:
/ The supplied entity key doesn't deserialize into the table's declared key shape — typically a composite-key call where the JSON list has the wrong arity or types. ### feature_not_found HTTP 400 · GET /get, POST /batch_get One of the feature names in the `features=[...]` filter isn't on the table. The body's `missing` key lists the offending names. Drop them or re-register the table with the new feature. ### batch_too_large HTTP 400 · POST /batch_get Total work (`keys × features`) exceeds the per-request limit (10,000). Split the batch on the client. ### Register errors ### invalid_registration HTTP 400 · POST /register The register payload failed structural validation (malformed DAG, missing required keys, raw `OpNode` shape errors). The body's `errors` list carries one `{kind, path, message}` per failure; the SDK exposes them via `RegistrationError.errors`. ### unsupported_node_kind HTTP 400 · POST /register · path: descriptors[i].kind The register payload included a descriptor with a `kind` the server doesn't accept. v0 accepts `"event"` and `"derivation"` only; aggregation tables are produced via `kind: "derivation", output_kind: "table"`. ### unbounded_op_in_lifetime_mode HTTP 400 · POST /register · path: descriptors[i].agg. An aggregation that requires a window (`velocity`, `rate`, etc.) was declared without one in a context that demands a bounded window. Add `window="..."` to the op. ### force_required HTTP 409 · POST /register The proposed registry change would destroy state (type change, removed field, etc.). The body carries a structured `diff` with `additive` and `destructive` sections — same shape the server returns under `dry_run`. Re-call with `force=True` to commit, or revise the change to be additive-only. ### invalid_descriptor SDK-side · raised pre-wire · path: descriptors[i] **Client-only.** Raised by `app.register(*descriptors)` when one of the descriptors is a raw `EventDerivation` (a chain expression that wasn't wrapped in `@bv.event`). The exception message includes the canonical rewrite. Never reaches the wire. ### Reset / admin errors ### reset_disabled_in_production HTTP 403 · POST /reset The server isn't in test mode (no `--test-mode` flag, no `BEAVA_TEST_MODE=1`). `/reset` is gated to keep production state safe. The SDK surfaces this as `RegistrationError(code="reset_disabled")` for backward compatibility — handle either string in your `except` branch if you straddle versions. ### Transport / framing errors ### unknown_op HTTP 400 · TCP fast-path The opcode in a TCP frame isn't in the dispatch table. Almost always a stale client; upgrade the SDK. ### op_not_implemented HTTP 400 · TCP fast-path The opcode is recognised but not handled in this build. Distinct from `unknown_op` (the opcode is outside the dispatch table entirely). ### frame_too_large HTTP 413 · TCP fast-path The TCP frame's declared length exceeds `max_frame_bytes`. Bump the server's frame ceiling or split the request. ### frame_error HTTP 400 · TCP fast-path Generic protocol-level frame violation (bad length, bad content-type marker, truncated payload). ### http_protocol_error HTTP 400 · HTTP transport The HTTP/1.1 layer rejected the request before it reached an application handler — typically a malformed request line or oversize headers. ### unsupported_content_type HTTP 415 · TCP fast-path The frame's `content_type` byte isn't `0x01` (JSON) — the only supported value in v0. ### unsupported_media_type HTTP 415 · HTTP transport The HTTP `Content-Type` header isn't `application/json`. Set the header explicitly on raw `curl` calls. ### unsupported_request_shape HTTP 400 · HTTP transport The request body parsed but didn't match any known shape for the endpoint (e.g. `/batch_get` got an object instead of an array). The body's `message` field carries a hint. ### not_found HTTP 404 · any HTTP path The HTTP route doesn't exist. Either a typo on a curl-built request or a version skew. ### method_not_allowed HTTP 405 · any HTTP path Right path, wrong verb (e.g. `GET /push`). The body echoes `method` and `path`. ### Server / durability errors ### wal_unavailable HTTP 503 · POST /register, POST /push The write-ahead log is taking writes but the durability path is degraded (disk full, fsync stuck, recovery in progress). Retries are safe — beava's contract is that successful writes are WAL-acked. ### wal_sync_timeout HTTP 504 · sync-mode push A sync-mode push waited longer than its timeout for fsync acknowledgement. The event may or may not be durable — if the server comes back, the event will appear with the next ack-LSN if it was buffered. Treat as an at-most-once retry candidate from the application side. ### internal_error HTTP 500 · any path Catch-all for server-side failures the engine couldn't categorize (panicked task, response serialization bug, unexpected I/O). The body's `reason` field carries a short hint. File a bug with the request payload and the server log line. ### SDK-only codes ### unparseable_error SDK-side · raised on non-JSON server response **Client-only.** Generated by the transport layer when the server returns a non-2xx response that isn't valid JSON (a load-balancer 502 page, a TCP RST mid-frame, an unexpected HTML body). The exception's `message` contains the first 200 bytes of the response so you can diagnose. Never originates server-side. ## Common questions How do I distinguish a 4xx from a 5xx? The exception doesn't carry the raw HTTP status — only the `code`. The mapping is documented per-code above (`event_not_found` is 404, `invalid_event` is 400, `wal_unavailable` is 503, etc.). Treat the code as the contract; the status is for HTTP-aware infrastructure (load balancers, monitoring) and isn't part of the SDK's public surface. If you need the status anyway, drop down to the transport layer (`app._transport`) — but that's a private API and may move. Does the SDK retry transient failures? No. Each method is one wire call. Retries belong in your application code — beava's contract is that successful pushes are WAL-acked (durable), so re-pushing on a transport error is safe (idempotent under `dedupe_key`, an at-least-once duplicate without). For server-side soft failures (`wal_unavailable`, `wal_sync_timeout`, `internal_error`), exponential backoff with jitter is a reasonable default. Don't retry `4xx` codes — those are client mistakes that won't fix themselves. Are these codes stable across versions? The codes documented above are stable. New codes get added (and that's a minor-version-compatible change); existing codes don't get renamed or repurposed without a major-version bump. If you write an exhaustive switch on `e.code`, fall through to a default branch — don't panic on unknown codes from a newer server. ## Where to go next Errors don't read in isolation. The two pages you'll cross-reference most: → **App client** (/sdk/python/app/) — The seven wire-mapped bv.App methods, each with its own Raises section keyed to the codes above. Start there if you're tracing where a specific error came from. → **Wire spec** (/sdk/http/wire-spec/) — Full HTTP / TCP request and response shapes per endpoint, with status codes, frame layouts, and content-type matrix. Useful for non-Python clients reading the wire codes raw. ======================================================================== # POST /push Source: https://beava.dev/sdk/http/push/ # POST /push Push a single event. ACK includes the WAL log offset and the registry version stamp. ## Overview `POST /push` is the canonical write path for event ingestion. Send one event per request; the server validates it against the registered `EventDescriptor`, appends it to the write-ahead log, applies it to in-memory aggregations, and replies with the durable LSN once the WAL slot is reserved. - Default port: 8080 (the data-plane HTTP listener; configure via the server's http_addr). - Status: 200 OK on success; structured 4xx on validation failure (see Errors (#errors)). - One event per request. **Verb-style body, not path-style.** The event name lives *inside* the JSON body under the `event` key — never in the URL path. Always `POST /push`; never `POST /push/Foo`. ## Request ### Headers - Content-Type: application/json — the only supported content type. /push always parses the body as JSON. ### Body The body is a JSON object with two top-level keys: event string required Name of a registered event type (e.g. `"Txn"`). Must match an `EventDescriptor` previously installed via `POST /register`; otherwise the server returns `404 event_not_found`. data object required Event fields as a flat object. Keys must match the descriptor's declared `schema.fields`; unknown keys are rejected with `unknown_field_v0`. The names `event_time` and `event_time_ms` are reserved and rejected with `unknown_field_event_time_v0` — v0 is processing-time only. ### Worked example — curl push.sh Copy ``` curl -X POST http://localhost:8080/push \ -H "Content-Type: application/json" \ -d '{ "event": "Txn", "data": { "user_id": "alice", "card_id": "card_001", "amount": 42.50, "merchant": "amazon", "ip": "203.0.113.42" } }' ``` ### Worked example — Python The Python SDK's `App` client wraps the same wire call: push.py Copy ``` import beava as bv app = bv.App("http://localhost:8080") ack = app.push("Txn", { "user_id": "alice", "card_id": "card_001", "amount": 42.50, "merchant": "amazon", "ip": "203.0.113.42", }) print(ack["ack_lsn"]) # → 12345 ``` ## Response Success returns `200 OK` with a JSON body: success body ``` { "ack_lsn": 12345, "registry_version": 1, "idempotent_replay": false } ``` ack_lsn integer ≥ 0 The durable WAL offset assigned to this event — server's monotonic Log Sequence Number. Reaching this LSN means the event survives a crash; the server returns `ack_lsn` as soon as the WAL slot is reserved (the WAL writer guarantees a fsync before the slot is reused). registry_version integer ≥ 1 The server's current registry counter. Increments on every successful `/register`. Useful as a cache-key invalidation / schema-evolution signal on long-lived clients — when this value changes from one push to the next, the registry shape changed underneath you. idempotent_replay boolean `true` when the server identified this push as a re-delivery of a prior event — matched by the descriptor's `dedupe_key` within the dedupe window. The underlying state was *not* mutated; the response is byte-identical to the original ack. Always `false` when the descriptor has no `dedupe_key`, or when `dedupe_key` is set but the value is novel. The HTTP transport also signals replay via the `X-Beava-Idempotent-Replay: 1` response header. ## Errors Every non-2xx response carries a JSON body with the canonical error envelope: error envelope ``` { "error": { "code": "", "path": "", // optional "message": "" // optional } } ``` The `code` field is a stable structured identifier; `path` and `message` are optional contextual detail. The push path emits these codes: 404 · event_not_found The `event` name doesn't match any registered `EventDescriptor`. Register the event first via `POST /register`. 400 · invalid_event `data` failed schema validation against the descriptor — wrong field types, wrong cardinality, or a required field missing. The canonical fixture for this case (with the optional `path` + `message` populated) lives at `examples/wire/push-validation-error.error.json`; SDKs surface that richer shape as `RegistrationError(code="schema_mismatch", path=…, message=…)`. 400 · invalid_json_body Request body isn't valid JSON. Most often a stray comma, an unquoted key, or a truncated payload. 400 · missing_event_name_in_body Body parsed as JSON but the top-level `event` string is absent or non-string. The verb-style envelope *requires* `{"event": "", "data": {…}}`. 400 · unknown_field_v0 `data` contains a key not in the descriptor's `schema.fields` (and not declared optional). v0 strict-denies unknown fields rather than silently dropping them. 400 · unknown_field_event_time_v0 Specialised case of `unknown_field_v0` for the reserved `event_time` / `event_time_ms` field names. v0 is processing-time only; clients sending event-time data get a structured 400 rather than silent acceptance. **HTTP /push does not enforce Content-Type.** The 415 `unsupported_media_type` code only fires on `POST /register`; `/push` attempts JSON parse against any body and emits `invalid_json_body` on failure. Always send `Content-Type: application/json` anyway — proxies and load balancers in front of beava may enforce it. ## Worked example: end-to-end Canonical request and response: request ``` { "event": "Txn", "data": { "user_id": "alice", "card_id": "card_001", "amount": 42.50, "merchant": "amazon", "ip": "203.0.113.42" } } ``` response · 200 OK ``` { "ack_lsn": 12345, "registry_version": 1, "idempotent_replay": false } ``` To reproduce locally: boot the server with a YAML config that sets `http_addr: 127.0.0.1:8080`, `storage.memory_only: true`, and `test_mode: true`, register a `Txn` event, then send the request above. Both fixture files validate against the JSON Schemas at `examples/wire/schemas/push.{request,response}.schema.json`. ## TCP equivalent The framed-TCP fast-path carries the same JSON envelope under opcode `OP_PUSH = 0x0010`. Frame format: tcp frame ``` [u32 length BE][u16 op = 0x0010][u8 content_type = 0x01][payload] payload: JSON // {"event":"Txn","data":{...}} ``` TCP is strict-FIFO with one in-flight request per connection — the server replies in the same order it received requests. HTTP `/push` always parses bodies as JSON. The full opcode catalogue and frame state machine live on the wire spec (/sdk/http/wire-spec/) page. ## Common questions What's `idempotent_replay` for if I'm not setting `dedupe_key`? It's always `false` in that case — the server only consults the dedupe cache when the descriptor declares a `dedupe_key`. The field is on every push response so the wire shape is uniform regardless of whether dedupe is enabled. To opt in, declare `dedupe_key=""` on your `@bv.event` and the server will replay-detect within the descriptor's dedupe window. Can I push multiple events in one request? No — `POST /push` is single-event. HTTP-level batching is intentionally absent: HTTP/1.1 keep-alive plus per-request acks already amortizes connection overhead well below the WAL throughput ceiling. Open one connection, fire many `POST /push` requests on it. Is `ack_lsn` durable across restarts? Yes — `ack_lsn` is the WAL offset, persisted to disk before the server returns the ack. After a crash, recovery replays the WAL from the last snapshot up to the highest synced LSN, so any LSN you saw in a 200 response will be reflected in the post-recovery state. The same LSN is monotonically assigned across snapshots, so it remains a stable durability anchor for as long as the WAL files exist. ## Where to go next You've sent your first event. The companion endpoints round out the data plane: → **POST /get** (/sdk/http/get/) — Read a single feature row by entity key. JSON request, JSON response — pairs naturally with /push for the push-then-query loop. → **App client** (/sdk/python/app/) — Python wrapper around /push, /get, /register, and the rest. Same wire shapes, with type hints and a context-manager lifecycle. ======================================================================== # POST /get Source: https://beava.dev/sdk/http/get/ # POST /get Read one feature row by entity key. Cold-start (no events for that key yet) returns `{}` with HTTP 200 — not a 404. ## Overview `POST /get` is the single-row read on the data plane. You name a registered table, give an entity key, and the server returns the latest feature row for that key as a flat JSON dict. The Redis-shaped contract matters here: **a key that has never received a matching event is just a key with no data, not an error.** The server returns HTTP 200 with body `{}`. That separates two distinct conditions: - Cold-start (HTTP 200, body {}) — the table is registered, the key parses, no events have populated this row yet. Treat it like GET on an unset Redis key. - unknown_table (HTTP 404) — the table name isn't in the registry. This is the error path. If you mistyped the table or forgot to register, you land here. **Cold-start is HTTP 200, not 404.** Client code that treats `{}` as an error will misbehave on every new entity. Branch on `response == {}` if you want a "no data yet" code path. ## Request Headers — the server attempts JSON parse regardless of `Content-Type`, but always send the canonical header so proxies, log scrapers, and curl-pasted requests stay portable: headers ``` Content-Type: application/json ``` Body shape: body schema ``` { "table": "", // required, registered table "key": "", // required, see below "features": ["f1", "f2", /* … */] // optional filter } ``` - table — the registered table's name. Required. Mismatched name → 404 unknown_table. - key — the entity key as a JSON string. For composite keys (declared with key=["a","b"]), the SDK pipe-joins the segments before serialising — e.g. "alice|merchant1". The empty string "" routes to the global-aggregation sentinel for tables registered with key=[]. - features — optional. When supplied, the server narrows the response to the named subset; when omitted, the full row is returned. Worked curl example: curl Copy ``` curl -sS -X POST http://localhost:8080/get \ -H 'Content-Type: application/json' \ -d '{"table": "UserTxnFeatures", "key": "alice"}' ``` ## Response The success body is a **flat dict mapping feature name → value**. There is no envelope — feature names are top-level keys. Cold-start returns `{}` at HTTP 200; document this in your client wrapper because it is easy to mistake for an empty error envelope. ### Standard hit Table is registered, key has events, full row requested: request ``` { "table": "UserTxnFeatures", "key": "alice" } ``` 200 OK ``` { "tx_count_1h": 7, "tx_sum_1h": 312.45, "tx_mean_1h": 44.64, "tx_p99_1h": 89.99, "tx_unique_merchants_1h": 3 } ``` ### Cold-start Same request, key the server has never seen. **HTTP 200, not 404.** request ``` { "table": "UserTxnFeatures", "key": "newuser" } ``` 200 OK ``` {} ``` ### Global aggregation Tables registered with `key=[]` (no group-by keys) hold a single, server-wide row. Address it with the empty-string sentinel `"key": ""`: request ``` { "table": "GlobalCounter", "key": "" } ``` 200 OK ``` { "click_count": 12345 } ``` ## The features filter When `features` is supplied, the server walks the registered descriptor and emits only the named subset. Useful for narrow client reads — a fraud rule that needs a single counter doesn't need to ship the full 30-feature row across the wire. Same key, two requests: full row request ``` { "table": "UserStats", "key": "alice" } ``` full row response ``` { "visits": 2, "last_path": "/checkout", "sessions": 1 } ``` narrowed request ``` { "table": "UserStats", "key": "alice", "features": ["visits"] } ``` narrowed response ``` { "visits": 2 } ``` If `features` names a column that isn't registered on the table, the whole call is rejected — no partial response. The error surfaces as HTTP 500 with `code: "internal_error"` and a `reason` that names the missing feature(s). The batch-get path uses the same whole-batch-reject disposition. ## Composite keys A table registered with `key=["user_id", "merchant_id"]` indexes rows on the pair. On the wire, the `key` field is still a single JSON string — the SDK pipe-joins the segments in registered order before serialising. Pipe characters inside a key value must be percent-encoded as `%7C`. composite key on the wire ``` // table registered with key=["user_id", "merchant_id"] { "table": "UserMerchantStats", "key": "alice|merchant1" } ``` The number of pipe-separated segments must exactly match the registered key arity. If it doesn't, the server returns 404 with `code: "key_parse_failure"` — distinct from `key_not_found` (cold-start; never surfaced to clients) so a malformed key looks different from a key with no data. ## Errors Each error body has the shape `{"error": {"code": "", ...}}`. 404 — unknown_table ``` HTTP/1.1 404 Not Found Content-Type: application/json {"error":{"code":"unknown_table"}} ``` `table` isn't in the registry. Re-check the spelling and confirm `POST /register` succeeded for the descriptor. 404 — key_parse_failure ``` HTTP/1.1 404 Not Found Content-Type: application/json {"error":{"code":"key_parse_failure"}} ``` The pipe-joined `key` string didn't split into the right number of segments for the table's registered key arity. Check that you sent `"a|b"` for a 2-column key, not `"a"` or `"a|b|c"`. 400 — unsupported_request_shape ``` HTTP/1.1 400 Bad Request Content-Type: application/json {"error":{ "code": "unsupported_request_shape", "message": "POST /get expects {table, key, features?}" }} ``` The body parsed as JSON but didn't match the canonical shape — common when a client sends a multi-key shape (`{keys, features}`) or a single-feature shape (`{feature, key}`). Use the verb-style body documented above. 500 — internal_error ``` HTTP/1.1 500 Internal Server Error Content-Type: application/json {"error":{ "code": "internal_error", "reason": "missing field `key` at line 1 column 15" }} ``` The body was malformed JSON, missed a required field, or named a feature in `features` that the table doesn't expose. The `reason` string carries the underlying parse / lookup error. Use it to fix your request. **Content-Type:** `POST /get` does not enforce `application/json` at the route layer; a request with `Content-Type: text/plain` and a JSON body still parses. Send `application/json` anyway so proxies and WAFs don't reject it upstream. ## TCP equivalent The custom-framed TCP fast-path (default port `8081`) carries the same body. `OP_GET = 0x0020` wraps a JSON payload identical to the HTTP body shape; the response comes back as `OP_GET_RESPONSE = 0x0023`. Strict-FIFO correlation on a connection — one in-flight request per socket. For multi-key reads, use `OP_BATCH_GET = 0x0024` instead of N round-trips. The Python SDK's `app.batch_get([...])` method maps to this opcode; over HTTP, the equivalent is `POST /batch_get`. Full wire format — frame header, content-type byte, JSON encoding — is documented in the wire spec (/sdk/http/wire-spec/). ## Common questions Why is cold-start `{}` instead of 404? Beava is Redis-shaped on reads. A key that hasn't received events yet isn't an exception — it's just a key with no data. Surfacing that as 404 would conflate three different conditions (cold-start, malformed key, unknown table) and force every client to inspect error bodies on the success path. `{}` at HTTP 200 keeps the happy path clean: one branch on `response == {}` if you care, otherwise treat the dict as authoritative. Can I get just a single feature without the table boilerplate? Yes — pass `features: ["my_feature"]` on the regular `/get` body. There's no separate single-feature route; the filter is the mechanism. For multi-key fetches use `POST /batch_get`. What happens if I pass `features` for a column that doesn't exist? The whole call is rejected — no partial response with the columns that did match. The server returns HTTP 500 with `code: "internal_error"` and a `reason` string of the form `"feature_not_found: missing=[\"bogus\"] table=UserStats"`. Same whole-batch-reject disposition as the multi-key path: clients see one consistent failure mode, not a half-populated row that silently dropped fields. Is `POST /get` idempotent? Yes — it's a pure read. The server queries in-memory aggregate state without mutating anything. Safe to retry on transport errors; safe to fan out across clients. The only caveat is "freshness": between two reads the underlying row may have advanced, because beava applies pushes atomically on the apply thread without read-side locks. ## Where to go next You've got reads. The other two HTTP endpoints close the loop: → **POST /register** (/sdk/http/register/) — Register one or more event/table descriptors. The shape that POST /get later resolves "table" against. → **POST /push** (/sdk/http/push/) — Push a single event. WAL-acked on return; the row that POST /get will read is updated atomically before the response comes back. ======================================================================== # POST /register Source: https://beava.dev/sdk/http/register/ # POST /register Register event sources and derivations on a running beava server. Hot-reloadable — no restart. Each successful call bumps `registry_version`. ## Overview `/register` is the cold path that installs (or extends) the pipeline a beava server runs. The body is a list of **nodes**; each node is either an event source (`kind: "event"`) or a derivation (`kind: "derivation"`). Two flags control behaviour: - dry_run: true — server validates and returns a categorized diff without committing. - force: true — replace conflicting descriptors instead of returning 409 force_required. Successful calls increment `registry_version` by one and append a `RegistryBump` record to the WAL before the in-memory registry mutates (apply-after-fsync). All client SDKs (`bv.App.register(...)`, the TCP fast-path, raw curl) emit the same JSON envelope documented below. ## Request ### Headers - Content-Type: application/json — required. Anything else returns 415 unsupported_media_type. ### Body shape envelope ``` { "nodes": [ /* one or more node objects, see below */ ], "force": false, // optional, default false "dry_run": false // optional, default false } ``` **The top-level field is nodes, not descriptors.** Some early prototypes / external write-ups used `descriptors` — that key is rejected by the v0 server. Always send `{"nodes": [...]}`. nodes array required Ordered list of nodes to install. Each entry is either an event source (`kind: "event"`) or a derivation (`kind: "derivation"`). Empty arrays are accepted and return `200 OK` with an unchanged `registry_version`. force bool If `true`, destructive changes (renames, type changes, key-cols changes, removed aggregations) are applied — the affected descriptor is dropped along with its accumulated state, and the new shape installs cleanly. Without `force`, destructive changes return `409 force_required`. default `false` dry_run bool If `true`, the server validates the payload and returns the categorized diff under `{"diff": ..., "would_apply": false}` without mutating the registry. `dry_run=true, force=true` still resolves to dry-run — dry-run wins so a "what would this do?" probe never escalates to a real mutation. default `false` ### Node kinds - kind: "event" — an event source. The typed input shape you'll POST /push against. - kind: "derivation" — a derived node. Either an event-derivation (output_kind: "event", no aggregation) or a table-derivation (output_kind: "table", aggregation into a per-entity feature row). - Any other kind returns 400 unsupported_node_kind. v0 is events-only at the top level; tables are produced by derivations. ### Event node — kind: "event" {"kind": "event", "name": "", "schema": {"fields": {...}, "optional_fields": [...]}} An event source declares a typed payload shape that downstream `POST /push` calls have to match. ### Fields - kind — literal "event". - name — string. The event-source identifier; case-sensitive, used as the event_name on /push. - schema.fields — object mapping field name → wire type. Allowed wire types: "str", "i64", "f64", "bool". - schema.optional_fields — array of field names that may be omitted on /push. Names must appear in schema.fields. - keep_events_for — optional duration string (e.g. "30d"). Retention horizon for the raw event log; events older than this are dropped from history. - cold_after_ms — optional integer. Per-entity cold-after threshold in milliseconds; entities idle longer than this are eligible for cold-storage tiering. ### Example event node ``` { "kind": "event", "name": "Txn", "schema": { "fields": { "user_id": "str", "card_id": "str", "amount": "f64", "merchant": "str", "ip": "str" }, "optional_fields": [] }, "keep_events_for": "30d", "cold_after_ms": 86400000 } ``` ### Derivation node — kind: "derivation" {"kind": "derivation", "name", "output_kind": "table"|"event", "upstreams": [...], "ops": [...], "table_primary_key"?: [...]} A derivation is a chain of operators applied to one or more upstream nodes. `output_kind` picks between two flavours: - "table" — aggregating derivation. Emits a per-entity row keyed by table_primary_key. Read with POST /get / POST /batch_get. - "event" — event-derivation. A typed transformation of an upstream event stream (filter / map / project) with no aggregation; downstream nodes can subscribe via upstreams. ### Fields - kind — literal "derivation". - name — string. The node identifier; for output_kind: "table" this is also the table name on /get. - output_kind — "table" or "event". - upstreams — array of strings. Names of nodes (events or derivations) this node consumes. Compile-time-resolved against the registry. - ops — array of operator objects. Each operator carries an op name and a params object; operator-specific shapes are documented in the Operator catalogue (/sdk/python/operators/). - schema — optional. Required for output_kind: "event" derivations (declares the output event's field types); inferred for tables. - table_primary_key — array of field names. Required when output_kind: "table". An empty array ([]) declares a global aggregation — a single feature row keyed by the empty-string sentinel. ### Example — table derivation (per-user) derivation node — output_kind: table ``` { "kind": "derivation", "name": "UserTxnFeatures", "output_kind": "table", "table_primary_key": ["user_id"], "upstreams": ["Txn"], "ops": [ { "op": "group_by", "keys": ["user_id"], "agg": { "tx_count_1h": { "op": "count", "params": { "window": "1h" } }, "tx_sum_1h": { "op": "sum", "params": { "field": "amount", "window": "1h" } }, "tx_p99_1h": { "op": "quantile", "params": { "field": "amount", "q": 0.99, "window": "1h" } } } } ] } ``` ### Example — table derivation (global) An empty `table_primary_key` + empty `group_by.keys` declares a single global counter — one feature row keyed by the empty-string sentinel. Read it back with `POST /get` and `key=""`. derivation node — global aggregation ``` { "kind": "derivation", "name": "GlobalCounter", "output_kind": "table", "table_primary_key": [], "upstreams": ["Click"], "ops": [ { "op": "group_by", "keys": [], "agg": { "click_count": { "op": "count", "params": {} } } } ] } ``` ## Response — success `200 OK` with a flat JSON body: success body ``` { "status": "ok", "registry_version": 1, "added": ["Txn", "UserTxnFeatures"], "already_present": [], "registered_descriptors": ["Txn", "UserTxnFeatures"] } ``` - status — literal "ok" on success. - registry_version — the post-call registry generation. Increments by one per successful registration that mutated state; unchanged on no-op / empty-payload calls. - added — names of nodes installed by this call (in payload order). - already_present — names from the payload that were already in the registry with the same shape; no-ops. - registered_descriptors — full snapshot of every descriptor name in the registry post-call. Not a copy of the request payload — it's the cumulative registry, including descriptors installed by prior /register calls. ## Dry-run Pass `"dry_run": true` to validate without committing. The server runs the same destructive-change classifier it would for a real call, and returns the categorized diff: request ``` { "nodes": [ { "kind": "event", "name": "Login", "schema": { "fields": { "user_id": "str", "device_id": "str" }, "optional_fields": [] } } ], "dry_run": true } ``` response ``` { "diff": { "additive": [ { "kind": "new_descriptor", "name": "Login" } ], "destructive": [] }, "would_apply": false } ``` If the dry-run diff has *any* destructive entries, the equivalent real call would return `409 force_required`. Use this to gate destructive deploys behind a human approval step. ## Force replace Destructive changes — type changes, renames, key-cols changes, removed aggregations — drop the affected descriptor's accumulated state when applied. Without `force=true`, the server returns `409 force_required` and refuses to proceed: force replace ``` { "nodes": [ { "kind": "event", "name": "Txn", "schema": { "fields": { "user_id": "str", "amount": "i64", "currency": "str" }, "optional_fields": [] } } ], "force": true } ``` **force=true drops accumulated state.** Aggregation tables tied to the replaced descriptor lose every per-entity row; pushed events resume populating an empty table. Use a dry-run first, then bake the force flag into a deliberate cutover. ## Errors All error responses share the envelope `{"error": {"code": "", ...}, "registry_version": }` with a non-2xx status. Codes: ### 400 unsupported_node_kind A node carries a `kind` the server doesn't recognise. v0 accepts only `"event"` and `"derivation"`; tables are produced via `kind: "derivation", output_kind: "table"`. Body includes `path` (the JSON pointer of the offending node) and `reason`. ### 400 invalid_registration The body parsed but failed schema validation — missing required field, unknown wire type, malformed operator params, unresolved upstream, etc. Body includes `path` and `reason`; v0 reports the first error wins. ### 409 force_required The payload would destructively mutate the registry but `force` wasn't set. Body carries the diagnostic `diff` so callers can inspect what would change before retrying with `force: true`: 409 body ``` { "code": "force_required", "reason": "Destructive registry change requires force=true. See diff for details.", "diff": { "additive": [], "destructive": [ { "kind": "type_change", "field": "Txn.amount", "from": "f64", "to": "i64" } ] } } ``` ### 415 unsupported_media_type Sent without `Content-Type: application/json`. Body: `{"error": {"code": "unsupported_media_type", "path": "/register", "reason": "expected application/json"}, "registry_version": 0}`. ## TCP equivalent The framed-TCP fast-path carries the same JSON envelope under opcode `OP_REGISTER = 0x0001`. Frame layout: `[u32 length][u16 op=0x0001][u8 content_type=0x01 (json)][payload bytes]`. Strict-FIFO correlation per connection — one in-flight request at a time; no `request_id`. Success returns the same JSON body under `OP_REGISTER`; structured errors return `OP_ERROR_RESPONSE` with the same body shape as the HTTP `error` envelope. See the full Wire spec (/sdk/http/wire-spec/) for frame details. ## Common questions Why hot-reload? Doesn't that risk inconsistency? Registration is atomic at the `registry_version` boundary: either the WAL-fsynced `RegistryBump` commits and every subsequent `/push` sees the new shape, or it doesn't and the registry is unchanged. Pushes never see a half-installed pipeline. Long-lived clients can ping the data plane and check `registry_version` to invalidate their schema cache the moment a deploy lands. Can I unregister a node? Two ways: (1) `force=true` a registration that replaces the descriptor with a new shape, or (2) restart the server with the desired registry. What goes in `optional_fields`? Field names from `schema.fields` that may be omitted on `/push`. Pushes that omit a non-optional field return `schema_mismatch`; pushes that omit a listed optional field record the field as null. Use it for late-arriving signals (e.g. an enrichment that's eventually populated) — **not** for fields you'll always send. Aggregations over an optional field skip events where it's null. Is `registered_descriptors` the same as my register payload? No — it's the full registry snapshot post-call, including descriptors installed by every prior `/register`. If the request was the first call against an empty server, the two will match by accident; in steady state they diverge. Treat `added` as "what this call did" and `registered_descriptors` as "what the server now knows about". ## Where to go next → **Wire spec** (/sdk/http/wire-spec/) — Framed-TCP layout, opcodes, status conventions, and the strict-FIFO correlation contract — every byte the server speaks. → **@bv.event** (/sdk/python/event/) — The Python decorator that compiles to the event-node JSON above. Class form, def form, and the kwargs that surface as wire fields. ======================================================================== # Wire spec Source: https://beava.dev/sdk/http/wire-spec/ # Wire spec Two transports. One JSON body shape. Strict-FIFO on TCP. The bytes that move between any beava client and the server — enough to implement a third-party SDK. ## Overview Beava ships two transports: - HTTP/1.1 on port 8080 — plain JSON, verb-style routes, ubiquitous tooling reach (curl / load-balancers / WAFs). - Custom-framed TCP fast-path on port 8081 — a four-byte length prefix plus a two-byte opcode, JSON payload, persistent connection, sub-millisecond P99. Both transports carry the same JSON envelope per opcode. The only differences are framing (HTTP headers vs the binary length-prefixed frame), the route/opcode mapping, and the strict-FIFO contract on TCP. Pick HTTP for reach; pick TCP for latency. **Admin endpoints live on a separate port.** Health, readiness, metrics and registry-introspection (`/health`, `/ready`, `/metrics`, `/registry`) are served by an admin sidecar bound to `cfg.admin_addr`. They are not part of the data-plane wire spec and are not exposed on the TCP port. ## HTTP routes All data-plane writes and reads are `POST`. Verb-style URLs only — the event name and entity key live in the JSON body, not in path segments. | Method & path | Request body | Success body | | --- | --- | --- | | POST /ping | {} | {"pong": true, "registry_version": } | | POST /register | {"nodes": [...], "force": false, "dry_run": false} | {"status": "ok", "registry_version": , "added": [...], "already_present": [...]} — 409 on a name collision without force. | | POST /push | {"event": "", "data": {...}} | {"ack_lsn": , "idempotent_replay": false, "registry_version": } | | POST /get | {"table": "", "entity_id": "", "features": [...]} | Flat row dict — e.g. {"visits": 2}. Cold-start returns {}. | | POST /batch_get | {"requests": [{"table","entity_id","features"?}, ...]} | {"results": [, ...]} — one row per request, in submission order. | | POST /reset | {} | 200 with {"reset": true, "registry_version": } when the server is in test mode; 403 + reset_disabled_in_production otherwise. | Errors on every route share one body shape — see Errors (#errors) below. ## TCP frame format Every TCP frame — request or response — has the same envelope. All multi-byte integers are big-endian (network byte order). on-wire bytes ``` [u32 length BE][u16 op BE][u8 content_type][payload: length - 3 bytes] ``` | Field | Width | Meaning | | --- | --- | --- | | length | 4 bytes BE | Bytes that follow this field — i.e. op + content_type + payload.len(). Minimum value is 3 (op + content_type, empty payload). The length itself is not counted. | | op | 2 bytes BE | Opcode. See the table below. Request and response frames share the same opcode space; the client→server direction is implicit. | | content_type | 1 byte | 0x01 = JSON. Any other byte returns unsupported_content_type; the connection stays open, only the offending frame is rejected. | | payload | length − 3 bytes | Opcode-specific JSON body. Server enforces length ≤ tcp_max_frame_bytes + 3; default is 4 MiB payload (4 * 1024 * 1024). Frames over the limit are rejected with frame_too_large and the connection is closed. | empty-payload OP_PING — 7 bytes total ``` # length=3 (op + ct), op=0x0000 (ping), ct=0x01 (JSON), payload=∅ 00 00 00 03 00 00 01 ``` ## TCP opcode table Opcodes are u16 big-endian. Opcodes outside this table return `unknown_op`. | Opcode | Name | Request payload | Response opcode & body | | --- | --- | --- | --- | | 0x0000 | OP_PING | Empty JSON ({} or zero-byte payload). | OP_GET_RESPONSE (0x0023) with {"pong": true, "registry_version": }. | | 0x0001 | OP_REGISTER | Same JSON DAG body as POST /register: {"nodes":[...], "force"?, "dry_run"?}. | OP_GET_RESPONSE with the success body, or OP_ERROR_RESPONSE on conflict. | | 0x0010 | OP_PUSH | {"event": "", "data": {...}} | OP_GET_RESPONSE with {"ack_lsn", "idempotent_replay", "registry_version"}. | | 0x0020 | OP_GET | {"table": "", "entity_id": "", "features": [...]} | OP_GET_RESPONSE with the flat row dict (cold-start: {}). | | 0x0023 | OP_GET_RESPONSE | Response-only. Generic JSON success-frame opcode shared by OP_PING, OP_REGISTER, OP_PUSH, OP_GET, OP_BATCH_GET, and OP_RESET. | Body is opcode-of-the-request-specific. | | 0x0024 | OP_BATCH_GET | {"requests": [{"table","entity_id","features"?}, ...]} — heterogeneous keys across tables in one frame. | OP_GET_RESPONSE with {"results": [, ...]} in submission order. | | 0x0040 | OP_RESET | Empty JSON ({}). Test-mode-gated — if the server is not in test mode, returns OP_ERROR_RESPONSE with reset_disabled_in_production. | OP_GET_RESPONSE with {"reset": true, "registry_version": }. | | 0xFFFF | OP_ERROR_RESPONSE | Response-only. Carries any structured error regardless of which opcode the request used. | {"error": {"code", "path", "message"}} — same shape as the HTTP error body. | ## Content type byte The single-byte `content_type` field gates payload parsing. v0 ships one value: `0x01` = `CT_JSON`. Every frame the SDKs send sets this byte; server-to-client response frames also use `0x01`. Any other content-type byte returns `OP_ERROR_RESPONSE` with code `unsupported_content_type`. The connection is *not* closed — only that frame is rejected, so a misconfigured client doesn't tear down a healthy long-lived session. ## Strict-FIFO contract Beava's TCP transport is **strict-FIFO**: at most one in-flight request per connection, and the server replies in the exact order it received requests. There is no `request_id` field on the wire because the order is the correlation. Concretely: - A client writes one frame, then waits for one response frame, then writes the next. - If a client writes two frames back-to-back, the server still replies in submission order — but the client must not interpret responses out of order or interleave reads from multiple application threads on the same socket. - The Python SDK's TCP transport enforces this client-side: a TCP-mode bv.App serialises send/recv on the socket, and concurrent calls from multiple threads block on a per-connection lock rather than racing the wire. **Do not multiplex on a single TCP connection.** Sharing a TCP connection across application threads or async tasks *without* a strict-FIFO mutex will interleave frames and corrupt the wire — there is no per-frame correlation ID to recover from. If you need parallelism on TCP, open multiple connections (one per thread or per task pool worker), each with its own send/recv lock. ## Errors Every error — HTTP or TCP — has the same body shape: error body ``` { "error": { "code": "event_not_found", "path": "/push", "message": "Unknown event 'PageView'" } } ``` Over HTTP this body is returned with the appropriate `4xx` / `5xx` status. Over TCP it is wrapped in a frame whose opcode is `OP_ERROR_RESPONSE = 0xFFFF` regardless of which opcode the request used. The `code` field is a stable string SDK clients can match on (e.g. `event_not_found`, `invalid_event`, `unknown_table`, `reset_disabled_in_production`, `unsupported_content_type`, `unknown_op`, `frame_too_large`). ## HTTP vs TCP — when to use which | | HTTP/1.1 (port 8080) | TCP framed (port 8081) | | --- | --- | --- | | Reach | Anything that speaks HTTP — curl, browsers, load-balancers, WAFs, sidecars. | Custom protocol; you write or use a beava SDK. | | Latency | ~1–2 ms per RTT typical; dominated by HTTP parsing on both ends. | Sub-millisecond P99 on a warm connection. | | Connection model | Pooled / keep-alive. Stateless on the wire — any worker can answer. | Persistent. Strict-FIFO on a single socket; one in-flight request per connection. | | Payload | JSON. | JSON. | | Best for | Bootstrapping, ops dashboards, server-side scripts, anything behind a load-balancer. | Hot-path push/get from latency-sensitive clients (fraud-rule engines, ad-tech bidders). | ## Common questions Can I tunnel TCP through HTTP (e.g. via WebSockets)? No. The TCP fast-path is a raw length-prefixed framing — it has no upgrade dance, no HTTP framing, no WebSocket envelope. If you can't reach port 8081 directly, use the HTTP transport. Beava deliberately does not try to be both. What's the maximum frame size? The configured `tcp_max_frame_bytes` applies to the *payload*, not the whole frame. Default is **4 MiB** (`4 * 1024 * 1024` = `4194304` bytes). The server accepts a `length` field of up to `tcp_max_frame_bytes + 3` (the `+3` covers `op + content_type`). Frames over the limit are rejected with `frame_too_large`; the connection is closed because the rest of the stream is not parseable. HTTP `POST` bodies have a parallel cap configured separately on the HTTP listener. Is the wire format stable? The opcodes and their semantics are locked for v0. Existing opcodes never change shape; new wire features get new opcode numbers. How do I implement a third-party SDK? Two layers. (1) A frame writer/reader: 4-byte length + 2-byte opcode + 1-byte content-type + payload. ~50 LOC in any language. (2) A JSON serialiser per opcode whose body shape is documented above. ~150 LOC for the six request opcodes (`OP_PING`, `OP_REGISTER`, `OP_PUSH`, `OP_GET`, `OP_BATCH_GET`, `OP_RESET`) plus the two response opcodes. Hold the strict-FIFO discipline (one in-flight request per socket, send/recv under a mutex) and you're done. The Python SDK's TCP transport is a good reference at ~250 LOC. ## Where to go next You've got the wire. The next things are the client that speaks it and the routes that consume it: → **App client** (/sdk/python/app/) — The synchronous Python client. Seven wire-mapped methods (register, push, get, batch_get, reset, ping, close), three transport modes (HTTP / TCP / embed), plus the lifecycle. → **POST /push** (/sdk/http/push/) — Per-route reference for the push opcode — request body shape, response body shape, error codes, idempotency contract, and a worked example.