Debian Codegraph @

docs/plans/m1-hsql-technical-plan.md

raw
1 # M1 Technical Plan — `hsql`, the headless CLI
2
3 Implementation plan for milestone M1 of [Harlequin for agents](./harlequin-for-agents.md).
4 That document is the product spec: what `hsql` is, why it's a separate command, and what
5 its contract with an agent looks like. This one is about how we build it, what has to be
6 refactored first, and in what order it can ship.
7
8 **M1's scope, from the roadmap:** second console script; extract the shared execution
9 core; import-linter rule and cold-start benchmark in CI; `-c`, `-f`, stdin, `-o`, `-F` +
10 shorthands, default `--limit 500`, truncation notices, `--stats`, exit codes,
11 `--on-error`, `--color`/`NO_COLOR`, plain errors; unknown-option hint on `harlequin`;
12 the seeded "Headless & Agents" docs topic. Closes
13 [#524](https://github.com/tconbeer/harlequin/issues/524).
14
15 **Bottom line up front.** A working prototype of the refactors below runs a
16 `select … union all select …` against DuckDB — interpreter startup, config discovery,
17 adapter load, connect, execute, fetch, normalize, render — in **220–242ms with Textual
18 never imported**, down from a 1335ms floor today. Nothing in M1 needs new normalization
19 or parsing code: the two hard pieces already exist in `textual-fastdatatable` and
20 `tree-sitter-sql`, and both can be reached without Textual.
21
22 ---
23
24 ## 1. Where the code actually is today
25
26 Everything below was measured on this repo at `2.8.0`, not estimated.
27
28 ### 1.1 There is no execution core to share
29
30 Query execution lives entirely inside the Textual app, as two threaded workers that
31 communicate by posting messages:
32
33 - `Harlequin._execute_query` (`src/harlequin/app.py:1077`) — loops over statements,
34 calls `connection.execute(q)`, applies `cur.set_limit(...)`, collects cursors, posts
35 `QueriesExecuted`.
36 - `Harlequin._fetch_data` (`src/harlequin/app.py:1154`) — drains each cursor with
37 `fetchall()` + `columns()`, times the batch, posts `ResultsFetched`.
38
39 There is no importable function. `hsql` cannot call any of this, and a naive copy is
40 exactly the "two products" failure §12 of the product plan warns about.
41
42 The split into *execute all, then fetch all* is deliberate and good — it's what lets the
43 TUI show "query executed" before results materialize. The extracted core should preserve
44 that shape rather than flatten it, so the TUI can adopt it without changing its
45 concurrency model.
46
47 `Harlequin._split_query_text` (`app.py:1135`) is a naive `text.split(";")`. **It is dead
48 code** — nothing calls it. The live splitter is `CodeEditor.selected_queries()`
49 (`components/code_editor.py:36`), which uses tree-sitter through textual-textarea. See
50 §3.2 — the grammar it uses is reachable without any of that.
51
52 ### 1.2 Cold start is 1.3 seconds, and the reasons are structural
53
54 ```
55 $ time harlequin --version
56 harlequin, version 2.8.0
57 real 0m1.335s
58 ```
59
60 That is the cheapest possible invocation of the current CLI. The 300ms target is not a
61 matter of shaving milliseconds; five separate things each pull in the whole TUI:
62
63 | # | Cause | Cost |
64 | --- | --- | --- |
65 | 1 | `harlequin/__init__.py` imports `harlequin.app` at module scope, so importing *any* `harlequin.*` submodule imports Textual, sqlfmt, prompt_toolkit and pyarrow | 660ms floor |
66 | 2 | `harlequin/adapter.py:7` imports `textual_fastdatatable.backend` for `AutoBackendType`, which is `Any` | 265ms |
67 | 3 | `textual_fastdatatable/__init__.py` imports the `DataTable` widget, so the backend can't be reached without Textual | 58ms + 158 modules of the 265ms above |
68 | 4 | `harlequin/options.py` imports `questionary`, `textual.validation`, `textual.widget` and `harlequin.copy_widgets` at module scope, for `to_questionary()` and `to_widgets()` | 187ms |
69 | 5 | `build_cli()` calls `load_adapter_plugins()`, which does `ep.load()` on **every installed adapter** to reach its `ADAPTER_OPTIONS` | 160ms for 4 adapters, unbounded |
70
71 Cause 2 recurs in the adapters themselves: `harlequin_duckdb/adapter.py:14` and
72 `harlequin_sqlite/adapter.py` both import `textual_fastdatatable.backend` at module
73 scope, so even a perfectly clean `hsql` would pay for Textual the moment it loaded an
74 adapter.
75
76 `harlequin/catalog.py:6` imports `textual.message.Message` for `NewCatalog` and
77 `NewCatalogItems` — two TUI-only messages sitting in a module every adapter imports.
78 Neither is used outside `app.py` and `components/data_catalog/database_tree.py`.
79
80 ### 1.3 `textual-fastdatatable` is ours, and its backend has no Textual in it
81
82 We control this package, which changes the answer to the hardest problem in M1 (§3.1).
83 Measured on the installed 0.16.0:
84
85 - `backend.py`, `format.py`, and `column.py` contain **zero references to Textual**. The
86 imports are pyarrow and rich.
87 - The only thing that pulls Textual is `textual_fastdatatable/__init__.py` importing
88 `data_table.DataTable`.
89 - With that `__init__` made lazy: `from textual_fastdatatable.backend import create_backend`
90 drops from 265ms/359 modules/Textual to **217ms/201 modules/no Textual**.
91 - Most of the remainder is `pyarrow.parquet`, imported at module scope but used only by
92 `ArrowBackend.from_parquet`. Deferring it into that classmethod takes the import to
93 **~140ms/183 modules**.
94 - `textual>=7.3.0` is a *required* dist dependency. Nothing in the backend uses it. A
95 future lean `hsql` install would need that made an extra.
96
97 ### 1.4 tree-sitter is already installed, and usable without Textual
98
99 `textual-textarea` requires `textual[syntax]`, which brings `tree-sitter` and
100 `tree-sitter-sql`. The editor's separator query is one line
101 (`code_editor.py:22`): `(";" @semicolon)`.
102
103 Driving that grammar directly, with no Textual and no textual-textarea, measures at
104 **28ms to import, 92 modules**, and 22ms to split a 2000-statement script. It gets
105 string literals, line comments, block comments, quoted identifiers and unicode right.
106 It gets `$$`-dollar-quoting wrong — and so does the TUI today, because it's the same
107 grammar and the same query.
108
109 Two further things fell out of driving it directly. Tree-sitter is used in exactly one
110 place in Harlequin — that one query — and nowhere else. And its `Point.column` is a
111 **byte** offset, which the editor feeds to a function expecting characters. See §3.2.
112
113 ### 1.5 Two places already write results to stdout that shouldn't
114
115 - `harlequin/plugins.py:54` — a bare `print()` when a plug-in fails to import. Under
116 `hsql -F csv > out.csv` that lands in the CSV.
117 - `harlequin/exception.py:68` `pretty_print_warning` — uses `rich.print`, i.e. stdout.
118 Reached from `locale_manager.py` and `windows_timezone.py`, both on the CLI path.
119
120 `pretty_print_error` already gets this right, with a comment saying why. The contract
121 exists in intent; M1 makes it true.
122
123 ### 1.6 Export is coupled to a widget
124
125 `harlequin/export.py:20` `copy()` takes a `ResultsTable` (a Textual widget) and reaches
126 into `table.backend.source_data`. The five exporters underneath it are pure
127 `pa.Table → file`. The column-deduplication step in between is data logic wearing a
128 widget's clothes.
129
130 ### 1.7 The prototype
131
132 I applied the §1.2 fixes plus the §1.3 upstream fixes and ran a script that does what
133 `hsql -c` will do — config discovery, single-adapter load, connect, execute with
134 `set_limit(limit + 1)`, `create_backend(data, max_rows=limit)`, write CSV to stdout:
135
136 ```
137 220ms 238ms 242ms textual=False 306 modules
138 ```
139
140 With `load_adapter_plugins()` left as-is (all four installed adapters imported) the same
141 script takes 377–398ms — which is cause 5 measured in situ, and the reason §3.4 is not
142 optional. `from harlequin import Harlequin` and `from textual_fastdatatable import DataTable`
143 both still work after the changes; those are load-bearing for third-party adapters and
144 for the TUI respectively. All patches were reverted.
145
146 ---
147
148 ## 2. The four obstacles, stated plainly
149
150 1. **No execution core exists.** It has to be extracted from the app before `hsql` can
151 have one, or we ship two implementations on day one.
152 2. **Every import path leads to Textual** — in this repo *and* one level upstream.
153 Fixable, cheap, measured; it must land first, because it's also the guard that keeps
154 the fix from silently regressing.
155 3. **Building the CLI requires importing every installed adapter.** The only unbounded
156 cost, and the only one that gets worse as the ecosystem grows.
157 4. **Text layout doesn't exist, and is coupled to a widget where it does.** The TUI
158 renders into a DataTable; `export.py` writes files but only from a `ResultsTable`.
159 Nothing arranges a result as `table`, `markdown` or `vertical` text.
160
161 Note what is *not* on this list, though earlier drafts of this plan had all three:
162 normalizing adapter output, parsing SQL into statements, and serializing values. Each
163 looked like a new subsystem and turned out to be an existing one we already own —
164 `create_backend`, `tree-sitter-sql`, and duckdb respectively. The residual work in M1 is
165 smaller than it first appears, and the parts that remain are the parts that are genuinely
166 ours: the CLI, the execution flow, and three text layouts.
167
168 ---
169
170 ## 3. Target architecture
171
172 Six new or reshaped libraries, plus one upstream change. Each owns a domain and has a
173 stated interface; none of them is a bag of helpers.
174
175 ```
176 textual-fastdatatable
177 __init__.py MOD lazy DataTable, so `backend` is reachable without Textual
178 backend.py MOD pyarrow.parquet deferred into from_parquet()
179
180 harlequin/
181 statements.py NEW locating statement boundaries in SQL text
182 query.py NEW execute SQL, get results, without a UI
183 layout.py NEW arranging already-serialized text for a reader
184 export.py MOD writing a result set to a file, serialized by duckdb/pyarrow
185 config.py MOD + merging CLI values over a profile
186 plugins.py MOD + naming and loading one adapter without importing the rest
187 options.py MOD renderer imports deferred; declaration stays import-light
188 hsql/ NEW the command
189 __init__.py main()
190 cli.py the click command and its two-phase adapter resolution
191 diagnostics.py everything written to stderr, and the code we exit with
192 ```
193
194 The one-line statement of the architecture, which is also a testable rule:
195
196 > **stdout is written only by `harlequin.layout` and `harlequin.export`. stderr is
197 > written only by `harlequin.hsql.diagnostics`.**
198
199 ### 3.1 `harlequin.query` — the execution core, over the existing backend
200
201 ```python
202 @dataclass(frozen=True)
203 class Statement:
204 sql: str
205 index: int # 0-based position in the submitted script
206
207
208 @dataclass(frozen=True)
209 class RowLimit:
210 max_rows: int | None # None = unlimited
211 detect_overflow: bool # fetch one extra row so truncation is knowable
212
213
214 @dataclass
215 class ExecutedStatement:
216 statement: Statement
217 cursor: HarlequinCursor | None # None for DDL/DML
218
219
220 @dataclass
221 class ResultSet:
222 statement: Statement
223 columns: list[tuple[str, str]] # (name, short type) from cursor.columns()
224 backend: DataTableBackend # from textual_fastdatatable
225 truncated: bool
226 elapsed: float
227
228 @property
229 def row_count(self) -> int: ... # backend.row_count
230 def rows(self) -> Iterator[Sequence[Any]]: ...
231 def text_columns(self) -> pa.Table: ... # every value CAST AS VARCHAR; see §3.3
232
233
234 def execute(
235 connection: HarlequinConnection,
236 statements: Sequence[Statement],
237 limit: RowLimit,
238 on_error: Literal["stop", "continue"] = "stop",
239 ) -> Iterator[ExecutedStatement]: ...
240 def fetch(executed: ExecutedStatement, limit: RowLimit) -> ResultSet: ...
241 ```
242
243 **`ResultSet` wraps a `DataTableBackend` rather than reimplementing one.**
244 `HarlequinCursor.fetchall()` returns `AutoBackendType`, which is `Any` — in practice a
245 `pa.Table` (duckdb), a `RecordBatch`, a `Sequence[Iterable]` (sqlite), a
246 `Mapping[str, Sequence]`, or a polars or pandas frame. `create_backend()` already
247 normalizes all of those, it is the normalization the TUI uses, and per §1.3 it needs no
248 Textual to run. Writing a second normalizer for `hsql` would put the most drift-prone
249 code in the codebase — "what counts as a row, what counts as null, how does a nested
250 struct come out" — in two places, and the disagreement would surface as `hsql` and the
251 TUI showing different data for the same query. That is the worst possible place for
252 these two front doors to diverge.
253
254 > **Superseded, after M1 shipped.** The collision described below was resolved by
255 > [#1026](https://github.com/tconbeer/harlequin/issues/1026): the display cap has its own
256 > key, `viewer_max_rows`, `limit` is the hard fetch limit in both commands, and the text
257 > layouts grew a soft cap of their own (`--display-rows`). `harlequin --limit` now fills
258 > in the Run Query Bar's limit and checks it, so the TUI does detect overflow — the
259 > premise below, that it always fetched every row, stopped holding the moment a user
260 > checked that box, and no longer holds at start-up either. See `AGENTS.md` for the
261 > current vocabulary. The rest of this section is the reasoning as it stood.
262
263 **Harlequin already has two different limits, and `hsql` wants the other one.** This is
264 worth spelling out, because the names collide and I had it wrong in an earlier draft:
265
266 | | What it does | Where |
267 | --- | --- | --- |
268 | **Soft, display** — `harlequin --limit`, `max_results`, default 100,000 | Fetches *everything*, caps what's loaded into the viewer | `results_viewer.py:147`, `create_backend(max_rows=…)` |
269 | **Hard, fetch** — the Run Query Bar's limit checkbox | `cur.set_limit(n)`, so fewer rows leave the database | `app.py:1093` |
270
271 The soft limit is why the TUI needs no overflow detection and never did: because it
272 fetched every row, it knows the exact total and already says so —
273 `"(Showing 100,000 of 3,412,887 Records)"` at `results_viewer.py:234`. That's strictly
274 better than anything an inference could give it. My earlier suggestion that it show
275 "100,000+" was wrong.
276
277 **`hsql -l` is the hard limit.** Fetching a million rows to print five hundred would
278 defeat the entire point of a limit for an agent — time, memory, and egress. There is also
279 no viewport headless, so the soft limit has no meaning: `hsql` has exactly one limit
280 concept, and it's the fetch-side one. Same flag name, different semantics between the two
281 commands; the docs need one sentence about that rather than a pretense that they match.
282
283 **Which is why truncation needs `limit + 1`.** `set_limit(n)` then `fetchall()` returns at
284 most n rows and tells you nothing about whether an n+1th existed; exactly n is ambiguous.
285 So `execute()` requests `limit + 1` and `fetch()` calls `create_backend(data, max_rows=limit)`.
286 `DataTableBackend` already distinguishes `row_count` (capped) from `source_row_count`
287 (what it was handed), so `truncated = source_row_count > row_count` — the mechanism
288 exists, we just feed it one extra row. This is why the limit is a value object with an
289 explicit `detect_overflow` rather than an `int` each caller interprets: principle 5 of the
290 product plan ("truncation must always be announced — never silent") is unimplementable
291 without it, and it costs exactly one row.
292
293 The asymmetry is real and defensible: the TUI can afford to know the exact total because
294 it already paid for every row; `hsql` deliberately hasn't, so it reports `500 of >500`.
295 Under `-l 0` there's no `set_limit` at all, so the count is exact and `--stats` reports
296 `"truncated": false` against a real number.
297
298 **No adapter-interface change for limits in M1.** The clean long-term answer is for the
299 cursor to say whether more rows exist — a `has_more()`, or a `set_limit()` that reports
300 back — instead of us inferring it from an extra row. That's a fifteen-adapter rollout for
301 a problem the existing API already solves, so it waits. `set_limit()` and the backend's
302 `max_rows` are both existing features, used as they are; the only thing `hsql` does
303 differently is pass `limit + 1`. If a later milestone adds a real capability, `RowLimit`
304 is the single place that changes.
305
306 **Upstream first.** The two `textual-fastdatatable` changes in §3 are a prerequisite, and
307 both are non-breaking: the lazy `__init__` keeps `from textual_fastdatatable import DataTable`
308 working via PEP 562 `__getattr__`, and deferring `pyarrow.parquet` is invisible to
309 callers. Making `textual` an optional extra is a bigger change — it would let a future
310 lean `hsql` install skip Textual entirely, but it's a dependency break for existing
311 users and buys M1 nothing, since `harlequin` needs Textual regardless. Deferred.
312
313 The TUI's two workers become thin wrappers: `_execute_query` calls `execute()`,
314 `_fetch_data` calls `fetch()`, both still post the same messages, and the DataTable gets
315 the same backend object it builds today.
316
317 ### 3.2 `harlequin.statements` — one grammar, one query, two slicers
318
319 Driving tree-sitter directly (§1.4) is better than every alternative I costed: 28ms
320 against sqlfmt's 85ms, no new SQL scanner to maintain, and — the part that matters —
321 **it is the same grammar and the same query the TUI already uses**, so `hsql -f script.sql`
322 and the editor cannot disagree about where a statement ends.
323
324 ```python
325 def find_separators(
326 text: str,
327 ) -> list[Point]: ... # (row, character column) past each ";"
328 def split(text: str) -> list[Statement]: ... # separators -> trimmed statements
329 ```
330
331 **`tree-sitter` and `tree-sitter-sql` become explicit, required dependencies of
332 `harlequin`** (Ted's call). Both are installed for everyone today, transitively via
333 `textual[syntax]`; depending on them directly costs 28ms, makes the guarantee real
334 instead of incidental, and collapses this section from "two splitters, carefully kept in
335 sync" to one. The accepted cost is that Harlequin stops installing on a platform with no
336 tree-sitter wheel — which is why `textual` made it an extra, and which the
337 `harlequin.sh/docs/troubleshooting/tree-sitter` page currently exists to explain. That
338 page becomes obsolete; PR 7 removes it.
339
340 **With that, there is exactly one splitter.** Tree-sitter is used in precisely one place
341 in Harlequin today — `code_editor.py`, for the semicolon query, and nowhere else
342 (highlighting is textual-textarea's own business and unaffected). So the editor calls
343 `find_separators(self.text)` and slices as it does now, and we delete `SEMICOLON_QUERY`,
344 `_semicolon_query`, `prepare_query`, `query_syntax_tree`, `has_shown_tree_sitter_error`,
345 and the whole `is_syntax_aware` fallback branch.
346
347 The one thing given up is textual-textarea's incremental tree: the shared library
348 reparses. Measured, that's 0.6ms for a realistic buffer and 22ms for a pathological
349 2000-statement one, and `selected_queries()` runs on submit rather than on keystroke. A
350 worthwhile trade for deleting a divergence.
351
352 **This fixes a live unicode bug in the TUI, which is why the shared library returns
353 character columns.** Tree-sitter's `Point.column` is a **byte** offset; Textual's own
354 docstring says so, and it hands the raw nodes back. But `get_text_range()` takes
355 *character* columns, and `code_editor.py:159` passes one straight into the other. Any
356 non-ASCII before a semicolon on the same line shifts the cut:
357
358 ```
359 select '日本語';select 2
360 splits today -> "select '日本語';select" | "2"
361 should be -> "select '日本語';" | "select 2"
362 ```
363
364 Both halves are then syntax errors. It's narrow — it needs non-ASCII before the
365 semicolon and a non-space after it, so `.strip()` usually absorbs the off-by-one — but
366 it's real, reproducible, and in `main` right now. Owning the byte→character conversion
367 in one place, once, is what stops `hsql` from inheriting it. Worth its own issue and a
368 changelog line, since it's a TUI bug fix that happens to fall out of this work.
369
370 *One known bug we don't fix:* `create function f() … $$ … ; … $$ …` splits inside the
371 dollar-quoted body. The TUI has it today, identically, because it's the grammar's. Its
372 own issue, not M1 scope — and a decent demonstration that sharing the grammar means
373 `hsql` inherits the TUI's behavior including its bugs, which is the definition of no
374 drift.
375
376 ### 3.3 Output — duckdb serializes, `hsql` lays out
377
378 ```python
379 **`hsql` writes no value-serialization code at all. duckdb is the serializer; `hsql`
380 only does layout.** That is the whole of §3.3, and everything below follows from it.
381
382 The temptation is to reach for the stdlib `csv` module, and on plain strings it is
383 indistinguishable — I diffed duckdb's writer against `csv.writer` on embedded commas,
384 embedded quotes, embedded newlines, nulls and unicode and got byte-identical output.
385 The divergence isn't escaping, it's **types**:
386
387 | value | `export.py` (duckdb) | stdlib `csv` + `str()` |
388 | --- | --- | --- |
389 | `timestamptz` | `2024-03-01 12:30:00+00` | `2024-03-01 12:30:00+00:00` |
390 | `boolean` | `true` | `True` |
391 | `blob` | `\x00\x01\xFF` | `b'\x00\x01\xff'` |
392
393 The third row is the argument. `b'\x00\x01\xff'` is a Python repr in a data file. A
394 hand-rolled writer doesn't just have to get RFC 4180 right, it has to own a rendering for
395 every type any of fifteen adapters can return — dates, intervals, decimals, blobs, lists,
396 structs, maps — and it will get them subtly wrong in ways nobody notices until an agent
397 parses one.
398
399 So the format table becomes:
400
401 | Format | Serialized by | Via |
402 | --- | --- | --- |
403 | `csv`, `tsv` | duckdb | `relation.write_csv(sep=…)` |
404 | `json`, `jsonl`/`ndjson` | duckdb | `COPY … (FORMAT JSON[, ARRAY TRUE])` |
405 | `parquet`, `orc`, `arrow`/`feather` | duckdb / pyarrow | the existing exporters |
406 | `table`, `markdown`/`md`, `vertical` | duckdb, then `hsql` lays it out | `CAST(col AS VARCHAR)` |
407 | `none` | — | rows discarded, status only |
408
409 `write_csv` already takes `sep`, `na_rep`, `header`, `quotechar`, `escapechar`, `quoting`,
410 `encoding` — so `tsv` is `sep="\t"`, `--no-header` is `header=False`, and
411 `--null-string` is `na_rep`. Nothing new needed. duckdb's JSON writer emits unquoted
412 numbers, bare `true`/`false`, real `null`, and preserves nested structs — the array-of-row-objects
413 shape §5 of the product plan asks for, with `ARRAY TRUE`, and jsonl without it.
414
415 **`ResultSet.text_columns()` is `CAST(col AS VARCHAR)`, and it's what keeps `-F table`
416 honest.** The human-facing layouts need strings, and if they derived them any other way
417 they would disagree with `-F csv` about what a timestamp or a blob looks like. Casting
418 through duckdb returns `1234.5600`, `true`, `\x00\xFF` — the same text `write_csv`
419 produces — with SQL `NULL` arriving as Python `None`, so it stays distinguishable from
420 the literal string `"NULL"` and `--null-string` works properly. `hsql` then does padding,
421 pipes and alignment, and nothing else.
422
423 **One serializer across every adapter is a feature, not a side effect.** Routing a
424 Postgres result through duckdb means Postgres, BigQuery and DuckDB timestamps print
425 identically — which is story A2 in the product plan ("the flags, output shape, and exit
426 codes are identical, so I don't relearn a CLI per database"). Getting that from a shared
427 serializer rather than from discipline is the cheap way to get it.
428
429 *Robustness:* everything reaches duckdb via `duckdb.from_arrow()`, so an arrow type
430 duckdb can't ingest would break the path. I tested large_string, dictionary-encoded,
431 duration, map and fixed-size-binary — all fine. There's still a `str()`-based fallback
432 with a stderr warning, as belt and braces rather than an expected path.
433
434 **`hsql` never calls `cell_formatter`, and this is the one place we deliberately don't
435 reuse the TUI's code.** `textual_fastdatatable.format.cell_formatter` is *display*
436 formatting: floats and ints as `f"{obj:n}"` (locale-aware thousands separators), booleans
437 as `✓ True`, strings as Rich markup. Correct for a data table a human is reading;
438 catastrophic in a CSV. Display and serialization are different operations, and conflating
439 them is how `1,234,567` ends up in a numeric column.
440
441 The corollary is a live trap: **`hsql` must not call `set_locale()`.** The `harlequin` CLI
442 does (`cli.py:339`), and inheriting it would make output vary with `LC_ALL` — a direct
443 violation of principle 4's "identical output" promise, visible only on someone else's
444 machine. `CAST AS VARCHAR` is locale-independent; `f"{obj:n}"` is not.
445
446 Column widths for `-F table` are measured over the strings from `text_columns()`, not
447 taken from `backend.column_content_widths` — the latter measures the width of the
448 *displayed* form we're not displaying.
449
450 They are measured in **terminal cells**, with `wcwidth` (Ted's call). An earlier draft
451 of this section said `max(len(s))` and dismissed display width as a great deal of
452 surface for a cosmetic problem; that was wrong on the cost, because `wcwidth` is already
453 installed and is one function call. It's the difference between a table that lines up
454 and one that doesn't for anyone whose data isn't Latin. `wcwidth` arrives transitively
455 via `prompt_toolkit` today — one of the packages the headless import graph exists to
456 keep *out* — so like `tree-sitter` in PR 2 it becomes a direct dependency. An ASCII fast
457 path keeps the common cell at `len()`.
458
459 ### Consequences worth stating plainly
460
461 **Nothing streams in M1, including CSV.** duckdb's writers are file-producing, so `-o PATH`
462 hands duckdb the path and stdout writes to a temp file and copies it out. My earlier
463 draft claimed csv and jsonl would stream; that was wrong twice over, because `fetchall()`
464 has already materialized the whole result before any writer sees it. Streaming is
465 uniformly an M5 problem that starts at the cursor, not at the formatter — which is
466 simpler than a format layer where some writers stream and some don't.
467
468 **One code path to stdout, not two.** `/dev/stdout` works on Linux and I verified it, but
469 it doesn't exist on Windows, and a platform-conditional output path is two paths to test
470 for no benefit. Temp file then `copyfileobj` everywhere. At the default `--limit 500`
471 it's unmeasurable; at `-l 0` duckdb writing a temp file beats building strings in Python.
472
473 **Newlines are still part of the contract.** duckdb writes `\n`; the copy to stdout must
474 be binary so Python's text-mode translation doesn't turn it into `\r\n` on Windows. Same
475 test as before, and now it covers every format at once.
476
477 **The overlap I flagged last draft is gone.** There was going to be one CSV writer for the
478 TUI's export dialog and another for `hsql`. There's one, and the export dialog's options
479 (compression, quoting, encoding) are already in its vocabulary.
480
481 ### `harlequin.export` and `harlequin.layout`
482
483 Given the above, the split isn't text-versus-columnar, it's **who serializes**:
484
485 ```python
486 # harlequin/export.py — writing a result set to a file, serialized by duckdb or pyarrow
487 def write_file(data: pa.Table, path: Path, format_name: str, options: Mapping[str, Any]) -> None: ...
488 def file_format_names() -> list[str]: ...
489
490 # harlequin/layout.py — arranging already-serialized text for a reader
491 @dataclass(frozen=True)
492 class LayoutOptions:
493 header: bool = True
494 footer: bool = True
495 aligned: bool = True
496 null_string: str | None = None
497 color: bool = False
498
499 class Layout(Protocol):
500 def write(self, result: ResultSet, out: TextIO) -> None: ...
501
502 def get_layout(name: str, options: LayoutOptions) -> Layout: ...
503 def layout_names() -> list[str]: ...
504 ```
505
506 `export.py` keeps its name and its job, loses the `ResultsTable` coupling from §1.6, and
507 gains `tsv` and `jsonl` as thin option variants of formats it already writes. `layout.py`
508 is new and small: three layouts, no type knowledge, no duckdb.
509
510 `LayoutOptions` is what makes psql's flag algebra fall out for free: `-t` is
511 `header=False, footer=False`, `-A` is `aligned=False`, and `-tA` needs no special case
512 because it was never one — two independent options, which is how psql users already think
513 about them. `--no-header` and `--null-string` also reach `export.py` as `header` and
514 `na_rep`, so the same four flags mean the same thing in every format.
515
516 ### 3.4 `harlequin.plugins` — naming an adapter without importing it
517
518 ```python
519 def adapter_names() -> list[str]: ... # entry-point names only
520 def load_adapter(name: str) -> type[HarlequinAdapter]: ... # imports exactly one
521 def load_adapter_plugins() -> dict[str, type[HarlequinAdapter]]: ... # existing
522 ```
523
524 `adapter_names()` reads entry-point *names* without calling `ep.load()`, so it costs
525 nothing. That's what makes the two-phase parse in §3.6 possible, and per §1.7 it is worth
526 ~160ms of the prototype's runtime — the difference between 380ms and 220ms.
527
528 ### 3.5 `harlequin.config` — merging CLI values over a profile
529
530 The merge in `cli.py:315-327` (drop every parameter whose click source is `DEFAULT`,
531 then `config.update(kwargs)`) is the precedence rule both commands must implement
532 identically. It moves to `config.py`, which already owns `Profile`:
533
534 ```python
535 def merge_profile_with_cli(
536 profile: Profile,
537 cli_values: Mapping[str, Any],
538 explicitly_set: Container[str],
539 ) -> Profile: ...
540 ```
541
542 `explicitly_set` rather than a click `Context`, so the config library stays free of the
543 CLI framework and is testable without one.
544
545 Adapter *instantiation* stays in each command — it's five lines, and the two commands
546 handle its failure differently (Rich panel and exit 2 vs. a plain line and exit 2). We
547 share the precedence rule, which is the part that would drift; we don't share five lines
548 of error handling that legitimately differ.
549
550 ### 3.6 `harlequin.hsql` — the command
551
552 Two-phase parse, which is what obstacle 3 forces and what makes `hsql --help` cheap:
553
554 1. Parse with `resilient_parsing` to find `-a/--adapter` and `-P/--profile`, using
555 `adapter_names()` — no adapter imported.
556 2. Resolve the profile (a profile may name an adapter), pick the one adapter in play,
557 `load_adapter(name)`, and build the real command with only that adapter's options.
558
559 An invocation only ever uses one adapter, so for *execution* this is not a compromise.
560
561 **Help is the exception, and it works differently (Ted's call).** My earlier version had
562 plain `hsql --help` render the default adapter's options, which is misleading: a Postgres
563 user reading `hsql --help` would see DuckDB's connection options and reasonably conclude
564 those were the only ones. `--help` is the one path that has to be true for every adapter.
565 So:
566
567 - **`hsql --help`** shows the adapter-agnostic surface — every option in §5 of the product
568 plan, the format list, the exit codes — plus the *names* of installed adapters and a
569 line saying `run 'hsql --help -a <adapter>' for its connection options`. No adapter is
570 imported to render this at all, only `adapter_names()`.
571 - **`hsql --help -a postgres`** imports postgres alone and adds its connection options.
572 - **`hsql --help -P prod`** does the same for whatever adapter the profile names, which is
573 the form a human will actually reach for.
574
575 This is better than what I had on every axis: it's honest, the top-level help is small and
576 stable (the thing an agent reads first), the adapter options are one explicitly signposted
577 call away, and rendering the common case imports nothing. It also degrades well as the
578 ecosystem grows — twenty installed adapters make the help *list* longer by twenty lines,
579 not the help *body* by twenty option tables.
580
581 `hsql info --json` (M2) remains the way to enumerate everything at once.
582
583 `harlequin` itself keeps its current all-adapters help. Changing it would alter published
584 `--help` output and the docs built from it, for no benefit to a TUI already paying for
585 Textual.
586
587 `diagnostics.py` owns the stderr contract:
588
589 ```python
590 class ExitCode(IntEnum):
591 OK = 0; QUERY = 1; USAGE = 2; CONNECTION = 3; TIMEOUT = 4; INTERRUPT = 130
592
593 def exit_code_for(error: BaseException) -> ExitCode: ...
594 def report_error(error: BaseException) -> None: # "hsql: error: ..."
595 def report_truncation(result: ResultSet, limit: RowLimit) -> None: ...
596 def report_stats(...) -> None: # one line of JSON
597 ```
598
599 Two things worth stating because they're easy to get wrong:
600
601 - **The truncation notice fires under `-t`.** `-t` suppresses stdout chrome; it does not
602 suppress warnings. A flag that silently defeated truncation reporting would undo the
603 principle it's meant to coexist with.
604 - **Exit codes are hsql's contract, not Harlequin's**, so the mapping lives here rather
605 than in `harlequin.exception`. `HarlequinQueryError → 1`, `HarlequinConnectionError → 3`,
606 `HarlequinConfigError → 2`, `KeyboardInterrupt → 130`.
607
608 ---
609
610 ## 4. Sequencing
611
612 One upstream release, then two Harlequin releases. The first Harlequin release contains
613 no new user-facing surface at all; the second is the feature. Every PR in the first is
614 independently reviewable, independently testable, and behavior-neutral for the TUI.
615
616 ### Upstream — `textual-fastdatatable` (0.17)
617
618 **PR 0.** Lazy `DataTable` in `__init__.py` via PEP 562; `pyarrow.parquet` deferred into
619 `ArrowBackend.from_parquet`. Add a test asserting `"textual" not in sys.modules` after
620 importing `textual_fastdatatable.backend` — otherwise the next contributor re-adds a
621 convenience import at the top of `__init__` and nobody notices for a year. Both changes
622 are non-breaking; harlequin then bumps its pin from `==0.16.0` to `==0.17.0`.
623
624 Blocks PR 2 and PR 3. Doesn't block PR 1, so it can be running in parallel.
625
626 ### Release A — the plumbing (2.9)
627
628 **PR 1 — Import hygiene, and the guard that keeps it.**
629 Lazy `harlequin/__init__.py` via PEP 562, preserving every current name.
630 `AutoBackendType` under `TYPE_CHECKING` in `adapter.py`, `harlequin_duckdb`,
631 `harlequin_sqlite`. `NewCatalog`/`NewCatalogItems` move to `harlequin/messages.py`, with
632 a module-level `__getattr__` shim in `catalog.py` so existing imports keep working
633 without importing Textual. Deferred renderer imports in `options.py`; `_CustomValidator`
634 moves to `copy_widgets.py`, which is already the option-widgets library. Fix the two
635 stdout leaks from §1.5. Add import-linter contracts and the cold-start benchmark script.
636
637 Ships value on its own: importing `harlequin_duckdb` goes from 691ms to 56ms, which
638 every adapter's test suite and every library consumer feels.
639
640 **PR 2 — `harlequin.statements` and `harlequin.query`.** Add `tree-sitter` and
641 `tree-sitter-sql` to `dependencies`. Build the splitter; refactor `CodeEditor` onto it and
642 delete its fallback branch, fixing the unicode column bug in the same move; land the
643 tricky-SQL corpus. Then the execution core, with `_execute_query` and `_fetch_data`
644 refactored onto it. Delete the dead `_split_query_text`. Snapshot tests are the safety
645 net for the TUI refactor.
646
647 This is the only PR in Release A with user-visible behavior in it — the unicode fix — so
648 it gets a changelog entry and its own issue while the rest stay silent.
649
650 **PR 3 — `export.py` decoupled from `ResultsTable`, plus `harlequin.layout`.** Extend
651 `export.py` with `tsv` and `jsonl` (option variants of formats it already writes) and the
652 temp-file-to-stream path; add the three layouts and `ResultSet.text_columns()`. Golden
653 files per format. No user-visible change; neither has a consumer until PR 5.
654
655 **PR 4 — `merge_profile_with_cli`, `adapter_names`, `load_adapter`.** `harlequin`'s own
656 CLI refactored onto the first; behavior-neutral, covered by the existing 392 lines of
657 `test_cli.py`.
658
659 *Why these land on main rather than accumulating on a feature branch:* they're
660 behavior-neutral and individually tested, and the alternative is a long-lived branch
661 rebasing against a moving TUI — which is where extraction refactors go to die.
662
663 ### Release B — the command (2.10)
664
665 **PR 5 — `hsql`.** Console script, two-phase parse, `-c`/`-f`/stdin, `-o`, `-F` and the
666 shorthands, `-t`/`-A`/`--no-header`/`--null-string`, `-P`, `-l` defaulting to 500,
667 `--result`, `--on-error`, `--color`/`NO_COLOR`, `--stats`, exit codes, truncation
668 notices, plain errors.
669
670 **PR 6 — Discoverability.** Unknown-option handler on `harlequin` (`-c` → "did you mean
671 `hsql -c`?"), and the `-t nord` hint on `hsql` when an unparseable conn_str matches a
672 known theme name.
673
674 **PR 7 — Docs.** The "Headless & Agents" topic (a PR against `tconbeer/harlequin-web`),
675 README, changelog. Retire the `troubleshooting/tree-sitter` page, which describes a
676 degraded mode that no longer exists (§3.2).
677
678 **PR 8 — The agent eval suite.** Three tasks against fixture databases, scored on
679 wrong-flag retries and completion. §13 of the product plan calls this the metric that
680 actually matters; three tasks is enough to start and to expand against.
681
682 **Ordering rationale.** Everything the output contract touches ships at once, in PR 5.
683 The product plan's premise is that format and exit codes are a frozen API — a
684 half-shipped `hsql -c` that we "improve later" is the one thing here that can't be
685 undone. Internals can be improved after release; the contract can't.
686
687 ---
688
689 ## 5. Testing
690
691 **Deterministic guards, not timing assertions.** The cold-start number is the headline,
692 but a wall-clock assertion on a shared CI runner is a flaky test that gets deleted within
693 a month. So:
694
695 - *Deterministic and blocking:* import-linter contracts — the `hsql` module graph must
696 not contain `textual` or `questionary`. Plus subprocess tests asserting
697 `"textual" not in sys.modules` after importing the headless core, and the same test
698 upstream after importing `textual_fastdatatable.backend`. These fail identically on
699 every machine.
700 - *Informational:* the benchmark reports `hsql -c "select 1"` against DuckDB into the
701 job summary, failing only past a loose ceiling (600ms) that catches a real regression
702 without catching a busy runner.
703
704 The import contracts are load-bearing. Timing is downstream of them.
705
706 Beyond that:
707
708 - **`CliRunner` tests** for `hsql`, following the existing `test_cli.py` patterns and its
709 adapter-mocking fixtures.
710 - **Golden files** per format (syrupy snapshots, as everywhere else in this repo)
711 against a fixture result set with nulls, unicode, wide
712 values, duplicate column names, and zero rows. Zero rows is the case that separates
713 "the query returned nothing" from "the query failed" — A3 in the product plan — and
714 the one most likely to be wrong in a format nobody exercised.
715 - **A type-coverage fixture** — timestamp, timestamptz, date, decimal, float, boolean,
716 blob, list, struct, map, and null in each — rendered into every format, as golden
717 files. This is the table in §3.3 turned into a test: it's what would catch a change in
718 duckdb's rendering, and it's the reason `-F table` and `-F csv` can be asserted to
719 agree cell for cell.
720 - **`text_columns()` agreement:** for that fixture, the strings `-F table` prints are the
721 same strings `-F csv` writes.
722 - **stdout purity:** for each format, stdout bytes identical with and without `--stats`;
723 a query error leaves stdout completely empty.
724 - **Determinism:** identical bytes whether stdout is a pipe, a file, or a pty; `\n`
725 regardless of platform, which now means the temp-file copy is binary; **identical bytes
726 under `LC_ALL=de_DE.UTF-8`**, the regression test for §3.3's locale trap.
727 - **`-o PATH` and `> PATH` produce identical bytes** for every format — the one thing the
728 temp-file path could plausibly get wrong.
729 - **`hsql -tAc "select count(*)"` returning a bare number and nothing else** as its own
730 named test. It's the idiom the scripting audience will try first.
731 - **Truncation:** exactly-at-limit, one-over-limit, and under-limit, on both duckdb and
732 sqlite — the two implement `set_limit` differently enough to matter.
733 - **The tricky-SQL corpus** against `statements.split()` and, through `selected_queries()`,
734 the editor — same fixtures, one splitter underneath. Includes non-ASCII before a
735 semicolon with no following space (the §3.2 bug, which fails on `main`) and a
736 skip-marked dollar-quoting case so the known bug is recorded rather than forgotten.
737
738 ---
739
740 ## 6. Decisions
741
742 **Settled.**
743
744 - *Limits stay on the existing machinery.* `cursor.set_limit()` and the backend's
745 `max_rows`, exactly as they are — no new adapter-interface method for truncation in M1
746 (see §3.1).
747 - *No overflow detection in the TUI.* It doesn't need any: `--limit` there is a soft
748 display cap over a full fetch, so it already reports the exact total (§3.1).
749 `detect_overflow=False`, no snapshot churn in PR 2.
750 - *Streaming is out.* Not designed around, not partially built — see §3.3 and §7.
751 - *`tree-sitter` and `tree-sitter-sql` become required dependencies.* One splitter, no
752 fallback, the troubleshooting page retired (§3.2). Accepted cost: no install on
753 platforms without a tree-sitter wheel.
754 - *`--help` is adapter-agnostic*, listing adapter names and pointing at `--help -a X`
755 for connection options (§3.6). Ted's design; better than what I proposed.
756 - *`--result` defaults to `all`, in every format* (below).
757
758 ### On `--result`
759
760 The flag only matters when one invocation produces more than one result set — `hsql -c
761 "select 1; select 2"`, or the common `-f script.sql` shape of a few setup statements
762 followed by the query you actually care about. `all` emits every result set; `last` emits
763 only the final one; `N` picks one. With a single statement, which is most invocations,
764 the flag does nothing.
765
766 The product plan's proposal was `all` for text formats and `last` for data formats. The
767 problem isn't the values, it's that the *same command* would emit different things
768 depending on `-F`, which is exactly the context-dependence principle 4 exists to prevent.
769 Agreed on consistency, so:
770
771 **`--result all` is the default everywhere. Formats that can't hold multiple result sets
772 say so rather than lying.** Concretely:
773
774 - One result set: works in every format, no change.
775 - Multiple, into `table` / `markdown` / `vertical` / `jsonl`: all of them, in order.
776 - Multiple, into `csv` / `tsv` / `json`: **error, exit 2** —
777 `hsql: error: 3 result sets, but csv holds one; use --result last or --result 3`.
778
779 Writing two headers into one CSV is silent corruption of the same family as silent
780 truncation, and an error that names the fix costs an agent one retry with a clear signal.
781 The alternative — silently defaulting to `last` — throws away data the user asked for
782 without saying so.
783
784 **Still open.** Nothing.
785
786 ---
787
788 ## 7. Explicitly not in M1
789
790 `--read-only`, `--timeout`, `--dry-run`, `--single-transaction` (M2 — the first three
791 need adapter-interface additions and an ecosystem rollout). Every subcommand: `catalog`,
792 `describe`, `fmt`, `spec`, `info`, `config`, `history`, `open`, `mcp`. Streaming of any
793 kind — it starts at the cursor interface, not the format layer (M5; see §3.3 and §8).
794 Unifying the TUI's export dialog onto `write_file` (mechanical, but it moves a UI).
795 Making `textual` an optional extra of
796 `textual-fastdatatable`, and the separate lean `hsql` distribution it would enable (§4
797 of the product plan: near-reversible, indefinitely deferrable). Fixing dollar-quoted
798 statement splitting (its own issue, affects the TUI equally).
799
800 Bare `hsql` with no arguments prints help and never launches the TUI, from the first
801 release.
802
803 ---
804
805 ## 8. Corrections to the product plan
806
807 All of these are **applied** in `harlequin-for-agents.md` in the same PR as this
808 document; they're recorded here so the reasoning behind each change is written down
809 somewhere.
810
811 - **§4 says the full adapter option matrix on `hsql --help` is "unavoidable and shared."**
812 It's avoidable. `hsql --help` lists adapter *names* and points at `--help -a X`, which
813 is both a token saving and the fix for the only unbounded startup cost (§3.6).
814 - **§12 lists cold start as a risk with "may need lazy entry-point resolution."** Not a
815 maybe: it's worth 160ms of a 380ms invocation with four adapters installed, and it
816 grows without bound. A requirement of M1, not a contingency.
817 - **§12's cold-start risk should name `textual-fastdatatable`, not just "Textual creeping
818 in."** The 265ms the adapter interface pays today is upstream of this repo, and an
819 import-linter rule here would never have caught it.
820 - **§5's truncation guarantee needs the `limit + 1` fetch to be implementable at all.**
821 Worth stating in the product plan, because it's exactly the kind of thing that gets
822 designed out as an implementation detail and then quietly breaks the promise.
823 - **§5 says "Large results stream" and lists it as an M1 concern.** Nothing streams in
824 M1, and it can't: `HarlequinCursor.fetchall()` materializes the whole result before any
825 writer exists, so the format layer is downstream of the problem. Streaming is an M5
826 change to the cursor interface, and M1 doesn't design around it — `rows()` returns an
827 iterator because that's the natural shape, not as a hedge. Agreed with Ted; the product
828 plan's §5 bullet should move to M5 outright.
829 - **§5's truncation footer says `… 500 of N rows`, and N is unknowable.** Under a hard
830 fetch limit we deliberately never learn the true total — that's the point of the limit.
831 The footer is `500 of >500` -- strictly greater, which the limit+1 fetch proves and
832 the conventional `500+` would understate -- and only `-l 0` yields an exact count. (The TUI *can* say
833 `100,000 of 3,412,887` because its limit is a display cap over a full fetch; see §3.1.)
834 - **§5 lists `--limit` as though it means the same thing in both commands.** It doesn't:
835 soft display cap in the TUI, hard fetch limit in `hsql`. Worth one explicit sentence in
836 the docs rather than letting a reader assume they match.
837 - **§5's `--result` default is format-dependent** (`all` for text, `last` for data), which
838 makes the same command emit different things depending on `-F`. It's `all` everywhere,
839 with an error rather than silent corruption where a format can't hold more than one
840 result set (§6).