Skip to content

Commit 3a5e8dd

Browse files
rustyconoverclaude
andcommitted
function_storage: add non-destructive worker_scan + expose BoundStorage on BindParams
Companion to worker_collect for read-only consumers like the table-function dynamic_to_string hook, where every parallel scan thread needs to see the same set of per-pid blobs without mutating storage. Returns (worker_id, state) pairs so the reader can correlate without extra bookkeeping. Implemented for the SQLite, Azure SQL, and CF DO backends; the CF DO path is wire-compatible with a future server-side worker_scan endpoint. BindParams gains an optional `storage: BoundStorage`, populated by _make_bind_params when an execution_id is supplied. The table_function_dynamic_to_string dispatcher now passes the global_execution_id through, so user-side hooks can read execution-scoped storage without manually reconstructing BoundStorage. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent cccd458 commit 3a5e8dd

7 files changed

Lines changed: 167 additions & 2 deletions

‎tests/test_function_storage.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,34 @@ def test_worker_put_replaces_existing(self, storage: FunctionStorageSqlite) -> N
4747
states = storage.worker_collect(invocation_id)
4848
assert states == [b"new_state"]
4949

50+
def test_worker_scan_non_destructive(self, storage: FunctionStorageSqlite) -> None:
51+
"""worker_scan returns (worker_id, state) pairs without deleting."""
52+
invocation_id = b"inv-scan"
53+
54+
storage.worker_put(invocation_id, worker_id=11, state=b"a")
55+
storage.worker_put(invocation_id, worker_id=22, state=b"b")
56+
57+
first = sorted(storage.worker_scan(invocation_id))
58+
assert first == [(11, b"a"), (22, b"b")]
59+
60+
# Repeat read returns the same data — non-destructive.
61+
second = sorted(storage.worker_scan(invocation_id))
62+
assert second == first
63+
64+
# And worker_collect after scan still drains.
65+
collected = sorted(storage.worker_collect(invocation_id))
66+
assert collected == [b"a", b"b"]
67+
assert storage.worker_scan(invocation_id) == []
68+
69+
def test_worker_scan_isolates_executions(self, storage: FunctionStorageSqlite) -> None:
70+
"""worker_scan only returns rows for the given execution_id."""
71+
storage.worker_put(b"exec-A", worker_id=1, state=b"a1")
72+
storage.worker_put(b"exec-B", worker_id=1, state=b"b1")
73+
74+
assert storage.worker_scan(b"exec-A") == [(1, b"a1")]
75+
assert storage.worker_scan(b"exec-B") == [(1, b"b1")]
76+
assert storage.worker_scan(b"exec-missing") == []
77+
5078
# --- Work Queue Tests ---
5179

5280
def test_queue_push_and_pop(self, storage: FunctionStorageSqlite) -> None:

‎tests/test_table_function_dynamic_to_string.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,44 @@ class _MyWorker(Worker):
139139
assert any("dynamic_to_string" in rec.message for rec in caplog.records), (
140140
"expected an error log when user hook raises"
141141
)
142+
143+
def test_bind_params_carries_execution_scoped_storage(self) -> None:
144+
"""Dispatcher populates BindParams.storage keyed by global_execution_id.
145+
146+
Lets dynamic_to_string read whatever process() persisted via
147+
worker_put without manually reconstructing BoundStorage.
148+
"""
149+
150+
@init_single_worker
151+
@bind_fixed_schema
152+
class _StorageFunc(TableFunctionGenerator[_Args]):
153+
class Meta:
154+
name = "with_storage"
155+
156+
FIXED_SCHEMA = pa.schema([pa.field("n", pa.int64())])
157+
158+
@classmethod
159+
def dynamic_to_string(
160+
cls, params: BindParams[_Args], execution_id: bytes
161+
) -> Mapping[str, str]:
162+
assert params.storage is not None
163+
pairs = params.storage.worker_scan()
164+
return {f"pid_{wid}": state.decode() for wid, state in sorted(pairs)}
165+
166+
@classmethod
167+
def process(cls, params, state, out) -> None: # type: ignore[no-untyped-def]
168+
out.finish()
169+
170+
class _MyWorker(Worker):
171+
functions = [_StorageFunc]
172+
173+
worker = _MyWorker()
174+
execution_id = b"\x01\x02\x03\x04\x05\x06\x07\x08"
175+
_StorageFunc.storage.worker_put(execution_id, worker_id=10, state=b"hello")
176+
_StorageFunc.storage.worker_put(execution_id, worker_id=20, state=b"world")
177+
178+
result = worker.table_function_dynamic_to_string(_request("with_storage"), _ctx())
179+
assert dict(zip(result.keys, result.values, strict=True)) == {
180+
"pid_10": "hello",
181+
"pid_20": "world",
182+
}

‎vgi/function_storage.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,27 @@ def worker_collect(self, execution_id: bytes) -> list[bytes]:
9999
"""
100100
...
101101

102+
def worker_scan(self, execution_id: bytes) -> list[tuple[int, bytes]]:
103+
"""Non-destructive read of all worker states for an execution.
104+
105+
Companion to ``worker_collect`` for use cases where multiple
106+
readers need to observe the same set of worker states without
107+
mutating storage. The intended consumer is the table-function
108+
``dynamic_to_string`` hook, which fires once per parallel scan
109+
thread at end-of-stream and is best-effort: every thread must
110+
be able to read the full set, which precludes the
111+
atomic-destructive semantics of ``worker_collect``.
112+
113+
Args:
114+
execution_id: Unique identifier for the function invocation.
115+
116+
Returns:
117+
List of ``(worker_id, state_bytes)`` pairs. Order is
118+
implementation-defined.
119+
120+
"""
121+
...
122+
102123
# --- Work Queue (distributed work items) ---
103124

104125
def queue_push(self, execution_id: bytes, items: list[bytes]) -> int:
@@ -342,6 +363,10 @@ def collect(self) -> list[bytes]:
342363
"""Atomically collect and delete all worker states."""
343364
return self._base.worker_collect(self._execution_id)
344365

366+
def worker_scan(self) -> list[tuple[int, bytes]]:
367+
"""Non-destructive read of (worker_id, state) pairs for this execution."""
368+
return self._base.worker_scan(self._execution_id)
369+
345370
def queue_push(self, items: list[bytes]) -> int:
346371
"""Add work items to the queue and register the invocation."""
347372
return self._base.queue_push(self._execution_id, items)
@@ -630,6 +655,19 @@ def worker_collect(self, execution_id: bytes) -> list[bytes]:
630655
conn.commit()
631656
return states
632657

658+
def worker_scan(self, execution_id: bytes) -> list[tuple[int, bytes]]:
659+
"""Non-destructive read of (process_id, state_data) for execution_id."""
660+
conn = self._conn()
661+
cursor = conn.execute(
662+
"""
663+
SELECT process_id, state_data
664+
FROM worker_state
665+
WHERE execution_id = ?
666+
""",
667+
(execution_id,),
668+
)
669+
return [(int(row[0]), row[1]) for row in cursor.fetchall()]
670+
633671
# --- Work Queue ---
634672

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

‎vgi/function_storage_azure_sql.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,31 @@ def _do(conn: pymssql.Connection) -> list[bytes]:
289289

290290
return self._execute_with_retry(_do)
291291

292+
def worker_scan(self, execution_id: bytes) -> list[tuple[int, bytes]]:
293+
"""Non-destructive read of (process_id, state_data) for execution_id."""
294+
295+
def _do(conn: pymssql.Connection) -> list[tuple[int, bytes]]:
296+
t0 = time.monotonic()
297+
cursor = conn.cursor()
298+
cursor.execute(
299+
"""
300+
SELECT process_id, state_data
301+
FROM worker_state
302+
WHERE execution_id = CAST(%s AS VARBINARY(16))
303+
""",
304+
(execution_id,),
305+
)
306+
rows: list[tuple[int, bytes]] = [(int(r[0]), r[1]) for r in cursor.fetchall()] # type: ignore[misc]
307+
_logger.debug(
308+
"worker_scan eid=%s rows=%d elapsed_ms=%.1f",
309+
execution_id.hex()[:8],
310+
len(rows),
311+
(time.monotonic() - t0) * 1000,
312+
)
313+
return rows
314+
315+
return self._execute_with_retry(_do)
316+
292317
# --- Work Queue ---
293318

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

‎vgi/function_storage_cf_do.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,24 @@ def worker_collect(self, execution_id: bytes) -> list[bytes]:
175175
)
176176
return states
177177

178+
def worker_scan(self, execution_id: bytes) -> list[tuple[int, bytes]]:
179+
"""Non-destructive read of (worker_id, state) pairs for execution_id."""
180+
t0 = time.monotonic()
181+
data = self._post(
182+
"worker_scan",
183+
{
184+
"execution_id": base64.b64encode(execution_id).decode(),
185+
},
186+
)
187+
rows = [(int(r["worker_id"]), base64.b64decode(r["state"])) for r in data["rows"]]
188+
_logger.debug(
189+
"worker_scan eid=%s rows=%d elapsed_ms=%.1f",
190+
execution_id.hex()[:8],
191+
len(rows),
192+
(time.monotonic() - t0) * 1000,
193+
)
194+
return rows
195+
178196
# --- Work Queue ---
179197

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

‎vgi/table_function.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -302,6 +302,12 @@ class BindParams[TArgs]:
302302
# rather than once per bind/cardinality/statistics/init phase.
303303
# ``None`` when ``bind_call.transaction_id`` is unset.
304304
transaction_storage: TransactionBoundStorage | None = None
305+
# Execution-scoped storage view. Populated only on call paths that
306+
# carry a ``global_execution_id`` — currently just
307+
# ``dynamic_to_string``. ``None`` for ``bind`` / ``cardinality`` /
308+
# ``statistics`` (they predate execution and have no
309+
# execution_id).
310+
storage: BoundStorage | None = None
305311
auth_context: AuthContext = AuthContext.anonymous()
306312

307313

@@ -576,11 +582,15 @@ def _make_bind_params(
576582
input: BindRequest,
577583
*,
578584
auth_context: AuthContext | None = None,
585+
execution_id: bytes | None = None,
579586
) -> BindParams[TArgs]:
580587
"""Construct BindParams from a BindRequest.
581588
582589
Shared by bind() and table_function_cardinality() to avoid
583-
duplicating BindParams construction logic.
590+
duplicating BindParams construction logic. ``execution_id`` is
591+
only populated on call paths that have one (currently just
592+
``dynamic_to_string``); when provided, ``BindParams.storage`` is
593+
a ``BoundStorage`` view keyed by it.
584594
"""
585595
txn_id = input.transaction_id
586596
return BindParams[TArgs](
@@ -589,6 +599,7 @@ def _make_bind_params(
589599
settings=_batch_to_scalar_dict(input.settings),
590600
secrets=SecretsAccessor(input.secrets, is_retry=input.resolved_secrets_provided),
591601
transaction_storage=TransactionBoundStorage(cls.storage, txn_id) if txn_id else None,
602+
storage=BoundStorage(cls.storage, execution_id) if execution_id else None,
592603
auth_context=auth_context if auth_context is not None else AuthContext.anonymous(),
593604
)
594605

‎vgi/worker.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1617,7 +1617,11 @@ def table_function_dynamic_to_string(
16171617
if not issubclass(func_cls, TableFunctionGenerator):
16181618
return empty
16191619
try:
1620-
params = func_cls._make_bind_params(request.bind_call, auth_context=ctx.auth)
1620+
params = func_cls._make_bind_params(
1621+
request.bind_call,
1622+
auth_context=ctx.auth,
1623+
execution_id=request.global_execution_id,
1624+
)
16211625
mapping = func_cls.dynamic_to_string(params, request.global_execution_id)
16221626
except Exception:
16231627
_logger.exception("dynamic_to_string: user hook raised on %s", func_cls.__name__)

0 commit comments

Comments
 (0)