Debian Codegraph @

tests/unit_tests/test_hsql_serve.py

raw
1 """The half of a warm session that holds the connection: `hsql --serve`.
2
3 What is asserted here is the server's half of the contract: which options each
4 role takes, that requests run one at a time on one connection, that the
5 session's state is what `--session-reset` clears, and the ways a session comes
6 down. Byte-equivalence with the cold path is `test_hsql_equivalence.py`'s.
7
8 Servers run in a fresh interpreter, because a server swaps the process's
9 streams, environment and working directory for every request; the command's
10 own refusals run in process, through the same `Served` the server hands it.
11 """
12
13 from __future__ import annotations
14
15 import json
16 import os
17 import signal
18 import socket
19 import sqlite3
20 import subprocess
21 import sys
22 import threading
23 import time
24 from pathlib import Path
25 from typing import Any, Callable, Iterator, Sequence, cast
26
27 import click
28 import pytest
29 from click.testing import CliRunner, Result
30
31 from harlequin.config import TUI_ONLY_KEYS
32 from harlequin.exception import HarlequinConnectionError
33 from harlequin.hsql import protocol, server
34 from harlequin.hsql.cli import (
35 CONFIG_OPTIONS,
36 CONNECTION_OPTIONS,
37 PER_REQUEST_OPTIONS,
38 ROLE_OPTIONS,
39 SERVER_OPTIONS,
40 _execute_all,
41 _fetched,
42 _Run,
43 bare_command,
44 build_cli,
45 connection_option_names,
46 connection_options_in,
47 )
48 from harlequin.hsql.diagnostics import ExitCode
49 from harlequin.hsql.server import InFlight, Served, Server
50 from harlequin.hsql.timeout import Deadline, TimedOut
51 from harlequin.plugins import load_adapter
52 from harlequin.query import RowLimit
53 from harlequin.query_log import QueryLog
54 from harlequin.statements import Statement
55 from harlequin.transaction_mode import HarlequinTransactionMode
56 from tests.hsql_sessions import HsqlSubprocess, ServeSession, WarmSession
57 from tests.waiting import wait_until
58
59 needs_unix_sockets = pytest.mark.skipif(
60 not hasattr(socket, "AF_UNIX"), reason="hsql sessions are POSIX-only"
61 )
62
63 Hsql = Callable[..., Result]
64
65 UNFINISHABLE = "select count(*) from range(200000000000)"
66 """A query no runner finishes inside a test's timeout.
67
68 `range()` streams, so this counts rows rather than materializing them, and
69 duckdb checks for an interrupt between chunks. Large enough that the fastest
70 runner cannot beat a tenth of a second: at 2e9 an arm64 macOS runner did, and
71 the timeout test got a result set where it wanted none.
72 """
73
74 A_REQUEST = b"AAAAAAAA"
75 ANOTHER_REQUEST = b"BBBBBBBB"
76 """Request ids, which are `REQUEST_ID_BYTES` long and otherwise arbitrary."""
77
78 SESSION_INIT_PATH = Path("boot.sql")
79 """The `--init-path` the in-process session recorded.
80
81 A `Path`, because that is what a `PathOption` resolves to and rendering one
82 is what `_shown()` exists for -- and a bare name, so that asserting on how it
83 prints spells no separator that is right on only one platform.
84 """
85
86
87 @pytest.fixture
88 def hsql(no_discovered_config: None) -> Hsql:
89 """Invoke hsql in process, cold, or served when `obj` names a session."""
90 runner = CliRunner()
91
92 def _run(*args: str, **kwargs: Any) -> Result:
93 argv = [str(arg) for arg in args]
94 return runner.invoke(build_cli(argv), argv, catch_exceptions=False, **kwargs)
95
96 return _run
97
98
99 @pytest.fixture
100 def duck() -> list[str]:
101 return ["-a", "duckdb", "--no-init", ":memory:"]
102
103
104 @pytest.fixture
105 def in_process_server(duckdb_adapter: Any) -> Server:
106 """A session with a real DuckDB connection, and no socket.
107
108 The identity is what `--serve` records when it connects: it is what a
109 served request's connection options are compared against, so a session
110 without one would refuse every option rather than the ones that differ.
111 """
112 adapter = duckdb_adapter([":memory:"], no_init=True)
113 return Server(
114 "inproc",
115 adapter="duckdb",
116 connection=adapter.connect(),
117 connection_id="inproc-connection",
118 reconnect=adapter.connect,
119 # what `hsql --serve inproc -P prod` records for a profile that says
120 # duckdb, `:memory:`, `no_init` and `read_only = false`
121 identity={
122 "conn_str": (":memory:",),
123 "read_only": False,
124 "no_init": True,
125 "init_path": SESSION_INIT_PATH,
126 },
127 )
128
129
130 def served_by(
131 server: Server, *, stdin: bytes | None = None, in_flight: InFlight | None = None
132 ) -> Served:
133 return Served(
134 server,
135 protocol.Request(
136 argv=[], cwd=os.getcwd(), environ={}, stdin=stdin, request_id=A_REQUEST
137 ),
138 in_flight,
139 )
140
141
142 # --- the partition -----------------------------------------------------------
143
144
145 def test_every_option_is_in_exactly_one_group() -> None:
146 """The rule that defines the two roles: `--serve` refuses the per-request
147 group and a served request refuses the server's, so an option in neither
148 or in both would be one nobody refuses -- or one both do."""
149 declared = {param.name for param in bare_command().params if param.name}
150 groups = [
151 CONNECTION_OPTIONS,
152 CONFIG_OPTIONS,
153 PER_REQUEST_OPTIONS,
154 SERVER_OPTIONS,
155 ROLE_OPTIONS,
156 ]
157 assert declared == set().union(*groups)
158 for first in groups:
159 for second in groups:
160 if first is not second:
161 assert not first & second
162
163
164 def test_a_session_records_the_connection_time_group_and_nothing_else() -> None:
165 """The identity a session compares a request against is the partition's
166 first group, so an option added to it is compared without anything being
167 added here."""
168 values = {param.name: None for param in bare_command().params if param.name}
169 assert (
170 set(connection_options_in(values, connection_option_names(None)))
171 == CONNECTION_OPTIONS
172 )
173
174
175 def test_a_key_the_command_does_not_declare_describes_no_connection() -> None:
176 """The IDE's own profile keys, and a misspelling in a profile: neither is
177 hsql's nor an adapter's, so neither is compared against a session."""
178 duckdb = load_adapter("duckdb").ADAPTER_OPTIONS
179 names = connection_option_names(duckdb)
180 assert not names & set(TUI_ONLY_KEYS)
181 assert "reed_only" not in names
182 assert "read_only" in names and "md_token" in names
183
184
185 def test_an_adapters_options_are_connection_options(hsql: Hsql) -> None:
186 """The command declares none of them, so they are the group by default."""
187 res = hsql("--serve", "prod", "-a", "duckdb", "--no-init", "--csv")
188 assert res.exit_code == ExitCode.USAGE
189 # `--csv` is refused, and `--no-init` was not -- it came first on the line
190 assert "--csv is a per-request option" in res.stderr
191
192
193 @pytest.mark.parametrize(
194 "args",
195 [
196 ["-c", "select 1"],
197 ["-f", "script.sql"],
198 ["--format", "csv"],
199 ["--limit", "10"],
200 ["--timeout", "5"],
201 ["--catalog"],
202 ["--info"],
203 ["-o", "out.csv"],
204 ["--stats"],
205 ["--no-write-history"],
206 ],
207 )
208 def test_serve_refuses_per_request_options(hsql: Hsql, args: list[str]) -> None:
209 """The feature's most likely first mistake, so the message names the right
210 invocation rather than only the wrong one."""
211 res = hsql("--serve", "prod", *args)
212 assert res.exit_code == ExitCode.USAGE
213 assert res.stdout == ""
214 assert "is a per-request option, and --serve takes none" in res.stderr
215 assert "hsql --serve prod" in res.stderr
216 assert "hsql --session prod" in res.stderr
217
218
219 def test_serve_and_session_are_two_roles(hsql: Hsql) -> None:
220 res = hsql("--serve", "a", "--session", "b")
221 assert res.exit_code == ExitCode.USAGE
222 assert "--serve starts a session and --session sends to one" in res.stderr
223
224
225 def test_serve_does_not_reset(hsql: Hsql) -> None:
226 """--session-reset is a client operation -- it asks a running session --
227 so on --serve it is refused as the per-request option it is."""
228 res = hsql("--serve", "a", "--session-reset")
229 assert res.exit_code == ExitCode.USAGE
230 assert "is a per-request option, and --serve takes none" in res.stderr
231
232
233 @pytest.mark.parametrize(
234 "name,reason",
235 [
236 # a flag with no value is the caller's typo on every platform, so it is
237 # answered before the platform is; the rest reach the name check only
238 # where a session could have run
239 ("", "needs a name"),
240 pytest.param("bad name", "is not a session name", marks=needs_unix_sockets),
241 pytest.param("../etc", "is not a session name", marks=needs_unix_sockets),
242 pytest.param("x" * 65, "is not a session name", marks=needs_unix_sockets),
243 ],
244 )
245 def test_serve_refuses_a_name_no_client_could_reach(
246 hsql: Hsql, name: str, reason: str
247 ) -> None:
248 """Asked with the client's own check, and before a connection is paid for."""
249 res = hsql("--serve", name, "-a", "duckdb", ":memory:")
250 assert res.exit_code == ExitCode.USAGE
251 assert reason in res.stderr
252
253
254 @pytest.mark.parametrize(
255 "flag,bounds",
256 [
257 ("--queue-timeout", "how long a request waits for the one before it"),
258 ("--idle-timeout", "how long a session sits with nothing to do"),
259 ("--max-lifetime", "how long a session runs at all"),
260 ],
261 )
262 def test_a_server_option_belongs_to_serve(
263 hsql: Hsql, duck: list[str], flag: str, bounds: str
264 ) -> None:
265 """The other half of `--serve` refusing the per-request group: a caller who
266 typed one of these on a cold invocation meant it for a session, and one
267 silently ignored is one they believe they set."""
268 res = hsql(*duck, flag, "2", "-c", "select 1")
269 assert res.exit_code == ExitCode.USAGE
270 assert f"{flag} is a --serve option: it bounds {bounds}." in res.stderr
271
272
273 def test_session_reset_needs_a_session(hsql: Hsql) -> None:
274 """It reconnects a running session, so with none named there is nothing to
275 do -- and it attaches no adapter options, so it takes no connection args."""
276 res = hsql("--session-reset")
277 assert res.exit_code == ExitCode.USAGE
278 assert "--session-reset reconnects a running session" in res.stderr
279 assert "HSQL_SESSION" in res.stderr
280
281
282 def test_session_status_needs_a_session(hsql: Hsql) -> None:
283 """The client answers it off a frame before click exists, so reaching the
284 parser means no session did."""
285 res = hsql("--session-status")
286 assert res.exit_code == ExitCode.USAGE
287 assert "--session-status reports on a running session" in res.stderr
288 assert "HSQL_SESSION" in res.stderr
289
290
291 def test_serve_does_not_report_its_own_status(hsql: Hsql) -> None:
292 """It asks a running session what it is doing, which is a client
293 operation, so on --serve it is refused as the per-request option it is."""
294 res = hsql("--serve", "a", "--session-status")
295 assert res.exit_code == ExitCode.USAGE
296 assert "is a per-request option, and --serve takes none" in res.stderr
297
298
299 def test_a_session_flag_that_reached_the_parser_is_refused(
300 hsql: Hsql, duck: list[str]
301 ) -> None:
302 """`main()` reads it before it parses anything, so only a caller that built
303 the command some other way can put it here."""
304 res = hsql(*duck, "--session", "prod", "-c", "select 1")
305 assert res.exit_code == ExitCode.USAGE
306 assert "--session prod is read before hsql parses anything else" in res.stderr
307
308
309 @pytest.mark.parametrize(
310 "key,value",
311 [("session", '"prod"'), ("serve", '"prod"'), ("session_status", "true")],
312 )
313 def test_a_profile_may_not_decide_which_process_runs_an_invocation(
314 hsql: Hsql, tmp_path: Path, key: str, value: str
315 ) -> None:
316 """The `CLI_ONLY_SSH_KEYS`-shaped refusal: `session` is decided before any
317 config file is read, a profile that served would turn a query into a
318 daemon, and `session_status` is read off argv by the client -- so a profile
319 could set it only for the runs that never reach a session."""
320 path = tmp_path / "hsql.toml"
321 path.write_text(f'[profiles.prod]\nadapter = "duckdb"\n{key} = {value}\n')
322 res = hsql("--config-path", path, "-P", "prod", "-c", "select 1")
323 assert res.exit_code == ExitCode.USAGE
324 assert f"{key} decides which process runs an invocation" in res.stderr
325 assert f"--{key.replace('_', '-')}" in res.stderr
326
327
328 def test_a_profiles_session_key_is_not_in_the_schema() -> None:
329 from harlequin.config_schema import build_schema
330
331 profile = build_schema(bare_command().params, adapters=None)["$defs"]["profile"][
332 "properties"
333 ]
334 assert "session" not in profile
335 assert "serve" not in profile
336 assert "session_status" not in profile
337 # while the keys a profile may set are
338 assert {"queue_timeout", "idle_timeout", "max_lifetime"} <= set(profile)
339
340
341 def test_session_is_a_profile_key_the_ide_leaves_alone() -> None:
342 """One profile serves both commands, and the IDE reads hsql's keys off the
343 command rather than a copy, so the new ones are there without a change."""
344 from harlequin.cli import hsql_profile_keys
345
346 assert {
347 "session",
348 "serve",
349 "session_reset",
350 "queue_timeout",
351 "idle_timeout",
352 "max_lifetime",
353 } <= hsql_profile_keys()
354
355
356 # --- a served request, in process --------------------------------------------
357
358
359 @pytest.mark.parametrize(
360 "args,spelling,asked,has",
361 [
362 (["-a", "sqlite"], "--adapter", "'sqlite'", "'duckdb'"),
363 (["--read-only"], "--read-only", "True", "False"),
364 (["other.db"], "CONN_STR", "['other.db']", "[':memory:']"),
365 ],
366 )
367 def test_a_served_request_that_asserts_a_different_connection_is_refused(
368 hsql: Hsql,
369 in_process_server: Server,
370 args: list[str],
371 spelling: str,
372 asked: str,
373 has: str,
374 ) -> None:
375 """A session's connection is fixed at start-up, so a request naming a
376 different one exits 2.
377
378 Both values are asserted: what the session was started with is the half a
379 caller cannot see, and a message echoing the request's value back for it
380 would report two identical values as differing."""
381 res = hsql(*args, "-c", "select 1", obj=served_by(in_process_server))
382 assert res.exit_code == ExitCode.USAGE
383 assert res.stdout == ""
384 assert (
385 f"{spelling} is {asked}. The session named 'inproc' was started with "
386 f"{has}, and its connection is fixed."
387 ) in res.stderr
388 assert "--serve NAME" in res.stderr
389
390
391 def test_a_refusal_names_an_adapters_own_option_and_spells_a_path_as_one(
392 hsql: Hsql, in_process_server: Server, tmp_path: Path
393 ) -> None:
394 """An adapter-declared option is compared like one of hsql's own, and a
395 `PathOption` resolves to a `Path` -- which a caller reads as a path and
396 not as `PosixPath('/p/boot.sql')`.
397
398 The asked value is left to click, which resolves it against wherever the
399 test runs; what is pinned is that both sides reach the caller as paths
400 rather than as reprs."""
401 res = hsql(
402 "--init-path",
403 str(tmp_path / "other.sql"),
404 "-c",
405 "select 1",
406 obj=served_by(in_process_server),
407 )
408 assert res.exit_code == ExitCode.USAGE
409 assert "--init-path is '" in res.stderr
410 assert f"was started with '{SESSION_INIT_PATH}'," in res.stderr
411 assert "other.sql" in res.stderr
412 assert "Path(" not in res.stderr
413
414
415 @pytest.mark.parametrize("args", [["-a", "duckdb"], ["--no-init"], [":memory:"]])
416 def test_a_served_request_may_assert_the_connection_the_session_has(
417 hsql: Hsql, in_process_server: Server, args: list[str]
418 ) -> None:
419 """Identical to the server's is served: the name is the caller's and the
420 identity is the server's, so a request that asks for what is already there
421 has asked for nothing."""
422 res = hsql(*args, "-tAc", "select 1", obj=served_by(in_process_server))
423 assert res.exit_code == ExitCode.OK
424 assert res.stdout == "1\n"
425
426
427 @pytest.mark.parametrize("args", [["--read-only"], ["--ssh-host", "bastion"]])
428 def test_a_served_request_is_refused_an_option_the_session_never_named(
429 hsql: Hsql, duckdb_adapter: Any, args: list[str]
430 ) -> None:
431 """A session that never named a key connected with whatever its adapter
432 defaults to, which core cannot enumerate -- so a request that names it is
433 refused rather than quietly served."""
434 adapter = duckdb_adapter([":memory:"], no_init=True)
435 session = Server(
436 "bare",
437 adapter="duckdb",
438 connection=adapter.connect(),
439 connection_id="bare-connection",
440 reconnect=adapter.connect,
441 )
442 res = hsql(*args, "-c", "select 1", obj=served_by(session))
443 assert res.exit_code == ExitCode.USAGE
444 assert (
445 "is a connection option. The session named 'bare' was started without it"
446 ) in res.stderr
447
448
449 def test_a_refusal_does_not_print_the_secret_it_names(
450 hsql: Hsql, in_process_server: Server
451 ) -> None:
452 """A connection option is exactly where a password is typed, so the
453 message about one that differs is a message about a secret."""
454 res = hsql(
455 "postgres://ted:hunter2@warehouse:5432/analytics",
456 "-c",
457 "select 1",
458 obj=served_by(in_process_server),
459 )
460 assert res.exit_code == ExitCode.USAGE
461 assert "hunter2" not in res.stderr
462 assert "********" in res.stderr
463
464
465 def test_a_served_request_takes_a_profile_of_per_request_options(
466 hsql: Hsql, in_process_server: Server, tmp_path: Path
467 ) -> None:
468 """A profile names where options come from rather than being one, so what
469 it holds decides: nothing here says which database, so it applies -- the
470 same way a `default_profile` discovered in the caller's directory does."""
471 path = tmp_path / "hsql.toml"
472 path.write_text('[profiles.csv-out]\nformat = "csv"\nlimit = 5\n')
473 res = hsql(
474 "--config-path",
475 path,
476 "-P",
477 "csv-out",
478 "-c",
479 "select 1 as a",
480 obj=served_by(in_process_server),
481 )
482 assert res.exit_code == ExitCode.OK
483 assert res.stdout == "a\n1\n"
484
485
486 @pytest.mark.parametrize(
487 "key,value,shown,has",
488 [
489 ("adapter", '"sqlite"', "'sqlite'", "'duckdb'"),
490 ("read_only", "true", "True", "False"),
491 ("conn_str", '["other.db"]', "['other.db']", "[':memory:']"),
492 ],
493 )
494 def test_a_served_request_refuses_a_profile_that_names_another_connection(
495 hsql: Hsql,
496 in_process_server: Server,
497 tmp_path: Path,
498 key: str,
499 value: str,
500 shown: str,
501 has: str,
502 ) -> None:
503 """A typed profile is judged by the keys it holds rather than by being one,
504 so one that names a different database is refused under the key that names
505 it rather than as a flag."""
506 path = tmp_path / "hsql.toml"
507 path.write_text(f"[profiles.prod]\n{key} = {value}\n")
508 res = hsql(
509 "--config-path",
510 path,
511 "-P",
512 "prod",
513 "-c",
514 "select 1",
515 obj=served_by(in_process_server),
516 )
517 assert res.exit_code == ExitCode.USAGE
518 assert res.stdout == ""
519 assert f"the profile 'prod' sets {key}, which is {shown}." in res.stderr
520 assert f"The session named 'inproc' was started with {has}," in res.stderr
521 assert "--serve NAME -P prod" in res.stderr
522
523
524 def test_a_served_request_takes_a_profile_that_names_the_sessions_connection(
525 hsql: Hsql, in_process_server: Server, tmp_path: Path
526 ) -> None:
527 """The profile the session was started with is the one a caller is most
528 likely to name here, and naming it asserts nothing the session has not
529 already answered."""
530 path = tmp_path / "hsql.toml"
531 path.write_text(
532 '[profiles.prod]\nadapter = "duckdb"\nconn_str = [":memory:"]\n'
533 "no_init = true\nlimit = 5\n"
534 )
535 res = hsql(
536 "--config-path",
537 path,
538 "-P",
539 "prod",
540 "-tAc",
541 "select 1",
542 obj=served_by(in_process_server),
543 )
544 assert res.exit_code == ExitCode.OK
545 assert res.stdout == "1\n"
546
547
548 @pytest.mark.parametrize("key", ["queue_timeout", "idle_timeout", "max_lifetime"])
549 def test_a_served_request_may_not_take_a_server_option_from_a_profile(
550 hsql: Hsql, in_process_server: Server, tmp_path: Path, key: str
551 ) -> None:
552 """A typed profile is judged by the keys it holds on both halves of the
553 rule: a server-lifetime key in one describes a server that is already up,
554 whichever way the caller named it."""
555 path = tmp_path / "hsql.toml"
556 path.write_text(f"[profiles.slow]\n{key} = 30\n")
557 res = hsql(
558 "--config-path",
559 path,
560 "-P",
561 "slow",
562 "-c",
563 "select 1",
564 obj=served_by(in_process_server),
565 )
566 assert res.exit_code == ExitCode.USAGE
567 assert f"the profile 'slow' sets {key}, which is a --serve option" in res.stderr
568
569
570 @pytest.mark.parametrize("key", ["theme", "locale", "viewer_max_rows"])
571 def test_a_served_request_takes_a_profile_the_ide_also_reads(
572 hsql: Hsql, in_process_server: Server, tmp_path: Path, key: str
573 ) -> None:
574 """One profile serves both commands, so a profile with a `theme` in it is
575 the normal case -- and hsql drops the IDE's keys before it connects, so a
576 session records none of them and none of them names a connection."""
577 path = tmp_path / "hsql.toml"
578 value = "10" if key == "viewer_max_rows" else '"nord"'
579 path.write_text(f'[profiles.prod]\nadapter = "duckdb"\n{key} = {value}\n')
580 res = hsql(
581 "--config-path",
582 path,
583 "-P",
584 "prod",
585 "-tAc",
586 "select 1",
587 obj=served_by(in_process_server),
588 )
589 assert res.exit_code == ExitCode.OK
590 assert res.stdout == "1\n"
591
592
593 def test_a_profile_that_names_an_option_the_session_never_did_is_refused(
594 hsql: Hsql, in_process_server: Server, tmp_path: Path
595 ) -> None:
596 """The `did not ask for` refusal, worded for a profile rather than a flag."""
597 path = tmp_path / "hsql.toml"
598 path.write_text('[profiles.other]\nmd_token = "tok_abcdef"\n')
599 res = hsql(
600 "--config-path",
601 path,
602 "-P",
603 "other",
604 "-c",
605 "select 1",
606 obj=served_by(in_process_server),
607 )
608 assert res.exit_code == ExitCode.USAGE
609 assert (
610 "the profile 'other' sets md_token, which is a connection option. The "
611 "session named 'inproc' was started without it"
612 ) in res.stderr
613 # declared `secret=True`, so the refusal names the key and not the token
614 assert "tok_abcdef" not in res.stderr
615
616
617 def test_a_refusal_masks_an_option_its_adapter_declared_secret(
618 hsql: Hsql, duckdb_adapter: Any
619 ) -> None:
620 """`secret=` is the mechanism, and the name backstop is only the backstop:
621 a differing value is masked because duckdb declared the option, not
622 because the key happens to be spelled like a password."""
623 adapter = duckdb_adapter([":memory:"], no_init=True)
624 session = Server(
625 "md",
626 adapter="duckdb",
627 connection=adapter.connect(),
628 connection_id="md-connection",
629 reconnect=adapter.connect,
630 identity={"md_token": "tok_theirs"},
631 options=adapter.ADAPTER_OPTIONS,
632 )
633 res = hsql("--md_token", "tok_mine", "-c", "select 1", obj=served_by(session))
634 assert res.exit_code == ExitCode.USAGE
635 assert "tok_mine" not in res.stderr
636 assert "tok_theirs" not in res.stderr
637 assert "--md_token is '********'" in res.stderr
638 assert "was started with '********'" in res.stderr
639
640
641 def test_a_profile_value_of_the_wrong_shape_is_a_usage_error(
642 hsql: Hsql, in_process_server: Server, tmp_path: Path
643 ) -> None:
644 """A caller who mistyped their own config is owed exit 2 naming the key,
645 not a crash report saying they found a bug in Harlequin."""
646 path = tmp_path / "hsql.toml"
647 path.write_text("[profiles.bad]\nconn_str = 5\n")
648 res = hsql(
649 "--config-path",
650 path,
651 "-P",
652 "bad",
653 "-c",
654 "select 1",
655 obj=served_by(in_process_server),
656 )
657 assert res.exit_code == ExitCode.USAGE
658 assert "the profile 'bad' sets conn_str, which is ['********']" in res.stderr
659
660
661 @pytest.mark.parametrize(
662 "flag", ["--queue-timeout", "--idle-timeout", "--max-lifetime"]
663 )
664 def test_a_served_request_may_not_type_a_server_option(
665 hsql: Hsql, in_process_server: Server, flag: str
666 ) -> None:
667 res = hsql(flag, "3", "-c", "select 1", obj=served_by(in_process_server))
668 assert res.exit_code == ExitCode.USAGE
669 assert f"{flag} is a --serve option, and the session named 'inproc'" in res.stderr
670
671
672 def test_a_served_request_may_not_serve(hsql: Hsql, in_process_server: Server) -> None:
673 res = hsql("--serve", "other", obj=served_by(in_process_server))
674 assert res.exit_code == ExitCode.USAGE
675 assert "pass one of them" in res.stderr
676
677
678 def test_a_mode_that_reads_no_database_is_not_the_sessions_business(
679 hsql: Hsql, in_process_server: Server
680 ) -> None:
681 """`--info -a sqlite` narrows a document; it does not ask to reconnect."""
682 res = hsql("--info", "-a", "sqlite", obj=served_by(in_process_server))
683 assert res.exit_code == ExitCode.OK
684 assert '"sqlite"' in res.stdout
685
686
687 def test_a_served_request_runs_on_the_sessions_connection(
688 hsql: Hsql, in_process_server: Server
689 ) -> None:
690 served = served_by(in_process_server)
691 assert hsql("-c", "create temp table t as select 1 as v", obj=served).exit_code == 0
692 res = hsql("-tAc", "select v from t", obj=served)
693 assert res.exit_code == ExitCode.OK
694 assert res.stdout == "1\n"
695
696
697 def test_a_dash_f_dash_with_no_stdin_is_refused(
698 hsql: Hsql, in_process_server: Server
699 ) -> None:
700 """The client's argv scan misses a `-f` behind a boolean short an adapter
701 declares, and an empty script run as if it were what was piped is the
702 silent failure this turns into an exit 2."""
703 res = hsql("-f", "-", obj=served_by(in_process_server, stdin=None))
704 assert res.exit_code == ExitCode.USAGE
705 assert "carried none" in res.stderr
706 assert "--file -" in res.stderr
707
708
709 def test_a_dash_f_dash_with_stdin_is_allowed(
710 hsql: Hsql, in_process_server: Server
711 ) -> None:
712 """The guard refuses only a `-f -` whose request carried no stdin; with one
713 it reads the caller's SQL. (The bytes come through the server's own stdin
714 stand-in end to end; here the CliRunner supplies them.)"""
715 served = served_by(in_process_server, stdin=b"select 5 as five")
716 res = hsql("-tAf", "-", obj=served, input="select 5 as five")
717 assert res.exit_code == ExitCode.OK
718 assert res.stdout == "5\n"
719
720
721 def test_session_reset_reconnects(hsql: Hsql, in_process_server: Server) -> None:
722 served = served_by(in_process_server)
723 hsql("-c", "create temp table t as select 1 as v", obj=served)
724 res = hsql("--session-reset", obj=served)
725 assert res.exit_code == ExitCode.OK
726 assert res.stdout == ""
727 assert "reconnected" in res.stderr
728 assert hsql("-c", "select v from t", obj=served).exit_code == ExitCode.QUERY
729
730
731 def test_a_reset_that_cannot_reconnect_leaves_the_session_without_a_connection(
732 hsql: Hsql, duckdb_adapter: Any
733 ) -> None:
734 """Exit 3 for the reset, and exit 3 for every request after it until a
735 reset succeeds: a session with no connection says so rather than pretending."""
736 adapter = duckdb_adapter([":memory:"], no_init=True)
737 attempts: list[int] = []
738
739 def reconnect() -> Any:
740 attempts.append(1)
741 if len(attempts) == 1:
742 raise HarlequinConnectionError("the warehouse is down")
743 return adapter.connect()
744
745 session = Server(
746 "flaky",
747 adapter="duckdb",
748 connection=adapter.connect(),
749 connection_id="flaky-connection",
750 reconnect=reconnect,
751 )
752 served = served_by(session)
753 res = hsql("--session-reset", obj=served)
754 assert res.exit_code == ExitCode.CONNECTION
755 assert "the warehouse is down" in res.stderr
756 res = hsql("-c", "select 1", obj=served)
757 assert res.exit_code == ExitCode.CONNECTION
758 assert "has no connection" in res.stderr
759 assert "--session-reset" in res.stderr
760 assert hsql("--session-reset", obj=served).exit_code == ExitCode.OK
761 assert hsql("-c", "select 1", obj=served).exit_code == ExitCode.OK
762
763
764 # --- stopping a request ------------------------------------------------------
765
766
767 class _FakeConnection:
768 def __init__(self, label: str) -> None:
769 self.label = label
770 self.closed = False
771 self.cancels = 0
772
773 def cancel(self) -> None:
774 self.cancels += 1
775
776 def close(self) -> None:
777 self.closed = True
778
779
780 def cancellable(implements_cancel: bool = True) -> tuple[Server, _FakeConnection]:
781 """A session with nothing but the bookkeeping a cancel reads."""
782 connection = _FakeConnection("held")
783 return (
784 Server(
785 "cancels",
786 adapter="duckdb",
787 connection=cast(Any, connection),
788 connection_id="cancels-connection",
789 reconnect=lambda: cast(Any, connection),
790 implements_cancel=implements_cancel,
791 ),
792 connection,
793 )
794
795
796 def running(session: Server, request_id: bytes) -> InFlight:
797 """A request that took its turn and went on to ask for the connection."""
798 in_flight = session._hold(request_id)
799 assert session._take_turn(in_flight)
800 session.note_connection_held(in_flight)
801 return in_flight
802
803
804 def test_a_cancel_stops_the_request_that_named_it() -> None:
805 """The id is the client's, so a cancel that arrives after its request
806 finished cannot stop whichever one the session went on to."""
807 session, connection = cancellable()
808 in_flight = running(session, A_REQUEST)
809 assert session.cancel(A_REQUEST) == server.STOPPED
810 assert connection.cancels == 1
811 # set before the database is asked, which is what tells the empty result
812 # the cancel produces from one a query really returned
813 assert in_flight.cancelled
814
815
816 def test_a_cancel_for_a_request_the_session_no_longer_holds_stops_nothing() -> None:
817 session, connection = cancellable()
818 finished = session._hold(A_REQUEST)
819 session._release(finished)
820 assert session.cancel(A_REQUEST) == server.UNKNOWN
821 assert session.cancel(ANOTHER_REQUEST) == server.UNKNOWN
822 assert connection.cancels == 0
823
824
825 def test_a_request_cancelled_while_it_queued_never_runs() -> None:
826 """A caller who gives up while their request waits for the one ahead is
827 cancelling something the session has -- and interrupting the database then
828 would land on whichever request is holding it."""
829 session, connection = cancellable()
830 waiting = session._hold(A_REQUEST)
831 assert session.cancel(A_REQUEST) == server.WAITING
832 assert connection.cancels == 0
833 assert not session._take_turn(waiting)
834
835
836 def test_a_cancel_an_adapter_cannot_honor_leaves_the_query_running() -> None:
837 """`cancel()` is optional on the contract, and a session that has none
838 detaches the caller rather than pretending to have stopped anything. The
839 request is still marked, so the script runs no further statement."""
840 session, connection = cancellable(implements_cancel=False)
841 in_flight = running(session, A_REQUEST)
842 assert session.cancel(A_REQUEST) == server.UNSTOPPABLE
843 assert connection.cancels == 0
844 assert in_flight.cancelled
845
846
847 def test_a_cancel_on_a_request_that_never_took_the_connection_interrupts_nothing() -> (
848 None
849 ):
850 """`cancel()` is connection-wide, so a served `--info` or `--config show`
851 -- which takes a turn and never asks for the connection -- must not reach
852 past itself into a driver no query is using. It is still marked, so a
853 script that had not got to its first statement runs none of them."""
854 session, connection = cancellable()
855 reporting = session._hold(A_REQUEST)
856 assert session._take_turn(reporting)
857 assert session.cancel(A_REQUEST) == server.IDLE
858 assert connection.cancels == 0
859 assert reporting.cancelled
860
861
862 def test_a_cancel_does_not_reach_into_a_connection_a_timed_out_thread_holds() -> None:
863 """`abandon()` leaves the connection to the thread still inside it, so a
864 cancel that called into it would be a second thread in one driver. The
865 session says it has no connection to offer, which is what `--session-reset`
866 is for."""
867 session, connection = cancellable()
868 in_flight = running(session, A_REQUEST)
869 session.abandon()
870 assert session.cancel(A_REQUEST) == server.DETACHED
871 assert connection.cancels == 0
872 assert in_flight.cancelled
873
874
875 def test_a_bug_in_the_cancel_path_is_not_someone_elses_stderr(
876 monkeypatch: pytest.MonkeyPatch,
877 ) -> None:
878 """The client exits 130 either way, so a cancel that raised has nothing to
879 tell it -- and the traceback belongs on the operator's stream rather than
880 in whichever request's recorder holds the process's stderr."""
881 session, _ = cancellable()
882 running(session, A_REQUEST)
883
884 def boom(request_id: bytes) -> str:
885 raise RuntimeError("simulated bug")
886
887 monkeypatch.setattr(session, "cancel", boom)
888 assert _cancel_over_a_socket(session, A_REQUEST) == (b"", ExitCode.INTERRUPT)
889
890
891 def test_a_cancel_never_reaches_the_request_that_took_over_the_connection() -> None:
892 """`HarlequinConnection.cancel()` is connection-wide, so a request the
893 session no longer holds must find nothing: interrupting its successor's
894 query would mark no `InFlight`, and an empty, error-free result nobody
895 attributes is exactly what a caller cannot tell from an empty table."""
896 session, connection = cancellable()
897 first = running(session, A_REQUEST)
898 # what `_attend` does before the turnstile lets the next request start
899 session._release(first)
900 second = running(session, ANOTHER_REQUEST)
901 assert session.cancel(A_REQUEST) == server.UNKNOWN
902 assert connection.cancels == 0
903 assert not second.cancelled
904
905
906 def test_a_request_is_released_before_the_turnstile_lets_the_next_one_in(
907 monkeypatch: pytest.MonkeyPatch,
908 ) -> None:
909 """The order that makes the guarantee above hold, pinned on `_attend`
910 itself: a request still registered when the next one can start is one
911 whose cancel would interrupt that one's query."""
912 session, _ = cancellable()
913
914 def ran(
915 request: protocol.Request, in_flight: server.InFlight | None = None
916 ) -> tuple[list[tuple[int, bytearray]], int]:
917 return [], int(ExitCode.OK)
918
919 monkeypatch.setattr(session, "_run", ran)
920 registered_when_leaving: list[list[bytes]] = []
921 leaving = session._turnstile.leave
922
923 def leave() -> None:
924 registered_when_leaving.append(list(session._in_flight))
925 leaving()
926
927 monkeypatch.setattr(session._turnstile, "leave", leave)
928 ours, theirs = socket.socketpair()
929 with ours, theirs:
930 protocol.send_frame(
931 theirs,
932 protocol.REQUEST,
933 protocol.pack_request(
934 argv=["-c", "select 1"],
935 cwd=os.getcwd(),
936 environ={},
937 stdin=None,
938 request_id=A_REQUEST,
939 ),
940 )
941 session._attend(ours)
942 assert registered_when_leaving == [[]]
943
944
945 def test_nothing_takes_a_turn_between_a_cancel_and_the_interrupt_it_sends() -> None:
946 """The other half: a request that started after the cancel read the
947 bookkeeping would be the one the connection-wide interrupt reached, so the
948 lock a request takes to start is held across the driver call."""
949 session, _ = cancellable()
950 running(session, A_REQUEST)
951 next_up = session._hold(ANOTHER_REQUEST)
952 trying = threading.Event()
953 turns: list[bool] = []
954 blocked_while_interrupting: list[bool] = []
955
956 def take_turn() -> None:
957 trying.set()
958 turns.append(session._take_turn(next_up))
959
960 def interrupt() -> None:
961 taking = threading.Thread(target=take_turn)
962 taking.start()
963 assert trying.wait(30)
964 taking.join(0.2)
965 blocked_while_interrupting.append(taking.is_alive())
966
967 session._connection = cast(Any, _Interrupting(interrupt))
968 assert session.cancel(A_REQUEST) == server.STOPPED
969 assert blocked_while_interrupting == [True]
970 # and it goes through once the cancel has let the lock go
971 wait_until(lambda: turns == [True], description="the waiting turn to go through")
972
973
974 class _Interrupting(_FakeConnection):
975 """A connection whose `cancel()` is what the test wants to watch."""
976
977 def __init__(self, interrupting: Callable[[], None]) -> None:
978 super().__init__("interrupting")
979 self._interrupting = interrupting
980
981 def cancel(self) -> None:
982 super().cancel()
983 self._interrupting()
984
985
986 def test_a_served_run_reads_the_sessions_cancel(in_process_server: Server) -> None:
987 """What the command reads between results, where a cold run reads its
988 clock."""
989 in_flight = in_process_server._hold(A_REQUEST)
990 served = served_by(in_process_server, in_flight=in_flight)
991 assert not served.cancelled
992 in_flight.cancel()
993 assert served.cancelled
994
995
996 def test_a_run_cancelled_before_it_started_submits_nothing(
997 in_process_server: Server,
998 ) -> None:
999 """A cancel that arrived before its request took the connection could not
1000 interrupt a query, so the one thing left that stops the run is submitting
1001 none -- checked before the first statement rather than after it."""
1002 submitted: list[str] = []
1003
1004 class Recording:
1005 def execute(self, sql: str) -> None:
1006 submitted.append(sql)
1007
1008 in_flight = in_process_server._hold(A_REQUEST)
1009 in_flight.cancel()
1010 run = _Run(served=served_by(in_process_server, in_flight=in_flight))
1011 executed = _execute_all(
1012 cast(Any, Recording()),
1013 [Statement(sql="select 1", index=0)],
1014 limit=RowLimit(),
1015 on_error="stop",
1016 run=run,
1017 )
1018 assert executed == []
1019 assert submitted == []
1020
1021
1022 def test_a_cancelled_run_is_an_error_that_exits_130(
1023 in_process_server: Server,
1024 ) -> None:
1025 """What `--stats` says about a run the caller stopped, and the code the
1026 session logs for it."""
1027 in_flight = in_process_server._hold(A_REQUEST)
1028 run = _Run(served=served_by(in_process_server, in_flight=in_flight))
1029 assert not run.stopped
1030 assert (run.status, run.message, run.exit_code) == ("ok", None, ExitCode.OK)
1031 in_flight.cancel()
1032 assert run.stopped
1033 assert (run.status, run.message, run.exit_code) == (
1034 "error",
1035 "cancelled",
1036 ExitCode.INTERRUPT,
1037 )
1038
1039
1040 def test_a_cancel_a_session_answers_says_only_what_the_caller_must_act_on() -> None:
1041 """Exit 130 whatever came of it -- the caller interrupted the run, which
1042 is the code for it cold too -- and a line only when the query outlived
1043 them."""
1044 session, _ = cancellable(implements_cancel=False)
1045 running(session, A_REQUEST)
1046 assert _cancel_over_a_socket(session, A_REQUEST) == (
1047 b"note: duckdb does not implement query cancellation, so the query is "
1048 b"still running on session 'cancels'; it holds the session until it "
1049 b"finishes. `hsql --session cancels --session-status` says when.\n",
1050 ExitCode.INTERRUPT,
1051 )
1052 stopping, _ = cancellable()
1053 running(stopping, A_REQUEST)
1054 assert _cancel_over_a_socket(stopping, A_REQUEST) == (b"", ExitCode.INTERRUPT)
1055
1056
1057 def _cancel_over_a_socket(session: Server, request_id: bytes) -> tuple[bytes, int]:
1058 """What a cancel sends back: the caller's stderr, and the code it exits."""
1059 ours, theirs = socket.socketpair()
1060 with ours, theirs:
1061 session._send_cancel(ours, request_id)
1062 ours.shutdown(socket.SHUT_WR)
1063 stderr = bytearray()
1064 code = -1
1065 while (frame := protocol.recv_frame(theirs)) is not None:
1066 if frame[0] == protocol.EXIT:
1067 code = int.from_bytes(frame[1], "big")
1068 elif frame[0] == protocol.STDERR:
1069 stderr.extend(frame[1])
1070 return bytes(stderr), code
1071
1072
1073 # --- and a cancel that does not land -----------------------------------------
1074
1075
1076 def test_a_deadline_a_server_gave_an_abandon_hook_ends_the_run_not_the_process() -> (
1077 None
1078 ):
1079 """Where the cold path halts the process, a deadline given an abandon hook
1080 calls it and raises TimedOut for the request to attribute, so the server
1081 lives on."""
1082 abandoned: list[bool] = []
1083 never = threading.Event()
1084 connection: Any = _FakeConnection("held")
1085 deadline = Deadline(0.01, grace=0.01, abandon=lambda: abandoned.append(True))
1086 with pytest.raises(TimedOut):
1087 deadline.run(lambda: never.wait(30), connection=connection)
1088 assert abandoned == [True]
1089 never.set()
1090
1091
1092 def test_a_bug_in_hsql_is_exit_70_through_a_session_too(
1093 in_process_server: Server, monkeypatch: pytest.MonkeyPatch
1094 ) -> None:
1095 """A crash is the one failure a session could answer differently from a
1096 cold run: 70 says a bug in hsql and 1 says the database rejected the SQL,
1097 which is the confusion `CRASH` exists to remove. The client gets the same
1098 diagnostic either way, and the session goes on serving."""
1099
1100 def boom(*args: Any, **kwargs: Any) -> int:
1101 raise RuntimeError("simulated bug")
1102
1103 monkeypatch.setattr("harlequin.hsql.cli.run", boom)
1104 request = protocol.Request(
1105 argv=["-c", "select 1"],
1106 cwd=os.getcwd(),
1107 environ={},
1108 stdin=None,
1109 request_id=A_REQUEST,
1110 )
1111 segments, code = in_process_server._run(request)
1112 assert code == ExitCode.CRASH
1113 stderr = b"".join(bytes(d) for kind, d in segments if kind == protocol.STDERR)
1114 assert b"hsql hit a bug in itself" in stderr
1115 assert not any(kind == protocol.STDOUT for kind, _ in segments)
1116
1117
1118 def test_an_abandoned_connection_is_offered_to_nobody_until_a_reset() -> None:
1119 """A cancel that outlasts its grace leaves the connection to the thread
1120 still inside it, so `abandon()` marks the session unusable until a reset,
1121 rather than handing the next request a connection another thread holds."""
1122 opened: list[Any] = [_FakeConnection("first")]
1123
1124 def reconnect() -> Any:
1125 opened.append(_FakeConnection(f"reconnect-{len(opened)}"))
1126 return opened[-1]
1127
1128 session = Server(
1129 "stuck",
1130 adapter="duckdb",
1131 connection=opened[0],
1132 connection_id="stuck-connection",
1133 reconnect=reconnect,
1134 )
1135 assert session.connection() is opened[0]
1136 session.abandon()
1137 with pytest.raises(HarlequinConnectionError) as raised:
1138 session.connection()
1139 assert "cancelled a query that did not stop" in raised.value.msg
1140 assert "--session-reset" in raised.value.msg
1141 # the abandoned connection is left to its thread, not closed under it
1142 assert not opened[0].closed # type: ignore[attr-defined]
1143 session.reset()
1144 assert session.connection() is opened[-1]
1145
1146
1147 # --- the turnstile ---------------------------------------------------------------
1148
1149
1150 def test_the_turnstile_serves_in_arrival_order() -> None:
1151 turnstile = server.Turnstile()
1152 order: list[int] = []
1153 assert turnstile.enter(None)
1154
1155 def wait_turn(number: int) -> None:
1156 turnstile.enter(None)
1157 order.append(number)
1158 turnstile.leave()
1159
1160 threads = []
1161 for number in (1, 2):
1162 thread = threading.Thread(target=wait_turn, args=(number,))
1163 thread.start()
1164 threads.append(thread)
1165
1166 # each ticket is taken before the next thread starts, so the arrival
1167 # order is this loop's rather than the scheduler's
1168 def has_arrived(waiting: int = number) -> bool:
1169 return turnstile.snapshot()[1] == waiting
1170
1171 wait_until(has_arrived, description=f"thread {number} to take its ticket")
1172
1173 turnstile.leave()
1174 for thread in threads:
1175 thread.join(5)
1176 assert order == [1, 2]
1177
1178
1179 def test_the_turnstile_gives_up_on_a_deadline() -> None:
1180 turnstile = server.Turnstile()
1181 assert turnstile.enter(None)
1182 started = time.monotonic()
1183 assert not turnstile.enter(0.05)
1184 assert time.monotonic() - started < 2
1185 assert turnstile.snapshot() == (True, 0)
1186 turnstile.leave()
1187 assert turnstile.enter(0.05)
1188
1189
1190 # --- the recorder -------------------------------------------------------------------
1191
1192
1193 def test_the_recorder_keeps_the_order_the_streams_were_written_in() -> None:
1194 """A note between two result sets reaches the terminal between them."""
1195 recorder = server.Recorder(stdout_isatty=True)
1196 out, err = recorder.stdout(), recorder.stderr()
1197 out.write("one\n")
1198 out.buffer.write(b"two\n")
1199 err.write("note\n")
1200 out.write("three\n")
1201 assert [(kind, bytes(data)) for kind, data in recorder.segments] == [
1202 (protocol.STDOUT, b"one\ntwo\n"),
1203 (protocol.STDERR, b"note\n"),
1204 (protocol.STDOUT, b"three\n"),
1205 ]
1206 assert out.isatty() and not err.isatty()
1207
1208
1209 def test_click_writes_binary_output_to_the_recorder() -> None:
1210 """`-o -` is `click.open_file("-", "wb")`, which has to find the buffer."""
1211 recorder = server.Recorder()
1212 stream = recorder.stdout()
1213 saved = sys.stdout
1214 sys.stdout = stream
1215 try:
1216 click.open_file("-", mode="wb").write(b"bytes\n")
1217 click.echo("text")
1218 finally:
1219 sys.stdout = saved
1220 assert bytes(recorder.segments[0][1]) == b"bytes\ntext\n"
1221
1222
1223 # --- a real server, in a fresh interpreter -------------------------------------
1224
1225
1226 @pytest.fixture
1227 def warm(serve_session: ServeSession) -> WarmSession:
1228 return serve_session("warm")
1229
1230
1231 @pytest.fixture
1232 def send(hsql_subprocess: HsqlSubprocess, warm: WarmSession) -> HsqlSubprocess:
1233 """One invocation, sent to the session by the real console script."""
1234
1235 def _send(argv: Sequence[str], **kwargs: Any) -> subprocess.CompletedProcess[bytes]:
1236 return hsql_subprocess(["--session", warm.name, *argv], env=warm.env, **kwargs)
1237
1238 return _send
1239
1240
1241 @needs_unix_sockets
1242 def test_a_session_answers(send: HsqlSubprocess, warm: WarmSession) -> None:
1243 proc = send(["-c", "select 1 as a"])
1244 assert proc.returncode == ExitCode.OK
1245 assert proc.stdout == b" a\n---\n 1\n(1 row)\n"
1246 assert proc.stderr == b""
1247
1248
1249 @needs_unix_sockets
1250 @pytest.mark.session_divergent
1251 def test_a_temp_table_survives_between_invocations(
1252 send: HsqlSubprocess, hsql_subprocess: HsqlSubprocess
1253 ) -> None:
1254 """The single most useful thing about the feature, and the one nobody reads
1255 the docs to discover. Cold, the second invocation has no such table."""
1256 assert (
1257 send(
1258 ["--format", "none", "-c", "create temp table t as select 7 as v"]
1259 ).returncode
1260 == 0
1261 )
1262 warm_result = send(["-tAc", "select v from t"])
1263 assert warm_result.returncode == ExitCode.OK
1264 assert warm_result.stdout == b"7\n"
1265 cold = ["-a", "duckdb", "--no-init", ":memory:"]
1266 assert (
1267 hsql_subprocess(
1268 [*cold, "-c", "create temp table t as select 7 as v"]
1269 ).returncode
1270 == 0
1271 )
1272 cold_result = hsql_subprocess([*cold, "-tAc", "select v from t"])
1273 assert cold_result.returncode == ExitCode.QUERY
1274 assert b"does not exist" in cold_result.stderr
1275
1276
1277 @needs_unix_sockets
1278 @pytest.mark.session_divergent
1279 def test_a_setting_survives_between_invocations(send: HsqlSubprocess) -> None:
1280 assert send(["--format", "none", "-c", "set TimeZone='Asia/Tokyo'"]).returncode == 0
1281 proc = send(["-tAc", "select current_setting('TimeZone')"])
1282 assert proc.stdout == b"Asia/Tokyo\n"
1283
1284
1285 @needs_unix_sockets
1286 @pytest.mark.session_divergent
1287 def test_a_reset_clears_the_sessions_state(send: HsqlSubprocess) -> None:
1288 send(["--format", "none", "-c", "create temp table t as select 7 as v"])
1289 proc = send(["--session-reset"])
1290 assert proc.returncode == ExitCode.OK
1291 assert proc.stdout == b""
1292 assert b"reconnected" in proc.stderr
1293 assert send(["-c", "select v from t"]).returncode == ExitCode.QUERY
1294
1295
1296 @needs_unix_sockets
1297 def test_a_relative_output_path_is_the_clients(
1298 send: HsqlSubprocess, tmp_path: Path
1299 ) -> None:
1300 """The server writes `-o`, resolved where the caller is, not where it is."""
1301 client_dir = tmp_path / "client"
1302 client_dir.mkdir()
1303 proc = send(["--csv", "-o", "out.csv", "-c", "select 1 as a"], cwd=client_dir)
1304 assert proc.returncode == ExitCode.OK
1305 assert proc.stdout == b""
1306 assert (client_dir / "out.csv").read_bytes() == b"a\n1\n"
1307
1308
1309 @needs_unix_sockets
1310 def test_a_relative_script_path_is_the_clients(
1311 send: HsqlSubprocess, tmp_path: Path
1312 ) -> None:
1313 client_dir = tmp_path / "client"
1314 client_dir.mkdir()
1315 (client_dir / "q.sql").write_text("select 'from a file' as a")
1316 proc = send(["-tAf", "q.sql"], cwd=client_dir)
1317 assert proc.returncode == ExitCode.OK
1318 assert proc.stdout == b"from a file\n"
1319
1320
1321 @needs_unix_sockets
1322 def test_a_config_file_where_the_client_is_applies_its_per_request_keys(
1323 send: HsqlSubprocess, tmp_path: Path
1324 ) -> None:
1325 """Config discovery is cwd-dependent, and the cwd is the client's."""
1326 client_dir = tmp_path / "project"
1327 client_dir.mkdir()
1328 (client_dir / ".harlequin.toml").write_text(
1329 'default_profile = "here"\n[profiles.here]\nformat = "csv"\n'
1330 )
1331 proc = send(["-c", "select 1 as a"], cwd=client_dir)
1332 assert proc.returncode == ExitCode.OK
1333 assert proc.stdout == b"a\n1\n"
1334
1335
1336 @needs_unix_sockets
1337 def test_a_typed_profile_resolves_where_the_client_is(
1338 send: HsqlSubprocess, tmp_path: Path
1339 ) -> None:
1340 """The session must resolve a `-P` against the *client's* directory, or a
1341 caller in a project would silently get a profile they did not write."""
1342 client_dir = tmp_path / "project"
1343 client_dir.mkdir()
1344 (client_dir / ".harlequin.toml").write_text(
1345 '[profiles.local]\nformat = "csv"\nlimit = 3\n'
1346 )
1347 proc = send(["-P", "local", "-c", "select 1 as a"], cwd=client_dir)
1348 assert proc.returncode == ExitCode.OK
1349 assert proc.stdout == b"a\n1\n"
1350
1351
1352 @needs_unix_sockets
1353 def test_the_config_path_the_caller_exported_travels_with_the_request(
1354 warm: WarmSession, hsql_subprocess: HsqlSubprocess, tmp_path: Path
1355 ) -> None:
1356 """`HARLEQUIN_CONFIG_PATH` is `--config-path` spelled as an environment
1357 variable, so a session that honored the flag and ignored the variable
1358 would read a config file neither of them named."""
1359 named = tmp_path / "elsewhere.toml"
1360 named.write_text('default_profile = "here"\n[profiles.here]\nformat = "csv"\n')
1361 proc = hsql_subprocess(
1362 ["--session", warm.name, "-c", "select 1 as a"],
1363 env={**warm.env, "HARLEQUIN_CONFIG_PATH": str(named)},
1364 )
1365 assert proc.returncode == ExitCode.OK
1366 assert proc.stdout == b"a\n1\n"
1367
1368
1369 @needs_unix_sockets
1370 def test_the_servers_own_config_path_is_not_the_requests(
1371 serve_session: ServeSession, hsql_subprocess: HsqlSubprocess, tmp_path: Path
1372 ) -> None:
1373 """The forwarded environment is the caller's: a variable the caller did not
1374 set arrives absent, rather than as whatever the operator exported."""
1375 servers = tmp_path / "server.toml"
1376 servers.write_text('default_profile = "there"\n[profiles.there]\nformat = "csv"\n')
1377 session = serve_session(
1378 "envd",
1379 "-a",
1380 "duckdb",
1381 "--no-init",
1382 ":memory:",
1383 env={"HARLEQUIN_CONFIG_PATH": str(servers)},
1384 )
1385 proc = hsql_subprocess(
1386 ["--session", "envd", "-c", "select 1 as a"], env=session.env
1387 )
1388 assert proc.returncode == ExitCode.OK
1389 # the table layout, and not the csv the server's own config file asks for
1390 assert proc.stdout == b" a\n---\n 1\n(1 row)\n"
1391
1392
1393 @needs_unix_sockets
1394 def test_piped_sql_reaches_the_session(send: HsqlSubprocess) -> None:
1395 proc = send(["-f", "-", "--csv"], stdin=b"select 3 as three")
1396 assert proc.returncode == ExitCode.OK
1397 assert proc.stdout == b"three\n3\n"
1398
1399
1400 def test_a_session_with_no_connection_says_so(in_process_server: Server) -> None:
1401 """`state` is what tells a session that is merely busy from one a caller
1402 has to reset before it will answer anything."""
1403 assert in_process_server.status()["state"] == "idle"
1404 in_process_server.abandon()
1405 assert in_process_server.status()["state"] == "unavailable"
1406
1407
1408 def test_a_status_carries_no_secret(duckdb_adapter: Any) -> None:
1409 """A session's command line is long-lived and visible in `ps`, and this is
1410 the document that would otherwise put its credentials in a caller's
1411 stdout."""
1412 adapter = duckdb_adapter([":memory:"], no_init=True)
1413 session = Server(
1414 "dsn",
1415 adapter="duckdb",
1416 connection=adapter.connect(),
1417 connection_id="dsn-connection",
1418 reconnect=adapter.connect,
1419 identity={
1420 "conn_str": ("postgres://ted:hunter2@warehouse:5432/analytics",),
1421 "password": "hunter2",
1422 },
1423 )
1424 status = session.status()
1425 assert status["connection"] == "postgres://ted:********@warehouse:5432/analytics"
1426 assert status["connection_options"]["password"] == "********"
1427 assert "hunter2" not in json.dumps(status)
1428
1429
1430 @needs_unix_sockets
1431 def test_a_session_says_what_it_is(send: HsqlSubprocess, warm: WarmSession) -> None:
1432 """The whole of `--session-status`: JSON on stdout, and the identity the
1433 session recorded when it connected."""
1434 send(["--format", "none", "-c", "select 1"])
1435 proc = send(["--session-status"])
1436 assert proc.returncode == ExitCode.OK
1437 assert proc.stderr == b""
1438 status = json.loads(proc.stdout)
1439 assert status["session"] == "warm"
1440 assert status["adapter"] == "duckdb"
1441 assert status["connection"] == ":memory:"
1442 assert status["connection_options"]["no_init"] is True
1443 assert status["version"] == protocol.VERSION
1444 assert status["pid"] == warm.process.pid
1445 assert status["requests"] == 1
1446 assert status["state"] == "idle"
1447 assert status["queued"] == 0
1448 assert status["ssh"] is None
1449 assert status["uptime_s"] >= 0
1450
1451
1452 def test_a_busy_session_does_not_ask_its_driver_for_the_mode(
1453 duckdb_adapter: Any,
1454 ) -> None:
1455 """The one field a status has to ask the connection for, so it takes a
1456 turn rather than reading beside one -- and reports null instead of
1457 waiting for it. DuckDB has no transaction mode, so the label comes from a
1458 stand-in; what is pinned is that a held turnstile suppresses the read."""
1459 adapter = duckdb_adapter([":memory:"], no_init=True)
1460 connection = adapter.connect()
1461 reads: list[int] = []
1462
1463 class Transacting:
1464 def __getattr__(self, name: str) -> Any:
1465 return getattr(connection, name)
1466
1467 @property
1468 def transaction_mode(self) -> HarlequinTransactionMode:
1469 reads.append(1)
1470 return HarlequinTransactionMode(label="Manual")
1471
1472 session = Server(
1473 "tx",
1474 adapter="duckdb",
1475 connection=cast(Any, Transacting()),
1476 connection_id="tx-connection",
1477 reconnect=adapter.connect,
1478 )
1479 # one read at start-up, which is the mode a later one is compared against
1480 assert reads == [1]
1481 assert session.status()["transaction_mode"] == "Manual"
1482 assert reads == [1, 1]
1483 assert session._turnstile.enter(0)
1484 try:
1485 busy = session.status()
1486 finally:
1487 session._turnstile.leave()
1488 assert busy["state"] == "busy"
1489 assert busy["transaction_mode"] is None
1490 # not merely null: the driver was never asked
1491 assert reads == [1, 1]
1492
1493
1494 @needs_unix_sockets
1495 def test_a_status_is_answered_while_a_request_holds_the_connection(
1496 blocked: Blocked, warm: WarmSession, hsql_subprocess: HsqlSubprocess
1497 ) -> None:
1498 """A status takes no turn at the connection. The `blocked` fixture holds
1499 one deterministically -- it is inside `_run`, reading its script from a
1500 FIFO -- so a status that started queueing would time out here rather than
1501 hang the run."""
1502 proc = hsql_subprocess(
1503 ["--session", warm.name, "--session-status"], env=warm.env, timeout=30
1504 )
1505 assert proc.returncode == ExitCode.OK
1506 assert json.loads(proc.stdout)["state"] == "busy"
1507 blocked.release()
1508 assert blocked.process.wait(30) == ExitCode.OK
1509
1510
1511 @needs_unix_sockets
1512 def test_a_status_is_answered_while_the_database_is_working(
1513 warm: WarmSession, hsql_subprocess: HsqlSubprocess, tmp_path: Path
1514 ) -> None:
1515 """The stronger half of the claim: the status arrives while duckdb is
1516 executing, not merely while a request holds the turnstile. A driver call
1517 holding the GIL or a process-wide lock would serialize the status, and a
1518 FIFO read releases the GIL.
1519
1520 `--timeout` bounds the query, so the session is free again for teardown.
1521 It only has to outlive the poll below, which returns on the first busy
1522 status."""
1523 query = subprocess.Popen(
1524 [
1525 sys.executable,
1526 "-c",
1527 "import sys\n"
1528 f"sys.argv = ['hsql', '--session', {warm.name!r}, '--timeout', "
1529 f"'5', '-c', {UNFINISHABLE!r}]\n"
1530 "from harlequin.hsql import main\n"
1531 "main()\n",
1532 ],
1533 stdout=subprocess.PIPE,
1534 stderr=subprocess.PIPE,
1535 cwd=tmp_path,
1536 env={**os.environ, **warm.env, "HOME": str(tmp_path)},
1537 )
1538 try:
1539 answered = _until_status(
1540 lambda: json.loads(
1541 hsql_subprocess(
1542 ["--session", warm.name, "--session-status"],
1543 env=warm.env,
1544 timeout=30,
1545 ).stdout
1546 ),
1547 lambda status: status["state"] == "busy",
1548 )
1549 assert answered["state"] == "busy"
1550 assert answered["queued"] == 0
1551 finally:
1552 query.kill()
1553 query.communicate(timeout=30)
1554
1555
1556 def _until_status(
1557 ask: Callable[[], dict[str, Any]],
1558 holds: Callable[[dict[str, Any]], bool],
1559 timeout: float = 30.0,
1560 ) -> dict[str, Any]:
1561 """Ask until the answer holds, so the test observes rather than sleeps."""
1562 deadline = time.monotonic() + timeout
1563 while time.monotonic() < deadline:
1564 status = ask()
1565 if holds(status):
1566 return status
1567 raise AssertionError("the session never reported what the test waited for")
1568
1569
1570 @needs_unix_sockets
1571 def test_a_status_takes_nothing_beside_it(send: HsqlSubprocess) -> None:
1572 """No parser sees a status ask, so a flag typed beside one is refused by
1573 name rather than silently dropped."""
1574 proc = send(["--session-status", "--csv"])
1575 assert proc.returncode == ExitCode.USAGE
1576 assert proc.stdout == b""
1577 assert b"takes no other options" in proc.stderr
1578
1579
1580 @needs_unix_sockets
1581 def test_a_mistyped_status_does_not_wait_for_the_query_it_asks_about(
1582 blocked: Blocked, warm: WarmSession, hsql_subprocess: HsqlSubprocess
1583 ) -> None:
1584 """`--session-status=1` is a typo click refuses either way, but one the
1585 scan missed would reach the session as a request and wait for a running
1586 query to say so."""
1587 proc = hsql_subprocess(
1588 ["--session", warm.name, "--session-status=1"], env=warm.env, timeout=30
1589 )
1590 assert proc.returncode == ExitCode.USAGE
1591 assert proc.stdout == b""
1592 assert b"--session-status is a flag and takes no value" in proc.stderr
1593 blocked.release()
1594 assert blocked.process.wait(30) == ExitCode.OK
1595
1596
1597 def test_a_bug_in_the_status_path_is_exit_70_and_not_someone_elses_stderr(
1598 in_process_server: Server, monkeypatch: pytest.MonkeyPatch
1599 ) -> None:
1600 """An escaping traceback would reach `threading.excepthook`, which writes
1601 to the stderr the in-flight *request* has swapped in -- so a bug here
1602 would print a server traceback into an unrelated caller's diagnostics."""
1603 monkeypatch.setattr(Server, "status", lambda self: 1 / 0, raising=True)
1604 left, right = socket.socketpair()
1605 with left, right:
1606 in_process_server._send_status(left, ["--session-status"])
1607 left.shutdown(socket.SHUT_WR)
1608 frames = []
1609 while (frame := protocol.recv_frame(right)) is not None:
1610 frames.append(frame)
1611 assert frames[-1] == (protocol.EXIT, bytes([ExitCode.CRASH]))
1612 said = b"".join(payload for kind, payload in frames if kind == protocol.STDERR)
1613 assert b"hsql hit a bug in itself" in said
1614 assert b"Traceback" not in said
1615
1616
1617 @needs_unix_sockets
1618 def test_a_status_is_not_a_request_the_session_counts(
1619 send: HsqlSubprocess, warm: WarmSession
1620 ) -> None:
1621 send(["--session-status"])
1622 assert warm.stop() == ExitCode.OK
1623 assert "--session-status: exit 0" in warm.stderr()
1624 assert "session 'warm' stopped after 0 requests" in warm.stderr()
1625
1626
1627 @needs_unix_sockets
1628 def test_a_request_that_asserts_the_sessions_connection_is_served(
1629 send: HsqlSubprocess,
1630 ) -> None:
1631 """End to end: the identity the server recorded is what a request's typed
1632 connection options are compared against."""
1633 assert send(["-a", "duckdb", "-tAc", "select 1"]).returncode == ExitCode.OK
1634 refused = send(["-a", "sqlite", "-c", "select 1"])
1635 assert refused.returncode == ExitCode.USAGE
1636 assert b"was started with 'duckdb'" in refused.stderr
1637
1638
1639 @needs_unix_sockets
1640 def test_the_servers_own_streams_carry_only_its_log(
1641 warm: WarmSession, send: HsqlSubprocess
1642 ) -> None:
1643 """Result sets go to the client that asked; the operator sees a line per request."""
1644 send(["-c", "select 'to the client' as a"])
1645 send(["-c", "select * from nowhere"])
1646 assert warm.stop() == ExitCode.OK
1647 log = warm.stderr()
1648 assert "to the client" not in log
1649 assert "session 'warm' is ready (duckdb)" in log
1650 assert "request 1: exit 0" in log
1651 assert "request 2: exit 1" in log
1652 assert "session 'warm' stopped after 2 requests" in log
1653 assert warm.process.stdout is not None
1654
1655
1656 @needs_unix_sockets
1657 def test_a_stopped_session_takes_its_socket_with_it(warm: WarmSession) -> None:
1658 assert warm.socket_path.exists()
1659 assert warm.stop() == ExitCode.OK
1660 assert not warm.socket_path.exists()
1661
1662
1663 @needs_unix_sockets
1664 def test_a_second_server_under_the_same_name_is_refused(
1665 warm: WarmSession, serve_session: ServeSession
1666 ) -> None:
1667 second = serve_session("warm", wait=False)
1668 assert second.process.wait(30) == ExitCode.USAGE
1669 assert "already running" in second.stderr()
1670 # and the first is untouched: its socket is still the one that answers
1671 assert warm.socket_path.exists()
1672
1673
1674 @needs_unix_sockets
1675 def test_a_stale_socket_is_replaced(
1676 short_runtime_dir: Path, serve_session: ServeSession
1677 ) -> None:
1678 """A server that died leaves its file; the next one under that name is
1679 what unlinks it, since a client never does."""
1680 from harlequin.hsql.session import socket_path
1681
1682 (short_runtime_dir / "hsql").mkdir(mode=0o700)
1683 stale = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1684 stale.bind(socket_path("warm", {"XDG_RUNTIME_DIR": str(short_runtime_dir)}))
1685 stale.close()
1686 session = serve_session("warm")
1687 assert session.socket_path.exists()
1688 assert session.stop() == ExitCode.OK
1689
1690
1691 @needs_unix_sockets
1692 def test_a_runtime_dir_someone_else_can_reach_is_refused(
1693 short_runtime_dir: Path, serve_session: ServeSession
1694 ) -> None:
1695 shared = short_runtime_dir / "hsql"
1696 shared.mkdir()
1697 os.chmod(shared, 0o777)
1698 session = serve_session("warm", wait=False)
1699 assert session.process.wait(30) == ExitCode.USAGE
1700 assert "cannot listen" in session.stderr()
1701
1702
1703 @needs_unix_sockets
1704 def test_serve_on_a_connection_that_fails_exits_3(serve_session: ServeSession) -> None:
1705 session = serve_session(
1706 "warm", "-a", "duckdb", "--no-init", "/nonexistent/dir/x.db", wait=False
1707 )
1708 assert session.process.wait(30) == ExitCode.CONNECTION
1709
1710
1711 class Blocked:
1712 """A request the test holds open: the server is reading a FIFO for its SQL.
1713
1714 Deterministic where a slow query is not: opening the FIFO for writing
1715 blocks until the server has opened it to read, which is after the request
1716 took its turn, so everything sent after that is queued behind it.
1717 """
1718
1719 def __init__(self, fifo: Path, warm: WarmSession, tmp_path: Path) -> None:
1720 self.fifo = fifo
1721 os.mkfifo(fifo)
1722 self.process = subprocess.Popen(
1723 [
1724 sys.executable,
1725 "-c",
1726 "import sys\n"
1727 f"sys.argv = ['hsql', '--session', {warm.name!r}, "
1728 f"'--format', 'none', '-f', {str(fifo)!r}]\n"
1729 "from harlequin.hsql import main\n"
1730 "main()\n",
1731 ],
1732 stdout=subprocess.PIPE,
1733 stderr=subprocess.PIPE,
1734 cwd=tmp_path,
1735 env={**os.environ, **warm.env, "HOME": str(tmp_path)},
1736 )
1737 self.writer = open(fifo, "w")
1738
1739 def release(self, sql: str = "select 1") -> None:
1740 self.writer.write(sql)
1741 self.writer.close()
1742
1743
1744 @pytest.fixture
1745 def blocked(
1746 warm: WarmSession, short_runtime_dir: Path, tmp_path: Path
1747 ) -> Iterator[Blocked]:
1748 held = Blocked(short_runtime_dir / "script.fifo", warm, tmp_path)
1749 yield held
1750 if held.process.poll() is None:
1751 held.process.kill()
1752 held.process.wait(5)
1753 if held.process.stdout is not None:
1754 held.process.stdout.close()
1755 if held.process.stderr is not None:
1756 held.process.stderr.close()
1757
1758
1759 @needs_unix_sockets
1760 @pytest.mark.session_divergent
1761 def test_a_second_client_waits_its_turn(blocked: Blocked, send: HsqlSubprocess) -> None:
1762 """One connection, one request at a time: the second client's query sees
1763 what the first one, still running when it was sent, went on to create."""
1764 second = subprocess.Popen(
1765 [
1766 sys.executable,
1767 "-c",
1768 "import sys\n"
1769 "sys.argv = ['hsql', '--session', 'warm', '-tAc', 'select v from q']\n"
1770 "from harlequin.hsql import main\n"
1771 "main()\n",
1772 ],
1773 stdout=subprocess.PIPE,
1774 stderr=subprocess.PIPE,
1775 env={**os.environ, **blocked_env(blocked)},
1776 )
1777 blocked.release("create temp table q as select 42 as v")
1778 out, err = second.communicate(timeout=30)
1779 assert second.returncode == ExitCode.OK, err
1780 assert out == b"42\n"
1781 assert blocked.process.wait(30) == ExitCode.OK
1782
1783
1784 def blocked_env(blocked: Blocked) -> dict[str, str]:
1785 return {"XDG_RUNTIME_DIR": str(blocked.fifo.parent)}
1786
1787
1788 @needs_unix_sockets
1789 def test_a_client_that_dies_mid_query_does_not_take_the_session_down(
1790 blocked: Blocked, send: HsqlSubprocess, warm: WarmSession
1791 ) -> None:
1792 blocked.process.kill()
1793 blocked.process.wait(5)
1794 blocked.release("select 1")
1795 proc = send(["-tAc", "select 'still up'"])
1796 assert proc.returncode == ExitCode.OK
1797 assert proc.stdout == b"still up\n"
1798 assert warm.stop() == ExitCode.OK
1799 assert "a client went away" in warm.stderr()
1800
1801
1802 @needs_unix_sockets
1803 def test_a_timeout_stops_the_request_and_leaves_the_session_up(
1804 send: HsqlSubprocess,
1805 ) -> None:
1806 """The whole chain a served `--timeout` crosses: the deadline cancels, the
1807 request attributes it and exits 4, and the session is usable straight
1808 after -- DuckDB's cancel lands inside the grace period, so the connection
1809 is never abandoned. (The grace running out is `Deadline`'s own test: no
1810 adapter that cancels can reach it.)"""
1811 proc = send(["--timeout", "0.1", "-c", UNFINISHABLE])
1812 assert proc.returncode == ExitCode.TIMEOUT
1813 assert proc.stdout == b""
1814 assert b"timed out after 0.1s" in proc.stderr
1815 assert send(["-tAc", "select 'still up'"]).stdout == b"still up\n"
1816
1817
1818 @needs_unix_sockets
1819 def test_an_interrupted_query_stops_and_leaves_the_session_up(
1820 warm: WarmSession,
1821 send: HsqlSubprocess,
1822 hsql_subprocess: HsqlSubprocess,
1823 tmp_path: Path,
1824 ) -> None:
1825 """The whole chain a `Ctrl-C` crosses: the client sends a cancel naming
1826 its request on a second connection and exits 130, the session stops the
1827 query, and the connection is free straight after -- rather than held by a
1828 query nobody is waiting for.
1829
1830 The next invocation answering is what proves the query stopped: an
1831 interrupt that never landed would leave the session counting rows for the
1832 rest of the test. Which outcome the session logs is not pinned, because a
1833 status of `busy` is a request that has taken its turn and a `Ctrl-C` can
1834 beat it to the connection -- and stopping a run before it submits anything
1835 is as good as interrupting one that has."""
1836 query = subprocess.Popen(
1837 [
1838 sys.executable,
1839 "-c",
1840 "import sys\n"
1841 f"sys.argv = ['hsql', '--session', {warm.name!r}, '-c', {UNFINISHABLE!r}]\n"
1842 "from harlequin.hsql import main\n"
1843 "main()\n",
1844 ],
1845 stdout=subprocess.PIPE,
1846 stderr=subprocess.PIPE,
1847 cwd=tmp_path,
1848 env={**os.environ, **warm.env, "HOME": str(tmp_path)},
1849 )
1850
1851 # not before the session has the query: an interrupt during start-up is
1852 # one with no request to name, which is a different path
1853 def status() -> dict[str, Any]:
1854 return cast(
1855 "dict[str, Any]",
1856 json.loads(
1857 hsql_subprocess(
1858 ["--session", warm.name, "--session-status"],
1859 env=warm.env,
1860 timeout=30,
1861 ).stdout
1862 ),
1863 )
1864
1865 _until_status(status, lambda reported: reported["state"] == "busy")
1866 # `busy` is a request that has taken its turn, which is a moment before it
1867 # has parsed its argv and asked for the connection; one more round trip
1868 # puts the interrupt inside the query rather than ahead of it
1869 assert status()["state"] == "busy"
1870 query.send_signal(signal.SIGINT)
1871 out, err = query.communicate(timeout=30)
1872 assert query.returncode == ExitCode.INTERRUPT
1873 # the rows the cancel produced are not rows the query returned
1874 assert out == b""
1875 assert err == b""
1876 assert send(["-tAc", "select 'still up'"], timeout=30).stdout == b"still up\n"
1877 assert warm.stop() == ExitCode.OK
1878 assert "cancel: " in warm.stderr()
1879
1880
1881 @needs_unix_sockets
1882 def test_a_client_that_gives_up_while_it_waits_runs_nothing(
1883 blocked: Blocked, warm: WarmSession, send: HsqlSubprocess, tmp_path: Path
1884 ) -> None:
1885 """A request cancelled in the queue never reaches the database. The one
1886 ahead of it finishes and releases the session, and what the caller gave up
1887 on does not then run behind them."""
1888 queued = subprocess.Popen(
1889 [
1890 sys.executable,
1891 "-c",
1892 "import sys\n"
1893 f"sys.argv = ['hsql', '--session', {warm.name!r}, '-c', "
1894 "'create temp table gave_up as select 1']\n"
1895 "from harlequin.hsql import main\n"
1896 "main()\n",
1897 ],
1898 stdout=subprocess.PIPE,
1899 stderr=subprocess.PIPE,
1900 cwd=tmp_path,
1901 env={**os.environ, **warm.env, "HOME": str(tmp_path)},
1902 )
1903 try:
1904 _until_status(
1905 lambda: json.loads(send(["--session-status"], timeout=30).stdout),
1906 lambda status: status["queued"] == 1,
1907 )
1908 queued.send_signal(signal.SIGINT)
1909 assert queued.wait(30) == ExitCode.INTERRUPT
1910 finally:
1911 queued.communicate(timeout=30)
1912 blocked.release()
1913 assert blocked.process.wait(30) == ExitCode.OK
1914 counted = send(
1915 ["-tAc", "select count(*) from duckdb_tables() where table_name = 'gave_up'"],
1916 timeout=30,
1917 )
1918 assert counted.stdout == b"0\n"
1919
1920
1921 @needs_unix_sockets
1922 def test_a_queue_timeout_is_not_a_query_timeout(
1923 serve_session: ServeSession,
1924 hsql_subprocess: HsqlSubprocess,
1925 short_runtime_dir: Path,
1926 tmp_path: Path,
1927 ) -> None:
1928 """A client that never reached the database exits 4 saying so -- a
1929 different fact from a query that ran too long, and one the caller acts on
1930 differently."""
1931 session = serve_session(
1932 "queued", "--queue-timeout", "0.2", "-a", "duckdb", "--no-init", ":memory:"
1933 )
1934 held = Blocked(short_runtime_dir / "q.fifo", session, tmp_path)
1935 try:
1936 proc = hsql_subprocess(
1937 ["--session", "queued", "-c", "select 1"], env=session.env
1938 )
1939 assert proc.returncode == ExitCode.TIMEOUT
1940 assert proc.stdout == b""
1941 assert b"never reached the database" in proc.stderr
1942 assert b"--queue-timeout" in proc.stderr
1943 finally:
1944 held.release()
1945 held.process.wait(30)
1946 assert (
1947 hsql_subprocess(
1948 ["--session", "queued", "-tAc", "select 2"], env=session.env
1949 ).stdout
1950 == b"2\n"
1951 )
1952
1953
1954 # --- the wire, from a client that is not ours -------------------------------------
1955
1956
1957 def raw_request(
1958 warm: WarmSession, **fields: Any
1959 ) -> tuple[list[tuple[int, bytes]], int]:
1960 """Send one request over the protocol by hand, and return what came back."""
1961 connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1962 with connection:
1963 connection.connect(str(warm.socket_path))
1964 hello = protocol.recv_frame(connection)
1965 assert hello == (protocol.HELLO, protocol.VERSION.encode())
1966 request = {
1967 "argv": [],
1968 "cwd": os.getcwd(),
1969 "environ": {},
1970 "stdin": None,
1971 "request_id": A_REQUEST,
1972 **fields,
1973 }
1974 protocol.send_frame(
1975 connection, protocol.REQUEST, protocol.pack_request(**request)
1976 )
1977 frames: list[tuple[int, bytes]] = []
1978 while True:
1979 frame = protocol.recv_frame(connection)
1980 assert frame is not None
1981 if frame[0] == protocol.EXIT:
1982 return frames, int.from_bytes(frame[1], "big")
1983 frames.append(frame)
1984
1985
1986 @needs_unix_sockets
1987 def test_the_server_refuses_a_dash_f_dash_that_carried_no_stdin(
1988 warm: WarmSession,
1989 ) -> None:
1990 """The check that turns every miss of the client's argv scan into an exit 2."""
1991 frames, code = raw_request(warm, argv=["-f", "-"], stdin=None)
1992 assert code == ExitCode.USAGE
1993 assert b"carried none" in b"".join(
1994 data for kind, data in frames if kind == protocol.STDERR
1995 )
1996
1997
1998 @needs_unix_sockets
1999 def test_the_server_refuses_a_working_directory_it_cannot_enter(
2000 warm: WarmSession,
2001 ) -> None:
2002 frames, code = raw_request(
2003 warm, argv=["-c", "select 1"], cwd="/nonexistent/anywhere"
2004 )
2005 assert code == ExitCode.USAGE
2006 assert b"cannot be entered" in b"".join(
2007 data for kind, data in frames if kind == protocol.STDERR
2008 )
2009
2010
2011 @needs_unix_sockets
2012 def test_the_servers_stdout_is_chunked(warm: WarmSession) -> None:
2013 """Many `STDOUT` frames then one `EXIT`, so that streaming has somewhere to land."""
2014 wide = "select repeat('x', 1000) as a from range(200)"
2015 frames, code = raw_request(warm, argv=["-tA", "--display-rows", "-1", "-c", wide])
2016 assert code == ExitCode.OK
2017 stdout = [data for kind, data in frames if kind == protocol.STDOUT]
2018 assert len(stdout) > 1
2019 assert all(len(chunk) <= protocol.CHUNK_SIZE for chunk in stdout)
2020 assert b"".join(stdout) == (b"x" * 1000 + b"\n") * 200
2021
2022
2023 @needs_unix_sockets
2024 def test_a_client_that_sends_no_request_is_dropped(
2025 warm: WarmSession, send: HsqlSubprocess
2026 ) -> None:
2027 """A version it refused to be served by, or one that died: the server
2028 reads the hello, hears nothing back, and goes on serving."""
2029 connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
2030 with connection:
2031 connection.connect(str(warm.socket_path))
2032 assert protocol.recv_frame(connection) is not None
2033 assert send(["-tAc", "select 1"]).stdout == b"1\n"
2034
2035
2036 @needs_unix_sockets
2037 def test_color_auto_reads_the_callers_terminal(warm: WarmSession) -> None:
2038 """On the server every stream is a buffer, so the request has to say."""
2039 argv = ["--color", "auto", "-c", "select 1 as a"]
2040 plain, _ = raw_request(warm, argv=argv, stdout_isatty=False)
2041 styled, _ = raw_request(warm, argv=argv, stdout_isatty=True)
2042 assert b"\x1b[" not in b"".join(data for _, data in plain)
2043 assert b"\x1b[" in b"".join(data for _, data in styled)
2044 honored, _ = raw_request(
2045 warm, argv=argv, stdout_isatty=True, environ={"NO_COLOR": "1"}
2046 )
2047 assert b"\x1b[" not in b"".join(data for _, data in honored)
2048
2049
2050 @needs_unix_sockets
2051 def test_the_peer_uid_is_ours_on_a_socketpair() -> None:
2052 left, right = socket.socketpair(socket.AF_UNIX)
2053 with left, right:
2054 uid = server.peer_uid(right)
2055 assert uid is None or uid == os.getuid()
2056
2057
2058 # --- the session's own clocks -------------------------------------------------
2059
2060
2061 def with_clocks(
2062 duckdb_adapter: Any,
2063 *,
2064 idle_timeout: float | None = None,
2065 max_lifetime: float | None = None,
2066 ) -> Server:
2067 """A session whose two clocks a test can wind on by hand.
2068
2069 Wound rather than waited out: an expiry these can only reach by sleeping
2070 is one CI reaches by flaking, and what is being asserted is which clock
2071 answers rather than how fast a runner is.
2072 """
2073 adapter = duckdb_adapter([":memory:"], no_init=True)
2074 return Server(
2075 "clocked",
2076 adapter="duckdb",
2077 connection=adapter.connect(),
2078 connection_id="clocked-connection",
2079 reconnect=adapter.connect,
2080 idle_timeout=idle_timeout,
2081 max_lifetime=max_lifetime,
2082 )
2083
2084
2085 def test_a_session_with_neither_clock_set_never_stops_itself(
2086 duckdb_adapter: Any,
2087 ) -> None:
2088 """`--idle-timeout 0` and `--max-lifetime 0` are how an operator asks for
2089 a session that runs until something stops it, and None is what the command
2090 turns a zero into."""
2091 session = with_clocks(duckdb_adapter)
2092 session._started -= 10_000
2093 session._active_at -= 10_000
2094 assert session._expired() is None
2095 assert session.status()["idle_timeout_s"] is None
2096 assert session.status()["expires_in_s"] is None
2097
2098
2099 def test_a_session_nobody_has_used_runs_out_of_idle_time(duckdb_adapter: Any) -> None:
2100 session = with_clocks(duckdb_adapter, idle_timeout=30.0)
2101 assert session._expired() is None
2102 session._active_at -= 31
2103 assert session._expired() == ("--idle-timeout", 30.0)
2104
2105
2106 def test_the_idle_clock_does_not_run_while_a_request_does(
2107 duckdb_adapter: Any,
2108 ) -> None:
2109 """A query that takes an hour is a session in use, not one nobody wants:
2110 the clock is about a session sitting with nothing to do, so a held turn
2111 stops it -- and starts it again when the turn is given up."""
2112 session = with_clocks(duckdb_adapter, idle_timeout=30.0)
2113 session._active_at -= 31
2114 assert session._turnstile.enter(0)
2115 try:
2116 assert session._expired() is None
2117 finally:
2118 session._turnstile.leave()
2119 assert session._expired() == ("--idle-timeout", 30.0)
2120
2121
2122 def test_the_lifetime_clock_runs_whatever_the_session_is_doing(
2123 duckdb_adapter: Any,
2124 ) -> None:
2125 """It bounds the credential rather than the idleness, so a busy session is
2126 not exempt -- the request in flight is answered on the way down."""
2127 session = with_clocks(duckdb_adapter, max_lifetime=600.0)
2128 session._started -= 601
2129 assert session._turnstile.enter(0)
2130 try:
2131 assert session._expired() == ("--max-lifetime", 600.0)
2132 finally:
2133 session._turnstile.leave()
2134
2135
2136 def test_the_sooner_clock_is_the_one_that_answers(duckdb_adapter: Any) -> None:
2137 session = with_clocks(duckdb_adapter, idle_timeout=30.0, max_lifetime=600.0)
2138 session._started -= 601
2139 session._active_at -= 31
2140 assert session._expired() == ("--max-lifetime", 600.0)
2141
2142
2143 def test_a_status_says_when_the_session_will_go_away(duckdb_adapter: Any) -> None:
2144 """`expires_in_s` is the sooner of the two countdowns, and the idle one is
2145 not counting while a request holds the connection -- a session in the
2146 middle of a query is answered by its lifetime alone."""
2147 session = with_clocks(duckdb_adapter, idle_timeout=30.0, max_lifetime=600.0)
2148 status = session.status()
2149 assert status["idle_timeout_s"] == 30.0
2150 assert 29 <= status["expires_in_s"] <= 30
2151 assert session._turnstile.enter(0)
2152 try:
2153 busy = session.status()
2154 finally:
2155 session._turnstile.leave()
2156 assert busy["state"] == "busy"
2157 assert busy["idle_timeout_s"] == 30.0
2158 assert 599 <= busy["expires_in_s"] <= 600
2159
2160
2161 def test_a_countdown_that_has_run_out_is_zero_rather_than_negative(
2162 duckdb_adapter: Any,
2163 ) -> None:
2164 """The window between the clock running out and the accept loop reading
2165 it, which a caller polling should not see as a time in the past."""
2166 session = with_clocks(duckdb_adapter, max_lifetime=600.0)
2167 session._started -= 900
2168 assert session.status()["expires_in_s"] == 0.0
2169
2170
2171 def test_a_client_that_has_not_spoken_yet_is_not_an_idle_session(
2172 duckdb_adapter: Any,
2173 ) -> None:
2174 """A client is accepted before it says what it wants, and its first frame
2175 can be a `-f -` script something upstream is still producing. It is in no
2176 turnstile and has sent no request, so this count is the only thing that can
2177 see it -- and a session that stopped here would unlink the socket under a
2178 client that had already reached it."""
2179 session = with_clocks(duckdb_adapter, idle_timeout=30.0)
2180 session._active_at -= 31
2181 assert session._expired() == ("--idle-timeout", 30.0)
2182 with session._attending_lock:
2183 session._attending += 1
2184 try:
2185 assert session._expired() is None
2186 finally:
2187 with session._attending_lock:
2188 session._attending -= 1
2189 # and the clock was held rather than reset: it runs out as soon as the
2190 # client is gone, which is what keeps a status poll from being use
2191 assert session._expired() == ("--idle-timeout", 30.0)
2192
2193
2194 def test_a_request_is_what_the_idle_clock_counts(duckdb_adapter: Any) -> None:
2195 """A status poll asks a session what it is doing; it does not use it. An
2196 agent watching a session it has stopped sending queries to would otherwise
2197 keep the connection open forever by watching."""
2198 session = with_clocks(duckdb_adapter, idle_timeout=30.0)
2199 session._active_at -= 31
2200 session.status()
2201 assert session._expired() == ("--idle-timeout", 30.0)
2202
2203
2204 @needs_unix_sockets
2205 def test_a_session_waits_for_a_client_that_is_still_typing(
2206 serve_session: ServeSession, tmp_path: Path
2207 ) -> None:
2208 """End to end, and the case the count exists for: a client connects and
2209 shakes hands, and only then reads the script off its stdin. A session that
2210 counted parsed requests alone would unlink the socket under it, and the
2211 caller would get a broken pipe from a session that was up when they
2212 reached it."""
2213 session = serve_session(
2214 "warm",
2215 "-a",
2216 "duckdb",
2217 "--no-init",
2218 ":memory:",
2219 "--idle-timeout",
2220 "1",
2221 "--max-lifetime",
2222 "0",
2223 )
2224 client = subprocess.Popen(
2225 [
2226 sys.executable,
2227 "-c",
2228 "import sys\n"
2229 f"sys.argv = ['hsql', '--session', {session.name!r}, '-tAf', '-']\n"
2230 "from harlequin.hsql import main\n"
2231 "main()\n",
2232 ],
2233 stdin=subprocess.PIPE,
2234 stdout=subprocess.PIPE,
2235 stderr=subprocess.PIPE,
2236 cwd=tmp_path,
2237 env={**os.environ, **session.env},
2238 )
2239 # longer than the idle timeout, and the client is already connected: what
2240 # it has not done is say what it wants
2241 time.sleep(3)
2242 stdout, stderr = client.communicate(b"select 1 as a\n", timeout=30)
2243 assert client.returncode == ExitCode.OK, stderr
2244 assert stdout == b"1\n"
2245
2246
2247 @needs_unix_sockets
2248 def test_a_session_nobody_uses_stops_itself(serve_session: ServeSession) -> None:
2249 """End to end, and the one place the wall clock is the point: the accept
2250 loop reads the clocks between accepts, so nothing else has to notice."""
2251 session = serve_session(
2252 "warm", "-a", "duckdb", "--no-init", ":memory:", "--idle-timeout", "1"
2253 )
2254 assert session.process.wait(30) == ExitCode.OK
2255 log = session.stderr()
2256 assert "has had no request for 1s, so it is stopping (--idle-timeout)" in log
2257 assert "Pass `--idle-timeout 0`" in log
2258 assert "stopped after 0 requests" in log
2259 assert not session.socket_path.exists()
2260
2261
2262 @needs_unix_sockets
2263 def test_a_session_that_has_been_up_long_enough_stops_itself(
2264 serve_session: ServeSession, hsql_subprocess: HsqlSubprocess
2265 ) -> None:
2266 """The lifetime bounds the credential, so it ends a session the idle clock
2267 would have kept up -- and the status it answered first says so."""
2268 session = serve_session(
2269 "warm",
2270 "-a",
2271 "duckdb",
2272 "--no-init",
2273 ":memory:",
2274 "--idle-timeout",
2275 "0",
2276 "--max-lifetime",
2277 "2",
2278 )
2279 status = json.loads(
2280 hsql_subprocess(
2281 ["--session", session.name, "--session-status"], env=session.env, timeout=30
2282 ).stdout
2283 )
2284 assert status["idle_timeout_s"] is None
2285 assert 0 < status["expires_in_s"] <= 2
2286 assert session.process.wait(30) == ExitCode.OK
2287 assert "has been up for 2s, so it is stopping (--max-lifetime)" in session.stderr()
2288
2289
2290 @pytest.mark.parametrize(
2291 "seconds,written",
2292 [
2293 (45, "45s"),
2294 (0.5, "0.5s"),
2295 # not "1m30s": whole units only, and the largest that divides it
2296 (90, "90s"),
2297 (120, "2m"),
2298 (1800, "30m"),
2299 (28800, "8h"),
2300 ],
2301 )
2302 def test_a_duration_prints_the_way_a_person_writes_one(
2303 seconds: float, written: str
2304 ) -> None:
2305 """These print a knob's value back at whoever set it, and the two defaults
2306 are half an hour and eight hours."""
2307 from harlequin.hsql.diagnostics import format_duration
2308
2309 assert format_duration(seconds) == written
2310
2311
2312 # --- a transaction the session is holding open --------------------------------
2313
2314
2315 class Moody:
2316 """A connection whose transaction mode is whatever the test last set."""
2317
2318 def __init__(self, connection: Any, mode: str | None) -> None:
2319 self._connection = connection
2320 self.mode = mode
2321
2322 def __getattr__(self, name: str) -> Any:
2323 return getattr(self._connection, name)
2324
2325 @property
2326 def transaction_mode(self) -> HarlequinTransactionMode | None:
2327 if self.mode is None:
2328 return None
2329 return HarlequinTransactionMode(label=self.mode)
2330
2331
2332 def moody(duckdb_adapter: Any, mode: str | None = "Auto") -> tuple[Server, Moody]:
2333 """A session whose transaction mode the test moves, which no adapter does.
2334
2335 `transaction_mode` is a setting `toggle_transaction_mode()` mutates and
2336 hsql never calls, so a session reached only through hsql cannot leave the
2337 mode it connected in -- this stands in for one moved out of band.
2338 """
2339 adapter = duckdb_adapter([":memory:"], no_init=True)
2340 connection = Moody(adapter.connect(), mode)
2341 return (
2342 Server(
2343 "tx",
2344 adapter="duckdb",
2345 connection=cast(Any, connection),
2346 connection_id="tx-connection",
2347 reconnect=lambda: cast(Any, Moody(adapter.connect(), mode)),
2348 ),
2349 connection,
2350 )
2351
2352
2353 def noted(session: Server) -> str:
2354 """What a request's caller is told about the session's transaction mode."""
2355 segments: list[tuple[int, bytearray]] = []
2356 session._note_transaction_mode(segments)
2357 assert all(kind == protocol.STDERR for kind, _ in segments)
2358 return b"".join(data for _, data in segments).decode("utf-8")
2359
2360
2361 def test_a_session_left_in_another_transaction_mode_tells_its_caller(
2362 duckdb_adapter: Any,
2363 ) -> None:
2364 """The mode is the adapter's Auto/Manual setting, so what is reported is a
2365 session moved out of band rather than anything about open work. Said every
2366 time rather than once, because every request after the change runs under
2367 it, and the caller who needs to know is each of them."""
2368 session, connection = moody(duckdb_adapter)
2369 assert noted(session) == ""
2370 connection.mode = "Manual"
2371 first = noted(session)
2372 assert "session 'tx' is in transaction mode 'Manual'" in first
2373 assert "not the one it connected in" in first
2374 assert "--session-reset" in first
2375 # every time, not once
2376 assert noted(session) == first
2377
2378
2379 def test_a_session_in_the_mode_it_connected_in_says_nothing(
2380 duckdb_adapter: Any,
2381 ) -> None:
2382 """The default is the mode the session started in, so a session whose
2383 adapter has modes is as quiet as one whose adapter has none until
2384 something moves it."""
2385 quiet, _ = moody(duckdb_adapter, mode="Manual")
2386 assert noted(quiet) == ""
2387 modeless, _ = moody(duckdb_adapter, mode=None)
2388 assert noted(modeless) == ""
2389
2390
2391 def test_a_reset_makes_the_new_connections_mode_the_default(
2392 duckdb_adapter: Any,
2393 ) -> None:
2394 """A reset is a fresh connection, which is a session starting over: the
2395 mode it comes back in is the one a later request is compared against."""
2396 session, connection = moody(duckdb_adapter)
2397 connection.mode = "Manual"
2398 assert noted(session) != ""
2399 session.reset()
2400 assert noted(session) == ""
2401
2402
2403 def test_a_session_with_nothing_to_ask_is_not_asked_for_its_mode(
2404 duckdb_adapter: Any,
2405 ) -> None:
2406 """Reading it takes the connection, and an abandoned one belongs to the
2407 thread still inside it -- the one place a request must not touch it."""
2408 session, connection = moody(duckdb_adapter)
2409 connection.mode = "Manual"
2410 session.abandon()
2411 assert noted(session) == ""
2412 assert session.status()["transaction_mode"] is None
2413
2414
2415 def test_an_adapter_that_raises_asking_for_its_mode_has_nothing_to_say(
2416 duckdb_adapter: Any,
2417 ) -> None:
2418 """Adapters are third-party code and this runs after every request, so one
2419 that raises here is answered the way one with no modes is."""
2420 adapter = duckdb_adapter([":memory:"], no_init=True)
2421
2422 class Raising:
2423 def __getattr__(self, name: str) -> Any:
2424 raise AssertionError(name)
2425
2426 @property
2427 def transaction_mode(self) -> HarlequinTransactionMode:
2428 raise RuntimeError("the driver said no")
2429
2430 session = Server(
2431 "raises",
2432 adapter="duckdb",
2433 connection=cast(Any, Raising()),
2434 connection_id="raises-connection",
2435 reconnect=adapter.connect,
2436 )
2437 assert noted(session) == ""
2438 assert session.status()["transaction_mode"] is None
2439
2440
2441 @needs_unix_sockets
2442 def test_a_caller_hears_about_the_transaction_from_the_request_that_ran(
2443 monkeypatch: pytest.MonkeyPatch, duckdb_adapter: Any
2444 ) -> None:
2445 """Wired to `_attend` rather than only callable: on the request's own
2446 stream, after its output, so a caller reading stderr sees it beside
2447 whatever else the run had to say."""
2448 session, connection = moody(duckdb_adapter)
2449
2450 def ran(
2451 request: protocol.Request, in_flight: server.InFlight | None = None
2452 ) -> tuple[list[tuple[int, bytearray]], int]:
2453 connection.mode = "Manual"
2454 recorder = server.Recorder()
2455 print("a row", file=recorder.stdout())
2456 return recorder.segments, int(ExitCode.OK)
2457
2458 monkeypatch.setattr(session, "_run", ran)
2459 ours, theirs = socket.socketpair()
2460 with ours, theirs:
2461 protocol.send_frame(
2462 theirs,
2463 protocol.REQUEST,
2464 protocol.pack_request(
2465 argv=["-c", "select 1"],
2466 cwd=os.getcwd(),
2467 environ={},
2468 stdin=None,
2469 request_id=A_REQUEST,
2470 ),
2471 )
2472 session._attend(ours)
2473 assert protocol.recv_frame(theirs) == (
2474 protocol.HELLO,
2475 protocol.VERSION.encode(),
2476 )
2477 answered: list[tuple[int, bytes]] = []
2478 while True:
2479 frame = protocol.recv_frame(theirs)
2480 assert frame is not None
2481 if frame[0] == protocol.EXIT:
2482 assert int.from_bytes(frame[1], "big") == ExitCode.OK
2483 break
2484 answered.append(frame)
2485 stream = {kind: data for kind, data in answered}
2486 assert stream[protocol.STDOUT] == b"a row\n"
2487 assert b"is in transaction mode 'Manual'" in stream[protocol.STDERR]
2488
2489
2490 # --- a secret on a session's command line -------------------------------------
2491
2492
2493 @needs_unix_sockets
2494 @pytest.mark.parametrize(
2495 "argv,named,code",
2496 [
2497 (
2498 ["-a", "duckdb", "--no-init", ":memory:", "--md_token", "hunter2"],
2499 "--md_token",
2500 ExitCode.OK,
2501 ),
2502 # exit 3, which is what says the warning is written before the session
2503 # connects: this DSN names a warehouse that is not there
2504 (
2505 ["-a", "duckdb", "--no-init", "duckdb://ted:hunter2@warehouse/db"],
2506 "CONN_STR",
2507 ExitCode.CONNECTION,
2508 ),
2509 ],
2510 ids=["declared-option", "dsn"],
2511 )
2512 def test_a_secret_typed_beside_serve_is_warned_about(
2513 serve_session: ServeSession, argv: list[str], named: str, code: ExitCode
2514 ) -> None:
2515 """A password on a one-shot invocation is in `ps` for a third of a second
2516 and the same one on a session is there for hours, so the arithmetic is
2517 worth saying out loud. A warning and not a refusal: a container with no
2518 config file has nowhere else to put it yet.
2519
2520 What counts as a secret is the adapter's `secret=` and `harlequin.redact`'s
2521 reading of a DSN, not a list of flag names kept beside the check."""
2522 session = serve_session("warm", *argv, "--idle-timeout", "1", wait=False)
2523 assert session.process.wait(30) == code
2524 log = session.stderr()
2525 assert f"{named} put a secret on this command line" in log
2526 assert "hsql --serve warm -P PROFILE" in log
2527 # and the warning is not itself the leak
2528 assert "hunter2" not in log
2529
2530
2531 @needs_unix_sockets
2532 def test_a_secret_a_profile_holds_is_not_warned_about(
2533 serve_session: ServeSession, tmp_path: Path
2534 ) -> None:
2535 """A profile is the remedy the warning points at, so a value read out of
2536 one is the thing that went right."""
2537 path = tmp_path / "hsql.toml"
2538 path.write_text(
2539 '[profiles.prod]\nadapter = "duckdb"\nconn_str = [":memory:"]\n'
2540 'no_init = true\nmd_token = "hunter2"\n'
2541 )
2542 session = serve_session(
2543 "warm", "--config-path", str(path), "-P", "prod", "--idle-timeout", "1"
2544 )
2545 assert session.process.wait(30) == ExitCode.OK
2546 log = session.stderr()
2547 assert "put a secret on this command line" not in log
2548 assert "session 'warm' is ready (duckdb)" in log
2549
2550
2551 @needs_unix_sockets
2552 def test_a_serve_with_no_secret_on_it_says_nothing(serve_session: ServeSession) -> None:
2553 session = serve_session(
2554 "warm", "-a", "duckdb", "--no-init", ":memory:", "--idle-timeout", "1"
2555 )
2556 assert session.process.wait(30) == ExitCode.OK
2557 assert "put a secret on this command line" not in session.stderr()
2558
2559
2560 # --- the query log -----------------------------------------------------------
2561
2562
2563 def recorded(store: Path) -> list[dict[str, Any]]:
2564 """Every row written to a query log, oldest first."""
2565 db = sqlite3.connect(store)
2566 db.row_factory = sqlite3.Row
2567 try:
2568 return [dict(row) for row in db.execute("select * from queries order by id")]
2569 finally:
2570 db.close()
2571
2572
2573 def test_a_served_request_logs_under_the_sessions_connection(
2574 hsql: Hsql, in_process_server: Server, query_log_path: Path
2575 ) -> None:
2576 """A served request is refused every option the id is derived from, so the
2577 session is the only thing that can answer what its queries ran against."""
2578 res = hsql("-c", "select 1 as a", obj=served_by(in_process_server))
2579 assert res.exit_code == ExitCode.OK
2580
2581 (row,) = recorded(query_log_path)
2582 assert row["sql"] == "select 1 as a"
2583 assert row["connection"] == in_process_server.connection_id
2584
2585
2586 def test_a_served_request_can_opt_out_of_the_history(
2587 hsql: Hsql, in_process_server: Server, query_log_path: Path
2588 ) -> None:
2589 """Per-request, so one invocation can go unrecorded without the session
2590 having decided that for every other one."""
2591 served = served_by(in_process_server)
2592 assert hsql("-c", "select 1", obj=served).exit_code == ExitCode.OK
2593 assert hsql("--no-write-history", "-c", "select 2", obj=served).exit_code == (
2594 ExitCode.OK
2595 )
2596
2597 assert [row["sql"] for row in recorded(query_log_path)] == ["select 1"]
2598
2599
2600 @needs_unix_sockets
2601 def test_a_warm_run_and_a_cold_one_are_one_history(
2602 serve_session: ServeSession,
2603 hsql_subprocess: HsqlSubprocess,
2604 tmp_path: Path,
2605 ) -> None:
2606 """The point of keying a connection at all: the same database reached two
2607 ways is one list, not two."""
2608 database = tmp_path / "warehouse.db"
2609 session = serve_session("keyed", "-a", "duckdb", "--no-init", str(database))
2610 argv = ["-a", "duckdb", "--no-init", str(database)]
2611
2612 warm = hsql_subprocess(
2613 ["--session", session.name, "-c", "select 1 as a"], env=session.env
2614 )
2615 assert warm.returncode == ExitCode.OK, warm.stderr
2616 # the session holds the file, and duckdb locks it -- so the cold run is
2617 # the same caller reaching the same database after the session is gone
2618 session.stop()
2619 cold = hsql_subprocess([*argv, "-c", "select 2 as a"])
2620 assert cold.returncode == ExitCode.OK, cold.stderr
2621
2622 # wherever platformdirs put it on this platform; `clean_env` keeps it here
2623 (store,) = tmp_path.rglob("history.db")
2624 rows = recorded(store)
2625 assert [row["sql"] for row in rows] == ["select 1 as a", "select 2 as a"]
2626 assert rows[0]["connection"], "an unset id would make this test vacuous"
2627 assert rows[0]["connection"] == rows[1]["connection"]
2628
2629
2630 def test_a_run_cancelled_before_it_started_records_nothing(
2631 in_process_server: Server, query_log_path: Path
2632 ) -> None:
2633 """The statements were never submitted, so the history has nothing to hold.
2634
2635 Each is written as the database is asked to run it, which is a generator
2636 `execute()` draws from -- so the check that stops the run has to come
2637 before that generator rather than inside it, or a query the database never
2638 saw is in the caller's history.
2639 """
2640 in_flight = in_process_server._hold(A_REQUEST)
2641 in_flight.cancel()
2642 served = served_by(in_process_server, in_flight=in_flight)
2643 log = QueryLog(program="hsql", connection=served.connection_id, adapter="duckdb")
2644 run = _Run(served=served, log=log)
2645
2646 assert (
2647 _execute_all(
2648 served.connection(),
2649 [Statement(sql="select 1", index=0)],
2650 limit=RowLimit(),
2651 on_error="stop",
2652 run=run,
2653 )
2654 == []
2655 )
2656 log.close()
2657 # the store opens on the first write, so a run that records nothing does
2658 # not even create one
2659 assert not query_log_path.exists()
2660
2661
2662 def test_every_statement_a_served_cancel_stopped_says_so(
2663 in_process_server: Server, query_log_path: Path
2664 ) -> None:
2665 """The served half of the cold run's cancel: the run reads the session's
2666 cancel where a cold one reads its clock, and both mark the statement in
2667 flight and every one after it.
2668
2669 Cancelled between two fetches rather than under a slow query, because what
2670 is asserted is which rows the cancel marks and not how long a runner takes
2671 to reach it.
2672 """
2673 in_flight = in_process_server._hold(A_REQUEST)
2674 served = served_by(in_process_server, in_flight=in_flight)
2675 log = QueryLog(program="hsql", connection=served.connection_id, adapter="duckdb")
2676 run = _Run(served=served, log=log)
2677
2678 executed = _execute_all(
2679 served.connection(),
2680 [Statement(sql=f"select {n}", index=n) for n in range(3)],
2681 limit=RowLimit(),
2682 on_error="stop",
2683 run=run,
2684 )
2685 assert len(executed) == 3
2686 results = _fetched(executed, limit=RowLimit(), on_error="stop", run=run)
2687 assert next(results)[0] == 1
2688 in_flight.cancel()
2689 assert list(results) == []
2690
2691 log.close()
2692 rows = recorded(query_log_path)
2693 assert [row["sql"] for row in rows] == ["select 0", "select 1", "select 2"]
2694 assert [row["status"] for row in rows] == ["ok", "canceled", "canceled"]
2695 # the one that did finish keeps what it returned
2696 assert rows[0]["rows"] == 1