This document captures an implementation-oriented reading of DuckDB's Quack protocol, version 3, which is still experimental. The date of examination is
2026-10-22. It is based on duckdb-quack@4f4b4c0 and duckdb@d25d1ce (branchv2.0-cyanoptera, DuckDB v2.0.0), both pinned as submodules underreferences/. Wire details were verified against a live DuckDB v2.0.0quack_serve()server.
The original Quack v1 examination (duckdb-quack@be9c9bb, 2026-05-13) was guided manually and performed with Codex and
gpt-5.5 xhigh. This revision for Quack v3 and the SDK's v3 implementation was performed with Claude Code (Opus 5.5).
Quack adds a client-server protocol to DuckDB. A DuckDB process can listen for
remote requests, and another DuckDB process can attach that remote database or
run one-off queries against it. It is an HTTP-based protocol whose bodies use
DuckDB's binary serialization format (application/vnd.duckdb).
At the wire level, Quack is simpler than it first appears:
- The transport is HTTP.
- The endpoint is
POST /quack. - Each request contains exactly one binary Quack message.
- Each response contains exactly one binary Quack message.
- The binary message format is DuckDB's
BinarySerializer. - Query result data and client data are serialized as DuckDB
DataChunks.
That last point is the most important one for a TypeScript client. We do not only need to parse a small message envelope. To read query results and send data, we need to encode and decode a meaningful subset of DuckDB's logical types, vectors, validity masks, and nested data encodings.
Quack v3 (DuckDB v2.0) is not wire compatible with v1 (DuckDB v1.5). The server accepts exactly one protocol version. The main changes:
| Area | v1 | v3 |
|---|---|---|
| Protocol version | 1 |
3; the server rejects any client whose [min, max] range excludes 3 |
| Response MIME type | application/duckdb |
application/vnd.duckdb |
| Serialization target | SerializationCompatibility::FromIndex(7) |
storage_compatibility = V2_0_0 |
| Connection lease | none | required heartbeat lease (heartbeat_timeout_seconds) |
| Query id | server-generated result_uuid |
client-generated query_uuid sent in PREPARE_REQUEST |
| Fetch | stateful "next batch" | batch-indexed (batch_index, ack_index), retry-safe |
| Fetch payload | chunks inside the response body | raw chunk blob after the response body |
| Writes | APPEND_REQUEST (id 9) |
removed; SEND_DATA_REQUEST (id 9) feeds an INSERT … FROM scan_data_from_quack_client(…) statement |
| New messages | – | CANCEL_REQUEST, SEND_DATA_RESPONSE, ACKNOWLEDGEMENT, HEARTBEAT_REQUEST |
| Errors | message only | message, exception type, extra info, must_invalidate |
| String vectors | list of strings in field 102 |
lengths blob + bytes blob (fields 107–109) |
| New logical types | – | TIMESTAMP_TZ_NS, TUPLE; VARIANT with shredded vectors |
| TLS | local HTTP | HTTPS by default for non-local hosts, certificate pinning |
Quack is a request-response RPC protocol. The client owns the session flow. The server never pushes data by itself; the client explicitly fetches result batches after a query starts and explicitly sends data batches to statements that read client data.
flowchart LR
subgraph Client["Client process"]
TS["TypeScript client"]
Enc["Quack message encoder"]
Dec["Quack message decoder"]
Chunk["DataChunk codec"]
HB["Heartbeat timer"]
end
subgraph Transport["HTTP transport"]
Post["POST /quack"]
Bytes["application/vnd.duckdb bytes"]
end
subgraph Server["DuckDB server process"]
Http["HTTP server (httplib)"]
Msg["QuackServer::HandleMessage"]
Conn["QuackConnection + lease"]
Drive["DriveQuery thread"]
Buf["Claim buffer (result batches)"]
DB["DuckDB Connection"]
end
TS --> Enc --> Post --> Bytes --> Http --> Msg --> Conn
HB --> Enc
Conn --> Drive --> DB
DB --> Buf --> Msg
Msg --> Http --> Bytes --> Dec --> Chunk --> TS
A Quack server is started from a DuckDB session with quack_serve. Each
PREPARE_REQUEST starts a DriveQuery thread that runs the SQL on the
connection's DuckDB Connection. A custom result collector serializes the
result into dense, numbered batches inside a bounded claim buffer, and
PREPARE and FETCH handlers pop those batches by index.
The DuckDB URI parser accepts:
quack:localhostquack:localhost:9494quack://localhostquack:[::1]:9494
The default port is 9494. The parser trims whitespace, strips the quack: or
quack:// prefix (only as a prefix, so hosts containing quack: survive),
extracts IPv6 hosts from square brackets, and rejects ports outside
0..65535.
The HTTP URL is derived from the Quack URI and its SSL flag:
quack:localhost -> http://localhost:9494
quack:127.0.0.1:9000 -> http://127.0.0.1:9000
quack:myhost:9000 -> https://myhost:9000
quack:[::1]:9494 -> http://[::1]:9494
quack_serve only listens on localhost, 127.0.0.1, or ::1 unless it is
called with allow_other_hostname := true ("We strongly recommend
reverse-proxying the Quack RPC when making it publicly available").
v3 enables HTTPS by default for every host except localhost, 127.0.0.1, and
::1, on both the server (quack_serve) and the DuckDB client. quack_serve
accepts disable_ssl := true to override this, and ssl_cert_file /
ssl_key_file to serve a given certificate (otherwise it generates a
self-signed one). DuckDB clients can pin the server certificate by its
SHA-256 fingerprint (ssl_fingerprint, from the ATTACH options or the quack
secret); with a pin, the client accepts exactly that certificate and skips CA
and hostname validation.
GET /returns a plain text informational message. It is a convenient readiness probe.OPTIONS /quackreturns permissive CORS headers (Access-Control-Allow-Origin: *) and status204.POST /quackreads the request body into a memory stream, decodes one message, handles it, and returns one response message asapplication/vnd.duckdb, also withAccess-Control-Allow-Origin: *.
The server does not check the request Content-Type. Protocol-level failures,
including messages that fail to decode, are returned as ERROR_RESPONSE with
HTTP status 200; only transport problems surface as HTTP errors.
There is no Quack-level length prefix around a message. HTTP gives the message boundary.
sequenceDiagram
participant C as Client
participant S as Quack server
C->>S: CONNECTION_REQUEST(auth, version range [3,3], heartbeat_timeout_seconds, client_id?)
S->>S: check version, authenticate token
S-->>C: CONNECTION_RESPONSE(header.connection_id, quack_version=3, heartbeat_timeout_seconds)
loop while idle, about every timeout/3
C->>S: HEARTBEAT_REQUEST(connection_id)
S-->>C: SUCCESS_RESPONSE
end
C->>S: DISCONNECT_MESSAGE(connection_id)
S-->>C: SUCCESS_RESPONSE
sequenceDiagram
participant C as Client
participant S as Quack server
participant D as DriveQuery thread
C->>S: PREPARE_REQUEST(sql, query_uuid, inline_rows?)
S->>S: authorize SQL, abort previous statement
S->>D: run SQL with Quack result collector
D-->>S: bound types/names, batches 1..N into claim buffer
S-->>C: PREPARE_RESPONSE(types, names, inline chunks, needs_more_fetch, query_uuid)
loop until a chunk-less response
C->>S: FETCH_REQUEST(query_uuid, batch_index=k, ack_index=k-1)
S-->>C: FETCH_RESPONSE(chunk_count, batch_index=k) + chunk blob
end
S-->>C: FETCH_RESPONSE(chunk_count=0, total_batches)
sequenceDiagram
participant C as Client
participant S as Quack server
participant D as DriveQuery thread
C->>S: PREPARE_REQUEST("INSERT INTO t SELECT * FROM scan_data_from_quack_client('stream_id', NULL::STRUCT(...), ordered := true)", query_uuid, inline_rows=0)
S->>D: run INSERT, the scan registers stream_id
S-->>C: PREPARE_RESPONSE(types=[Count], needs_more_fetch=true)
loop for each batch k = 1..N
C->>S: SEND_DATA_REQUEST(stream_id, chunk_count, batch_index=k) + chunk blob
S-->>C: SEND_DATA_RESPONSE
end
C->>S: SEND_DATA_REQUEST(stream_id, total_batches=N)
S-->>C: SEND_DATA_RESPONSE
C->>S: FETCH_REQUEST(query_uuid, batch_index=1)
S-->>C: FETCH_RESPONSE + chunk blob (inserted row count)
sequenceDiagram
participant C1 as Client request A
participant C2 as Client request B
participant S as Quack server
C1->>S: PREPARE_REQUEST(slow SQL, query_uuid=Q)
C2->>S: CANCEL_REQUEST(query_uuid=Q)
S->>S: abort statement, interrupt connection
S-->>C2: SUCCESS_RESPONSE
S-->>C1: ERROR_RESPONSE("Interrupted: query was cancelled")
The server accepts these request types and returns ERROR_RESPONSE for any
other:
CONNECTION_REQUESTPREPARE_REQUESTFETCH_REQUESTSEND_DATA_REQUESTDISCONNECT_MESSAGECANCEL_REQUESTACKNOWLEDGEMENTHEARTBEAT_REQUEST
The server keeps active connections in memory. A successful
CONNECTION_REQUEST creates a QuackConnection with:
- a server-generated random token, used as the connection id
- a DuckDB
Connectionwith progress bars disabled - a heartbeat lease (
heartbeat_timeout_seconds, last renewal time) - the current statement: its result stream,
query_uuid, producer thread, and abort error - an optional replay cache of the last client query (reconnect support)
client_id_hash,HMAC-SHA256(server_key, client_id), when the client sent aclient_id
stateDiagram-v2
[*] --> Disconnected
Disconnected --> Idle: CONNECTION_REQUEST accepted
Idle --> Running: PREPARE_REQUEST
Running --> Running: FETCH_REQUEST / SEND_DATA_REQUEST
Running --> Running: PREPARE_REQUEST supersedes statement
Running --> Idle: terminal FETCH_RESPONSE or CANCEL_REQUEST
Idle --> Idle: HEARTBEAT_REQUEST
Idle --> Expired: no request for heartbeat_timeout_seconds
Running --> Expired: no request for heartbeat_timeout_seconds
Expired --> Disconnected: next request gets "Connection heartbeat lease expired"
Idle --> Disconnected: DISCONNECT_MESSAGE
Running --> Disconnected: DISCONNECT_MESSAGE
Every supported, structurally valid message for an existing connection renews
the lease when it arrives. The lease is checked only on arrival: there is no
background sweep, so a long-running request is never cut off mid-flight, but a
client that stays silent longer than the timeout finds its connection gone on
the next request (ERROR_RESPONSE("Connection heartbeat lease expired")). The
server then interrupts and drops the connection.
The client chooses the timeout in CONNECTION_REQUEST. The server rejects 0
and values above INT64_MAX / 1000, and echoes the accepted value in
CONNECTION_RESPONSE. DuckDB's own client defaults to 60 seconds
(quack_default_heartbeat_timeout) and sends a HEARTBEAT_REQUEST every
timeout / 3 seconds with ±20% jitter. Failed heartbeats are retried on the
next interval.
A connection runs one statement at a time. A new PREPARE_REQUEST first aborts
and joins the current statement ("superseded by a new query"). Its stream is
replaced, so later fetches for the old query_uuid return
ERROR_RESPONSE("Result has been closed"). Parallel statements need distinct
Quack connections.
query_uuid {0, 0} is reserved for internal catalog traffic from DuckDB's
own ATTACH client. Such a prepare never displaces the client's cached result.
Client queries must use a nonzero id.
The SQL may contain several statements. The first statement that produces a
result set is sent through the stream. If no statement produces one, the last
statement's result (for example the Count of an INSERT) is sent as a single
batch. A result without columns is an error ("Query did not return any
columns").
Every Quack message is serialized as two DuckDB binary objects back to back.
FETCH_RESPONSE and SEND_DATA_REQUEST are followed by a raw chunk blob:
MessageHeaderobject- message-specific body object
- only for chunk-carrying messages:
chunk_countDataChunkobjects
flowchart LR
Msg["HTTP body"] --> H["MessageHeader object"]
H --> B["Message body object"]
B --> Blob["Chunk blob (FETCH_RESPONSE, SEND_DATA_REQUEST)"]
H --> H1["field 1: type"]
H --> H2["field 2: connection_id (omitted when empty)"]
H --> H3["field 3: client_query_id"]
B --> BodyFields["message-specific fields, incl. chunk_count"]
Blob --> C1["DataChunk object 1"]
Blob --> C2["DataChunk object ..."]
There is no magic number, no protocol byte, and no total length. A decoder
starts at byte 0, reads the header object, uses header.type to choose a body
decoder, reads the body object, and then reads chunk_count chunk objects when
the message carries a blob. Each chunk in the blob is a plain DataChunk
object (Begin / DataChunk::Serialize / End) without a wrapper, field id,
or nullable byte.
The server builds chunk payloads with 256 bytes of free space in front and
writes the header and body into that space right before sending, so a served
batch is never patched. It retains the finished bytes, so a transport retry of
the same FETCH_REQUEST gets an identical response.
The extension serializes messages and chunk blobs with:
BinarySerializer
SerializationOptions.storage_compatibility = StorageCompatibility::FromIndex(StorageVersion::V2_0_0)
serialize_enum_as_string = false (default)
Enums are therefore serialized as their underlying integer values. The storage version also selects DuckDB 2.0's vector encodings (see String Vectors).
DuckDB's BinarySerializer object format is a sequence of fields followed by
an object terminator:
object :=
field*
0xffff
field :=
field_id:u16le
value
A field has no embedded type tag. The decoder must already know the expected schema and type for each field. Required fields are read in order. Optional fields are detected by peeking at the next field id.
WritePropertyWithDefault omits the field entirely if the value equals the
default value. This is a major compatibility detail.
Examples:
- empty string: omitted
- empty vector/list/map: omitted
- numeric zero: omitted, unless an explicit non-zero default is given
false: omitted- invalid
optional_idx: omitted when written withWritePropertyWithDefaultand defaultoptional_idx(); written as the invalid sentinel when written withWriteProperty - null pointer: omitted only when the pointer property itself is written with
WritePropertyWithDefault
If a pointer field is present, the pointer value then has its own nullable byte:
optional property absent -> no field id at all
optional property present null -> field id, present byte = 0
optional property present value -> field id, present byte = 1, object payload
| DuckDB type | Wire encoding |
|---|---|
bool |
one raw byte, 0 or 1 |
| unsigned integers | unsigned LEB128 |
| signed integers | signed LEB128 |
| enums | underlying integer, then integer encoding |
idx_t |
unsigned LEB128 uint64 |
optional_idx |
idx_t, with 0xFFFFFFFFFFFFFFFF meaning invalid |
hugeint_t |
signed LEB128 upper:int64, then unsigned LEB128 lower:uint64 (not an object) |
float / double |
raw 4 / 8 byte little-endian float |
string / string_t / Identifier |
unsigned LEB128 length, then raw UTF-8 bytes |
| data blob | unsigned LEB128 uint64 length, then raw bytes |
| vector/list | unsigned LEB128 idx_t count, then each element |
unordered_map<K, V> |
list of objects {0: key, 1: value} |
| object | nested field sequence terminated by 0xffff |
Identifier is new in DuckDB 2.0 (for example, struct child names). It is
serialized exactly like a string.
The serializer writes raw float, double, field ids, and data blobs using
host memory layout. A client should use little-endian reads and writes,
because DuckDB's common target platforms are little-endian and the code does
not swap bytes.
| Name | Id | Direction |
|---|---|---|
CONNECTION_REQUEST |
1 |
client to server |
CONNECTION_RESPONSE |
2 |
server to client |
PREPARE_REQUEST |
3 |
client to server |
PREPARE_RESPONSE |
4 |
server to client |
FETCH_REQUEST |
7 |
client to server |
FETCH_RESPONSE |
8 |
server to client |
SEND_DATA_REQUEST |
9 |
client to server |
SUCCESS_RESPONSE |
10 |
server to client |
DISCONNECT_MESSAGE |
11 |
client to server |
CANCEL_REQUEST |
12 |
client to server |
SEND_DATA_RESPONSE |
14 |
server to client |
ACKNOWLEDGEMENT |
15 |
client to server |
HEARTBEAT_REQUEST |
16 |
client to server |
ERROR_RESPONSE |
100 |
server to client |
Id 9 used to be APPEND_REQUEST in v1. Ids 5, 6, and 13 are unused.
Every message starts with this header object:
| Field id | Name | Type | Notes |
|---|---|---|---|
1 |
type |
MessageType |
required |
2 |
connection_id |
string |
omitted when empty |
3 |
client_query_id |
optional_idx |
always written; invalid sentinel when unset |
connection_id is the server-issued session id. The server requires it on
every request except CONNECTION_REQUEST, and returns it in the header of the
CONNECTION_RESPONSE. Server responses otherwise leave it empty.
client_query_id is for client/server log correlation. In v3, DuckDB's client
sets it from the active transaction's query id before encoding. Responses
carry the invalid sentinel.
The message bodies are generated from src/include/quack_message.json into
src/serialize_quack_message.cpp. ErrorResponse and the chunk blobs are
handled by hand-written code in src/quack_message.cpp.
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
auth_string |
string |
omitted if empty |
2 |
client_duckdb_version |
string |
omitted if empty |
3 |
client_platform |
string |
omitted if empty |
4 |
min_supported_quack_version |
idx_t |
omitted if 0 |
5 |
max_supported_quack_version |
idx_t |
omitted if 0 |
6 |
client_id |
string |
omitted if empty |
7 |
heartbeat_timeout_seconds |
idx_t |
omitted if 0, which the server rejects |
The server returns an error unless min <= 3 <= max. DuckDB's client sets both
bounds to 3. client_id is optional; when set, DuckDB's client requires at
least 4 characters. The server only stores its HMAC (client_id_hash), which
is shown in quack_active_connections() and the request log.
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
server_duckdb_version |
string |
omitted if empty |
2 |
server_platform |
string |
omitted if empty |
3 |
quack_version |
idx_t |
omitted if 0 |
4 |
heartbeat_timeout_seconds |
idx_t |
omitted if 0 |
The connection id is in the response header. Clients must verify
quack_version == 3 and should use the returned heartbeat timeout.
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
sql_query |
string |
omitted if empty |
2 |
query_uuid |
hugeint_t |
required |
3 |
inline_rows |
optional_idx |
omitted if unset |
query_uuid is chosen by the client and names the statement in later FETCH,
CANCEL, and ACKNOWLEDGEMENT requests. inline_rows caps the rows returned
inline in the prepare response; unset uses quack_prepare_inline_rows
(default 24576). 0 makes the server answer before the statement produces any
row, which statements waiting for client data require.
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
result_types |
vector<LogicalType> |
omitted if empty |
2 |
result_names |
vector<string> |
omitted if empty |
3 |
needs_more_fetch |
bool |
omitted if false |
4 |
results |
vector<unique_ptr<DataChunkWrapper>> |
omitted if empty |
5 |
query_uuid |
hugeint_t |
required, echoes the request |
results holds the inline batches as wrapped chunks inside the body (not as a
blob). The server drains whole batches, so it may overshoot inline_rows up to
a batch boundary. needs_more_fetch is false only when the server saw a clean
end of the result; a stale true costs the client one extra fetch.
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
query_uuid |
hugeint_t |
required |
2 |
batch_index |
idx_t |
omitted if 0, which the server rejects |
3 |
ack_index |
idx_t |
omitted if 0 |
batch_index is 1-based and counts the batches after those returned inline
by PREPARE (the server adds its prepare_batches offset). ack_index tells
the server that batches 1..ack_index arrived, so it can release their
retained payloads. Because every request names its batch, a transport retry
asks for, and gets, the same batch again.
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
chunk_count |
idx_t |
omitted if 0 |
2 |
total_batches |
optional_idx |
omitted if unset; set on the terminal response |
3 |
batch_index |
optional_idx |
omitted if unset; set on data responses |
The body is followed by chunk_count DataChunk objects. A response with
chunk_count == 0 is terminal: the result ended below the requested index, and
total_batches (when known) tells the client how many fetch batches the
result had, so it can detect a lost batch. A data response echoes the
requested batch_index.
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
stream_id |
string |
omitted if empty |
2 |
chunk_count |
idx_t |
omitted if 0 |
3 |
total_batches |
optional_idx |
omitted if unset; set on the terminal message |
4 |
batch_index |
optional_idx |
omitted if unset; required with chunks |
The body is followed by chunk_count DataChunk objects. See
Client Data Streams.
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
accept_budget |
optional_idx |
always written; currently always invalid |
accept_budget is a placeholder for future flow control. Invalid means
unbounded, and DuckDB's client ignores it.
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
query_uuid |
hugeint_t |
required |
{0, 0} cancels whatever statement runs on the connection. Any other id must
match the current statement, or the server returns an error.
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
query_uuid |
hugeint_t |
omitted if {0, 0} |
Confirms that the client received a full result, releasing the replay cache.
The bodies are empty objects (just the 0xffff terminator).
| Field id | Name | Type | Default behavior |
|---|---|---|---|
1 |
message |
string |
omitted if empty; raw message without type prefix |
2 |
exception_type |
string |
omitted if empty, e.g. Catalog, Binder, Invalid Input, INTERRUPT |
3 |
extra_info |
unordered_map<string, string> |
omitted if empty |
4 |
must_invalidate |
bool |
omitted if false |
See Errors.
A FETCH_RESPONSE captured from DuckDB v2.0.0 for
SELECT 'hello'::VARCHAR AS s, NULL::VARCHAR AS n, 42::INTEGER AS i, 'x'::BLOB AS b
with inline_rows = 0, abbreviated to the first column:
01 00 08 header field 1 type = 8 (FETCH_RESPONSE)
03 00 ff ff ff ff ff ff ff ff ff 01
header field 3 client_query_id = invalid
ff ff end of header
01 00 01 body field 1 chunk_count = 1
03 00 01 body field 3 batch_index = 1
ff ff end of body
64 00 01 chunk field 100 rows = 1
65 00 04 chunk field 101 types: list of 4
64 00 19 ff ff {100 id = 25 VARCHAR}
64 00 19 ff ff {100 id = 25 VARCHAR}
64 00 0d ff ff {100 id = 13 INTEGER}
64 00 1a ff ff {100 id = 26 BLOB}
66 00 04 chunk field 102 columns: list of 4
64 00 00 vector field 100 has_validity_mask = false
6b 00 05 vector field 107 byte_data_length = 5
6c 00 04 05 00 00 00 vector field 108 length_data: u32 [5]
6d 00 05 68 65 6c 6c 6f vector field 109 byte_data: "hello"
ff ff end of vector
... three more vectors
ff ff end of chunk
The terminal response of the same query is
0100 08 0300 ffffffffffffffffff01 ffff 0200 01 ffff: header, then body field
2 total_batches = 1.
flowchart TD
Q["PREPARE_REQUEST(sql, query_uuid, inline_rows)"] --> Exec["DriveQuery fills claim buffer with dense batches"]
Exec --> Inline["Pop batches 1..k while inline rows are below the limit"]
Inline --> Prep["PREPARE_RESPONSE(inline chunks, needs_more_fetch)"]
Prep --> More{"needs_more_fetch?"}
More -- "false" --> Done["Client has all rows"]
More -- "true" --> Fetch["FETCH_REQUEST(batch_index = n, ack_index = n - 1)"]
Fetch --> Batch["FETCH_RESPONSE(chunk_count, batch_index) + blob"]
Batch --> Empty{"chunk_count = 0?"}
Empty -- "no" --> Fetch
Empty -- "yes" --> Check["check total_batches = n - 1"] --> Done
- Batches are cut by the shared "rebalancer" sink at roughly
quack_target_batch_bytes(default 32 MiB of serialized chunks). Settings are read from the connection's context, so a client can tune them withSETon its own connection. - The claim buffer is bounded by
quack_server_stream_buffer_bytes(default 256 MiB, capped at a quarter of the operator memory limit). The producer waits when it is full. - A
FETCH_REQUESTfor a batch that is not produced yet blocks until it is. - Served payloads stay retained until acknowledged through
ack_index, so a retried fetch is answered with identical bytes. - After a statement is aborted, a fetch for its
query_uuidreturns the abort error (for example, the cancel reason) instead of "Result has been closed".
DuckDB's own client keeps several fetches in flight (quack_fetch_read_ahead,
default: number of async threads) and reorders batches by index.
v3 removed APPEND_REQUEST. Writes are ordinary SQL statements that read
client data through the internal table function
scan_data_from_quack_client:
INSERT INTO "schema"."table"
SELECT * FROM scan_data_from_quack_client(
'<stream_id>',
NULL::STRUCT(col0 INTEGER, col1 VARCHAR),
ordered := true
)- The second argument is a typed
NULLprototype. ItsSTRUCTtype carries the column schema, so the statement can be planned before any data arrives. DuckDB's client renders it withLogicalType::ToString(). - The scan only works on a Quack server connection (it needs the session
state). It registers the stream while binding, which also releases the
waiting
PREPARE; hence the prepare must useinline_rows = 0. ordered := truemakes the scan consume batches in index order. Withfalse, it accepts batches in any order and lets DuckDB insert in parallel.- The stream id only needs to be unique within the connection; the connection
id is the secret that authorizes
SEND_DATA_REQUEST.
The client then sends numbered batches (batch_index from 1). The server
drops duplicate indices, so a retried batch is safe. A final chunk-less
SEND_DATA_REQUEST with total_batches = N closes the stream. If fewer
batches arrived, the statement fails instead of inserting a partial result.
The statement's own result (one Count row, or RETURNING rows) is then read
with an ordinary FETCH_REQUEST(batch_index = 1), so failures after the last
batch, such as constraint violations, surface there.
If a statement fails, the server also fails its client streams, and further
SEND_DATA_REQUESTs return the error. DuckDB's client sends a
CANCEL_REQUEST when an insert is abandoned; otherwise the statement waits for
data until the next statement supersedes it.
DuckDB's server deserializes chunks larger than 2048 rows, but its operators
assume at most STANDARD_VECTOR_SIZE (2048) rows per chunk. Clients should
split outgoing chunks accordingly.
Because every write is a single SQL statement, it is atomic, sees TEMP
tables and the connection's open transaction, matches columns by position
(SELECT *), and passes through the authorization callback like any query.
CANCEL_REQUEST aborts and joins the current statement's producer (errors its
buffer so parked producers wake up), interrupts the DuckDB connection, marks
the query cancelled, and clears the result cache. The interrupted request gets
ERROR_RESPONSE with the message Interrupted: query was cancelled; DuckDB's
client recognizes a cancel by the "Interrupt" text.
When the server enables quack_enable_reconnects, each client query's result
stream retains every served payload in a replay cache, bounded by
quack_cache_max_rows (default 100000; larger results drop the cache) and
expired after quack_result_ttl seconds idle (default 3600). The client sends
ACKNOWLEDGEMENT(query_uuid) after receiving the full result to release it.
Without reconnect support, ACKNOWLEDGEMENT is a no-op that still returns
SUCCESS_RESPONSE. The cache is per connection; client_id_hash is the stable
key intended for reconnect bookkeeping across connections.
The server returns ERROR_RESPONSE for:
- version mismatch and invalid heartbeat timeouts
- unsupported message types and undecodable messages
- invalid connection ids and expired leases
- authentication and authorization failures
- query errors from DuckDB, including binder and catalog errors
- closed or superseded results, missing batch indices
- unknown data streams and failed stream batches
- cancel or acknowledgement for a different
query_uuid
message is DuckDB's raw error message. Clients that want DuckDB's usual
display form can render "<exception_type> Error: <message>".
extra_info carries DuckDB's error metadata (for example name, type,
candidates, error_subtype for a missing table). The server filters out
keys that only make sense in the process that raised the error:
exception_type, exception_message, position, stack_trace, and
stack_trace_pointers. The receiving side filters them again.
Error types that would invalidate a DuckDB database (INTERNAL, fatal) are
downgraded by DuckDB's client to Invalid Input, with the message prefixed
"<type> Error on the Quack server:" and the original type kept in
extra_info.original_exception_type. This keeps a broken server from
poisoning the client's own database.
must_invalidate is set when the server's database has been invalidated.
The client should stop using the connection; the server has to be restarted.
An invalidated server answers every request with an error before touching the
database.
A client should decode the header first. If header.type == ERROR_RESPONSE,
decode the error body and throw before decoding the expected response type.
The default authentication model is token based.
On the client side, the caller supplies a token directly, or DuckDB looks up a
quack secret matching the target URI. The quack secret can also carry
EXTRA_HTTP_HEADERS (sent with every request, for example to authenticate at a
proxy) and an SSL_FINGERPRINT. The token is sent as auth_string in
CONNECTION_REQUEST.
On the server side, authentication calls the configured
quack_authentication_function (default quack_check_token, a timing-safe
comparison):
(connection_id, auth_string, server_token) -> BOOLEAN
A NULL, false, or failing result rejects the connection with
"Authentication failed" (or "Authentication callback failed: …"). The server
requires tokens of at least four characters. quack_serve can take the token
from a parameter, from a quack secret, or generate one (optionally persisting
it as a secret).
Each PREPARE_REQUEST is authorized through quack_authorization_function
(default quack_nop_authorization, which allows everything):
(connection_id, query_string) -> BOOLEAN | VARCHAR
NULL or false rejects the query. A VARCHAR result replaces the SQL that
is executed, which lets a callback rewrite queries. Since writes are
INSERT … scan_data_from_quack_client(…) statements, the callback sees the real
write statement; v1's dummy INSERT INTO schema.table VALUES (NULL)
authorization is gone.
Chunks appear in two forms:
-
In
PREPARE_RESPONSE.results(and in DuckDB's own catalog traffic) as avector<unique_ptr<DataChunkWrapper>>. Each element is a nullable pointer byte followed by aDataChunkWrapperobject with one field:Field id Name Type 300chunkDataChunkobjectFor normal result chunks the pointer byte is
1. -
In the chunk blob after
FETCH_RESPONSEandSEND_DATA_REQUESTbodies, as bareDataChunkobjects,chunk_countof them back to back.
DataChunkWrapper is marked as a workaround ("TODO: remove in 2.0") in the
extension source but is still used in v3.
A DataChunk is DuckDB's vectorized row batch. It stores columns, not row
objects.
| Field id | Name | Type | Notes |
|---|---|---|---|
100 |
rows |
sel_t / uint32 |
row count |
101 |
types |
list of LogicalType |
one per column, never empty |
102 |
columns |
list of Vector objects |
one per column |
flowchart TD
Chunk["DataChunk"] --> Rows["100 rows"]
Chunk --> Types["101 types[]"]
Chunk --> Cols["102 columns[]"]
Types --> T0["LogicalType column 0"]
Types --> T1["LogicalType column 1"]
Cols --> V0["Vector column 0"]
Cols --> V1["Vector column 1"]
V0 --> Valid0["validity mask"]
V0 --> Data0["physical data"]
Each vector is decoded using the corresponding logical type from the chunk's
type list and the chunk's row count. Deserialization allocates
max(rows, 2048) rows. The server never serializes an empty chunk into a
batch.
| Field id | Name | Type | Notes |
|---|---|---|---|
100 |
id |
LogicalTypeId |
required |
101 |
type_info |
nullable LogicalTypeInfo pointer |
omitted for parameterless types |
LogicalTypeId values in DuckDB 2.0:
| Type | Id | Physical type |
|---|---|---|
SQLNULL |
1 |
INT32 |
BOOLEAN |
10 |
BOOL |
TINYINT / SMALLINT / INTEGER / BIGINT |
11 / 12 / 13 / 14 |
INT8 / INT16 / INT32 / INT64 |
DATE |
15 |
INT32 |
TIME |
16 |
INT64 |
TIMESTAMP_SEC / TIMESTAMP_MS / TIMESTAMP / TIMESTAMP_NS |
17 / 18 / 19 / 20 |
INT64 |
DECIMAL |
21 |
INT16 / INT32 / INT64 / INT128 by width |
FLOAT / DOUBLE |
22 / 23 |
FLOAT / DOUBLE |
CHAR / VARCHAR / BLOB |
24 / 25 / 26 |
VARCHAR |
INTERVAL |
27 |
INTERVAL |
UTINYINT / USMALLINT / UINTEGER / UBIGINT |
28 / 29 / 30 / 31 |
unsigned ints |
TIMESTAMP_TZ |
32 |
INT64 |
TIMESTAMP_TZ_NS (new) |
33 |
INT64 |
TIME_TZ / TIME_NS |
34 / 35 |
INT64 |
BIT / BIGNUM |
36 / 39 |
VARCHAR |
UHUGEINT / HUGEINT |
49 / 50 |
UINT128 / INT128 |
UUID |
54 |
INT128 |
GEOMETRY |
60 |
VARCHAR (WKB) |
STRUCT / LIST / MAP |
100 / 101 / 102 |
STRUCT / LIST / LIST |
ENUM |
104 |
UINT8 / UINT16 / UINT32 by size |
LEGACY_AGGREGATE_STATE (renamed) |
105 |
read back as BLOB |
UNION |
107 |
STRUCT |
ARRAY |
108 |
ARRAY |
VARIANT |
109 |
STRUCT |
TUPLE (new) |
110 |
STRUCT |
The ids used only during binding (UNKNOWN, ANY, UNBOUND, TEMPLATE,
TYPE, STRING_LITERAL, INTEGER_LITERAL, POINTER, VALIDITY, TABLE,
LAMBDA) keep their v1 values.
TUPLEis an unnamed struct (all child names empty), for example the type of(1, 'a'). On storage versions older than 2.0 it is written as aSTRUCT, and an all-unnamedSTRUCTis read back as aTUPLE.VARIANTalways carries aSTRUCT_TYPE_INFOdescribing its internal layout:keys VARCHAR[],children STRUCT(keys_index UINTEGER, values_index UINTEGER)[],values STRUCT(type_id UTINYINT, byte_offset UINTEGER)[],data BLOB.LEGACY_AGGREGATE_STATEno longer serializes its function details and is deserialized asBLOB.
DuckDB 2.0 renamed ExtraTypeInfo to LogicalTypeInfo. The base fields are:
| Field id | Name | Type | Notes |
|---|---|---|---|
100 |
type |
LogicalTypeInfoType |
required |
101 |
alias |
string |
omitted if empty |
102 |
modifiers |
– | deleted; still skipped on read |
103 |
extension_info |
nullable ExtensionTypeInfo |
omitted if absent |
Derived fields:
| Info type | Id | Main fields |
|---|---|---|
GENERIC_TYPE_INFO |
1 |
none |
DECIMAL_TYPE_INFO |
2 |
200 width:uint8, 201 scale:uint8 |
STRING_TYPE_INFO |
3 |
200 collation:string |
LIST_TYPE_INFO |
4 |
200 child_type:LogicalType |
STRUCT_TYPE_INFO |
5 |
200 child_types: list<{0 name, 1 type}> |
ENUM_TYPE_INFO |
6 |
200 values_count:idx_t, 201 values:string[] |
UNBOUND_TYPE_INFO |
7 |
204 expr (a ParsedExpression); only pre-1.5 targets write 200 name, 201 catalog, 202 schema |
LEGACY_AGGREGATE_STATE_TYPE_INFO |
8 |
none written; old 200–202 skipped on read |
ARRAY_TYPE_INFO |
9 |
200 child_type:LogicalType, 201 size:uint32 |
ANY_TYPE_INFO |
10 |
200 target_type:LogicalType, 201 cast_score:idx_t |
INTEGER_LITERAL_TYPE_INFO |
11 |
200 constant_value:Value |
TEMPLATE_TYPE_INFO |
12 |
200 name:string |
GEO_TYPE_INFO |
13 |
200 crs: {100 definition:string} |
MAP uses LIST_TYPE_INFO whose child is a STRUCT(key, value).
The scan_data_from_quack_client prototype needs SQL type text. DuckDB's
LogicalType::ToString() renders:
- scalar names, with
TIMESTAMP_S,TIMESTAMP WITH TIME ZONE,TIMESTAMPTZ_NS,TIME WITH TIME ZONE, and"NULL"as special spellings DECIMAL(w,s),T[],T[n],MAP(K, V),ENUM('a', 'b')STRUCT("name" T, …)with SQL-quoted identifiers,TUPLE(T, …)GEOMETRYorGEOMETRY('<crs>')- the alias instead of the structure when a type has one (for example a user
ENUMtype name orJSON)
A vector object starts with optional field 90, vector_type:
| Vector type | Id | Meaning |
|---|---|---|
FLAT_VECTOR |
0 |
default; field 90 absent |
FSST_VECTOR |
1 |
not serialized on this path |
CONSTANT_VECTOR |
2 |
one value repeated |
DICTIONARY_VECTOR |
3 |
selection vector plus dictionary payload |
SEQUENCE_VECTOR |
4 |
arithmetic sequence |
SHREDDED_VECTOR (new) |
5 |
shredded VARIANT |
Compressed forms (constant, dictionary, sequence, shredded) are only written
with compressed_serialization, which DataChunk::Serialize enables by
default. Clients must decode them; they may always send flat vectors.
| Field id | Name | Type | Notes |
|---|---|---|---|
99 |
geometry_format |
GeometryStorageType |
GEOMETRY only; 1 = WKB (absent means legacy 0 = SPATIAL) |
100 |
has_validity_mask |
bool |
required |
101 |
validity |
data blob | only present if field 100 is true |
102 |
data |
varies | fixed-size data, GEOMETRY list |
103–109 |
– | varies | nested and string layouts, see below |
has_validity_mask is count > 0 && mask may contain nulls, so it can be true
even when every row is valid.
The validity mask is an array of little-endian uint64 entries,
ceil(rows / 64) * 8 bytes. Bit 1 means valid. Bit 0 means null.
Row i maps to:
entry_index = floor(i / 64)
bit_index = i % 64
valid = (entry[entry_index] & (1 << bit_index)) != 0
DuckDB initializes masks as all-valid, so the padding bits past the row count
are 1 (one null row serializes as fe ff ff ff ff ff ff ff).
For constant-size physical types, field 102 is a data blob of
rows * physical_width bytes in DuckDB's storage layout:
| Physical type | Width |
|---|---|
BOOL, INT8, UINT8 |
1 |
INT16, UINT16 |
2 |
INT32, UINT32, FLOAT |
4 |
INT64, UINT64, DOUBLE |
8 |
INT128, UINT128 |
16 (lower uint64, then upper) |
INTERVAL |
16 (months:int32, days:int32, micros:int64) |
Null rows still have placeholder bytes. The validity mask is authoritative.
UUID is stored as INT128 with the top bit of the upper word flipped.
DuckDB 2.0 serializes string-like vectors as two blobs:
| Field id | Name | Type | Notes |
|---|---|---|---|
107 |
byte_data_length |
optional_idx |
total byte length; its presence selects this layout |
108 |
length_data |
data blob | one uint32 length per row, 0 for nulls |
109 |
byte_data |
data blob | concatenated bytes of the non-null rows |
Row i is the next length_data[i] bytes of byte_data. Readers fall back to
the pre-2.0 layout when field 107 is absent: a list in field 102 with one
length-prefixed string per row (nulls included). The server still accepts that
layout in client data.
Geometry vectors keep the list layout: field 99 (geometry_format = 1,
WKB) and field 102 as a list with one WKB blob per row.
Struct-like vectors serialize their children in field 103, each child for
the same row count as the parent:
103 children: list<Vector>
VARIANT flat vectors are plain structs of its internal layout (see above).
| Field id | Name | Type |
|---|---|---|
104 |
list_size |
uint64 |
105 |
entries |
list of {100 offset:uint64, 101 length:uint64} |
106 |
child |
child Vector object |
One entry per parent row, referencing a slice of the child vector. Null rows
have {0, 0}.
| Field id | Name | Type |
|---|---|---|
103 |
array_size |
uint64 |
104 |
child |
child Vector object |
The child vector length is array_size * row_count.
Field 90 = CONSTANT_VECTOR, then one value encoded recursively as a flat
vector of size 1 in the same object. The decoder repeats it for the chunk's row
count.
| Field id | Name | Type |
|---|---|---|
90 |
vector_type |
DICTIONARY_VECTOR |
91 |
sel_vector |
data blob of uint32 indices, 4 * rows bytes |
92 |
dict_count |
idx_t |
Then the (trimmed) dictionary is serialized as a flat vector with dict_count
rows into the same object. DuckDB only uses this form when it halves the size.
| Field id | Name | Type |
|---|---|---|
90 |
vector_type |
SEQUENCE_VECTOR |
91 |
seq_start |
int64 |
92 |
seq_increment |
int64 |
No other fields follow. Row i is seq_start + i * seq_increment.
| Field id | Name | Type |
|---|---|---|
90 |
vector_type |
SHREDDED_VECTOR |
91 |
shredded_type |
LogicalType, a STRUCT(unshredded, shredded) |
92 |
shredded_data |
Vector object of shredded_type |
Only valid for VARIANT.
| Setting | Default | Scope | Effect |
|---|---|---|---|
quack_authentication_function |
quack_check_token |
global | connection callback |
quack_authorization_function |
quack_nop_authorization |
global | query callback |
quack_prepare_inline_rows |
24576 |
global | inline rows when inline_rows is unset |
quack_target_batch_bytes |
32 MiB | connection | serialized size per result/send batch |
quack_server_stream_buffer_bytes |
256 MiB | global | claim buffer bound (≤ memory limit / 4) |
quack_server_max_connections |
1024 |
global | concurrent HTTP connections |
quack_server_keep_alive_timeout |
300 s |
global | idle HTTP keep-alive |
quack_enable_reconnects |
false |
global | result replay cache |
quack_cache_max_rows |
100000 |
global | cache size limit (0 = unlimited) |
quack_result_ttl |
3600 s |
global | idle cache expiry (0 = never) |
quack_default_heartbeat_timeout |
60 s |
client | DuckDB client lease request |
quack_default_client_id |
random / $QUACK_CLIENT_ID |
client | DuckDB client client_id |
quack_fetch_read_ahead |
0 (async threads) |
client | DuckDB client fetch pipelining |
There are also quack_debug_* settings for fault injection (delays, dropped
and duplicated batches).
@quack-protocol/sdk 0.3 speaks Quack v3 only.
| Module | Responsibility |
|---|---|
src/binary.ts |
BinaryWriter / BinaryReader: objects, LEB128, hugeints, blobs, lists, nullable pointers |
src/messages.ts |
all 14 message types, header/body codecs, chunk blob framing, optional_idx handling |
src/vector.ts |
DataChunk and vector codecs, tagged value types, row materialization |
src/logical-types.ts |
LogicalType model, LogicalTypeInfo codecs (named ExtraTypeInfo in the SDK), physical type mapping, LogicalTypes helpers |
src/sql.ts |
client-side parameter formatting, quoteIdentifier(), logicalTypeToSql() |
src/client.ts |
QuackClient: transport, connect/heartbeat, statement queue, query/stream/append, cancel |
src/arrow.ts |
Flechette (Arrow) conversion in both directions |
src/builders.ts, src/values.ts, src/json.ts |
chunk builders with type inference, value constructors, JSON-safe output |
src/constants.ts, src/errors.ts |
protocol constants, error classes |
POST {baseUrl}/quackwithAcceptandContent-Type: application/vnd.duckdband any userheaders. Bodies are encoded withencodeMessage()and decoded withdecodeMessage(), which requires the whole body to be consumed.- Non-2xx responses throw
QuackProtocolError.ERROR_RESPONSEthrowsQuackServerError. signalandtimeoutMscombine into oneAbortSignalper request; the timeout covers reading the response body.
- Resolves
quack:and bare-host strings like DuckDB'sQuackUri: HTTP forlocalhost(any case),127.0.0.1, and::1, HTTPS for every other host. Thessloption overrides this either way;http://andhttps://URLs keep their scheme. - Sends
CONNECTION_REQUESTwith version range[3, 3],heartbeat_timeout_seconds(optionheartbeatTimeoutSeconds, default 60, validated to1..Number.MAX_SAFE_INTEGER), optionalclientId(≥ 4 characters), the token, and the platform (navigator.userAgentorquack-ts). - Requires
quack_version == 3in the response; otherwise it disconnects and throws. Adopts the server's heartbeat timeout. client.infoexposesserverDuckdbVersion,serverPlatform,quackVersion, andheartbeatTimeoutSeconds.
A setTimeout chain fires every timeout / 3 with ±20% jitter, like DuckDB's
client. It sends HEARTBEAT_REQUEST only if no request was sent in the last
half interval, since any request renews the lease. Failures are ignored and
retried on the next tick. The timer is unref()ed in Node so it never keeps a
process alive, and it stops on disconnect() or when the server reports
must_invalidate. heartbeat: false disables it, and client.heartbeat()
sends one manually.
Because the server supersedes a running statement on every PREPARE, the
client serializes statements per instance through a promise chain (the
"statement slot"). query(), first(), one(), values(), append*(), and
transaction() statements hold the slot from PREPARE until their last
response, so Promise.all([client.query(a), client.query(b)]) is safe.
Every statement gets a random, nonzero 128-bit query_uuid
(crypto.getRandomValues, with a Math.random fallback) and a generation
number.
query() sends PREPARE_REQUEST (with inlineRows when given), then, while
needs_more_fetch, FETCH_REQUEST(batch_index = n, ack_index = n - 1) for
n = 1, 2, … until a chunk-less response. Each data response must echo the
requested batch index, and the terminal total_batches must equal the number
of fetched batches; otherwise the client throws QuackProtocolError. Fetches
are sequential; there is no read-ahead.
stream(), streamRows(), and streamArrow() hold the statement slot only
for each request (the prepare, then each fetch), not while the caller
processes chunks. This avoids deadlocks when the consumer issues statements
inside its loop. If another statement started on the client in the meantime
(generation changed), the next fetch throws
QuackProtocolError("Stream was interrupted by another statement …").
Leaving a loop early (break, return, thrown error) sends a best-effort
CANCEL_REQUEST for the remaining result.
client.cancel()sendsCANCEL_REQUESTwith the active statement'squery_uuidon a separate request, outside the statement queue. The running request then rejects with the server'sQuackServerError(Interrupted: query was cancelled). It resolves tofalsewhen no statement runs. It does not abort the client-sidefetch.- When a statement's request is aborted (
signal) or times out (timeoutMs), or fails at the transport level, the client sends a best-effortCANCEL_REQUEST(5 s timeout) before releasing the statement slot, so the server stops the work too. Server errors on queries skip that cancel, because the statement already ended.
With acknowledgeResults: true, the client sends ACKNOWLEDGEMENT(query_uuid)
after each fully received query or stream result, ignoring failures. It is off
by default because it is only useful when the server enables
quack_enable_reconnects. The SDK does not implement reconnect replay itself.
append(table, chunk | chunks, schemaOrOptions), appendRows(), and
appendArrow() run one INSERT INTO <target> SELECT * FROM scan_data_from_quack_client('<random hex stream id>', NULL::STRUCT(col0 T0, …), ordered := true) statement:
- The target is
quoteIdentifier()-quotedcatalog.schema.table, from a string, a{ catalog?, schema?, table }reference, or theschemaoption. - Column types come from the first chunk; every chunk must have the same type
ids.
logicalTypeToSql()renders the prototype like DuckDB'sToString(), but always structurally (aliases are ignored,CHARrenders asVARCHAR, collations are dropped) so it does not depend on user types being visible. PREPARE_REQUESTwithinline_rows = 0.- Chunks are sliced to at most 2048 rows, grouped into
SEND_DATAbatches of up to 32768 rows, and sent sequentially withbatch_index = 1..N. Each must be answered bySEND_DATA_RESPONSE. - A terminal
SEND_DATA_REQUESTwithtotal_batches = N(0for an empty append). FETCH_REQUEST(batch_index = 1)reads theCountrow; the call resolves to that number.
Any failure, including server errors, sends a best-effort CANCEL_REQUEST,
because a failed insert can otherwise keep waiting for data. All chunks of one
call are atomic. appendRows()' batchSize only controls local chunk sizes;
appendArrow() converts each Arrow record batch into one chunk.
Outgoing chunks are always flat. String-like vectors use the 2.0 blob layout,
GEOMETRY the WKB list with geometry_format = 1, and validity masks are
all-valid padded like DuckDB's.
- All vector types except FSST and shredded
VARIANTare decoded; those throwQuackUnsupportedTypeError. String vectors accept both the 2.0 and the legacy layout. TUPLEvalues become arrays in member order,STRUCTvalues objects.TIMESTAMP_TZ_NSbecomes{ kind: "timestamp", unit: "nanos", timezone: "utc" }.VARIANTflat vectors are returned in their raw internal struct layout.- Aggregate-state type info fields are optional on read.
ExtensionTypeInfo,UNBOUND_TYPE_INFOwith an expression (field204, which is the only form v3 servers write), andINTEGER_LITERAL_TYPE_INFOwith a value are rejected withQuackUnsupportedTypeError. These only describe types during binding and do not appear in normal result schemas.
QuackServerError exposes serverMessage, exceptionType, extraInfo, and
mustInvalidate; its message is "<exceptionType> Error: <serverMessage>"
when a type is present. The SDK does not downgrade invalidating error types
(it has no database of its own to protect). After a must_invalidate error the
client marks itself unusable: isConnected becomes false, requests throw
QuackProtocolError, the heartbeat stops, and disconnect() skips the
network call.
Query results convert to Flechette tables with a quack:logicalType field
metadata entry, so they append back without explicit types. TIMESTAMP_TZ_NS
maps to a nanosecond UTC timestamp, TUPLE to a struct with fields "0",
"1", …, and GEOMETRY to binary tagged ARROW:extension:name = geoarrow.wkb, which Flechette 2.7's useGeoJSON option decodes into GeoJSON.
- Unit tests decode wire bytes captured from DuckDB v2.0.0
(
test/fixtures/quack-v3-wire.ts: connection, inline and deferred prepare, fetch data, terminal fetch, typed error, success) and re-encode the data messages byte for byte. - Integration tests start a real
quack_serve()server (DuckDB ≥ 2.0.0, extension from thecorerepository) and cover the lease and heartbeats, multi-batch fetches (by loweringquack_target_batch_byteswithSET), queueing, stream interruption and early exit, cancel and timeouts, typed errors, and atomic, multi-batch, transactional appends.
- Certificate pinning.
fetchcannot pin a certificate fingerprint, so a remote server with a self-signed certificate needs a trusted certificate (ssl_cert_file/ssl_key_file) or a TLS-terminating proxy. - Reconnects. The SDK can acknowledge results but does not replay cached results across reconnects.
- Parallelism. One statement at a time per client and no fetch read-ahead.
SEND_DATAbatches are sent sequentially withordered := true. - Unsupported encodings. FSST vectors, shredded
VARIANT, semanticVARIANTdecoding, extension type info. accept_budgetis ignored, as in DuckDB's client.
Quack still exposes DuckDB internal serialization directly. Areas to watch:
StorageVersiontargeted by the extension (V2_0_0here), which already changed the string vector layout onceLogicalTypeIdnumeric values andLogicalTypeInfoschemas- vector compression encodings (new
SHREDDED_VECTOR) DataChunkWrapper, marked for removal- geometry storage formats
- endianness assumptions for raw fixed-width data
- the internal
scan_data_from_quack_clientsignature, which clients now depend on for writes
The protocol version guards the message envelope, but most result-data compatibility is inherited from DuckDB's serializer and vector code.
Inline result chunks sit inside the PREPARE_RESPONSE body as wrapped
pointers, while fetched and sent chunks follow the body as bare objects. A
decoder needs both paths.
FETCH_REQUEST.batch_index and FETCH_RESPONSE.total_batches exclude the
batches already returned by PREPARE. Since PREPARE drains whole batches up
to inline_rows, the split point depends on server batching, so clients must
not assume a fixed number of inline rows.
exception_type values come from DuckDB's exception type names, which are
not consistently cased: for example Catalog and Invalid Input, but
INTERRUPT for cancelled queries.
There is no dedicated cancelled status. DuckDB's client recognizes a cancelled query by the "Interrupt" text in the error message.
The HTTP body is the frame. That is fine for HTTP, but carrying Quack over a streaming transport would need a length prefix or equivalent.
Leases are only checked when a request arrives. An expired connection keeps its server resources until the client's next request (or the server shuts down).
- DuckDB Quack overview: https://duckdb.org/docs/current/quack/overview
- Extension message schema:
duckdb-quack/src/include/quack_message.json
(local:
references/duckdb-quack/src/include/quack_message.json) - Message classes and protocol constants: duckdb-quack/src/include/quack_message.hpp
- Generated message serialization: duckdb-quack/src/serialize_quack_message.cpp
- Envelope, chunk blobs, and error mapping: duckdb-quack/src/quack_message.cpp
- Server dispatch, lease, fetch, and send-data handling: duckdb-quack/src/quack_server.cpp
- HTTP endpoint: duckdb-quack/src/quack_http_server.cpp
- Reference client, heartbeat, and TLS pinning: duckdb-quack/src/quack_client.cpp
- Insert path and client data streams: duckdb-quack/src/storage/quack_insert.cpp, duckdb-quack/src/quack_send_data.cpp, duckdb-quack/src/quack_scan_from_client.cpp
- DuckDB binary serializer: duckdb/src/include/duckdb/common/serializer/serializer.hpp
- DuckDB data chunk serialization: duckdb/src/common/types/data_chunk.cpp
- DuckDB vector serialization: duckdb/src/common/types/vector.cpp
- DuckDB logical type serialization: duckdb/src/common/types.cpp, duckdb/src/storage/serialization/serialize_types.cpp