Skip to content

Commit 48b69d2

Browse files
rustyconoverclaude
andcommitted
client: drive aggregate and COPY functions
The Python Client wrapped bind/init and the buffered RPCs, but nothing else: all 12 aggregate RPCs and catalog_copy_from_formats were recorded as NotExposed in the protocol inventory, so no Python test could reach them. Close the gap against the C++ extension as the reference. Aggregates (vgi/client/aggregate.py) mirror the drive loop in vgi_aggregate_function_impl.cpp across three surfaces: * aggregate_function() keys groups client-side in first-seen order (DuckDB's order), pumps batches through aggregate_update, finalizes in chunks, and returns group keys + results as one RecordBatch. * aggregate_session() is the raw surface with caller-allocated group ids -- update/combine/finalize/destroy plus the window RPCs -- and destroys the execution on exit, including on exception. * aggregate_streaming() drives the streaming-partitioned open/chunk/close protocol, resolving output_schema with a probe bind exactly as the extension does. Wire shapes match C++: __vgi_group_id prepended as column 0, the (source_group_id, target_group_id) merge batch, the one-column group_id batch, and the packed filter_mask / frame_stats / all_valid window encodings. COPY reuses the existing drivers rather than adding new ones, as it does on the C++ side: copy_from() is table_function plus a CopyFromContext, copy_to() is table_buffering_function plus a CopyToContext with no Source phase, and copy_formats() is the discovery step that turns a FORMAT name into the handler to invoke. table_buffering_function gains an input_schema override so an empty COPY still binds with the source schema -- the header-row case, which peeking the first batch cannot serve. ClientError moves to vgi/client/errors.py so the driver modules can raise it without importing the module that imports them; vgi.client.client re-exports it, so existing imports are unchanged. 157 new tests run against the real fixture worker over all three transports. One is pinned to subprocess: reaching the "not a COPY-TO writer" guard means running the buffered Source phase, which HttpStreamSession does not implement -- a pre-existing gap unrelated to COPY, since a CopyToFunction returns no finalize keys. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 1c84c2e commit 48b69d2

12 files changed

Lines changed: 2074 additions & 136 deletions

‎docs/aggregate-functions.md‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,50 @@ worker = Worker(
333333

334334
The framework automatically detects `AggregateFunction` subclasses and registers them with the correct function type in the catalog.
335335

336+
## Invoking From Python
337+
338+
Real users reach aggregates through DuckDB, which drives the all-unary aggregate RPCs from its hash-aggregate operator. Non-DuckDB callers drive the same protocol through `Client`.
339+
340+
`aggregate_function()` is the convenience shape — it keys the groups client-side, pumps every batch through `update`, and finalizes in chunks:
341+
342+
```python test="skip"
343+
import pyarrow as pa
344+
345+
from vgi.client import Client
346+
347+
batch = pa.RecordBatch.from_pydict({"cat": ["a", "b", "a"], "value": [1, 10, 2]})
348+
349+
with Client("vgi-fixture-worker") as client:
350+
result = client.aggregate_function(
351+
function_name="vgi_sum",
352+
schema_name="main",
353+
input=[batch],
354+
group_by=["cat"],
355+
)
356+
# {'cat': ['a', 'b'], 'result': [3, 10]}
357+
```
358+
359+
Every input column not named in `group_by` is passed to the aggregate as a value column, in batch order — so order the columns to match the declared `Param`s. Omitting `group_by` gives the global-aggregate shape (`SELECT vgi_sum(x) FROM t`), which returns one row even for empty input.
360+
361+
For the raw protocol — caller-allocated group ids, `combine`, and the optional window RPCs — use `aggregate_session()`:
362+
363+
```python test="skip"
364+
with Client("vgi-fixture-worker") as client:
365+
with client.aggregate_session(
366+
function_name="vgi_sum",
367+
schema_name="main",
368+
input_schema=pa.schema([pa.field("value", pa.int64())]),
369+
) as session:
370+
session.update(
371+
group_ids=[0, 0, 1],
372+
batch=pa.RecordBatch.from_pydict({"value": [1, 2, 100]}),
373+
)
374+
session.combine(source_group_ids=[1], target_group_ids=[0])
375+
session.finalize([0, 1]) # -> {'result': [103, 100]}
376+
```
377+
378+
The session is destroyed on exit, so worker-side group state never outlives the `with` block. Window-capable aggregates add `window_init()` / `window()` / `window_batch()` / `window_destroy()` on the same session; streaming-partitioned aggregates use `client.aggregate_streaming(...)` instead (see below).
379+
336380
## Streaming-Partitioned Variant
337381

338382
For `OVER (PARTITION BY ... ORDER BY ...)` queries against unbounded inputs (e.g. running aggregates across years of trade history), the standard windowed path materializes each partition in DuckDB memory before the aggregate sees it — fine for bounded data, OOMs at scale.
@@ -386,6 +430,28 @@ class MyRunningAgg(AggregateFunction[MyState]):
386430

387431
Queries that don't satisfy all of these fall back to the standard windowed path automatically. The streaming path is opt-in and additive — it does not replace `update`/`combine`/`finalize`, which still service `GROUP BY` queries normally.
388432

433+
From Python, `Client.aggregate_streaming()` opens the session and closes it on exit. The chunk schema is positional: partition keys first, then order keys, then value columns.
434+
435+
```python test="skip"
436+
schema = pa.schema(
437+
[pa.field("k", pa.string()), pa.field("ts", pa.int64()), pa.field("v", pa.int64())]
438+
)
439+
440+
with Client("vgi-fixture-worker") as client:
441+
with client.aggregate_streaming(
442+
function_name="vgi_streaming_sum",
443+
schema_name="main",
444+
input_schema=schema,
445+
partition_key_count=1,
446+
order_key_count=1,
447+
) as session:
448+
chunk = pa.RecordBatch.from_pydict(
449+
{"k": ["a", "b", "a", "b"], "ts": [1, 1, 2, 2], "v": [1, 10, 2, 20]},
450+
schema=schema,
451+
)
452+
session.chunk(chunk) # -> {'result': [1, 10, 3, 30]}
453+
```
454+
389455
**When pre-aggregation is the better answer.** For most analytics shapes — "EOD positions per book per day, carrying forward across days" — pre-aggregating the input is the cleanest pattern in plain SQL:
390456

391457
```sql

0 commit comments

Comments
 (0)