Skip to content

Commit 53ee8ce

Browse files
rustyconoverclaude
andcommitted
feat: Attach() gives a scalar's compute() its ATTACH options
compute() could not read ATTACH options: only bind() sees them, process() is final, and its signature is fixed. A compute() parameter annotated Annotated[dict[str, Any], Attach()] now receives attach_options() of the worker-unwrapped attach (secret options included; {} outside a catalog), as Auth() receives the AuthContext. BoundStorage keeps the unwrapped attach it is built with, so process()'s signature is unchanged. BindResult.opaque_data's docstring no longer claims compute() receives it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9de85cd commit 53ee8ce

6 files changed

Lines changed: 193 additions & 3 deletions

File tree

‎docs/catalog-interface.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,23 @@ class Lookup(TableFunctionGenerator[None, None]):
407407
...
408408
```
409409

410+
A `ScalarFunction`'s `compute()` has no `params`; declare a parameter annotated with `Attach()`
411+
instead. It receives the same dict (`{}` when the call is not through an attached catalog):
412+
413+
```python test="skip"
414+
from vgi import Attach, Param, Returns, ScalarFunction
415+
416+
class Lookup(ScalarFunction):
417+
@classmethod
418+
def compute(
419+
cls,
420+
key: Annotated[pa.StringArray, Param(doc="Key")],
421+
options: Annotated[dict[str, Any], Attach()],
422+
) -> Annotated[pa.StringArray, Returns()]:
423+
base_url = options.get("base_url", "https://api.example.com")
424+
...
425+
```
426+
410427
On a host whose temp directory is shared or unsuitable, point `VGI_ATTACH_SECRET_KEY_FILE` at a
411428
private file (all worker processes of the deployment must use the same one), or call
412429
`vgi.attach_secret_options.set_attach_secret_options_key(key)` at startup.
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""A scalar's ``compute()`` receives its ATTACH options through an ``Attach()`` parameter."""
4+
5+
from __future__ import annotations
6+
7+
from collections.abc import Iterator
8+
from pathlib import Path
9+
from typing import Annotated, Any
10+
11+
import pyarrow as pa
12+
import pytest
13+
from vgi_rpc.rpc import AuthContext
14+
15+
from vgi import attach_secret_options as aso
16+
from vgi._test_fixtures.writable_tx import TxfixWorker
17+
from vgi.arguments import Arguments, Attach, Param, Returns
18+
from vgi.function_storage import BoundStorage
19+
from vgi.invocation import FunctionType, GlobalInitResponse
20+
from vgi.protocol import BindRequest, CatalogAttachRequest, InitRequest
21+
from vgi.scalar_function import ScalarFunction
22+
23+
24+
@pytest.fixture(autouse=True)
25+
def _private_key_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
26+
"""Point the host-local attach key at a per-test file."""
27+
monkeypatch.setenv("VGI_ATTACH_SECRET_KEY_FILE", str(tmp_path / "keys" / "attach-secret-options.key"))
28+
aso._host_local_cache.clear()
29+
aso.set_attach_secret_options_key(None)
30+
yield
31+
aso._host_local_cache.clear()
32+
33+
34+
class _OptionEcho(ScalarFunction):
35+
"""Returns one ATTACH option per row."""
36+
37+
class Meta:
38+
"""Metadata."""
39+
40+
name = "option_echo"
41+
42+
@classmethod
43+
def compute(
44+
cls,
45+
x: Annotated[pa.Int64Array, Param(doc="Any column")],
46+
options: Annotated[dict[str, Any], Attach()],
47+
) -> Annotated[pa.StringArray, Returns()]:
48+
"""Echo the ``token`` option (or 'none') for every row."""
49+
value = options.get("token")
50+
return pa.array([str(value) if value is not None else "none"] * len(x), type=pa.string())
51+
52+
53+
def _run(attach_plaintext: bytes | None) -> list[str]:
54+
bind_call = BindRequest(
55+
function_name="option_echo",
56+
arguments=Arguments(),
57+
function_type=FunctionType.SCALAR,
58+
input_schema=pa.schema([("x", pa.int64())]),
59+
)
60+
init_call = InitRequest(bind_call=bind_call, output_schema=pa.schema([("result", pa.string())]))
61+
result = _OptionEcho.process(
62+
batch=pa.record_batch({"x": [1, 2]}),
63+
init_call=init_call,
64+
init_response=GlobalInitResponse(),
65+
storage=BoundStorage(_OptionEcho.storage, b"\x00" * 16, attach_plaintext=attach_plaintext),
66+
auth_context=AuthContext.anonymous(),
67+
)
68+
return [str(v) for v in result.column(0).to_pylist()]
69+
70+
71+
def test_attach_param_detected() -> None:
72+
"""The marker is found and is not a call argument."""
73+
assert _OptionEcho._attach_param == "options"
74+
assert "options" not in _OptionEcho._compute_params
75+
assert "options" not in _OptionEcho._const_params
76+
77+
78+
def test_compute_receives_attach_options_including_secret() -> None:
79+
"""Options of a real attach (a secret one included) reach compute() through the unwrapped attach."""
80+
worker = TxfixWorker(quiet=True)
81+
options = pa.RecordBatch.from_pylist([{"token": "tok-attach-echo", "transactional": False}])
82+
sealed = worker.catalog_attach(
83+
CatalogAttachRequest(name="txfix", options=options, data_version_spec=None, implementation_version=None)
84+
).attach_opaque_data
85+
assert sealed is not None
86+
assert b"tok-attach-echo" not in bytes(sealed)
87+
88+
assert _run(worker._unwrap_attach_full(bytes(sealed))) == ["tok-attach-echo", "tok-attach-echo"]
89+
90+
91+
def test_no_attach_gives_empty_options() -> None:
92+
"""Outside an attached catalog the parameter is ``{}``."""
93+
assert _run(None) == ["none", "none"]
94+
95+
96+
def test_two_attach_params_rejected() -> None:
97+
"""Declaring the marker twice is an error at class definition."""
98+
with pytest.raises(TypeError, match="multiple Attach parameters"):
99+
100+
class _Twice(ScalarFunction):
101+
class Meta:
102+
name = "twice"
103+
104+
@classmethod
105+
def compute(
106+
cls,
107+
x: Annotated[pa.Int64Array, Param(doc="x")],
108+
a: Annotated[dict[str, Any], Attach()],
109+
b: Annotated[dict[str, Any], Attach()],
110+
) -> Annotated[pa.Int64Array, Returns()]:
111+
return x

‎vgi/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
Arg,
3636
Arguments,
3737
ArgumentValidationError,
38+
Attach,
3839
Auth,
3940
ConstParam,
4041
Param,
@@ -175,6 +176,7 @@
175176
"ArgumentValidationError",
176177
"Arguments",
177178
"ArgumentMonotonicity",
179+
"Attach",
178180
"Auth",
179181
"AuthContext",
180182
"CallContext",

‎vgi/arguments.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,7 @@ def _accepts_none(annotated_inner_type: Any) -> bool:
206206
"TaggedUnion",
207207
"TypeBoundPredicate",
208208
"OutputLength",
209+
"Attach",
209210
"Setting",
210211
"Secret",
211212
"SecretLookupEntry",
@@ -1910,6 +1911,28 @@ class Auth:
19101911
"""
19111912

19121913

1914+
@dataclass(frozen=True, slots=True)
1915+
class Attach:
1916+
"""Metadata for an ATTACH-options parameter in `compute()`.
1917+
1918+
Use with Annotated to declare a parameter that receives the options of the
1919+
``ATTACH`` the scalar was called through, as returned by
1920+
[`attach_options`][vgi.catalog.attach_option.attach_options]: lower-cased
1921+
option names to values, secret options included, defaults not filled in.
1922+
A call outside an attached catalog receives ``{}``.
1923+
1924+
```python
1925+
@classmethod
1926+
def compute(
1927+
cls,
1928+
vin: Annotated[pa.StringArray, Param(doc="VIN")],
1929+
options: Annotated[dict[str, Any], Attach()],
1930+
) -> pa.StringArray: ...
1931+
```
1932+
1933+
"""
1934+
1935+
19131936
@dataclass(frozen=True, slots=True)
19141937
class OutputLength:
19151938
"""Metadata for output length parameter in `compute()`.

‎vgi/function_storage.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -683,6 +683,9 @@ def __init__(
683683
# derivation origin for debug logs.
684684
origin = f"BoundStorage({type(request).__name__})" if request is not None else "BoundStorage"
685685
self._shard_key = _resolve_shard_key(storage, attach_plaintext, origin)
686+
# Kept for ScalarFunction.process, which reads the ATTACH options for an
687+
# ``Attach()`` compute() parameter from here (process()'s signature is fixed).
688+
self._attach_plaintext = attach_plaintext
686689

687690
def transaction(self, transaction_opaque_data: bytes) -> TransactionBoundStorage:
688691
"""Return a transaction-scoped storage view.

‎vgi/scalar_function.py‎

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
Arg,
5454
Arguments,
5555
ArgumentValidationError,
56+
Attach,
5657
Auth,
5758
ConstParam,
5859
OutputLength,
@@ -97,8 +98,10 @@ class BindResult(ArrowSerializableDataclass):
9798
9899
Attributes:
99100
output_type: Arrow data type for the output value.
100-
opaque_data: Optional serialized data, opaque to the caller,
101-
that will be passed to `global_init()` and `process()`.
101+
opaque_data: Optional serialized data, opaque to the caller. It is
102+
passed to `global_init()`; a `process()` override can read it as
103+
``init_call.bind_opaque_data``. `compute()` does not receive it: use
104+
an [`Attach`][vgi.arguments.Attach] parameter for ATTACH options.
102105
103106
"""
104107

@@ -894,6 +897,7 @@ def __getattr__(self, _name: str) -> Any:
894897
_secret_params: dict[str, Secret] # Secret params: param_name -> Secret instance
895898
_output_length_param: str | None # OutputLength param name (batch row count)
896899
_auth_param: str | None # Auth param name (receives AuthContext)
900+
_attach_param: str | None # Attach param name (receives the ATTACH options)
897901
_returns_output_type: pa.DataType | None # Output type from Returns()
898902

899903
def __init_subclass__(cls, **kwargs: Any) -> None:
@@ -951,6 +955,7 @@ def __getattr__(self, name: str) -> Any:
951955
"Setting": vgi_args.Setting,
952956
"Secret": vgi_args.Secret,
953957
"Auth": vgi_args.Auth,
958+
"Attach": vgi_args.Attach,
954959
"OutputLength": vgi_args.OutputLength,
955960
"Returns": vgi_args.Returns,
956961
"AnyArrow": vgi_args.AnyArrow,
@@ -968,6 +973,7 @@ def __getattr__(self, name: str) -> Any:
968973
const_scalar_params: set[str] = set() # ConstParams annotated as pa.Scalar
969974
output_length_param: str | None = None # param that receives batch row count
970975
auth_param: str | None = None # param that receives AuthContext
976+
attach_param: str | None = None # param that receives the ATTACH options
971977
returns_output_type: pa.DataType | None = None
972978

973979
# Check return type for Returns() annotation
@@ -1069,6 +1075,17 @@ def __getattr__(self, name: str) -> Any:
10691075
# Don't increment overall_position - not a call argument
10701076
break
10711077

1078+
# Attach: receives the ATTACH options as a dict
1079+
if isinstance(meta, Attach):
1080+
if attach_param is not None:
1081+
raise TypeError(
1082+
f"{cls.__name__}.compute() has multiple Attach parameters: "
1083+
f"{attach_param!r} and {name!r}"
1084+
)
1085+
attach_param = name
1086+
# Don't increment overall_position - not a call argument
1087+
break
1088+
10721089
# Extract Setting/Secret params using shared helper
10731090
setting_params, secret_params = _extract_setting_secret_params(compute_method)
10741091

@@ -1079,6 +1096,7 @@ def __getattr__(self, name: str) -> Any:
10791096
cls._secret_params = secret_params
10801097
cls._output_length_param = output_length_param
10811098
cls._auth_param = auth_param
1099+
cls._attach_param = attach_param
10821100
cls._returns_output_type = returns_output_type
10831101

10841102
@final
@@ -1132,6 +1150,7 @@ def _extract_compute_kwargs(
11321150
batch: pa.RecordBatch,
11331151
bind_call: BindRequest,
11341152
auth_context: AuthContext,
1153+
attach_plaintext: bytes | None = None,
11351154
) -> dict[str, Any]:
11361155
"""Extract columns/values for `compute()` parameters.
11371156
@@ -1142,6 +1161,8 @@ def _extract_compute_kwargs(
11421161
batch: Input RecordBatch.
11431162
bind_call: The BindCall with arguments, settings, and secrets.
11441163
auth_context: Authentication context for the current request.
1164+
attach_plaintext: The worker-unwrapped attach (``uuid || options ||
1165+
catalog bytes``), for an ``Attach()`` parameter; None outside a catalog.
11451166
11461167
Returns:
11471168
Dict mapping parameter names to their resolved values.
@@ -1200,6 +1221,14 @@ def _extract_compute_kwargs(
12001221
if cls._auth_param is not None:
12011222
kwargs[cls._auth_param] = auth_context
12021223

1224+
# Attach param: the ATTACH options, read from the unwrapped attach exactly
1225+
# as BindParameters.attach_options reads them at bind.
1226+
if cls._attach_param is not None:
1227+
from vgi.catalog.attach_option import attach_options
1228+
from vgi.function_storage import attach_catalog_bytes
1229+
1230+
kwargs[cls._attach_param] = attach_options(attach_catalog_bytes(attach_plaintext))
1231+
12031232
return kwargs
12041233

12051234
@final
@@ -1333,7 +1362,12 @@ def process(
13331362
output_schema = init_call.output_schema
13341363

13351364
# Extract columns for keyword-only parameters
1336-
kwargs = cls._extract_compute_kwargs(batch, init_call.bind_call, auth_context)
1365+
kwargs = cls._extract_compute_kwargs(
1366+
batch,
1367+
init_call.bind_call,
1368+
auth_context,
1369+
getattr(storage, "_attach_plaintext", None),
1370+
)
13371371

13381372
# Validate input types match declared Param types
13391373
cls._validate_param_types(kwargs)

0 commit comments

Comments
 (0)