{/* Generated from dreamdb-core spec snapshot c63af5f16bfa1ce0c6a7cf8c58d3dfc1c5bf7022 by scripts/sync-spec-docs.mjs — do not edit. */}
# Spec 0028 — Read-only SQL v1

Status: v1 contract for [#377](https://github.com/dreamlake-ai/dreamdb-core/issues/377).
This is a query API, not a persisted format or a claim of SQL conformance.

## 1. Boundary and syntax

The initial surface is the native Rust `dreamdb-sql` crate. Existing SDKs,
wire formats and writers do not acquire a parser dependency. Python, JavaScript,
CLI and remote query-service adapters can use this contract in later work;
they are not part of v1. An engine opens one named Dataset through a caller's
Connector. SQL cannot select a bucket, URL, file, credential or another Dataset.

Supported statements are one SELECT, optionally prefixed with EXPLAIN:

```sql
SELECT _anchor, label AS class FROM dataset WHERE label = $1 LIMIT 20
SELECT _anchor, caption FROM dataset
  WHERE _anchor >= $1 AND _anchor < $2 LIMIT 100
SELECT _anchor, _score FROM vector_search('embedding', $1, 10, 8)
SELECT _anchor, title FROM text_search('title', $1, 10)
  WHERE rating >= 3 LIMIT 5
```

Projection is a list of field identifiers or `_anchor`, `_timeline`, `_score`,
optionally AS an identifier. Wildcards, expression projections, table aliases,
qualification, JOIN, subqueries, WITH, DISTINCT, aggregates, ORDER BY, OFFSET,
FETCH, hints, locking, multiple statements and all writes are rejected.
Unquoted field identifiers fold to lowercase; double-quoted identifiers match
Schema names exactly. Reserved pseudo-column names cannot shadow Schema fields.
Output names must be unique. SELECT list order is preserved.

WHERE supports field/literal comparisons (=, !=, \<, \<=, >, >=), AND, OR, NOT,
parentheses, IS NULL and IS NOT NULL. Scalar comparisons are strictly typed;
integer literals can bind to float columns only by an exact conversion.
Booleans, strings, finite floats, signed integers and NULL are values. Timestamp
columns compare integer nanoseconds. `$N` is a one-based typed parameter,
never interpolated SQL; vectors are parameter values, not SQL string literals.
Unknown fields, unavailable parameters and unsupported expressions fail before
query execution. LIMIT and search k must be nonnegative/positive integers
respectively; limits exceeding execution policy fail instead of truncating
silently. No implicit casts of strings to numbers or truth values.

## 2. Rows and missing values

The opened Dataset has exactly one Timeline. Row identity is (Timeline, anchor).
`dataset` contains the union of live anchors in its scalar fields, independent
of projection. It does not enumerate media-only or embedding-only anchors.
Scalar values join by exact anchor, not interval overlap or nearest neighbor.
Absent scalar values produce SQL NULL. Comparisons to NULL are UNKNOWN; WHERE
keeps TRUE only. NOT UNKNOWN remains UNKNOWN. Tombstones are respected.

Scalar projection is supported; projection of embeddings, arrays, text-index
pseudo-fields, images, video, audio and geometry is rejected before their bodies
are read. V1 does not manufacture a generic media reference without a defined
type. `_anchor` is u64, `_timeline` is the Timeline hash string, and `_score`
is f32 available only for search sources. Ordinary rows are anchor-ascending.

## 3. Search

`vector_search(field, vector_parameter, k, nprobe)` invokes the existing scored
vector API without hydration. `nprobe` is explicit and positive. Execution
options also carry embedding-space identity, rerank mode and pool size; existing
identity/exactness checks apply and graph queries reject unsupported probe
controls rather than ignoring them. No automatic approximate fallback.

`text_search(field, query, k)` invokes the existing typed text-index binding.
Search sources contain the returned top-k anchors, including anchors not in the
ordinary scalar row universe. WHERE is **after top-k**, then LIMIT; it does not
refill k or mean filtered ANN retrieval. `_score` is the product API score.
Search order is descending score, then ascending anchor within the returned
candidate set. This does not change selection at the underlying top-k tie cutoff
or certify approximate retrieval recall. No implicit fusion or hybrid scoring.

## 4. Snapshot, planning and performance

A SQL session pins the Ref bytes on open. All internal reopens see those same
bytes, and the content-addressed Manifest is verified by Dataset. A new session
is needed to observe an advanced Ref. The wrapper rejects writes and other Ref
access; SQL has no publication or mutation path.

Parsing, binding, logical planning, physical planning and execution are separate
steps. EXPLAIN binds names/types and reports the pinned Manifest, source operator,
indexed predicates, projected fields, candidate selection, residual predicates,
search controls, post-top-k semantics, scan policy and materialization limits.
It executes no search, bucket scan or column hydration (session open has its own
metadata reads). It must not advertise an index-only plan when column lookup
needs an index walk.

For ordinary SELECT, a scalar comparison leaf or an AND-contained comparison
can drive candidate anchors through `query_scalar`; an OR can drive candidates
only when both sides have complete index-backed candidates. NOT is normalized
using De Morgan's laws and inverse comparisons without complementing NULL rows.
Residual evaluation is still performed for SQL NULL/type semantics. NULL tests, anchor
windows and otherwise unindexable predicates require scalar anchor enumeration.
Such enumeration requires explicit `allow_scan`; it is refused by default.
EXPLAIN may show a scan plan without granting permission to execute it.
Index readers can themselves scan legacy bitmap indexes for ordered comparison;
EXPLAIN must disclose that possibility, not promise universal B-tree pruning.

Projection is late: predicate columns first, then LIMIT, then output-only
columns. Never enumerate or hydrate unrequested media. Existing scalar indexes
are value-to-anchor, not anchor-to-value: materializing a column may walk that
column's index and overlapping buckets even for small LIMIT. V1 must say so and
cannot claim O(LIMIT) I/O. Scalar reads must surface missing/corrupt dependency
errors rather than convert storage failure to NULL.

### 4.1 Execution diagnostics

Successful query output includes `timings` with integer microseconds:
`selection_us`, `materialization_us`, and `total_us`. Selection covers predicate
index evaluation, candidate enumeration/search, residual reads/filtering and
LIMIT. Materialization covers remaining projected-column reads and result-batch
construction. Scalar enumeration may already read projected values during
selection; these are elapsed phases, not disjoint categories of storage work.
Total covers both phases and executor overhead after acquiring the session lock.
Session open, parse/bind, lock wait and adapter serialization are excluded.
EXPLAIN and LIMIT 0 report zero phase timings and do not read query data.
Zero is valid for a phase below clock resolution. Errors return no partial stats.

`reads.requests` counts admitted logical GET/HEAD operations (one per requested
range for multi-range reads), not HTTP retries or sockets. `reads.bytes` counts
returned payload bytes, not headers or physical transfer. Counters reset for each
execution; session caches persist, so warm and cold executions are not comparable
without identifying that difference. These diagnostics do not report cache-hit
ratios, memory peaks or storage-device throughput.

## 5. Resource and failure contract

Execution options bound SQL bytes, candidate count, output
rows, batch size, connector requests and returned connector bytes. An explicit
cancel flag and deadline are checked at execution/I/O boundaries. Requests are
counted before dispatch; bytes after return, so one response can exceed the byte
budget before rejection. Lower-level eager index/search calls can allocate their
whole candidate list before the candidate-count check. Batched output is not
a streaming execution or hard working-set guarantee. Cancellation cannot
preempt synchronous decoding/scoring or retract an in-flight backend request.
Resource failure returns an error, not successful partial results.

SQL input is additionally capped at 1,024 lexer tokens and parser/predicate
depth 64. Read counters measure connector-level operations, not HTTP retries:
multi-range calls preserve backend batching and are charged per requested range.
Returned bytes are logical response bytes, not wire traffic or decompressed
working-set measurements. Index-only predicate evaluation need not hydrate its
scalar column; NULL presence tests and output projection do.

Error classes distinguish parse/unsupported, bind/type, resource/cancel and
storage/product failures. Search text/vector and comparison values must not be
included in EXPLAIN; bound field names, limits and search controls are visible.
Prepared plans are session-bound; no stale plan can run on a different snapshot.

## 6. Minimum acceptance and extension

Direct product-boundary checks cover scalar/NULL/boolean semantics, projection,
parameters, snapshot stability, indexed reads, scan refusal, cancellation,
limits, vector and BM25, and rejection of unsupported/write syntax. Measure SQL
against equivalent direct APIs with the same data and search controls; record
connector request/byte counts and result equality, not network latency claims.
A projected indexed anchor-only query must avoid column/media hydration.
No new benchmark framework or recursive testing of evidence machinery.

Future joins, aggregation, ordering and hybrid retrieval add logical/physical
operators, not reinterpret v1 syntax. Future general row domains and media
references require explicit contracts. Resource-aware streaming must reach the
underlying operators before stronger bounds are advertised. No storage rewrite,
production rollout, package release or change to #89 is implied.

## 7. SDK and CLI adapters (#379)

The initial native-only scope above describes #377. The adapters add Python
`SqlSession.open(ref_name, backend)` and npm `SqlSession.open(refName, backend)`,
with `query(sql, params, options)` and `explain(sql, params, options)`, plus
`dreamdb sql --backend ... --ref-name ... --query ...`. They use the same Rust
binder/planner/executor. Each independently opened session pins its Ref; it does
not follow an independently opened Dataset/Space or automatically refresh.

Python exposes a synchronous boundary with the GIL released for I/O. JavaScript
exposes asynchronous open/query and synchronous explain, in Node and browser
builds. Browsers load a separate read-only SQL WASM artifact on first open;
ordinary Space/Writer calls do not download the SQL parser. SQL parameters accept null,
boolean, string, finite number, exact integer and vector; booleans are not ints.
JS integer Numbers outside the safe integer range MUST be rejected, not rounded;
BigInt carries i64/u64 and SQL integer result values are BigInt. Python returns
int and None without losing 64-bit values. CLI JSON parameters use ordinary
JSON values or explicit `{ "type": "int"|"uint", "value": "decimal" }`
for exact integers; numeric arrays are vectors. CLI JSON integer results are
decimal JSON numbers and consumers must use a lossless integer parser.

Options use snake_case consistently across adapters: scan permission, candidate,
row, batch, read, byte and SQL-size limits, timeout_ms, rerank_mode,
rerank_pool_size and query_spec_id. Unknown keys and invalid ranges refuse.
Timeouts use a target-appropriate clock/timer; browser execution must not invoke
a native Tokio timer. Cancellation remains available on the native Rust API;
adapters initially expose timeouts, not an AbortSignal/cancel-handle API.

Results retain columns, column-major batches, explain and read statistics.
Adapters do not hydrate fields, change search controls or run queries for
EXPLAIN. Resource limits are unchanged; language marshalling adds allocations
and does not imply streaming or a hard memory bound. CLI stdout is one JSON
result, failures go to stderr with a nonzero exit; no partial success document.
This integration does not itself publish registry packages.
