@@ -39,6 +39,40 @@ class UnknownInvocationError(Exception):
3939 """
4040
4141
42+ def _scan_worker_stream_id () -> bytes :
43+ """Return raw stream-id bytes for the current scan worker.
44+
45+ HTTP transport: pulls the per-stream UUID from
46+ ``vgi_rpc.rpc._common._current_stream_id`` and returns its raw 16-byte
47+ form. The framework sets this once per ``_serve_stream`` call and
48+ preserves it across HTTP turns via the state token, so every tick of
49+ one scan worker yields the same bytes regardless of which machine
50+ or thread serves it.
51+
52+ Stdio transport / any non-stream path: returns
53+ ``struct.pack("<Q", os.getpid())`` so we still have a stable
54+ per-pid identifier and the storage row doesn't collide. Distinct
55+ pids → distinct keys; same pid across queries → overwrite (same
56+ semantics as the old per-pid ``BoundStorage.put``).
57+ """
58+ import struct
59+ try :
60+ from vgi_rpc .rpc ._common import _current_stream_id
61+ except ImportError :
62+ return struct .pack ("<Q" , os .getpid ())
63+ sid = _current_stream_id .get ()
64+ if not sid :
65+ return struct .pack ("<Q" , os .getpid ())
66+ # Stream ids are hex-encoded 128-bit UUIDs. Decode to the canonical
67+ # 16-byte form so the storage column doesn't carry the encoding tax.
68+ try :
69+ return bytes .fromhex (sid )
70+ except ValueError :
71+ # Defensively fall back to UTF-8 bytes — preserves uniqueness
72+ # even if a future framework version uses a non-hex stream id.
73+ return sid .encode ("utf-8" )
74+
75+
4276def _get_default_db_path () -> str :
4377 """Return the default SQLite database path for VGI storage."""
4478 from pathlib import Path
@@ -120,6 +154,49 @@ def worker_scan(self, execution_id: bytes) -> list[tuple[int, bytes]]:
120154 """
121155 ...
122156
157+ # --- Scan Worker State (per-stream-id, distinct from worker_state) ---
158+ #
159+ # ``worker_state`` above is keyed by ``os.getpid()`` and conflates threads
160+ # in one process — under HTTP transport (waitress thread pool) every scan
161+ # worker landing in the same Python process collides on a single row.
162+ # ``scan_worker_state`` keys by the framework's per-scan-worker UUID
163+ # (``vgi_rpc.rpc._common._current_stream_id``), giving each scan worker
164+ # its own row regardless of pid/thread/machine.
165+
166+ def scan_worker_put (self , execution_id : bytes , stream_id : bytes , state : bytes ) -> None :
167+ """Store per-scan-worker state for an execution.
168+
169+ Replaces any prior state for the same ``(execution_id, stream_id)``
170+ pair — successive ticks of one scan worker overwrite each other.
171+
172+ Args:
173+ execution_id: Unique identifier for the function invocation.
174+ stream_id: The framework's per-scan-worker stream UUID
175+ (raw bytes; typically the 16-byte form of the hex
176+ ``_current_stream_id`` ContextVar).
177+ state: Serialized state bytes.
178+
179+ """
180+ ...
181+
182+ def scan_worker_scan (self , execution_id : bytes ) -> list [tuple [bytes , bytes ]]:
183+ """Non-destructive read of all per-scan-worker states for an execution.
184+
185+ The intended consumer is the table-function ``dynamic_to_string``
186+ hook. Each scan worker writes one row keyed by its stream_id;
187+ ``dynamic_to_string`` reads all of them to build the EXPLAIN ANALYZE
188+ Extra Info block.
189+
190+ Args:
191+ execution_id: Unique identifier for the function invocation.
192+
193+ Returns:
194+ List of ``(stream_id, state_bytes)`` pairs. Order is
195+ implementation-defined.
196+
197+ """
198+ ...
199+
123200 # --- Work Queue (distributed work items) ---
124201
125202 def queue_push (self , execution_id : bytes , items : list [bytes ]) -> int :
@@ -367,6 +444,25 @@ def worker_scan(self) -> list[tuple[int, bytes]]:
367444 """Non-destructive read of (worker_id, state) pairs for this execution."""
368445 return self ._base .worker_scan (self ._execution_id )
369446
447+ # --- Scan Worker State (per-stream-id) ---
448+
449+ def scan_worker_put (self , state : bytes ) -> None :
450+ """Store state for the current scan worker.
451+
452+ Keyed by the framework's per-stream UUID (``_current_stream_id``
453+ ContextVar) so each scan worker has its own row regardless of
454+ pid/thread/machine — distinct from ``put()`` which conflates
455+ multiple threads in one Python process. Falls back to a
456+ pid-derived key when no stream is active (stdio transport, or
457+ any code path called outside an HTTP scan request).
458+ """
459+ sid = _scan_worker_stream_id ()
460+ self ._base .scan_worker_put (self ._execution_id , sid , state )
461+
462+ def scan_worker_scan (self ) -> list [tuple [bytes , bytes ]]:
463+ """Non-destructive read of (stream_id, state) pairs for this execution."""
464+ return self ._base .scan_worker_scan (self ._execution_id )
465+
370466 def queue_push (self , items : list [bytes ]) -> int :
371467 """Add work items to the queue and register the invocation."""
372468 return self ._base .queue_push (self ._execution_id , items )
@@ -607,6 +703,19 @@ def _ensure_tables(self) -> None:
607703 PRIMARY KEY (transaction_id, key)
608704 )
609705 """ )
706+ # Scan worker state - per-(execution_id, stream_id) storage for
707+ # diagnostic blobs that must be scoped to the exact scan worker
708+ # that produced them. Distinct from worker_state above (which is
709+ # keyed by os.getpid() and conflates threads of one process).
710+ conn .execute ("""
711+ CREATE TABLE IF NOT EXISTS scan_worker_state (
712+ execution_id BLOB NOT NULL,
713+ stream_id BLOB NOT NULL,
714+ state_data BLOB NOT NULL,
715+ created_at REAL DEFAULT (julianday('now')),
716+ PRIMARY KEY (execution_id, stream_id)
717+ )
718+ """ )
610719 # Aggregate window partitions - per-partition cached input for windowed aggregates
611720 conn .execute ("""
612721 CREATE TABLE IF NOT EXISTS aggregate_window_partitions (
@@ -668,6 +777,34 @@ def worker_scan(self, execution_id: bytes) -> list[tuple[int, bytes]]:
668777 )
669778 return [(int (row [0 ]), row [1 ]) for row in cursor .fetchall ()]
670779
780+ # --- Scan Worker State ---
781+
782+ def scan_worker_put (self , execution_id : bytes , stream_id : bytes , state : bytes ) -> None :
783+ """Store per-(execution_id, stream_id) state."""
784+ conn = self ._conn ()
785+ conn .execute (
786+ """
787+ INSERT OR REPLACE INTO scan_worker_state
788+ (execution_id, stream_id, state_data, created_at)
789+ VALUES (?, ?, ?, julianday('now'))
790+ """ ,
791+ (execution_id , stream_id , state ),
792+ )
793+ conn .commit ()
794+
795+ def scan_worker_scan (self , execution_id : bytes ) -> list [tuple [bytes , bytes ]]:
796+ """Non-destructive read of (stream_id, state_data) for execution_id."""
797+ conn = self ._conn ()
798+ cursor = conn .execute (
799+ """
800+ SELECT stream_id, state_data
801+ FROM scan_worker_state
802+ WHERE execution_id = ?
803+ """ ,
804+ (execution_id ,),
805+ )
806+ return [(row [0 ], row [1 ]) for row in cursor .fetchall ()]
807+
671808 # --- Work Queue ---
672809
673810 def queue_push (self , execution_id : bytes , items : list [bytes ]) -> int :
@@ -952,6 +1089,13 @@ def cleanup_old_entries(self, max_age_days: float = 1.0) -> int:
9521089 """ ,
9531090 (max_age_days ,),
9541091 )
1092+ cursor8 = conn .execute (
1093+ """
1094+ DELETE FROM scan_worker_state
1095+ WHERE julianday('now') - created_at > ?
1096+ """ ,
1097+ (max_age_days ,),
1098+ )
9551099 conn .commit ()
9561100 return (
9571101 int (cursor1 .rowcount )
@@ -961,4 +1105,5 @@ def cleanup_old_entries(self, max_age_days: float = 1.0) -> int:
9611105 + int (cursor5 .rowcount )
9621106 + int (cursor6 .rowcount )
9631107 + int (cursor7 .rowcount )
1108+ + int (cursor8 .rowcount )
9641109 )
0 commit comments