Skip to content

Commit e804203

Browse files
rustyconoverclaude
andcommitted
function_storage: add scan_worker_state primitive keyed by stream_id
BoundStorage.put hardcoded os.getpid() as the worker_id, which conflated multiple waitress threads under HTTP transport (and across machines two pids can collide). The diagnostic write path used by table-function dynamic_to_string therefore lost N-1 of every N concurrent writes — EXPLAIN ANALYZE Extra Info reflected only the last writer's slice and flapped between runs. Introduce a parallel scan_worker_state primitive keyed by (execution_id, stream_id BLOB) where stream_id is the framework's per-scan-worker UUID (vgi_rpc.rpc._common._current_stream_id, preserved across HTTP turns via the state token). Each scan worker now has its own row regardless of pid/thread/machine. BoundStorage.scan_worker_put pulls the stream_id from the contextvar and falls back to a packed pid for stdio transport. Implementations on FunctionStorageSqlite and FunctionStorageCfDo; NotImplementedError stubs on FunctionStorageAzureSql until that backend is brought back into the matrix. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent df335ba commit e804203

3 files changed

Lines changed: 208 additions & 0 deletions

File tree

‎vgi/function_storage.py‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
4276
def _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
)

‎vgi/function_storage_azure_sql.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,27 @@ def _do(conn: pymssql.Connection) -> list[tuple[int, bytes]]:
314314

315315
return self._execute_with_retry(_do)
316316

317+
# --- Scan Worker State ---
318+
319+
def scan_worker_put(self, execution_id: bytes, stream_id: bytes, state: bytes) -> None:
320+
"""Store per-(execution_id, stream_id) state.
321+
322+
Not yet implemented for Azure SQL — raises so callers can detect
323+
the missing capability rather than silently dropping diagnostic
324+
rows. Add the ``scan_worker_state`` table to the Azure schema
325+
and an INSERT/UPSERT body here when this backend is brought back
326+
into the matrix.
327+
"""
328+
raise NotImplementedError(
329+
"scan_worker_state is not yet implemented for the Azure SQL backend."
330+
)
331+
332+
def scan_worker_scan(self, execution_id: bytes) -> list[tuple[bytes, bytes]]:
333+
"""Non-destructive read of (stream_id, state_data) for execution_id."""
334+
raise NotImplementedError(
335+
"scan_worker_state is not yet implemented for the Azure SQL backend."
336+
)
337+
317338
# --- Work Queue ---
318339

319340
def queue_push(self, execution_id: bytes, items: list[bytes]) -> int:

‎vgi/function_storage_cf_do.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,48 @@ def worker_scan(self, execution_id: bytes) -> list[tuple[int, bytes]]:
228228
)
229229
return rows
230230

231+
# --- Scan Worker State ---
232+
233+
def scan_worker_put(self, execution_id: bytes, stream_id: bytes, state: bytes) -> None:
234+
"""Store per-(execution_id, stream_id) state."""
235+
t0 = time.monotonic()
236+
self._post(
237+
"scan_worker_put",
238+
{
239+
"execution_id": base64.b64encode(execution_id).decode(),
240+
"stream_id": base64.b64encode(stream_id).decode(),
241+
"state": base64.b64encode(state).decode(),
242+
},
243+
)
244+
_logger.debug(
245+
"scan_worker_put eid=%s stream=%s state_bytes=%d elapsed_ms=%.1f",
246+
execution_id.hex()[:8],
247+
stream_id.hex()[:8],
248+
len(state),
249+
(time.monotonic() - t0) * 1000,
250+
)
251+
252+
def scan_worker_scan(self, execution_id: bytes) -> list[tuple[bytes, bytes]]:
253+
"""Non-destructive read of (stream_id, state) pairs for execution_id."""
254+
t0 = time.monotonic()
255+
data = self._post(
256+
"scan_worker_scan",
257+
{
258+
"execution_id": base64.b64encode(execution_id).decode(),
259+
},
260+
)
261+
rows = [
262+
(base64.b64decode(r["stream_id"]), base64.b64decode(r["state"]))
263+
for r in data["rows"]
264+
]
265+
_logger.debug(
266+
"scan_worker_scan eid=%s rows=%d elapsed_ms=%.1f",
267+
execution_id.hex()[:8],
268+
len(rows),
269+
(time.monotonic() - t0) * 1000,
270+
)
271+
return rows
272+
231273
# --- Work Queue ---
232274

233275
def queue_push(self, execution_id: bytes, items: list[bytes]) -> int:

0 commit comments

Comments
 (0)