Skip to content

Commit 70799ca

Browse files
EC2 Default Userclaude
andcommitted
Writable catalog tables, transaction hooks, attach options in functions
Porting a Hue worker (an UPDATE-able table whose changes are staged in DuckDB transactions) needed a dynamic proxy around VgiServiceImpl. Every gap is now public API: - CatalogTable.Builder insertFunction/updateFunction/deleteFunction and writeResultMode: TableInfo advertises write_result_modes and the inline write functions, and catalog_table_{insert,update,delete}_function_get answer (they were UNIMPLEMENTED). farm.query.vgi.write: WriteOptions, WriteResultMode, WriteResults (rowIdField, resultSchema, result batches). - A writable constrained table negotiates vgi.constraint.enforce.v1 automatically (TS catalogWriteProfiles), and a provider advertising enforce without records-read no longer loses it in the merge. - Worker.onAttach(AttachHook) -> AttachSettings: per-attach supports_transactions / supports_time_travel (worker-wide defaults Worker.supportsTransactions / supportsTimeTravel, still true). - Worker.transactionHooks(TransactionHooks): begin mints the plaintext id, commit (throw to fail COMMIT) and rollback receive the same bytes on every transport; CatalogInterface gets the same hooks for hosted catalogs. - Table and table in-out bind/init params carry transactionId() and attachOptions() (secret options included); TableInOutInitParams also attachId() and bindOpaqueData(). - Secret ATTACH options are encrypted into attach_opaque_data (never plaintext): configured signing key, else the HTTP sealing key, else a per-user host key file shared by pooled / stdio worker processes. - The main catalog's resolved data version travels in the attach envelope, so a process that never served the ATTACH recovers it. - FunctionMetadata.withStability, Schemas.serialize; TransactionStorage javadoc corrected (autocommit statements on a transactional attach have a transaction). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 24cafd7 commit 70799ca

33 files changed

Lines changed: 2832 additions & 96 deletions

‎CLAUDE.md‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,34 @@ with several replies:
346346
`vgi-example-worker/.../tableinout/PagedStateTest`. Unit: `internal/ContinuedOutputTest`;
347347
pipe + HTTP round trips: `client/ContinuedOutputTransportTest`.
348348

349+
## Writable tables, transaction hooks, attach options (2026-11-08, 0.46.3)
350+
351+
Found porting a Hue worker (an UPDATE-able `lights` table staged in DuckDB transactions); the
352+
contract is vgi `docs/writable_tx_fixtures.md`, served by `example/txfix/TxFixWorker`
353+
(`ci/wrappers/vgi-worker-txfix`, `VGI_WRITABLE_TX_FIXTURES` / `VGI_WRITABLE_TX_WORKER` on every
354+
lane). User docs: `docs/writable-tables-and-transactions.md`.
355+
356+
- `CatalogTable.Builder#insertFunction/updateFunction/deleteFunction/writeResultMode`;
357+
`toTableInfo` inlines them and `catalog_table_{insert,update,delete}_function_get` answer
358+
(resolved over the catalog's table in-out functions). `farm.query.vgi.write` holds
359+
`WriteOptions` / `WriteResults` (TS `write-results.ts` port).
360+
- `ConstraintContract.profilesFor` adds `vgi.constraint.enforce.v1` for a writable constrained
361+
table; `merge` re-selects over the whole advertisement, so a provider advertising enforce
362+
without records-read is no longer dropped by `CatalogProfiles.select`.
363+
- `Worker.onAttach(AttachHook)` -> `AttachSettings` (per-attach `supports_transactions` /
364+
`supports_time_travel`; worker-wide defaults stay `true`). `Worker.transactionHooks` runs at
365+
begin/commit/rollback with the PLAINTEXT id (begin mints it; sealed on HTTP by the framework);
366+
commit throwing fails COMMIT. `CatalogInterface` has the same four hooks for hosted catalogs.
367+
- Functions get `transactionId()` and `attachOptions()` on Table{Bind,Init}Params and
368+
TableInOut{Bind,Init}Params; TableInOutInitParams also `attachId()` / `bindOpaqueData()`.
369+
- Secret ATTACH options are ChaCha20-Poly1305-encrypted into the attach id's IPC schema
370+
metadata (`vgi.secret_options`, AAD = uuid). Key: configured signing key, else the HTTP
371+
sealing key, else `internal/HostLocalKey` (per-user 0600 file, shared by pooled/stdio
372+
processes). Old 3-arg `AttachOptionsAttachId.encode` still drops them.
373+
- The main catalog's resolved data version now rides inside the attach envelope
374+
(`CatalogRegistry.recoverableAttach`, only when the ATTACH name equals the catalog name), so
375+
a process that never saw the ATTACH no longer loses it.
376+
349377
## Attach tickets (2026-10-07)
350378

351379
> **Protocol 2.0.0 (2026-10-17):** `AttachTicket.expires_at` is a nullable

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Version 0.46.0 uses VGI wire 3.1.0 under `vgi.v3` and requires a native VGI clie
3030
- **Table buffering functions** — sink/source functions that buffer all input before emitting (distributed-aggregation style lifecycles: process → combine → finalize).
3131
- **Aggregate functions** — partial aggregation with cross-process state combine.
3232
- **Catalog versioning** — semver data/implementation version negotiation, release manifests, multi-branch tables, transactions, and attach options.
33+
- **Writable tables and transactions** — catalog tables with INSERT / UPDATE / DELETE functions and write result modes, per-attach `supports_transactions` with begin / commit / rollback hooks, the transaction id and ATTACH options (secret ones included) in every function ([docs](docs/writable-tables-and-transactions.md)).
3334
- **Attach tickets** — seal a user's ATTACH (secret options included) so a runner holding their grant can replay it later without seeing an option ([docs](docs/attach-tickets.md)).
3435

3536
## Start a new worker
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
# Writable tables, transactions and ATTACH options
2+
3+
This page covers the main catalog's per-attach hooks: reading ATTACH options (secret ones
4+
included) in functions, deciding `supports_transactions` per attach, running code at
5+
transaction begin / commit / rollback, and declaring catalog tables DuckDB can write to.
6+
The `txfix` fixture worker (`vgi-example-worker/.../example/txfix/TxFixWorker.java`, which
7+
serves the vgi suite's `writable_tx/*.test`) uses every piece below and nothing else.
8+
9+
## ATTACH options in functions
10+
11+
Declare options with `Worker.attachOptions(...)`. Every table and table in-out function gets
12+
their values in its parameters, at bind and at init:
13+
14+
```java
15+
String token = params.attachOptions().getString("token"); // a secret option
16+
boolean tx = params.attachOptions().getBoolean("transactional", false);
17+
```
18+
19+
`TableBindParams`, `TableInitParams`, `TableInOutBindParams` and `TableInOutInitParams` all
20+
carry `attachOptions()` (`farm.query.vgi.AttachOptions`). The values travel inside the
21+
attach's `attach_opaque_data`, so a process that never served the `ATTACH` (a pooled launcher,
22+
the subprocess transport, another HTTP replica) sees them too. Keep no per-attach state in
23+
process memory.
24+
25+
**Secret options** (`AttachOptionSpec.asSecret()`) never appear in plaintext in that value
26+
(`vgi-opaque-data-sealing.md` rule 5). The framework encrypts them (ChaCha20-Poly1305, bound to
27+
the attach) with:
28+
29+
1. the configured key (`Worker.signingKey`, `Worker.opaqueDataKey` or `VGI_SIGNING_KEY`), else
30+
2. over HTTP, the per-process sealing key (multi-replica deployments configure a key anyway), else
31+
3. on stdio / unix sockets, a per-user key file shared by the host's worker processes:
32+
`$XDG_RUNTIME_DIR/vgi/attach-secret-options.key`, else
33+
`<java.io.tmpdir>/vgi-<user>/attach-secret-options.key` (directory `0700`, file `0600`,
34+
both owned by the user; `VGI_ATTACH_SECRET_KEY_FILE` names another file). It is created on
35+
the first attach that gives a secret option a value.
36+
37+
A process holding a different key sees secret options as absent and
38+
`AttachOptions.secretsAvailable()` is false. `AttachOptions.fromAttachId(attachId)` decodes the
39+
non-secret options from a plain attach id without the framework (secrets are never visible
40+
that way). `AttachOptions.toString()` redacts secret values.
41+
42+
## Per-attach settings: `Worker.onAttach`
43+
44+
```java
45+
worker.onAttach((attach, request) ->
46+
AttachSettings.transactional(attach.options().getBoolean("transactional", false)));
47+
```
48+
49+
The hook runs on every `ATTACH` of the main catalog, after required options are checked. It
50+
sees the catalog name, the plain attach id and every option value. It returns
51+
`AttachSettings(supportsTransactions, supportsTimeTravel)`; a `null` component keeps the
52+
worker-wide default, `Worker.supportsTransactions(boolean)` / `Worker.supportsTimeTravel(boolean)`
53+
(both `true` by default, as in earlier releases). Throwing fails the `ATTACH`.
54+
55+
## Transaction hooks: `Worker.transactionHooks`
56+
57+
On an attach whose result advertised `supports_transactions`, DuckDB calls
58+
`catalog_transaction_begin` / `_commit` / `_rollback` for every transaction, including the
59+
implicit one around each autocommit statement. `TransactionHooks` runs worker code there:
60+
61+
```java
62+
worker.transactionHooks(new TransactionHooks() {
63+
@Override public byte[] begin(AttachContext attach) { ... return id; } // default: 16 random bytes
64+
@Override public void commit(AttachContext attach, byte[] id) { ... } // throw to fail COMMIT
65+
@Override public void rollback(AttachContext attach, byte[] id) { ... }
66+
});
67+
```
68+
69+
- `begin` returns the transaction's **plaintext** id. Over HTTP the framework seals it on the
70+
way out and opens it on every later call, so `commit`, `rollback` and every function of the
71+
transaction receive exactly these bytes: `transactionId()` on the four parameter types
72+
above. A function can therefore stage work under the id and the hooks apply or discard it.
73+
- An exception from `commit` fails the client's `COMMIT` (or autocommit statement) with its
74+
message. Discard the staged work before throwing; do not count on a rollback call after a
75+
failed commit.
76+
- The hooks get an `AttachContext` with the attach's options, secret ones included.
77+
- They may run on any worker process: keep staged work somewhere all of them reach.
78+
79+
A producer or exchange that needs the id while producing rows keeps it in a field of its
80+
state (state fields survive HTTP turns). `TableBindParams.transactionStorage()` remains a
81+
key/value store scoped to the transaction (it exists for autocommit statements too).
82+
83+
Code-implemented catalogs (`Worker.registerCatalog`) have the same hooks as
84+
`CatalogInterface.supportsTransactions(attachId)` / `transactionBegin` / `transactionCommit` /
85+
`transactionRollback`. Auxiliary catalogs (`Worker.ExtraCatalog`) do not support transactions.
86+
87+
## Writable catalog tables
88+
89+
Name the write functions on the table descriptor:
90+
91+
```java
92+
CatalogTable.builder("main", "items", Schemas.serialize(schemaWithRowId))
93+
.scanFunction("items_scan") // emits rowid, declares projection pushdown
94+
.updateFunction("items_update") // a TableInOutFunction in this catalog
95+
.writeResultMode(WriteOperation.UPDATE, WriteResultMode.ROWS)
96+
.constraints(records, revision)
97+
.build();
98+
```
99+
100+
The framework then advertises `write_result_modes` and the inline write functions in
101+
`TableInfo` and answers `catalog_table_{insert,update,delete}_function_get`; a table without
102+
the function for an operation makes DuckDB refuse it ("does not support UPDATE"). UPDATE and
103+
DELETE need a scan function emitting a row-id column (`WriteResults.rowIdField()`) through
104+
projection pushdown.
105+
106+
A write function is an ordinary `TableInOutFunction`. DuckDB passes `write_options`:
107+
108+
```java
109+
WriteResultMode mode = WriteOptions.from(params.arguments()).resultMode();
110+
// bind:
111+
BindResponse.forSchema(Schemas.serialize(WriteResults.resultSchema(mode, userColumns)));
112+
// per input batch, after applying it:
113+
out.emit(WriteResults.resultBatch(mode, userColumns, oldRows, newRows, Allocators.root()));
114+
```
115+
116+
`COUNT` is a plain statement, `ROWS` is `RETURNING`; `CHANGES` (old / new images) is a maximum
117+
that satisfies both. UPDATE receives the `SET` columns (every column with `RETURNING`) plus the
118+
row id.
119+
120+
**Constraint enforcement.** A catalog with a table that carries constraint records *and* a write
121+
function advertises and selects `vgi.constraint.enforce.v1` automatically (the write functions
122+
must keep the table's ENFORCED constraints). A provider's own `Worker.catalogCapabilities`
123+
decision is merged with it; a profile it advertises whose prerequisite only the framework
124+
supplies (enforce without records read) is still selected.
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Copyright 2026 Query Farm LLC - https://query.farm
2+
3+
package farm.query.vgi;
4+
5+
/**
6+
* The attach an {@link AttachHook} or a {@link TransactionHooks} call belongs to.
7+
*
8+
* @param catalogName the catalog name the {@code ATTACH} named
9+
* @param attachId the plain attach id: the bytes functions see as {@code attachId()} and
10+
* the shard key of the worker's shared storage (never the sealed wire value)
11+
* @param options the attach's option values, secret ones included
12+
*/
13+
public record AttachContext(String catalogName, byte[] attachId, AttachOptions options) {}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Copyright 2026 Query Farm LLC - https://query.farm
2+
3+
package farm.query.vgi;
4+
5+
import farm.query.vgi.protocol.CatalogAttachRequest;
6+
7+
/**
8+
* Called on every {@code ATTACH} of the worker's main catalog, after required options are
9+
* checked and before the attach result is returned; registered with
10+
* {@link Worker#onAttach(AttachHook)}.
11+
*
12+
* <p>The hook sees every option value, secret ones included, and decides the attach's
13+
* per-attach settings, for example {@code supports_transactions} from an option:
14+
*
15+
* <pre>{@code
16+
* worker.onAttach((attach, request) ->
17+
* AttachSettings.transactional(attach.options().getBoolean("transactional", false)));
18+
* }</pre>
19+
*
20+
* <p>Throwing fails the {@code ATTACH} with the exception's message. Keep no per-attach
21+
* state in process memory: later calls of the attach may reach another worker process
22+
* (pooled launcher, subprocess transport, HTTP replicas). Everything a function or hook
23+
* needs later is in its {@link AttachOptions}.
24+
*/
25+
@FunctionalInterface
26+
public interface AttachHook {
27+
28+
/**
29+
* Decide the settings of one attach.
30+
*
31+
* @param attach the attach being created: catalog name, plain attach id, option values
32+
* @param request the raw attach request
33+
* @return the settings, or {@code null} for {@link AttachSettings#defaults()}
34+
*/
35+
AttachSettings onAttach(AttachContext attach, CatalogAttachRequest request);
36+
}

0 commit comments

Comments
 (0)