> Fetch the index of the TinyStore docs, every page as markdown, at https://tinyshed.org/tinystore/llms.txt

# TinyStore 0.13.0

TinyStore 0.13.0 came out on 27 November 2026. In SQL, a table can now mirror the
rows of another system, hide its deleted rows, and reject an edit that was
made from an old version. A `once` handle can return its last answer
immediately while it builds a new one in the background. A semaphore lets a
person's request go ahead of background work, and it pauses when the
service behind it is down. A queue can gather many events into one job and
hold that job until the morning. Search understands abbreviations and can
query several indexes in one call. A stream's query can be limited to the
rows of a SQL statement, and it can split events into sessions. Metrics can
compare a window with the usual value and write Prometheus' text format.

- **SQL**
  - [What a statement answers](#what-a-statement-answers): `describe`, its columns without running it.
  - [A mirror of another system's rows](#a-mirror-of-another-systems-rows): `mirror`, `replace` and `upsert`, with what was added, changed and gone.
  - [Deleted rows and versions](#deleted-rows-and-versions): `deleted` and `version`, `ifVersion`, `restore` and `purge`.
- **KV**
  - [An answer kept while a new one is made](#an-answer-kept-while-a-new-one-is-made): `fresh`, `fetch` and `clear`.
- **Locks**
  - [Urgent and background holds](#urgent-and-background-holds): `background`, a hold's priority and its `timeout`.
  - [A pause when a service is down](#a-pause-when-a-service-is-down): `breaker`, `permit.healthy()` and `state`.
- **Jobs**
  - [Gather what arrives into one job](#gather-what-arrives-into-one-job): `gather`, with `settle` and `max`.
  - [Quiet hours](#quiet-hours): `quiet`, a queue's hours or a job's own.
- **Search**
  - [Cut a snippet](#cut-a-snippet): the piece of a field around its first match.
  - [Abbreviations and synonyms](#abbreviations-and-synonyms): `synonyms`, read both ways.
  - [Ask several indexes at once](#ask-several-indexes-at-once): `store.search`, its groups and `merged`.
- **Records**
  - [A where kept to a database's statement](#a-where-kept-to-a-databases-statement): `db.statement` in a `where`.
  - [Sessions](#sessions): a stream's events cut by a pause.
- **Metrics**
  - [Compare now with usual](#compare-now-with-usual): `compare`, a window against the windows before it.
  - [To Prometheus](#to-prometheus): the newest sample of every series as Prometheus' text, in Rust.
- **Command line**
  - [Export metrics and events](#export-metrics-and-events): `metrics export` and `events export`.
  - [Times in one zone](#times-in-one-zone): `--tz` and `TINYSTORE_TZ`.

> \[!WARNING]
> **Bun, Node and Python: a database's `describe` is now `label`**
> A database and its transaction had a text property `describe`, such as
> `'sql app'`, that names it in errors. `describe` is now the call that
> describes a statement's columns, and the text is `label`:
>
> ```diff
> - log.warn(`${db.describe}: sync skipped`)
> + log.warn(`${db.label}: sync skipped`)
> ```

## What a statement answers

`describe` returns the columns that a statement returns, in the statement's
order, without running it. For example, a console, a dashboard or an export
that shows a statement someone else wrote can show its column names even
when the statement returns no rows
([What a statement answers](https://tinyshed.org/tinystore/docs/guides/sql.md#what-a-statement-answers)):

```ts
const columns = await db.describe`select id, title, length(title) as size from notes where author_id = ${userId}`
// [{ name: 'id', type: 'TEXT' }, { name: 'title', type: 'TEXT' }, { name: 'size' }]
```

```python
columns = await db.describe("select id, title, length(title) as size from notes where author_id = ?", user_id)
# [Column(name='id', type='TEXT'), Column(name='title', type='TEXT'), Column(name='size', type=None)]
```

```go
columns, err := sqldb.Describe(ctx, db, `select id, title, length(title) as size from notes where author_id = ?`, userID)
// [{Name:id Type:TEXT} {Name:title Type:TEXT} {Name:size Type:}]
```

```rust
let columns = db.describe(sql!("select id, title, length(title) as size from notes where author_id = ?", user_id))?;
// [Column { name: "id", declared: Some("TEXT") }, …, Column { name: "size", declared: None }]
```

- A column that comes straight from a table has the type that the table
  declares. An expression has no type.
- `describe` runs no part of the statement, so it also works on a statement
  given as text alone, without its values.
- A statement that writes fails with `invalid` (contract SQL-16).
- When a query finds no rows, `tinystore sql` on the command line now prints
  the query's columns with `no rows` under them.

## A mirror of another system's rows

Before this release, a program that synced a course's works from another
system had to compare the list with its table by hand, row by row. A mirror
does this for you. You give it the list that the source returned. It writes
only the difference, in one commit, and returns the rows that were added,
changed and gone ([Mirrors](https://tinyshed.org/tinystore/docs/guides/sql/mirror.md)):

```ts
const works = db.mirror<Work>('works', { key: ['course_id', 'id'], gone: 'gone_at', changeOn: ['grade'] })

const diff = await works.replace({ course_id: 1 }, fetched, { minKept: 0.5 })
for (const { before, after } of diff.changed) notify(after, before.grade, after.grade)
// diff: { added: Work[], changed: { before, after }[], gone: Work[], same: 41, suspect: false }
await works.upsert(changedSinceYesterday) // a delta: adds and changes, marks nothing gone
```

```python
works = db.mirror("works", Work, key=["course_id", "id"], gone="gone_at", change_on=["grade"])

diff = await works.replace({"course_id": 1}, fetched, min_kept=0.5)
for changed in diff.changed:
    notify(changed.after, changed.before.grade, changed.after.grade)
await works.upsert(changed_since_yesterday)
```

```go
works := sqldb.OpenMirror[Work](db, "works", sqldb.MirrorOptions{
	Key: []string{"course_id", "id"}, Gone: "gone_at", ChangeOn: []string{"grade"},
})

diff, err := works.Replace(ctx, map[string]any{"course_id": 1}, fetched, sqldb.MinKept(0.5))
for _, changed := range diff.Changed {
	notify(changed.After, changed.Before.Grade, changed.After.Grade)
}
diff, err = works.Upsert(ctx, changedSinceYesterday)
```

```rust
let works = db.mirror::<Work>("works").key(["course_id", "id"]).gone("gone_at").change_on(["grade"]).open()?;

let diff = works.min_kept(0.5).replace(&[("course_id", 1)], &fetched)?;
for changed in &diff.changed {
    notify(&changed.after, changed.before.grade, changed.after.grade);
}
works.upsert(&changed_since_yesterday)?;
```

- `replace(scope, rows)` makes the rows of the scope (here, course 1) match
  the list. If a row in the list is the same as the stored row, it is not
  written at all (contracts SQL-17, SQL-18 and SQL-19).
- With `gone`, a row that is missing from the list is marked with the time
  instead of deleted. `changeOn / change_on / ChangeOn / change_on` sets the
  columns that count: a row is `changed` only when one of them changes.
- `minKept / min_kept / MinKept / min_kept` protects you from a source that
  returns an empty page during an outage. If the list would keep fewer than
  that fraction of the scope's rows, nothing is written, and the result has
  `suspect: true` (contract SQL-20).
- In Rust, a mirror can join its database's transaction with
  `tx.with(&works)`. The SDKs can't use a mirror inside a transaction yet.
- A saved sync state per scope, such as a cursor that the next call resumes
  from, is not built.

On 5,000 rows where 1 % had changed, a `replace` wrote 50 rows in 9.2 ms.
Deleting every row and inserting the list wrote 5,000 rows in 15.0 ms, and
an upsert of the list wrote 5,000 rows in 17.6 ms. These are the medians of
nine passes in one run, with a release build on a 4 vCPU Intel Xeon
2.10 GHz Linux container with 15 GiB, while other builds shared the CPU:

```sh
cargo test --release -p tinystore --lib --features async,testing mirror_against_the_loops -- --ignored --nocapture
```

## Deleted rows and versions

A table's handle can now manage two columns for you. With `deleted`, a delete
marks the row instead of removing it, and every call on the handle skips
marked rows. With `version`, an edit made from an old version fails with a
conflict error instead of overwriting someone else's work
([Deleted rows and versions](https://tinyshed.org/tinystore/docs/guides/sql/deleted-and-versions.md)):

```ts
const tasks = db.table<Task>('tasks', { deleted: 'deleted_at', version: 'version' })

const seen = await tasks.where({ id: 1 }).one() // { id: 1, title: 'Draft', deleted_at: null, version: 0 }
await tasks.where({ id: 1 }).update({ title: 'from Ann' }, { ifVersion: seen!.version }) // version 1
await tasks.where({ id: 1 }).update({ title: 'from Ben' }, { ifVersion: seen!.version })
// ConflictError: sql app: table tasks: the row is at version 1, not 0

await tasks.where({ id: 1 }).delete() // sets deleted_at, and the row stays in the file
await tasks.where({ id: 1 }).restore() // clears deleted_at: the row is back
await tasks.deletedOnly().where('deleted_at < ?', monthAgo).purge() // deletes for good
```

```python
tasks = db.table("tasks", Task, deleted="deleted_at", version="version")

seen = await tasks.where(id=1).one()  # Task(id=1, title='Draft', deleted_at=None, version=0)
await tasks.where(id=1).update({"title": "from Ann"}, if_version=seen.version)  # version 1
await tasks.where(id=1).update({"title": "from Ben"}, if_version=seen.version)
# tinystore.ConflictError: sql app: table tasks: the row is at version 1, not 0

await tasks.where(id=1).delete()  # sets deleted_at, and the row stays in the file
await tasks.where(id=1).restore()  # clears deleted_at: the row is back
await tasks.deleted_only().where("deleted_at < ?", month_ago).purge()  # deletes for good
```

```go
tasks := sqldb.OpenTable[Task](db, "tasks", sqldb.Deleted("deleted_at"), sqldb.Version("version"))

seen, _, err := tasks.Where(sqldb.Eq{"id": 1}).One(ctx) // {ID:1 Title:Draft DeletedAt:<nil> Version:0}
_, err = tasks.Where(sqldb.Eq{"id": 1}).Update(ctx, sqldb.Set{"title": "from Ann"}, sqldb.IfVersion(seen.Version))
_, err = tasks.Where(sqldb.Eq{"id": 1}).Update(ctx, sqldb.Set{"title": "from Ben"}, sqldb.IfVersion(seen.Version))
if errors.Is(err, tinystore.ErrConflict) {
	// sql app: table tasks: the row is at version 1, not 0
}

_, err = tasks.Where(sqldb.Eq{"id": 1}).Delete(ctx)  // sets deleted_at, and the row stays in the file
_, err = tasks.Where(sqldb.Eq{"id": 1}).Restore(ctx) // clears deleted_at: the row is back
_, err = tasks.DeletedOnly().Where(sqldb.SQL("deleted_at < ?", monthAgo)).Purge(ctx) // deletes for good
```

```rust
let tasks = db.table::<Task>("tasks").deleted("deleted_at").version("version");

let seen = tasks.filter(sql::eq("id", &1)).one()?.unwrap(); // Task { id: 1, title: "Draft", deleted_at: None, version: 0 }
tasks.filter(sql::eq("id", &1)).if_version(seen.version).update([("title", sql::value("from Ann"))])?; // version 1
let ben = tasks.filter(sql::eq("id", &1)).if_version(seen.version).update([("title", sql::value("from Ben"))]);
if ben.is_err_and(|error| error.kind() == ErrorKind::Conflict) {
    // sql app: table tasks: the row is at version 1, not 0: conflict
}

tasks.filter(sql::eq("id", &1)).delete()?; // sets deleted_at, and the row stays in the file
tasks.filter(sql::eq("id", &1)).restore()?; // clears deleted_at: the row is back
tasks.deleted_only().filter(sql!("deleted_at < ?", month_ago)).purge()?; // deletes for good
```

- Your migration creates the columns in the table. A table opened without
  these options writes exactly the same statements as before.
- The handle doesn't show, count or change a marked row unless you ask for
  it with `withDeleted()` or `deletedOnly()` (contract SQL-21). A `purge` on
  the plain handle fails with `invalid`, so it never removes live rows
  (contract SQL-22).
- `ifVersion` is checked in a single statement, so an edit of several rows
  writes all of them or none (contracts SQL-23 and SQL-24).
- A statement that you write by hand, such as `db.all('select …')`, sees
  every row.

## An answer kept while a new one is made

With only `keep`, every caller had to wait for a whole new build after
`keep` ran out, and a failed build left nothing to return. With `fresh`, the
handle returns the older answer immediately and builds one new answer in the
background. If that build fails, the last good answer stays in place
([Once](https://tinyshed.org/tinystore/docs/guides/kv/once.md#an-answer-kept-while-a-new-one-is-made)):

```ts
const books = store.once<GradeBook>('cabinet-books', { fresh: '10m', keep: '12h' })

const { value, age, stale } = await books.fetch(String(userId), () => cabinet.book(userId))
await books.under(courseId).clear() // a branch and every branch under it, in one commit
```

```python
books = store.once("cabinet-books", GradeBook, fresh="10m", keep="12h")

answer = await books.fetch(str(user_id), lambda: cabinet.book(user_id))  # answer.value, .age, .stale
await books.under(course_id).clear()
```

```go
books, err := kv.OpenOnce[GradeBook](store, "cabinet-books", kv.Fresh(10*time.Minute), kv.Keep(12*time.Hour))

answer, err := books.Fetch(ctx, strconv.Itoa(userID), func(ctx context.Context) (GradeBook, error) { return cabinet.Book(ctx, userID) })
// answer.Value, answer.Age, answer.Stale
err = books.Under(courseID).Clear(ctx)
```

```rust
let books = store.once::<GradeBook>("cabinet-books").fresh(Duration::from_mins(10)).keep(Duration::from_hours(12)).open()?;

let cabinet = cabinet.clone(); // the build may outlive the call, so it owns what it uses
let answer = books.fetch(user_id, move || cabinet.book(user_id))?; // answer.value, answer.age, answer.stale
books.under(course_id).clear()?;
```

- Only one background build per key runs at a time, across every client of
  the store (contract KV-16). After a failed build, the next one waits for a
  tenth of `fresh`, but at least a second and at most a minute (contract
  KV-17).
- `fetch` returns the value with its `age` and whether it is `stale`
  (contract KV-18). `run` returns only the value, as before.
- `clear` deletes every answer in a branch and in the branches under it, in
  one commit (contract KV-19).
- In Rust with async, a handle opened with `fresh` needs `spawn`, the
  runtime that runs the background build.
- The store's own metrics count the builds per name
  (`tinystore_once_builds_total` and `tinystore_once_build_failures_total`)
  and the stale answers (`tinystore_once_stale_total`)
  ([self-metrics](https://tinyshed.org/tinystore/docs/guides/metrics/self-metrics.md)).
- Waiting a limited time for the new answer before falling back to the
  stale one is not built.

## Urgent and background holds

Say every request to an outside service goes through one semaphore. While a
person waits, background jobs should not fill the line. A semaphore can now
reserve places for urgent holds. A hold's `timeout` starts counting when
the hold gets its place
([Semaphores](https://tinyshed.org/tinystore/docs/guides/locks/semaphores.md#urgent-and-background)):

```ts
const cabinet = store.semaphore('cabinet', { limit: 8, background: 4 })

await cabinet.hold('requests', permit => syncGrades(permit.signal), {
	priority: 'background',
	wait: '60s',
	timeout: '15s',
})
await cabinet.hold('requests', permit => fetchProfile(user.id, permit.signal)) // urgent: passes the background line
```

```python
cabinet = store.semaphore("cabinet", limit=8, background=4)

async with cabinet.hold("requests", priority="background", wait="60s", timeout="15s"):
    await sync_grades()
async with cabinet.hold("requests"):  # urgent: passes the background line
    await fetch_profile(user.id)
```

```go
cabinet, err := locks.OpenSemaphore(store, "cabinet", locks.Limit(8), locks.Background(4))

err = cabinet.Hold(ctx, "requests", syncGrades,
	locks.InBackground(), locks.Wait(time.Minute), locks.Timeout(15*time.Second))
err = cabinet.Hold(ctx, "requests", fetchProfile) // urgent: passes the background line
```

```rust
let cabinet = store.semaphore("cabinet").limit(8).background(4).open()?;

cabinet
    .key("requests")
    .background()
    .wait(Duration::from_secs(60))
    .timeout(Duration::from_secs(15))
    .hold(|_| sync_grades())?;
cabinet.hold("requests", |_| fetch_profile(&user.id))?; // urgent: passes the background line
```

- A hold is urgent unless you ask for background priority, so every hold in
  code written before this release is urgent.
- `background` sets how many of a key's places background holds can take at
  once. With 8 places and `background: 4`, urgent holds always have 4
  places. Within each priority, holds are served in the order they arrived
  (contracts LOCK-09 and LOCK-10).
- When a hold runs past its `timeout`, it loses its place and fails with a
  lost error, the same as at `maxHold`, and its signal aborts (contract
  LOCK-11).

## A pause when a service is down

Before this release, when the service behind a semaphore was down, every
caller waited for its own timeout. A breaker marks the key as down for a
pause after a set number of failed holds in a row, and every caller learns
about it immediately
([Semaphores](https://tinyshed.org/tinystore/docs/guides/locks/semaphores.md#a-pause-when-what-it-guards-is-down)):

```ts
const cabinet = store.semaphore('cabinet', { limit: 8, breaker: { failures: 2, pause: '30s' } })

try {
	return await cabinet.hold('requests', async permit => {
		const response = await fetch(url, { signal: permit.signal })
		if (response.status === 404) {
			permit.healthy() // the cabinet answered: it is up
			throw new NotFound(user.id)
		}
		return response.json()
	})
} catch (err) {
	if (err instanceof UnavailableError) return showCached(user.id) // the cabinet is down
	throw err
}
const { up, downSince, waiting, holding } = await cabinet.state('requests')
```

```python
cabinet = store.semaphore("cabinet", limit=8, breaker=Breaker(failures=2, pause="30s"))

try:
    async with cabinet.hold("requests") as permit:
        response = await client.get(url)
        if response.status_code == 404:
            permit.healthy()  # the cabinet answered: it is up
            raise NotFound(user.id)
except UnavailableError:
    return show_cached(user.id)  # the cabinet is down
state = await cabinet.state("requests")  # state.up, state.down_since, state.waiting, state.holding
```

```go
cabinet, err := locks.OpenSemaphore(store, "cabinet", locks.Limit(8), locks.Breaker(2, 30*time.Second))

err = cabinet.Hold(ctx, "requests", func(ctx context.Context, permit *locks.Lease) error {
	response, err := get(ctx, url)
	if err == nil && response.StatusCode == http.StatusNotFound {
		permit.Healthy() // the cabinet answered: it is up
		return errNotFound
	}
	return err
})
if errors.Is(err, tinystore.ErrUnavailable) {
	return showCached(user.ID) // the cabinet is down
}
state, err := cabinet.State(ctx, "requests") // state.Up, state.DownSince, state.Waiting, state.Holding
```

```rust
let cabinet = store.semaphore("cabinet").limit(8).breaker(2, Duration::from_secs(30)).open()?;

let fetched = cabinet.hold("requests", |permit| {
    let response = get(&url)?;
    if response.status() == 404 {
        permit.healthy(); // the cabinet answered: it is up
        return Err(not_found(&user.id));
    }
    Ok(response)
});
if fetched.as_ref().is_err_and(|error| error.kind() == ErrorKind::Unavailable) {
    show_cached(&user.id); // the cabinet is down
}
let state = cabinet.state("requests")?; // state.up, state.down_since, state.waiting, state.holding
```

- A hold counts as failed when its function throws or returns an error, or
  when it runs past its `timeout` or `maxHold`. A successful hold resets the
  count.
- While the key is down, every hold on it fails immediately with an
  unavailable error: `UnavailableError` in Bun and Python, `ErrUnavailable`
  in Go and `ErrorKind::Unavailable` in Rust (contract LOCK-12). After the
  pause, one hold goes through, and its result marks the key as up or down
  again (contract LOCK-13).
- Call `healthy()` when the service answered. The hold then doesn't count as
  a failure, even if the function throws afterwards.
- `state` returns whether the key is up, since when it has been down, its
  last failure, and how many holds are waiting and holding a place (contract
  LOCK-14).
- The breaker lives in the memory of the process that has the store open.
  After a restart, every key starts as up (NOT-14).

100,000 uncontended pairs of a hold and its release took 1.515 µs per pair
on a plain semaphore and 1.552 µs on one with `background` and a breaker.
These are the medians of seven alternating passes in one run, with a release
build on a 4 vCPU Intel Xeon 2.10 GHz Linux container with 15 GiB, while
other builds shared the CPU:

```sh
cargo test --release -p tinystore --lib --features testing hold_and_release_with_and_without -- --ignored --nocapture
```

## Gather what arrives into one job

Grades appear one by one, but a student should get one push notification
for all of them. `gather` collects everything that arrives under one id into
one job. The job runs `settle` after the last gather, and no later than
`max` after the first one
([Gather and quiet hours](https://tinyshed.org/tinystore/docs/guides/jobs/gather.md)):

```ts
const batch = store.queue<Notice[]>('notify-batch')

await batch.gather('grades:7', [{ course: 1, grade: 'A' }], { settle: '5m', max: '1h' }) // { added: true, count: 1, at }
await batch.gather('grades:7', [{ course: 2, grade: 'B' }], { settle: '5m', max: '1h' }) // { added: false, count: 2, at }

batch.work(async notices => push(7, `${notices.length} new grades`)) // one push with both
```

```python
batch = store.queue("notify-batch", list[Notice])

await batch.gather("grades:7", [Notice(course=1, grade="A")], settle="5m", max="1h")  # Gathered(added=True, count=1, at=…)
await batch.gather("grades:7", [Notice(course=2, grade="B")], settle="5m", max="1h")  # Gathered(added=False, count=2, at=…)


async def notify(notices: list[Notice], run: tinystore.Run) -> None:
    await push(7, f"{len(notices)} new grades")  # one push with both


worker = batch.work(notify)
```

```go
batch, err := jobs.OpenQueue[[]Notice](store, "notify-batch")

every := jobs.Settle(5 * time.Minute).Max(time.Hour)
gathered, err := batch.Gather(ctx, "grades:7", []Notice{{Course: 1, Grade: "A"}}, every) // {Added: true, Count: 1, At: …}
gathered, err = batch.Gather(ctx, "grades:7", []Notice{{Course: 2, Grade: "B"}}, every)  // {Added: false, Count: 2, At: …}

err = batch.Work(ctx, func(ctx context.Context, notices []Notice, run *jobs.Run) error {
	return push(ctx, 7, fmt.Sprintf("%d new grades", len(notices))) // one push with both
})
```

```rust
use tinystore::jobs::Gather;

let batch = store.queue::<Vec<Notice>>("notify-batch").open()?;
let every = Gather::settle(Duration::from_mins(5)).max(Duration::from_hours(1));
let gathered = batch.gather("grades:7", &vec![Notice { course: 1, grade: "A".into() }], every)?; // added, count 1
let gathered = batch.gather("grades:7", &vec![Notice { course: 2, grade: "B".into() }], every)?; // count 2

let worker = batch.work(|notices: Vec<Notice>, _run| push(7, &format!("{} new grades", notices.len())))?;
```

- The items stay in the order they arrived. If a gather comes in while the
  job runs, its items go to the next run. No item is lost when a run fails
  (contracts JOB-22 and JOB-23).
- The job's value is a list. A gather fails with `invalid` if a repeating job
  already has that id, or if it sets `at`, `delay`, `every` or `cron`.
- In Rust and in Bun, `tx.with(batch).gather(…)` gathers inside a database's
  transaction. Python's database transactions, the store's transactions in
  the SDKs and Go's transactions can't gather.
- A copy of a store on another node rejects a gather. Gather on the store's
  home node instead.

## Quiet hours

Say nothing should be sent from 23:00 to 07:00 Moscow time. Give the queue
quiet hours, and whenever the store would schedule a job inside them, it
moves the job to the end of the quiet hours
([Quiet hours](https://tinyshed.org/tinystore/docs/guides/jobs/gather.md#quiet-hours)):

```ts
const night = { from: '23:00', to: '07:00', timeZone: 'Europe/Moscow' }
const pushes = store.queue<Notice[]>('notify-push', { quiet: night })

await pushes.gather('grades:7', [{ course: 1, grade: 'A' }], { settle: '5m' }) // at 23:58: { at: 07:00 the next morning }
await pushes.add([{ course: 0, grade: 'exam moved' }], { quiet: false }) // this job is not held
```

```python
night = tinystore.Quiet(from_="23:00", to="07:00", time_zone="Europe/Moscow")
pushes = store.queue("notify-push", list[Notice], quiet=night)

await pushes.gather("grades:7", [Notice(course=1, grade="A")], settle="5m")  # at 23:58: at 07:00 the next morning
await pushes.add([Notice(course=0, grade="exam moved")], quiet=False)  # this job is not held
```

```go
night := jobs.Quiet("23:00", "07:00", "Europe/Moscow")
pushes, err := jobs.OpenQueue[[]Notice](store, "notify-push", night)

gathered, err := pushes.Gather(ctx, "grades:7", []Notice{{Course: 1, Grade: "A"}}, jobs.Settle(5*time.Minute)) // at 23:58: At 07:00
added, err := pushes.Add(ctx, []Notice{{Course: 0, Grade: "exam moved"}}, jobs.NoQuiet()) // this job is not held
```

```rust
use tinystore::jobs::{Gather, Quiet};

let night = Quiet::hours("23:00", "07:00", "Europe/Moscow");
let pushes = store.queue::<Vec<Notice>>("notify-push").quiet(night).open()?;

let gathered = pushes.gather("grades:7", &vec![Notice { course: 1, grade: "A".into() }], Gather::settle(Duration::from_mins(5)))?;
let added = pushes.id("exam:3").quiet(Quiet::none()).add(&vec![Notice { course: 0, grade: "exam moved".into() }])?;
```

- Quiet hours move the time set by `add`, set, update and upsert, a
  gather's settle, a retry's backoff, a snooze and a repeat's next run. They
  move an explicit `at` too (contract JOB-24). `get` and the command line
  show the moved time.
- If a worker reaches a job only inside the quiet hours, for example after a
  backlog or a full group, the job is moved to their end instead of started.
- If `from` is later than `to`, the hours wrap past midnight. The hours
  follow the wall clock of their time zone.
- A job's own `quiet` setting overrides its queue's. Quiet hours also
  override a gather's `max`.

## Cut a snippet

A page's body is often too long to show in full under its title. With
`snippet`, each hit contains the piece of one field around its first match,
and the positions of the matches inside that piece
([Show what matched](https://tinyshed.org/tinystore/docs/guides/search/matches.md#cut-a-snippet)):

```ts
const found = await pages.search({ text: 'algebra', snippet: { field: 'plain', around: 60 } })
found.hits[0].snippet // { text: '…Then linear algebra took three weeks of…', marks: [{ start: 13, end: 20 }] }
```

```python
result = await pages.search("algebra", snippet={"field": "plain", "around": 60})
result.hits[0].snippet  # Snippet(text='…Then linear algebra took three weeks of…', marks=[Mark(start=13, end=20)])
```

```go
result, err := pages.Search(ctx, "algebra", search.Snippet("plain", 60))
result.Hits[0].Snippet // &{Text: "…Then linear algebra took three weeks of…", Marks: [{Start: 15, End: 22}]}
```

```rust
let found = pages.search("algebra").snippet("plain", 60).run()?;
let snippet = found.hits[0].snippet.as_ref().unwrap();
&snippet.text[snippet.marks[0].clone()] // "algebra"
```

`around` sets how many characters to keep on each side of the match. The
default is 80. The piece never splits a word or a character in two. `marks`
count positions the same way as `matches` in each language. The store adds
no markup and escapes nothing, so escape each piece yourself before you put
it into HTML.

## Abbreviations and synonyms

Students type «кмзи» for a course named «Криптографические методы защиты
информации». An index's `synonyms` pair each short form with the phrase
that it stands for, and Search matches each pair in both directions
([Abbreviations and synonyms](https://tinyshed.org/tinystore/docs/guides/search/synonyms.md)):

```ts
const catalog = store.index<{ name: string }>('catalog', {
	fields: { name: 4 },
	synonyms: { кмзи: 'криптографические методы защиты информации', ml: 'machine learning' },
})
const { hits } = await catalog.search('кмзи') // the course by its phrase, and «Экзамен по КМЗИ» by the word itself
```

```python
catalog = store.index(
    "catalog",
    Course,
    fields={"name": 4},
    synonyms={"кмзи": "криптографические методы защиты информации", "ml": "machine learning"},
)
result = await catalog.search("кмзи")
```

```go
catalog, err := search.OpenIndex[Course](store, "catalog", search.Fields{"name": 4},
	search.Synonyms{"кмзи": "криптографические методы защиты информации", "ml": "machine learning"})
result, err := catalog.Search(ctx, "кмзи")
```

```rust
let catalog = store
    .index::<Course>("catalog")
    .field("name", 4.0)
    .synonyms([("кмзи", "криптографические методы защиты информации"), ("ml", "machine learning")])
    .open()?;
let found = catalog.search("кмзи").run()?;
```

- A search for the short form finds the phrase, with its words next to each
  other and in order, using the same stems as the index. A search for the
  phrase finds the short form. `matches` and snippets mark the text that is
  actually in the document (contract SRCH-23).
- The index applies synonyms when you set a document, so searches don't pay
  for them. If you open the index later with different synonyms, that is a
  change of settings. Search then re-reads the documents beside the index,
  the same as when you add a field.
- An index can have at most 1,000 synonyms. Each short form is one word, and
  each phrase is 1 to 8 words.

Setting 20,000 documents of 50 words each took 869 ms without synonyms and
903 ms with 200 synonyms. A two-word search took 116 µs and 100 µs, and that
difference is noise. These are the medians of three passes, with a release
build on a 4 vCPU Intel Xeon 2.10 GHz Linux container with 15 GiB, while
other builds shared the CPU:

```sh
cargo test --release -p tinystore --lib --features testing indexing_with_synonyms_takes -- --ignored --nocapture
```

## Ask several indexes at once

A "find anything" box sends one query to courses, pages and people.
`store.search` queries every index in one call, each with its own filter,
limit and snippet. It returns a group of hits for each index, and `merged`,
one list of the best hits from all of them, ordered by rank
([Ask several indexes at once](https://tinyshed.org/tinystore/docs/guides/search/many.md)):

```ts
const found = await store.search({
	text: 'algebra',
	in: [
		{ index: courses, boost: 2, limit: 5 },
		{ index: pages, where: { space_id: 7 }, limit: 5, snippet: { field: 'plain', around: 60 } },
		{ index: people, limit: 5 },
	],
})
found.groups // [{ index: 'courses', hits, more: true }, { index: 'pages', hits, more: false }, …]
found.merged // [{ index: 'courses', group: 0, hit }, { index: 'pages', group: 1, hit }, …]
```

```python
found = await store.search(
    "algebra",
    among=[
        search.Among(courses, boost=2, limit=5),
        search.Among(pages, where={"space_id": 7}, limit=5, snippet={"field": "plain", "around": 60}),
        search.Among(people, limit=5),
    ],
)
found.groups  # [ManyGroup(index='courses', hits=[…], more=True, …), …]
found.merged  # [Merged(index='courses', group=0, hit=Hit(…)), …]
```

```go
found, err := search.Many(ctx, store, "algebra",
	search.Among(courses, search.Boost(2), search.Limit(5)),
	search.Among(pages, search.Where{"space_id": 7}, search.Limit(5), search.Snippet("plain", 60)),
	search.Among(people, search.Limit(5)))
found.Groups // [{Index: "courses", Hits: […], More: true}, …]
found.Merged // [{Index: "courses", Group: 0, Hit: &found.Groups[0].Hits[0]}, …]
```

```rust
use tinystore::search::eq;

let found = store
    .search("algebra")
    .among(&courses, |a| a.boost(2.0).limit(5))
    .among(&pages, |a| a.filter(eq("space_id", &7)).limit(5).snippet("plain", 60))
    .among(&people, |a| a.limit(5))
    .run()?;
found.groups[0].more // true: courses has more than five
found.merged[0].hit.id // the best of all three, by rank
```

- One call queries 1 to 32 indexes, and a table's index can be one of them.
  `more` tells you exactly whether an index has hits past its group's limit.
- If one index fails, the others still return results. The failed index's
  group contains the error.
- `merged` never compares scores from different indexes. It merges with
  reciprocal rank fusion, and `boost` gives more weight to a group's ranks.
- The store's own indexes are searched in one snapshot of search.db.

In process, one search of 13 indexes with 200 documents each took 410 to
443 µs. 13 separate searches took 391 to 414 µs, so one call is about 6 %
slower. The gain comes over a connection, with one round trip instead of
13, and that gain is not measured. These are the medians of alternating
passes in one run, with a release build on a 4 vCPU Intel Xeon 2.10 GHz
Linux container with 15 GiB:

```sh
cargo test --release -p tinystore --lib --features testing many_against_single -- --ignored --nocapture
```

## A where kept to a database's statement

Say you want to know what teachers use. A stream's query can now be limited
to the values that a database's statement returns. The store then counts
only the teachers' events, instead of your program loading everybody's
events and filtering them
([Reading](https://tinyshed.org/tinystore/docs/guides/records/reading.md#a-where-kept-to-a-databases-statement)):

```ts
const teachers = db.statement`select id from teachers` // bound to its database; nothing runs yet
await events.count({ since: '1d', where: { userId: teachers } })
await events.list({ since: '1d', where: { userId: { not: teachers } } })
```

```python
teachers = db.statement("select id from teachers")  # bound to its database; nothing runs yet
await events.count(since="1d", where={"userId": teachers})
await events.list(since="1d", where={"userId": {"not": teachers}})
```

```go
teachers := db.Statement("select id from teachers") // bound to its database; nothing runs yet
events.Count(ctx, records.Query{Since: 24 * time.Hour, Where: records.Where{"userId": teachers}})
events.List(ctx, records.Query{Since: 24 * time.Hour, Where: records.Where{"userId": records.Not(teachers)}})
```

```rust
use tinystore::records::Not;

let (teachers, day) = (db.statement("select id from teachers"), Duration::from_hours(24)); // nothing runs yet
events.list().since(day).filter("userId", &teachers).count()?;
events.list().since(day).filter("userId", Not(&teachers)).page()?;
```

- The statement runs once, when the query starts. It must return one
  column, and its values match the same way as a list of values. It can
  return at most 100,000 rows.
- The statement and the events are not read from the same snapshot,
  because they live in two different files.
- `count`, `list`, `top`, `largest`, `aggregate` and `delete` accept a
  statement. A tail rejects it.

Over 1,000,000 events from 100,000 people, a count limited to a statement
of 50,000 ids took 1,039 ms. Reading every event and filtering the same ids
in the program took 13,579 ms. A count with no `where` took 2,304 ms, which
is slower than the count limited to the statement, and the reason is not
known yet. These are the medians of seven alternating passes, with
a release build on a 4 vCPU Intel Xeon 2.10 GHz Linux container with
15 GiB, while other builds shared the CPU:

```sh
cargo test --release -p tinystore --lib --features testing records::condition::tests::a_count_kept -- --ignored --nocapture
```

## Sessions

What did a newcomer do on their first visit? `sessions` splits a stream's
events into sessions at pauses. A session is a run of one person's events
where each event comes within `gap` of the one before
([Reading](https://tinyshed.org/tinystore/docs/guides/records/reading.md#sessions)):

```ts
const visits = await events.sessions({
	since: '30d', by: 'userId', gap: '30m', max: '4h', firstSessions: 1, maxEvents: 50,
	where: { userId: db.statement`select id from students where first_seen_at > ${from}` },
}) // Session[]: [{ by: { userId: 1 }, from, to, count: 2, events: [{ at, name, fields… }, …], partial }]
```

```python
visits = await events.sessions(
    since="30d", by="userId", gap="30m", max="4h", first_sessions=1, max_events=50,
    where={"userId": db.statement("select id from students where first_seen_at > ?", start)},
)  # list[Session]
```

```go
newcomers := db.Statement("select id from students where first_seen_at > ?", from)
visits, err := events.Sessions(ctx, records.Query{Since: 30 * 24 * time.Hour, By: []string{"userId"},
	Gap: 30 * time.Minute, Max: 4 * time.Hour, FirstSessions: 1, MaxEvents: 50, Where: records.Where{"userId": newcomers}})
```

```rust
use tinystore::records::Sessions;

let (minute, day) = (Duration::from_mins(1), Duration::from_hours(24));
let newcomers = db.statement(tinystore::sql!("select id from students where first_seen_at > ?", from));
let visit = Sessions::by(["userId"]).gap(minute * 30).max(minute * 240).first_sessions(1).max_events(50);
let visits = events.list().since(day * 30).filter("userId", &newcomers).sessions(&visit)?; // Vec<Session>
```

- `max` ends a session once that much time has passed since its first
  event. `firstSessions / first_sessions / FirstSessions / first_sessions`
  keeps only each person's first sessions, and `maxEvents / max_events /
  MaxEvents / max_events` sets how many events per session are returned.
- If the range cuts a session, that session is returned with `partial`.
- The result is returned whole, with at most 10,000 sessions and 64 MiB. If
  it would be larger, the call fails with `limit`. It never returns fewer
  sessions instead. Sessions are not paged yet, so use a shorter range,
  `firstSessions` or a `where` to keep the result within these limits.

Over 1,000,000 events from 8,000 people, with five visits each, counting the
range took 1,380 ms. Finding each person's first visit took 1,724 ms, and
the first visit with its first 5 events took 1,868 ms. These are the medians
of seven alternating passes, with a release build on a 4 vCPU Intel Xeon
2.10 GHz Linux container with 15 GiB, while other builds shared the CPU:

```sh
cargo test --release -p tinystore --lib --features testing records::sessions::tests::a_million -- --ignored --nocapture
```

## Compare now with usual

Is a call slower than usual? `compare` computes the `op` over the newest
window and the median of the same `op` over the windows before it. It does
this in one call that reads one snapshot, so your program doesn't need to
keep a baseline of its own
([Compare now with usual](https://tinyshed.org/tinystore/docs/guides/metrics/compare.md)):

```ts
const now = await store.metrics.compare({
	name: 'moodle_call_ms',
	where: { source: 'server' },
	op: 'p50',
	window: '15m',
	against: '7d',
	sameHour: true,
})
// { value: 840, usual: 310, ratio: 2.7, samples: 412, windows: 7 }
```

```python
now = await store.metrics.compare(
    "moodle_call_ms", op="p50", window="15m", where={"source": "server"}, against="7d", same_hour=True
)
# Compared(value=840.0, usual=310.0, ratio=2.7, samples=412, windows=7)
```

```go
now, err := metrics.Compare(ctx, store, metrics.Comparison{
	Name: "moodle_call_ms", Where: metrics.Where{"source": "server"}, Op: metrics.Percentile(50),
	Window: 15 * time.Minute, Against: 7 * 24 * time.Hour, SameHour: true,
})
// now.Value, now.Usual and now.Ratio are *float64: nil when there is none
```

```rust
let now = store
    .metrics()?
    .query()
    .name("moodle_call_ms")
    .filter("source", "server")
    .compare(Op::Percentile(50.0), Duration::from_mins(15))
    .against(Duration::from_hours(7 * 24))
    .same_hour()
    .run()?;
// Compared { value: Some(840.0), usual: Some(310.0), ratio: Some(2.7), samples: 412, windows: 7 }
```

- With `sameHour`, the earlier windows are the same quarter hour on each of
  the 7 days. Without it, they are every window of the week, up to 1,000.
- A window without samples is left out of the median. It never counts as
  zero.
- A timer's percentile can be compared only with `estimate`.
- The store doesn't evaluate alert rules or notify anyone by itself yet.
  The guide shows a schedule that runs `compare` every minute and adds a
  job to the program's own queue.

On 10 gauges with a sample every 10 seconds for 7 days, one `compare` took
1.394 ms and 1.365 ms in two runs. The old way, with one aggregate of the
week by 15 minutes and one of the newest window, took 20.98 ms and
21.75 ms. These are the medians of seven alternating passes, with a release
build on a 4 vCPU Intel Xeon 2.10 GHz Linux container with 15 GiB:

```sh
cargo test -p tinystore --lib --release --features async,testing compare_against -- --ignored --nocapture
```

## To Prometheus

An existing Prometheus or Grafana can now read the store's metrics. The
Metrics engine writes the newest sample of every series in Prometheus' text
format, and your program's own HTTP server returns that text to the scrape
([To Prometheus](https://tinyshed.org/tinystore/docs/guides/metrics/exposition.md)):

```rust
let stats = store.metrics()?;
let mut body = Vec::new();
let written = stats.exposition().only_prefix("shop_").write(&mut body)?; // Written { names, series }
```

```text
# HELP shop_orders_total Orders placed.
# TYPE shop_orders_total counter
shop_orders_total{shop="msk"} 1027 1732622400000
```

- The call exists only in Rust. It is not on the wire yet, so Bun, Node,
  Python and Go have no call for it. From those languages, and from a
  shell, use `tinystore metrics export`, which writes the same text.
- TinyStore doesn't serve HTTP and has no listener for a scrape. Your
  program's own server serves the text.
- With `since`, a series whose newest sample is older than that is left
  out. Without it, every series in the store is written, with the time of
  its last sample.
- `timestamps(false)`, and `--no-timestamps` on the command line, write the
  samples without their times, which is the form that node_exporter's
  textfile collector expects.
- If a name or label has characters outside Prometheus' classic set, they
  are replaced with `_`, the same way OpenTelemetry does it. If a series'
  name or labels then match another series, that series is left out, and
  `Written` counts it in `skipped`.
- The store's own ingest reads the text back to the same names, labels,
  kinds and newest samples (MET-31). An exposition writes every series that
  matches, or fails; it never stops short silently (MET-32). It holds only
  one part of the store in memory at a time.

An exposition of 100,000 series under 100 names took 361 ms (between 340
and 382 ms), and it used at most 42.8 KB of the store's memory. These are
the medians of five passes, with a release build on a 4 vCPU Intel Xeon
2.10 GHz Linux container with 15 GiB, while other builds shared the CPU:

```sh
cargo test --release -p tinystore --lib --features testing exposition_of_a_hundred_thousand -- --ignored --nocapture
```

## Export metrics and events

The command line can now export a store's metrics as Prometheus' text and
a stream's events as JSON lines. It works while the program that has the
store open keeps running
([metrics export](https://tinyshed.org/tinystore/docs/guides/cli/metrics.md#export-for-prometheus),
[events export](https://tinyshed.org/tinystore/docs/guides/cli/events.md#export-a-stream)):

```sh
tinystore metrics ./data export --only-prefix shop_ --since 5m -o shop.prom
tinystore events ./data export audit --from 2026-11-01T00:00Z --to 2026-11-02T00:00Z > day.jsonl
```

- `metrics export` writes the same text as
  [To Prometheus](#to-prometheus).
- `events export` writes every event in the range, oldest first, as the
  same object that `list --json` prints. It reads one page at a time, so
  only one page is in memory, however long the stream is.
- `-o` first writes to a `.part` file next to the target and renames it
  when it is complete, so a reader never sees half a file.

## Times in one zone

The command line now uses the time zone that `--tz` sets for two things:
the times it prints for people to read, and the times you pass to
`--from`, `--to` or `--at` without an offset
([Command line](https://tinyshed.org/tinystore/docs/guides/cli.md)):

```sh
tinystore events ./data list audit --tz Asia/Kolkata --from 2026-11-25T09:00 --to 2026-11-25T18:00
TINYSTORE_TZ=utc tinystore logs ./data --since 1h
```

`--tz` accepts an IANA name, `utc` or `local`. Without it, `TINYSTORE_TZ`
sets the zone, and without either, the command line uses this machine's
zone. `--json` always prints UTC, whatever the zone.

## Changed names

- Bun, Node and Python: the text property `describe` of a database and of a
  transaction is now `label`. `describe` is now the call described in
  [What a statement answers](#what-a-statement-answers):

  ```ts
  db.describe // 0.12.0: 'sql app'
  db.label // 0.13.0: 'sql app'
  ```

  ```python
  db.describe  # 0.12.0: 'sql app'
  db.label  # 0.13.0: 'sql app'
  ```

  Go and Rust had no such property, so nothing changes there.

## Install

```sh for=bun
bun add @tinyshed/tinystore@0.13.0
npm install @tinyshed/tinystore@0.13.0
```

```sh for=python
pip install tinyshed-tinystore==0.13.0
```

```sh for=go
go get tinyshed.org/tinystore@v0.13.0
```

```sh for=rust
cargo add tinystore@0.13.0
cargo install tinystore-cli@0.13.0
```

0.13.0 adds two steps to jobs' migrations (`0003_gather.sql` and
`0004_quiet.sql`) and one to search's (`0004_synonyms.sql`), in jobs.db and
search.db, and in any database file that contains a queue or a table's
index. Because of this, 0.12.0 refuses to open a store that 0.13.0 has
opened, instead of reading it wrong. Open it with 0.13.0 or later. Programs
that connect over the wire get the new calls once the server runs 0.13.0.
The server image is `ghcr.io/tinyshed/tinystore:0.13.0`.

Every commit since 0.12.0 is in the
[GitHub release](https://github.com/tinyshed/tinystore/releases/tag/v0.13.0).
