classifyre-cli 0.9.3__py3-none-any.whl → 0.9.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: classifyre-cli
3
- Version: 0.9.3
3
+ Version: 0.9.4
4
4
  Summary: Classifyre CLI — scan data sources for personal data and secrets
5
5
  License: MIT
6
6
  Keywords: data,governance,masking,pii,secrets
@@ -93,26 +93,26 @@ src/pipeline/scan_cache.py,sha256=cje5Fcbf2vJDOd3DOoTT__gn28fxQp_HojZESnhr2_s,30
93
93
  src/pipeline/text_artifact.py,sha256=7gpu1r6Ipc0nAt4S8bdzcy8KV9JKaTRgHPgrMw7J1I8,2433
94
94
  src/pipeline/worker_pool.py,sha256=Yjr_2LXxV2nYNcXNN4gFRPK9KN15GP_IkkAzaplKaTc,10543
95
95
  src/query/__init__.py,sha256=RhfyfKL7loabux082s5CMWFlBTq3rDl3q23LwpurAO0,989
96
- src/query/bindings.py,sha256=z-YSWuUaj4ZaqxT2EsiffcVxhAMINVlkd-AawnKb10Q,6046
96
+ src/query/bindings.py,sha256=KMqATSAJHGD9y3HrWhbE1w8ixJgGV5dDsqHq2FgkL-A,6258
97
97
  src/query/describe.py,sha256=oJBA2WruLYWXROHHlg2Y_P9T6KtWyATUiYbx2T8KoSw,3245
98
98
  src/query/gate.py,sha256=cNvdANq3cvcc9AGE-wk2Ad_1HpsZKphUNBscCTga-eM,13040
99
99
  src/query/masks.py,sha256=E-B1kt_99BIcaKpTEYGXYLGKnr3R5b-piLqaZci84Aw,10982
100
100
  src/query/predicate.py,sha256=VH4U3UyfAL5aWKdcrSSgADy5T3s7WVWJowmNywo6EaE,1644
101
101
  src/query/rows.py,sha256=JcUgThkVIKJsQIlhemT_xQ0aiQNItCQ-x8NsLx0KLhc,4588
102
- src/query/runner.py,sha256=Azp3PMVMQCwXIsgku8FDiuCmDgzViltrqksutbd8Bvg,7804
103
- src/query/session.py,sha256=RmPoa_Z4fCIIpsDGrLwgNXBA5voLoz7rQ3CXiTlh3JU,36389
104
- src/query/warm.py,sha256=Fq9x6Oej51ezywmRvoDUwYJKfHwZMmRBul4JJ01N8oo,7268
105
- src/query/worker.py,sha256=SsimpxTREWj219vmelHLamQtMVws8V35CVKp--6S3zU,40087
102
+ src/query/runner.py,sha256=EBwcaMHwSgBgdGNr9k_DMhEB2yc0qcDWGUm8C0AzPjw,7888
103
+ src/query/session.py,sha256=ELrjIZ3etEQUkLwl4gAqQJ5Rgz9dHABZ4kLGQ1fApYU,43538
104
+ src/query/warm.py,sha256=E1QQKm2FqJ5M8hOPeLBYn24bjetFeE8GPYaf8PoR1T8,7719
105
+ src/query/worker.py,sha256=nxW6sqkVFOiCtJh5Tbek8esoY07pxnWrhCwvC8D9e88,52962
106
106
  src/query/connectors/__init__.py,sha256=e8rZ-xjwo4qewUMzdwAl5yifTY0sPpUGFaWyYeB48R4,4669
107
- src/query/connectors/arrow.py,sha256=psnqGJZXNx0Riyl4yhGQ9hayIxMrqaDA-7aplEz7YLc,22760
107
+ src/query/connectors/arrow.py,sha256=HZtCVhIGa4GUibFOejUYkKGHvlurLoa3zZx5MFRTr8g,23012
108
108
  src/query/connectors/attached_catalog.py,sha256=KrxLIAGvHsLFjEoGg4KI28wuealjHYDjld4a1UM2vYg,1516
109
- src/query/connectors/base.py,sha256=H0wIWxuNMWzhPfzSaJv15uwQLpLisHPXPwY_gB_TGPY,7755
109
+ src/query/connectors/base.py,sha256=Y-5AyRl-gQm8B1CFHDgKf6Z-O9poJq6ICWRiEN-BnIw,7887
110
110
  src/query/connectors/custom.py,sha256=BLAWAsjXjRMKN58nYhxABdSCCviAUid1hFSkx1xgKYM,4313
111
111
  src/query/connectors/databricks.py,sha256=Cvlke_yM72iUO6RB8H-i6duRxiOiTpwbQJsFIJia90c,2757
112
112
  src/query/connectors/meilisearch.py,sha256=_mpeFJ_Nn1eIaz6BHm6viOY1ioQahYNxNkV5eKIrPow,8909
113
113
  src/query/connectors/mysql.py,sha256=7QyYY35yt_-oRsaWrhLz-7O7zCiSrZqyw-EW2veu1cw,5598
114
114
  src/query/connectors/neo4j.py,sha256=leGRZ-uH4Ba2G3yp2mYx8Jouao7nmu5E3B9jUjO8MXk,8533
115
- src/query/connectors/object_storage.py,sha256=RuOGCQcbUj3u0MtlOPts4VoaxArbFIDdDbcdWsc6FDM,5003
115
+ src/query/connectors/object_storage.py,sha256=hN_-_q5XAQwnWgR2Ogdysj_PDghuqi1dcpTB1Wtf5kU,5354
116
116
  src/query/connectors/odbc.py,sha256=23URmiz3pDTDrGO08zC7BAQa6ugztAE_JM7dK8iPLnQ,2936
117
117
  src/query/connectors/postgres.py,sha256=pOvVxToZCTs2oE3KW1f0lvjo2Br0_NTl9Nj3VX7TYkQ,2916
118
118
  src/sources/__init__.py,sha256=wYksO_0IcvlGXLouWapKyqzL0jG0El4rDDGRfwa4Zqk,3350
@@ -254,7 +254,7 @@ src/utils/urn.py,sha256=gqSl0H0FBZZ3cJbpDWX1ewGcyZz2MrNVTIQdoFrQMM0,12622
254
254
  src/utils/uv_sync.py,sha256=L4ETHuidlgFLbz4e3Vv0Ornh7w8xrkYeFQQGw0hJe8E,10214
255
255
  src/utils/validation.py,sha256=5NHsgyZwyEONRu9_ADxUAQNPvbMnpMhKL-hpgFEVMm8,3837
256
256
  src/utils/video_processing.py,sha256=B6Br9ybFEa_ioglJGo0P9Fmp1e2B95C24joAktwrjww,11293
257
- classifyre_cli-0.9.3.dist-info/METADATA,sha256=6QV3kZlLVXgczd7LrZl7J_t62xKkRg8bJ1ZJJZU0FKo,5841
258
- classifyre_cli-0.9.3.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
259
- classifyre_cli-0.9.3.dist-info/entry_points.txt,sha256=edxllyMiIFfajgCZ3dTRACXYGC34ZX1AYTezMSR5E_8,45
260
- classifyre_cli-0.9.3.dist-info/RECORD,,
257
+ classifyre_cli-0.9.4.dist-info/METADATA,sha256=5Pgq6D2zNUjcESHhgr_waCGlp-NhYQukC68cItfpN1s,5841
258
+ classifyre_cli-0.9.4.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
259
+ classifyre_cli-0.9.4.dist-info/entry_points.txt,sha256=edxllyMiIFfajgCZ3dTRACXYGC34ZX1AYTezMSR5E_8,45
260
+ classifyre_cli-0.9.4.dist-info/RECORD,,
src/query/bindings.py CHANGED
@@ -136,6 +136,11 @@ class SourceBinding:
136
136
  """Why a connector's scan of that table failed, as it said it."""
137
137
  return self._reader.failure(relation) if self._reader else None
138
138
 
139
+ def reset_query(self, conn: Any) -> None:
140
+ """Release per-query state registered on ``conn`` between sticky queries."""
141
+ if self._reader is not None:
142
+ self._reader.reset_query(conn)
143
+
139
144
  def close(self) -> None:
140
145
  if self._reader is not None:
141
146
  self._reader.close()
@@ -171,6 +171,14 @@ class ArrowConnector(QueryBinding):
171
171
  live = self._live.get(relation.strip('"'))
172
172
  return live.error if live is not None else None
173
173
 
174
+ def reset_query(self, conn: Any) -> None:
175
+ for name in list(self._live):
176
+ try:
177
+ conn.unregister(name)
178
+ except Exception: # pragma: no cover - best effort
179
+ pass
180
+ self._live.clear()
181
+
174
182
  def close(self) -> None:
175
183
  self._live.clear()
176
184
 
@@ -161,6 +161,9 @@ class QueryBinding(ABC):
161
161
  (``ConnectorError``); None for tables DuckDB reads itself."""
162
162
  return None
163
163
 
164
+ def reset_query(self, conn: Any) -> None:
165
+ """Release per-query state registered on ``conn`` between sticky queries."""
166
+
164
167
  def close(self) -> None:
165
168
  """Release what the binding made (temporary files); the session closes DuckDB."""
166
169
 
@@ -30,6 +30,7 @@ class ObjectStorageBinding(QueryBinding):
30
30
  def __init__(self, source: SourceContext) -> None:
31
31
  super().__init__(source)
32
32
  self._storage: Any = None
33
+ self._iceberg_version_guessing = False
33
34
 
34
35
  def relation(self, conn: Any, location: TableLocation) -> str:
35
36
  (key,) = self.require(location, "object_key")
@@ -59,7 +60,13 @@ class ObjectStorageBinding(QueryBinding):
59
60
  # Without a version-hint file DuckDB finds the newest metadata by
60
61
  # listing the root, which it calls "unsafe" because a writer could
61
62
  # be mid-commit; for a read-only query that is the right trade.
62
- conn.execute("SET unsafe_enable_version_guessing = true")
63
+ if not self._iceberg_version_guessing:
64
+ row = conn.execute(
65
+ "SELECT current_setting('unsafe_enable_version_guessing')"
66
+ ).fetchone()
67
+ if not (row and bool(row[0])):
68
+ conn.execute("SET unsafe_enable_version_guessing = true")
69
+ self._iceberg_version_guessing = True
63
70
  return f"iceberg_scan({uri}, allow_moved_paths = true)"
64
71
  if location.kind == "file":
65
72
  if fmt == "parquet":
src/query/runner.py CHANGED
@@ -20,7 +20,7 @@ from typing import TYPE_CHECKING, Any
20
20
  from ..utils.redaction import ENCRYPTED_CONFIG_PATHS, Redactor, _leaves_at_path
21
21
 
22
22
  if TYPE_CHECKING:
23
- from .session import QueryRequest, QueryResult
23
+ from .session import QueryRequest, QueryResult, StickyDuckDbState
24
24
 
25
25
  logger = logging.getLogger(__name__)
26
26
 
@@ -123,7 +123,9 @@ def ensure_dependencies() -> None:
123
123
  require_module("sqlglot", "SQL query", ["lineage"])
124
124
 
125
125
 
126
- def run_query(request_data: dict[str, Any]) -> tuple[dict[str, Any], QueryResult | None]:
126
+ def run_query(
127
+ request_data: dict[str, Any], *, sticky: StickyDuckDbState | None = None
128
+ ) -> tuple[dict[str, Any], QueryResult | None]:
127
129
  """Run a request; return the status payload and, on success, the result."""
128
130
  redact = _redactor(request_data)
129
131
  try:
@@ -136,7 +138,7 @@ def run_query(request_data: dict[str, Any]) -> tuple[dict[str, Any], QueryResult
136
138
 
137
139
  request = QueryRequest.from_dict(request_data)
138
140
  try:
139
- with QuerySession(request) as session:
141
+ with QuerySession(request, sticky=sticky) as session:
140
142
  result = session.run()
141
143
  except QueryRefusedError as exc:
142
144
  return error_payload(exc.code, redact(str(exc))), None
src/query/session.py CHANGED
@@ -21,7 +21,7 @@ import re
21
21
  import tempfile
22
22
  import threading
23
23
  import time
24
- from collections.abc import Iterator
24
+ from collections.abc import Callable, Iterator
25
25
  from contextlib import contextmanager
26
26
  from dataclasses import dataclass, field, replace
27
27
  from pathlib import Path
@@ -266,22 +266,145 @@ def _known_columns(value: Any) -> list[str] | None:
266
266
  return [str(name) for name in value if isinstance(name, str)]
267
267
 
268
268
 
269
+ def _build_bindings(sources: list[dict[str, Any]]) -> dict[str, SourceBinding]:
270
+ bindings: dict[str, SourceBinding] = {}
271
+ for index, entry in enumerate(sources):
272
+ alias = str(entry.get("alias") or "").lower()
273
+ recipe = entry.get("recipe")
274
+ if alias and isinstance(recipe, dict):
275
+ bindings[alias] = SourceBinding(
276
+ alias, index, recipe, str(entry.get("sourceId") or "")
277
+ )
278
+ return bindings
279
+
280
+
281
+ class StickyDuckDbState:
282
+ """Reusable warm DuckDB database + attached source bindings for one sticky worker.
283
+
284
+ Scoped strictly to a single ``(workspaceId, connectionId, sourceCredsDigest)``
285
+ child process (docs/prd/SG-sql-gateway-native-catalog.md §6.3). Reuses the
286
+ DuckDB instance, verified extensions, and already-attached ``__src_<n>``
287
+ remote catalogs across sequential BI dashboard cards, while resetting all
288
+ view catalogs, registered live Arrow datasets, and spill files between
289
+ queries so column masks and row filters are always rebuilt fresh.
290
+ """
291
+
292
+ def __init__(self) -> None:
293
+ self._conn: Any = None
294
+ self._bindings: dict[str, SourceBinding] = {}
295
+ self._spill: tempfile.TemporaryDirectory[str] | None = None
296
+ self._locked: bool = False
297
+ self._view_catalogs: set[str] = set()
298
+ self._reuse_count: int = 0
299
+
300
+ @property
301
+ def is_warm(self) -> bool:
302
+ return self._conn is not None
303
+
304
+ @property
305
+ def reuse_count(self) -> int:
306
+ return self._reuse_count
307
+
308
+ def ensure_spill_dir(self) -> str:
309
+ if self._spill is None:
310
+ self._spill = tempfile.TemporaryDirectory(prefix="classifyre-sticky-")
311
+ return self._spill.name
312
+
313
+ def get_or_init_bindings(self, sources: list[dict[str, Any]]) -> dict[str, SourceBinding]:
314
+ if not self._bindings:
315
+ self._bindings = _build_bindings(sources)
316
+ return self._bindings
317
+
318
+ def checkout_connection(self, opener: Callable[[str], Any]) -> tuple[Any, bool]:
319
+ if self._conn is not None:
320
+ return self._conn, True
321
+ self._conn = opener(self.ensure_spill_dir())
322
+ return self._conn, False
323
+
324
+ def recycle(
325
+ self, sources: list[dict[str, Any]], opener: Callable[[str], Any]
326
+ ) -> tuple[Any, str, dict[str, SourceBinding]]:
327
+ """Close the locked warm connection and open a fresh one for retry."""
328
+ self.close()
329
+ spill_path = self.ensure_spill_dir()
330
+ bindings = self.get_or_init_bindings(sources)
331
+ self._conn = opener(spill_path)
332
+ return self._conn, spill_path, bindings
333
+
334
+ def track_view_catalog(self, catalog: str) -> None:
335
+ self._view_catalogs.add(catalog)
336
+
337
+ def mark_locked(self) -> None:
338
+ self._locked = True
339
+
340
+ def record_reuse(self) -> None:
341
+ self._reuse_count += 1
342
+
343
+ def clean_spill_files(self) -> None:
344
+ if self._spill is None:
345
+ return
346
+ import shutil
347
+
348
+ for entry in Path(self._spill.name).iterdir():
349
+ if entry.is_dir() and not entry.is_symlink():
350
+ shutil.rmtree(entry, ignore_errors=True)
351
+ else:
352
+ try:
353
+ entry.unlink()
354
+ except OSError:
355
+ pass
356
+
357
+ def reset_after_query(self) -> None:
358
+ """Detach view catalogs, unregister live connector datasets, and clean spill files."""
359
+ if self._conn is None:
360
+ return
361
+ for catalog in list(self._view_catalogs):
362
+ try:
363
+ self._conn.execute(f"DETACH IF EXISTS {quote_identifier(catalog)}")
364
+ except Exception:
365
+ self.close()
366
+ return
367
+ self._view_catalogs.clear()
368
+ for binding in self._bindings.values():
369
+ binding.reset_query(self._conn)
370
+ self.clean_spill_files()
371
+
372
+ def close(self) -> None:
373
+ if self._conn is not None:
374
+ try:
375
+ self._conn.close()
376
+ except Exception: # pragma: no cover - best effort
377
+ pass
378
+ self._conn = None
379
+ for binding in self._bindings.values():
380
+ binding.close()
381
+ self._bindings.clear()
382
+ self._view_catalogs.clear()
383
+ self._locked = False
384
+ if self._spill is not None:
385
+ self._spill.cleanup()
386
+ self._spill = None
387
+
388
+
269
389
  class QuerySession:
270
390
  """Runs one :class:`QueryRequest`; use as a context manager."""
271
391
 
272
- def __init__(self, request: QueryRequest) -> None:
392
+ def __init__(
393
+ self, request: QueryRequest, *, sticky: StickyDuckDbState | None = None
394
+ ) -> None:
273
395
  self.request = request
274
396
  self._duckdb = require_duckdb()
275
- self._spill = tempfile.TemporaryDirectory(prefix="classifyre-query-")
397
+ self._sticky = sticky
398
+ if sticky is not None:
399
+ self._spill: tempfile.TemporaryDirectory[str] | None = None
400
+ self._spill_path = sticky.ensure_spill_dir()
401
+ else:
402
+ spill = tempfile.TemporaryDirectory(prefix="classifyre-query-")
403
+ self._spill = spill
404
+ self._spill_path = spill.name
276
405
  self._conn: Any = None
277
406
  self._bindings: dict[str, SourceBinding] = {}
278
- for index, entry in enumerate(request.sources):
279
- alias = str(entry.get("alias") or "").lower()
280
- recipe = entry.get("recipe")
281
- if alias and isinstance(recipe, dict):
282
- self._bindings[alias] = SourceBinding(
283
- alias, index, recipe, str(entry.get("sourceId") or "")
284
- )
407
+ self._init_bindings()
285
408
  #: Each source table's view reads this binding's relation.
286
409
  self._relations: dict[str, _Relation] = {}
287
410
  self._tables: dict[TableName, _Table] = {}
@@ -294,6 +417,12 @@ class QuerySession:
294
417
  if table is not None:
295
418
  self._tables[table.name] = table
296
419
 
420
+ def _init_bindings(self) -> None:
421
+ if self._sticky is not None:
422
+ self._bindings = self._sticky.get_or_init_bindings(self.request.sources)
423
+ return
424
+ self._bindings = _build_bindings(self.request.sources)
425
+
297
426
  def _source_table(self, entry: dict[str, Any]) -> _Table | None:
298
427
  name = TableName.of(
299
428
  str(entry.get("source") or ""),
@@ -346,6 +475,10 @@ class QuerySession:
346
475
  self.close()
347
476
 
348
477
  def close(self) -> None:
478
+ if self._sticky is not None:
479
+ self._sticky.reset_after_query()
480
+ self._conn = None
481
+ return
349
482
  if self._conn is not None:
350
483
  try:
351
484
  self._conn.close()
@@ -354,14 +487,15 @@ class QuerySession:
354
487
  self._conn = None
355
488
  for binding in self._bindings.values():
356
489
  binding.close()
357
- self._spill.cleanup()
490
+ if self._spill is not None:
491
+ self._spill.cleanup()
358
492
 
359
493
  # ── setup ──────────────────────────────────────────────────────────
360
494
 
361
- def _open(self) -> Any:
495
+ def _open(self, spill_path: str | None = None) -> Any:
362
496
  conn = connect(self._duckdb)
363
497
  conn.execute("SET enable_progress_bar = false")
364
- conn.execute(f"SET temp_directory = '{self._spill.name}'")
498
+ conn.execute(f"SET temp_directory = '{spill_path or self._spill_path}'")
365
499
  memory = self.request.memory_limit or os.environ.get("CLASSIFYRE_QUERY_MEMORY_LIMIT")
366
500
  if memory:
367
501
  conn.execute(f"SET memory_limit = '{memory.replace(chr(39), '')}'")
@@ -389,7 +523,7 @@ class QuerySession:
389
523
  """
390
524
  conn.execute("SET autoinstall_known_extensions = false")
391
525
  conn.execute("SET autoload_known_extensions = false")
392
- allowed = [*REMOTE_PREFIXES, _as_directory(self._spill.name)]
526
+ allowed = [*REMOTE_PREFIXES, _as_directory(self._spill_path)]
393
527
  for binding in self._bindings.values():
394
528
  allowed += recipe_endpoints(binding.recipe)
395
529
  # Not the allowlist itself: only the folders the query's sources read.
@@ -429,7 +563,9 @@ class QuerySession:
429
563
  logger.info("external access left on for %s (a Job of its own)", ", ".join(external))
430
564
  conn.execute("SET lock_configuration = true")
431
565
 
432
- def _attach_tables_as_views(self, conn: Any, tables: set[TableName]) -> None:
566
+ def _attach_tables_as_views(
567
+ self, conn: Any, tables: set[TableName], *, track_sticky: bool = True
568
+ ) -> None:
433
569
  created_catalogs: set[str] = set()
434
570
  created_schemas: set[tuple[str, str]] = set()
435
571
 
@@ -437,6 +573,8 @@ class QuerySession:
437
573
  if catalog not in created_catalogs:
438
574
  conn.execute(f"ATTACH ':memory:' AS {quote_identifier(catalog)}")
439
575
  created_catalogs.add(catalog)
576
+ if track_sticky and self._sticky is not None:
577
+ self._sticky.track_view_catalog(catalog)
440
578
  if (catalog, schema) not in created_schemas:
441
579
  conn.execute(
442
580
  f"CREATE SCHEMA IF NOT EXISTS "
@@ -565,15 +703,17 @@ class QuerySession:
565
703
  ) from exc
566
704
 
567
705
  @contextmanager
568
- def _deadline(self, conn: Any, seconds: float) -> Iterator[threading.Event]:
706
+ def _deadline(self, seconds: float) -> Iterator[threading.Event]:
569
707
  fired = threading.Event()
570
708
 
571
709
  def interrupt() -> None:
572
710
  fired.set()
573
- try:
574
- conn.interrupt()
575
- except Exception: # pragma: no cover - connection already closed
576
- pass
711
+ conn = self._conn
712
+ if conn is not None:
713
+ try:
714
+ conn.interrupt()
715
+ except Exception: # pragma: no cover - connection already closed
716
+ pass
577
717
 
578
718
  timer = threading.Timer(max(seconds, 0.001), interrupt)
579
719
  timer.daemon = True
@@ -591,7 +731,7 @@ class QuerySession:
591
731
  cap = int(self.request.max_rows)
592
732
  if fmt == "xlsx":
593
733
  cap = min(cap, XLSX_MAX_ROWS)
594
- path = Path(self._spill.name) / f"export.{fmt}"
734
+ path = Path(self._spill_path) / f"export.{fmt}"
595
735
  projection = _export_columns(conn, sql, fmt)
596
736
  options = {
597
737
  "xlsx": "FORMAT xlsx, HEADER true",
@@ -636,29 +776,36 @@ class QuerySession:
636
776
  validated = validate(self.request.sql, self._tables.keys())
637
777
  conn = self._open()
638
778
  self._conn = conn
639
- with self._deadline(conn, self.request.timeout_seconds) as fired:
779
+ try:
780
+ with self._deadline(self.request.timeout_seconds) as fired:
781
+ try:
782
+ self._attach_tables_as_views(conn, validated.tables, track_sticky=False)
783
+ self._lock_down(conn)
784
+ described = conn.execute(
785
+ f"DESCRIBE SELECT * FROM ({validated.sql}) AS __result"
786
+ ).fetchall()
787
+ schemas: dict[TableName, list[str]] = {}
788
+ for name in validated.tables:
789
+ target = ".".join(
790
+ quote_identifier(p) for p in (name.source, name.schema, name.table)
791
+ )
792
+ schemas[name] = [
793
+ str(row[0])
794
+ for row in conn.execute(f"DESCRIBE SELECT * FROM {target}").fetchall()
795
+ ]
796
+ except Exception:
797
+ if fired.is_set():
798
+ raise QueryTimeoutError(
799
+ f"Describing the query took longer than "
800
+ f"{self.request.timeout_seconds} s and was stopped."
801
+ ) from None
802
+ raise
803
+ finally:
804
+ self._conn = None
640
805
  try:
641
- self._attach_tables_as_views(conn, validated.tables)
642
- self._lock_down(conn)
643
- described = conn.execute(
644
- f"DESCRIBE SELECT * FROM ({validated.sql}) AS __result"
645
- ).fetchall()
646
- schemas: dict[TableName, list[str]] = {}
647
- for name in validated.tables:
648
- target = ".".join(
649
- quote_identifier(p) for p in (name.source, name.schema, name.table)
650
- )
651
- schemas[name] = [
652
- str(row[0])
653
- for row in conn.execute(f"DESCRIBE SELECT * FROM {target}").fetchall()
654
- ]
655
- except Exception:
656
- if fired.is_set():
657
- raise QueryTimeoutError(
658
- f"Describing the query took longer than "
659
- f"{self.request.timeout_seconds} s and was stopped."
660
- ) from None
661
- raise
806
+ conn.close()
807
+ except Exception: # pragma: no cover - best effort
808
+ pass
662
809
  columns = [{"name": str(row[0]), "type": str(row[1])} for row in described]
663
810
  return QueryResult(
664
811
  arrow=b"",
@@ -685,17 +832,48 @@ class QuerySession:
685
832
  database=self.request.database,
686
833
  search_path=self.request.search_path,
687
834
  )
688
- conn = self._open()
835
+ if self._sticky is not None:
836
+ conn, reused = self._sticky.checkout_connection(self._open)
837
+ else:
838
+ conn, reused = self._open(), False
689
839
  self._conn = conn
690
840
  for binding in self._bindings.values():
691
841
  binding.deadline = started + self.request.timeout_seconds
692
- with self._deadline(conn, self.request.timeout_seconds) as fired:
842
+ with self._deadline(self.request.timeout_seconds) as fired:
693
843
  try:
694
- self._attach_tables_as_views(conn, validated.tables)
844
+ try:
845
+ self._attach_tables_as_views(conn, validated.tables)
846
+ except Exception:
847
+ if fired.is_set() or not reused or self._sticky is None:
848
+ raise
849
+ # A newly referenced source/format needed an extension or
850
+ # path not present before lock_configuration=true: recycle
851
+ # the warm DuckDB connection cleanly and retry once under
852
+ # the same active deadline (self._conn is updated so
853
+ # interrupt() targets the retried connection).
854
+ conn, self._spill_path, self._bindings = self._sticky.recycle(
855
+ self.request.sources, self._open
856
+ )
857
+ self._conn = conn
858
+ if fired.is_set():
859
+ raise QueryTimeoutError(
860
+ f"The query took longer than {self.request.timeout_seconds} s "
861
+ "and was stopped."
862
+ ) from None
863
+ for binding in self._bindings.values():
864
+ binding.deadline = started + self.request.timeout_seconds
865
+ self._relations.clear()
866
+ reused = False
867
+ self._attach_tables_as_views(conn, validated.tables)
695
868
  setup_done = time.monotonic()
696
869
  if self.request.export_format == "xlsx":
697
870
  load_extension(conn, "excel")
698
- self._lock_down(conn)
871
+ if not reused:
872
+ self._lock_down(conn)
873
+ if self._sticky is not None:
874
+ self._sticky.mark_locked()
875
+ elif self._sticky is not None:
876
+ self._sticky.record_reuse()
699
877
  if self.request.export_format:
700
878
  exported = self._export(conn, validated.sql)
701
879
  else:
@@ -721,6 +899,11 @@ class QuerySession:
721
899
  "setupMs": int((setup_done - started) * 1000),
722
900
  "executeMs": int((executed - setup_done) * 1000),
723
901
  "totalMs": int((time.monotonic() - started) * 1000),
902
+ **(
903
+ {"stickyReuse": self._sticky.reuse_count}
904
+ if self._sticky is not None
905
+ else {}
906
+ ),
724
907
  }
725
908
  result.tables = sorted(str(t) for t in validated.tables)
726
909
  result.scans = self._scan_stats()
src/query/warm.py CHANGED
@@ -25,6 +25,7 @@ logged and the query that needs it pays for it as a Job would.
25
25
 
26
26
  from __future__ import annotations
27
27
 
28
+ import gc
28
29
  import logging
29
30
  import os
30
31
  import threading
@@ -176,6 +177,14 @@ def warm_up() -> dict[str, float]:
176
177
  ", ".join(others),
177
178
  )
178
179
  timings["other_threads"] = float(len(others))
180
+ with _step("gc_freeze"):
181
+ # Preserve Linux Copy-on-Write page sharing across forked query
182
+ # processes (docs/prd/SG-sql-gateway-native-catalog.md §6.1): moving
183
+ # preloaded objects into CPython's permanent generation stops cyclic GC
184
+ # from mutating their refcount/GC headers in every forked child.
185
+ gc.collect()
186
+ gc.freeze()
187
+ timings["gc_frozen_objects"] = float(gc.get_freeze_count())
179
188
  return timings
180
189
 
181
190
 
src/query/worker.py CHANGED
@@ -48,6 +48,8 @@ frameworks are not fork-safe, and DuckDB's httpfs reaches them through curl.
48
48
 
49
49
  from __future__ import annotations
50
50
 
51
+ import gc
52
+ import hashlib
51
53
  import hmac
52
54
  import http.server
53
55
  import json
@@ -61,14 +63,18 @@ import sys
61
63
  import tempfile
62
64
  import threading
63
65
  import time
66
+ from collections import OrderedDict
64
67
  from collections.abc import MutableMapping
65
68
  from dataclasses import dataclass, field
66
69
  from multiprocessing.connection import Connection, wait
67
70
  from pathlib import Path
68
- from typing import Any, Literal
71
+ from typing import TYPE_CHECKING, Any, Literal
69
72
 
70
73
  from ..utils.resources import get_effective_cpu_count, get_effective_memory_mb
71
74
 
75
+ if TYPE_CHECKING:
76
+ from .session import StickyDuckDbState
77
+
72
78
  logger = logging.getLogger(__name__)
73
79
 
74
80
  ENV_PREFIX = "CLASSIFYRE_QUERY_WORKER_"
@@ -101,6 +107,12 @@ DEFAULT_MEMORY_GUARD_PERCENT = 90
101
107
  GUARD_INTERVAL_SECONDS = 0.1
102
108
  DEFAULT_DRAIN_SECONDS = 960
103
109
  DEFAULT_WORKSPACE_SHARE_PERCENT = 75
110
+ #: Short-TTL sticky reuse per (workspaceId, connectionId, sourceCredsDigest)
111
+ #: (docs/prd/SG-sql-gateway-native-catalog.md §6.3). Disabled (0) by default
112
+ #: until benchmarked on BI dashboard bursts.
113
+ DEFAULT_STICKY_TTL_SECONDS = 0
114
+ #: Upper cap on idle sticky processes kept per pod.
115
+ DEFAULT_MAX_IDLE_STICKY = 4
104
116
  #: Source types whose queries always run as Jobs: they load native code the
105
117
  #: source names (an ODBC ``Driver=`` path) or run code its editors wrote (a
106
118
  #: CUSTOM notebook's ``scan()``), which must not share a process host with
@@ -291,6 +303,19 @@ class WorkerConfig:
291
303
  #: The share of the slots one workspace may hold at once (review of
292
304
  #: 383fd5c4, P6): the rest stay for other workspaces sharing the pool.
293
305
  workspace_share_percent: int = DEFAULT_WORKSPACE_SHARE_PERCENT
306
+ #: Idle TTL (seconds) for reusing a warm query process for the same
307
+ #: ``(workspaceId, connectionId, sourceCredsDigest)``. 0 disables reuse.
308
+ sticky_ttl_seconds: int = DEFAULT_STICKY_TTL_SECONDS
309
+ #: Cap on idle sticky processes kept per pod; 0 derives ``min(4, max(1, slots // 2))``.
310
+ max_idle_sticky: int = 0
311
+
312
+ @property
313
+ def effective_max_idle_sticky(self) -> int:
314
+ if self.sticky_ttl_seconds <= 0:
315
+ return 0
316
+ if self.max_idle_sticky > 0:
317
+ return self.max_idle_sticky
318
+ return min(DEFAULT_MAX_IDLE_STICKY, max(1, self.slots // 2))
294
319
 
295
320
  @classmethod
296
321
  def from_env(cls, environ: MutableMapping[str, str] | None = None) -> WorkerConfig:
@@ -335,6 +360,8 @@ class WorkerConfig:
335
360
  workspace_share_percent=_int(
336
361
  env, "WORKSPACE_SHARE_PERCENT", DEFAULT_WORKSPACE_SHARE_PERCENT, 1
337
362
  ),
363
+ sticky_ttl_seconds=_int(env, "STICKY_TTL_SECONDS", DEFAULT_STICKY_TTL_SECONDS),
364
+ max_idle_sticky=_int(env, "MAX_IDLE_STICKY", 0),
338
365
  )
339
366
 
340
367
 
@@ -400,28 +427,101 @@ def _harden(workdir: str) -> None:
400
427
  os.chdir(workdir)
401
428
 
402
429
 
403
- def _query_process(request_data: dict[str, Any], out: Connection, workdir: str) -> None:
404
- """Runs in the forked query process: one query, as a query Job runs it."""
405
- _harden(workdir)
430
+ @dataclass(frozen=True)
431
+ class StickyKey:
432
+ """Strict isolation key for optional sticky process reuse (SG §6.3)."""
433
+
434
+ workspace_id: str
435
+ connection_id: str
436
+ sources_digest: str
437
+
438
+
439
+ def sticky_key_of(request_data: dict[str, Any]) -> StickyKey | None:
440
+ """Strict isolation key for optional sticky process reuse (SG §6.3).
441
+
442
+ Scoped strictly to ``(workspaceId, connectionId, sourceCredsDigest)``:
443
+ queries without a workspace or SQL connection, exports, or requests whose
444
+ source recipes/credentials differ never share a process.
445
+ """
446
+ workspace_id = str(request_data.get("workspaceId") or "").strip()
447
+ connection_id = str(request_data.get("connectionId") or "").strip()
448
+ if not workspace_id or not connection_id:
449
+ return None
450
+ if request_data.get("exportFormat") or request_data.get("describe"):
451
+ return None
452
+ sources = request_data.get("sources") or []
453
+ canonical = json.dumps(sources, sort_keys=True, separators=(",", ":")).encode("utf-8")
454
+ digest = hashlib.sha256(canonical).hexdigest()
455
+ return StickyKey(workspace_id, connection_id, digest)
456
+
457
+
458
+ def _execute_and_report(
459
+ request_data: dict[str, Any], *, sticky: StickyDuckDbState | None = None
460
+ ) -> tuple[dict[str, Any], bool]:
461
+ """Run one query and deliver its result callback; returns (payload, fatal)."""
406
462
  from .runner import error_payload, report_result, run_query
407
463
  from .session import QueryRequest
408
464
 
409
- payload: dict[str, Any] = error_payload("execution_error", "The query process stopped early.")
410
465
  try:
411
- payload, result = run_query(request_data)
466
+ payload, result = run_query(request_data, sticky=sticky)
412
467
  report_result(
413
468
  QueryRequest.from_dict(request_data),
414
469
  payload,
415
470
  result.arrow if result is not None else None,
416
471
  echo=False,
417
472
  )
473
+ return payload, False
418
474
  except Exception as exc: # run_query catches query errors; this is the rest
419
- payload = error_payload("execution_error", type(exc).__name__)
475
+ return error_payload("execution_error", type(exc).__name__), True
476
+
477
+
478
+ def _sticky_query_process(req_in: Connection, resp_out: Connection, workdir: str) -> None:
479
+ """Long-lived hardened child process serving sequential queries for one StickyKey.
480
+
481
+ Keeps a warm :class:`.session.StickyDuckDbState` (DuckDB database, verified
482
+ extensions, and attached remote source catalogs) alive across sequential
483
+ queries while resetting views and spill files between queries.
484
+ """
485
+ _harden(workdir)
486
+ from .session import StickyDuckDbState
487
+
488
+ sticky_state = StickyDuckDbState()
489
+ try:
490
+ while True:
491
+ try:
492
+ request_data = req_in.recv()
493
+ except (EOFError, OSError):
494
+ break
495
+ if request_data is None:
496
+ break
497
+ payload, fatal = _execute_and_report(request_data, sticky=sticky_state)
498
+ gc.collect()
499
+ try:
500
+ resp_out.send(payload)
501
+ except OSError:
502
+ break
503
+ if fatal or payload.get("status") != "success":
504
+ break
420
505
  finally:
506
+ sticky_state.close()
421
507
  try:
422
- out.send(payload)
423
- finally:
424
- out.close()
508
+ req_in.close()
509
+ except OSError:
510
+ pass
511
+ try:
512
+ resp_out.close()
513
+ except OSError:
514
+ pass
515
+
516
+
517
+ def _query_process(request_data: dict[str, Any], out: Connection, workdir: str) -> None:
518
+ """Runs in the forked query process: one query, as a query Job runs it."""
519
+ _harden(workdir)
520
+ payload, _ = _execute_and_report(request_data)
521
+ try:
522
+ out.send(payload)
523
+ finally:
524
+ out.close()
425
525
 
426
526
 
427
527
  def _ping(out: Connection) -> None:
@@ -449,6 +549,9 @@ class Stats:
449
549
  self.queries: dict[str, int] = {}
450
550
  self.refused: dict[str, int] = {}
451
551
  self.seconds_sum = 0.0
552
+ self.sticky_hits = 0
553
+ self.sticky_misses = 0
554
+ self.sticky_evictions = 0
452
555
 
453
556
  def started(self) -> None:
454
557
  with self._lock:
@@ -464,7 +567,19 @@ class Stats:
464
567
  with self._lock:
465
568
  self.refused[reason] = self.refused.get(reason, 0) + 1
466
569
 
467
- def prometheus(self, slots: int, ready: bool) -> str:
570
+ def record_sticky_hit(self) -> None:
571
+ with self._lock:
572
+ self.sticky_hits += 1
573
+
574
+ def record_sticky_miss(self) -> None:
575
+ with self._lock:
576
+ self.sticky_misses += 1
577
+
578
+ def record_sticky_eviction(self, count: int = 1) -> None:
579
+ with self._lock:
580
+ self.sticky_evictions += count
581
+
582
+ def prometheus(self, slots: int, ready: bool, sticky_idle: int = 0) -> str:
468
583
  with self._lock:
469
584
  lines = [
470
585
  "# HELP classifyre_query_worker_slots Queries one worker runs at once.",
@@ -476,6 +591,18 @@ class Stats:
476
591
  "# HELP classifyre_query_worker_ready 1 when the worker takes queries.",
477
592
  "# TYPE classifyre_query_worker_ready gauge",
478
593
  f"classifyre_query_worker_ready {1 if ready else 0}",
594
+ "# HELP classifyre_query_worker_sticky_idle Idle sticky query processes held for reuse.",
595
+ "# TYPE classifyre_query_worker_sticky_idle gauge",
596
+ f"classifyre_query_worker_sticky_idle {sticky_idle}",
597
+ "# HELP classifyre_query_worker_sticky_hits_total Queries served by a warm sticky process.",
598
+ "# TYPE classifyre_query_worker_sticky_hits_total counter",
599
+ f"classifyre_query_worker_sticky_hits_total {self.sticky_hits}",
600
+ "# HELP classifyre_query_worker_sticky_misses_total Sticky-eligible queries that forked a fresh process.",
601
+ "# TYPE classifyre_query_worker_sticky_misses_total counter",
602
+ f"classifyre_query_worker_sticky_misses_total {self.sticky_misses}",
603
+ "# HELP classifyre_query_worker_sticky_evictions_total Idle sticky processes evicted by TTL, LRU cap, or memory pressure.",
604
+ "# TYPE classifyre_query_worker_sticky_evictions_total counter",
605
+ f"classifyre_query_worker_sticky_evictions_total {self.sticky_evictions}",
479
606
  "# HELP classifyre_query_worker_queries_total Queries run, by outcome.",
480
607
  "# TYPE classifyre_query_worker_queries_total counter",
481
608
  ]
@@ -570,6 +697,31 @@ class _Running:
570
697
  memory_mb: float | None = None
571
698
 
572
699
 
700
+ @dataclass
701
+ class _StickyProcess:
702
+ key: StickyKey
703
+ process: multiprocessing.process.BaseProcess
704
+ req_out: Connection
705
+ resp_in: Connection
706
+ workdir: str
707
+ last_used_at: float = field(default_factory=time.monotonic)
708
+
709
+ def terminate(self) -> None:
710
+ try:
711
+ self.req_out.close()
712
+ except OSError:
713
+ pass
714
+ try:
715
+ self.resp_in.close()
716
+ except OSError:
717
+ pass
718
+ if self.process.pid is not None:
719
+ if self.process.is_alive():
720
+ self.process.kill()
721
+ self.process.join(5)
722
+ shutil.rmtree(self.workdir, ignore_errors=True)
723
+
724
+
573
725
  class QueryWorker:
574
726
  def __init__(self, config: WorkerConfig) -> None:
575
727
  self.config = config
@@ -586,8 +738,16 @@ class QueryWorker:
586
738
  self.warm_timings: dict[str, float] = {}
587
739
  self._running: dict[int, _Running] = {}
588
740
  self._running_lock = threading.Lock()
741
+ #: Idle sticky workers keyed by PID, ordered LRU (oldest first).
742
+ self._sticky_idle: OrderedDict[int, _StickyProcess] = OrderedDict()
743
+ self._sticky_lock = threading.Lock()
589
744
  self._query_dirs = Path(tempfile.gettempdir()) / QUERY_DIRS
590
745
 
746
+ @property
747
+ def sticky_idle_count(self) -> int:
748
+ with self._sticky_lock:
749
+ return len(self._sticky_idle)
750
+
591
751
  @property
592
752
  def ready(self) -> bool:
593
753
  return self._ready.is_set() and not self._draining.is_set()
@@ -688,6 +848,15 @@ class QueryWorker:
688
848
  else DEFAULT_TIMEOUT_SECONDS
689
849
  )
690
850
  deadline = started + seconds + BACKSTOP_SECONDS
851
+ if self.config.sticky_ttl_seconds > 0:
852
+ key = sticky_key_of(request_data)
853
+ if key is not None:
854
+ return self._run_sticky(key, request_data, client, deadline)
855
+ return self._run_oneshot(request_data, client, deadline)
856
+
857
+ def _run_oneshot(
858
+ self, request_data: dict[str, Any], client: socket.socket | None, deadline: float
859
+ ) -> Outcome:
691
860
  workdir = tempfile.mkdtemp(prefix="q-", dir=self._query_dirs)
692
861
  reader, writer = self._ctx.Pipe(duplex=False)
693
862
  process = self._ctx.Process(
@@ -702,7 +871,7 @@ class QueryWorker:
702
871
  running = _Running(process, workdir)
703
872
  with self._running_lock:
704
873
  self._running[process.pid] = running
705
- outcome = self._await(process, reader, client, deadline)
874
+ outcome = self._await(process, reader, client, deadline, wait_for_exit=True)
706
875
  if outcome.kind == "crashed" and running.memory_mb is not None:
707
876
  return Outcome("memory", exit_code=process.exitcode)
708
877
  return outcome
@@ -718,12 +887,157 @@ class QueryWorker:
718
887
  # with it, also when it was killed before it could clean up.
719
888
  shutil.rmtree(workdir, ignore_errors=True)
720
889
 
890
+ def _pop_expired_sticky_locked(self, now: float) -> list[_StickyProcess]:
891
+ ttl = self.config.sticky_ttl_seconds
892
+ expired: list[_StickyProcess] = []
893
+ for pid, entry in list(self._sticky_idle.items()):
894
+ if not entry.process.is_alive() or now - entry.last_used_at >= ttl:
895
+ expired.append(self._sticky_idle.pop(pid))
896
+ return expired
897
+
898
+ def _terminate_evicted(self, entries: list[_StickyProcess]) -> None:
899
+ if not entries:
900
+ return
901
+ for entry in entries:
902
+ entry.terminate()
903
+ self.stats.record_sticky_eviction(len(entries))
904
+
905
+ def _checkout_sticky(self, key: StickyKey) -> _StickyProcess | None:
906
+ now = time.monotonic()
907
+ chosen: _StickyProcess | None = None
908
+ with self._sticky_lock:
909
+ expired = self._pop_expired_sticky_locked(now)
910
+ for pid in reversed(list(self._sticky_idle.keys())):
911
+ if self._sticky_idle[pid].key == key:
912
+ chosen = self._sticky_idle.pop(pid)
913
+ break
914
+ self._terminate_evicted(expired)
915
+ return chosen
916
+
917
+ def _checkin_sticky(self, entry: _StickyProcess) -> None:
918
+ cap = self.config.effective_max_idle_sticky
919
+ if (
920
+ cap <= 0
921
+ or self._draining.is_set()
922
+ or self._stopping.is_set()
923
+ or not entry.process.is_alive()
924
+ or entry.process.pid is None
925
+ ):
926
+ entry.terminate()
927
+ return
928
+ entry.last_used_at = time.monotonic()
929
+ evicted: list[_StickyProcess] = []
930
+ with self._sticky_lock:
931
+ self._sticky_idle[entry.process.pid] = entry
932
+ self._sticky_idle.move_to_end(entry.process.pid)
933
+ while len(self._sticky_idle) > cap:
934
+ _, oldest = self._sticky_idle.popitem(last=False)
935
+ evicted.append(oldest)
936
+ self._terminate_evicted(evicted)
937
+
938
+ def _spawn_sticky(self, key: StickyKey) -> _StickyProcess:
939
+ workdir = tempfile.mkdtemp(prefix="qs-", dir=self._query_dirs)
940
+ req_in, req_out = self._ctx.Pipe(duplex=False)
941
+ resp_in, resp_out = self._ctx.Pipe(duplex=False)
942
+ process = self._ctx.Process(
943
+ target=_sticky_query_process,
944
+ args=(req_in, resp_out, workdir),
945
+ daemon=False,
946
+ )
947
+ process.start()
948
+ req_in.close()
949
+ resp_out.close()
950
+ return _StickyProcess(
951
+ key=key,
952
+ process=process,
953
+ req_out=req_out,
954
+ resp_in=resp_in,
955
+ workdir=workdir,
956
+ )
957
+
958
+ def _run_sticky(
959
+ self,
960
+ key: StickyKey,
961
+ request_data: dict[str, Any],
962
+ client: socket.socket | None,
963
+ deadline: float,
964
+ ) -> Outcome:
965
+ sticky = self._checkout_sticky(key)
966
+ if sticky is not None:
967
+ self.stats.record_sticky_hit()
968
+ else:
969
+ self.stats.record_sticky_miss()
970
+ sticky = self._spawn_sticky(key)
971
+
972
+ running = _Running(sticky.process, sticky.workdir)
973
+ reusable = False
974
+ try:
975
+ with self._running_lock:
976
+ if sticky.process.pid is not None:
977
+ self._running[sticky.process.pid] = running
978
+ try:
979
+ sticky.req_out.send(request_data)
980
+ except OSError:
981
+ return Outcome("crashed", exit_code=sticky.process.exitcode)
982
+ outcome = self._await(
983
+ sticky.process, sticky.resp_in, client, deadline, wait_for_exit=False
984
+ )
985
+ if outcome.kind == "crashed" and running.memory_mb is not None:
986
+ return Outcome("memory", exit_code=sticky.process.exitcode)
987
+ if (
988
+ outcome.kind == "done"
989
+ and outcome.payload is not None
990
+ and outcome.payload.get("status") == "success"
991
+ and running.memory_mb is None
992
+ and sticky.process.is_alive()
993
+ ):
994
+ reusable = True
995
+ return outcome
996
+ finally:
997
+ if sticky.process.pid is not None:
998
+ with self._running_lock:
999
+ self._running.pop(sticky.process.pid, None)
1000
+ if reusable:
1001
+ self._checkin_sticky(sticky)
1002
+ else:
1003
+ sticky.terminate()
1004
+
1005
+ def _reap_expired_sticky(self) -> None:
1006
+ if self.config.sticky_ttl_seconds <= 0:
1007
+ return
1008
+ with self._sticky_lock:
1009
+ expired = self._pop_expired_sticky_locked(time.monotonic())
1010
+ self._terminate_evicted(expired)
1011
+
1012
+ def _evict_idle_sticky_for_memory(self) -> bool:
1013
+ """Evict all idle sticky workers before touching any active query (SG §6.3)."""
1014
+ with self._sticky_lock:
1015
+ if not self._sticky_idle:
1016
+ return False
1017
+ evicted = list(self._sticky_idle.values())
1018
+ self._sticky_idle.clear()
1019
+ self._terminate_evicted(evicted)
1020
+ logger.warning(
1021
+ "Memory pressure: evicted %d idle sticky query worker(s) before touching active queries",
1022
+ len(evicted),
1023
+ )
1024
+ return True
1025
+
1026
+ def clear_sticky_idle(self) -> None:
1027
+ with self._sticky_lock:
1028
+ entries = list(self._sticky_idle.values())
1029
+ self._sticky_idle.clear()
1030
+ for entry in entries:
1031
+ entry.terminate()
1032
+
721
1033
  def _await(
722
1034
  self,
723
1035
  process: multiprocessing.process.BaseProcess,
724
1036
  reader: Connection,
725
1037
  client: socket.socket | None,
726
1038
  deadline: float,
1039
+ *,
1040
+ wait_for_exit: bool = True,
727
1041
  ) -> Outcome:
728
1042
  payload: dict[str, Any] | None = None
729
1043
  watch: list[Any] = [reader, process.sentinel]
@@ -742,7 +1056,13 @@ class QueryWorker:
742
1056
  try:
743
1057
  payload = reader.recv()
744
1058
  except (EOFError, OSError):
745
- pass
1059
+ if not wait_for_exit:
1060
+ process.join(5)
1061
+ return Outcome("crashed", exit_code=process.exitcode)
1062
+ if not wait_for_exit:
1063
+ assert payload is not None
1064
+ code = 0 if payload.get("status") == "success" else 1
1065
+ return Outcome("done", payload, code)
746
1066
  watch.remove(reader)
747
1067
  elif item is client:
748
1068
  if _client_gone(client):
@@ -751,7 +1071,7 @@ class QueryWorker:
751
1071
  watch.remove(client) # unexpected bytes: stop watching, keep running
752
1072
  else:
753
1073
  process.join(5)
754
- if payload is None:
1074
+ if payload is None and wait_for_exit:
755
1075
  try:
756
1076
  if reader.poll(0):
757
1077
  payload = reader.recv()
@@ -792,8 +1112,14 @@ class QueryWorker:
792
1112
  limit = container * self.config.memory_guard_percent / 100
793
1113
  while not self._stopping.is_set():
794
1114
  time.sleep(GUARD_INTERVAL_SECONDS)
1115
+ self._reap_expired_sticky()
795
1116
  with self._running_lock:
796
1117
  running = list(self._running.values())
1118
+ used = container_memory_mb() if limit else None
1119
+ if used is not None and used > limit:
1120
+ # Evict idle sticky workers FIRST before touching active queries (SG §6.3).
1121
+ if self._evict_idle_sticky_for_memory():
1122
+ continue
797
1123
  if not running:
798
1124
  continue
799
1125
  sizes = [
@@ -805,7 +1131,6 @@ class QueryWorker:
805
1131
  for size, entry in sizes:
806
1132
  if cap and size > cap:
807
1133
  self._stop_for_memory(entry, size, f"more than its {cap} MB")
808
- used = container_memory_mb() if limit else None
809
1134
  if used is not None and used > limit and sizes:
810
1135
  size, entry = max(sizes, key=lambda pair: pair[0])
811
1136
  if entry.memory_mb is None:
@@ -823,6 +1148,7 @@ class QueryWorker:
823
1148
  def drain(self) -> None:
824
1149
  """Stop taking queries, let running ones finish, then stop the rest."""
825
1150
  self._draining.set()
1151
+ self.clear_sticky_idle()
826
1152
  deadline = time.monotonic() + self.config.drain_seconds
827
1153
  while self.stats.active > 0 and time.monotonic() < deadline:
828
1154
  time.sleep(0.2)
@@ -832,6 +1158,7 @@ class QueryWorker:
832
1158
  stop_by = time.monotonic() + 10
833
1159
  while self.stats.active > 0 and time.monotonic() < stop_by:
834
1160
  time.sleep(0.1)
1161
+ self.clear_sticky_idle()
835
1162
 
836
1163
 
837
1164
  # ── HTTP ───────────────────────────────────────────────────────────────
@@ -874,7 +1201,9 @@ class _Handler(http.server.BaseHTTPRequestHandler):
874
1201
  ready = worker.ready
875
1202
  self._send(200 if ready else 503, {"ready": ready, "active": worker.stats.active})
876
1203
  elif self.path == "/metrics":
877
- text = worker.stats.prometheus(worker.config.slots, worker.ready)
1204
+ text = worker.stats.prometheus(
1205
+ worker.config.slots, worker.ready, worker.sticky_idle_count
1206
+ )
878
1207
  self._send(200, text, "text/plain; version=0.0.4")
879
1208
  else:
880
1209
  self._send(404, {"code": "not_found"})