Repository navigation
feat: add lossless read_rows RPC for table-to-table copy (#207) - #211
Merged
Merged
Conversation
With the builtin PostgreSQL driver removed (tabularis#1625), the host's Transfer feature has no PostgreSQL source path: execute_query formats values for display (truncates bytea to a 10 KB preview, drops fractional seconds on time/timestamp, drops both fractional seconds and the timezone offset on timestamptz), so a copy built on it cannot meet the reject-any-lossy-conversion rule. Add a read_rows RPC that returns full-precision values plus the PostgreSQL type name and OID per column: - Three Full temporal types (PgTimeFull, PgTimestampFull, PgTimestampTzFull) retain sub-second micros and emit .ffffff when nonzero (matching the already-lossless TimeTz/Interval pattern); PgTimestampTzFull appends +00:00 (PostgreSQL native UTC format). - BYTEA uses encode_blob_full (no 10 KB truncation). - All other scalar types delegate to the existing (already-lossless) extract_simple_kind arms. - A parallel extract_value_lossless function diverges from the display extract_value in only those four arms, so the hot execute_query path is untouched. With a session_id, the first page opens BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY on a pinned connection (reusing the session::Slot machinery); subsequent pages reuse that connection and its snapshot, so rows are not skipped or repeated when the source table changes between pages. Release with release_session (ROLLBACK). On any error after BEGIN, ROLLBACK and discard — do not re-pin (25P02 cascade risk). A table_copy capability flag in .tabularium gates the feature on the host side (companion to tabularis#1625); the host never calls read_rows on an older build. Arrays/ranges/composites of temporals stay lossy in this PR (documented limitation; the copy acceptance criteria are scalar columns). 13 new unit tests cover the Full temporal wire format (fractional seconds, +00:00 offset, infinity sentinels) and request validation; 2 live tests cover the lossless round-trip (timestamp(6)/timestamptz/ bytea>10KB/numeric/int8/float8/bool/text/uuid) and the REPEATABLE READ snapshot (a row inserted between pages is not visible to page 2). Co-authored-by: Adam J. Esslinger <14128427@aesslinger@users.noreply.github.com>
Version suggestionBased on this PR's title (
This is informational only — no tag or release is created automatically yet. |
) The read side (read_rows) landed in the prior commit; this adds the write side so the host can copy tables PG to PG, not just PG to SQLite. insert_records takes a table, an optional schema, and a rows array of {column: value, ...} objects (the host builds them from a read_rows result set). It reuses the existing bind_pg_value typed cascade (which is row-agnostic) with column types discovered once per batch (the one-row insert_record path re-queries per insert), in one transaction on a one-shot connection (BEGIN / chunked INSERTs / COMMIT, ROLLBACK on any error), so a batch that fails writes none of its rows. A batch exceeding the 65535-placeholder cap is split across multiple INSERT statements inside the same transaction, preserving atomicity. The BLOB:...:base64 format from read_rows round-trips through bind_pg_value's decode_blob_wire_format, so a PG to PG copy preserves every value — bytea, full-precision timestamps, numeric, etc. A live round-trip test (read_rows -> insert_records -> read_rows verify) confirms byte-for-byte identity across timestamp(6)/timestamptz/bytea >10KB/numeric(38,10)/int8/float8/bool/text/uuid. 2 new unit tests cover insert_records request validation; 1 new live test covers the full PG-to-PG copy round-trip. Co-authored-by: Adam J. Esslinger <14128427@aesslinger@users.noreply.github.com>
A pre-handoff ensemble review (12 agents) found 9 issues. All fixed:
Blockers:
1. placeholder_idx not reset per chunk: chunk 2+ generated $32001+
placeholders while owned_params had only chunk-2's params. PostgreSQL's
Bind protocol maps params positionally to $1,$2,..., so any batch large
enough to split (the primary use case) failed. Reset placeholder_idx = 1
inside the chunk loop.
2. Fractional seconds not zero-padded: 100µs → "100" → "1" → ".1", which
PostgreSQL parses as 100,000µs (1000× error). Fixed all 3 Full temporal
From impls to format!("{:06}", micros).trim_end_matches('0').
3. cleanup_on_error skipped ROLLBACK on subsequent pages (opened_txn=false),
leaking an aborted transaction into the shared pool (RecyclingMethod::Fast
accepts it without reset, poisoning the next borrower). Now ROLLBACKs
whenever a transaction is open, regardless of which call opened it.
Judgment calls:
4. SET LOCAL outside a transaction was a no-op on the one-shot read_rows
path (schema filter silently dropped). Wrap the one-shot read in
BEGIN READ ONLY / COMMIT so SET LOCAL takes effect.
5. insert_records docstring advertised a columns param the handler never
read. Removed the dead param_columns_placeholder function and fixed the
docstring; columns are always derived from rows[0]'s keys.
6. insert_records response was {affected_rows: u64} (object) vs
insert_record's bare u64. Changed to bare u64 for parity.
7. insert_records used -32603 (internal error) for a missing table instead
of -32602 (invalid params), inconsistent with read_rows in the same PR.
Moved the validation to the handler top level with -32602.
8. read_rows dropped column metadata on empty result sets. Documented the
limitation (the host reads table schema via get_columns separately).
9. A row missing a column present in rows[0] silently bound NULL (could
violate NOT-NULL or insert wrong data). Now rejects mismatched rows with
a clear "row is missing column" error.
2 new unit tests cover the fractional-seconds zero-pad fix (100µs → .0001).
Co-authored-by: Adam J. Esslinger <14128427@aesslinger@users.noreply.github.com>
aesslinger
marked this pull request as ready for review
December 1, 2026 18:33
Code Review SummaryStatus: No Issues Found | Recommendation: Merge The previous warning is fixed: Files Reviewed (1 file)
Previous Review Summary (commit 2a31ef7)Current summary above is authoritative. Previous snapshots are kept for context only. Previous review (commit 2a31ef7)Status: 1 Issue Found | Recommendation: Address before merge Overview
Issue Details (click to expand)WARNING
Files Reviewed (9 files)
Reviewed by claude-sonnet-5.5 · Input: 4.1K · Output: 1.2K · Cached: 155K |
The Kilo code review bot flagged that insert_records takes its column list from rows[0] only, so extra keys in later rows are silently dropped. The pre-handoff review's finding #9 fixed missing keys (a row missing a column from rows[0] now errors), but extra keys (a row with a key not in rows[0]) were still silently ignored. Now both directions are validated: every row must have exactly the same keys as rows[0]. Co-authored-by: Adam J. Esslinger <14128427@aesslinger@users.noreply.github.com>
aesslinger
added a commit
that referenced
this pull request
Dec 2, 2026
) * fix: close four table-copy gaps in read_rows/insert_records (#214) Four gaps in the table-copy path added by #211, blocking the host (TabularisDB/tabularis#1625) from consuming the copy RPC pair without data loss or a dropped feature: 1. Wide NUMERIC / NaN read back as NULL (data loss). read_rows decoded NUMERIC through rust_decimal::Decimal (96-bit, ~28-29 significant digits, no NaN), so a numeric(38,10) value over 29 digits or a NaN silently became Null — the worst failure mode on the "lossless" path. Add a PgNumeric FromSql that decodes the base-10000 wire bytes directly (reproducing PG16's numeric_out/get_str_from_var) so wide values and NaN/Infinity survive. The write side (bind_pg_numeric_string) falls back to a TEXT+CAST($N AS numeric) bind for values Decimal can't hold, with a numeric-shape guard so garbage is still rejected client-side; small numerics still bind as Type::NUMERIC. 2. Column metadata mismatch. get_columns now returns the canonical type name (pg_catalog.format_type) and the oid — the same vocabulary read_rows uses via Type::name() — so the host has one type mapping for both row data and column metadata. Additive; get_view_columns, get_materialized_view_columns, and the batch fetch get the same fields. 3. insert_records on_conflict. Add an optional on_conflict param ("fail" default, "skip" -> ON CONFLICT DO NOTHING); the response changes from a bare u64 to { affected_rows, skipped } so the host's rows_written/rows_skipped stay honest. 4. read_rows pages with LIMIT/OFFSET (quadratic, no stable order). The session-pinned path now DECLAREs a NO SCROLL cursor and FETCH FORWARD per page — linear in table size, one stable row order — like the removed built-in driver did. The cursor lives/dies with the pinned transaction, so release_session cleans it up. has_more is rows.len() == page_size (a NO SCROLL cursor can't probe ahead without consuming a row). The one-shot path keeps LIMIT/OFFSET. Tests: 12 PgNumeric wire-format + 3 binding unit tests (no live DB); live tests cover wide-numeric/NaN round-trip, large-table cursor paging, and on_conflict skip. 701 lib tests pass; 59 live_db + 82/84 live matrix pass (the 2 failures are pre-existing env gaps: a multi-backend pgbouncer container not running and a missing SSL host env var). Co-Authored-By: Adam J Esslinger <esslinger@gmail.com> * fix: correct NUMERIC weight<-1 decoding and drop false empty-page claim Two issues found by kilo code bot review of PR #216: 1. CRITICAL: PgNumeric decoded values with weight < -1 wrong. The integer branch set d = 0 and kept it there when weight < 0, so the fractional loop read digits[0] as the first fractional group instead of reading leading zero groups first. 0.00001234 (weight=-2, digits=[1234], dscale=8) decoded as 0.12340000 — silent data corruption on any value below 0.0001, exactly the lossless-path bug the PR exists to fix. Set d = weight + 1 in the weight<0 branch (matching PostgreSQL's get_str_from_var); the existing d >= 0 guard handles the negative indices. Added pg_numeric_weight_below_minus_one and pg_numeric_weight_minus_three regression tests. 2. WARNING: the cursor-path doc comments claimed a zero-row FETCH still carries column metadata (fixing the empty-page gap). It does not — query_typed returns Vec<Row>, so a zero-row FETCH has no rows to read columns from. Dropped the false claim from run_snapshot/fetch_cursor docs and noted the host falls back to get_columns for an empty source. Co-Authored-By: Adam J Esslinger <esslinger@gmail.com> * fix: address pre-handoff ensemble review findings for #214 23-agent ensemble review (11 dimensions × 2 passes + generalist) found 15 confirmed issues. All are fixed here; the two kilo code bot findings (weight<-1 data corruption, false empty-page claim) were already fixed in the prior commit (1de5f50). Security: - Session-cursor DECLARE now uses query_typed (extended protocol) instead of batch_execute (simple-query protocol), restoring the single-statement invariant the one-shot path has — a multi-statement `query` with `;` stacking is rejected the same way both paths (3 independent sources). Concurrency/retry-safety: - is_first_page now keys off pinned.is_none(), not the client-supplied `page` number, so a retried/duplicate page=1 reuses the existing cursor via FETCH instead of re-DECLAREing (which errored "cursor already exists" and tore down the live snapshot) (4 sources). - CancelGuard is dropped before cleanup_on_error's ROLLBACK so a re-sent cancel can't interrupt the cleanup. Validation: - page_size clamped to .max(1) — limit:0 previously made FETCH FORWARD 0 loop forever (has_more = 0>=0 = true) on the cursor path (4 sources). - on_conflict present-but-non-string (number/bool/array/object) is now rejected with -32602, not silently defaulted to "fail" (3 sources). JSON null still defaults (treated as absent). Data integrity: - bind_pg_numeric_string NUMERIC/DECIMAL arm now always binds via TEXT+CAST, dropping the Decimal::parse success arm that silently rounded high-scale values (e.g. numeric(40,36)) to 28 significant digits — the exact round-trip corruption #214 item 1 exists to fix (2 sources). - PgNumeric validates each base-10000 digit is <= 9999 (rejects garbage chars) and rejects unrecognized sign values (0xE000, 0x2000) instead of silently fabricating "NaN" or positive (3 sources). API/contract: - get_columns/get_view_columns/get_materialized_view_columns `type` field now uses pg_type.typname (the short internal name: int8, numeric, timestamptz) matching read_rows' Type::name(), NOT format_type (which gives bigint, numeric(38,10)). The "one type vocabulary" claim is now true (2 sources). - get_view_columns uses LEFT JOIN pg_attribute so a view column whose pg_attribute row is absent (foreign table, ALTER edge case) isn't silently dropped from the result. Docs: - extract_value_lossless / extract_simple_kind_lossless doc comments corrected: NUMERIC is no longer listed as "already lossless, delegates" — it has a dedicated PgNumeric override arm; "four" → "five" overrides. Tests: 713 lib tests pass (up from 703); 59 live_db + 75/84 live matrix pass (the 9 failures are pre-existing env gaps: TLS/unix-socket/multi- backend pgbouncer containers not running). New unit tests cover PgNumeric wire validation (digit>=10000, unknown signs), numeric-column garbage rejection + edge-form acceptance, cursor_name sanitization, and on_conflict type validation. The vacuous page>1 test is replaced with non-vacuous limit:0 and on_conflict-type tests. Co-Authored-By: Adam J Esslinger <esslinger@gmail.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Resolves #207 — lossless table-to-table copy for PostgreSQL, both read and write sides. With the builtin PostgreSQL driver removed (tabularis#1625), the host's Transfer feature has no PostgreSQL source/target path.
execute_queryformats values for display (truncatesbyteato a 10 KB preview, drops fractional seconds ontime/timestamp, drops both fractional seconds and the timezone offset ontimestamptz), andinsert_recordis one-row-per-RPC with no batch/atomicity contract — neither can meet the reject-any-lossy-conversion rule the table transfer was reviewed against.What this PR adds
Two new RPCs + a
table_copycapability flag, covering the full PG→PG copy path:read_rows— lossless, optionally-snapshot readReturns full-precision values plus the PostgreSQL type name and OID per column:
execute_query(display)read_rows(lossless)time/timestamp(6)HH:MM:SS)HH:MM:SS.ffffff)timestamptz+00:00UTC offsetbyteanumeric/int8/float8/bool/text/uuid/jsonWith a
session_id, the first page opensBEGIN ISOLATION LEVEL REPEATABLE READ READ ONLYon a pinned connection (reusing thesession::Slotmachinery); subsequent pages reuse the snapshot, so rows are not skipped or repeated when the source changes. Release withrelease_session(ROLLBACK).insert_records— batch typed insertTakes a
table, optionalschema, and arowsarray of{column: value, ...}objects (the host builds them from aread_rowsresult set). Reuses thebind_pg_valuetyped cascade with column types discovered once per batch (the one-rowinsert_recordre-queries per insert), in one transaction on a one-shot connection (BEGIN→ chunkedINSERTs →COMMIT,ROLLBACKon any error), so a batch that fails writes none of its rows. Batches exceeding the 65535-placeholder cap are split across multipleINSERTs inside the same transaction.Round-trip
The
BLOB:...:base64format fromread_rowsround-trips throughbind_pg_value'sdecode_blob_wire_format, so a PG→PG copy preserves every value —bytea, full-precision timestamps,numeric, etc.How
PgTimeFull,PgTimestampFull,PgTimestampTzFull) retain sub-second micros and emit.ffffffwhen nonzero (matching the already-losslessTimeTz/Intervalpattern);PgTimestampTzFullappends+00:00.extract_value_lossless— a parallel function toextract_value, diverging in only 4 arms (TIME/TIMESTAMP/TIMESTAMPTZ/BYTEA). The hotexecute_querydisplay path is untouched.handlers/copy.rs(new) —read_rows(own simpler execution, session-pinned snapshot,CancelGuard, ROLLBACK-and-discard on error) andinsert_records(one-shot client, atomicBEGIN/COMMIT/ROLLBACK, chunked multi-rowINSERT).table_copycapability in.tabularium— the host gates the Transfer feature on this flag. Companion to tabularis#1625.Verification (all green locally)
cargo build✅cargo test --lib✅ — 677 passed (662 + 15 new), 0 failedcargo clippy --all-targets -- -D warnings✅cargo fmt --all -- --check✅npx markdownlint README.md CHANGELOG.md✅cargo audit✅ — exit 0timestamp(6)keeps.345678,timestamptzkeeps+00:00,bytea>10 KB is full base64read_rows→insert_records→read_rows(verify); every value byte-for-byte identical acrosstimestamp(6)/timestamptz/bytea>10KB/numeric(38,10)/int8/float8/bool/text/uuidKnown limitations (documented in README + CHANGELOG)
extract_kind_from_bytes.byteain a single row is unbounded in the read response (no cap — the issue wants lossless). A cap +fetch_blob_as_data_urlfallback is a follow-up if the host needs it.Host companion
The
table_copyflag is inert until the host (tabularis#1625) consumes it — the host gates the Transfer feature on the capability and callsread_rows(withsession_idfor the snapshot) +insert_records+release_session. The plugin PR is mergeable independently; the feature lights up when the companion lands.Notes for review
extract_value_losslessparallel-function approach (vs anExtractModeenum threaded throughextract_value) was chosen to keep the hotexecute_querydisplay path untouched — an enum would touch ~120 type arms for zero functional gain.release_session(always ROLLBACK) is reused for snapshot release — for a read-only REPEATABLE READ snapshot, ROLLBACK is semantically correct (nothing to commit).min_runtime_versionis not bumped — the capability flag gates the RPCs (cf.read_only_queriesrequiring v0.33.0); an older host never callsread_rows/insert_records.