Skip to content

Commit 915118a

Browse files
rustyconoverclaude
andcommitted
meta_worker: unwrap attach_id on table_function_{cardinality,statistics,dynamic_to_string} + magic-prefix wrapper
Two related fixes plus observability. 1. **Missing unwraps.** `MetaWorker.{bind, init, catalog_*, aggregate_*}` all unwrap the sub-worker index byte before delegating to the matching sub-worker. `table_function_cardinality`, `table_function_statistics`, and `table_function_dynamic_to_string` did not — they passed the wrapped attach_id straight through. Result: `process()` derived its storage shard_key from the unwrapped (sub-worker-side) attach_id while `dynamic_to_string` derived from the still-wrapped (meta-side) attach_id, so storage reads landed on a different CF Durable Object than the writes. Symptom: `EXPLAIN ANALYZE` lost user-supplied Extra Info on attached catalogs. Fix: shared `_unwrap_bind_call_attach_id` helper threaded through all three sites. 2. **Self-identifying wrapper.** The wrap format was `bytes([idx]) + attach_id` — a bare 1-byte prefix indistinguishable from a real attach_id whose first byte happened to match. New format prepends a 3-byte `b"MW\x00"` magic, so `_unwrap` raises `KeyError` (callers fall back to a function-name registry scan) when input isn't actually a MetaWorker wrap. 4 bytes of total overhead instead of 1. Storage shards prefixed with `att-4d570000…` are visibly MetaWorker-routed. 3. **Dispatch tagging.** Every MetaWorker wrap/unwrap site now emits a `vgi.meta_worker` debug log with `method`, `function`, `sub_worker_index`, `wrapped_aid` (short hex), `unwrapped_aid` (short hex). Startup emits one info-level mapping of `{index, worker_class, catalogs}` per sub-worker so a stray `wrapped_aid=…` line in a dispatch log is self-explanatory. `function_storage._derive_shard_key` emits a matching `vgi.storage.shard` debug log on every BoundStorage construction so routing bugs can be diffed line-by-line between meta-side dispatch and storage-side shard derivation. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 8934996 commit 915118a

3 files changed

Lines changed: 236 additions & 23 deletions

File tree

‎vgi/function_storage.py‎

Lines changed: 38 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"""
1717

1818
import hashlib
19+
import logging
1920
import os
2021
import random
2122
import sqlite3
@@ -24,21 +25,31 @@
2425

2526
import pyarrow as pa
2627

28+
29+
# When the parent vgi.* logger is configured at DEBUG, this emits one line
30+
# per BoundStorage construction with the resolved shard_key — handy for
31+
# cross-referencing storage-routing bugs with MetaWorker dispatch logs.
32+
_shard_logger = logging.getLogger("vgi.storage.shard")
33+
2734
__all__ = [
2835
"FunctionStorage",
2936
"FunctionStorageSqlite",
3037
]
3138

3239

33-
def _derive_shard_key(*, attach_id: bytes | None, auth: Any) -> str:
40+
def _derive_shard_key(*, attach_id: bytes | None, auth: Any, _origin: str = "?") -> str:
3441
"""Return the routing key for the ``FunctionStorageCfDo`` Durable Object.
3542
3643
Server-derived inside the trusted worker process. The CF DO routes by
3744
this key (``idFromName(shard_key)``), so one DO instance hosts every
3845
storage op carrying the same shard_key. Precedence:
3946
40-
1. ``attach_id`` (UUID4 minted by ``catalog_attach``) — one DO per
41-
ATTACH window. Best amortization for ATTACH-ed catalogs.
47+
1. ``attach_id`` (worker-vended bytes from ``catalog_attach``) — one
48+
DO per logical ATTACH. Best amortization for ATTACH-ed catalogs.
49+
Note: workers are NOT required to make attach_ids globally unique,
50+
so collisions across processes are possible. MetaWorker prepends
51+
a 1-byte sub-worker index, which keeps shards distinct *within*
52+
one DuckDB session.
4253
2. Hash of ``(auth.domain, auth.principal)`` — HTTP transport,
4354
authenticated, no ATTACH. One DO per (user, deployment).
4455
3. ``"loc-anon"`` — anonymous, no-ATTACH callers. Single shared DO
@@ -47,15 +58,29 @@ def _derive_shard_key(*, attach_id: bytes | None, auth: Any) -> str:
4758
(subprocess transport, local CLIs) are typically dev/test.
4859
4960
No-op for non-CfDo backends — they ignore the value.
61+
62+
``_origin`` labels the call site (e.g. ``"BoundStorage(InitRequest)"``).
63+
Emitted as a ``vgi.storage.shard`` debug log for cross-referencing
64+
storage-routing bugs with MetaWorker dispatch logs.
5065
"""
5166
if attach_id is not None:
52-
return "att-" + attach_id.hex()
53-
if auth is not None and getattr(auth, "authenticated", False):
67+
key = "att-" + attach_id.hex()
68+
elif auth is not None and getattr(auth, "authenticated", False):
5469
domain = getattr(auth, "domain", "")
5570
principal = getattr(auth, "principal", "")
5671
digest = hashlib.sha256(f"{domain}\0{principal}".encode()).hexdigest()
57-
return "prn-" + digest[:32]
58-
return "loc-anon"
72+
key = "prn-" + digest[:32]
73+
else:
74+
key = "loc-anon"
75+
if _shard_logger.isEnabledFor(logging.DEBUG):
76+
_shard_logger.debug(
77+
"shard derived origin=%s attach_id=%s authed=%d key=%s",
78+
_origin,
79+
attach_id.hex()[:16] if attach_id else "-",
80+
int(bool(auth is not None and getattr(auth, "authenticated", False))),
81+
key,
82+
)
83+
return key
5984

6085

6186
def _scan_worker_stream_id() -> bytes:
@@ -434,13 +459,15 @@ def __init__(
434459
# BoundStorage), or pass request= / attach_id= / auth= and let us
435460
# derive. See BoundStorage for the request= polymorphism.
436461
if shard_key is None:
462+
origin = "TransactionBoundStorage"
437463
if attach_id is None and request is not None:
438464
attach_id = getattr(request, "attach_id", None)
439465
if attach_id is None:
440466
bind_call = getattr(request, "bind_call", None)
441467
if bind_call is not None:
442468
attach_id = getattr(bind_call, "attach_id", None)
443-
shard_key = _derive_shard_key(attach_id=attach_id, auth=auth)
469+
origin = f"TransactionBoundStorage({type(request).__name__})"
470+
shard_key = _derive_shard_key(attach_id=attach_id, auth=auth, _origin=origin)
444471
self._shard_key = shard_key
445472

446473
def get(self, keys: list[bytes]) -> list[bytes | None]:
@@ -488,13 +515,15 @@ def __init__(
488515
# or ``request.bind_call.attach_id`` (InitRequest). Callers may
489516
# alternatively pass ``attach_id=`` directly; anonymous callers
490517
# fall through to "loc-anon".
518+
origin = "BoundStorage"
491519
if attach_id is None and request is not None:
492520
attach_id = getattr(request, "attach_id", None)
493521
if attach_id is None:
494522
bind_call = getattr(request, "bind_call", None)
495523
if bind_call is not None:
496524
attach_id = getattr(bind_call, "attach_id", None)
497-
self._shard_key = _derive_shard_key(attach_id=attach_id, auth=auth)
525+
origin = f"BoundStorage({type(request).__name__})"
526+
self._shard_key = _derive_shard_key(attach_id=attach_id, auth=auth, _origin=origin)
498527

499528
def transaction(self, transaction_id: bytes) -> TransactionBoundStorage:
500529
"""Return a transaction-scoped storage view.

0 commit comments

Comments
 (0)