SSyncropel Docs

Query

Filter records with structured query documents: nested fields, and/or/not, pagination, and an explain option that shows whether a filter uses an index.

Overview

Query lets you ask the workspace: "give me every record where X", with X expressed as a structured filter document. The filter runs on the workspace, so only the matches are sent to you. Use it for any query that touches more than one thread, any filter over body shape (body.kind, body.priority, body._refs.*), or any data large enough that filtering in your own code would waste bandwidth.

Two entry points:

  • HTTP: POST /v1/records/query with a JSON body describing the filter.
  • SDK: client.richQuery({ filter, ... }) (TypeScript) or await client.query(filter, ...) (Python).

This guide covers both, the filter format, and how to use the explain flag to check that an index is being used.

Quick Start

# All INTEND records on task threads from the dev agent, newest first.
curl -s -X POST http://localhost:9100/v1/records/query \
  -H 'content-type: application/json' \
  -d '{
    "filter": {
      "act": "INTEND",
      "actor": "did:sync:agent:dev",
      "body.kind": { "$in": ["core.task.record", "core.task.record.v1"] }
    },
    "sort": { "clock": -1 },
    "limit": 20
  }'

The same query from TypeScript:

import { Client, Identity } from "@syncropel/sdk";

const client = new Client({
  endpoint: "http://localhost:9100",
  identity: Identity.static("did:sync:user:alice"),
});

const result = await client.richQuery({
  filter: {
    act: "INTEND",
    actor: "did:sync:agent:dev",
    "body.kind": { $in: ["core.task.record", "core.task.record.v1"] },
  },
  sort: { clock: -1 },
  limit: 20,
});

for (const rec of result.records) {
  console.log(rec.id, rec.body);
}

And Python:

from syncropel import Client, Identity

client = Client(
    endpoint="http://localhost:9100",
    identity=Identity.static("did:sync:user:alice"),
)

records = await client.query(
    filter={
        "act": "INTEND",
        "actor": "did:sync:agent:dev",
        "body.kind": {"$in": ["core.task.record", "core.task.record.v1"]},
    },
    sort={"clock": -1},
    limit=20,
)

for rec in records:
    print(rec["id"], rec["body"])

Filter Grammar

A filter is a JSON object. Top-level keys are AND-combined. Each value is either a plain value (shorthand for $eq) or an operator object.

Comparison operators

OperatorSemanticsExample
$eqfield equals value{ "act": { "$eq": "KNOW" } }
$nefield differs from value{ "body.status": { "$ne": "cancelled" } }
$gtgreater than{ "clock": { "$gt": 100 } }
$gtegreater than or equal{ "clock": { "$gte": 100 } }
$ltless than{ "clock": { "$lt": 1000 } }
$lteless than or equal{ "clock": { "$lte": 1000 } }
$infield in list{ "actor": { "$in": ["did:...", "did:..."] } }
$ninfield not in list{ "act": { "$nin": ["DO", "CALL"] } }
$likeSQL LIKE pattern{ "body.title": { "$like": "music/%" } }
$ilikecase-insensitive LIKE{ "body.title": { "$ilike": "%LOVE%" } }
$existsfield present (true) or absent (false){ "body.awaits": { "$exists": true } }

A plain value, such as { "act": "KNOW" }, is equivalent to { "act": { "$eq": "KNOW" } }.

Logical combinators

OperatorSemanticsExample
$andall children must match{ "$and": [{ "act": "KNOW" }, { "clock": { "$gt": 0 } }] }
$orany child matches{ "$or": [{ "act": "DO" }, { "act": "CALL" }] }
$notchild must not match{ "$not": { "actor": "did:sync:system:engine" } }

Top-level fields are AND-combined implicitly, so $and is usually only needed inside $or/$not.

Allowed field paths

Only these paths are allowed. Other fields, such as signatures, can't be queried.

  • Top-level columns: id, thread, actor, act, clock, data_type, namespace, created_at
  • Body paths: body.<segment>[.<segment>...] where each segment matches [A-Za-z0-9_-]+

So body.kind, body.priority, and body._refs.music_artist all work; body alone (without a sub-path) is rejected.

Request Shape

{
  "filter":   { /* the filter described above */ },
  "thread":   "th_optional_scope",
  "sort":     { "clock": -1 },
  "limit":    100,
  "offset":   0,
  "explain":  false
}
  • thread: optional. Limits the query to one thread, the same as adding { "thread": "th_..." } to the filter. This is fast.
  • sort: an object with one key; the value is 1 for ascending, -1 for descending. Example: { "clock": -1 } (newest first), { "created_at": 1 } (oldest first), { "body.priority": -1 } (highest priority first, but see body-kind manifests for why you'll want to declare body fields first).
  • limit: default 100, clamped to 1000. Asking for more returns 1000 rows and capped: true; read capped to know a page is partial. matched_total counts only the rows you are allowed to see, so it can be lower than the workspace's real total. Use capped, not matched_total, to decide whether you have the whole answer.
  • offset: for pagination. Once you have a last-seen clock, prefer { "clock": { "$gt": last_clock } } as a cursor: it is cheaper than a deep offset.
  • Counts and pages: a count that takes more than 250 ms answers read.total: null with read.total_at_least; send "total": "skip" to count nothing. Send next_cursor back unchanged as cursor, or you get 400 CURSOR_INVALID. A read that takes too long answers 503 READ_BUDGET_EXCEEDED. See Reads, budgets and cursors.
  • Who can filter on what: callers other than the owner can filter, sort or group only on the routing fields (body.kind and the record's own fields) and on the columns of views declared for them; any other body field returns 400 QUERY_FIELD_NOT_READABLE {field}. "own_writes": true serves the caller's own writes with body filters. See the rules.
  • explain: when true, the response includes a plan describing which fields used an index and which fields had to scan record bodies.

The same grammar, from inside an actor

An actor working on a task uses this same filter format through its query_thread tool instead of HTTP, with the same access rules:

{"thread": "th_library", "filter": {"body.kind": "track.v1", "body.labeled": false}, "count_only": true}

count_only returns how many records match without returning them, so an actor can count a large thread without loading it all. A sandboxed run sees exactly what its credential could read anyway.

Two messages are worth knowing. A field path that can't be used is named in the error (unknown field path: kind; body fields are body.<path>). And "the filter matched nothing" is reported differently from "the thread may hold records outside this run's view". Neither proves nothing exists, so don't treat them as the same answer.

Using explain

The explain flag is how you verify a query is using an index before running it against a large set of records:

curl -s -X POST http://localhost:9100/v1/records/query \
  -H 'content-type: application/json' \
  -d '{
    "filter": { "thread": "th_abc...", "body.kind": "music.catalog.track" },
    "limit": 1,
    "explain": true
  }' | jq '.plan'

Example response:

{
  "indexed_fields": ["thread"],
  "unindexed_fields": ["body.kind"]
}

The plan says body.kind was matched by scanning record bodies, a slow scan. To make it use an index, declare a body-kind manifest:

spl config add-body-kind-manifest \
  --kind music.catalog.track \
  --indexed-field body.kind \
  --indexed-field body.title

After the workspace reloads config, queries on body.kind are served from the new index. The plan's unindexed_fields list still names body.kind, because it lists every body.* path whether or not an index is used; measure the query time to confirm.

Patterns

"Most recent by thread"

{
  "thread": "th_abc...",
  "sort": { "clock": -1 },
  "limit": 50
}

The thread shortcut is fast however much data you have.

"All tasks assigned to a specific agent"

{
  "filter": {
    "body.kind": { "$in": ["core.task.record", "core.task.record.v1"] },
    "body.assigned_to": "did:sync:agent:dev"
  },
  "sort": { "clock": -1 }
}

Declare body.kind + body.assigned_to in a manifest to avoid the body scan once your task log exceeds a few thousand records.

"Records produced in the last hour"

{
  "filter": {
    "created_at": { "$gte": 1719830400 }
  },
  "sort": { "created_at": -1 },
  "limit": 100
}

created_at is already indexed; no manifest needed.

"Reference lookup"

{
  "filter": {
    "body._refs.music_artist": "spotify:artist:4Z8W4fKeB5YxbusRsdQVPb"
  }
}

References stored via Ref.* constructors in the SDK live at body._refs.<entity>. Declare each reference path you query in a manifest for speed.

"Pending decision-gate proposals"

{
  "filter": {
    "act": "KNOW",
    "body.awaits": "actor_decision"
  },
  "sort": { "clock": -1 }
}

Limits & Failure Modes

  • Filter depth: nested $and/$or works, but deep nesting gets slower. Keep filters under about 10 levels.
  • Type mismatches: comparing a body field that is sometimes a string and sometimes an object returns no match; the comparison uses the stored type, so a text filter won't match when the stored value is an object. Use $exists: true if you only need to check presence.
  • No joins: the filter operates on one record at a time. For "records where another record referencing them exists", compose two queries client-side.
  • SDKs on network errors: both SDKs return an empty record list (not an exception) on network or server errors. An empty list can mean "no matches" or "the request failed". Use the onEmit hook or the raw HTTP call if you need to tell them apart.

A query can be a record (core.query.v1)

Everything above is a filter you send and a result you read. When a query is worth keeping (a view you return to, a named scope, a standing question), you save it as a record of kind core.query.v1.

A one-off filter, a saved View and a standing (live) query are all the same kind of record, core.query.v1, kept on the th_queries thread. The record carries:

  • pipeline: the filter, facets, sort and window (the same filter you would send directly).
  • name: required once the query is saved.
  • saved / live: lifecycle flags. saved turns a one-time filter into a lasting View; live makes it a standing query.
  • provenance: where it came from, as source_thread (the conversation that shaped it), trigger_record, derived_from (an earlier query it was copied from).

A saved View has a lasting identity and history you can revisit and share, so you don't have to retype it. Queries are saved and promoted in the workspace (the Studio scope bar). There is no CLI command for them: you write a core.query.v1 record like any other.

core.query.v1 is distinct from core.graph.query.v1 (a request to explore a connected workspace's graph). The two are different and not interchangeable.

Next Steps

On this page