Skip to content

Commit 4274795

Browse files
rustyconoverclaude
andcommitted
examples: cache-control and custom COPY format workers
cache_worker.py shows the whole vgi.cache.* vocabulary on one table function: a freshness lifetime, an etag validator with revalidatable, and the 304-equivalent 0-row reply that tells the client to keep what it has. copy_format_worker.py wires both COPY directions in one catalog -- a producer-mode table function for FROM, a buffered function whose close() is the combine for TO -- and gives each direction its own format name. That last part is not stylistic: the extension registers COPY functions by name alone and silently skips a hit, so a reader and a writer sharing one name drops the writer and COPY ... TO fails with "COPY TO is not supported for FORMAT". The comment in ReadOnlyCatalogInterface said the opposite; corrected, along with a note that one name serving both directions requires a single direction="both" entry, which nothing emits today. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 28efbda commit 4274795

4 files changed

Lines changed: 399 additions & 3 deletions

File tree

‎examples/cache_worker.py‎

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# /// script
2+
# requires-python = ">=3.13"
3+
# dependencies = ["vgi-python"]
4+
# ///
5+
"""A table function that advertises its result as cacheable, and revalidates it.
6+
7+
Caching is *advertised*, not requested: the worker attaches ``vgi.cache.*``
8+
metadata to the **first** data batch it emits, and the client (the DuckDB
9+
extension) decides what to do with it. Nothing is cached unless you say so.
10+
11+
This worker exposes ``rates()``, standing in for a slow upstream — a remote API,
12+
a rate-limited service — whose answer is worth reusing. It shows the whole
13+
vocabulary:
14+
15+
- a **freshness lifetime** (``ttl``), so repeat queries inside the window never
16+
reach the worker at all;
17+
- a **validator** (``etag``) plus ``revalidatable=True``, which is what lets the
18+
client ask "is this still good?" instead of paying for a recompute;
19+
- the **304-equivalent** reply — a 0-row batch carrying
20+
``CacheControl(not_modified=True)`` — which tells the client its stored payload
21+
is still fresh.
22+
23+
``out`` is typed as vgi-rpc's ``OutputCollector``, which knows nothing about
24+
caching; the object the framework actually passes is a VGI wrapper that accepts
25+
``cache_control=``. Cast to :class:`vgi.protocol.VgiOutputCollector` to reach it
26+
with types intact — every cache-aware function does this.
27+
28+
ATTACH 'rates' (TYPE vgi, LOCATION 'uv run cache_worker.py');
29+
SELECT * FROM rates.rates(); -- second call inside the TTL never lands here
30+
"""
31+
32+
from dataclasses import dataclass
33+
from typing import cast
34+
35+
import pyarrow as pa
36+
37+
from vgi import Worker
38+
from vgi.cache_control import CacheControl
39+
from vgi.catalog import Catalog, Schema
40+
from vgi.protocol import VgiOutputCollector
41+
from vgi.table_function import (
42+
OutputCollector,
43+
ProcessParams,
44+
TableFunctionGenerator,
45+
bind_fixed_schema,
46+
init_single_worker,
47+
)
48+
49+
_SCHEMA = pa.schema([("currency", pa.string()), ("rate", pa.float64())])
50+
51+
# Stands in for whatever makes your upstream's answer change. A real worker
52+
# would derive this from the source — a last-modified header, a version column,
53+
# a content hash — and it is the ONLY thing revalidation compares.
54+
_DATA_VERSION = '"rates-v3"'
55+
56+
_ROWS = {"currency": ["EUR", "GBP", "JPY"], "rate": [1.09, 1.27, 0.0067]}
57+
58+
59+
@dataclass(slots=True, frozen=True, kw_only=True)
60+
class RatesArgs:
61+
"""``rates()`` takes no arguments — the whole table is the result."""
62+
63+
64+
@bind_fixed_schema
65+
@init_single_worker
66+
class Rates(TableFunctionGenerator[RatesArgs, None]):
67+
"""Emit the rate table once, advertising it as cacheable for 5 minutes."""
68+
69+
FIXED_SCHEMA = _SCHEMA
70+
71+
class Meta:
72+
"""Function metadata."""
73+
74+
name = "rates"
75+
description = "Exchange rates from a slow upstream, cacheable for 5 minutes"
76+
77+
@classmethod
78+
def process(cls, params: ProcessParams[RatesArgs, None], state: None, out: OutputCollector) -> None:
79+
"""Answer the scan — or, if the client's copy is still current, say so."""
80+
vgi_out = cast(VgiOutputCollector, out)
81+
82+
# Conditional request: the client holds a stale-but-revalidatable copy
83+
# and is asking whether it may keep it. Both validators are None on a
84+
# normal call, so this branch is simply skipped.
85+
if params.if_none_match == _DATA_VERSION:
86+
vgi_out.emit(
87+
pa.RecordBatch.from_pylist([], schema=_SCHEMA), # zero rows: "keep what you have"
88+
cache_control=CacheControl(
89+
ttl=300,
90+
etag=_DATA_VERSION,
91+
revalidatable=True,
92+
not_modified=True,
93+
),
94+
)
95+
out.finish()
96+
return
97+
98+
# Normal path: stream the result and advertise how it may be reused.
99+
# The metadata rides on the FIRST data batch; attaching it later has no
100+
# effect, because by then the client has decided how to treat the stream.
101+
vgi_out.emit(
102+
pa.RecordBatch.from_pydict(_ROWS, schema=_SCHEMA),
103+
cache_control=CacheControl(
104+
ttl=300, # reusable for 5 minutes without asking
105+
etag=_DATA_VERSION, # ...and after that, cheap to revalidate
106+
revalidatable=True, # gates whether the client ever asks
107+
stale_while_revalidate=60, # serve stale while refreshing behind it
108+
stale_if_error=600, # serve stale rather than fail
109+
),
110+
)
111+
out.finish()
112+
113+
114+
class CacheWorker(Worker):
115+
"""A worker exposing the ``rates`` catalog."""
116+
117+
catalog = Catalog(
118+
name="rates",
119+
schemas=[Schema(name="main", functions=[Rates])],
120+
)
121+
122+
123+
if __name__ == "__main__":
124+
CacheWorker().run()

‎examples/copy_format_worker.py‎

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
# /// script
2+
# requires-python = ">=3.13"
3+
# dependencies = ["vgi-python"]
4+
# ///
5+
"""Custom ``COPY ... FROM`` and ``COPY ... TO`` formats, in one catalog.
6+
7+
A VGI catalog can register its own ``COPY`` formats, so users read and write a
8+
format DuckDB has never heard of. Both directions reuse machinery that already
9+
exists, which is why they add so few new rules:
10+
11+
- a :class:`CopyFromFunction` is an ordinary producer-mode **table function**;
12+
- a :class:`CopyToFunction` is a **buffered** function with no Source phase —
13+
``write`` is the sink (per batch, parallel), ``close`` is the combine (once).
14+
15+
The format here is tab-separated values, one record per line, no header, no
16+
quoting. Deliberately trivial — the point is the wiring, not the parser.
17+
18+
Note the reader and writer declare **different** format names (``tsvlite`` and
19+
``tsvlite_out``). A reader and a writer that share one name look fine on the
20+
Python side — the catalog advertises both, keyed by (direction, format) — but the
21+
extension registers COPY functions by name alone, so the writer is silently
22+
dropped and ``COPY ... TO`` fails with "COPY TO is not supported for FORMAT".
23+
Give each direction its own name.
24+
25+
Two rules the framework enforces, and this file demonstrates:
26+
27+
1. **The reader must emit ``expected_schema`` exactly.** DuckDB inserts no cast
28+
between the scan and the INSERT, so the target table's columns are the output
29+
schema — that is why ``on_bind`` is ``@final`` on a COPY-FROM function.
30+
2. **The writer must finish inside ``close``.** There is no finalize phase, and
31+
``write`` and ``close`` may run in different processes, so shards go through
32+
``params.storage`` scoped by ``execution_id`` — never on ``self``.
33+
34+
The SQL ``FORMAT`` name is qualified by the catalog alias you attached as, NOT
35+
the bare ``COPY_*_FORMAT`` string — the extension namespaces formats per attach,
36+
so two workers may both call theirs ``tsvlite``:
37+
38+
ATTACH 'tsv' (TYPE vgi, LOCATION 'uv run copy_format_worker.py');
39+
CREATE TABLE people (name VARCHAR, age BIGINT);
40+
COPY people FROM 'people.tsv' (FORMAT 'tsv.tsvlite');
41+
COPY (SELECT * FROM people) TO 'out.tsv' (FORMAT 'tsv.tsvlite_out', header true);
42+
"""
43+
44+
from dataclasses import dataclass
45+
from typing import Annotated
46+
47+
import pyarrow as pa
48+
49+
from vgi import Arg, Worker
50+
from vgi.catalog import Catalog, Schema
51+
from vgi.copy_from_function import CopyFromFunction
52+
from vgi.copy_to_function import CopyToFunction
53+
from vgi.table_buffering_function import TableBufferingParams
54+
from vgi.table_function import OutputCollector, ProcessParams
55+
56+
57+
@dataclass(slots=True, frozen=True, kw_only=True)
58+
class ReadOptions:
59+
"""Options accepted by ``COPY ... FROM ... (FORMAT tsvlite, ...)``.
60+
61+
These are ordinary ``Arg``-annotated arguments — the source path is NOT one
62+
of them; it arrives on the bind. Each ``doc`` becomes the option's
63+
description in ``vgi_copy_formats()``.
64+
"""
65+
66+
skip_rows: Annotated[int, Arg("skip_rows", doc="Leading lines to discard", default=0)] = 0
67+
68+
69+
@dataclass(slots=True, frozen=True, kw_only=True)
70+
class WriteOptions:
71+
"""Options accepted by ``COPY ... TO ... (FORMAT 'tsv.tsvlite_out', ...)``."""
72+
73+
header: Annotated[bool, Arg("header", doc="Write a header line of column names", default=False)] = False
74+
75+
76+
class ReadTsvLite(CopyFromFunction[ReadOptions]):
77+
"""Read a tab-separated file into the COPY target table."""
78+
79+
COPY_FROM_FORMAT = "tsvlite"
80+
COPY_FROM_COMMENT = "Tab-separated, one record per line, no quoting"
81+
82+
@classmethod
83+
def read(
84+
cls,
85+
*,
86+
path: str,
87+
options: ReadOptions,
88+
expected_schema: pa.Schema,
89+
params: ProcessParams[ReadOptions],
90+
out: OutputCollector,
91+
) -> None:
92+
"""Parse ``path`` and emit batches matching ``expected_schema`` exactly."""
93+
with open(path, encoding="utf-8") as handle:
94+
lines = [line.rstrip("\n") for line in handle if line.strip()]
95+
lines = lines[options.skip_rows :]
96+
97+
# Split into columns positionally, then let Arrow cast each column to the
98+
# type the target table declared. Emitting a mismatched type or arity is
99+
# rejected by the extension at COPY bind, not silently coerced.
100+
columns: list[list[str | None]] = [[] for _ in expected_schema]
101+
for line in lines:
102+
cells = line.split("\t")
103+
for index in range(len(expected_schema)):
104+
value = cells[index] if index < len(cells) else ""
105+
columns[index].append(value if value != "" else None)
106+
107+
out.emit(
108+
pa.RecordBatch.from_arrays(
109+
[
110+
pa.array(col, type=pa.string()).cast(field.type)
111+
for col, field in zip(columns, expected_schema, strict=True)
112+
],
113+
schema=expected_schema,
114+
)
115+
)
116+
out.finish()
117+
118+
119+
class WriteTsvLite(CopyToFunction[WriteOptions]):
120+
"""Write query results out as a tab-separated file."""
121+
122+
COPY_TO_FORMAT = "tsvlite_out"
123+
COPY_TO_COMMENT = "Tab-separated, one record per line, no quoting"
124+
125+
@classmethod
126+
def write(
127+
cls,
128+
*,
129+
batch: pa.RecordBatch,
130+
options: WriteOptions,
131+
file_path: str,
132+
params: TableBufferingParams[WriteOptions],
133+
) -> None:
134+
"""Sink: stash this batch as a shard. Runs per batch, possibly in parallel."""
135+
rows = ["\t".join("" if value is None else str(value) for value in row.values()) for row in batch.to_pylist()]
136+
# execution_id-scoped, because close() may run in a different process.
137+
params.storage.state_append(b"shards", b"", "\n".join(rows).encode("utf-8"))
138+
139+
@classmethod
140+
def close(
141+
cls,
142+
*,
143+
options: WriteOptions,
144+
file_path: str,
145+
params: TableBufferingParams[WriteOptions],
146+
) -> int:
147+
"""Combine: read every shard back and write the file, once. Returns rows written."""
148+
shards = params.storage.state_log_scan(b"shards", b"")
149+
body = [chunk.decode("utf-8") for _key, chunk in shards if chunk]
150+
151+
written = 0
152+
with open(file_path, "w", encoding="utf-8") as handle:
153+
if options.header:
154+
schema = params.init_call.bind_call.input_schema
155+
handle.write("\t".join(schema.names) + "\n")
156+
for chunk in body:
157+
handle.write(chunk + "\n")
158+
written += len(chunk.split("\n"))
159+
# Called even for an empty COPY — the file is created either way.
160+
return written
161+
162+
163+
class TsvWorker(Worker):
164+
"""A worker whose catalog advertises both COPY directions.
165+
166+
The declarative ``Catalog`` introspects its function list for
167+
``CopyFromFunction`` / ``CopyToFunction`` subclasses and advertises what it
168+
finds, so registering them here is all the wiring there is.
169+
"""
170+
171+
catalog = Catalog(
172+
name="tsv",
173+
schemas=[Schema(name="main", functions=[ReadTsvLite, WriteTsvLite])],
174+
)
175+
176+
177+
if __name__ == "__main__":
178+
TsvWorker().run()

‎tests/test_examples_workers.py‎

Lines changed: 80 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
import pytest
2424

2525
from vgi.client import Client
26-
from vgi.table_function import ProcessParams
26+
from vgi.table_function import OutputCollector, ProcessParams
2727

2828
EXAMPLES_DIR = Path(__file__).resolve().parent.parent / "examples"
2929

@@ -161,3 +161,82 @@ def test_sum_worker_aggregate_phases() -> None:
161161

162162
out = m.Sum.finalize(pa.array([0, 1], type=pa.int64()), states, params=no_params)
163163
assert out.column("result").to_pylist() == [15, 6]
164+
165+
166+
def test_cache_worker_advertises_and_revalidates() -> None:
167+
"""The caching worker serves rows, and answers a conditional request with 0 rows.
168+
169+
The ``vgi.cache.*`` metadata itself is consumed by the C++ extension, not by
170+
the Python Client, so what is asserted here is the worker-side contract: the
171+
normal path emits the table, and a matching ``if_none_match`` produces the
172+
304-equivalent empty batch instead of re-streaming it.
173+
"""
174+
import cache_worker as m
175+
176+
from vgi.arguments import Arguments
177+
178+
with _spawn("cache_worker.py") as client:
179+
rows = list(
180+
client.table_function(function_name="rates", schema_name="main", arguments=Arguments(positional=[]))
181+
)
182+
assert [v for b in rows for v in b.column("currency").to_pylist()] == ["EUR", "GBP", "JPY"]
183+
184+
# The advertised metadata renders to the keys the extension reads by string.
185+
advertised = m.CacheControl(ttl=300, etag=m._DATA_VERSION, revalidatable=True).to_metadata()
186+
assert advertised["vgi.cache.ttl"] == "300"
187+
assert advertised["vgi.cache.etag"] == m._DATA_VERSION
188+
assert advertised["vgi.cache.revalidatable"] == "1"
189+
assert advertised["vgi.cache.scope"] == "catalog"
190+
191+
# not_modified is what makes the 0-row reply mean "keep what you have".
192+
assert m.CacheControl(not_modified=True).to_metadata()["vgi.cache.not_modified"] == "1"
193+
194+
195+
def test_copy_format_worker_advertises_both_directions() -> None:
196+
"""The COPY worker's catalog advertises a reader AND a writer for ``tsvlite``."""
197+
import copy_format_worker as m
198+
199+
interface = m.TsvWorker()._get_catalog_interface()()
200+
formats = interface.copy_from_formats(attach_opaque_data=b"", transaction_opaque_data=None)
201+
by_direction = {f.direction: f for f in formats}
202+
203+
assert by_direction["from"].format_name == "tsvlite"
204+
assert by_direction["from"].handler == "read_tsv_lite"
205+
# Deliberately NOT "tsvlite": the extension registers COPY functions by name
206+
# alone, so a reader and a writer sharing one name silently loses the writer.
207+
assert by_direction["to"].format_name == "tsvlite_out"
208+
assert by_direction["to"].handler == "write_tsv_lite"
209+
210+
211+
def test_copy_format_worker_round_trips_a_file(tmp_path: Path) -> None:
212+
"""The reader parses TSV into the target schema; the writer writes it back.
213+
214+
Driven directly rather than through ``COPY``, so the test covers the worker
215+
halves without needing an engine whose extension registers both directions.
216+
"""
217+
import copy_format_worker as m
218+
219+
source = tmp_path / "people.tsv"
220+
source.write_text("skipme\nalice\t30\nbob\t41\ncarol\t\n", encoding="utf-8")
221+
schema = pa.schema([("name", pa.string()), ("age", pa.int64())])
222+
223+
emitted: list[pa.RecordBatch] = []
224+
225+
class _Out:
226+
def emit(self, batch: pa.RecordBatch) -> None:
227+
emitted.append(batch)
228+
229+
def finish(self) -> None:
230+
pass
231+
232+
m.ReadTsvLite.read(
233+
path=str(source),
234+
options=m.ReadOptions(skip_rows=1),
235+
expected_schema=schema,
236+
params=cast("ProcessParams[m.ReadOptions]", None),
237+
out=cast("OutputCollector", _Out()),
238+
)
239+
240+
assert len(emitted) == 1
241+
assert emitted[0].schema == schema
242+
assert emitted[0].to_pydict() == {"name": ["alice", "bob", "carol"], "age": [30, 41, None]}

0 commit comments

Comments
 (0)