|
1 | | -# VGI Protocol Flow |
| 1 | +# VGI Protocol Specification |
2 | 2 |
|
3 | | -This document describes the Arrow IPC protocol between client and worker. |
| 3 | +This document describes the Arrow IPC streaming protocol between VGI clients and worker processes. |
4 | 4 |
|
5 | | -## Scalar Function (row transform) |
| 5 | +## Protocol Summary |
| 6 | + |
| 7 | +VGI uses Apache Arrow IPC streaming over stdin/stdout for communication: |
| 8 | + |
| 9 | +| Direction | Format | Description | |
| 10 | +|-----------|--------|-------------| |
| 11 | +| Client → Worker | Arrow IPC | Invocation, then input batches (if any) | |
| 12 | +| Worker → Client | Arrow IPC | OutputSpec, then output batches with status metadata | |
| 13 | + |
| 14 | +**Key concepts:** |
| 15 | +- All messages are Arrow RecordBatches serialized to IPC streaming format |
| 16 | +- Status is communicated via custom metadata on output batches |
| 17 | +- Three function types: Scalar (1:1 transform), Table (generator), Table-In-Out (transform with finalize) |
| 18 | + |
| 19 | +--- |
| 20 | + |
| 21 | +## Function Types Overview |
| 22 | + |
| 23 | +| Type | Base Class | Input | Output | Use Case | |
| 24 | +|------|------------|-------|--------|----------| |
| 25 | +| **Scalar** | `ScalarFunction` | Batches | Single column, same row count | `upper()`, `abs()`, per-row transforms | |
| 26 | +| **Table** | `TableFunctionGenerator` | None | Multi-column batches | `range()`, `read_csv()`, data generation | |
| 27 | +| **Table-In-Out** | `TableInOutFunction` | Batches | Multi-column batches | Filtering, aggregation, enrichment | |
| 28 | + |
| 29 | +--- |
| 30 | + |
| 31 | +## Message Flow Diagrams |
| 32 | + |
| 33 | +### Scalar Function Protocol |
6 | 34 |
|
7 | 35 | Scalar functions transform input batches to single-column output with 1:1 row mapping. |
8 | | -They are used for per-row computations like `upper()`, `abs()`, or `concat()`. |
9 | 36 |
|
10 | 37 | ``` |
11 | 38 | Client Worker |
12 | 39 | │ │ |
13 | | - │──── Invocation (function, args) ─────▶│ |
14 | | - │ │ instantiate function |
15 | | - │◀──── OutputSpec (output schema) ──────│ (single column) |
| 40 | + │──── Invocation ───────────────────▶ │ deserialize, lookup function |
16 | 41 | │ │ |
17 | | - │──── Input Batch 1 ───────────────────▶│ |
18 | | - │◀──── Output Batch 1 ─────────────────│ compute() / process() |
19 | | - │ │ (same row count) |
20 | | - │──── Input Batch 2 ───────────────────▶│ |
21 | | - │◀──── Output Batch 2 ─────────────────│ |
| 42 | + │◀──── OutputSpec ────────────────── │ single-column schema |
22 | 43 | │ │ |
23 | | - │──── (generator closed) ──────────────▶│ |
24 | | - │ │ teardown() |
| 44 | + │──── Input Batch 1 ────────────────▶ │ |
| 45 | + │◀──── Output Batch 1 ────────────── │ compute() → Array (same row count) |
| 46 | + │ │ |
| 47 | + │──── Input Batch N ────────────────▶ │ |
| 48 | + │◀──── Output Batch N ────────────── │ |
| 49 | + │ │ |
| 50 | + │──── (close generator) ────────────▶ │ teardown() |
| 51 | + └───────────────────────────────────────┘ |
25 | 52 | ``` |
26 | 53 |
|
27 | | -**Key differences from Table-In-Out:** |
28 | | -- Output schema must have exactly one column |
29 | | -- Output row count must equal input row count (1:1 mapping) |
30 | | -- No finalize phase - processing ends when input stream ends |
31 | | -- No `NEED_MORE_INPUT` status (always expects more input until closed) |
| 54 | +**Constraints:** |
| 55 | +- Output schema: exactly 1 column named "result" |
| 56 | +- Output row count = input row count (enforced by framework) |
| 57 | +- No finalize phase |
| 58 | +- No `NEED_MORE_INPUT` status (implicit: always ready) |
32 | 59 |
|
33 | | -## Table Function (no input) |
| 60 | +### Table Function Protocol |
34 | 61 |
|
35 | 62 | Table functions generate data without receiving input batches. |
36 | 63 |
|
37 | 64 | ``` |
38 | 65 | Client Worker |
39 | 66 | │ │ |
40 | | - │──── Invocation (function, args) ─────▶│ |
41 | | - │ │ instantiate function |
42 | | - │◀──── OutputSpec (output schema) ──────│ |
| 67 | + │──── Invocation ───────────────────▶ │ deserialize, lookup function |
43 | 68 | │ │ |
44 | | - │──── GlobalStateInitInput ────────────▶│ |
45 | | - │◀──── InitResult ────────────────│ initialize_global_state() |
| 69 | + │◀──── OutputSpec ────────────────── │ output schema + cardinality |
46 | 70 | │ │ |
47 | | - │◀──── Output Batch 1 ──────────────────│ process() yields |
48 | | - │◀──── Output Batch 2 ──────────────────│ |
49 | | - │◀──── ... ─────────────────────────────│ |
50 | | - │◀──── Final Output (FINISHED) ─────────│ |
| 71 | + │──── GlobalStateInitInput ─────────▶ │ (empty batch with projection info) |
| 72 | + │◀──── InitResult ────────────────── │ initialize_global_state() |
51 | 73 | │ │ |
| 74 | + │◀──── Output Batch 1 ────────────── │ process() yields Output(batch) |
| 75 | + │◀──── Output Batch 2 ────────────── │ |
| 76 | + │◀──── ... ───────────────────────── │ |
| 77 | + │◀──── Output (FINISHED) ─────────── │ generator exhausted |
| 78 | + │ │ teardown() |
| 79 | + └───────────────────────────────────────┘ |
52 | 80 | ``` |
53 | 81 |
|
54 | | -## Table-In-Out Function (with input) |
| 82 | +### Table-In-Out Function Protocol |
55 | 83 |
|
56 | | -Table-in-out functions transform input batches to output batches. |
| 84 | +Table-in-out functions transform input batches with an optional finalize phase. |
57 | 85 |
|
58 | 86 | ``` |
59 | 87 | Client Worker |
60 | 88 | │ │ |
61 | | - │──── Invocation (function, args) ─────▶│ |
62 | | - │ │ instantiate function |
63 | | - │◀──── OutputSpec (output schema) ──────│ |
| 89 | + │──── Invocation ───────────────────▶ │ deserialize, lookup function |
64 | 90 | │ │ |
65 | | - │──── GlobalStateInitInput ────────────▶│ |
66 | | - │◀──── InitResult ────────────────│ initialize_global_state() |
| 91 | + │◀──── OutputSpec ────────────────── │ output schema |
67 | 92 | │ │ |
68 | | - │──── Input Batch 1 ───────────────────▶│ |
69 | | - │◀──── Output Batch 1 (NEED_MORE_INPUT)─│ transform() / process() |
| 93 | + │──── GlobalStateInitInput ─────────▶ │ (empty batch with projection) |
| 94 | + │◀──── InitResult ────────────────── │ initialize_global_state() |
70 | 95 | │ │ |
71 | | - │──── Input Batch 2 ───────────────────▶│ |
72 | | - │◀──── Output Batch 2 (NEED_MORE_INPUT)─│ |
| 96 | + │──── Input Batch 1 ────────────────▶ │ |
| 97 | + │◀──── Output (NEED_MORE_INPUT) ──── │ transform() → batch |
73 | 98 | │ │ |
74 | | - │──── FINALIZE (empty batch) ──────────▶│ |
75 | | - │◀──── Final Output (FINISHED) ─────────│ finish() / finalize() |
| 99 | + │──── Input Batch N ────────────────▶ │ |
| 100 | + │◀──── Output (NEED_MORE_INPUT) ──── │ |
76 | 101 | │ │ |
| 102 | + │──── FINALIZE (empty batch) ───────▶ │ signals end of input |
| 103 | + │◀──── Output Batch ──────────────── │ finish() → final batches |
| 104 | + │◀──── Output (FINISHED) ─────────── │ |
| 105 | + │ │ teardown() |
| 106 | + └───────────────────────────────────────┘ |
| 107 | +``` |
| 108 | + |
| 109 | +--- |
| 110 | + |
| 111 | +## Status Values |
| 112 | + |
| 113 | +Output batches include a status string in Arrow IPC custom metadata: |
| 114 | + |
| 115 | +| Status | Meaning | Next Action | |
| 116 | +|--------|---------|-------------| |
| 117 | +| `NEED_MORE_INPUT` | Ready for next input batch | Client sends next batch | |
| 118 | +| `HAVE_MORE_OUTPUT` | More output available | Client calls send() again | |
| 119 | +| `FINISHED` | Processing complete | Client closes connection | |
| 120 | + |
| 121 | +**Status metadata key:** `vgi.status` in batch metadata |
| 122 | + |
| 123 | +--- |
| 124 | + |
| 125 | +## Message Formats |
| 126 | + |
| 127 | +### Invocation (Client → Worker) |
| 128 | + |
| 129 | +First message sent when invoking a function. Serialized as Arrow RecordBatch with single row. |
| 130 | + |
| 131 | +| Field | Arrow Type | Description | |
| 132 | +|-------|------------|-------------| |
| 133 | +| `function_name` | `string` | Function name in worker registry | |
| 134 | +| `arguments` | `struct` | Positional and named arguments | |
| 135 | +| `input_schema` | `binary` | Arrow IPC serialized schema (nullable) | |
| 136 | +| `function_type` | `string` | `"SCALAR"` or `"TABLE"` | |
| 137 | +| `invocation_id` | `binary` | Unique ID for this invocation (nullable) | |
| 138 | +| `correlation_id` | `string` | Request tracing/logging ID | |
| 139 | +| `global_execution_identifier` | `binary` | Shared state ID for parallel workers (nullable) | |
| 140 | +| `client_features` | `list<string>` | Client capability flags | |
| 141 | +| `attach_id` | `binary` | DuckDB attachment identifier (nullable) | |
| 142 | +| `settings` | `map<string, string>` | DuckDB settings/pragmas (nullable) | |
| 143 | + |
| 144 | +**Arguments struct:** |
| 145 | +``` |
| 146 | +arguments: { |
| 147 | + positional: list<dense_union<...Arrow scalar types...>>, |
| 148 | + named: map<string, dense_union<...Arrow scalar types...>> |
| 149 | +} |
| 150 | +``` |
| 151 | + |
| 152 | +### OutputSpec (Worker → Client) |
| 153 | + |
| 154 | +Response to Invocation, describing output schema and execution hints. |
| 155 | + |
| 156 | +| Field | Arrow Type | Description | |
| 157 | +|-------|------------|-------------| |
| 158 | +| `output_schema` | `binary` | Arrow IPC serialized output schema | |
| 159 | +| `cardinality` | `struct` | Row count estimates (table functions) | |
| 160 | +| `max_processes` | `int32` | Max parallel workers allowed (nullable) | |
| 161 | +| `requires_finalize` | `bool` | Whether finalize phase is needed | |
| 162 | +| `stability` | `string` | Output determinism hint | |
| 163 | + |
| 164 | +**Cardinality struct:** |
| 165 | +``` |
| 166 | +cardinality: { |
| 167 | + estimate: int64 (nullable), |
| 168 | + min: int64 (nullable), |
| 169 | + max: int64 (nullable) |
| 170 | +} |
77 | 171 | ``` |
78 | 172 |
|
79 | | -## Status Values (in IPC metadata) |
| 173 | +### GlobalStateInitInput (Client → Worker) |
| 174 | + |
| 175 | +Sent after OutputSpec to initialize global state (table/table-in-out functions). |
| 176 | + |
| 177 | +| Field | Arrow Type | Description | |
| 178 | +|-------|------------|-------------| |
| 179 | +| `projected_columns` | `list<string>` | Requested output columns (nullable) | |
| 180 | + |
| 181 | +### InitResult (Worker → Client) |
| 182 | + |
| 183 | +Response to GlobalStateInitInput. |
| 184 | + |
| 185 | +| Field | Arrow Type | Description | |
| 186 | +|-------|------------|-------------| |
| 187 | +| `global_execution_identifier` | `binary` | Identifier for shared state (nullable) | |
| 188 | + |
| 189 | +### Data Batches |
| 190 | + |
| 191 | +Input and output data are standard Arrow RecordBatches matching the declared schemas. |
| 192 | + |
| 193 | +**Output batch metadata includes:** |
| 194 | +- `vgi.status`: One of `NEED_MORE_INPUT`, `HAVE_MORE_OUTPUT`, `FINISHED` |
| 195 | +- `vgi.log_level`: Log level if log message present (optional) |
| 196 | +- `vgi.log_message`: Log message text (optional) |
| 197 | + |
| 198 | +--- |
| 199 | + |
| 200 | +## Error Handling |
| 201 | + |
| 202 | +Errors are communicated via log messages with level `EXCEPTION`: |
| 203 | + |
| 204 | +``` |
| 205 | +Output batch metadata: |
| 206 | + vgi.status: "FINISHED" |
| 207 | + vgi.log_level: "EXCEPTION" |
| 208 | + vgi.log_message: "Error message with stack trace" |
| 209 | +``` |
80 | 210 |
|
81 | | -| Status | Meaning | |
82 | | -|--------|---------| |
83 | | -| `NEED_MORE_INPUT` | Ready for next input batch | |
84 | | -| `HAVE_MORE_OUTPUT` | Call send() again for more output | |
85 | | -| `FINISHED` | Processing complete | |
| 211 | +**Error categories:** |
| 212 | +- **Function not found:** Unknown function name in registry |
| 213 | +- **Argument mismatch:** Wrong number or type of arguments |
| 214 | +- **Schema mismatch:** Output doesn't match declared schema |
| 215 | +- **Row count mismatch:** Scalar function output row count ≠ input |
| 216 | +- **Runtime errors:** Exceptions during transform/compute |
86 | 217 |
|
87 | | -## Invocation Fields |
| 218 | +--- |
88 | 219 |
|
89 | | -The Invocation message contains the following fields: |
| 220 | +## Parallel Execution |
90 | 221 |
|
91 | | -| Field | Type | Description | |
92 | | -|-------|------|-------------| |
93 | | -| `function_name` | string | Name of the function to invoke | |
94 | | -| `arguments` | struct | Positional and named arguments | |
95 | | -| `input_schema` | binary | Arrow IPC serialized schema (nullable) | |
96 | | -| `function_type` | string | `SCALAR` or `TABLE` | |
97 | | -| `invocation_id` | binary | Unique ID for this binding (nullable) | |
98 | | -| `correlation_id` | string | For request tracing/logging | |
99 | | -| `global_execution_identifier` | binary | Shared state ID for parallel workers | |
100 | | -| `client_features` | list\<string\> | Feature flags from client | |
101 | | -| `attach_id` | binary | DuckDB attachment identifier (nullable) | |
102 | | -| `settings` | map\<string, string\> | settings/pragmas (nullable) | |
| 222 | +When `max_workers > 1`, the client may spawn multiple worker processes: |
| 223 | + |
| 224 | +**Primary Worker:** |
| 225 | +1. Receives `global_execution_identifier = None` in Invocation |
| 226 | +2. Runs `initialize_global_state()` → returns InitResult with new identifier |
| 227 | +3. Runs `finalize()` after all workers complete |
| 228 | + |
| 229 | +**Secondary Workers:** |
| 230 | +1. Receive `global_execution_identifier` from primary's InitResult |
| 231 | +2. Run `load_global_state()` with the identifier |
| 232 | +3. Do NOT run `finalize()` |
| 233 | + |
| 234 | +**State synchronization:** |
| 235 | +- Workers use `save_state()` to persist partial results |
| 236 | +- Primary uses `load_states()` to collect all worker states before finalize |
| 237 | +- State storage: SQLite database at platform-specific cache directory |
| 238 | + |
| 239 | +--- |
103 | 240 |
|
104 | 241 | ## DuckDB Settings |
105 | 242 |
|
106 | | -Functions can declare required settings via `Meta.required_settings`. These |
107 | | -settings are passed from client to worker in the Invocation during the bind phase. |
| 243 | +Functions can declare required settings in `Meta.required_settings`: |
108 | 244 |
|
109 | 245 | ```python |
110 | 246 | class MyFunction(TableFunctionGenerator): |
111 | 247 | class Meta: |
112 | 248 | required_settings = ["TimeZone", "threads"] |
113 | | - |
114 | | - @property |
115 | | - def output_schema(self) -> pa.Schema: |
116 | | - # Settings available during bind |
117 | | - tz = self.get_setting("TimeZone", "UTC") |
118 | | - return pa.schema([("timestamp", pa.timestamp("us", tz=tz))]) |
119 | 249 | ``` |
120 | 250 |
|
121 | | -The worker validates that all required settings are present before instantiating |
122 | | -the function. Missing settings result in an error. |
| 251 | +Settings are passed in the Invocation and available during bind: |
| 252 | +- Access via `self.settings` dict or `self.get_setting(name, default)` |
| 253 | +- Available before `output_schema` property is accessed |
| 254 | +- Missing required settings cause invocation to fail |
| 255 | + |
| 256 | +--- |
| 257 | + |
| 258 | +## Wire Format Details |
| 259 | + |
| 260 | +**Serialization:** Apache Arrow IPC streaming format |
| 261 | +- Each message is a complete IPC stream (schema + batch) |
| 262 | +- Uses `pa.ipc.new_stream()` / `pa.ipc.RecordBatchStreamReader` |
| 263 | + |
| 264 | +**Transport:** stdin/stdout of worker subprocess |
| 265 | +- Client writes to worker's stdin |
| 266 | +- Client reads from worker's stdout |
| 267 | +- Worker stderr is captured for diagnostics |
| 268 | + |
| 269 | +**Byte order:** Native endianness (Arrow handles cross-platform) |
| 270 | + |
| 271 | +--- |
| 272 | + |
| 273 | +## Implementation Notes |
| 274 | + |
| 275 | +**Framework guarantees:** |
| 276 | +- `teardown()` always called, even on exceptions |
| 277 | +- Schema validation before sending to client |
| 278 | +- Row count validation for scalar functions |
| 279 | +- Automatic error wrapping with stack traces |
| 280 | + |
| 281 | +**Client responsibilities:** |
| 282 | +- Spawn worker subprocess with correct command |
| 283 | +- Send Invocation as first message |
| 284 | +- Handle all status values correctly |
| 285 | +- Close connection gracefully |
| 286 | + |
| 287 | +**Worker responsibilities:** |
| 288 | +- Parse Invocation and lookup function |
| 289 | +- Validate arguments against function signature |
| 290 | +- Send OutputSpec with correct schema |
| 291 | +- Handle GeneratorExit for cleanup |
0 commit comments