# libds series backings

How libds's seven built-in series backends are shaped and registered. An
integrator supplies and registers none
([NSBK.2.3]), so the structure here is libds's own: the vtable each backend fills
in, the declaration each instance is created from, and the checks libds makes
when it registers them at engine construction.

## What this is not

- Not integrator contract. What an integrator meets of the series backends —
  which backings exist, their identities in the platform signature, the
  integrator's read — is
  [NSBK].
- Not the author-side series language — see
  [LSER].

---

(ISBK-1)=
## The backend vtable [ISBK.1]

One structure is the whole contract between libds's engine and each of its
series backends ([NSBK.2]). The engine calls nothing a backend has not put
here, and knows nothing about it beyond the identifying fields at the head. It
is libds's internal shape, not integrator contract: an integrator supplies no
backend ([NSBK.2.3]).

Four entry points are **required** -- create per-key state, release it, absorb
a sample, answer a query ([ISBK.1.2]-[ISBK.1.4]). Everything past them may be
absent, and the ABI version in the header ([ISBK.1.1]) is what tells libds how
much of the tail is present at all ([ISBK.1.7]).

An absent optional entry point is an **answer, not an omission**. No stale
sweep means the backend needs no wall-clock eviction ([ISBK.1.5]); no
as-of-now query means reads land as of the last absorbed sample ([ISBK.1.8]);
no clone means an engine holding a live series on this backend cannot be
cloned at all ([ISBK.1.9]). Leaving a hook out states something about the
backend's semantics, so leave it out deliberately.

```c
typedef struct ds_series_backend_vtable {
    uint32_t    abi_version;     /* must equal DS_SERIES_BACKEND_ABI_VERSION */
    const char *backend_name;    /* e.g. "ds-ring-buffer" */
    const char *backend_version; /* impl-defined; part of the replay platform signature */
    uint32_t    atom_field;      /* the backing atom's field number ([ISBK.1.1]) */
    uint64_t    supported_aggs;  /* bitmask of DS_SERIES_AGG_* ordinals */

    ds_result_t (*instance_new)(const ds_series_decl_t *decl, void **out_state);   /* REQUIRED */
    void        (*instance_free)(void *state);                                     /* REQUIRED */
    ds_result_t (*update)(void *state, const ds_slot_value_t *value, uint64_t ts_ns); /* REQUIRED */
    ds_result_t (*query)(void *state, ds_series_agg_kind_t agg, uint64_t window_ns,
                         ds_slot_value_t *out_value);                              /* REQUIRED */
    void        (*evict_stale)(void *state, uint64_t now_ns);                      /* OPTIONAL (NULL ok) */
    ds_result_t (*query_with_value)(void *state, ds_series_agg_kind_t agg,
                         uint64_t window_ns, const ds_slot_value_t *lookup_value,
                         uint32_t k_param, ds_slot_value_t *out_value);            /* OPTIONAL (ABI v2) */
    ds_result_t (*instance_clone)(const void *state, void **out_state);           /* OPTIONAL (ABI v4) */
    ds_result_t (*query_at)(void *state, ds_series_agg_kind_t agg, uint64_t window_ns,
                         uint64_t now_ns, ds_slot_value_t *out_value);             /* OPTIONAL (ABI v5) */
} ds_series_backend_vtable_t;
```

*see also:* [ISBK.1.1](#ISBK-1-1), [ISBK.1.2](#ISBK-1-2), [ISBK.1.4](#ISBK-1-4), [ISBK.1.5](#ISBK-1-5), [ISBK.1.7](#ISBK-1-7), [ISBK.1.8](#ISBK-1-8), [ISBK.1.9](#ISBK-1-9), [NSBK.2](#NSBK-2), [NSBK.2.3](#NSBK-2-3)

(ISBK-1-1)=
[ISBK.1.1] **Header (required).** `abi_version` gates the whole structure
(mismatch → `DS_ERR_BACKEND_ABI_VERSION`). `atom_field` binds the backend to one
of the seven backings of [NSBK.6.1]: it is the field number of the backing's
atom ([RFCS.16.1]), the number a `.dsc` carries the series' atom under, so the
loader keys a declaration to its backend with no translation. `supported_aggs` is a bitmask over the
`ds_series_agg_kind_t` ordinals; build it with `DS_SERIES_AGG_BIT(k)`.
`ds_series_agg_kind_t`, declared in libds's internal series header with the
vtable, must mirror `specs/registry/series_agg.ebnf` ([NSBK.6.3]) name for name
and value for value.
`backend_name` / `backend_version` are identity strings that feed the replay
platform signature ([NSBK.7.1]).

*see also:* [NSBK.6.1](#NSBK-6-1), [NSBK.6.3](#NSBK-6-3), [NSBK.7.1](#NSBK-7-1), [RFCS.16.1](#RFCS-16-1)

(ISBK-1-2)=
[ISBK.1.2] **Lifecycle (required).** `instance_new` receives the resolved
`ds_series_decl_t` ([ISBK.2]) and allocates per-key state into `*out_state`
(opaque to libds). `instance_free` releases it at engine teardown.

*see also:* [ISBK.2](#ISBK-2)

(ISBK-1-3)=
[ISBK.1.3] **`update` (required).** Absorbs one sample. `value->kind` matches the
slot's schema type; reject an unsupported kind with `DS_ERR_INVAL`.

(ISBK-1-4)=
[ISBK.1.4] **`query` (required).** `agg` selects the aggregation
(`DS_SERIES_AGG_*`); `window_ns` is the declared series window (ignored by some
backends). Set `out_value->kind` (typically `DS_SLOT_FLOAT`; `DS_SLOT_INT` for
counts).

(ISBK-1-5)=
[ISBK.1.5] **`evict_stale` (optional, NULL ok).** Drops the samples that have
left the window at `now_ns`. libds calls it at the step's clock in two places:
in the series sweep after each pump's absorption, and before every rule read of
the backing ([RDSC.5a.1a]). A backing whose window is a trimmed sequence of
samples carries it: the ring buffer, the FIFO deque and the monotonic deque
([LSER.9.3.1]). One with no window, or whose `query_at` already answers at the
clock ([ISBK.1.8]), leaves it NULL ([ISBK.3.5]).

*see also:* [ISBK.1.8](#ISBK-1-8), [ISBK.3.5](#ISBK-3-5), [LSER.9.3.1](#LSER-9-3-1), [RDSC.5a.1a](#RDSC-5a-1a)

(ISBK-1-6)=
[ISBK.1.6] **`query_with_value` (optional, ABI v2).** For the aggregations a
rule reads with a value — `DS_SERIES_AGG_COUNT_OF` and `DS_SERIES_AGG_CONTAINS`,
whose value is the one looked up, and `DS_SERIES_AGG_PERCENTILE`, whose value is
the percentile — all exact over the window. libds passes `k_param` as 0 on every
call: no aggregation in this edition takes a `k`. A read that no declared
backing with this hook can serve answers the aggregation's cold value
([LSER.19.8]) and stashes `DS_ERR_SERIES_NO_BACKING` for the pump to return
([NERR.6]).

*see also:* [LSER.19.8](#LSER-19-8), [NERR.6](#NERR-6)

(ISBK-1-7)=
[ISBK.1.7] **ABI evolution.** libds adds vtable fields only at the tail and
bumps `DS_SERIES_BACKEND_ABI_VERSION` when it does. Every backend is libds's own
and is built with the header it registers against ([NSBK.2.3]), so an
integrator never meets a mismatch through a backend. libds still checks each
backend's `abi_version` at registration, and a mismatch fails engine
construction with `DS_ERR_BACKEND_ABI_VERSION` ([NSBK.2]).

*see also:* [NSBK.2](#NSBK-2), [NSBK.2.3](#NSBK-2-3)

(ISBK-1-8)=
[ISBK.1.8] **`query_at` (optional, ABI v5).** Reads the aggregation **as of an
explicit monotonic-clock `now_ns`** ([LTIM.2.8.2]), not as of the last absorbed
sample — the read-only discount + open-interval extrapolation the signal
aggregations need when a rule queries after a quiet gap ([LSIG.2.5]). Every rule
read of a backing that carries it goes through it, at the step's held sample
([LTIM.2.8.4]). The hook requires `now_ns` no earlier than the row's last
absorb, so libds raises `now_ns` to that absorb when a sample stamped ahead of
the clock is the newest. A NULL hook means reads land as of the last absorb,
through `query`.

*see also:* [LSIG.2.5](#LSIG-2-5), [LTIM.2.8.2](#LTIM-2-8-2), [LTIM.2.8.4](#LTIM-2-8-4)

(ISBK-1-9)=
[ISBK.1.9] **`instance_clone` (optional, ABI v4).** Deep-copies per-key state
into `*out_state` — **verbatim**, including any PRNG state (the reservoir's
`xorshift64` seed) and every owned buffer / string — so a cloned engine's series
are exact, not cold-started ([IARC.11.2] / [LDET.2.2b]). The copy is caller-owned
and freed via `instance_free`, independently of the source; `DS_ERR_OOM` on
allocation failure leaves the source unchanged. Consumed by the engine-clone
deep-copy (the `[IARC.11.1]` deep-copy-mutable set).

**Every backend libds ships must set the hook.** The backend set is closed
([NSBK.2.3]), so no engine an integrator holds has a series that cannot be
cloned. A NULL hook is a defect in libds's own registration, and
`ds_engine_clone` refuses an engine holding a live series row on such a backend
with `DS_ERR_STATE` rather than cold-start it.

---

*see also:* [IARC.11.1](#IARC-11-1), [IARC.11.2](#IARC-11-2), [LDET.2.2b](#LDET-2-2b), [NSBK.2.3](#NSBK-2-3)

(ISBK-2)=
## The series declaration [ISBK.2]

(ISBK-2-1)=
[ISBK.2.1] `instance_new` receives a resolved `ds_series_decl_t`. Strings are
borrowed for the call only — copy before retaining.

The declaration names the series' schema, its slot and its identity slot, which
is the empty string for `by: none`. Its `window_ns` is `0` for an unwindowed
series and its `persist_ns` `0` for a live-only one. Its `atom_field` is the
backing atom's field number ([ISBK.1.1]). Its `element_type` is `UNSPECIFIED`
(`0`) where the backing reads none, and its `max_samples` is `0` for the
backend's default. `time_model` and `gap_policy` are [ISBK.2.2]'s.

```c
typedef struct ds_series_decl {
    const char *schema_name;
    const char *slot_name;
    const char *identity_slot_name;   /* "" for `by: none` */
    uint64_t    window_ns;            /* 0 = unwindowed */
    uint64_t    persist_ns;           /* 0 = live-only */
    uint32_t    atom_field;           /* the backing atom's field number ([ISBK.1.1]) */
    ds_series_element_type_t element_type; /* 0 = unspecified */
    uint32_t    max_samples;          /* 0 = backend default */
    uint32_t    time_model;           /* ds_series_time_model_t; the numeric integral only */
    uint32_t    gap_policy;           /* ds_series_gap_policy_t; the numeric integral only */
} ds_series_decl_t;
```

`ds_series_element_type_t`, declared in libds's internal series header with the
vtable, must mirror `proto/series_backend_ring_buffer.proto#SeriesElementType`
([NSBK.5.3]) member for member and value for value, `UNSPECIFIED` included.

*see also:* [ISBK.1.1](#ISBK-1-1), [ISBK.2.2](#ISBK-2-2), [NSBK.5.3](#NSBK-5-3)

(ISBK-2-2)=
[ISBK.2.2] The mode-specific fields are **reused** across backends; the backend
dispatches on its own `atom_field` and reads only the fields meaningful to it —
e.g. `element_type` (the ring buffer, the FIFO deque and the monotonic deque),
`max_samples` (ring cap / reservoir k). `time_model` and `gap_policy` are read
by the numeric integral alone ([LSIG.2.3.6]) and are `0` for every other
backing.

---

*see also:* [LSIG.2.3.6](#LSIG-2-3-6)

(ISBK-3)=
## Registration [ISBK.3]

(ISBK-3-1)=
[ISBK.3.1] The built-in ring-buffer backend is the reference implementation of
the vtable; it lives in `runtime/src/libds/series/ring_buffer.c` +
`runtime/src/libds/series/ring_buffer_backend.c` and is compiled into `libds.a`,
registered with the other six when libds constructs an engine ([NSBK.2]). Its
name and version, and the other six's, are [NDET.2.5]'s.

It is the reference in the sense that every other backend's vtable is shaped
like it — not in the sense that an integrator may supply a competing one
([NSBK.2.3]).

*see also:* [NDET.2.5](#NDET-2-5), [NSBK.2](#NSBK-2), [NSBK.2.3](#NSBK-2-3)

(ISBK-3-2)=
[ISBK.3.2] **`supported_aggs` validation.** Each backing has a static
upper-bound set of aggregations it may serve. A backend may declare a
**subset**; one declaring a **superset** fails registration, and so engine
construction, with `DS_ERR_BACKEND_BAD_AGGS` ([NSBK.2]). The aggregation
ordinals are `ds_series_agg_kind_t` (`DS_SERIES_AGG_AVG` …
`DS_SERIES_AGG_PERCENTILE`; [NSBK.6.3]).

*see also:* [NSBK.2](#NSBK-2), [NSBK.6.3](#NSBK-6-3)

(ISBK-3-3)=
[ISBK.3.3] **`atom_field` validation.** A backend whose `atom_field` names none
of the seven backings of [NSBK.6.1] fails registration, and so engine
construction, with `DS_ERR_BACKEND_BAD_MAGIC` ([NSBK.2]).

*see also:* [NSBK.2](#NSBK-2), [NSBK.6.1](#NSBK-6-1)

(ISBK-3-4)=
[ISBK.3.4] **Order and atomicity.** libds validates every backend in a
registration before it registers any, so a bad entry registers nothing. Each
backend is checked in this order, and the first check it fails is the answer:

1. a missing vtable: `DS_ERR_INVAL`;
2. the ABI version ([ISBK.1.7]);
3. the backing ([ISBK.3.3]);
4. the aggregation set ([ISBK.3.2]);
5. the four required entry points ([ISBK.1]): `DS_ERR_INVAL`.

Once every entry passes, a backend for a backing already registered, or two for
one backing in the same registration, is `DS_ERR_STATE`, and nothing registers:
each backing has exactly one backend ([NSBK.2.3]). libds registers the seven
itself when it constructs an engine ([NSBK.2]), so an integrator meets none of
these codes but through a defect in libds.

*see also:* [ISBK.1](#ISBK-1), [ISBK.1.7](#ISBK-1-7), [ISBK.3.2](#ISBK-3-2), [ISBK.3.3](#ISBK-3-3), [NSBK.2](#NSBK-2), [NSBK.2.3](#NSBK-2-3)

(ISBK-3-5)=
[ISBK.3.5] **The seven backends.** Each backing's static aggregation set
([ISBK.3.2]), and the optional entry points its backend carries ([ISBK.1.5],
[ISBK.1.6], [ISBK.1.8]). Every one carries `instance_clone` ([ISBK.1.9]). Names
and versions are [NDET.2.5]'s.

| Backing | Static aggregation set | `evict_stale` | `query_with_value` | `query_at` |
|---|---|---|---|---|
| `SeriesBackendWelfordEwma` | avg, stdev, pstdev, variance, pvariance, min, max, rate, direction, count, sum, first, last, bool_and, bool_or | | | |
| `SeriesBackendRingBuffer` | the Welford set, and median, count_distinct, count_of, contains, percentile, onset_rate | yes | yes | yes |
| `SeriesBackendMonotonicDeque` | min, max | yes | | |
| `SeriesBackendFifoDeque` | first, last, bool_and, bool_or | yes | | |
| `SeriesBackendReservoir` | avg, stdev, pstdev, variance, pvariance, min, max, sum, count, median, percentile, bool_and, bool_or | | yes | |
| `SeriesBackendIntervalPulse` | active_fraction | | | yes |
| `SeriesBackendNumericIntegral` | integral | | | yes |

A static set bounds what a backend may serve. Which backing serves each
aggregation in a program is [LSER.18.1]'s and [LSIG.1.1]'s.

---

*see also:* [ISBK.1.5](#ISBK-1-5), [ISBK.1.6](#ISBK-1-6), [ISBK.1.8](#ISBK-1-8), [ISBK.1.9](#ISBK-1-9), [ISBK.3.2](#ISBK-3-2), [LSER.18.1](#LSER-18-1), [LSIG.1.1](#LSIG-1-1), [NDET.2.5](#NDET-2-5)

