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.
5
6 **Revised against 2.13.0**, with [M1](./m1-hsql-technical-plan.md),
7 [M2](./m2-hsql-technical-plan.md) and [M3](./m3-hsql-technical-plan.md) shipped and SSH
8 tunnels landed; the first draft was written against 2.9.0, when M2 was still a plan. Every
9 number below is re-measured on this checkout — Python 3.10.15, Linux, four adapters
10 installed — on a machine about a third slower than the one the first draft used, so read
11 the ratios rather than the absolutes. §10 lists what the revision changed, for a reader
12 who has the first draft in their head. PR 1 has shipped; §9 says what is in it.
13
14 **Bottom line up front.** The idea works, and the win is bigger than the quarter-second it
15 was proposed to recover — but only if one constraint is treated as the load-bearing one:
16 **the client must not import anything Harlequin owns.** The client built to that rule and
17 shipped in PR 1 answers `select 1` in **27ms against 348ms cold**, and 20 sequential
18 invocations in **0.55s against 7.5s**. A client that imported `click` and nothing else
19 would already be near 65ms, and one that imported `harlequin.config` near 90ms (§2) — so
20 the difference between a good version of this feature and a mediocre one is decided by the
21 first few lines of the console script, not by the protocol.
22
23 The other finding is that speed is the *smaller* half. A warm process is a **session**:
24 temp tables, `SET`, `search_path`, and open transactions survive between invocations. That
25 is a genuine feature for an agent — and it is also the reason this cannot be turned on by
26 default, cannot be auto-started in v1, and cannot be a silent fallback. §5 is the part of
27 this document I would argue about; §1–§2 are mostly arithmetic.
28
29 Recommended shape, in one line:
30
31 ```bash
32 hsql --serve prod ./warehouse.db # foreground, holds the connection
33 HSQL_SESSION=prod hsql -c "select 1" # 27ms, same bytes, same exit code
34 ```
35
36 ---
37
38 ## 1. Where the 350ms actually goes
39
40 `hsql -c "select 1"` against in-memory DuckDB, best of twenty runs of the real console
41 script:
42
43 | Invocation | Best | Median |
44 | --- | --- | --- |
45 | `hsql -c "select 1"` | 348ms | 362ms |
46 | `hsql -c "select 1" -a sqlite` | 323ms | 336ms |
47 | `hsql --help` | 130ms | 134ms |
48 | `harlequin --version` | 895ms | 917ms |
49
50 Instrumenting the same work phase by phase, cumulative from process spawn:
51
52 | Phase | Cumulative | Cost |
53 | --- | --- | --- |
54 | interpreter ready | 17ms | 17ms |
55 | `import click` | 53ms | 36ms |
56 | `harlequin.config` | 87ms | 34ms |
57 | `harlequin.plugins` | 93ms | 6ms |
58 | `load_adapter("duckdb")` | 163ms | 70ms |
59 | `harlequin.query` (pyarrow + `textual_fastdatatable.backend`) | 266ms | 103ms |
60 | `adapter()` + `connect()` | 279ms | 13ms |
61 | the rest: `harlequin.statements`, `harlequin.layout`, and the query | 329ms | 50ms |
62
63 That last row is mostly two more imports — tree-sitter for the splitter and wcwidth for
64 the layout. Measured in a process that has already paid for all of them, `connect()` is
65 10.8ms and **`execute()` + `fetch()` + layout together are 5.0ms.**
66
67 **So the database work is 5ms of a 350ms invocation.** Everything else is getting ready to
68 do it. M1 already took the cheap wins — lazy entry points, the lazy
69 `textual-fastdatatable` `__init__`, deferred `harlequin.query` — and what is left is
70 genuinely irreducible on the cold path:
71
72 - **pyarrow, 103ms with the backend.** `harlequin.query` normalizes every result set
73 through `create_backend()`, which is the whole reason both front ends agree about what a
74 row is. Removing it means a second normalizer, which the M1 plan rejected for good
75 reasons that have not changed.
76 - **The driver, 70ms for duckdb.** Not ours.
77 - **click, 36ms.** Ours to remove in principle, at the cost of hand-rolling the option
78 surface that adapters plug into. Not worth it.
79 - **CPython itself, 17ms.** The floor for any Python process on this machine.
80
81 So: even a version of `hsql` that imported *nothing* of Harlequin's beyond click and its
82 config would land near 200ms, and one that also dropped click near 165ms. **There is no
83 sequence of import fixes that reaches 50ms.** That is the honest case for a second
84 process, and it is worth stating in the plan because the alternative — "keep optimizing" —
85 has been the right answer up to now and stops being the right answer here.
86
87 ### 1.1 And `connect()` is 11ms only because DuckDB is a library
88
89 The table above understates the win, because the adapter it measures opens a file. The
90 in-tree number is `connect()` at 10.8ms for in-memory DuckDB, and a local file or SQLite
91 is the same order. Every adapter that speaks to a *server* — Postgres, MySQL, BigQuery, Trino,
92 Databricks, Snowflake — pays TCP setup, a TLS handshake, and an auth round trip on each
93 `connect()`, and for the OAuth-shaped ones a token exchange on top. Those are the
94 connections a human hands an agent, and they are the ones where holding the connection open
95 matters more than holding the imports.
96
97 This design should therefore not be sold on "350ms → 27ms against DuckDB." It should be
98 sold on **the invocation cost stops depending on how far away the database is**, with the
99 DuckDB number as the floor case rather than the typical one.
100
101 ## 2. What a warm session costs instead — measured, not projected
102
103 The first draft measured a throwaway prototype. These are the **shipped** client from PR 1
104 — the real `main()`, the real `harlequin.hsql.client`, the real frames — against a stub
105 server that speaks `protocol.py` and returns fixed bytes without touching a database, so
106 the number is the invocation's cost rather than a query's. Same machine, twenty runs:
107
108 | | Best | Median |
109 | --- | --- | --- |
110 | warm round trip, `select 1` | **26.6ms** | 27.6ms |
111 | cold `hsql -c "select 1"` | 348.2ms | 361.8ms |
112 | **20 sequential invocations, warm** | **547ms** | — |
113 | **20 sequential invocations, cold** | **7520ms** | — |
114
115 The warm client's 27ms decomposes almost entirely into things that are not the feature:
116
117 | | Cumulative | Modules |
118 | --- | --- | --- |
119 | CPython boot (`python -c pass`) | 16.8ms | 33 |
120 | `import harlequin.hsql` (the entry point) | 17.9ms | 36 |
121 | `import harlequin.hsql.session` (the decision) | 18.0ms | 37 |
122 | `import harlequin.hsql.client` (socket, struct, protocol) | 26.1ms | 58 |
123 | connect, send, receive, write, exit | ~1ms | — |
124
125 **The round trip is about a millisecond.** The client is ~95% interpreter start-up, which
126 means the protocol can afford to be careful — framing, a handshake, a version check, a
127 capability exchange — without moving the number. It also means the ceiling is 17ms unless
128 the client stops being Python, which §7 leaves as future work rather than pretending it is
129 free.
130
131 **25 modules over a bare interpreter is the whole of it**, and that is why §6's guard
132 counts modules rather than milliseconds: a count is the same on every machine, where a
133 wall clock on a shared CI runner is not. For scale, on the same interpreter `import click`
134 is 100 modules, `harlequin.config` 141 and `harlequin.hsql.diagnostics` 149.
135
136 ### 2.1 The constraint this puts on the entry point
137
138 `import click` costs 36ms and `import json` costs 9ms. Against a 27ms invocation those are
139 133% and 33%. So the rule is not "the client should be lean," it is:
140
141 > **`harlequin.hsql.main()` must decide whether this invocation belongs to a session, and
142 > hand off to a stdlib-only module, before it imports anything that is not stdlib.**
143
144 That is the single most important line-level decision in this document, and the first
145 draft under-scoped it. Three things were on the entry point's path, not one, and PR 1 took
146 all three off:
147
148 - **click, 36ms.** `main()` opened with `import click`. It now looks at `HSQL_SESSION` and
149 `--session` first — a `sys.argv` scan and an `os.environ` lookup, both free — and only
150 falls through to `build_cli()` when there is no session.
151 - **`harlequin.hsql.diagnostics`, 68ms.** The bigger one, and invisible until measured:
152 `harlequin/hsql/__init__.py` imported `ExitCode` from it at module scope, and that
153 module reaches `harlequin.redact` → `harlequin.config` → msgspec. Deferred into the cold
154 path, where it was already being imported anyway.
155 - **`typing`, 10ms.** `harlequin/__init__.py` imported it, and importing *any*
156 `harlequin.*` submodule executes that file. Every annotation there is a string under PEP
157 563, so the module now declares `TYPE_CHECKING = False` itself and imports nothing at
158 all. The four modules on the client's path do the same.
159
160 A consequence worth stating, because it looks like a violation of a rule this repo has:
161 **the client writes its own stderr rather than going through `diagnostics._write()`**,
162 which is otherwise "the one line every message leaves through". Nothing is lost. That
163 function exists to redact, and the client holds no secret to redact — it reads no profile,
164 loads no adapter, and never sees a connection string. The server's stderr arrives already
165 redacted and is copied through untouched.
166
167 It also gives the guard a shape CI can hold, exactly as the "no Textual in `hsql`" rule
168 does: **an import-linter contract saying the client's three modules reach nothing of
169 Harlequin's and nothing third-party**, plus a run-time test that counts modules against a
170 bare interpreter. One caveat the first draft missed: import-linter cannot express "this
171 package's `__init__` may not import click at module scope" — a contract's source module
172 matches its descendants — so *that* half is a run-time test only
173 (`test_deciding_whether_an_invocation_is_warm_does_not_import_click`). Without both, the
174 first contributor who needs a config value in the client re-adds 68ms and nobody
175 notices.
176
177 ## 3. Why a daemon, rather than the four cheaper things
178
179 ### 3.1 Not "keep optimizing imports"
180
181 §1 measured the floor at ~165–200ms. Rejected on arithmetic.
182
183 ### 3.2 Not a batch mode (`hsql --repl`, statements on stdin)
184
185 One process, many statements, no daemon, no socket, no security model. It is strictly
186 simpler and it is the right tool for a migration script.
187
188 It does not serve the caller this feature is for. An agent working through a Bash tool gets
189 **one command per turn** and cannot hold a pipe open across turns; a shell script that
190 wants to interleave `hsql` with `jq` and `git` cannot either. Batch mode solves "many
191 statements known up front." The daemon solves "many invocations, each decided after seeing
192 the last one's output" — which is what an agent loop is.
193
194 Worth noting they compose: `hsql --serve` is a batch mode whose batch arrives over a
195 socket.
196
197 ### 3.3 Not MCP instead — but this is the closest call
198
199 M6 in the product plan is `hsql mcp`: a long-lived process an agent talks to over stdio,
200 running on the same M1 execution core — still the last milestone, with M4 (handoff, in
201 three releases) and M5 (streaming) ahead of it. **It is already a warm session.** It holds a
202 connection, it pays the imports once, and it needs no socket, no file permissions, no
203 daemon lifecycle, and no uid check, because the agent harness owns the process and the pipe
204 is the security boundary. If the only persona were "an agent whose harness speaks MCP,"
205 this document should be closed and M6 pulled forward.
206
207 Two reasons it is not:
208
209 1. **Most agent harnesses give you Bash, not MCP** — and even the ones that speak MCP run
210 in contexts (CI, a container's entrypoint, a Makefile, a `postCreateCommand`) where the
211 available interface is a command line. The product plan's own P1 persona is defined as
212 "usually inside a coding agent's Bash tool."
213 2. **The audience is not only agents.** A human running twenty `hsql` calls in a shell loop
214 against Snowflake gets the same win, and MCP does nothing for them.
215
216 The right relationship is that **`hsql mcp` should be a client of this server, not a
217 parallel implementation of it.** Both are "a warm connection plus a request loop"; the only
218 difference is the transport and the serialization. If M6 grows its own connection lifecycle
219 the plan has two of them, which is the same mistake the plan already refuses to make with
220 the TUI and the CLI. That is an argument for building the session layer *first* and letting
221 MCP land on top — and it is the strongest argument in this document for doing this at all.
222
223 ### 3.4 Not a connection pool
224
225 A pool would let several clients run at once. It also destroys the thing that makes a
226 session useful — a temp table created on connection 3 is invisible to the next request that
227 lands on connection 1 — and it turns "which connection am I on" into a question the caller
228 has to think about. One session is one connection. §4.5 handles concurrency by serializing
229 rather than by multiplying connections, and §7 leaves read-only pools as future work.
230
231 ## 4. The design
232
233 ### 4.1 One command, two roles
234
235 `hsql --serve NAME [CONN_STR] [connection options]` runs the server **in the foreground**.
236 Not a `start`/`stop`/`status` subcommand family, and not a self-daemonizing fork:
237
238 - Foreground is what every supervisor already knows how to run — `&`, `systemd`, a
239 container entrypoint, `docker compose`, a `SessionStart` hook, `tmux`. Self-daemonizing
240 processes reimplement all of that badly, and orphaned ones holding a live warehouse
241 credential is exactly the failure this feature must not have.
242 - It keeps the mode-option shape M2 already settled on (`--catalog`, `--info`, `--spec`,
243 `--config MODE`) rather than introducing the subcommand ambiguity that shape exists to
244 avoid: `hsql` takes `CONN_STR` positionally, so `hsql server foo.db` would be ambiguous
245 in the same way `hsql catalog` was.
246 - `--serve` takes the session name as its value, so one flag carries both "be a server"
247 and "be *this* server."
248
249 #### Why `--serve` and `--session`, and not two nouns
250
251 The first draft of this document paired `--server NAME` with `--session NAME`, and that is
252 the wrong pair: in database vocabulary "server" and "session" are near-synonyms, and
253 neither word tells a reader which of the two processes it belongs to. The client half is
254 effectively pinned — `HSQL_SESSION` is the ambient spelling and nobody wants to write
255 `HSQL_SERVER` for a thing that is not one — so the question is only what the server's flag
256 is called, and the answer should be a **verb**:
257
258 > **`--serve` is a mode option; `--session` is not.** M2's grammar is that mode options say
259 > what an invocation *is* (`--catalog`, `--info`, `--spec`, `--config MODE`) and plain
260 > options modify a normal invocation. `hsql --session prod -c "select 1"` *is* an ordinary
261 > query invocation — it just runs somewhere warm — so `--session` is a plain option, and
262 > `--serve` joins the modes. The grammar already encodes the asymmetry the names need.
263
264 Considered and not taken:
265
266 | Spelling | Why not |
267 | --- | --- |
268 | **`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. |
269 | `--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). |
270 | `--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. |
271 | `--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** (`first_pass.attach_adapter_options`, under the spellings hsql reserves), so this would quietly take `--host` away from them. Every new flag in this design needs that check. Done, against duckdb, sqlite, postgres and mysql: none of `--serve`, `--session`, `--idle-timeout`, `--max-lifetime` or `--queue-timeout` collides with anything any of them declares. |
272 | `--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. |
273 | `--connect NAME` | Overloaded with the connection every other part of this CLI is about. |
274 | 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. |
275
276 One consequence of the rename, applied through the rest of this document: the daemon's own
277 knobs lose the `--server-` prefix they only carried to disambiguate — `--idle-timeout`,
278 `--max-lifetime`, `--queue-timeout` — since they appear only next to `--serve`. And the two
279 that are *client* operations are named for what the caller is addressing:
280 **`--session-status`** and **`--session-reset`**, both of which are things you ask a running
281 session, not things you configure a server with.
282
283 #### What `--serve` accepts, and what it refuses
284
285 **No, `--serve` does not accept `-c`** — and the reason generalizes into the rule that
286 defines the two roles. Every flag `hsql` has falls into exactly one of three groups, decided
287 by *when the question it answers can possibly be answered*:
288
289 | Group | Answered | Flags | `--serve` | client |
290 | --- | --- | --- | --- | --- |
291 | **connection-time** | once, when the server connects | `CONN_STR`, `-a`, `-P`, `--config-path`, `-r`/`--read-only`, every adapter option, and the five SSH options (`--ssh-host`, `--ssh-forward`, `--ssh-batch-mode`, `--ssh-allow-reuse`, `--ssh-timeout`) | **accepted** | accepted, but rejected if it differs from the server's (§4.4) |
292 | **per-request** | on every invocation | `-c`, `-f`, `-o`, `--format` and the shorthand flags, `-t`, `-A`, `-x`, `--no-header`, `--no-footer`, `--null-string`, `--limit`, `--display-rows`, `--result`, `--on-error`, `--stats`, `--color`, `--timeout`, and every mode: `--catalog`, `--catalog-search`, `--path`, `--config`, `--info`, `--spec`, `--skill` | **refused, exit 2** | accepted |
293 | **server-lifetime** | once, and only a server has one | `--idle-timeout`, `--max-lifetime`, `--queue-timeout` | **accepted** | refused, exit 2 |
294
295 The partition is exact and it is symmetric: **each side refuses the other's group.** That
296 turns §4.4's differing-connection-options rejection from a one-off into a special case of a
297 single rule, and it gives both refusals an error that names the right invocation rather than
298 just the wrong one — principle 7, applied to the feature's most likely first mistake:
299
300 ```
301 hsql: -c is a per-request option, and --serve takes none.
302 Start the session, then send it a query:
303 hsql --serve prod ./warehouse.db
304 hsql --session prod -c "select 1"
305 ```
306
307 **The one real argument for `-c` on `--serve` is an init script** — `SET search_path`,
308 `CREATE TEMP TABLE`, `INSTALL`/`LOAD` — run once at connect time, which is a genuinely
309 useful thing for a session to do. It is already served, by the better mechanism:
310 `--init-path` (`-i`) is an *adapter* option on both in-tree adapters, so it is
311 connection-time, group 1, and comes along for free. It is also the more correct of the two,
312 because it runs inside `connect()`, where the adapter decides what "init" means for its
313 database and where a failure is a *connection* failure rather than a request failure. A
314 `-c` on `--serve` would be a second, worse spelling of something that works today.
315
316 #### Adapter options are allowed on `--serve`, and should still be discouraged
317
318 They have to be accepted: the server is the only process that connects, so refusing them
319 would mean the only way to serve anything but a local file is a profile.
320
321 But `--serve` changes their risk profile, and the docs should say so. **A server's command
322 line is long-lived and visible in `ps`.** A password on a one-shot invocation is exposed for
323 350ms; the same password on an eight-hour session is exposed for eight hours, to every
324 process on the box. So:
325
326 - **`-P` is the spelling the docs should show.** A profile is already "how to connect to my
327 warehouse," and `hsql --serve prod -P prod` should be the normal form with the flag-soup
328 version as the exception.
329 - **Warn when a secret-typed option is passed literally to `--serve`**, detected through
330 the declarative `secret=` that shipped with #667 rather than a hand-written list of flag
331 names. A warning rather than a refusal in v1, because refusing needs env interpolation
332 (#898) to have shipped first so that there is a documented alternative for the container
333 case. Tightening it to a refusal once #898 lands is a reasonable later call, and a cheap
334 one.
335
336 #### The SSH options are connection-time, and a session is where they pay off
337
338 They landed after the first draft, and they fit the partition without an exception: a
339 tunnel is opened once, on the way to `connect()`, so `--ssh-host` and its four companions
340 are group 1. This is the case a warm session is *most* worth having — a tunnel costs an
341 ssh handshake on every cold invocation, and holding it open is the larger half of the win
342 §1.1 describes.
343
344 Two consequences the server has to carry rather than invent:
345
346 - **The tunnel is part of what the server holds open**, so §4.7's "the server is a
347 credential" reads on it too, and `--max-lifetime` bounds it.
348 - **`--ssh-allow-reuse` is already a `CLI_ONLY_SSH_KEYS` key** — a config file may not turn
349 off the check that the local port is not already someone else's listener, because config
350 files are discovered in the working directory. That reasoning does not weaken on a
351 server; it is the same flag, read the same way.
352
353 Clients opt in two ways, and the distinction matters:
354
355 | | Spelling | Missing server → |
356 | --- | --- | --- |
357 | **ambient** | `HSQL_SESSION=prod` in the environment | warn on stderr, run cold |
358 | **explicit** | `hsql --session prod -c "..."` | fail, exit 3 (connection) |
359
360 A name that could never name a session — one with a `/` or a space in it, which §4.4's
361 validation refuses — is the same shape of answer one step earlier: exit **2**, because a
362 bad name is a bad argument rather than a server that is down. Native Windows is the same
363 again: explicit exits 2 (it can never work here), ambient warns and runs cold.
364
365 An environment variable is a preference — the human or the harness set it once, and an
366 `hsql` call that still works when the server is down is the behavior that does not break a
367 script. A typed `--session` is an assertion, and silently running cold against an assertion
368 would mean silently losing the temp table the caller was counting on. Same reasoning as
369 `merge_profile_with_cli()`: **a value the caller actually typed carries intent that a
370 default does not.**
371
372 The fallback warning is not optional and not suppressible. "It got slow and
373 my temp tables vanished" must never be something the caller has to guess at.
374
375 ### 4.2 The client is stdlib-only, and forwards argv verbatim
376
377 ```
378 harlequin/hsql/
379 __init__.py main(): session check, then click or the client. Stdlib only.
380 session.py which session an invocation names, and where its socket is.
381 Stdlib only, and read before anything else.
382 client.py stdlib only: socket, struct, sys, os. No click, no json, no
383 harlequin beyond session.py and protocol.py.
384 protocol.py framing + the frame vocabulary, shared -- but written so that
385 client.py's half needs no imports the client cannot afford.
386 server.py accept loop, one worker, lifecycle, the uid check.
387 cli.py unchanged, plus --serve / --session
388 ```
389
390 The first three of those shipped in PR 1. `session.py` is separate from `client.py`
391 because the decision has to be cheaper than the client: a cold invocation reads it, finds
392 no session, and pays two modules and no socket for the question.
393
394 **The server parses the flags; the client does not.** The client scans `sys.argv` for the
395 three things it cannot avoid knowing about —
396
397 - `--session NAME` (strip it; it is the client's own flag),
398 - `-f -` / `--file -` (read stdin and send the bytes, because the server has no stdin),
399 - `--session-status` (send it as its own frame; §4.10 is answered by the session rather
400 than by the command, and it must be answerable while a request is running),
401 - nothing else —
402
403 and forwards the rest opaquely. Every other flag, including `--help`, including a
404 misspelling, is parsed by the server, by the same `build_cli()` the cold path uses, and
405 produces the same diagnostic. There is no second parser to keep in step, which is the
406 failure mode this design would otherwise be most likely to have. `hsql --session prod
407 --badflag` should print the same message and exit the same 2 as `hsql --badflag`, and it
408 will, because it *is* the same code.
409
410 The request carries what the server cannot know: **argv, the client's cwd, stdin bytes if
411 asked for, `NO_COLOR`, and whether the caller's stdout and stderr are terminals**
412 (the two halves of what `--color auto` reads: it checks `sys.stdout.isatty()` and
413 `NO_COLOR`, and on the server every stream is a buffer, so `auto` would otherwise mean
414 "never" however the caller's terminal looks). `TERM` is *not* carried — nothing in the
415 output path reads it. Deliberately *not* the
416 client's whole environment — the server has its own, an adapter option's `envvar` resolves
417 against the server's, and shipping the caller's environment across a socket is a credential
418 leak with no upside.
419
420 The cwd is doing more work there than it looks. **Config discovery is cwd-dependent** — home,
421 then the user config dir, then the cwd, later winning — so the server must resolve a
422 client's `-P` and `--config-path` against *the client's* directory, not its own. Otherwise
423 `hsql --session prod -P local` run in a project would silently read the server's
424 `pyproject.toml`, and a caller would get a profile they did not write. This costs nothing —
425 the cwd is already in the request for `-o` (§4.3) — but it has to be deliberate, because the
426 natural implementation resolves against the process that is running. A profile is then
427 subject to the same partition as typed flags: its connection-time keys go through §4.4's
428 comparison, its per-request keys apply normally, and `-P` needs no special case on either
429 side.
430
431 ### 4.3 What crosses the wire is bytes, not rows
432
433 The response is three things: **stdout bytes, stderr bytes, exit code.** The server runs
434 `harlequin.query` and `hsql.output` exactly as the cold path does, writing into a buffer
435 instead of `click.open_file("-", mode="wb")`, and the client copies that buffer to its own
436 stdout and exits with the code.
437
438 This is the decision that makes the feature safe. It means:
439
440 - **The client cannot format anything**, so it needs no pyarrow, no layouts, no `--format`
441 knowledge, and no ability to disagree with the cold path about a timestamp.
442 - **Byte-equivalence is testable** (§6). Every golden-format snapshot can be asserted
443 against both paths.
444 - **`--stats`, truncation notices, and the row-cap notice need no protocol support** —
445 they are already stderr bytes.
446
447 Two things need care:
448
449 - **Streaming.** The buffer means a 500-row default costs nothing, but `--limit -1` on a
450 large table materializes twice: once as Arrow on the server, once as bytes. That is the
451 same failure as #875 and it is not made worse here, but the frame format should be
452 **chunked from the start** (many `stdout` frames, then a terminating `exit` frame) so
453 that M5's streaming work has somewhere to land. Chunked framing is free now and
454 impossible to retrofit without a protocol version bump.
455 - **`-o PATH`.** The **server** writes it, resolving a relative path against the *client's*
456 cwd from the request. Not the client: `--format parquet` writes through duckdb, not
457 through our byte stream, and routing it back through the socket would both double the
458 memory and break `output.py`'s "one binary stream, `-o` included" invariant. This is
459 also the design's clearest statement that **client and server share a filesystem** —
460 which a `AF_UNIX` socket already implies.
461
462 ### 4.4 Named sessions, not hashed connection identity
463
464 The tempting design derives the socket path from a hash of the connection identity, so a
465 client automatically finds the right server. Rejected:
466
467 - The hash would have to include connection-affecting options and exclude presentation
468 ones (`--format`, `--limit`, `--color`), and that partition is not written down anywhere
469 today — it would become a new thing to keep in step with every adapter's options.
470 - Profiles resolve differently depending on cwd, so the same command in two directories
471 would hash differently, or the same hash would mean two databases.
472 - Hashing secrets to name a file is a bad habit even when the hash is sound.
473
474 Instead: **the name is the caller's, and the server owns the identity.** `hsql --serve
475 prod -P prod` connects however `-P prod` says to, and records what it resolved to. A client
476 that sends connection-affecting options gets one of two answers:
477
478 - identical to the server's → served;
479 - different → **rejected**, exit 2, naming the flag that differs and what the server has.
480
481 Not "reconnect with the new options" (that is a different session, and silently swapping
482 the database under a caller is the worst possible behavior), and not "ignore them"
483 (a client that typed `-a postgres` and got DuckDB has been lied to).
484
485 Socket path: `$XDG_RUNTIME_DIR/hsql/<name>.sock`, falling back to `$TMPDIR/hsql-<uid>/`
486 (or `/tmp/hsql-<uid>/`) when `XDG_RUNTIME_DIR` is unset — which is macOS, and also WSL2
487 without systemd, and also this container (§4.8). The fallback is the common path, not the
488 exotic one, and the directory is created 0700 and owned by the user either way. The name is
489 validated as `[A-Za-z0-9_-]{1,64}` so it cannot escape the directory.
490
491 **Not platformdirs**, which is what the rest of Harlequin uses for a user directory and
492 what the first draft named here. It costs ~22ms to import — about the whole of what a warm
493 invocation is supposed to cost — so the derivation is a dozen lines of `os.path` in
494 `session.py`, shared by both halves so they cannot disagree about where the socket is. It
495 is also the smaller question than it looks: `XDG_RUNTIME_DIR` is the only path platformdirs
496 would resolve differently on Linux, and the fallback branch is the one this design has to
497 get right anyway.
498
499 **A name that fits is not always a path that fits.** `sun_path` holds 104 bytes on
500 macOS (108 on Linux), the directory counts toward it, and the `TMPDIR` macOS supplies is
501 itself ~50 bytes — so a name well inside `[A-Za-z0-9_-]{1,64}` can still be one no socket
502 can be bound to. The client measures the assembled path and refuses with a message that
503 names the limit, rather than letting `connect()` fail with a bare errno.
504
505 **No `--session-socket PATH` in v1.** Letting a caller name the socket file directly is the
506 obvious escape hatch and the obvious way to end up with a socket on a mode-0777 shared
507 directory, or on a filesystem that cannot host one (§4.8). If it ever ships it has to
508 re-derive §4.7's guarantees for a path it did not choose — verify the directory's owner and
509 mode, and refuse anything that is not a real local filesystem — which is most of the reason
510 it is not in v1.
511
512 ### 4.5 One request at a time
513
514 Measured, on this checkout: **two threads calling `execute()` on one DuckDB connection
515 fail** —
516
517 ```
518 HarlequinQueryError('Invalid Input Error: Attempting to execute an
519 unsuccessful or closed pending query result')
520 ```
521
522 — and this is not a DuckDB quirk. The adapter contract says nothing about thread-safety,
523 and the TUI has never needed it: its database work runs in `@work(thread=True,
524 exclusive=True)` workers, which is to say *one at a time, and cancel the previous one*.
525 `hsql --serve` inherits that invariant rather than inventing a new one.
526
527 So: **a single worker thread, and a request queue.** A second client waits. Waiting is
528 bounded by `--queue-timeout` (default: the same value as the request's own `--timeout`,
529 which shipped in M2), and a client that times out in the queue exits 4 with a message that
530 says it never reached the database — which is a different fact from a query that ran too long, and the
531 caller needs to be able to tell them apart.
532
533 The accept loop stays responsive while a query runs, so `--session-status` and cancellation
534 (§4.6) are answerable mid-query. That is the whole reason the queue is in the server rather
535 than implicit in a single-threaded accept loop.
536
537 ### 4.6 Cancellation, and a real gotcha in the contract
538
539 `Ctrl-C` on a client must stop the query, not orphan it. The client catches `SIGINT`, opens
540 a **second** connection to the socket (the first is busy carrying the response), sends
541 `cancel` with its request id, and exits 130.
542
543 The server calls `connection.cancel()` when the adapter implements it. When it does not —
544 `cancel()` is an optional method, and `HarlequinAdapter.IMPLEMENTS_CANCEL` says whether it is real — the honest
545 behavior is to detach the client, exit 130, and **say on stderr that the query is still
546 running on the server**, because it is.
547
548 The gotcha, found while measuring: DuckDB's cursor reports an interrupt by returning `None`
549 from `fetchall()`, not by raising:
550
551 ```python
552 def fetchall(self) -> AutoBackendType | None:
553 try:
554 result = self.relation.to_arrow_table()
555 except duckdb.InterruptException:
556 return None
557 ```
558
559 In the TUI that is fine, because the user pressed the button and the app knows. **In server
560 mode a cancelled query and an empty result are the same bytes**, so the server must
561 attribute cancellation from its own bookkeeping — "I called `cancel()` on request 7, and
562 request 7 came back empty" — rather than from anything the adapter says. Worth writing down
563 because the alternative is a caller who sees `(0 rows)` and exit 0 for a query that was
564 killed.
565
566 **This is not a new mechanism, and PR 4 should not invent one.** `--timeout` shipped in M2
567 and has exactly this problem: `harlequin/hsql/timeout.py` cancels, then reads its own
568 deadline between results and attributes the empty result itself, and
569 `diagnostics.report_timeout()` is the line that says so. The server's bookkeeping is the
570 same shape, one level up — "I called `cancel()` on request 7" instead of "the deadline
571 passed" — and it should read like it.
572
573 (A cleaner long-term fix is a distinguished return or exception on the contract, which is
574 an adapter-ecosystem change of the same shape as M2's five additive members. Out of scope
575 here; noted in §7.)
576
577 ### 4.7 Security: the server is a credential, held open
578
579 This is the part that deserves the most conservatism, because a running server is **a live,
580 authenticated database connection that anything able to write its socket can use.** There
581 is no password on the wire and there does not need to be — the socket *is* the credential.
582
583 - **`AF_UNIX` only.** No TCP, not even on loopback, not behind a token. Loopback TCP is
584 reachable by every process and every container sharing the namespace, and a token file
585 is a second secret to leak.
586 - **The socket lives in a 0700 directory** owned by the user, and the socket itself is
587 created 0600 (bind, then `chmod`, or `umask` around the bind — file permissions on a UDS
588 are honored on Linux and macOS but not on every kernel, which is why the *directory* mode
589 is the real control).
590 - **The server refuses a request whose argv names `-f -` and carries no stdin
591 section.** The client's argv scan is a scan, not a parse, and its set of
592 boolean short flags is hsql's own — a boolean short an *adapter* declares is
593 not in it, so `-zf -` for such a `-z` would forward no stdin. One check on the
594 server turns every miss of that shape, including ones nobody has thought of,
595 into an exit 2 rather than a silently empty script. The server never reads its
596 own stdin.
597 - **Both halves `lstat` the directory before trusting it.** `XDG_RUNTIME_DIR` is
598 guaranteed by the system; the `TMPDIR` fallback is not, and on a shared host another
599 user can create `/tmp/hsql-<uid>/` first and put a listener at `prod.sock`. What a
600 client sends is argv, the cwd and piped stdin, and argv can carry a `CONN_STR` with a
601 password in it, so the client refuses a directory it does not own privately — and the
602 server does the same, since `os.mkdir(mode=0o700)` does nothing to a directory that
603 already exists.
604 - **`SO_PEERCRED` / `LOCAL_PEERCRED` uid check on accept.** Reject and log any peer whose
605 uid is not the server's. Belt and braces over the directory mode, and the thing that
606 makes a shared `/tmp` misconfiguration fail closed.
607 - **`--max-lifetime`** (default 8h) and **`--idle-timeout`** (default 30m,
608 `0` to disable). A credential held forever because someone opened a tmux tab in March is
609 the predictable bad outcome; these two make the default outcome "it goes away."
610 - **No secrets in `--session-status`.** It reports the adapter, the session name, the
611 redacted connection identity, uptime, request count, and current state — through
612 `harlequin.redact` and the declarative `secret=` that shipped with #667, not through a
613 hand-written allowlist.
614 - **An SSH tunnel is part of the credential.** A session opened with `--ssh-host` holds an
615 `ssh` process and a local listener for as long as it runs, and `--max-lifetime` is what
616 bounds that too.
617
618 ### 4.8 Windows — and WSL2, which is not the same question
619
620 `socket.AF_UNIX` is **not available in CPython on Windows**, through 3.14. The alternatives
621 are a named pipe with a hand-built DACL, or loopback TCP with a token — the first is real
622 work with a security model that has to be got right on a platform none of the maintainers
623 run daily, and the second is the thing §4.7 rejects.
624
625 **v1 is POSIX-only.** `hsql --serve` on native Windows exits 2 with a message saying so, and
626 `HSQL_SESSION` on native Windows warns once and runs cold — which is exactly the
627 ambient-fallback behavior §4.1 already specifies, so nothing special is needed on the client
628 side. A named pipe transport is a clean later addition behind the same `protocol.py`, and
629 pretending otherwise in v1 would mean shipping a weaker security model to every platform to
630 accommodate one.
631
632 **WSL2 gets the feature, because WSL2 is Linux.** It runs a real kernel in a VM, its Python
633 is a Linux CPython with `AF_UNIX` present, and a server and client both inside it need
634 nothing special — no branch, no fallback, no separate transport. That matters more than it
635 sounds: the Windows users most likely to want a warm session for an agent are already
636 working inside WSL, so "POSIX-only" costs much less than the phrase implies, and the docs
637 should say *native Windows* rather than *Windows* everywhere so nobody in WSL concludes the
638 feature is not for them.
639
640 Two WSL-specific notes, both of which §4.4's path derivation already handles:
641
642 - **Do not put the socket on a DrvFs/9p mount.** Binding a unix socket under `/mnt/c` does
643 not work. The socket lives in the runtime dir, so this is right by construction — but it
644 is one of the reasons §4.4 keeps `--session-socket PATH` out of v1.
645 - **`XDG_RUNTIME_DIR` is often unset under WSL2**, since systemd is opt-in there. That is
646 exactly the fallback branch §4.4 specifies (a 0700 `hsql-<uid>` directory under
647 `TMPDIR`), and it is not hypothetical — it is unset in the container these
648 measurements were taken in, too. The fallback is the common path, not the exotic one, and
649 should be tested as such.
650
651 What does **not** work, and cannot be made to: a native-Windows `hsql.exe` reaching a
652 session running inside WSL2. That is not a socket-routing problem to solve — they are two
653 different Python installations on two different filesystems, and the Windows one has no
654 `AF_UNIX` to offer regardless. Stay on one side of the boundary.
655
656 ### 4.9 Lifecycle, and the four ways this goes wrong
657
658 | Failure | Detection | Behavior |
659 | --- | --- | --- |
660 | **Stale socket** (server died, file remains) | `connect()` → `ECONNREFUSED` | client reports it and falls back or fails per §4.1; the **server** unlinks a stale file when it starts, because a running one also refuses between its `bind()` and its `listen()`, and on the BSDs whenever its backlog is full — a client that deleted the file on one refusal would take a live session away from every caller after it |
661 | **Version skew** (server 2.13, client 2.14) | server sends its version in the handshake; the client compares against a literal in `protocol.py` | refuse, exit 2, "restart the session" — never serve, because output bytes are the API and two versions may not agree on them |
662 | **Server busy shutting down** | server stops accepting before it closes the connection | client sees a clean refusal, not a truncated frame |
663 | **Client dies mid-query** | `EPIPE` on write | server finishes or cancels the request, drops the response, keeps running |
664
665 The version check is stricter than it needs to be on purpose. `hsql`'s output format is
666 documented as frozen, but "frozen" has always meant "across releases we intend"; a server
667 from a different release serving bytes a caller attributes to the installed version is a
668 category of bug nobody will diagnose quickly.
669
670 **A literal, and not `importlib.metadata.version("harlequin")`**, which costs ~43ms —
671 nearly twice the whole warm invocation. That makes it the second version `uv version`
672 cannot reach, beside the plugin manifest, so `scripts/bump_plugin_version.py` became
673 `scripts/bump_versions.py` and writes both; a test pins each to the installed version, so a
674 release that forgot fails in the release PR rather than in a user's shell.
675
676 ### 4.10 Observability
677
678 `hsql --session prod --session-status` returns JSON on stdout:
679
680 ```json
681 {"session":"prod","pid":8123,"version":"2.13.0","adapter":"duckdb",
682 "connection":"/home/ted/warehouse.db","connection_options":{"read_only":true},
683 "uptime_s":412,"requests":37,"state":"idle","queued":0,
684 "transaction_mode":null,"ssh":null,"idle_timeout_s":1800,"expires_in_s":1788.4}
685 ```
686
687 `connection_options` is the rest of §4.4's identity — what a request's own
688 connection options are compared against — masked by whatever each adapter declared
689 `secret=`. It holds what the session was *given*: an option it never named is one
690 its adapter defaulted for itself, which core cannot enumerate, so `read_only` appears
691 only for a session started with it. `state` is `idle`, `busy`, or `unavailable` for a
692 session whose connection a reset has to bring back. `idle_timeout_s` is the idle
693 clock as it was set, and `expires_in_s` the sooner of the two countdowns — with
694 the idle one left out while a request holds the connection, since a session in
695 the middle of a query is not idle for any length of time yet. Either is null
696 where the clock behind it is off.
697
698 Answerable while a query is running (§4.5), which is what makes "is it hung or is it slow"
699 a question with an answer. `transaction_mode` is on it because §5 says it has to be.
700
701 ## 5. The thing that isn't speed: a session is state
702
703 Everything above is mechanism. This section is the actual product decision.
704
705 A cold `hsql` invocation is **hermetic**: fresh process, fresh connection, no memory of the
706 last one. Every existing `hsql` behavior, doc sentence, and test assumes that. A warm
707 session is the opposite, and the difference is observable in ways a caller will not expect:
708
709 - **Temp tables persist.** `create temp table t as select ...` in one invocation is
710 queryable by the next. This is the single most useful thing about the feature, and it is
711 the one nobody will read the docs to discover.
712 - **Session settings persist.** `SET`, `search_path`, `SET TIME ZONE`, DuckDB `PRAGMA`s,
713 installed extensions. A `SET` in invocation 3 changes the results of invocation 12.
714 - **In-memory databases persist.** `hsql --serve scratch :memory:` is a scratch warehouse
715 that survives between calls — genuinely good, genuinely a semantic change.
716 - **Transactions persist, and this is the sharp edge.** A caller who runs `BEGIN` and then
717 exits has left an open transaction holding locks, and every subsequent request in that
718 session runs inside it. In a cold invocation the process exit rolled it back. Nothing
719 rolls it back now.
720
721 Three responses, and I would take all three:
722
723 1. **Never on by default, never auto-started, never a silent fallback.** All three are
724 already in §4.1. This is the reason for them: the feature changes semantics, so it must
725 be something a caller asked for.
726 2. **The server reports transaction state whenever it is not the default** — on stderr
727 after the request, and in `--session-status`. `HarlequinConnection.transaction_mode`
728 already exists on the contract, so this costs nothing and turns the worst failure mode
729 into a visible one. A session sitting in an open transaction is a thing the caller
730 should be told about every single time, not once.
731
732 **This premise does not hold, and PR 5 shipped the narrower thing instead.**
733 `transaction_mode` is the adapter's Auto/Manual *setting* — a plain attribute that
734 only `toggle_transaction_mode()` moves, which hsql never calls — so it says nothing
735 about whether a transaction is open, and a `begin` left open is silent. The worst
736 failure mode is therefore **not** visible, and `--session-reset` (item 3) is the only
737 thing in this design that answers it. Detecting an open transaction needs a new
738 member on the adapter contract, which is §7's "distinguished cancellation signal"
739 shape of change: additive, ecosystem-wide, and not this feature's to make. §9's PR 5
740 entry has what was shipped in its place.
741 3. **`hsql --session prod --session-reset`** rolls back, closes, and reconnects, without
742 restarting the process (so the imports are still warm). This is the escape hatch for
743 "the agent left the session in a weird state," and it is a much better answer than
744 asking someone to find and kill a pid.
745
746 What I would **not** do is reset between requests. It would make the server semantically
747 identical to the cold path, which sounds safe until you notice it also throws away the
748 half of the win that is `connect()` — and against a warehouse, that is the larger half.
749
750 ### 5.1 Documenting it as a session, not as a cache
751
752 The docs framing follows from this: **`hsql --serve` is not "hsql, but faster." It is "a
753 database session you can send commands to."** The speed is a consequence. A caller who
754 holds the second model in their head will predict the temp-table behavior correctly; a
755 caller who holds the first will file a bug.
756
757 ## 6. Testing: byte-equivalence, but only where it is true
758
759 The risk this feature carries is not that it fails, it is that it **drifts** — that in some
760 corner (a NULL, a `-t` footer, an error's exit code, a truncation notice) the warm path and
761 the cold path produce different bytes, and a caller who set `HSQL_SESSION` in their
762 environment months ago gets a different answer than the docs describe.
763
764 **Byte-equivalence is the guard for that, and it is a claim about one invocation, not about
765 a test.** Two invocations against a session are *supposed* to diverge from two cold ones —
766 that is §5, and it is the feature. A parametrization that ran the whole suite both ways and
767 demanded identical bytes would fail on every test that invokes `hsql` twice, and the
768 tempting fix — quietly exempting those — would put the divergences nobody has thought about
769 in the same bucket as the ones we designed. So the guard has to be stated with its scope on
770 it:
771
772 > **Equivalence holds per invocation, from a fresh session.** Given the same starting state,
773 > one `hsql` invocation produces the same bytes and the same exit code whether it ran cold
774 > or warm. Nothing is claimed about what the *next* invocation sees.
775
776 That precondition has to be manufactured, because the cold path gets it for free (a new
777 process every time) and the warm path does not. **Each test gets a fresh session** — one
778 server per xdist worker, `--session-reset` between tests — which is cheap, since a reset is
779 a reconnect and not a re-import. Pleasingly, it makes the test suite the primary consumer of
780 the escape hatch §5 proposes for humans, so the thing that rescues a wedged session is
781 exercised hundreds of times per run rather than never.
782
783 Three kinds of test, then, not one:
784
785 1. **Equivalence** — every single-invocation functional test, run twice, asserting identical
786 stdout bytes, identical stderr bytes, identical exit code. The golden-format snapshots
787 (`test_golden_formats.py`) come along for free, since they are single-file syrupy
788 snapshots written in binary and already assert on bytes. This is the drift guard, and it
789 is the suite that runs on every PR if only one can.
790 2. **Divergence, marked and asserted** — a multi-invocation test cannot be in group 1, and a
791 marker (`@pytest.mark.session_divergent`, registered in `[tool.pytest.ini_options]`
792 beside `online`, `use_cache` and `py12`) takes it out. The marker's cost is that it does
793 not merely opt out: **the test must assert what the warm behavior *is***, not just that it
794 differs. A temp table created by invocation 1 is `no such table` cold and a result set
795 warm, and both belong in the assertions. Otherwise the exemption list becomes the place
796 bugs live, which is exactly what the exemption exists to prevent.
797 3. **Session semantics** — tests that only exist on the warm path, because they are the
798 feature: state surviving between invocations, an open transaction being reported, a reset
799 clearing it, two clients queueing, a session refusing a client whose connection options
800 differ.
801
802 The marker earns its keep twice over, because **the set of tests carrying it is an
803 executable version of §5.** §5's list of what statefulness changes is prose today; the
804 marker turns it into an enumerated one that cannot silently grow. A contributor who
805 introduces a new divergence has to mark a test, and the marker is the review trigger that
806 asks whether §5 should have mentioned it.
807
808 Alongside those:
809
810 - **An import-linter contract**, next to the existing `hsql does not reach the TUI` one,
811 saying the client's three modules may not import `click` or anything of Harlequin's
812 outside themselves. Its other half is *not* expressible there — a contract's source
813 module matches its descendants, so "`harlequin.hsql.__init__` may not import click at
814 module scope" cannot be written — and is a run-time test instead. Both shipped in PR 1.
815 - **A cold-start benchmark for the client**, next to the existing one for `hsql`
816 (`scripts/cold_start.py`), plus a run-time test that counts the client's modules against
817 a bare interpreter — a count, not a wall clock, because the count is what a shared CI
818 runner can hold. Both shipped in PR 1.
819 - **Deterministic lifecycle tests**, not timing ones: stale socket, wrong uid (skipped
820 unless the test runner can drop privileges), version skew, a client killed mid-query, two
821 clients queued, a cancel that lands, a cancel against an adapter that cannot cancel.
822
823 One trap worth naming, since the suite runs under `-n auto`: **a session-scoped server
824 fixture is cross-test contamination waiting to happen.** A test that runs `SET` or leaves a
825 transaction open changes the result of an unrelated test that lands on the same worker
826 later, and it will present as a flake with no obvious cause. The per-test reset above is
827 what prevents it, and it is the reason the fixture must not be session-scoped for
828 convenience.
829
830 ## 7. What's cut, and why
831
832 - **Auto-start.** A client that spawns a server when it does not find one is the obvious
833 ergonomic win and the obvious way to end up with orphan processes holding warehouse
834 credentials that nobody remembers starting. It is also the feature that is *easy to add
835 later and impossible to remove*, once scripts depend on it. Ship explicit-only, watch how
836 people actually set sessions up, then decide. If it does land, it should be
837 `--session-autostart` and it should inherit the idle timeout, not the max lifetime.
838 - **Windows.** §4.8.
839 - **TCP, remote servers, containers-talking-to-hosts.** `AF_UNIX` and a shared filesystem
840 are assumptions of §4.3's `-o` handling as well as §4.7's security model. Removing them
841 is a different product.
842 - **Connection pooling / parallel requests.** §3.4. A read-only pool is a plausible later
843 addition, but only for `--read-only` sessions, where "which connection" is unobservable.
844 - **Multiple databases per server.** One session, one connection. Two databases is two
845 `--serve` processes, and they cost 200MB of RSS each at most, which is not the
846 constraint here.
847 - **A session for the TUI.** `harlequin --session prod` sounds appealing and is not: the
848 IDE holds its own connection for its whole run, so it has nothing to gain, and it would
849 put the TUI's evolving surface on the frozen protocol.
850 - **A distinguished cancellation signal on the adapter contract** (§4.6). Real, and an
851 ecosystem change; it belongs with M2's additive members, not here. The server's own
852 bookkeeping is a correct workaround in the meantime.
853 - **A compiled client.** 16ms of the 27ms is CPython boot, so a Rust or Go client would
854 land near 2ms. It also means platform wheels for a project that ships pure Python, and
855 it optimizes the half of the budget that is already smallest. Revisit only if someone is
856 running thousands of invocations.
857
858 ## 8. Risks
859
860 - **A second execution path is a second product.** The mitigation is structural, not
861 disciplinary: the server calls `build_cli()` and the same `query`/`output` code, and §6's
862 equivalence suite fails if the bytes diverge. If the server ever grows its own
863 formatting or its own flag handling, that is the signal the layering went wrong — the
864 same signal the product plan already names for MCP.
865 - **The credential-held-open surface.** §4.7 is the mitigation and it is not complete:
866 anything running as the same uid can use the session. That is the same trust boundary as
867 the user's `~/.ssh` and their Harlequin config, and it should be stated in the docs in
868 those terms rather than implied.
869 - **Statefulness surprising someone.** §5. The transaction reporting is the mitigation I'd
870 least want cut.
871 - **It overlaps M6.** §3.3 argues that is a reason to build this first and land MCP on top.
872 If M6 is imminent, the sequencing question is real and should be settled before PR 1 —
873 building both connection lifecycles would be the expensive mistake.
874 - **A lifetime expiry mid-query leaves that query unreachable.** The expiry path is the
875 stop signal's, which closes the listener and unlinks the socket *before* it drains: the
876 request in flight is still answered, but for the rest of its run no cancel and no
877 `--session-status` can reach it, because both open a second connection to a path that
878 is gone. Under `SIGINT` an operator is present and knows what they just did; under
879 `--max-lifetime` it happens by itself, at eight hours, to whoever is mid-query. Draining
880 before the unlink would need care around a client racing in on the still-live socket,
881 so PR 5 left the ordering alone — but the docs should say that a lifetime expiry mid-query
882 leaves the query uninterruptible until it finishes.
883 - **Idle servers as an operational nuisance.** Idle timeout defaults to 30m for this
884 reason. Expect the first bug report to be "my session died between calls"; the answer is
885 `--idle-timeout 0`, and the docs should say so before the report arrives.
886 - **Nobody uses it.** The honest risk. The feature is only reachable by someone who set it
887 up deliberately, which §5 says it must be. Mitigations are the docs framing, a
888 `SessionStart`-hook example, and the fallback warning — which is the one place a caller
889 who *should* be using a session will be told it exists.
890
891 ## 9. Shipping sequence
892
893 Six PRs, in dependency order. The first two are the ones with the interesting decisions in
894 them; everything after is additive and independently revertible.
895
896 1. **The entry-point split and the framing. Shipped.** `main()` decides whether an
897 invocation belongs to a session before it imports anything that is not stdlib;
898 `session.py` (the decision, and the socket path), `client.py` (stdlib only) and
899 `protocol.py` (chunked frames, handshake, version). No server yet — the client's only
900 reachable behavior is the fallback path, which is testable on its own, and the rest is
901 pinned against a stub server built on `protocol.py`. Ships the import-linter contract,
902 the run-time guards, and the client's steps in `scripts/cold_start.py`.
903
904 Two things moved out of it, both deliberately. **`--session` is not yet a click
905 option**: the client intercepts it before click, so it works, but a flag `--help` and
906 `--spec` advertise while no server can answer it would be worse than one they do not
907 mention yet. And declaring it raises a question PR 2 has to answer anyway — a click
908 parameter's name becomes a *profile* key, and `session` must not be one, because the
909 decision is made before any config file is read. That is a `CLI_ONLY_SSH_KEYS`-shaped
910 refusal, and it belongs with the flag. Until then no adapter reserves the spelling
911 either; none of the four checked declares it (§4.1).
912 2. **The server: accept loop, one worker, the queue, the uid check, socket lifecycle.**
913 `hsql --serve NAME`, the `--session` click option and its profile-key refusal,
914 `HSQL_SESSION`, and the §4.1 flag partition on both sides. Ships §6's equivalence suite
915 with it, not after it — this is the PR where equivalence is cheap to establish and
916 expensive to retrofit.
917 **`--session-reset` lands here too**, ahead of the rest of the lifecycle work: §6's
918 fixture needs it to give each test a fresh session, so it is a dependency of the suite
919 rather than a nicety, and the suite is the thing that proves it works.
920 3. **Identity and rejection. Shipped.** The server's recorded connection identity, the
921 differing-options rejection, client-side profile resolution against the client's cwd
922 (§4.2), `--session-status`. One question this PR settled that the first draft did not
923 ask: **whether `HARLEQUIN_CONFIG_PATH` travels with the request.** It does. It is the
924 caller's intent in the same way `--config-path` is, and a session that honored the flag
925 and ignored the variable would read a config file neither of them named — which is the
926 same failure §4.2 forwards the client's cwd to avoid. It widens
927 `protocol.FORWARDED_ENV_VARS` past "what `--color auto` needs", and the line that
928 replaces PR 1's is narrower than it looks: the two variables on it name *where a value
929 comes from* rather than being one, and neither is a credential.
930
931 Two things this PR settled that the plan did not name. **`--session-status` is not a
932 request**, because §4.5 promises it is answerable mid-query and a request cannot be:
933 a served invocation borrows the process's cwd, environment and streams for its whole
934 run, so a second one parsed alongside it would take them out from under a query. So
935 the client sends it as its own frame — a third thing its argv scan knows about — and
936 the server answers it off its own bookkeeping, which is the shape PR 4's cancel wants
937 anyway. It stays a declared click option so that `--help`, `--spec` and the partition
938 still describe it, and so a cold invocation is refused rather than ignored; and it
939 joins `CLI_ONLY_SESSION_KEYS`, because a profile could otherwise set it only for the
940 runs that never reach a session. The status's `transaction_mode` is **null while the
941 session is busy**: reading it means asking a driver a question on a second thread,
942 which is the thread-safety §4.5 refuses to assume. `idle_timeout_s` and `expires_in_s`
943 are null until PR 5 can answer them, rather than absent, so the document's shape does
944 not change under a caller.
945 4. **Cancellation. Shipped.** `SIGINT` → cancel frame → `connection.cancel()`, the
946 `IMPLEMENTS_CANCEL = False` path, and the DuckDB `fetchall() -> None` attribution.
947
948 Two things this PR settled that the plan did not name. **The request id is the
949 client's, not the server's**: a server-assigned one would have to reach the client
950 before its query started, and the only frame ahead of a request is the handshake,
951 whose shape has to stay readable by every release for the §4.9 version check to
952 work — so it is a sixth section of the request, eight bytes from `os.urandom()`.
953 And **a request is cancellable from the moment its argv arrives, not from the moment
954 it takes its turn.** A caller who gives up while their request waits behind the one
955 ahead is cancelling something the session is holding, and nothing else would stop it
956 running when its turn came.
957
958 That makes the load-bearing invariant one about *windows*, because
959 `HarlequinConnection.cancel()` is connection-wide: the window in which a request is
960 registered and marked started has to be exactly the window in which it holds the
961 turnstile. Widen it at either end and a cancel naming a request that has already
962 finished interrupts whichever query holds the connection now — and marks *that* one's
963 bookkeeping not at all, so the empty, error-free result the interrupt produces is one
964 nobody can attribute and the caller reads as an empty table. Two things keep the
965 windows equal: the server releases a request from its bookkeeping *before* it leaves
966 the turnstile, and `cancel()` holds the lock a request takes to start across the
967 driver call, so nothing can start between the check and the interrupt. The client's
968 half of the same rule is that the send and the relay are under one `try`, or an
969 interrupt landing between them exits 130 having sent no cancel at all.
970 5. **Lifecycle and state hygiene. Shipped.** `--idle-timeout`, `--max-lifetime`,
971 transaction-mode reporting, and the secret-on-a-server-command-line warning (§4.1).
972
973 Three things this PR settled that the plan did not name. **A status poll is not
974 use of a session**, so it does not touch the idle clock: an agent that watches a
975 session it has stopped sending queries to would otherwise keep the credential
976 open by watching it, which is the outcome the clock exists to prevent. The clock
977 is therefore *held* while a client is connected rather than *reset* when one
978 arrives — which is also what keeps a session from stopping under a client that
979 has connected and not yet said what it wants, since a `-f -` reads its script
980 after the handshake and nothing else can see such a client. (Review caught that:
981 the first cut counted parsed requests alone, and a slow producer upstream of
982 `-f -` got the socket unlinked under it.) **The
983 idle clock does not run while a request does**, and the lifetime clock does —
984 the first is about a session nobody wants and the second bounds the credential,
985 so a query that takes an hour is not idle and is not exempt either; a lifetime
986 that runs out mid-query stops the accept loop and lets the request in flight
987 finish, which is the path a stop signal already took, at the cost §8 now records.
988 And **the default a
989 transaction mode is compared against is the one the session connected in**,
990 re-read on every `--session-reset`, because the contract offers no way to ask an
991 adapter which of its modes is its default. Review then found the premise above it
992 does not hold either: the mode is a setting nothing hsql runs can move, so what
993 shipped reports a session moved **out of band** and makes no claim about open
994 work — §5 item 2 has the correction. A narrow feature honestly described, rather
995 than a safety net that is not there.
996 6. **Docs. Shipped.** `/docs/hsql/sessions` on harlequin.sh, written per §5.1, with the
997 `SessionStart`-hook example on it. Not optional and not last in spirit — a feature that
998 must be deliberately adopted is a feature that lives or dies by its docs.
999
1000 One thing this PR settled that the plan did not name: **the `hsql --help` mention was
1001 already there**, since the flags became click options in PR 2 and the epilog gained a
1002 Sessions block with them. What the docs owed instead was the two things `--help` cannot
1003 hold: what a session *remembers* (§5), and the three pages that were true only of a cold
1004 invocation — `psql.md`'s "no session variables" and "No Interactive Session", and the
1005 tutorial's every-invocation-connects framing.
1006
1007 M2 has shipped, and M3 with it. M4 is in flight in three releases and touches `cli.py`
1008 elsewhere (`--open`, the hooks, query history), so sequencing against it is a scheduling
1009 question rather than a technical one. The one real ordering constraint is still §3.3's:
1010 **settle the relationship with M6 first.**
1011
1012 ---
1013
1014 ## 10. What this revision changed
1015
1016 For a reader who has the first draft in their head. Nothing about the shape of the design
1017 moved; the changes are the arithmetic, the flags that shipped in between, and three things
1018 the first draft got wrong about the entry point.
1019
1020 - **Re-measured on 2.13.0** (§1, §2). The machine is slower than the first draft's, so the
1021 absolutes moved and the ratios did not: 348ms cold, 27ms warm, and the database work is
1022 5ms of the 348.
1023 - **§2 is the shipped client, not a prototype.** PR 1's numbers replace the throwaway's.
1024 - **The entry point had three imports on it, not one** (§2.1). click was the known one;
1025 `harlequin.hsql.diagnostics` (68ms, via `redact` → `config` → msgspec) and `typing`
1026 (10ms, via `harlequin/__init__.py`) were not. Together they were more than twice the
1027 invocation they sat on.
1028 - **One import-linter contract, not two** (§2.1, §6). The second is not expressible; it is
1029 a run-time test.
1030 - **The socket path is derived with stdlib, not platformdirs** (§4.4), which costs ~22ms.
1031 - **The version literal lives in `protocol.py`, and a release script writes it** (§4.9).
1032 - **M2's flags are no longer conditional** — `--read-only`, `--timeout`, the mode options
1033 and declarative `secret=` all shipped, and `--timeout`'s implementation in
1034 `hsql/timeout.py` is the precedent PR 4's cancellation attribution should follow (§4.6).
1035 - **The SSH options are in the partition** (§4.1), as connection-time, and the tunnel is
1036 part of what §4.7 calls a credential held open.
1037 - **`--session` waits for PR 2 to become a click option** (§9); PR 3 answered the
1038 `HARLEQUIN_CONFIG_PATH` question with "it travels."