Debian Codegraph @

docs/plans/hsql-warm-sessions-design.md

raw
1 # Warm sessions for `hsql` — a design for `hsql --serve`
2
3 A design for a long-lived `hsql` process that holds an open connection, so that repeated
4 invocations pay neither the import cost nor the connection cost again. Written against
5 2.9.0 (M1 shipped, M2 planned in [the M2 technical plan](./m2-hsql-technical-plan.md)),
6 and measured on this checkout: Python 3.11.15, Linux, four adapters installed.
7
8 **Bottom line up front.** The idea works, and the win is bigger than the 250ms it was
9 proposed to recover — but only if one constraint is treated as the load-bearing one:
10 **the client must not import anything Harlequin owns.** A prototype built to that rule
11 answers `select 1` in **20ms against 250ms cold**, and 20 sequential queries in **0.46s
12 against 5.4s**. A client that imports `click` and nothing else would already be at 55ms,
13 and one that imports `harlequin.config` at 70ms — so the difference between a good version
14 of this feature and a mediocre one is decided by the first three lines of the console
15 script, not by the protocol.
16
17 The other finding is that speed is the *smaller* half. A warm process is a **session**:
18 temp tables, `SET`, `search_path`, and open transactions survive between invocations. That
19 is a genuine feature for an agent — and it is also the reason this cannot be turned on by
20 default, cannot be auto-started in v1, and cannot be a silent fallback. §5 is the part of
21 this document I would argue about; §1–§2 are mostly arithmetic.
22
23 Recommended shape, in one line:
24
25 ```bash
26 hsql --serve prod ./warehouse.db # foreground, holds the connection
27 HSQL_SESSION=prod hsql -c "select 1" # 20ms, same bytes, same exit code
28 ```
29
30 ---
31
32 ## 1. Where the 250ms actually goes
33
34 `hsql -c "select 1"` against in-memory DuckDB, best of twelve runs of the real console
35 script:
36
37 | Invocation | Best | Median |
38 | --- | --- | --- |
39 | `hsql -c "select 1"` | 243ms | 250ms |
40 | `hsql -c "select 1" -a sqlite` | 225ms | 237ms |
41 | `hsql --help` | 91ms | 93ms |
42 | `harlequin --version` | 733ms | 755ms |
43
44 Instrumenting the same work phase by phase, cumulative from process spawn:
45
46 | Phase | Cumulative | Cost |
47 | --- | --- | --- |
48 | interpreter ready | 12ms | 12ms |
49 | `import click` | 39ms | 27ms |
50 | `harlequin.config` | 54ms | 15ms |
51 | `harlequin.plugins` | 72ms | 18ms |
52 | `load_adapter("duckdb")` | 115ms | 43ms |
53 | `harlequin.query` (pyarrow + `textual_fastdatatable.backend`) | 182ms | 67ms |
54 | `adapter()` | 182ms | 0ms |
55 | `connect()` | 193ms | 11ms |
56 | `execute()` + `fetch()` | 195ms | 2ms |
57 | layout | 196ms | 1ms |
58
59 **The database work is 2ms of a 250ms invocation.** Everything else is getting ready to do
60 it. M1 already took the cheap wins — lazy entry points, the lazy `textual-fastdatatable`
61 `__init__`, deferred `harlequin.query` — and what is left is genuinely irreducible on the
62 cold path:
63
64 - **pyarrow, 67ms with the backend.** `harlequin.query` normalizes every result set
65 through `create_backend()`, which is the whole reason both front ends agree about what a
66 row is. Removing it means a second normalizer, which the M1 plan rejected for good
67 reasons that have not changed.
68 - **The driver, 43ms for duckdb.** Not ours.
69 - **click, 27ms.** Ours to remove in principle, at the cost of hand-rolling the option
70 surface that adapters plug into. Not worth it.
71 - **CPython itself, 12ms.** The floor for any Python process on this machine.
72
73 So: even a version of `hsql` that imported *nothing* of Harlequin's beyond click and its
74 config would land near 150ms, and one that also dropped click near 120ms. **There is no
75 sequence of import fixes that reaches 50ms.** That is the honest case for a second
76 process, and it is worth stating in the plan because the alternative — "keep optimizing" —
77 has been the right answer up to now and stops being the right answer here.
78
79 ### 1.1 And `connect()` is 11ms only because DuckDB is a library
80
81 The table above understates the win, because the adapter it measures opens a file. The
82 in-tree numbers are `connect()` at 11ms for in-memory DuckDB, 14ms for a DuckDB file, 2.6ms
83 for SQLite. Every adapter that speaks to a *server* — Postgres, MySQL, BigQuery, Trino,
84 Databricks, Snowflake — pays TCP setup, a TLS handshake, and an auth round trip on each
85 `connect()`, and for the OAuth-shaped ones a token exchange on top. Those are the
86 connections a human hands an agent, and they are the ones where holding the connection open
87 matters more than holding the imports.
88
89 This design should therefore not be sold on "250ms → 20ms against DuckDB." It should be
90 sold on **the invocation cost stops depending on how far away the database is**, with the
91 DuckDB number as the floor case rather than the typical one.
92
93 ## 2. What a warm session costs instead — measured, not projected
94
95 I built a throwaway server (a `AF_UNIX` socket, one pre-connected DuckDB connection, the
96 real `harlequin.query` core and the real `hsql.output` writer) and a stdlib-only client
97 that sends SQL and writes back whatever bytes it gets. Same machine, same twenty runs:
98
99 | | Best | Median |
100 | --- | --- | --- |
101 | warm round trip, `select 1` | **20.0ms** | 21.4ms |
102 | warm round trip, 1000 rows | 22.0ms | 23.3ms |
103 | cold `hsql -c "select 1"` | 253.7ms | 263.2ms |
104 | **20 sequential queries, warm** | **459ms** | — |
105 | **20 sequential queries, cold** | **5386ms** | — |
106
107 The warm client's 20ms decomposes almost entirely into things that are not the feature:
108
109 | | Cost |
110 | --- | --- |
111 | CPython boot (`python -c pass`) | 12ms |
112 | `import socket` | +6ms |
113 | `import struct` | +1ms |
114 | connect, send, receive, write, exit | ~1ms |
115
116 **The round trip is about a millisecond.** The client is 95% interpreter start-up, which
117 means the protocol can afford to be careful — framing, a handshake, a version check, a
118 capability exchange — without moving the number. It also means the ceiling is 12ms unless
119 the client stops being Python, which §7 leaves as future work rather than pretending it is
120 free.
121
122 ### 2.1 The constraint this puts on the entry point
123
124 `import click` costs 27ms and `import json` costs 3.5ms. On a 20ms budget those are 135%
125 and 18% respectively. So the rule is not "the client should be lean," it is:
126
127 > **`harlequin.hsql.main()` must decide whether this invocation belongs to a session, and
128 > hand off to a stdlib-only module, before it imports click.**
129
130 Today `main()` opens with `import click`. The change is to look at `HSQL_SESSION` /
131 `--session` first — a `sys.argv` scan and an `os.environ` lookup, both free — and only fall
132 through to `build_cli()` when there is no session. That is a five-line change to
133 `__init__.py` and it is the single most important line-level decision in this document.
134
135 It also gives the guard a shape CI can hold, exactly as the "no Textual in `hsql`" rule
136 does: **an import-linter contract saying the client module's graph contains nothing from
137 `harlequin` and nothing from `click`**, plus a test that runs the client with
138 `-X importtime` and fails if the module count crosses a threshold. Otherwise the first
139 contributor who needs a config value in the client re-adds 15ms and nobody notices.
140
141 ## 3. Why a daemon, rather than the four cheaper things
142
143 ### 3.1 Not "keep optimizing imports"
144
145 §1 measured the floor at ~120–150ms. Rejected on arithmetic.
146
147 ### 3.2 Not a batch mode (`hsql --repl`, statements on stdin)
148
149 One process, many statements, no daemon, no socket, no security model. It is strictly
150 simpler and it is the right tool for a migration script.
151
152 It does not serve the caller this feature is for. An agent working through a Bash tool gets
153 **one command per turn** and cannot hold a pipe open across turns; a shell script that
154 wants to interleave `hsql` with `jq` and `git` cannot either. Batch mode solves "many
155 statements known up front." The daemon solves "many invocations, each decided after seeing
156 the last one's output" — which is what an agent loop is.
157
158 Worth noting they compose: `hsql --serve` is a batch mode whose batch arrives over a
159 socket.
160
161 ### 3.3 Not MCP instead — but this is the closest call
162
163 M6 in the product plan is `hsql mcp`: a long-lived process an agent talks to over stdio,
164 running on the same M1 execution core. **It is already a warm session.** It holds a
165 connection, it pays the imports once, and it needs no socket, no file permissions, no
166 daemon lifecycle, and no uid check, because the agent harness owns the process and the pipe
167 is the security boundary. If the only persona were "an agent whose harness speaks MCP,"
168 this document should be closed and M6 pulled forward.
169
170 Two reasons it is not:
171
172 1. **Most agent harnesses give you Bash, not MCP** — and even the ones that speak MCP run
173 in contexts (CI, a container's entrypoint, a Makefile, a `postCreateCommand`) where the
174 available interface is a command line. The product plan's own P1 persona is defined as
175 "usually inside a coding agent's Bash tool."
176 2. **The audience is not only agents.** A human running twenty `hsql` calls in a shell loop
177 against Snowflake gets the same win, and MCP does nothing for them.
178
179 The right relationship is that **`hsql mcp` should be a client of this server, not a
180 parallel implementation of it.** Both are "a warm connection plus a request loop"; the only
181 difference is the transport and the serialization. If M6 grows its own connection lifecycle
182 the plan has two of them, which is the same mistake the plan already refuses to make with
183 the TUI and the CLI. That is an argument for building the session layer *first* and letting
184 MCP land on top — and it is the strongest argument in this document for doing this at all.
185
186 ### 3.4 Not a connection pool
187
188 A pool would let several clients run at once. It also destroys the thing that makes a
189 session useful — a temp table created on connection 3 is invisible to the next request that
190 lands on connection 1 — and it turns "which connection am I on" into a question the caller
191 has to think about. One session is one connection. §4.5 handles concurrency by serializing
192 rather than by multiplying connections, and §7 leaves read-only pools as future work.
193
194 ## 4. The design
195
196 ### 4.1 One command, two roles
197
198 `hsql --serve NAME [CONN_STR] [connection options]` runs the server **in the foreground**.
199 Not a `start`/`stop`/`status` subcommand family, and not a self-daemonizing fork:
200
201 - Foreground is what every supervisor already knows how to run — `&`, `systemd`, a
202 container entrypoint, `docker compose`, a `SessionStart` hook, `tmux`. Self-daemonizing
203 processes reimplement all of that badly, and orphaned ones holding a live warehouse
204 credential is exactly the failure this feature must not have.
205 - It keeps the mode-option shape M2 already settled on (`--catalog`, `--info`, `--spec`,
206 `--config MODE`) rather than introducing the subcommand ambiguity that shape exists to
207 avoid: `hsql` takes `CONN_STR` positionally, so `hsql server foo.db` would be ambiguous
208 in the same way `hsql catalog` was.
209 - `--serve` takes the session name as its value, so one flag carries both "be a server"
210 and "be *this* server."
211
212 #### Why `--serve` and `--session`, and not two nouns
213
214 The first draft of this document paired `--server NAME` with `--session NAME`, and that is
215 the wrong pair: in database vocabulary "server" and "session" are near-synonyms, and
216 neither word tells a reader which of the two processes it belongs to. The client half is
217 effectively pinned — `HSQL_SESSION` is the ambient spelling and nobody wants to write
218 `HSQL_SERVER` for a thing that is not one — so the question is only what the server's flag
219 is called, and the answer should be a **verb**:
220
221 > **`--serve` is a mode option; `--session` is not.** M2's grammar is that mode options say
222 > what an invocation *is* (`--catalog`, `--info`, `--spec`, `--config MODE`) and plain
223 > options modify a normal invocation. `hsql --session prod -c "select 1"` *is* an ordinary
224 > query invocation — it just runs somewhere warm — so `--session` is a plain option, and
225 > `--serve` joins the modes. The grammar already encodes the asymmetry the names need.
226
227 Considered and not taken:
228
229 | Spelling | Why not |
230 | --- | --- |
231 | **`hsqld NAME CONN_STR`** + `hsql --session NAME` | The clearest of all, on forty years of `sshd`/`dockerd`, and it frees the daemon's own knobs from any prefix. Costs a third console script to package and document, and worse discoverability than `hsql` — which the product plan already lists as a risk. **The runner-up**; take it if the daemon's flag surface ever outgrows one command. |
232 | `--listen NAME` | Accurate about the mechanism, unambiguous about direction, but reads network-y: someone will look for the port. Wrong prior for a design that refuses TCP on purpose (§4.7). |
233 | `--daemon NAME` | Unambiguous and false. This process runs in the foreground; a `--daemon` flag that does not daemonize is a lie the user finds out about when they try to background it. |
234 | `--host-session NAME` | "Host a session" reads well, but `-h/--host` is a connection option on the postgres, mysql and trino adapters — and **hsql's own flags win collisions** (`_attach_adapter_options`), so this would quietly take `--host` away from them. Every new flag in this design needs that check; `--serve`, `--session`, `--idle-timeout` and `--max-lifetime` pass it against the in-tree adapters, and should be checked against the ecosystem before PR 1. |
235 | `--attach NAME` | tmux/docker vocabulary, and every agent knows it — but `ATTACH` is a DuckDB statement for attaching a database. Collides with the subject matter, in a tool whose subject matter is databases. |
236 | `--connect NAME` | Overloaded with the connection every other part of this CLI is about. |
237 | No server flag: infer the role from argument shape (a CONN_STR and no SQL means serve) | This is principle 7's "never make the agent guess," inverted. |
238
239 One consequence of the rename, applied through the rest of this document: the daemon's own
240 knobs lose the `--server-` prefix they only carried to disambiguate — `--idle-timeout`,
241 `--max-lifetime`, `--queue-timeout` — since they appear only next to `--serve`. And the two
242 that are *client* operations are named for what the caller is addressing:
243 **`--session-status`** and **`--session-reset`**, both of which are things you ask a running
244 session, not things you configure a server with.
245
246 #### What `--serve` accepts, and what it refuses
247
248 **No, `--serve` does not accept `-c`** — and the reason generalizes into the rule that
249 defines the two roles. Every flag `hsql` has falls into exactly one of three groups, decided
250 by *when the question it answers can possibly be answered*:
251
252 | Group | Answered | Flags | `--serve` | client |
253 | --- | --- | --- | --- | --- |
254 | **connection-time** | once, when the server connects | `CONN_STR`, `-a`, `-P`, `--config-path`, every adapter option, M2's `--read-only` | **accepted** | accepted, but rejected if it differs from the server's (§4.4) |
255 | **per-request** | on every invocation | `-c`, `-f`, `-o`, `--format` and the shorthand flags, `-t`, `-A`, `--no-header`, `--no-footer`, `--null-string`, `--limit`, `--display-rows`, `--result`, `--on-error`, `--stats`, `--color`, M2's mode options and `--timeout` | **refused, exit 2** | accepted |
256 | **server-lifetime** | once, and only a server has one | `--idle-timeout`, `--max-lifetime`, `--queue-timeout` | **accepted** | refused, exit 2 |
257
258 The partition is exact and it is symmetric: **each side refuses the other's group.** That
259 turns §4.4's differing-connection-options rejection from a one-off into a special case of a
260 single rule, and it gives both refusals an error that names the right invocation rather than
261 just the wrong one — principle 7, applied to the feature's most likely first mistake:
262
263 ```
264 hsql: -c is a per-request option, and --serve takes none.
265 Start the session, then send it a query:
266 hsql --serve prod ./warehouse.db
267 hsql --session prod -c "select 1"
268 ```
269
270 **The one real argument for `-c` on `--serve` is an init script** — `SET search_path`,
271 `CREATE TEMP TABLE`, `INSTALL`/`LOAD` — run once at connect time, which is a genuinely
272 useful thing for a session to do. It is already served, by the better mechanism:
273 `--init-path` (`-i`) is an *adapter* option on both in-tree adapters, so it is
274 connection-time, group 1, and comes along for free. It is also the more correct of the two,
275 because it runs inside `connect()`, where the adapter decides what "init" means for its
276 database and where a failure is a *connection* failure rather than a request failure. A
277 `-c` on `--serve` would be a second, worse spelling of something that works today.
278
279 #### Adapter options are allowed on `--serve`, and should still be discouraged
280
281 They have to be accepted: the server is the only process that connects, so refusing them
282 would mean the only way to serve anything but a local file is a profile.
283
284 But `--serve` changes their risk profile, and the docs should say so. **A server's command
285 line is long-lived and visible in `ps`.** A password on a one-shot invocation is exposed for
286 250ms; the same password on an eight-hour session is exposed for eight hours, to every
287 process on the box. So:
288
289 - **`-P` is the spelling the docs should show.** A profile is already "how to connect to my
290 warehouse," and `hsql --serve prod -P prod` should be the normal form with the flag-soup
291 version as the exception.
292 - **Warn when a secret-typed option is passed literally to `--serve`**, detected through
293 M2's declarative secret type (#667) rather than a hand-written list of flag names. A
294 warning rather than a refusal in v1, because refusing needs env interpolation (#898) to
295 have shipped first so that there is a documented alternative for the container case.
296 Tightening it to a refusal once #898 lands is a reasonable later call, and a cheap one.
297
298 Clients opt in two ways, and the distinction matters:
299
300 | | Spelling | Missing server → |
301 | --- | --- | --- |
302 | **ambient** | `HSQL_SESSION=prod` in the environment | warn on stderr, run cold |
303 | **explicit** | `hsql --session prod -c "..."` | fail, exit 3 (connection) |
304
305 An environment variable is a preference — the human or the harness set it once, and an
306 `hsql` call that still works when the server is down is the behavior that does not break a
307 script. A typed `--session` is an assertion, and silently running cold against an assertion
308 would mean silently losing the temp table the caller was counting on. Same reasoning as
309 `merge_profile_with_cli()`: **a value the caller actually typed carries intent that a
310 default does not.**
311
312 The fallback warning is not optional and not suppressible. "It got slow and
313 my temp tables vanished" must never be something the caller has to guess at.
314
315 ### 4.2 The client is stdlib-only, and forwards argv verbatim
316
317 ```
318 harlequin/hsql/
319 __init__.py main(): session check, then click or the client. No new imports.
320 client.py stdlib only: socket, struct, sys, os. No click, no json, no harlequin.
321 protocol.py framing + the frame vocabulary, shared -- but written so that
322 client.py's half needs no imports the client cannot afford.
323 server.py accept loop, one worker, lifecycle, the uid check.
324 session.py socket path derivation, stale-socket handling, the identity record.
325 cli.py unchanged, plus --serve / --session
326 ```
327
328 **The server parses the flags; the client does not.** The client scans `sys.argv` for the
329 three things it cannot avoid knowing about —
330
331 - `--session NAME` (strip it; it is the client's own flag),
332 - `-f -` / `--file -` (read stdin and send the bytes, because the server has no stdin),
333 - nothing else —
334
335 and forwards the rest opaquely. Every other flag, including `--help`, including a
336 misspelling, is parsed by the server, by the same `build_cli()` the cold path uses, and
337 produces the same diagnostic. There is no second parser to keep in step, which is the
338 failure mode this design would otherwise be most likely to have. `hsql --session prod
339 --badflag` should print the same message and exit the same 2 as `hsql --badflag`, and it
340 will, because it *is* the same code.
341
342 The request carries what the server cannot know: **argv, the client's cwd, stdin bytes if
343 asked for, and `TERM`/`NO_COLOR`** (which `--color auto` reads). Deliberately *not* the
344 client's whole environment — the server has its own, an adapter option's `envvar` resolves
345 against the server's, and shipping the caller's environment across a socket is a credential
346 leak with no upside.
347
348 The cwd is doing more work there than it looks. **Config discovery is cwd-dependent** — home,
349 then the user config dir, then the cwd, later winning — so the server must resolve a
350 client's `-P` and `--config-path` against *the client's* directory, not its own. Otherwise
351 `hsql --session prod -P local` run in a project would silently read the server's
352 `pyproject.toml`, and a caller would get a profile they did not write. This costs nothing —
353 the cwd is already in the request for `-o` (§4.3) — but it has to be deliberate, because the
354 natural implementation resolves against the process that is running. A profile is then
355 subject to the same partition as typed flags: its connection-time keys go through §4.4's
356 comparison, its per-request keys apply normally, and `-P` needs no special case on either
357 side.
358
359 ### 4.3 What crosses the wire is bytes, not rows
360
361 The response is three things: **stdout bytes, stderr bytes, exit code.** The server runs
362 `harlequin.query` and `hsql.output` exactly as the cold path does, writing into a buffer
363 instead of `click.open_file("-", mode="wb")`, and the client copies that buffer to its own
364 stdout and exits with the code.
365
366 This is the decision that makes the feature safe. It means:
367
368 - **The client cannot format anything**, so it needs no pyarrow, no layouts, no `--format`
369 knowledge, and no ability to disagree with the cold path about a timestamp.
370 - **Byte-equivalence is testable** (§6). Every golden-format snapshot can be asserted
371 against both paths.
372 - **`--stats`, truncation notices, and the row-cap notice need no protocol support** —
373 they are already stderr bytes.
374
375 Two things need care:
376
377 - **Streaming.** The buffer means a 500-row default costs nothing, but `--limit -1` on a
378 large table materializes twice: once as Arrow on the server, once as bytes. That is the
379 same failure as #875 and it is not made worse here, but the frame format should be
380 **chunked from the start** (many `stdout` frames, then a terminating `exit` frame) so
381 that M5's streaming work has somewhere to land. Chunked framing is free now and
382 impossible to retrofit without a protocol version bump.
383 - **`-o PATH`.** The **server** writes it, resolving a relative path against the *client's*
384 cwd from the request. Not the client: `--format parquet` writes through duckdb, not
385 through our byte stream, and routing it back through the socket would both double the
386 memory and break `output.py`'s "one binary stream, `-o` included" invariant. This is
387 also the design's clearest statement that **client and server share a filesystem** —
388 which a `AF_UNIX` socket already implies.
389
390 ### 4.4 Named sessions, not hashed connection identity
391
392 The tempting design derives the socket path from a hash of the connection identity, so a
393 client automatically finds the right server. Rejected:
394
395 - The hash would have to include connection-affecting options and exclude presentation
396 ones (`--format`, `--limit`, `--color`), and that partition is not written down anywhere
397 today — it would become a new thing to keep in step with every adapter's options.
398 - Profiles resolve differently depending on cwd, so the same command in two directories
399 would hash differently, or the same hash would mean two databases.
400 - Hashing secrets to name a file is a bad habit even when the hash is sound.
401
402 Instead: **the name is the caller's, and the server owns the identity.** `hsql --serve
403 prod -P prod` connects however `-P prod` says to, and records what it resolved to. A client
404 that sends connection-affecting options gets one of two answers:
405
406 - identical to the server's → served;
407 - different → **rejected**, exit 2, naming the flag that differs and what the server has.
408
409 Not "reconnect with the new options" (that is a different session, and silently swapping
410 the database under a caller is the worst possible behavior), and not "ignore them"
411 (a client that typed `-a postgres` and got DuckDB has been lied to).
412
413 Socket path: `$XDG_RUNTIME_DIR/hsql/<name>.sock`, falling back to a 0700 directory under
414 the platformdirs user runtime/cache dir when `XDG_RUNTIME_DIR` is unset — which is macOS,
415 and also WSL2 without systemd, and also this container (§4.8). The fallback is the common
416 path, not the exotic one. The name is validated as `[A-Za-z0-9_-]{1,64}` so it cannot escape
417 the directory.
418
419 **No `--session-socket PATH` in v1.** Letting a caller name the socket file directly is the
420 obvious escape hatch and the obvious way to end up with a socket on a mode-0777 shared
421 directory, or on a filesystem that cannot host one (§4.8). If it ever ships it has to
422 re-derive §4.7's guarantees for a path it did not choose — verify the directory's owner and
423 mode, and refuse anything that is not a real local filesystem — which is most of the reason
424 it is not in v1.
425
426 ### 4.5 One request at a time
427
428 Measured, on this checkout: **two threads calling `execute()` on one DuckDB connection
429 fail** —
430
431 ```
432 HarlequinQueryError('Invalid Input Error: Attempting to execute an
433 unsuccessful or closed pending query result')
434 ```
435
436 — and this is not a DuckDB quirk. The adapter contract says nothing about thread-safety,
437 and the TUI has never needed it: its database work runs in `@work(thread=True,
438 exclusive=True)` workers, which is to say *one at a time, and cancel the previous one*.
439 `hsql --serve` inherits that invariant rather than inventing a new one.
440
441 So: **a single worker thread, and a request queue.** A second client waits. Waiting is
442 bounded by `--queue-timeout` (default: the same value as `--timeout`, once M2 ships
443 it), and a client that times out in the queue exits 4 with a message that says it never
444 reached the database — which is a different fact from a query that ran too long, and the
445 caller needs to be able to tell them apart.
446
447 The accept loop stays responsive while a query runs, so `--session-status` and cancellation
448 (§4.6) are answerable mid-query. That is the whole reason the queue is in the server rather
449 than implicit in a single-threaded accept loop.
450
451 ### 4.6 Cancellation, and a real gotcha in the contract
452
453 `Ctrl-C` on a client must stop the query, not orphan it. The client catches `SIGINT`, opens
454 a **second** connection to the socket (the first is busy carrying the response), sends
455 `cancel` with its request id, and exits 130.
456
457 The server calls `connection.cancel()` when the adapter implements it. When it does not —
458 `cancel()` is an optional method, and `HarlequinAdapter.IMPLEMENTS_CANCEL` says whether it is real — the honest
459 behavior is to detach the client, exit 130, and **say on stderr that the query is still
460 running on the server**, because it is.
461
462 The gotcha, found while measuring: DuckDB's cursor reports an interrupt by returning `None`
463 from `fetchall()`, not by raising:
464
465 ```python
466 def fetchall(self) -> AutoBackendType | None:
467 try:
468 result = self.relation.to_arrow_table()
469 except duckdb.InterruptException:
470 return None
471 ```
472
473 In the TUI that is fine, because the user pressed the button and the app knows. **In server
474 mode a cancelled query and an empty result are the same bytes**, so the server must
475 attribute cancellation from its own bookkeeping — "I called `cancel()` on request 7, and
476 request 7 came back empty" — rather than from anything the adapter says. Worth writing down
477 because the alternative is a caller who sees `(0 rows)` and exit 0 for a query that was
478 killed.
479
480 (A cleaner long-term fix is a distinguished return or exception on the contract, which is
481 an adapter-ecosystem change of the same shape as M2's five additive members. Out of scope
482 here; noted in §7.)
483
484 ### 4.7 Security: the server is a credential, held open
485
486 This is the part that deserves the most conservatism, because a running server is **a live,
487 authenticated database connection that anything able to write its socket can use.** There
488 is no password on the wire and there does not need to be — the socket *is* the credential.
489
490 - **`AF_UNIX` only.** No TCP, not even on loopback, not behind a token. Loopback TCP is
491 reachable by every process and every container sharing the namespace, and a token file
492 is a second secret to leak.
493 - **The socket lives in a 0700 directory** owned by the user, and the socket itself is
494 created 0600 (bind, then `chmod`, or `umask` around the bind — file permissions on a UDS
495 are honored on Linux and macOS but not on every kernel, which is why the *directory* mode
496 is the real control).
497 - **`SO_PEERCRED` / `LOCAL_PEERCRED` uid check on accept.** Reject and log any peer whose
498 uid is not the server's. Belt and braces over the directory mode, and the thing that
499 makes a shared `/tmp` misconfiguration fail closed.
500 - **`--max-lifetime`** (default 8h) and **`--idle-timeout`** (default 30m,
501 `0` to disable). A credential held forever because someone opened a tmux tab in March is
502 the predictable bad outcome; these two make the default outcome "it goes away."
503 - **No secrets in `--session-status`.** It reports the adapter, the session name, the
504 redacted connection identity, uptime, request count, and current state — through M2's
505 declarative redaction (#667), not through a hand-written allowlist.
506
507 ### 4.8 Windows — and WSL2, which is not the same question
508
509 `socket.AF_UNIX` is **not available in CPython on Windows**, through 3.14. The alternatives
510 are a named pipe with a hand-built DACL, or loopback TCP with a token — the first is real
511 work with a security model that has to be got right on a platform none of the maintainers
512 run daily, and the second is the thing §4.7 rejects.
513
514 **v1 is POSIX-only.** `hsql --serve` on native Windows exits 2 with a message saying so, and
515 `HSQL_SESSION` on native Windows warns once and runs cold — which is exactly the
516 ambient-fallback behavior §4.1 already specifies, so nothing special is needed on the client
517 side. A named pipe transport is a clean later addition behind the same `protocol.py`, and
518 pretending otherwise in v1 would mean shipping a weaker security model to every platform to
519 accommodate one.
520
521 **WSL2 gets the feature, because WSL2 is Linux.** It runs a real kernel in a VM, its Python
522 is a Linux CPython with `AF_UNIX` present, and a server and client both inside it need
523 nothing special — no branch, no fallback, no separate transport. That matters more than it
524 sounds: the Windows users most likely to want a warm session for an agent are already
525 working inside WSL, so "POSIX-only" costs much less than the phrase implies, and the docs
526 should say *native Windows* rather than *Windows* everywhere so nobody in WSL concludes the
527 feature is not for them.
528
529 Two WSL-specific notes, both of which §4.4's path derivation already handles:
530
531 - **Do not put the socket on a DrvFs/9p mount.** Binding a unix socket under `/mnt/c` does
532 not work. The socket lives in the runtime dir, so this is right by construction — but it
533 is one of the reasons §4.4 keeps `--session-socket PATH` out of v1.
534 - **`XDG_RUNTIME_DIR` is often unset under WSL2**, since systemd is opt-in there. That is
535 exactly the fallback branch §4.4 specifies (a 0700 directory under the platformdirs
536 runtime dir), and it is not hypothetical — it is unset in the container these
537 measurements were taken in, too. The fallback is the common path, not the exotic one, and
538 should be tested as such.
539
540 What does **not** work, and cannot be made to: a native-Windows `hsql.exe` reaching a
541 session running inside WSL2. That is not a socket-routing problem to solve — they are two
542 different Python installations on two different filesystems, and the Windows one has no
543 `AF_UNIX` to offer regardless. Stay on one side of the boundary.
544
545 ### 4.9 Lifecycle, and the four ways this goes wrong
546
547 | Failure | Detection | Behavior |
548 | --- | --- | --- |
549 | **Stale socket** (server died, file remains) | `connect()` → `ECONNREFUSED` | client unlinks it, then falls back or fails per §4.1 |
550 | **Version skew** (server 2.9, client 2.10) | server sends its version in the handshake; the client compares against a literal in `client.py` | refuse, exit 2, "restart the session" — never serve, because output bytes are the API and two versions may not agree on them |
551 | **Server busy shutting down** | server stops accepting before it closes the connection | client sees a clean refusal, not a truncated frame |
552 | **Client dies mid-query** | `EPIPE` on write | server finishes or cancels the request, drops the response, keeps running |
553
554 The version check is stricter than it needs to be on purpose. `hsql`'s output format is
555 documented as frozen, but "frozen" has always meant "across releases we intend"; a server
556 from a different release serving bytes a caller attributes to the installed version is a
557 category of bug nobody will diagnose quickly.
558
559 ### 4.10 Observability
560
561 `hsql --session prod --session-status` returns JSON on stdout:
562
563 ```json
564 {"session":"prod","pid":8123,"version":"2.9.0","adapter":"duckdb",
565 "connection":"/home/ted/warehouse.db","uptime_s":412,"requests":37,
566 "state":"idle","queued":0,"transaction_mode":null,
567 "idle_timeout_s":1800,"expires_in_s":26988}
568 ```
569
570 Answerable while a query is running (§4.5), which is what makes "is it hung or is it slow"
571 a question with an answer. `transaction_mode` is on it because §5 says it has to be.
572
573 ## 5. The thing that isn't speed: a session is state
574
575 Everything above is mechanism. This section is the actual product decision.
576
577 A cold `hsql` invocation is **hermetic**: fresh process, fresh connection, no memory of the
578 last one. Every existing `hsql` behavior, doc sentence, and test assumes that. A warm
579 session is the opposite, and the difference is observable in ways a caller will not expect:
580
581 - **Temp tables persist.** `create temp table t as select ...` in one invocation is
582 queryable by the next. This is the single most useful thing about the feature, and it is
583 the one nobody will read the docs to discover.
584 - **Session settings persist.** `SET`, `search_path`, `SET TIME ZONE`, DuckDB `PRAGMA`s,
585 installed extensions. A `SET` in invocation 3 changes the results of invocation 12.
586 - **In-memory databases persist.** `hsql --serve scratch :memory:` is a scratch warehouse
587 that survives between calls — genuinely good, genuinely a semantic change.
588 - **Transactions persist, and this is the sharp edge.** A caller who runs `BEGIN` and then
589 exits has left an open transaction holding locks, and every subsequent request in that
590 session runs inside it. In a cold invocation the process exit rolled it back. Nothing
591 rolls it back now.
592
593 Three responses, and I would take all three:
594
595 1. **Never on by default, never auto-started, never a silent fallback.** All three are
596 already in §4.1. This is the reason for them: the feature changes semantics, so it must
597 be something a caller asked for.
598 2. **The server reports transaction state whenever it is not the default** — on stderr
599 after the request, and in `--session-status`. `HarlequinConnection.transaction_mode`
600 already exists on the contract, so this costs nothing and turns the worst failure mode
601 into a visible one. A session sitting in an open transaction is a thing the caller
602 should be told about every single time, not once.
603 3. **`hsql --session prod --session-reset`** rolls back, closes, and reconnects, without
604 restarting the process (so the imports are still warm). This is the escape hatch for
605 "the agent left the session in a weird state," and it is a much better answer than
606 asking someone to find and kill a pid.
607
608 What I would **not** do is reset between requests. It would make the server semantically
609 identical to the cold path, which sounds safe until you notice it also throws away the
610 half of the win that is `connect()` — and against a warehouse, that is the larger half.
611
612 ### 5.1 Documenting it as a session, not as a cache
613
614 The docs framing follows from this: **`hsql --serve` is not "hsql, but faster." It is "a
615 database session you can send commands to."** The speed is a consequence. A caller who
616 holds the second model in their head will predict the temp-table behavior correctly; a
617 caller who holds the first will file a bug.
618
619 ## 6. Testing: byte-equivalence, but only where it is true
620
621 The risk this feature carries is not that it fails, it is that it **drifts** — that in some
622 corner (a NULL, a `-t` footer, an error's exit code, a truncation notice) the warm path and
623 the cold path produce different bytes, and a caller who set `HSQL_SESSION` in their
624 environment months ago gets a different answer than the docs describe.
625
626 **Byte-equivalence is the guard for that, and it is a claim about one invocation, not about
627 a test.** Two invocations against a session are *supposed* to diverge from two cold ones —
628 that is §5, and it is the feature. A parametrization that ran the whole suite both ways and
629 demanded identical bytes would fail on every test that invokes `hsql` twice, and the
630 tempting fix — quietly exempting those — would put the divergences nobody has thought about
631 in the same bucket as the ones we designed. So the guard has to be stated with its scope on
632 it:
633
634 > **Equivalence holds per invocation, from a fresh session.** Given the same starting state,
635 > one `hsql` invocation produces the same bytes and the same exit code whether it ran cold
636 > or warm. Nothing is claimed about what the *next* invocation sees.
637
638 That precondition has to be manufactured, because the cold path gets it for free (a new
639 process every time) and the warm path does not. **Each test gets a fresh session** — one
640 server per xdist worker, `--session-reset` between tests — which is cheap, since a reset is
641 a reconnect and not a re-import. Pleasingly, it makes the test suite the primary consumer of
642 the escape hatch §5 proposes for humans, so the thing that rescues a wedged session is
643 exercised hundreds of times per run rather than never.
644
645 Three kinds of test, then, not one:
646
647 1. **Equivalence** — every single-invocation functional test, run twice, asserting identical
648 stdout bytes, identical stderr bytes, identical exit code. The golden-format snapshots
649 (`test_golden_formats.py`) come along for free, since they already assert on bytes. This
650 is the drift guard, and it is the suite that runs on every PR if only one can.
651 2. **Divergence, marked and asserted** — a multi-invocation test cannot be in group 1, and a
652 marker (`@pytest.mark.session_divergent`) takes it out. The marker's cost is that it does
653 not merely opt out: **the test must assert what the warm behavior *is***, not just that it
654 differs. A temp table created by invocation 1 is `no such table` cold and a result set
655 warm, and both belong in the assertions. Otherwise the exemption list becomes the place
656 bugs live, which is exactly what the exemption exists to prevent.
657 3. **Session semantics** — tests that only exist on the warm path, because they are the
658 feature: state surviving between invocations, an open transaction being reported, a reset
659 clearing it, two clients queueing, a session refusing a client whose connection options
660 differ.
661
662 The marker earns its keep twice over, because **the set of tests carrying it is an
663 executable version of §5.** §5's list of what statefulness changes is prose today; the
664 marker turns it into an enumerated one that cannot silently grow. A contributor who
665 introduces a new divergence has to mark a test, and the marker is the review trigger that
666 asks whether §5 should have mentioned it.
667
668 Alongside those:
669
670 - **Import-linter contracts**, next to the existing `hsql does not reach the TUI` one:
671 `hsql.client` may not import `harlequin.*` or `click`, and `harlequin.hsql.__init__` may
672 not import click at module scope.
673 - **A cold-start benchmark for the client**, next to the existing one for `hsql`, so the
674 20ms is a number CI defends rather than a number this document once measured.
675 - **Deterministic lifecycle tests**, not timing ones: stale socket, wrong uid (skipped
676 unless the test runner can drop privileges), version skew, a client killed mid-query, two
677 clients queued, a cancel that lands, a cancel against an adapter that cannot cancel.
678
679 One trap worth naming, since the suite runs under `-n auto`: **a session-scoped server
680 fixture is cross-test contamination waiting to happen.** A test that runs `SET` or leaves a
681 transaction open changes the result of an unrelated test that lands on the same worker
682 later, and it will present as a flake with no obvious cause. The per-test reset above is
683 what prevents it, and it is the reason the fixture must not be session-scoped for
684 convenience.
685
686 ## 7. What's cut, and why
687
688 - **Auto-start.** A client that spawns a server when it does not find one is the obvious
689 ergonomic win and the obvious way to end up with orphan processes holding warehouse
690 credentials that nobody remembers starting. It is also the feature that is *easy to add
691 later and impossible to remove*, once scripts depend on it. Ship explicit-only, watch how
692 people actually set sessions up, then decide. If it does land, it should be
693 `--session-autostart` and it should inherit the idle timeout, not the max lifetime.
694 - **Windows.** §4.8.
695 - **TCP, remote servers, containers-talking-to-hosts.** `AF_UNIX` and a shared filesystem
696 are assumptions of §4.3's `-o` handling as well as §4.7's security model. Removing them
697 is a different product.
698 - **Connection pooling / parallel requests.** §3.4. A read-only pool is a plausible later
699 addition, but only for `--read-only` sessions, where "which connection" is unobservable.
700 - **Multiple databases per server.** One session, one connection. Two databases is two
701 `--serve` processes, and they cost 200MB of RSS each at most, which is not the
702 constraint here.
703 - **A session for the TUI.** `harlequin --session prod` sounds appealing and is not: the
704 IDE holds its own connection for its whole run, so it has nothing to gain, and it would
705 put the TUI's evolving surface on the frozen protocol.
706 - **A distinguished cancellation signal on the adapter contract** (§4.6). Real, and an
707 ecosystem change; it belongs with M2's additive members, not here. The server's own
708 bookkeeping is a correct workaround in the meantime.
709 - **A compiled client.** 12ms of the 20ms is CPython boot, so a Rust or Go client would
710 land near 2ms. It also means platform wheels for a project that ships pure Python, and
711 it optimizes the half of the budget that is already smallest. Revisit only if someone is
712 running thousands of invocations.
713
714 ## 8. Risks
715
716 - **A second execution path is a second product.** The mitigation is structural, not
717 disciplinary: the server calls `build_cli()` and the same `query`/`output` code, and §6's
718 equivalence suite fails if the bytes diverge. If the server ever grows its own
719 formatting or its own flag handling, that is the signal the layering went wrong — the
720 same signal the product plan already names for MCP.
721 - **The credential-held-open surface.** §4.7 is the mitigation and it is not complete:
722 anything running as the same uid can use the session. That is the same trust boundary as
723 the user's `~/.ssh` and their Harlequin config, and it should be stated in the docs in
724 those terms rather than implied.
725 - **Statefulness surprising someone.** §5. The transaction reporting is the mitigation I'd
726 least want cut.
727 - **It overlaps M6.** §3.3 argues that is a reason to build this first and land MCP on top.
728 If M6 is imminent, the sequencing question is real and should be settled before PR 1 —
729 building both connection lifecycles would be the expensive mistake.
730 - **Idle servers as an operational nuisance.** Idle timeout defaults to 30m for this
731 reason. Expect the first bug report to be "my session died between calls"; the answer is
732 `--idle-timeout 0`, and the docs should say so before the report arrives.
733 - **Nobody uses it.** The honest risk. The feature is only reachable by someone who set it
734 up deliberately, which §5 says it must be. Mitigations are the docs framing, a
735 `SessionStart`-hook example, and the fallback warning — which is the one place a caller
736 who *should* be using a session will be told it exists.
737
738 ## 9. Shipping sequence
739
740 Six PRs, in dependency order. The first two are the ones with the interesting decisions in
741 them; everything after is additive and independently revertible.
742
743 1. **The entry-point split and the framing.** `main()` checks for a session before
744 importing click; `client.py` (stdlib only), `protocol.py` (chunked frames, handshake,
745 version). No server yet — the client's only reachable behavior is the fallback path,
746 which is testable on its own. Ships the two import-linter contracts and the client
747 benchmark.
748 2. **The server: accept loop, one worker, the queue, the uid check, socket lifecycle.**
749 `hsql --serve NAME`, `--session NAME`, `HSQL_SESSION`, and the §4.1 flag partition on
750 both sides. Ships §6's equivalence suite with it, not after it — this is the PR where
751 equivalence is cheap to establish and expensive to retrofit.
752 **`--session-reset` lands here too**, ahead of the rest of the lifecycle work: §6's
753 fixture needs it to give each test a fresh session, so it is a dependency of the suite
754 rather than a nicety, and the suite is the thing that proves it works.
755 3. **Identity and rejection.** The server's recorded connection identity, the
756 differing-options rejection, client-side profile resolution against the client's cwd
757 (§4.2), `--session-status`.
758 4. **Cancellation.** `SIGINT` → cancel frame → `connection.cancel()`, the
759 `IMPLEMENTS_CANCEL = False` path, and the DuckDB `fetchall() -> None` attribution.
760 5. **Lifecycle and state hygiene.** `--idle-timeout`, `--max-lifetime`, transaction-mode
761 reporting, and the secret-on-a-server-command-line warning (§4.1).
762 6. **Docs.** The "Headless & Agents" topic gains a session section written per §5.1, plus a
763 `SessionStart`-hook example and an `hsql --help` mention. Not optional and not last in
764 spirit — a feature that must be deliberately adopted is a feature that lives or dies by
765 its docs.
766
767 M2 does not block any of this, and this does not block M2 — the two touch `cli.py` in
768 different places. Sequencing between them is a scheduling question, not a technical one.
769 The one real ordering constraint is §3.3's: **settle the relationship with M6 first.**