Debian Codegraph @

tests/unit_tests/test_hsql_equivalence.py

raw
1 """One invocation produces the same bytes cold and warm.
2
3 The risk a session carries is not that it fails but that it drifts: that in
4 some corner -- a NULL, a `-t` footer, an error's exit code, a truncation notice
5 -- the served path and the cold path produce different bytes, and a caller who
6 set `HSQL_SESSION` months ago gets an answer the docs do not describe.
7
8 The claim is about one invocation, from a fresh session. Given the same
9 starting state, an invocation writes the same stdout, the same stderr and exits
10 the same whether it ran cold or warm; nothing is claimed about what the *next*
11 invocation sees, which is the feature (`@pytest.mark.session_divergent` is
12 where those live). So every case here runs twice, both through the real
13 console script, and the session is reset between cases.
14 """
15
16 from __future__ import annotations
17
18 import re
19 import socket
20 from pathlib import Path
21 from typing import Iterator, Sequence
22
23 import pytest
24
25 from harlequin.hsql.diagnostics import ExitCode
26 from tests.hsql_sessions import HsqlSubprocess, ServeSession, WarmSession
27
28 pytestmark = pytest.mark.skipif(
29 not hasattr(socket, "AF_UNIX"), reason="hsql sessions are POSIX-only"
30 )
31
32 COLD = ["-a", "duckdb", "--no-init", ":memory:"]
33 """What the session connects with, so a cold run connects the same way."""
34
35 TEN_ROWS = (
36 "with recursive t(n) as ("
37 "select 1 union all select n + 1 from t where n < 10"
38 ") select n from t"
39 )
40
41 ELAPSED = re.compile(rb'"elapsed_ms":\d+')
42 """The one field of `--stats` that two runs of anything never agree on."""
43
44 # Cases that connect and run SQL, or error at the connect step: cold carries
45 # the connection, warm carries the session, and the per-request args are the
46 # same on both sides.
47 CONNECTING: dict[str, list[str]] = {
48 "select": ["-c", "select 1 as a, 'two' as b, null as c"],
49 "tuples-only": ["-tAc", "select 42"],
50 "psql-algebra": ["--no-header", "--no-footer", "-c", "select 1 as a"],
51 "null-string": ["--null-string", "∅", "-c", "select null as a"],
52 "csv": ["--csv", "-c", "select 1 as a, null as b"],
53 "csv-null": ["--csv", "--null-string", "NULL", "-c", "select null as a"],
54 "json": ["--json", "-c", "select 1 as a, 'x' as b"],
55 "jsonl": ["--jsonl", "-c", "select 1 as a; select 2 as a"],
56 "markdown": ["--markdown", "-c", "select 1 as a"],
57 "vertical": ["-x", "-c", "select 1 as a, 2 as b"],
58 "none": ["--format", "none", "-c", "select 1"],
59 "unicode": ["-c", "select '中文' as a, 'ab' as b"],
60 "types": [
61 "-c",
62 "select 12345.6789::decimal(18, 4) as d, date '2024-03-01' as day, "
63 "[1, 2] as items, {'a': 1} as record, '\\x00\\xFF'::blob as payload",
64 ],
65 "truncated": ["--limit", "3", "-c", TEN_ROWS],
66 "row-cap": ["--display-rows", "2", "-tc", TEN_ROWS],
67 "row-cap-ignored": ["--csv", "--display-rows", "2", "-c", TEN_ROWS],
68 "two-results": ["-c", "select 1 as a", "-c", "select 2 as b"],
69 "result-last": ["--result", "last", "-c", "select 1 as a; select 2 as b"],
70 "result-index": ["--result", "2", "-c", "select 1 as a; select 2 as b"],
71 "result-out-of-range": ["--result", "9", "-c", "select 1"],
72 "one-csv-two-results": ["--csv", "-c", "select 1; select 2"],
73 "on-error-stop": ["-c", "select * from nowhere; select 1 as after"],
74 "on-error-continue": [
75 "--on-error",
76 "continue",
77 "-c",
78 "select * from nowhere; select 1 as after",
79 ],
80 "query-error": ["-c", "select from"],
81 "empty-result": ["--csv", "-c", "select 1 as a where false"],
82 "stats": ["--stats", "--limit", "3", "-c", TEN_ROWS],
83 "stats-error": ["--stats", "-c", "select * from nowhere"],
84 "color-always": ["--color", "always", "-c", "select 1 as a"],
85 "color-never": ["--color", "never", "-c", "select 1 as a"],
86 "two-formats": ["--csv", "--json", "-c", "select 1"],
87 "path-without-catalog": ["--path", "x", "-c", "select 1"],
88 "catalog": ["--catalog"],
89 "catalog-path": ["--catalog", "--path", "memory.main"],
90 "catalog-search": ["--catalog-search", "zzz"],
91 "catalog-limit-ignored": ["--catalog", "--limit", "5"],
92 "file": ["-tAf", "q.sql"],
93 "file-missing": ["-f", "missing.sql"],
94 "stdin": ["--csv", "-f", "-"],
95 "output-file": ["--csv", "-o", "out.csv", "-c", "select 1 as a"],
96 "output-dir": ["--csv", "-o", "results/", "-c", "select 1 as a; select 2 as b"],
97 "output-parquet": [
98 "--format",
99 "parquet",
100 "-o",
101 "out.parquet",
102 "-c",
103 "select 1 as a",
104 ],
105 }
106
107 # Cases that never reach the connection: the modes, and the usage errors caught
108 # before connecting. The session runs them through the same command the cold
109 # path builds, so cold and warm run the identical argv -- warm just names the
110 # session -- and the equivalence is that the session did nothing to the bytes.
111 LOCAL: dict[str, list[str]] = {
112 "bare": [],
113 "bad-flag": ["--nope"],
114 "two-modes": ["--catalog", "--spec"],
115 "help": ["--help"],
116 "version": ["--version"],
117 "spec": ["--spec", "-a", "duckdb"],
118 "info": ["--info", "-a", "duckdb"],
119 "config-show": ["--config", "show"],
120 "config-list-profiles": ["--config", "list-profiles"],
121 "skill": ["--skill"],
122 }
123
124 STDIN = b"select 'piped' as a"
125
126
127 @pytest.fixture(scope="module")
128 def session(serve_session_module: ServeSession) -> WarmSession:
129 return serve_session_module("eq")
130
131
132 @pytest.fixture(scope="module")
133 def serve_session_module(
134 tmp_path_factory: pytest.TempPathFactory,
135 ) -> Iterator[ServeSession]:
136 """One server per module per xdist worker -- and, below, a fresh session
137 per case, which is what makes a shared server safe."""
138 import shutil
139 import tempfile
140
141 runtime_dir = Path(tempfile.mkdtemp(prefix="hsql-", dir="/tmp"))
142 home = tmp_path_factory.mktemp("session-home")
143 started: list[WarmSession] = []
144
145 def _serve(name: str) -> WarmSession:
146 started.append(WarmSession(name, COLD, runtime_dir=runtime_dir, home=home))
147 started[-1].wait_until_ready()
148 return started[-1]
149
150 yield _serve
151 for session in started:
152 session.stop()
153 shutil.rmtree(runtime_dir, ignore_errors=True)
154
155
156 @pytest.fixture
157 def fresh(session: WarmSession, hsql_subprocess: HsqlSubprocess) -> WarmSession:
158 """Equivalence holds from a fresh session, so every case gets one."""
159 proc = hsql_subprocess(
160 ["--session", session.name, "--session-reset"], env=session.env
161 )
162 assert proc.returncode == ExitCode.OK, proc.stderr
163 return session
164
165
166 @pytest.fixture
167 def workspace(tmp_path: Path) -> Path:
168 """What the cases that read or write files find where they run."""
169 (tmp_path / "q.sql").write_text("select 'from a file' as a")
170 return tmp_path
171
172
173 def _normalize(stream: bytes) -> bytes:
174 return ELAPSED.sub(b'"elapsed_ms":N', stream)
175
176
177 def _both(
178 hsql_subprocess: HsqlSubprocess,
179 workspace: Path,
180 fresh: WarmSession,
181 cold_argv: Sequence[str],
182 warm_argv: Sequence[str],
183 *,
184 stdin: bytes | None,
185 ) -> None:
186 cold_dir, warm_dir = workspace / "cold", workspace / "warm"
187 for directory in (cold_dir, warm_dir):
188 directory.mkdir()
189 (directory / "q.sql").write_bytes((workspace / "q.sql").read_bytes())
190
191 cold = hsql_subprocess(cold_argv, cwd=cold_dir, stdin=stdin)
192 warm = hsql_subprocess(
193 ["--session", fresh.name, *warm_argv], cwd=warm_dir, stdin=stdin, env=fresh.env
194 )
195
196 assert warm.returncode == cold.returncode
197 assert warm.stdout == cold.stdout
198 assert _normalize(warm.stderr) == _normalize(cold.stderr)
199 cold_files = {
200 p.relative_to(cold_dir): p.read_bytes()
201 for p in cold_dir.rglob("*")
202 if p.is_file()
203 }
204 warm_files = {
205 p.relative_to(warm_dir): p.read_bytes()
206 for p in warm_dir.rglob("*")
207 if p.is_file()
208 }
209 assert warm_files == cold_files
210
211
212 @pytest.mark.parametrize("argv", list(CONNECTING.values()), ids=list(CONNECTING))
213 def test_a_query_is_the_same_bytes_cold_and_warm(
214 argv: Sequence[str],
215 fresh: WarmSession,
216 hsql_subprocess: HsqlSubprocess,
217 workspace: Path,
218 ) -> None:
219 """Cold connects for itself; warm runs on the session's connection. Same
220 starting state, same bytes."""
221 stdin = STDIN if "-" in argv else None
222 _both(hsql_subprocess, workspace, fresh, [*COLD, *argv], argv, stdin=stdin)
223
224
225 @pytest.mark.parametrize("argv", list(LOCAL.values()), ids=list(LOCAL))
226 def test_a_mode_is_the_same_bytes_cold_and_warm(
227 argv: Sequence[str],
228 fresh: WarmSession,
229 hsql_subprocess: HsqlSubprocess,
230 workspace: Path,
231 ) -> None:
232 """A mode reads no database, so the session runs the identical argv the
233 cold path would, and must not touch the bytes on the way."""
234 _both(hsql_subprocess, workspace, fresh, argv, argv, stdin=None)
235
236
237 def test_the_cases_cover_every_exit_code_but_the_signals(
238 fresh: WarmSession, hsql_subprocess: HsqlSubprocess, workspace: Path
239 ) -> None:
240 """A drift in an exit code is the one a script notices last."""
241 codes = set()
242 for argv in (CONNECTING["select"], CONNECTING["query-error"], LOCAL["bad-flag"]):
243 codes.add(hsql_subprocess([*COLD, *argv], cwd=workspace).returncode)
244 assert codes == {ExitCode.OK, ExitCode.QUERY, ExitCode.USAGE}