Debian Codegraph @

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

raw
1 # M2 Technical Plan — self-description and safety
2
3 Implementation plan for milestone M2 of [Harlequin for agents](./harlequin-for-agents.md),
4 following [the M1 technical plan](./m1-hsql-technical-plan.md). The product plan says what
5 `hsql` is for; M1 built the command and the execution core under it. This one is about
6 letting an agent learn a database before it queries one, and about the flags that let a
7 human hand an agent a warehouse credential.
8
9 **M2's scope, from the roadmap:** `catalog` (one level below the match), `info --json`,
10 `spec --json`, `config validate/show/schema/init`, capability flags, the
11 secret option type and declarative redaction
12 ([#667](https://github.com/tconbeer/harlequin/issues/667)), env interpolation
13 ([#898](https://github.com/tconbeer/harlequin/issues/898)), `--read-only`, `--timeout`, and
14 a published JSON Schema. `find` + `implements_catalog_search` is promoted out of the stretch
15 column and ships with implementations for both in-tree adapters; optional `fetch_descendants`
16 stays future work.
17
18 **Cut in review** (§7 has the reasoning for each): `describe`, `fmt`, `--dry-run`,
19 `--single-transaction` (which M1 §7 had deferred to M2), `--password-stdin`, recursive
20 `--depth`, the node budget, child counts, round-trip counting, and the `compact` and `tree`
21 layouts.
22
23 **Where M1 actually got to.** PRs 1–6 shipped: the import-hygiene work, the statement
24 splitter and execution core, `export`/`layout`, the shared profile-merge and one-adapter
25 loading, `hsql` itself, and the two commands pointing at each other. PR 7 (the docs topic,
26 against `tconbeer/harlequin-web`) is in flight. PR 8, the agent eval suite, is not being
27 done — so M2 has no automated measure of "an agent used the right flag first try," and the
28 guards below are all deterministic ones.
29
30 **Bottom line up front.** M2 needs no new execution path, no new output format family, and
31 no second config parser: **catalog listings are result sets**, so `--format`, `-o`, `-t/-A`,
32 `--display-rows` and `--stats` already apply to them, and the row cap that keeps a 400-row
33 listing readable is the one M1 already shipped. What M2 does need is **five additive members
34 on the adapter contract** — four fields and one method — because the features that would
35 otherwise be built on guesswork are unimplementable without them: the catalog knows a column
36 is `##` but not that it is `DECIMAL(18,2)`, no adapter can say whether it enforces read-only,
37 and none can answer "where does `orders` live" without a walk. Those are measured,
38 below, not feared.
39
40 **On the shape of the CLI.** Every capability here is a **mode option** on the one `hsql`
41 command — `--catalog`, `--find`, `--info`, `--spec`, `--config MODE` — not a subcommand
42 (Ted's call). It matches `harlequin --config`, and it removes an ambiguity subcommands
43 would have created: `hsql` takes `CONN_STR` positionally, so a database file named
44 `catalog` would have collided with the verb. There is no collision to rule on if there is
45 no verb. See §3.1.
46
47 ---
48
49 ## 1. Where the code actually is today
50
51 Measured on this checkout — 2.8.1 plus the unreleased M1 work — on Python 3.10.15, Linux,
52 with four adapters installed (duckdb, sqlite, postgres 1.3.1, mysql 1.3.0). Wall times are
53 the best of five runs of the real console script.
54
55 ```
56 hsql -c "select 1" 257ms
57 hsql --help 90ms
58 hsql --version 87ms
59 harlequin --version 767ms
60 ```
61
62 M1's targets held. Everything M2 adds has to keep them, which is most of why §3 is shaped
63 the way it is.
64
65 ### 1.1 The catalog is lazy in the right way, and resolving a path is itself a walk
66
67 `get_catalog()` returns the top level only — one query — and every level below it is a
68 separate `fetch_children()` call on the item you are standing on. That is exactly the shape
69 the product plan asks for, and it is why one level below the match is cheap.
70
71 But there is no way to *reach* an item except by fetching its ancestors. To call
72 `fetch_children()` on `mydb.analytics.orders` you need that item object, which only
73 `SchemaCatalogItem.fetch_children()` can hand you, which needs the schema item, which needs
74 the database item. I built a DuckDB file with 400 relations in one schema and counted the
75 round trips (spelling the calls in the mode-option syntax of §3.1):
76
77 | Call | Children | Round trips | Local ms |
78 | --- | --- | --- | --- |
79 | `hsql --catalog wide.db` | 1 database | 1 | 1.9 |
80 | `hsql --catalog --path wide wide.db` | 2 schemas | 2 | 10.2 |
81 | `hsql --catalog --path wide.analytics wide.db` | 400 relations | 3 | 12.8 |
82 | `hsql --catalog --path wide.analytics.t000 wide.db` | 3 columns | 4 | 22.8 |
83 | the same at a hypothetical `--depth 2` | 400 relations + 1200 columns | **403** | **2303** |
84
85 So a listing costs **one round trip per path segment, plus one** — not the "exactly one
86 `fetch_children()`" the product plan's §6 claims. On local DuckDB that difference is 20ms;
87 on BigQuery or Trino it is four network calls where the plan promised one.
88
89 **What recursion costs depends entirely on where you stand**, which is why the product
90 plan's blanket `--depth N` is the wrong knob. Depth 2 from the root fetches every database's
91 schema names: one round trip per database, and databases are few. Depth 2 from a *schema* is
92 one round trip per relation, and the last row above is what that means — **403 round trips
93 and 2.3 seconds against a local file**, on the call an agent would most want to make.
94
95 M2 therefore ships **one level, always**, and no `--depth` at all (§3.2). The honest
96 recursive answer needs `fetch_descendants()` on the adapter contract so a database can
97 answer in one query (§3.8), and that is where the flag should arrive from.
98
99 ### 1.2 Catalog depth is adapter-specific, and nothing declares it
100
101 DuckDB and Postgres are four levels (database → schema → relation → column). SQLite is
102 three (database → relation → column). BigQuery's own hierarchy is project → dataset →
103 table, which is four levels wearing different words. Nothing in `harlequin.catalog` says
104 how deep a catalog goes or what a level is called.
105
106 So `--path` cannot document its grammar as `database.schema.table`. Paths are **positional
107 segments** whose meaning is the adapter's, and the type label on each item (`db`, `sch`,
108 `t`, `v`) is what tells a reader what they got. That is a small design constraint with a
109 large documentation consequence, and it beats inventing a level vocabulary that would be
110 wrong for a third of the ecosystem.
111
112 ### 1.3 The catalog knows the short type, and throws the real one away
113
114 `CatalogItem.type_label` is documented as "a short (1-3 chars) label" — `##` for a bigint,
115 `s` for a varchar, `ts` for a timestamp. It is a Data Catalog affordance: it has to fit in a
116 tree column next to the name.
117
118 So a listing of `analytics.orders` can say `id ##, customer_id ##, total #.#` and no more,
119 which tells an agent almost nothing and would send it back to `select * limit 0` to find out
120 what it is joining on. **The type an agent needs to write a join is not in the catalog
121 contract** — only the glyph that fits in the IDE's tree.
122
123 The data is right there and discarded. `DuckDbConnection._get_columns()` selects
124 `column_name, data_type` from `information_schema.columns` and then does
125 `type_label=self.connection._short_column_type(column_type)`, dropping `column_type` on the
126 floor. SQLite's is the same shape. So this is one field on `CatalogItem`, not a new query
127 (§3.2).
128
129 **Child counts are a different matter, and M2 does not add a field for them.** There is
130 nowhere to hang a count today, and there shouldn't be: no adapter can produce one without
131 fetching the children, so a `child_count` field would either be `None` everywhere or be a
132 fetch in disguise. The count that is knowable is `len(children)` once they are loaded —
133 which is what a listing already shows in its own footer. The product plan's "report child
134 counts wherever the adapter can get them cheaply" turns out to have no cheap case, and it
135 was proposed as a mitigation for a recursion M2 is not shipping anyway.
136
137 ### 1.4 Capability flags have to be declared, and only some of them are
138
139 Today's capability surface is three things on the adapter class: `IMPLEMENTS_CANCEL`,
140 `implements_copy` (derived from `COPY_FORMATS`, and deprecated), and `provides_details`.
141 Everything else — `cancel`, `validate_sql`, `copy`, `transaction_mode` — lives on the
142 *connection*, and the connection class is not reachable from the adapter class without
143 connecting to a database.
144
145 Nor can an override be detected reflectively. `type(conn).validate_sql is not
146 HarlequinConnection.validate_sql` reports SQLite as validating SQL, because
147 `HarlequinSqliteConnection.validate_sql` **is** defined and its body is `raise
148 NotImplementedError`. That is not a bug — the app catches `NotImplementedError` at the call
149 site and carries on — but it does mean a reflective probe cannot answer the question, and
150 that a class variable is the pattern that can.
151
152 Cost, measured, with those four adapters installed:
153
154 | | ms | modules |
155 | --- | --- | --- |
156 | entry-point *names* (`adapter_names()`) | 46 | 126 |
157 | names + dist name and version (`ep.dist`) | 51 | 128 |
158 | `load_adapter("duckdb")` | 114 | 187 |
159 | `load_adapter_plugins()` — all four | 309 | 425 |
160
161 Two things follow. Adapter **versions are free** — `ep.dist.version` costs 5ms over reading
162 names, so what is installed is answerable without importing any of it. (Capability flags are
163 class variables, so reporting *those* costs the import; §3.4.) And anything that wants every
164 adapter's *options* pays 300ms and rising, which is fine for `--spec`, a once-per-task
165 lookup, and not fine for anything on the query path.
166
167 ### 1.5 Options can be declared but not described, validated, or marked secret
168
169 `AbstractOption` renders three ways — `to_click()`, `to_widgets()`, `to_questionary()` — and
170 has no fourth. There is no serialization, so `--spec` has nothing to call, and the
171 debug-info screen builds a markdown table by reaching for `opt.name`, `opt.short_decls` and
172 `getattr(opt, "default", None)` — duck-typing at a distance, which is what a real
173 `to_dict()` would replace.
174
175 Adding an **abstract** method is not available: `AbstractOption` is public API and
176 third-party adapters subclass it. Anything added here has to be concrete, with a base
177 implementation that works for a subclass that has never heard of it.
178
179 Nothing declares a value sensitive. Sampling the ecosystem, `harlequin-postgres` 1.3.1
180 declares twelve options, of which `password` is a plain `TextOption`, `sslkey` is a
181 `TextOption`, and `passfile` is a `PathOption`. So `--spec` would today teach an agent that
182 `--password` exists and say nothing about why it must not be typed on a command line, where
183 `ps` and shell history can read it.
184
185 **And nothing validates an adapter option that arrives from a profile.** Options typed on the
186 command line go through click, which rejects what it doesn't know; options read out of a
187 config file go straight to the adapter's constructor as keyword arguments, and the adapter
188 contract tells adapters to tolerate supersets of what they declare. So a misspelled key is
189 accepted in silence, by design, all the way down:
190
191 ```python
192 >>> DuckDbAdapter(conn_str=(":memory:",), reed_only=True, dbnmae="warehouse")
193 constructed fine | read_only = False
194 ```
195
196 That is the safety-relevant version of §1.6: a human who put `reed_only = true` in a profile
197 believes they handed an agent a read-only connection, and did not. Nobody in the stack is in
198 a position to notice — except a step that knows both the profile and the adapter's declared
199 options, which is §3.5's second pass.
200
201 ### 1.6 Config files merge per top-level key, and it is worse than losing a profile
202
203 Ted asked me to test this rather than assert it, and the result is sharper than the first
204 draft claimed. `_merge_config_files()` is a top-level `dict.update()` per file, so:
205
206 ```toml
207 # ~/.harlequin.toml
208 default_profile = "personal"
209 [profiles.personal] # + [profiles.shared]
210
211 # ./.harlequin.toml
212 [profiles.project]
213 ```
214
215 ```
216 merged: {'default_profile': 'personal', 'profiles': {'project': {'adapter': 'sqlite'}}}
217 ```
218
219 The cwd file's `profiles` table replaces the home file's outright — but `default_profile`
220 survives from the home file, because it is a *different* top-level key. So the two do not
221 just disagree, they contradict, and **both commands then refuse to start**:
222
223 ```
224 harlequin.exception.HarlequinConfigError: Config files set the default_profile to
225 personal, but do not define a profile with that name.
226 ```
227
228 A project-local config file that names one profile bricks a user whose personal file sets a
229 default. **This predates the `tomllib` refactor**: I ran the same probe against the
230 pre-refactor `config.py` (the tomlkit read path, from `1af8cca`) and got the identical
231 error, so the C parser did not introduce it — `dict.update()` has always replaced the table
232 rather than merging it.
233
234 Reading is `tomllib` (fast, and every start-up pays it, including on the `pyproject.toml`
235 that sits in any Python project's cwd) and writing is `tomlkit` (slow, preserves comments,
236 loaded only when something writes). That split is right and M2 keeps it — but note that
237 `config_wizard` reads `ConfigFile.relevant_config` and writes it back through `update()`, so
238 **anything that transforms values on read will be written back transformed** unless the read
239 path used for writing stays raw. That is the whole implementation risk in env interpolation
240 (§3.5).
241
242 Schema errors (`_raise_on_bad_schema`) are good prose with no machine channel and no
243 positions: `tomllib` reports a line for a *parse* error inside its message, and neither
244 parser will tell you where key `profiles.prod.limitt` sits in the file.
245
246 ### 1.7 Two expensive imports the query path must never pay
247
248 `hsql` is contractually forbidden from importing `sqlfmt`, `questionary` and Textual: the
249 `hsql does not reach the TUI` import-linter contract lists them, and
250 `tests/unit_tests/test_import_hygiene.py` asserts they stay out of `sys.modules` after every
251 headless import. With `fmt` cut from this milestone (§7), **sqlfmt stays forbidden outright**
252 — there is now no headless code path that wants it.
253
254 Two others are merely expensive, and M2 adds the first consumer of each:
255
256 - **`questionary`, 156ms and 329 modules.** `hsql` must never import it, because `hsql` must
257 never prompt (§3.7). `--config init` is the non-interactive path, and the wizard stays
258 where it is.
259 - **`tomlkit`, 49ms alone and +8ms on top of `harlequin.hsql.cli`.** Only `--config init`
260 writes a file, so only `--config init` pays it, deferred into the mode.
261
262 For scale, `harlequin.hsql.cli` alone imports in 107ms across 187 modules, and importing
263 sqlfmt on top of it would have taken that to 217ms/304 — most of a second `hsql -c`
264 invocation, for a feature §7 explains we are not shipping.
265
266 ### 1.8 There is nothing to build `--read-only` on, and transactions are worse
267
268 No adapter declares read-only as a capability. DuckDB and SQLite each declare their own
269 `read-only` *option*, which core could set by name — but `harlequin-postgres` declares no
270 such option at all, so a convention-based `--read-only` would silently do nothing on the
271 adapter most likely to be pointed at production. (Postgres can enforce it; it wants `set
272 default_transaction_read_only = on` at connect, which is adapter work, not core work.)
273
274 Transactions are the same shape and further gone, which is why `--single-transaction` is cut
275 (§7). `HarlequinConnection.transaction_mode` returns a
276 `HarlequinTransactionMode(label, commit, rollback)` or None, and **the label is whatever the
277 adapter chose**: SQLite offers Auto/Manual on 3.12+, Postgres offers Auto/Manual, DuckDB
278 overrides nothing and so returns None, and a third-party adapter may name its modes anything
279 at all and default to whatever its driver does. Core cannot ask for "the manual one" through
280 that interface without first making the contract say which mode is which.
281
282 ### 1.9 A cancelled query returns zero rows and exit code 0
283
284 This is the one that would have shipped as a bug. I ran a billion-row DuckDB aggregate
285 through `harlequin.query` on a worker thread and called `connection.cancel()` from the main
286 thread:
287
288 ```
289 cancel() returned in 0.0ms
290 executed: [(has_result_set=True, error=None)]
291 rows: 0
292 elapsed: 702ms
293 ```
294
295 `DuckDbCursor.fetchall()` catches `duckdb.InterruptException` and returns `None`; `fetch()`
296 turns `None` into an empty backend, correctly, because that is also what a real empty result
297 looks like. So a naive `--timeout` prints an empty result set, writes no diagnostic, and
298 exits 0 — reporting "your query returned nothing" for a query that was killed. That is the
299 silent-wrong-answer family the whole product plan exists to avoid, and no amount of care in
300 the adapter helps, because the adapter cannot tell an interrupt it was asked for from one it
301 wasn't.
302
303 Two more things I measured while establishing what a deadline can do:
304
305 - **Exiting while a worker thread is inside DuckDB aborts the process.** `sys.exit(4)` with
306 a live daemon thread in `to_arrow_table()` produces `terminate called without an active
307 exception` and exit code **134**, which is not in the documented table. `os._exit(4)`
308 after an explicit flush exits 4 with stdout intact.
309 - So a deadline is implementable, but only as: cancel → wait → flush → `os._exit`. And with
310 an adapter that cannot cancel, there is no way to stop the work at all.
311
312 ---
313
314 ## 2. The obstacles, stated plainly
315
316 1. **The adapter contract can't answer four of M2's questions.** What is this column's real
317 type; where does a name live; can you enforce read-only; can you validate SQL. All are
318 additive, with defaults (plus one more on options, for secrets), and all need an ecosystem
319 rollout before they are true everywhere — which is why the release that needs none of them
320 goes first.
321 2. **Resolution is a walk, and recursion is unbounded.** One round trip per path segment,
322 and 403 for a single recursive listing of a wide schema. The answer M2 takes is to ship
323 one level and no recursion at all, rather than to ship a knob with a cliff behind it.
324 3. **`hsql` grows four modes without losing a 90ms `--help`.** Two of them need imports the
325 query path must never pay — every installed adapter at once, and tomlkit — and one of
326 them (`--info`) has to work when the database is unreachable, which is precisely when a
327 diagnostic is worth most.
328 4. **A timeout cannot trust the adapter to report itself.** §1.9. `hsql` has to attribute
329 the cancellation it caused, because the adapter can't.
330 5. **Secrets leak through four new mouths at once.** `--info`, `--spec`, `--config show` and
331 errors are all output surfaces M2 adds, and every one of them handles connection options.
332 Redaction has to be a property of the declaration, not a rule applied four times.
333
334 Note what is *not* on the list. There is no new output subsystem: catalog listings are rows,
335 so `--format`, `-o`, `-t`, `-A`, `--display-rows` and `--stats` are already written and
336 already tested (§3.3). And there is no new config parser: provenance, interpolation and
337 schema generation are all things to do to the config we already read.
338
339 ---
340
341 ## 3. Target architecture
342
343 ```
344 harlequin/
345 adapter.py MOD + IMPLEMENTS_READ_ONLY, IMPLEMENTS_VALIDATE_SQL
346 catalog.py MOD + CatalogItem.type_name
347 navigate.py NEW resolving a catalog path and listing one level below it
348 options.py MOD + secret=..., + to_dict()
349 config.py MOD per-profile merge, provenance, ${VAR} interpolation
350 config_schema.py NEW the JSON Schema for a config file, generated from what is installed
351 redact.py NEW redaction helpers, driven by the options that declare themselves secret
352 query.py MOD text_columns() returns string data unchanged
353 hsql/
354 cli.py MOD + the mode options, and which of them attaches adapter options
355 timeout.py NEW a wall clock over a run, and how it exits
356 modes/ NEW catalog.py find.py info.py spec.py config.py
357 ```
358
359 M1's rule stands and now covers four modes as well as the run form:
360
361 > **stdout is written only by `harlequin.layout` and `harlequin.export`. stderr is written
362 > only by `harlequin.hsql.diagnostics`.**
363
364 M2 adds a second, which is the whole milestone in a sentence and is also testable:
365
366 > **No mode pays for what it did not ask for.** `--help` imports no adapter; `--spec` and
367 > `--config` import no database driver; `--info` opens no connection; `--catalog` fetches
368 > one level; and the query path imports neither sqlfmt, tomlkit nor questionary.
369
370 ### 3.1 Modes are options, not subcommands
371
372 ```
373 hsql [OPTIONS] [CONN_STR]...
374
375 --catalog List catalog objects one level below --path.
376 --path TEXT Where in the catalog to look. Dotted segments; default is the top.
377 --find TERM Search the catalog for TERM, where the adapter can.
378 --info Report versions, config files, adapters and capabilities. JSON.
379 --spec Dump the installed CLI surface, including adapter options. JSON.
380 --config MODE show | list-profiles | validate | schema | init
381 ```
382
383 **Why options rather than subcommands (Ted's call).** It matches `harlequin --config`, so
384 one shape covers both commands. It keeps `hsql`'s parse a plain click command — M1's
385 two-phase build stays two phases rather than growing a verb phase in front. And it removes
386 an ambiguity that subcommands would have introduced for free: `hsql` takes `CONN_STR`
387 positionally, so `hsql catalog` and a DuckDB file named `catalog` would have needed a
388 disambiguation rule, docs for the rule, and a test for the rule. No verb, no rule.
389
390 Modes are **mutually exclusive**; two of them is a usage error, exit 2, naming both. With no
391 mode, `hsql` is what M1 shipped.
392
393 **`--path`, not `-c`.** Ted floated reusing `-c` for the catalog path and offered `--path`
394 or `--relation` as alternatives; `--path` is the one to take. `-c` is `--command` and means
395 *SQL* in this CLI, in psql, and in duckdb, and the whole premise of principle 4 is that a
396 flag should not change meaning with context. An agent that has learned `-c` types
397 `hsql --catalog -c "select 1"` sooner or later, and the right outcome is an error, not a
398 lookup for a relation named `select 1`. `--path` also leaves `-c` free to mean what it
399 means, if a later milestone wants `--catalog` and a query in one invocation.
400
401 **Nor a value on `--catalog` itself** (Ted's question, taken after PR 9). `--catalog PATH`
402 reads better and costs two tokens fewer, but click takes an optional value greedily -- the
403 next token, whether or not an `=` is written -- and `CONN_STR` is a variadic positional. So
404 `hsql --catalog mydb.db` would read the file as a catalog path against an in-memory
405 database, which is the `hsql catalog`-versus-a-file-named-`catalog` ambiguity in a different
406 spelling, and it would need the rule §3.1 exists to avoid. With `--path`, `CONN_STR` stays
407 free to sit anywhere on the line and `hsql --catalog mydb.db` lists what is in `mydb.db`.
408 `--find` composes either way: `--path` is the scope for it too (§3.8).
409
410 **Which mode needs what**, because this is the table that keeps §3's second rule true:
411
412 | mode | adapter import | connection | notable import |
413 | --- | --- | --- | --- |
414 | (none — run SQL) | one | yes | — |
415 | `--catalog`, `--find` | one | yes | — |
416 | `--info` | all, for capability flags; one under `-a` | **no** | — |
417 | `--spec` | all, or one under `-a` | no | — |
418 | `--config show/validate/schema` | all, for adapter options | no | — |
419 | `--config init` | one | no | tomlkit |
420
421 `--info` not connecting is a design decision, not an omission: the diagnostic an agent runs
422 when the database is unreachable must not itself require the database. Capability flags come
423 from declarations (§3.4) precisely so that this holds — reading a declaration costs an import
424 of the adapter class, but never a connection.
425
426 `--info` and `--spec` emit JSON documents rather than rows, so `--format` does not apply to
427 them; a caller who sets it explicitly gets the same kind of stderr note `--display-rows`
428 already produces when it cannot reach the chosen format. `--catalog` and `--find` produce
429 rows, and every format applies (§3.3).
430
431 The modes live one module apiece under `harlequin/hsql/modes/`, imported by the callback
432 when that mode is chosen — which is how `--config init`'s tomlkit and `--spec`'s
433 all-adapters import stay off every other invocation.
434
435 ### 3.2 `harlequin.navigate` — one level, and what it cost
436
437 ```python
438 @dataclass(frozen=True)
439 class CatalogPath:
440 segments: tuple[str, ...] # positional; the adapter names the levels
441 glob: str | None = None # a trailing wildcard only
442
443
444 @dataclass
445 class Listing:
446 parent: CatalogItem | None # None at the top level
447 items: list[CatalogItem]
448
449
450 def resolve(connection, path) -> CatalogItem | None: ...
451 def list_children(connection, path) -> Listing: ...
452 ```
453
454 Three things this module owns, and nothing else does:
455
456 **One level, always.** No `--depth`. §1.1 is the argument: recursion's cost depends on the
457 level it starts from, so a single number cannot be safe at every level, and the one place an
458 agent most wants it is the one place it is 403 round trips. An agent that wants a schema's
459 columns asks for one relation at a time, which is what the IDE's own catalog does and what
460 Ted proposed in review. Recursion comes back when an adapter can answer it in one query
461 (§3.8), and it arrives with the capability rather than ahead of it.
462
463 **A trailing glob is sugar; an interior one is a different mode.** `--path analytics.ord*`
464 filters one resolved parent's children in the client and stays one round trip.
465 `--path *.orders` cannot be evaluated without fetching every candidate level, so it belongs
466 to `--find` (§3.8) and is refused here rather than quietly walked.
467
468 **Quoting is this syntax's own, not a database's.** A segment holding a dot, a quote or a
469 wildcard is written in double quotes on every adapter -- not MySQL's backticks or SQL
470 Server's brackets, since accepting those would make a label that *contains* one unreachable,
471 and a path an agent copies out of a listing would then depend on which adapter wrote it. A
472 path is `spell()`'s output, and the `path` column of a listing is where a caller gets one.
473
474 There is nothing to instrument, either. An earlier draft had `--stats` report `round_trips`,
475 which existed to make a recursive walk's cost visible after the fact; without recursion the
476 number is `len(path) + 1` and a caller can read it off the path they typed.
477
478 There is no node budget, because there is nothing left to bound: one level is one round
479 trip, and a listing with four hundred rows in it is a *display* problem that M1 already
480 solved. `--display-rows` caps what a text layout prints and the footer says `(40 of 400
481 rows)`, exactly as it does for a query.
482
483 The one field this needs on the contract:
484
485 ```python
486 @dataclass
487 class CatalogItem:
488 ...
489 type_name: str | None = None # the adapter's own full type, e.g. DECIMAL(18,2)
490 ```
491
492 It defaults to None and is populated in-tree from data the adapters already fetch (§1.3). A
493 listing prints it beside `type_label` rather than instead of it, so an adapter that never
494 adopts the field degrades to today's short label rather than to a blank column.
495
496 *One caveat for adapter authors:* `CatalogItem` is a dataclass and its subclasses append
497 fields, so a new base field shifts positional argument order for subclass constructors.
498 Every in-tree call site uses keywords (`from_parent(...)`), and the adapter template does
499 too, but the changelog entry should say so.
500
501 ### 3.3 Catalog listings are result sets, so the output layer is already written
502
503 A listing is rows: `path`, `name`, `type`, `type_name`, `query_name`. Making it a
504 `ResultSet` — `create_backend()` takes a sequence of rows and the column names, with no
505 database involved — means `--catalog` inherits `--format csv|json|jsonl|markdown|table|
506 vertical|parquet`, `-o PATH`, `-t/-A/--no-header`, `--display-rows` and the byte-for-byte
507 determinism M1's snapshots already pin. The alternative is a second renderer for the same
508 job, which is how `--format json` and a catalog's JSON end up disagreeing about how to spell
509 null.
510
511 **And no new layouts.** An earlier draft added `compact` and `tree`; both are out.
512
513 `tree` had nothing to draw: one level is a flat list of children, not a tree. And `compact`
514 — `analytics.orders(id BIGINT, customer_id BIGINT, total DECIMAL(18,2))` — only reads that
515 way for a relation and its columns. §1.2 is the reason it can't generalize: what a level
516 *is* belongs to the adapter, so `parent(child TYPE, …)` would render a database's schemas
517 as `mydb(analytics sch, main sch)`, which is a format pretending to a structure the catalog
518 does not promise. The token efficiency it was after is already available over the same rows
519 — `hsql --catalog --path analytics.orders -tA --format csv` is names and types and nothing
520 else — and it stays honest at every level, because a row is just a row.
521
522 One change in `query.py` makes this cheap: **`text_columns()` returns string data
523 unchanged.** Today every text layout casts through duckdb, which is right for query results
524 (§3.3 of the M1 plan) and pointless for a listing that is already strings — and it would
525 import duckdb (~85ms) on a `hsql -a postgres --catalog` that has no other reason to. The
526 short-circuit is one type check, and it is also a small win for `select` results that are
527 all VARCHAR.
528
529 **`query_name`, always.** Adapters already compute the correctly quoted identifier for every
530 item; emitting it means the agent never guesses whether this backend wants `"Orders"` or
531 `` `orders` ``. It costs nothing and no other client does it.
532
533 **Describing a relation is listing it.** `--catalog --path mydb.analytics.orders` is the
534 columns of `orders`, with their names, types and quoted identifiers — which is everything a
535 `describe` was going to print. There is no second mode for it (§7).
536
537 ### 3.4 Capabilities are declared, not detected
538
539 ```python
540 class HarlequinAdapter(ABC):
541 IMPLEMENTS_CANCEL = False # exists
542 IMPLEMENTS_READ_ONLY = False # new: connect() honors read_only=True
543 IMPLEMENTS_VALIDATE_SQL = False # new: the connection's validate_sql() is real
544 IMPLEMENTS_CATALOG_SEARCH = False # new: search_catalog() (§3.8)
545 ```
546
547 Declarations rather than reflection, because reflection cannot answer the question: SQLite
548 defines `validate_sql` and raises `NotImplementedError` from it (§1.4). The app already
549 handles that at the call site, so nothing is broken today — but an adapter that *says* what
550 it does is the better pattern, and it is the only one `--info` can read without connecting.
551
552 Two consequences worth stating:
553
554 - **A flag whose capability is undeclared refuses, before connecting.** `hsql --read-only -a
555 postgres` exits 2 with `postgres does not declare read-only support; see hsql --info` —
556 rather than connecting, running the query, and hoping. Refusing early is the entire point
557 of the flag: `--read-only` exists so a human can hand over a credential, and a flag that
558 no-ops is worse than one that is absent.
559 - **Core still catches `NotImplementedError` at the call site**, as the app does. A
560 declaration can be wrong, and the failure should be a clear error rather than a traceback.
561
562 `IMPLEMENTS_VALIDATE_SQL` has no consumer in `hsql` now that `--dry-run` is cut (§7). It is
563 still worth declaring: `--info` reports it, and the app can consult it instead of calling a
564 method it expects to raise.
565
566 `hsql --info` reports, per installed adapter: name, distribution, version, declared
567 capabilities, and whether the adapter imported at all. Plus Harlequin's version, Python's,
568 the platform, the discovered config files **in precedence order**, and the active profile
569 with every secret redacted (§3.7).
570
571 It opens no connection, but it does import: capabilities are class variables, so reading
572 them means loading the adapter class. That is the one cost this mode pays — 309ms for four
573 installed adapters, against 51ms for names and versions alone (§1.4) — and it is the right
574 trade for a once-per-task lookup whose entire job is that the agent stops guessing.
575 `hsql --info -a duckdb` imports one (114ms) for the common case of asking about the adapter
576 you are using, and an adapter that fails to import is reported with its capabilities as
577 `"unknown"` and the import error alongside — never as `false`, because guessing false about
578 `implements_read_only` is the direction that gets someone hurt.
579
580 ### 3.5 Config: validate each file, then merge, with provenance
581
582 **Validation moves in front of the merge** (Ted's call). Today `load_config()` merges every
583 discovered file into one dict and then calls `_raise_on_bad_schema()` on the result, which is
584 backwards twice over: the error can only name a key, never the file it came from, and the
585 thing being validated is a structure no user wrote. Validating each file as it is read means
586 every message can say *which file* and *which key*, and the merge then only ever combines
587 inputs already known to be well-formed.
588
589 ```python
590 def load_config(config_path: Path | None) -> Config:
591 return merge([validate(ConfigFile(p)) for p in _find_config_files(config_path)])
592 ```
593
594 That reordering is free, and it is most of what makes `--config validate` worth having.
595
596 **The merge becomes per profile, and files are read nearest first** (§1.6; amended in PR 1,
597 Ted's call). `profiles` merges per profile name and `keymaps` per keymap name, and the
598 nearest file that defines one supplies it whole. An earlier draft of this section had a
599 profile merge per *option* as well; that is what PR 1 traded away, because it is
600 incompatible with the early stop below — a profile's keys are not known to be complete until
601 every file has been read, so per-option merging means no file can ever be skipped. Half a
602 connection from each of two files is also not a connection either of them describes.
603
604 This is a behavior change for both commands and a bug fix for a failure mode that is worse
605 than losing a profile: before it, a project-local file that names one profile, plus a home
606 file that sets `default_profile`, makes both commands refuse to start. It gets a Bug Fixes
607 changelog entry and a test that pins the new semantics against both files.
608
609 **Discovery is reversed, and the profile read path stops early** (Ted's call, PR 1).
610 `_find_config_files()` returns candidates highest priority first, so the first definition of
611 anything is the winning one, and `load_profile()` — the read path `hsql` uses when it
612 want a profile and not the keymaps beside it — returns at the file that defines it. The
613 files behind that one are never opened, parsed or validated. `-P None` reads nothing at all.
614 `load_config()` is the whole document, for `--config show` and the IDE's keymaps, and has no
615 reason to stop.
616
617 Resolving a name is separated from reading the document in the same PR, because otherwise the
618 two commands disagree about a config file neither of them is using: a `default_profile` that
619 names no profile is raised where the name is *used*, so `-P other` and `-P None` start rather
620 than being refused over a key they overrode. What remains is the honest half of the
621 difference — `hsql` cannot report a problem in a file it stopped before opening — and
622 `--config validate` (PR 3) is the mode that reads everything and reports everything. Measured with four candidate files present, the skipped reads pay for most
623 of msgspec's import: with four candidate files present, `hsql -c "select 1"` and `hsql --help`
624 are both within noise of the pre-PR-1 command (±3ms), and so is a run that finds exactly one
625 config file.
626
627 **Validation itself runs in two passes, and the second one is new ground** (Ted's design).
628 Pass 1 validates what core owns, per file, before the merge: the top-level keys, the shape
629 of `profiles` and `keymaps`, and the profile keys with meaning to `harlequin` or `hsql`. It
630 cannot reject what it does not recognize, because every adapter's options live in the same
631 table.
632
633 Pass 2 is what makes that safe. Once the adapter is known — which the first pass already
634 settles, and `load_adapter()` has already imported for the run about to happen — its
635 `ADAPTER_OPTIONS` say exactly which further keys are legal, so the selected profile can be
636 validated in full:
637
638 ```python
639 declared = {sluggify(o.name) for o in adapter_cls.ADAPTER_OPTIONS}
640 allowed = core_keys | TUI_ONLY_KEYS | declared
641 ```
642
643 **This validates a surface nothing validates today** (§1.5): `reed_only = true` in a profile
644 is silently discarded by the adapter's `**kwargs`, and the user believes they are connected
645 read-only. Pass 2 is the only place in the stack that knows both the profile and the
646 adapter's declared options, so it is the only place that can say `unknown option 'reed_only'
647 for adapter duckdb; did you mean 'read_only'?`
648
649 Two things bound how strict it can be:
650
651 - **"Valid" is a union of three sets** — core keys, `TUI_ONLY_KEYS` (a profile written for
652 the IDE has to work headlessly), and the adapter's declared options. Get the union wrong
653 and configs that work today start failing, so each set gets a test.
654 - **Values may legitimately arrive uncast.** `adapter.py` tells adapters to "check the types
655 of options, as they may not be cast to the correct types", and TOML gives us whatever the
656 user typed — `port = 5432` and `port = "5432"` both work today and must keep working. So
657 pass 2 checks **names and declared choices**, which is where the value is, and stays
658 permissive about scalar types.
659
660 Which mode validates what follows from the passes: the run path validates the one selected
661 profile, with the one adapter it was going to import anyway, while `--config validate`
662 validates every profile and imports each adapter its profiles name — 309ms for four (§1.4),
663 which is the right trade for the mode whose whole job is to check.
664
665 **On declaring the schema as a model rather than hand-rolling it.** Pydantic, msgspec and
666 cattrs were all measured against a Harlequin-shaped config; the numbers and the facts that
667 decide it are in §6.1. The short version: **Pydantic costs +135ms on every invocation and so
668 fails on the axis it was proposed to improve**, cattrs cannot generate the JSON Schema this
669 section needs, and **msgspec is the one that pays for itself** at +37ms — strict where it
670 matters, and `msgspec.defstruct()` builds pass 2's per-adapter struct in 0.022ms, which is
671 what makes the two-pass design declarative rather than another hand-written loop. Ted is
672 leaning toward msgspec; §6.1 records what would reverse that, and PR 1 is where it becomes
673 real.
674
675 Provenance falls out of doing the merge properly:
676
677 ```python
678 @dataclass(frozen=True)
679 class Provenance:
680 value: Any
681 path: Path # which file this key's winning value came from
682 overrode: list[Path]
683 ```
684
685 `--config show` prints the effective config with a `# from ~/.harlequin.toml` per key, and
686 `--config show --json` emits the same as `{key: {value, from, overridden_by}}`. That is the
687 single best troubleshooting artifact in the plan, and it is also how a human discovers which
688 file is winning.
689
690 **`--config list-profiles`** (Ted's call) prints the names of every profile found, which is
691 the question a human actually asks first — *what can I pass to `-P`* — and the one `show`
692 answers only by making them read a merged document. It is rows, so `-tA` gives a bare list a
693 shell loop can consume, and it marks which profile is the default. It is also the mode that
694 would have made #1040 obvious: a profile that a project-local file quietly displaced is a
695 name missing from a short list.
696
697 **`${VAR}` and `${VAR:-default}`** (Ted's call), resolved on read, over every string value
698 in a profile, recursively through arrays and tables:
699
700 - A bare `{` never triggers anything, which is Ted's constraint on #898: nothing anyone has
701 in a password today needs escaping. `$${` is the escape for a literal `${`.
702 - An unset variable with no default is a `HarlequinConfigError` naming the variable *and the
703 file it appears in* — exit 2, never an empty string. A password that silently becomes `""`
704 is an authentication error three layers away from its cause.
705 - **Resolution happens on the read path only.** `ConfigFile.relevant_config` stays raw,
706 because `config_wizard` reads it and writes it back (§1.6): interpolating there would bake
707 a resolved secret into the user's file on their next `harlequin --config`. This is the one
708 place where getting the layering wrong writes a plaintext password to disk, so it gets its
709 own test.
710 - **Amended in PR 16: the read path is where a profile is *selected*, not where a file is
711 read.** Resolving each file as it was read would have refused an invocation over a variable
712 named in a profile it was not running — and the IDE reads every discovered file for its
713 keymaps, so one `${MYPASSWORD}` in a home config would have stopped `harlequin` from
714 starting under any profile. Resolving in `_select_profile()` instead is the rule
715 `default_profile` already follows (a name is raised where it is *used*), and it costs the
716 merge's `Provenance` — once every file is merged, that is the only thing that still knows
717 which file a profile was written in, which an unset variable's message has to name. Two
718 consequences worth writing down: `--config show` and the IDE's debug
719 screen report what the files say, so they print `${MYPASSWORD}` rather than resolving it —
720 which is also the reading that keeps an unset variable from breaking a report *about* the
721 file naming it — and `default_profile` and the `keymaps` tables are not interpolated at all,
722 which nothing needs and which is what buys the laziness. `--config validate` resolves every
723 profile in every file, and reports an unset variable like any other problem.
724 - Shell-command interpolation (asked for on #898) is out: it is arbitrary code execution
725 driven by a file discovered from the working directory.
726
727 **`--config validate`** reports `{file, key_path, message, line?}` per problem — one entry
728 per file per problem, which is what validating before merging buys. Line numbers only where
729 the parser gives one: `tomllib` puts a line in its parse-error message, and neither parser
730 reports positions for a key we merely dislike. Saying "line unknown" is better than a made-up
731 number and better than not shipping the mode.
732
733 **`--config schema`** generates a JSON Schema for `.harlequin.toml` from the config model
734 plus the installed adapters' options — which is why `AbstractOption.to_dict()` (§1.5, §3.7)
735 has to land first — so it is locally accurate: it knows this machine has
736 `harlequin-databricks` and what its options are. With a declared model this is
737 `msgspec.json.schema()` plus the adapter options grafted on; hand-rolled, it is a small
738 generator over the same two sources. A static base schema also ships in the
739 package, at `harlequin/schemas/config-v1.json`, for the site to publish at
740 `https://harlequin.sh/schemas/config/v1.json` — that publication is a `harlequin-web` PR,
741 outside this repo.
742
743 **`--config init`** writes a profile through the existing `ConfigFile` tomlkit path, so
744 comments and key order survive, taking `--profile NAME`, `--adapter`, and the adapter's own
745 options as flags. It imports no questionary — the wizard stays exactly where it is, and each
746 command gets the affordance right for its audience. It is also the exact counterpart of
747 `harlequin --config`, which is the argument for spelling the modes as options in the first
748 place.
749
750 ### 3.6 Safety: read-only and timeout
751
752 **`--read-only`** is a `read_only` argument on `HarlequinAdapter.__init__`, passed by both
753 commands, and refused before connecting when `IMPLEMENTS_READ_ONLY` is false (§3.4). An
754 option of that name in the bag handed to the adapter would have worked in-tree, but only
755 because DuckDB and SQLite each declare an option called `read-only` — a convention rather
756 than a contract, and the same convention §1.8 rules out for the adapters that declare
757 nothing (amended in PR 13, Ted's call). So the two in-tree adapters drop their own
758 `read-only` options and take the argument, and `--read-only` is a core flag on `harlequin`
759 as well as `hsql`. Out-of-tree adapters are a long tail, and `hsql --info` is what makes the
760 tail legible.
761
762 **`--timeout SECONDS`** is a wall clock over the whole run — execute *and* fetch, because
763 DuckDB executes lazily and the work happens in `fetchall()` (§1.9):
764
765 1. Refuse at parse time if `IMPLEMENTS_CANCEL` is false. There is no way to stop the work
766 otherwise, and a timeout that can only lie about having stopped it is worse than no flag.
767 2. Run the statements on a worker thread; the main thread waits on the deadline.
768 3. On expiry: `connection.cancel()`, then join for a short grace period.
769 4. **`hsql` attributes the cancellation itself.** The result set that comes back after a
770 cancel is empty and error-free (§1.9), so it is discarded rather than printed, the
771 diagnostic is `hsql: error: timed out after 30s`, and the exit code is 4 — the number
772 `ExitCode.TIMEOUT` has been reserving since M1.
773 5. If the grace period expires too, flush both streams and `os._exit(ExitCode.TIMEOUT)`.
774 Plain `sys.exit` with a live worker inside DuckDB aborts the interpreter and exits 134
775 (§1.9), which would be a documented-exit-code violation caused by the flag that exists to
776 make failure legible.
777
778 `SIGINT` takes the same path and exits 130, which it already does.
779
780 **It bounds `--catalog` and `--catalog-search` as well as a run** (amended in PR 14). Both
781 connect and both wait on the database, and this repo's own rule about a flag that silently
782 does nothing (`report_limit_ignored`, `report_row_cap_ignored`) applies hardest to the one
783 flag whose job is safety. It is the same wrapper around the mode's report call; the modes that
784 report on files or on the installation connect to nothing and are left alone, as `--read-only`
785 leaves them.
786
787 **hsql's `--timeout` collides with the SQLite adapter's own `timeout`, and the adapter's is
788 renamed** (amended in PR 14). §3.4's rule says an adapter option that collides with one of
789 hsql's flags loses the spelling -- which is right for the out-of-tree tail and wrong to leave
790 in place for an adapter we ship: sqlite's option is how long to wait for a *locked table*, and
791 losing it would cost a real setting and silently reread a profile's `timeout` as a deadline. So
792 it becomes `lock-timeout`, which is what it does, exactly as PR 13 renamed `connection_mode` to
793 `mode`. Breaking, and one line of the changelog.
794
795 `--single-transaction` is cut (§7): transaction modes are named by each adapter and default
796 to undefined behavior, so core cannot drive them generically, and a caller who wants one
797 transaction can write `begin` and `commit` in the script they are already sending.
798
799 ### 3.7 `harlequin.redact` — the helpers, and what tells them what to hide
800
801 ```python
802 def redact_profile(profile: Profile, options: Sequence[AbstractOption]) -> Profile: ...
803 def redact_conn_str(conn_str: Sequence[str]) -> list[str]: ...
804 def redact_text(text: str, secrets: Container[str]) -> str: ...
805 ```
806
807 Redaction helpers, and nothing else — *what* to hide is not a list kept here. It is a
808 declaration on the option itself: `AbstractOption` gains `secret: bool = False`, as a class
809 attribute *and* a keyword, so a third-party subclass that has never passed it still answers
810 False rather than raising. That is the whole point of doing it declaratively — core cannot
811 enumerate every adapter's secret (`--service-account-key`, `--token`, `--tls-key`, whatever
812 the next adapter invents), but each adapter can declare its own once and every consumer gets
813 it free: `to_dict()` reports it, which is what teaches an agent not to construct
814 `hsql --password hunter2`; `to_questionary()` masks the input; and `--info`, `--spec`,
815 `--config show` and error rendering all route through `redact_profile`.
816
817 Two things the declaration cannot cover, both with a helper of their own above:
818
819 - **Connection strings are positional**, so no option type describes
820 `postgres://user:pw@host/db`. `redact_conn_str` is DSN-aware — and
821 [#354](https://github.com/tconbeer/harlequin/issues/354) is evidence people really do put
822 passwords there.
823 - **A driver exception that echoes a DSN** does not pass through our option layer, so
824 `redact_text` is the backstop applied to error messages before they are printed.
825
826 **`hsql` never prompts, and adds no new channel for a password either.** A prompt that blocks
827 on stdin is the worst failure mode for an agent — no output, no exit code, the whole turn
828 burned until something times out — so a secret an invocation needs and cannot find is a
829 fast failure naming the profile or the driver's own environment variable. An earlier draft
830 added `--password-stdin`; it is out (§7). Between profiles, `${VAR}` interpolation (§3.5) and
831 the variables the drivers already read (`PGPASSWORD`, a pgpass file, and each adapter's
832 equivalent), there is no gap it would fill that is worth a flag whose whole job is to consume
833 the stream `-f -` also wants.
834
835 What this milestone contributes to #667 is the declaration and the redaction that follow from
836 it. The interactive prompt belongs to `harlequin`, and is not here.
837
838 ### 3.8 `--find`, and the capability recursion is waiting for
839
840 `--find` is what an agent actually needs — *where does `orders` live*, *which tables have a
841 `customer_id`* — and it cannot be a walk. It wants an optional capability:
842
843 ```python
844 class HarlequinConnection:
845 def search_catalog(
846 self, term: str, kind: Literal["tables", "columns", "all"]
847 ) -> list[CatalogItem]: ... # raises NotImplementedError
848 ```
849
850 One `information_schema`-style query where the adapter can serve it, an explicit "not
851 supported by this adapter, try `--catalog`" where it can't, surfaced through
852 `IMPLEMENTS_CATALOG_SEARCH` in `--info`.
853
854 `fetch_descendants(depth)` on `InteractiveCatalogItem`, defaulting to a `fetch_children`
855 walk, is the same bet at the other end, and it is **the precondition for recursion ever
856 coming back** (§3.2): it is what turns §1.1's 403 round trips into one for an adapter that
857 can express the whole level in a single query, and it improves the IDE's expand-all path
858 too. A `--depth` flag on top of a walking default would just be the cliff again with a
859 prettier name, which is why it waits for this rather than shipping beside it.
860
861 *On the other idea from review — concurrency.* Opening several connections to parallelize a
862 recursive walk would help wall-clock time and nothing else, and it costs more than it looks:
863 the adapter contract says nothing about a connection being usable from two threads, nor does
864 it offer a way to open a second one from an existing connection, so `hsql` would have to
865 re-`connect()` (re-authenticating N times) and hope. It also multiplies load on the database
866 for a call the agent should not be making in bulk. Worth revisiting if `fetch_descendants`
867 lands and is still too slow; not worth it as the first answer.
868
869 ---
870
871 ## 4. Sequencing
872
873 Three releases, **config and self-description first** (Ted's call). That group fixes bugs
874 that exist today — the merge in #1040, and error messages that can't name the file they came
875 from — and needs no adapter change at all, so it can ship while the catalog's contract
876 addition is still being rolled out. The catalog follows, with search implemented for both
877 in-tree adapters rather than left as a stretch. Safety is last, because it is the only group
878 whose flags are false on most adapters until the ecosystem catches up.
879
880 **PRs 15 and 16 were pulled forward into Release A** (Ted's call, taken after PR 7). They are
881 the two that never needed the rest of Release C: neither declares a capability, so neither
882 waits on the ecosystem. They belong with the self-description modes instead — the whole of
883 what `--config show`, `--info` and `--spec` do is print a user's own config back, and the
884 release that adds three ways to print a profile should not be the release before the one that
885 learns which of its values must not be printed. `${VAR}` follows redaction because it is the
886 other half of the same answer: redaction keeps a secret out of Harlequin's output, and
887 interpolation keeps it out of the config file to begin with. They keep their numbers, which
888 the rest of this document refers to; only the release they ship in changed.
889
890 Numbering assumes M1's remaining work releases as 2.9.
891
892 ### Release A — config and self-description (2.10)
893
894 **PR 1 — Validate per file, then merge per profile.** The reordering, the per-profile merge, the
895 second pass over the selected profile's adapter options, and the errors that can finally name
896 a file. This is where msgspec arrives as a dependency, or doesn't. Fixes
897 [#1040](https://github.com/tconbeer/harlequin/issues/1040), which is a hard stop for anyone
898 whose home config sets `default_profile` and who then adds a project-local file. Behavior
899 change, Bug Fixes entry, and the failing case as its test.
900
901 **PR 2 — `--config show` and `--config list-profiles`.** Provenance per key, and the short
902 list of names that answers "what can I pass to `-P`".
903
904 **PR 3 — `--config validate`.** The machine channel over PR 1's per-file diagnostics.
905
906 **PR 4 — `AbstractOption.to_dict()` and `--spec`.** Concrete, never abstract, with a base
907 implementation that works for a subclass that predates it. `--spec` covers hsql's own options
908 and every installed adapter's; `-a NAME` narrows it to one. (It cannot cover `harlequin`'s
909 own flags: `hsql` may not import `harlequin.cli`, which builds the IDE's command. Say so in
910 the output rather than pretending the list is exhaustive.)
911
912 **PR 5 — `--info`.** Versions, platform, discovered config files in precedence order, active
913 profile, and declared capabilities per adapter. No connection.
914
915 **PR 6 — `--config schema` and the packaged base schema.** Depends on PR 4's serialization.
916
917 **PR 7 — `--config init`.** tomlkit deferred; no questionary.
918
919 **PR 15 — Secret options and redaction.** `secret=` on options, `harlequin.redact`, DSN
920 redaction, masked wizard input. Closes #667's structural half. Pulled forward from Release C:
921 every mode Release A adds prints a profile, and this is what decides what they print.
922
923 **PR 16 — `${VAR}` interpolation.** Closes #898. Pulled forward with PR 15 — a caller told to
924 keep a token out of their config file needs the spelling that replaces it in the same release.
925
926 **PR 8 — Docs.** The config spec page, the self-description pages, the site's JSON Schema
927 route, and — arriving with PRs 15 and 16 rather than in PR 17 — the secrets guidance and the
928 `${VAR}` spelling.
929
930 *If the model question in §3.5 resolves toward `msgspec`, it lands in PR 1 — the declaration
931 is what PR 1's validation and PR 6's schema both read, and retrofitting it later means
932 writing both twice.*
933
934 ### Release B — the catalog (2.11)
935
936 **PR 9 — Mode options, and `--catalog` at one level.** The mode flags and their mutual
937 exclusion, `--path`, and which modes attach adapter options. `harlequin.navigate` with path
938 resolution and single-level listing. Listings as result sets, `query_name` included, and the
939 `text_columns()` string short-circuit that keeps duckdb out of a Postgres catalog call.
940 Guard: `hsql --help` still imports no adapter, and is still ~90ms.
941
942 **PR 10 — Real type names.** `CatalogItem.type_name` on the contract, populated by the DuckDB
943 and SQLite adapters from data they already fetch. This is the PR that makes a listing say
944 `total DECIMAL(18,2)` instead of `total #.#`.
945
946 **PR 11 — `--find`.** `IMPLEMENTS_CATALOG_SEARCH` and `search_catalog()` on the connection,
947 **implemented for DuckDB and SQLite** rather than declared and left to the ecosystem;
948 explicit refusal on adapters that don't declare it.
949
950 **PR 12 — Docs.** Catalog and Introspection in the "Headless & Agents" topic (a
951 `harlequin-web` PR), plus the adapter-author note for `type_name` and `search_catalog()`.
952
953 ### Release C — safety (2.12)
954
955 **PR 13 — Capability declarations and `--read-only`.** `IMPLEMENTS_READ_ONLY` and
956 `IMPLEMENTS_VALIDATE_SQL` on the contract, declared by both in-tree adapters, reported by
957 `--info`, and refused where undeclared. Companion issues filed against the out-of-tree
958 adapters we maintain.
959
960 **PR 14 — `--timeout`.** The deadline, the cancel, the grace period, the `os._exit`, and the
961 attribution that keeps a cancelled query from printing as an empty one.
962
963 *PRs 15 and 16 shipped in Release A — see there.*
964
965 **PR 17 — Docs.** Safety page and the psql differences table. The secrets guidance went with
966 PR 8, alongside the release that shipped it.
967
968 **Ordering rationale.** Within each release the contract change lands with the first consumer
969 that needs it, as in M1 — a field nothing reads is a field nobody notices is wrong. Across
970 releases: fix what is broken before adding what is new, and let nothing that needs an
971 ecosystem rollout block anything that doesn't.
972
973 ---
974
975 ## 5. Testing
976
977 The M1 guards stay and grow; the new ones are the same kind — deterministic, and failing
978 identically on every machine.
979
980 - **Import hygiene, extended per mode.** `hsql -c "select 1"` imports no `tomlkit`, no
981 `questionary` and (still) no `sqlfmt`; `hsql --help` imports no adapter; `hsql -a sqlite
982 --catalog` imports no `duckdb`. Each is a subprocess reading `sys.modules`, and each
983 deferral has a matching `ignore_imports` entry with a comment at the import site.
984 - **A fake adapter that declares nothing** proves every refusal path: `--read-only`,
985 `--timeout` and `--find` each exit 2 with a message naming the adapter, before any
986 connection is opened.
987 - **Golden files** for `--catalog`, `--info`, `--spec` and `--config show` in
988 every format they support, as syrupy snapshots alongside the M1 output snapshots. Fixtures
989 with unicode labels, a zero-child node, and an adapter that populates no `type_name` — the
990 degradation path is the one nobody exercises.
991 - **Redaction is asserted negatively and exhaustively**: for a profile with a secret in an
992 option *and* in a connection string, the secret's literal value appears in no byte of
993 `--info`, `--spec`, `--config show`, any error message, or `--stats`.
994 - **Interpolation**: `${VAR}`, `${VAR:-default}`, `$${` as a literal, an unset variable
995 exiting 2 and naming both the variable and the file, and — after PR 16's amendment above —
996 a profile the invocation is *not* running being left alone. The one that matters most is
997 that `harlequin --config` on a file containing `${MYPASSWORD}` writes `${MYPASSWORD}` back.
998 - **The merge fix gets the failing case as its test**: a home file with `default_profile` and
999 two profiles, a cwd file with a third, asserting all three survive and the default still
1000 resolves. That combination raises `HarlequinConfigError` on `main` today.
1001 - **Timeout tests use a fake adapter, not a slow query**: `execute` blocks on an event,
1002 `cancel` sets it. Deterministic, fast, and it exercises the attribution logic, which is the
1003 part that would otherwise be tested by accident. One integration test against DuckDB covers
1004 the real interrupt path, marked slow.
1005 - **A listing is as deterministic as a result set**: identical bytes whether stdout is a
1006 pipe, a file or a pty, `\n` on every platform, and unaffected by `LC_ALL` — the M1
1007 properties, now over rows that never went through a database.
1008 - **Pass 2's allowed set is asserted per source**: a core key, a `TUI_ONLY_KEYS` key and a
1009 declared adapter option are each accepted in a profile, and a misspelling of one is
1010 rejected naming the adapter — with `port = 5432` and `port = "5432"` both still accepted,
1011 since the adapter contract promises values may arrive uncast.
1012 - **The merge fix is asserted per profile, not just per table**: a profile defined in two
1013 files is the nearer file's, whole, and the profiles only the farther file defines survive
1014 beside it — which is the half of "later wins" that a table-level replace gets wrong.
1015 - **Early stopping is asserted with an unreadable file**: a home file containing invalid
1016 TOML, and a cwd file defining the wanted profile. A file that is opened at all takes the
1017 test down with it, which is a guard that cannot pass by accident.
1018
1019 Not tested, because it was dropped from M1: an agent eval suite. §13 of the product plan
1020 calls it the metric that actually matters, and M2 widens the surface an agent has to choose
1021 from. If it comes back, `--spec` is what makes it cheap to write, and Release B is where it
1022 would land.
1023
1024 ---
1025
1026 ## 6. Decisions
1027
1028 **Settled.**
1029
1030 - *Modes are options, not subcommands* (Ted's call, §3.1) — consistent with
1031 `harlequin --config`, and no verb-versus-conn_str ambiguity to adjudicate.
1032 - *The catalog path is `--path`*, not a reused `-c` and not a value on `--catalog` itself
1033 (§3.1). `-c` would mean SQL in one invocation and an identifier in another; `--catalog
1034 PATH` would take its value greedily and read `hsql --catalog mydb.db` as a path against an
1035 in-memory database.
1036 - *One level, no `--depth`, no node budget* (§3.2). Recursion returns with
1037 `fetch_descendants()`, which is what would make it one round trip instead of 403.
1038 - *No `child_count` field* (§1.3). A count is only knowable by fetching, and `len(children)`
1039 after a listing is the honest version of it.
1040 - *Three releases, config and self-description first* (Ted's call, §4) — they fix existing
1041 bugs and need no adapter change; then the catalog, with search implemented for both
1042 in-tree adapters; then safety.
1043 - *Secrets and `${VAR}` ship in Release A, not Release C* (Ted's call, §4, taken after PR 7).
1044 They declare no capability, so nothing in them waits on the ecosystem, and the release that
1045 adds three modes for printing a profile is the one that has to know what not to print.
1046 - *No `--describe`* (Ted's call, §7). `--catalog --path db.schema.relation` is a describe.
1047 - *No new layouts* (Ted's call, §3.3). `tree` has no tree to draw over one level, and
1048 `compact` only reads as `parent(child TYPE, …)` for a relation and its columns, which §1.2
1049 says is not a shape the catalog contract promises.
1050 - *No round-trip counting* (Ted's call, §3.2). Without recursion the number is `len(path) +
1051 1`, which a caller can read off the path they typed.
1052 - *Validation runs in two passes* (Ted's design, §3.5): per file ahead of the merge for the
1053 keys core owns, so an error can name the file it came from, and then the selected profile
1054 against the adapter's declared options — which catches a misspelled adapter option that
1055 today is discarded in silence (§1.5).
1056 - *`--config list-profiles`* (Ted's call, §3.5).
1057 - *`--read-only` is a declared capability and refuses when it is absent* (Ted's call, §3.4).
1058 The flag works on two of fifteen adapters on the day it ships, and says so on the other
1059 thirteen instead of quietly not working.
1060 - *No `--single-transaction`, no `--password-stdin`* (Ted's call, §7).
1061 - *Secrets: declare and redact* (Ted's call, §3.7). No prompt in `hsql`, ever, and no new
1062 input channel; the IDE's interactive prompt is not in this milestone.
1063 - *`${VAR}` and `${VAR:-default}`* (Ted's call, §3.5), resolved on the read path only, with
1064 an unset variable an error rather than an empty string.
1065 - *Catalog listings are result sets*, so M2 adds no output subsystem at all (§3.3).
1066 - *Capabilities are declared, not detected* — reflection cannot tell a real implementation
1067 from a raising stub (§1.4).
1068 - *`--info` does not connect*, and `--spec` and `--config` do not either (§3.1).
1069 - *No `fmt`, no `--dry-run`* (Ted's call, §7).
1070 - *No shell-command interpolation* in config values (§3.5).
1071
1072 - *Config files are read nearest first, and the profile read path stops at the file that
1073 defines what it was asked for* (Ted's call, §3.5). The cost of that is per-option merging
1074 within a profile, which PR 1 gave up to get it: a profile is the nearest file's, whole.
1075 - *The config is declared as msgspec models* (settled in PR 1, §3.5 and §6.1). `Config` is
1076 the TypedDict *and* the model, so there is one declaration of what a config file may say
1077 and `msgspec.convert(raw, Config)` is the whole of pass 1; pass 2 builds a struct from the
1078 adapter's own `ADAPTER_OPTIONS` and parses the profile into it, so an option arrives as the
1079 type its adapter declared. `Config` is a `Struct` with `forbid_unknown_fields`, so msgspec
1080 refuses a key nobody declared and the import is module-scope: ~13ms on an invocation that
1081 finds no config file at all, and within noise of `main` on one that finds any, because the
1082 files early stopping skips pay for it. One thing is still written by hand, because the
1083 message is the point: the near miss on a key -- `read-only`, `reed_only`, `keymap_names` --
1084 which is where `difflib` says *did you mean `read_only`*, computed only once a conversion
1085 has already failed.
1086
1087 **Still open.**
1088
1089 - Nothing from PR 1. §6.1's reversal conditions — the import cost mattering more once
1090 `--info` and `--spec` are real, or wanting Pydantic's `extra="allow"` — are still the
1091 things that would reopen it.
1092
1093 ### 6.1 The config model, measured
1094
1095 Three libraries were suggested or considered for declaring `Config`/`Profile` rather than
1096 hand-rolling `_raise_on_bad_schema()`. All of them were run against a Harlequin-shaped
1097 config on this checkout, because the deciding facts are not the ones the READMEs lead with.
1098
1099 | | Pydantic 2.13 | msgspec 0.21 | cattrs 26.1 | hand-rolled |
1100 | --- | --- | --- | --- | --- |
1101 | cost on **every** invocation | +135ms | +37ms | +63ms | 0 |
1102 | new runtime dependencies | pydantic, pydantic-core | msgspec (C ext) | attrs, cattrs, exceptiongroup (3.10) | none |
1103 | unknown keys — i.e. adapter options | preserved (`extra="allow"`) | **dropped** | **dropped** | n/a |
1104 | `limit = true` | coerced to `1` | rejected | coerced to `1` | rejected today |
1105 | `limit = "500"` | coerced to `500` | rejected | coerced to `500` | rejected today |
1106 | error carries a path | yes | in the message | via `transform_error()` | ours to write |
1107 | generates JSON Schema | yes | yes | **no** | ours to write |
1108
1109 Four things decide it, and none is the headline benchmark:
1110
1111 - **The cost is model *construction*, not import, and config is read on every invocation of
1112 both commands.** Pydantic builds a core schema per model at class-definition time, so its
1113 135ms lands on `hsql -c "select 1"` — 257ms today — taking it to roughly 390ms, past the
1114 300ms the product plan tracks in CI. There is no lazy way out, because the read path *is*
1115 the validating path. Pydantic is a no on the one axis it was proposed to improve.
1116 - **Adapter options are unknown keys, and two of the three eat them.** A `Profile` model with
1117 declared fields turns `{"adapter": "postgres", "dbname": "warehouse"}` into a profile with
1118 no `dbname`, which is the value the adapter needed. msgspec and cattrs both drop unknown
1119 keys (their only alternative is to *reject* them), so under either, `profiles` stays
1120 `dict[str, dict[str, Any]]` with a model validating the keys core owns and the raw dict
1121 carried alongside. Only Pydantic's `extra="allow"` preserves them — the one place it is
1122 genuinely the better tool.
1123 - **Two of the three would reintroduce a bug we already guard.** `limit = true` structures to
1124 `1` under Pydantic and cattrs. `parse_row_count()` rejects it today, with a comment saying
1125 why: a bool is an int in Python, and `true` is not one row. msgspec is strict and rejects
1126 it, which is the behavior we want and currently hand-write.
1127 - **cattrs cannot generate the schema**, and `--config schema` is the deliverable that would
1128 most justify declaring a model at all. It is also the most expensive of the two viable
1129 options. Its advantages — pure Python, so no wheel per Python version, and a very stable
1130 ecosystem — do not pay for that here.
1131
1132 **The two-pass design changes the conclusion, and is the reason to take msgspec.** An earlier
1133 draft of this section recommended staying hand-rolled, on the grounds that a model would
1134 replace less code than it looked — the adapter-options tail would stay hand-validated
1135 whatever we chose. §3.5's second pass is what dissolves that objection: those options are not
1136 an untyped tail, they are a set the adapter *declares*, and a struct can be built from the
1137 declaration at run time. Measured, `msgspec.defstruct()` for a twelve-option adapter costs
1138 **0.022ms** and validating a profile against it **0.5µs**, so the per-adapter model is free
1139 at the point of use.
1140
1141 What that buys is not a tidier version of validation we already do. It is validation of a
1142 surface **nothing validates today** (§1.5) — the difference between `reed_only = true`
1143 silently connecting read-write and an error naming the option and the adapter. It also comes
1144 with the declared choices, so `sslmode = "verify-ful"` is caught by the same pass; and the
1145 same declarations feed `--config schema`, so one source describes the config, validates it,
1146 and documents it.
1147
1148 **So: msgspec, at +37ms on every invocation.** Strict where it matters (`limit = true` is
1149 rejected rather than silently made `1`), path-carrying errors, JSON Schema included, Python
1150 ≥3.10 and cp310–cp314 wheels — exactly our floor and our matrix. The bet is that it is
1151 pre-1.0 and effectively a one-maintainer project, which is the same class of bet M1
1152 knowingly took on `tree-sitter`; if it goes bad, the fallback is the hand-rolled version of
1153 the same two passes, which is a contained loss because the *design* is what matters here and
1154 it survives the library.
1155
1156 What would reverse it: the 37ms mattering more than it looks once `--info` and `--spec` are
1157 real, or wanting `extra="allow"`-style preservation badly enough to prefer Pydantic's cost.
1158 Both are visible in PR 1, which is where this becomes real.
1159
1160 *Two questions an earlier draft left open are closed rather than answered.* `--describe`
1161 does not exist, so neither does the question of whether it should report row counts. And
1162 `--catalog` does not reuse the IDE's catalog cache: `catalog_cache.py` is kept for
1163 compatibility and is not a live cache to warm or read (Ted). Repeat navigation re-resolves
1164 its prefix, which is one round trip per segment and the price of not serving an agent a
1165 stale catalog to write a query against.
1166
1167 ---
1168
1169 ## 7. Explicitly not in M2
1170
1171 **Cut in review, from the roadmap's own M2 list:**
1172
1173 - **`describe`.** `--catalog --path mydb.analytics.orders` already returns the columns of
1174 `orders` with their names, real types and quoted identifiers, in one round trip below the
1175 resolve — which is the whole of what a describe was going to print. The only thing a
1176 separate mode could add is per-object detail the adapter contract does not carry
1177 (comments) or that costs a table scan (row counts), and neither is worth a second mode
1178 that would otherwise be a synonym.
1179 - **`hsql fmt`.** sqlfmt is already a dependency and the wrapper would be small, but the case
1180 for it is thin: an agent that wants formatted SQL can run `sqlfmt` itself, and this is the
1181 one mode that would have forced a 196ms import into a package whose import graph is
1182 otherwise a tested contract. Cut outright rather than deferred.
1183 - **`--dry-run`.** In practice only DuckDB implements `validate_sql` at all, and even there
1184 it is a parse check rather than an existence check: measured on this checkout,
1185 `select * from no_such_table` and `insert into no_such_table values (1)` both validate
1186 clean, because the adapter deliberately treats every non-parser error as valid so that DDL
1187 passes. Making it useful would mean a `PREPARE` pass in the DuckDB adapter (which catches
1188 the missing table, but rejects DDL as a parser error) plus a refusal path everywhere else —
1189 a lot of machinery for a flag that would be honest on one adapter. Punted to a later
1190 milestone, or never.
1191 - **Recursive `--depth`, the node budget, and child counts** (§1.3, §3.2). All three exist to
1192 make a recursive walk survivable; none is needed if the walk isn't there, and recursion
1193 should arrive with `fetch_descendants()` rather than ahead of it. Round-trip counting in
1194 `--stats` goes with them: it existed to make a walk's cost visible after the fact.
1195 - **The `compact` and `tree` layouts** (§3.3). One level is a flat list, so `tree` has
1196 nothing to draw, and `compact`'s `parent(child TYPE, …)` shape only reads for a relation
1197 and its columns — what a level *is* belongs to the adapter (§1.2). The same rows through
1198 `-tA --format csv` are as compact and stay true at every level.
1199 - **`--single-transaction`.** Adapters name their transaction modes freely and default to
1200 undefined transaction behavior, so core cannot drive a mode it can't identify; making it
1201 work would mean reworking the transaction-mode contract for a flag whose job a caller can
1202 do by putting `begin` and `commit` in the script they are already sending.
1203 - **`--password-stdin`** (§3.7). Between profiles, `${VAR}` interpolation and the environment
1204 variables every driver already reads, it fills no gap worth a flag — and the one it does
1205 fill, it fills by consuming the stream `-f -` wants.
1206
1207 **Deferred to later milestones, as planned:** `hsql history` and `hsql open` (M4, with the
1208 skill); `hsql mcp` (M6); streaming and pagination (M5); the interactive password prompt on
1209 `harlequin` (#667's other half); the agent eval suite (dropped from M1); the site's
1210 `llms.txt`, raw markdown routes and Docs API (M3). Publishing the JSON Schema at
1211 `harlequin.sh/schemas/config/v1.json` is a `harlequin-web` PR that this repo's
1212 `--config schema` feeds. Unifying the IDE's export dialog onto `write_file`, and making
1213 `textual` an optional extra of `textual-fastdatatable`, both still deferred from M1.
1214
1215 ---
1216
1217 ## 8. Corrections to the product plan
1218
1219 Applied to `harlequin-for-agents.md` in the same PR as this document; recorded here so the
1220 reasoning behind each is written down.
1221
1222 - **§4 and §6 spell the introspection surface as subcommands.** They are mode options on the
1223 one command — `hsql --catalog`, `hsql --info` — which matches `harlequin --config` and
1224 avoids ruling on whether `hsql catalog` means the verb or the database file of that name.
1225 - **§6 says `hsql catalog mydb.analytics.orders` is "exactly one `fetch_children()` call."**
1226 It is one round trip *per path segment* plus one for the listing — four for that example —
1227 because an item can only be reached through its ancestors (§1.1).
1228 - **§6's `--depth N` is a knob with a cliff behind it.** Its cost depends on the level it
1229 starts from: depth 2 from the root is one round trip per database, and depth 2 from a
1230 schema is 403 round trips and 2.3 seconds against a local file. M2 ships one level and no
1231 flag, and recursion returns with the adapter capability that would make it a single query.
1232 - **§6's `describe` is `catalog` on a relation.** Listing one level below a relation is its
1233 columns, so the two would differ only in the per-object detail the contract doesn't carry.
1234 There is no `--describe`.
1235 - **§6's child counts have no cheap case.** A count is only knowable by fetching the
1236 children, so the mitigation the product plan proposes cannot be implemented as stated; what
1237 a listing can report is what it fetched.
1238 - **§6's `--format compact` is both unimplementable and ungeneralizable.** `CatalogItem`
1239 carries a 1–3 character `type_label`, so the type an agent needs is not in the contract at
1240 all — hence `type_name`, which the in-tree adapters already fetch and discard (§1.3). And
1241 the format's `parent(child TYPE, …)` shape only reads for a relation and its columns; a
1242 database's schemas are not a signature. There is no `compact` format; `-tA --format csv`
1243 over the same rows is as cheap and is true at every level.
1244 - **§6's capability flags cannot be read off a connection reflectively.** SQLite defines
1245 `validate_sql` and raises `NotImplementedError` from it — which the app handles correctly
1246 today, but which no probe can distinguish from a real implementation. Declaring the flags
1247 on the adapter class is also what lets `hsql --info` answer while the database is
1248 unreachable (§1.4).
1249 - **§5's `--timeout` needs `hsql` to attribute the cancellation itself.** A cancelled DuckDB
1250 query returns an empty result set and no error, so a timeout that trusts the adapter
1251 reports "no rows" and exits 0 (§1.9).
1252 - **§5's `--dry-run`, `--single-transaction` and `--password-stdin`, and §6's `fmt`, are
1253 cut** (§7), so the roadmap's M2 row and §5's flag list both overstate what the milestone
1254 delivers. `--single-transaction` is the one worth a sentence in the product plan rather
1255 than only here: adapters name their transaction modes freely, so story A6's guarantee has
1256 to come from `begin`/`commit` in the caller's own script until the contract says which
1257 mode is which.
1258 - **§7's config validation runs on the merged document**, so no error can name the file it
1259 came from. Validating each file as it is read, and merging only valid ones, is what makes
1260 the diagnostics §7 asks for possible (§3.5).
1261 - **§7's config-file merge is per top-level key, and the failure is worse than the docs
1262 imply.** A cwd file that defines any profile replaces the home file's whole `profiles`
1263 table while leaving its `default_profile` behind, so both commands refuse to start (§1.6).
1264 Verified against the pre-refactor `config.py` as well: this is long-standing behavior, not
1265 something the `tomllib` change introduced.
1266 - **§7's `${VAR}` interpolation needs to be a read-path transform**, because
1267 `harlequin --config` reads the config and writes it back — interpolating too early writes
1268 the resolved secret into the user's file (§1.6).