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

# TinyStore 0.11.0

TinyStore 0.11.0 came out on 19 November 2026. Most of it comes from one
application's list of what it had to write around: polls that upsert
themselves and end on their own, a nightly crawl an admin can run now, a
search that says how many it found and keeps to the rows of a query, logs
filtered by any of a list, charts with every hour on them, and a store a
test opens in one line. The command line can now write to a store that a
program holds embedded.

- **Jobs**
  - [Add it, or bring it to the call](#add-it-or-bring-it-to-the-call): `upsert`.
  - [A repeat that ends](#a-repeat-that-ends): `ttl` and `expiresAt` on a job.
  - [Run a schedule now](#run-a-schedule-now): `runNow`.
  - [Once a day, in a user's time zone](#once-a-day-in-a-users-time-zone): a calendar `dedupe`, and a job's own.
  - [Keep a failed job, or not](#keep-a-failed-job-or-not): a job's own `keep`, `'0s'` for none.
- **Records**
  - [Any of a list, not, a prefix](#any-of-a-list-not-a-prefix): the conditions of a `where`.
  - [Every span, and its local date](#every-span-and-its-local-date): `fill` and `date` in an aggregate.
  - [The largest numbers](#the-largest-numbers): `largest`, and `message` as a key.
  - [Delete a person's events](#delete-a-persons-events): `events.delete({ where })`.
  - [Errors with their causes](#errors-with-their-causes): an `Error`'s whole chain in a log line.
- **Search**
  - [How many it finds](#how-many-it-finds): `total`.
  - [Among the rows of a query](#among-the-rows-of-a-query): a statement in a `where`.
  - [A key of several columns](#a-key-of-several-columns): `key: ['space', 'n']`.
  - [Another table, read beside](#another-table-read-beside): a table's index moved to a new table or key.
- **Metrics**
  - [Every bucket, and its local date](#every-bucket-and-its-local-date): `fill` and `date`.
  - [Reads without flush](#reads-without-flush): a read sees what the instruments counted.
  - [A bound on an instrument's labels](#a-bound-on-an-instruments-labels): `maxSeries`.
  - [100,000 samples in one write](#100000-samples-in-one-write): a larger `ingest`.
- **SQL**
  - [An upsert of many rows](#an-upsert-of-many-rows): a list, one statement.
- **KV**
  - [How many keys](#how-many-keys): `count()`.
- **Channels**
  - [Who listens now](#who-listens-now): `subscribers()`.
- **Locks**
  - [How long a hold waited](#how-long-a-hold-waited): `waited`, and gauges of who waits.
- **Store**
  - [A store for each test](#a-store-for-each-test): `openTemp`, on a clock the test moves.
  - [Write to a store a program holds](#write-to-a-store-a-program-holds): `cli: true`.
  - [Durations as the store reads them](#durations-as-the-store-reads-them): `ms` and `spelled` in TypeScript.

> \[!WARNING]
> **Records: a list in a `where` is any of its values**
> `{ op: ['a', 'b'] }` used to find an event whose `op` was that list. It
> now finds `op` `'a'` or `'b'`. For the list itself, put it in a list:
>
> ```diff
> - await api.list({ since: '1d', where: { tags: ['a', 'b'] } })
> + await api.list({ since: '1d', where: { tags: [['a', 'b']] } })
> ```
>
> **Jobs: a failed job no longer holds its id**
> An `add` with the id of a job that failed for good used to answer `false`.
> It now starts a new job in its place.
>
> **Rust: `search::Found` is `#[non_exhaustive]`, and `is_in` takes no turbofish**
>
> ```diff
> - let Found { hits, corrected } = found;
> + let Found { hits, corrected, .. } = found;
> - .filter(is_in::<&str>("brand", &brands))
> + .filter(is_in("brand", &brands))
> ```

## Add it, or bring it to the call

A program polls each group it has seen, and the poll's interval comes from
the code. `add` of a taken id changes nothing, so a new `every` never reached
a job already there; `set` reset the job's time and attempts on every
request. `upsert` adds the job when the id is free, and otherwise changes
only what differs ([Ids](https://tinyshed.org/tinystore/docs/guides/jobs/ids.md#add-it-or-bring-it-to-the-call-upsert)):

```ts
const polls = store.queue<{ group: string }>('polls')
const changed = await polls.upsert(`group:${g}`, { group: g }, { every: '3m' }) // true: added or changed; false: it already was so
```

```python
polls = store.queue("polls", Poll)
changed = await polls.upsert(f"group:{g}", Poll(group=g), every="3m")  # True: added or changed
```

```go
polls, err := jobs.OpenQueue[Poll](store, "polls")
changed, err := polls.Upsert(ctx, "group:"+g, Poll{Group: g}, jobs.Every(3*time.Minute))
```

```rust
let polls = store.queue::<Poll>("polls").open()?;
let changed: bool = polls.id(&format!("group:{g}")).every(Duration::from_mins(3)).upsert(&Poll { group: g })?;
```

- The job's time, attempts and steps stay; `at` and `delay` count only when
  it adds the job. A changed value drops the steps kept for the old one, as
  `update` does.
- A changed repeat moves the job to the new repeat's next time.
- When the job already is what the call says, it answers `false` and writes
  nothing, so it is cheap enough to call on every request.

For "look now" requests that come in a burst, the guide shows
[`set`](https://tinyshed.org/tinystore/docs/guides/jobs/ids.md#look-now): many in a row are one job, and one
during a run gets a run more after it.

## A repeat that ends

A group nobody has opened for two weeks should stop being polled. `ttl`
counts from the job's last write, so an `upsert` on every sighting renews
it; `expiresAt` is a fixed time. They are the words a KV key uses for the
same thing ([Schedules and cron](https://tinyshed.org/tinystore/docs/guides/jobs/schedules.md#a-repeat-that-ends-ttl-and-expiresat)):

```ts
await polls.upsert(`group:${g}`, { group: g }, { every: '3m', ttl: '14d' }) // each sighting renews the 14 days
await reports.add({ term }, { id: `report:${term}`, every: '1d', expiresAt: endOfTerm })
```

```python
await polls.upsert(f"group:{g}", Poll(group=g), every="3m", ttl="14d")
await reports.add(Report(term=term), id=f"report:{term}", every="1d", expires_at=end_of_term)
```

```go
_, err = polls.Upsert(ctx, "group:"+g, Poll{Group: g}, jobs.Every(3*time.Minute), jobs.TTL(14*24*time.Hour))
_, err = reports.Add(ctx, Report{Term: term}, jobs.ID("report:"+term), jobs.Every(24*time.Hour), jobs.ExpiresAt(endOfTerm))
```

```rust
polls.id(&format!("group:{g}")).every(Duration::from_mins(3)).ttl(Duration::from_hours(24 * 14)).upsert(&poll)?;
reports.id(&format!("report:{term}")).every(Duration::from_hours(24)).expires_at(end_of_term).add(&report)?;
```

- A job never starts at or after its term. A run under way finishes, and the
  job then ends instead of moving to its next time.
- A job that reaches its term leaves as a cancelled one does: its id is
  free, and a watcher's last state is `cancelled`.
- An `upsert` writes a renewal at most once per thirtieth of the `ttl`, so a
  hot path doesn't write each time. An `add` of a taken id renews nothing.
- A term works on a job that doesn't repeat too: a push not sent within the
  hour is dropped.

A different interval by night is two ids, each with a cron for its hours,
both upserted with the same `ttl`.

## Run a schedule now

After a first deploy, the nightly crawl should not wait for the night; an
admin may ask for it too. `runNow` runs a schedule once as soon as a worker
is free, and keeps its later times
([Schedules and cron](https://tinyshed.org/tinystore/docs/guides/jobs/schedules.md#run-a-schedule-now)):

```ts
const night = store.schedule('night', { cron: '30 3 * * *', timeZone: 'Europe/Moscow' }, crawl)
await night.runNow() // one run as soon as a worker is free; 03:30 stays its time
if (!(await night.get())?.lastRun) await night.runNow() // the first deploy: run once if it never ran
```

```python
night = store.schedule("night", crawl, cron="30 3 * * *", time_zone="Europe/Moscow")
await night.run_now()
```

```go
night, err := jobs.OpenSchedule(store, "night", jobs.Cron("30 3 * * *", "Europe/Moscow"))
err = night.RunNow(ctx)
```

```rust
let night = store.schedule("night").cron("30 3 * * *", "Europe/Moscow").work(crawl)?;
night.run_now()?;
```

- A schedule that is running runs once more right after the run under way,
  never beside it. One waiting for a retry runs that retry now.
- It needs no worker in the same process: whichever worker runs the
  schedule picks it up.
- A run missed while the program was down now runs at the start even when
  the deploy that brought it back changed its repeat; before, it was lost.

## Once a day, in a user's time zone

`dedupe` now takes a calendar: the id stays taken until the local day, week
or month in which the job was done ends. A job can also have its own
`dedupe`, which wins over its queue's
([Ids](https://tinyshed.org/tinystore/docs/guides/jobs/ids.md#once-a-day-in-a-users-time-zone)):

```ts
const crawl = store.queue<{ group: string }>('schedule-fetch', { dedupe: { calendar: 'day', timeZone: 'Europe/Moscow' } })
await crawl.add({ group: g }, { id: `crawl:${g}` }) // false until Moscow's midnight after it was done
await crawl.add({ group: g }, { id: `now:${g}`, dedupe: '10m' }) // this job's own
```

```python
crawl = store.queue("schedule-fetch", Crawl, dedupe=tinystore.Dedupe(calendar="day", time_zone="Europe/Moscow"))
await crawl.add(Crawl(group=g), id=f"crawl:{g}")
await crawl.add(Crawl(group=g), id=f"now:{g}", dedupe="10m")
```

```go
crawl, err := jobs.OpenQueue[Crawl](store, "schedule-fetch", jobs.DedupeCalendar(tinystore.Day, "Europe/Moscow"))
_, err = crawl.Add(ctx, Crawl{Group: g}, jobs.ID("crawl:"+g))
_, err = crawl.Add(ctx, Crawl{Group: g}, jobs.ID("now:"+g), jobs.Dedupe(10*time.Minute))
```

```rust
let day = Dedupe::calendar(Calendar::Day, "Europe/Moscow");
let crawl = store.queue::<Crawl>("schedule-fetch").dedupe(day).open()?;
crawl.id(&format!("crawl:{g}")).add(&Crawl { group: g })?;
crawl.id(&format!("now:{g}")).dedupe(Duration::from_mins(10)).add(&Crawl { group: g })?;
```

"Once a day" means once in each local day, not once every 24 hours: a job
done at 23:59 Moscow time holds its id for a minute. A day is 23 or 25 hours
long on the days the clock moves.

## Keep a failed job, or not

A job that failed for good stays for its queue's `keep`, a week, so that you
can look at it. A job can now have its own, and `'0s'` keeps it not at all,
for a push whose text should not sit in jobs.db
([Ids](https://tinyshed.org/tinystore/docs/guides/jobs/ids.md#keep-a-failed-job-or-not)):

```ts
await pushes.add({ to, text }, { keep: '0s' }) // fails for good: gone at once; its watcher sees failed and the error
await reports.add(report, { id: `report:${id}`, keep: '30d' }) // this job's own, beside the queue's
```

```python
await pushes.add(Push(to=to, text=text), keep="0s")
await reports.add(report, id=f"report:{id}", keep="30d")
```

```go
_, err = pushes.Add(ctx, Push{To: to, Text: text}, jobs.Keep(0))
_, err = reports.Add(ctx, report, jobs.ID("report:"+id), jobs.Keep(30*24*time.Hour))
```

```rust
pushes.keep(Duration::ZERO).add(&Push { to, text })?;
reports.id(&format!("report:{id}")).keep(Duration::from_hours(24 * 30)).add(&report)?;
```

Gone means unreadable through the store: SQLite leaves a deleted row's bytes
in free pages until it reuses them. For text that must never rest on disk,
put a reference in the value and read the text in the handler.

## Any of a list, not, a prefix

A `where` on events took one value a key. It now takes a list, any of its
values, `{ not }` and `{ prefix }`
([Reading](https://tinyshed.org/tinystore/docs/guides/records/reading.md#a-where)):

```ts
await api.aggregate({ names: ['call'], since: '1d', by: ['op'], where: { op: ['grading.works', 'drafts.get'] } })
await api.list({ since: '1d', where: { userId: [7, 12, 31], route: { prefix: '/admin' }, env: { not: 'test' } } })
```

```python
await api.aggregate(names=["call"], since="1d", by=["op"], where={"op": ["grading.works", "drafts.get"]})
await api.list(since="1d", where={"userId": [7, 12, 31], "route": {"prefix": "/admin"}, "env": {"not": "test"}})
```

```go
api.Aggregate(ctx, records.Query{Names: []string{"call"}, Since: 24 * time.Hour, By: []string{"op"},
	Where: records.Where{"op": records.OneOf("grading.works", "drafts.get")}})
api.List(ctx, records.Query{Since: 24 * time.Hour,
	Where: records.Where{"userId": []int{7, 12, 31}, "route": records.Prefix("/admin"), "env": records.Not("test")}})
```

```rust
use tinystore::{Not, Prefix};
let day = Duration::from_hours(24);
api.list().since(day).filter("op", &["grading.works", "drafts.get"]).aggregate(&Aggregate::new().by(["op"]))?;
api.list().since(day).filter("userId", &[7, 12, 31]).filter("route", Prefix("/admin")).filter("env", Not("test")).page()?;
```

- A list holds 1 to 1,000 values, each matched by its exact JSON, as a
  single value is: `[42, '42']` finds `42` and `'42'`, not `42.0`.
- `{ not }` also finds an event without the key. It reads more than the
  other conditions, so give it a range or another condition.
- A list or an object as the value itself goes inside a list: `[['a', 'b']]`.
- A server of 0.10 or before refuses a list, `{ not }` and `{ prefix }` as
  `unimplemented`, rather than match nothing.

## Every span, and its local date

A chart wants a row for every day, and a calendar's day by its own date.
`fill` gives a row for every span of the range, an empty one with
`count: 0`, and a calendar's row carries `date`
([Reading](https://tinyshed.org/tinystore/docs/guides/records/reading.md#every-span-and-its-local-date)):

```ts
const days = await api.aggregate({ names: ['call'], since: '30d', calendar: 'day', timeZone: 'Europe/Moscow', fill: true })
// [{ at, date: '2026-10-21', count: 0, by: {}, stats: {}, distinct: {} }, …, { at, date: '2026-11-19', count: 14, … }]
```

```python
days = await api.aggregate(names=["call"], since="30d", calendar="day", time_zone="Europe/Moscow", fill=True)
```

```go
days, err := api.Aggregate(ctx, records.Query{Names: []string{"call"}, Since: 30 * 24 * time.Hour,
	Calendar: tinystore.Day, TimeZone: "Europe/Moscow", Fill: true}) // days[0].Date == "2026-10-21"
```

```rust
let days = api.list().names(["call"]).since(Duration::from_hours(30 * 24))
    .aggregate(&Aggregate::new().calendar(Calendar::Day, "Europe/Moscow").fill())?; // days[0].date: Some("2026-10-21")
```

- The range is what the stream keeps of it, and `fill` needs a start,
  `since` or `from`.
- `date` is `YYYY-MM-DD`: a day's own date, a week's Monday, a month's
  first. It is a `datetime.date` in Python and text elsewhere. Rows of
  `every` have none.

## The largest numbers

`top('ms')` counts how often each value occurs. `largest` gives the events
themselves, those of a field's largest numbers first, such as the slowest
page opens with their `path`
([Reading](https://tinyshed.org/tinystore/docs/guides/records/reading.md#the-largest-numbers)):

```ts
const slowest = await pages.largest('ms', { names: ['page-open'], since: '7d', limit: 20 }) // Event[]
```

```python
slowest = await pages.largest("ms", names=["page-open"], since="7d", limit=20)  # list[Event]
```

```go
slowest, err := pages.Largest(ctx, "ms", records.Query{Names: []string{"page-open"}, Since: 7 * 24 * time.Hour, Limit: 20})
```

```rust
let slowest = pages.list().names(["page-open"]).since(Duration::from_hours(7 * 24)).limit(20).largest("ms")?; // Vec<Event>
```

It reads every event the query finds, as `top` does, and holds only the
events it gives. `top`, `by` and `distinct` now also take `message`, the
event's message, as a key.

## Delete a person's events

A person asks for their data to go. Their rows, buckets and files went, but
a stream only appended, so a year of their events stayed until `keep`
passed. `delete` takes the events a query finds out of the streams, and
what the store kept only for them ([Deleting events](https://tinyshed.org/tinystore/docs/guides/records/deleting.md)):

```ts
const deleted = await store.events().delete({
	streams: ['activity', 'client-errors', 'key-calls', 'oauth-steps'],
	where: { userId: 97516 },
}) // 412
```

```python
deleted = await store.events().delete(streams=["activity", "client-errors"], where={"userId": 97516})  # 412
```

```go
events, err := records.OpenAllEvents(store)
deleted, err := events.Delete(ctx, records.Query{Streams: []string{"activity", "client-errors"}, Where: records.Where{"userId": 97516}})
```

```rust
let deleted = store.all_events()?.list().streams(["activity", "client-errors"]).filter("userId", &97516).delete()?;
```

- It takes a read's query, `where` required, with its lists, `{ not }` and
  `{ prefix }`, and answers how many it deleted.
- With the events go a context only they had, their keys among `fields`,
  their values in the filters, and their bytes: the store writes zeros over
  what it frees and empties the WAL, so neither `records.db` nor its WAL
  keeps them once the call returns.
- It moves no cursor: a poll from a place given before it still gives every
  other event once, and events of one time keep their order.
- It writes a stream a part at a time, so a delete cut off is finished by
  running it again. It reaches neither a backup taken before it nor another
  node's `records.db`; the guide says what to do there.
- An event's id stays held until `keep` passes its time, so a producer that
  sends it again writes nothing.

Not yet on the command line or among the MCP tools.

## Errors with their causes

In TypeScript a logged `Error` is now kept as its stack, then `Caused by: `
and the stack of each `cause`, and of each of an `AggregateError`'s
`errors`. An `Error` inside an object is written the same way, where it was
`{}` ([Logging](https://tinyshed.org/tinystore/docs/guides/records/logging.md#errors)):

```ts
log.error('sync failed', { err: new Error('moodle 502', { cause: timeout }) })
```

```log
16:42:24.094 ERROR api  sync failed
    err: Error: moodle 502
        at sync (moodle.ts:40:11)
    Caused by: Error: timeout
        at fetch (http.ts:7:5)
```

A logger given a stream that is not text is refused at once. A dotted
`named('queue')` was not added: the guide shows the two lines that keep a
component's path.

## How many it finds

"Teachers named Ivanov: 340" on a chip, and whether a next page exists. Ask
for `total`, and a search counts every document it finds under its `where`,
whatever its `limit` and `offset`
([Search](https://tinyshed.org/tinystore/docs/guides/search.md#how-many-it-finds)):

```ts
const found = await people.search({ text: 'иванов', where: { role: 'teacher' }, limit: 20, total: true })
found.total // { count: 340, atLeast: false }
```

```python
found = await people.search("иванов", where={"role": "teacher"}, limit=20, total=True)
found.total  # Total(count=340, at_least=False)
```

```go
found, err := people.Search(ctx, "иванов", search.Where{"role": "teacher"}, search.Limit(20), search.Total())
found.Total // &search.Counted{Count: 340, AtLeast: false}; nil without search.Total()
```

```rust
let found = people.search("иванов").filter(eq("role", "teacher")).limit(20).total().run()?;
found.total // Some(Total { count: 340, at_least: false })
```

- `count` is exact up to 10,000. Past that the search stops counting and
  answers 10,000 with `atLeast`: at least that many, never an estimate.
- Counting reads every document the words' lists hold, which a search alone
  mostly skips, so it costs more. Without `total` a search costs what it did.
- A search by a vector with `total` is `invalid`.

## Among the rows of a query

"Find a student by name among this teacher's students", when a teacher has
thousands: a table's index takes a statement of its database where a list
goes, as SQL's `in (select …)` does
([Filters](https://tinyshed.org/tinystore/docs/guides/search/filters.md#the-rows-of-a-statement)):

```ts
const mine = sql`select user_id from course_members where course_id = ${courseId}`
const found = await users.search({ text: 'ива', prefix: true, where: { id: mine }, limit: 20 })
```

```python
mine = sql("select user_id from course_members where course_id = ?", course_id)
found = await users.search("ива", prefix=True, where={"id": mine}, limit=20)
```

```go
mine := sqldb.SQL("select user_id from course_members where course_id = ?", courseID)
found, err := users.Search(ctx, "ива", search.Prefix(), search.Where{"id": mine}, search.Limit(20))
```

```rust
let mine = sql!("select user_id from course_members where course_id = ?", course_id);
let found = users.search("ива").prefix().filter(is_in("id", mine)).limit(20).run()?;
```

- The statement runs in the search's own snapshot, so the two see the same
  moment.
- It gives one column and only reads, up to 100,000 rows; past that the
  search fails with a limit error, never a shorter set.
- On the table's key it needs no filter. On any other column, the column is
  one of the index's `filters`.

## A key of several columns

A table whose rows are named by two columns together, task 6 of space NW,
needs no surrogate id for its index
([A table's index](https://tinyshed.org/tinystore/docs/guides/search/table-index.md#a-key-of-several-columns)):

```ts
const tasks = db.searchIndex<Task>('tasks_search', { table: 'tasks', key: ['space', 'n'], fields: { title: 1 } })
const found = await tasks.search('экран')
found.hits[0] // { id: '["NW",6]', value: { space: 'NW', n: 6, title: 'экран входа' }, score: … }
```

```python
tasks = db.search_index("tasks_search", Task, table="tasks", key=("space", "n"), fields={"title": 1})
```

```go
tasks, err := search.OpenIndex[Task](db, "tasks_search", search.Table("tasks"), search.Key("space", "n"), search.Fields{"title": 1})
```

```rust
let tasks = db.search_index::<Task>("tasks_search").table("tasks").key(["space", "n"]).field("title", 1.0).open()?;
```

A hit's `id` is the key's values as a JSON array, `["NW",6]`. A table's
primary key of several columns is the index's key unless `key` names
others. A table without a key is refused, and the error says what to add.

## Another table, read beside

Moving a table's index to a new table or key no longer needs a new index
name. Open it under the same name with the new table, and the store reads
the new table beside it while the old table's rows answer every search and
take writes; then it switches in one commit
([A table's index](https://tinyshed.org/tinystore/docs/guides/search/table-index.md#settings-and-dropping)):

```ts
const articles = db.searchIndex<Article>('articles_search', { table: 'articles_v2', key: 'slug', fields: { title: 2, body: 1 } })
await articles.status() // { state: 'rebuilding', done: 0 }: the rows of articles answer until the switch
await articles.ready() // switched: the rows of articles_v2, by slug
```

```python
articles = db.search_index("articles_search", Article, table="articles_v2", key="slug", fields={"title": 2, "body": 1})
await articles.ready()
```

```go
articles, err := search.OpenIndex[Article](db, "articles_search",
	search.Table("articles_v2"), search.Key("slug"), search.Fields{"title": 2, "body": 1})
err = articles.Ready(ctx)
```

```rust
let articles = db.search_index::<Article>("articles_search").table("articles_v2").key("slug")
    .field("title", 2.0).field("body", 1.0).open()?;
articles.ready()?;
```

- A table a migration drops now takes its index with it, at the next open
  of an index of that database; a table rebuilt by SQLite's twelve steps
  keeps its index, read again whole.
- Only what the store can't make again needs another name: the vectors of
  a new model. The error for other dimensions now says so.
- Known gap: a migration that rebuilds the new table while it is being read
  beside loses the triggers that feed the rows beside.

## Every bucket, and its local date

A chart of errors by hour wants every hour, the ones without errors too.
`fill` gives every bucket of the range, and a calendar's bucket carries its
local `date`
([Aggregates](https://tinyshed.org/tinystore/docs/guides/metrics/aggregates.md#every-bucket-with-fill)):

```ts
const { groups } = await store.metrics.aggregate({ name: 'errors_total', since: '1d', every: '1h', op: 'increase', fill: true })
const hours = groups[0]?.buckets.map(hour => hour.value ?? 0) // 25 hours, an empty one drawn as 0
```

```python
groups = (await store.metrics.aggregate(name="errors_total", since="1d", every="1h", op="increase", fill=True)).groups
hours = [hour.value or 0 for hour in groups[0].buckets]
```

```go
page, err := metrics.Aggregate(ctx, store, metrics.Query{Name: "errors_total", Since: 24 * time.Hour, Every: time.Hour,
	Op: metrics.Increase, Fill: true}) // an empty bucket's Value is nil
```

```rust
let groups = stats.query().name("errors_total").since(Duration::from_hours(24)).every(Duration::from_hours(1))
    .fill().aggregate(Op::Increase)?.groups;
let hours: Vec<f64> = groups[0].buckets.iter().map(|hour| hour.value.exact().unwrap_or(0.0)).collect();
```

- An empty bucket has `samples: 0` and no `value`, not a zero: a counter's
  process may have been down that hour, and what it grew then is counted in
  the next bucket with samples. The chart picks its zero.
- `fill` takes `since` or `from`, and no `limit` yet: both are `invalid`.
- A `calendar` bucket's `date` is `'2026-11-19'`, a week's Monday, a month's
  first, so a chart labels it with no zone math of its own. A bucket of
  `every` has none.

## Reads without flush

A test that counted a call and read it back needed a `flush` in between. Now
a `read`, an `aggregate` or a `latest` sees what the program's instruments
counted before it
([Instruments](https://tinyshed.org/tinystore/docs/guides/metrics/instruments.md#reading-them-back-flush-and-tests)):

```ts
calls.inc()
const { groups } = await store.metrics.aggregate({ name: 'calls', since: '1h', op: 'increase' }) // counts it
```

```python
calls.inc()
groups = (await store.metrics.aggregate(name="calls", since="1h", op="increase")).groups  # counts it
```

```go
calls.Inc()
page, err := metrics.Aggregate(ctx, store, metrics.Query{Name: "calls", Since: time.Hour, Op: metrics.Increase})
```

```rust
calls.inc();
let groups = stats.query().name("calls").since(Duration::from_hours(1)).aggregate(Op::Increase)?.groups;
```

The store writes the totals first only when an instrument the query finds
changed since the last write, in the same one commit `flush` makes. Another
process's instruments reach the store within a second of their calls.

## A bound on an instrument's labels

A label that holds a person's id grows an instrument a set of labels per
person. `maxSeries` bounds the sets it holds, 2,000 unless given; a new set
past it counts into `{ __overflow: 'true' }`, so the total stays whole
([Instruments](https://tinyshed.org/tinystore/docs/guides/metrics/instruments.md#how-many-series)):

```ts
const people = store.metrics.counter('op_people', { keep: '90d', maxSeries: 200 })
```

```python
people = store.metrics.counter("op_people", keep="90d", max_series=200)
```

```go
people, err := metrics.OpenCounter(store, "op_people", metrics.Keep(90*24*time.Hour), metrics.MaxSeries(200))
```

```rust
let people = stats.counter("op_people").keep(Duration::from_hours(90 * 24)).max_series(200).open()?;
```

The first set past the bound is said once, a `warn` line in TinyStore's own
lines, which every SDK now prints as its own:
`metrics instrument past its sets of labels, counting into __overflow`, with
the instrument's name.

## 100,000 samples in one write

An `ingest` takes 100,000 samples and 32 MiB in one call, ten times what it
took, and writes them in one write. From Bun, Node, Python or Go a call past
one message goes up in pieces and is still one write, so seeding a test's
history needs no splitting by hand. A series takes 16,384 samples a call
that it has not packed yet
([Ingesting](https://tinyshed.org/tinystore/docs/guides/metrics/ingesting.md)).

## An upsert of many rows

`upsert` takes a list of rows, as `insert` does: one statement, every row
written or none ([Tables](https://tinyshed.org/tinystore/docs/guides/sql/tables.md)):

```ts
await users.upsert(fromBilling, { conflict: 'id', update: ['plan', 'seats'] }) // one statement, all or none
```

```python
await users.upsert(from_billing, conflict="id", update=["plan", "seats"])  # one statement, all or none
```

```go
_, err = users.UpsertMany(ctx, fromBilling, sqldb.Conflict("id"), sqldb.Update("plan", "seats"))
```

```rust
users.upsert_all(&from_billing, Upsert::on(["id"]).update(["plan", "seats"]))?; // one statement, all or none
```

`update` stays required: name each column a stored row takes from the new
one. In Bun and Node an upsert without it is now `InvalidError`, where it
was a `TypeError`. A statement holds at most 32,766 values, so split a long
list, as for `insert`.

## How many keys

Retiring a bucket meant walking its pages to know when it is empty.
`count()` says how many keys `all()` would walk now, of the bucket or of a
branch ([Branches](https://tinyshed.org/tinystore/docs/guides/kv/branches.md#how-many-keys)):

```ts
const left = await uploads.count() // 1834
const mine = await sessions.under(userId).count() // one user's sessions
```

```python
left = await uploads.count()  # 1834
mine = await sessions.under(user_id).count()  # one user's sessions
```

```go
left, err := uploads.Count(ctx) // int64
mine, err := sessions.Under(userID).Count(ctx)
```

```rust
let left = uploads.count()?; // u64
let mine = sessions.under(user_id).count()?;
```

An expired key is not counted, even before it is deleted from the file. It
reads every key of the branch, so its cost grows with the branch.
`tinystore status ./data --names` counts every bucket whole.

## Who listens now

A page synced every 15 seconds while someone has it open, every 5 minutes
otherwise, kept its own count of listeners in memory, wrong the day there
are two processes. `subscribers()` counts every subscription a message
published on a branch now would reach, in every process that reaches the
store ([Subscriptions](https://tinyshed.org/tinystore/docs/guides/channels/subscriptions.md#who-listens-now)):

```ts
const live = store.channel<Change>('live')

const watched = (await live.under(courseId).subscribers()) > 0
setTimeout(sync, watched ? 15_000 : 300_000)
```

```python
live = store.channel("live", Change)

watched = await live.under(course_id).subscribers() > 0
```

```go
live, err := channels.OpenChannel[Change](store, "live")

n, err := live.Under(courseID).Subscribers(ctx) // an int
watched := n > 0
```

```rust
let live = store.channel::<Change>("live").open()?;

let watched = live.under(course_id).subscribers()? > 0; // a usize
```

It counts the branch's own subscriptions and the `recursive` ones above it.
Hooks for the first and the last subscriber are not built.

## How long a hold waited

A lease and a permit now say how long their hold waited for its key, for a
chart of a semaphore's queue
([Holding](https://tinyshed.org/tinystore/docs/guides/locks/holding.md#how-long-a-hold-waited)):

```ts
const moodle = store.semaphore('moodle', { limit: 24 })

await moodle.hold('requests', async permit => {
	queueWait.record(permit.waited) // '22ms'
	return fetchMoodle(permit.signal)
})
```

```python
moodle = store.semaphore("moodle", limit=24)

async with moodle.hold("requests") as permit:
    queue_wait.record(permit.waited)  # timedelta(microseconds=22000)
    await fetch_moodle()
```

```go
moodle, err := locks.OpenSemaphore(store, "moodle", locks.Limit(24))

err = moodle.Hold(ctx, "requests", func(ctx context.Context, permit *locks.Lease) error {
	queueWait.Record(permit.Waited) // 22ms, a time.Duration
	return fetchMoodle(ctx)
})
```

```rust
let moodle = store.semaphore("moodle").limit(24).open()?;

moodle.hold("requests", |permit| {
    queue_wait.record(permit.waited()); // a Duration
    fetch_moodle()
})?;
```

- It is never less than the time the hold stood in line.
- With the store's [own metrics](https://tinyshed.org/tinystore/docs/guides/metrics/self-metrics.md) on,
  `tinystore_locks_waiting` and `tinystore_locks_held` say how many asks wait
  and how many leases are held now, and a lost lease is labelled by its lock.
- A breaker for a service that is down is not built: the
  [semaphores guide](https://tinyshed.org/tinystore/docs/guides/locks/semaphores.md#a-pause-when-what-it-guards-is-down)
  keeps that decision in a key with a `ttl`.

## A store for each test

A test made a temporary directory, opened a store in it, closed it and
removed the directory. `openTemp` does all four, and the store can run on a
clock the test moves, embedded, with no process
([Testing jobs](https://tinyshed.org/tinystore/docs/guides/jobs/testing.md#a-store-for-each-test)):

```ts
import { openTemp } from '@tinyshed/tinystore/testing'

await using store = await openTemp({ clock: new Date('2026-10-09T09:00:00Z') })
await store.clock.advance('1h')
```

```python
from tinystore.testing import open_temp

async with open_temp(clock=datetime(2026, 10, 9, 9, tzinfo=UTC)) as store:
    await store.clock.advance("1h")
```

```go
store := tinystoretest.Open(t, tinystore.Clock(time.Date(2026, 10, 9, 9, 0, 0, 0, time.UTC)))
err = store.Clock().Advance(ctx, time.Hour)
```

```rust
let clock = Arc::new(TestClock::new(start));
let store = tinystore::testing::open_temp(Options { clock: Some(clock.clone()), background: false, ..Options::default() })?;
clock.advance(Duration::from_hours(1));
```

- Its close removes the directory: `await using`, `async with`,
  `t.Cleanup` in Go, the drop in Rust. A file still held a second after the
  close fails the close, so a leaked handle shows.
- Each test has its own store, so tests run in parallel.
- Rust needs the crate's `testing` feature, in `[dev-dependencies]`.

## Write to a store a program holds

Writing from the shell to a store a program holds embedded needed a sidecar
or `tinystore serve`. With `cli`, the program listens where a sidecar would,
on a socket or a named pipe only its own user may reach, and every write
command goes through it
([Command line](https://tinyshed.org/tinystore/docs/guides/cli.md#writing-to-a-store-a-program-holds)):

```ts
const store = await open('./data', { embedded: true, cli: true })
```

```python
store = await tinystore.open("./data", embedded=True, cli=True)
```

```go
store, err := tinystore.Open(ctx, "./data", tinystore.Embedded(), tinystore.CLI())
```

```rust
// with the library's `local` feature
let store = Store::open("./data", Options { cli: true, ..Options::default() })?;
```

```sh
# while the program runs
tinystore jobs ./data add teacher-reviews '{"teacher":4353}'
```

- `tinystore mcp --write` works too. `tinystore stop ./data` refuses: the
  program decides when it stops.
- A close tells each command to go, waits up to 2 seconds for its calls,
  and removes `SERVE` before it lets go of the directory.
- It serves four commands at a time, and an SDK that would open the
  directory through a sidecar gets `InUseError`, naming the program's pid.

## Durations as the store reads them

The TypeScript package now exports `ms` and `spelled`, the parser the
store's own calls use, so `'60d'` means the same to the program and to the
store ([Layers](https://tinyshed.org/tinystore/docs/guides/config/layers.md)):

```ts
import { ms, spelled } from '@tinyshed/tinystore'

ms('60d') // 5184000000
spelled(5_400_000) // '1h30m'
```

## Changed names

- Records: a list in a `where` means any of its values, where it was the
  list itself. Put a list or an object meant as the value in a list:

  ```ts
  await api.list({ since: '1d', where: { tags: ['a', 'b'] } })   // 0.10.0: tags is ['a', 'b']; 0.11.0: tags is 'a' or 'b'
  await api.list({ since: '1d', where: { tags: [['a', 'b']] } }) // 0.11.0: tags is ['a', 'b']
  ```

- Jobs: a job that failed for good is kept for `keep` but holds no id. An
  `add` of its id answers `true` and starts a new job, its attempts from
  one; until the new job's first run ends, a `get` shows the failed one's
  `error`. `set` of the id starts it again, and `upsert` adds it:

  ```ts
  await sends.add(push, { id: 'push:42' }) // after push:42 failed: 0.10.0 false, nothing added; 0.11.0 true, a new job
  ```

- Rust: `search::Found` gains `total` and is `#[non_exhaustive]`, so a
  pattern names `..` and a test can no longer build one by a struct literal:

  ```rust
  let Found { hits, corrected } = found;     // 0.10.0
  let Found { hits, corrected, .. } = found; // 0.11.0
  ```

- Rust: `search::is_in` takes `impl Values`, a list or a statement, so it
  takes no turbofish:

  ```rust
  .filter(is_in::<&str>("brand", &brands)) // 0.10.0
  .filter(is_in("brand", &brands))         // 0.11.0
  ```

## Fixes

- A query field an SDK does not know, `name` written for `names`, was
  dropped in Bun and Python, so a records or metrics query read everything.
  It is refused now, naming the field and the one it was likely meant to be.
- A walk of a metrics aggregate's pages gave a group cut by a page in two
  parts; it gives each group once, whole.
- A read inside a transaction over the wire took only the rows of one
  answer, so an `all` that worked outside failed inside. Its rows now come
  in parts of about 1 MiB, which an SDK of 0.11 joins; an older SDK is
  refused as `limit`.
- A schedule's run missed while the program was down was lost when the
  deploy that brought it back changed its repeat.
- A search filter's list past its bound did not say which bound it passed;
  it names it, 101 values past 100.
- Bun dropped `clock` given with `private` and `embedded` together; `clock`
  now works on an embedded store, and `private` with `embedded` is refused.
- Bun and Node logged an `Error` inside a field as `{}`.

## Install

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

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

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

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

0.11.0 adds a step to jobs' migrations (`0002_own_options.sql`), to
search's (`0003_keys.sql`) and to records' (`0005_holes.sql`), in jobs.db, search.db
and records.db, and in a database's file that holds a queue or a table's
index. So 0.10.0 refuses a store that 0.11.0 has opened rather than read it
wrong. Open it with 0.11.0 or later. What a program gets over the wire comes
once the server is 0.11.0. The server image is
`ghcr.io/tinyshed/tinystore:0.11.0`.

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