Skip to content

fix: close four table-copy gaps in read_rows/insert_records (#214) - #216

Merged
aesslinger merged 3 commits into
mainfrom
fix/issue-214-table-copy-gaps
Dec 2, 2026
Merged

aesslinger merged 3 commits into
mainfrom
fix/issue-214-table-copy-gaps

Conversation

@aesslinger

@aesslinger aesslinger commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Closes #214 — four gaps in the table-copy path added by #211 (read_rows / insert_records), opened by the host side (TabularisDB/tabularis#1625) before it can consume the copy RPC pair without risking data loss or dropping a feature the built-in driver had. The host will pin its CI fixture and migration gate to the release carrying these.

The four items, in the order the issue blocks on them:

1. Wide NUMERIC / NaN read back as NULL (data loss) — read + write sides

read_rows is the "lossless" path but decoded NUMERIC through rust_decimal::Decimal (96-bit mantissa, ~28–29 significant digits, no NaN), so a numeric(38,10) value over 29 digits or a NaN silently became JsonValue::Null.

  • Read side (extract.rs): new PgNumeric FromSql decodes the base-10000 wire bytes directly, reproducing PG16's numeric_out/get_str_from_var. Wide values and NaN/Infinity survive. The display path keeps Decimal.
  • Write side (binding.rs): bind_pg_numeric_string always binds NUMERIC/DECIMAL via TEXT+CAST($N AS numeric) (validated by looks_like_numeric_literal), not Decimal::parse — which silently rounds high-scale values to 28 significant digits.

2. get_columns canonical type name + OID

get_columns now returns type (pg_type.typname — the short internal name matching read_rows' Type::name()) and oid. Additive; get_view_columns, get_materialized_view_columns, and the batch fetch get the same fields.

3. insert_records on_conflict: "skip"

Optional on_conflict param ("fail" default, "skip" → ON CONFLICT DO NOTHING). Response: { affected_rows, skipped }. Breaking response-shape change — the only consumer is the host PR (tabularis#1625), which the issue says to coordinate with.

4. Server-side cursor for session-pinned read_rows

The session path DECLAREs a NO SCROLL cursor + FETCH FORWARD per page — linear, one stable order. The cursor is declared once (keyed off pinned.is_none(), not the page number, so a retried page=1 reuses the cursor). has_more = rows.len() == page_size. The one-shot path keeps LIMIT/OFFSET. An empty source still reports columns: [] — the host falls back to get_columns.

Post-review fixes

Commit 1de5f50 (kilo code bot review)

  • CRITICAL — NUMERIC weight < -1 data corruption: decoder set d = 0 and kept it there when weight < 0, so 0.00001234 (weight=-2) decoded as 0.12340000. Fixed: d = weight + 1. Regression tests added.
  • WARNING — false empty-page claim: dropped the doc claim that a zero-row FETCH carries column metadata.

Commit 6e15650 (23-agent ensemble review — 15 confirmed findings, all fixed)

Security:

  • Session-cursor DECLARE now uses query_typed (extended protocol) not batch_execute (simple-query), restoring the single-statement invariant — ;-stacked SQL injection is rejected on both paths (3 sources).

Concurrency/retry-safety:

  • is_first_page keys off pinned.is_none(), not page — a retried page=1 reuses the cursor instead of re-DECLAREing and corrupting the snapshot (4 sources).
  • CancelGuard dropped before cleanup_on_error's ROLLBACK so a re-sent cancel can't interrupt cleanup.

Validation:

  • page_size clamped to .max(1) — limit:0 previously made FETCH FORWARD 0 loop forever (4 sources).
  • on_conflict present-but-non-string (number/bool/array/object) rejected with -32602, not silently defaulted (3 sources). JSON null still defaults.

Data integrity:

  • bind_pg_numeric_string always TEXT+CAST — the Decimal::parse success arm silently rounded high-scale numerics (numeric(40,36)) to 28 digits (2 sources).
  • PgNumeric validates digit ≤ 9999 (rejects garbage chars) and rejects unrecognized sign values (3 sources).

API/contract:

  • get_columns type uses pg_type.typname (int8, numeric) not format_type (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 isn't silently dropped.

Docs: extract_value_lossless / extract_simple_kind_lossless corrected (NUMERIC no longer "already lossless, delegates"; "four" → "five" overrides).

Test plan

  • Unit (no live DB): 713 lib tests pass (0 failed), including new tests for PgNumeric wire validation, numeric-column garbage rejection + edge forms, cursor_name sanitization, on_conflict type validation, and empty-batch return. cargo clippy --all-targets -- -D warnings clean; cargo fmt --all --check clean.
  • Live matrix (podman, all containers up): 59 live_db integration tests pass; 75/84 client_live_tests pass. The 9 failures are pre-existing env gaps (TLS/unix-socket/multi-backend pgbouncer containers not running locally — need tests/podman/env.sh up + a native PostgreSQL socket).
  • New live tests: read_rows_session_cursor_pages_a_large_table_linearly (2500 rows, 3 pages), insert_records_on_conflict_skip_reports_inserted_and_skipped, wide-numeric/NaN coverage.

Notes for review

  • The NUMERIC wire decoder is the riskiest piece — direct port of PG16's get_str_from_var, verified against hand-built wire bytes for 38/30-digit integers, NaN/±Inf, dscale trailing zeros, weight<-1, digit≥10000, unknown signs.
  • Item 3 is a breaking response-shape change (u64 → object). The host PR (tabularis#1625) coordinates on it.
  • affected_rows/skipped naming: the host's TableTransferTableResult uses rows_written/rows_skipped. The plugin's field names differ; the host remaps. This is a judgment call (1 source flagged it, 1 source filtered it as disclosed).

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>
@aesslinger aesslinger added bug Something isn't working prerelease:rc Version suggestion targets a release candidate labels Dec 1, 2026
@aesslinger aesslinger self-assigned this Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown

Version suggestion

Based on this PR's title (fix) and the prerelease:rc label:

Current 1.0.0-rc.14
Suggested next tag v1.0.0-rc.15

This is informational only — no tag or release is created automatically yet.

@aesslinger
aesslinger marked this pull request as ready for review December 1, 2026 22:47
Comment thread src/extract.rs Resolved
Comment thread src/handlers/copy.rs Resolved
@kilo-code-bot

kilo-code-bot Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: No Issues Found | Recommendation: Merge

Files Reviewed (3 files)
  • src/extract.rs
  • src/extract_tests.rs
  • src/handlers/copy.rs
Previous Review Summary (commit 2ff5cb8)

Current summary above is authoritative. Previous snapshots are kept for context only.

Previous review (commit 2ff5cb8)

Status: 2 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 1
WARNING 1
SUGGESTION 0
Issue Details (click to expand)

CRITICAL

File Line Issue
src/extract.rs 1180 PgNumeric does not set d = weight + 1 for weight < 0, so values with weight <= -2 (e.g. 0.00001234) decode incorrectly

WARNING

File Line Issue
src/handlers/copy.rs 317 Zero-row session FETCH returns empty columns, contradicting the docs and PR claim
Files Reviewed (8 files)
  • src/binding.rs
  • src/binding_tests.rs
  • src/client_live_tests.rs
  • src/extract.rs - 1 issue
  • src/extract_tests.rs
  • src/handlers/copy.rs - 1 issue
  • src/handlers/copy_tests.rs
  • src/handlers/metadata.rs

Fix these issues in Kilo Cloud


Reviewed by claude-sonnet-5.5 · Input: 4.1K · Output: 1.4K · Cached: 141.2K

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>
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>
@aesslinger
aesslinger merged commit 468555e into main Dec 2, 2026
16 checks passed
@aesslinger
aesslinger deleted the fix/issue-214-table-copy-gaps branch December 2, 2026 14:00
aesslinger added a commit that referenced this pull request Dec 2, 2026
Merge main (PRs #216, #217) into release/rc.15 and update the CHANGELOG:
- Added: session-pinned cursor paging, on_conflict skip, get_columns
  type+oid (#214, #216)
- Fixed: wide NUMERIC/NaN data-loss on read_rows, read_rows byte-budget
  bounding (#215, #217)
- Test count: 682 → 713

Co-Authored-By: Adam J Esslinger <esslinger@gmail.com>
aesslinger added a commit that referenced this pull request Dec 2, 2026
* chore: release 1.0.0-rc.15

Bumps version to 1.0.0-rc.15 in .tabularium, Cargo.toml, Cargo.lock, and
the CHANGELOG. This release includes:

- feat: lossless table-to-table copy path (#207) — read_rows RPC
  (lossless, optionally-snapshot read) + insert_records RPC (batch typed
  insert) + table_copy capability
- fix: replace unmaintained chrono with custom wire-decode (#200) — full
  Postgres date range parity, jiff dependency removed
- fix: avoid SQL pagination for data-modifying CTE statements (#212) —
  WITH ... INSERT/UPDATE/DELETE no longer gets LIMIT appended or re-executed
- fix: paginate queries that end in a comment (#204) — comment-aware lexer
- fix: large limit/page no longer wraps to LIMIT 0

Co-authored-by: Adam J. Esslinger <14128427@aesslinger@users.noreply.github.com>

* chore: update rc.15 CHANGELOG with #214/#216 and #215/#217 entries

Merge main (PRs #216, #217) into release/rc.15 and update the CHANGELOG:
- Added: session-pinned cursor paging, on_conflict skip, get_columns
  type+oid (#214, #216)
- Fixed: wide NUMERIC/NaN data-loss on read_rows, read_rows byte-budget
  bounding (#215, #217)
- Test count: 682 → 713

Co-Authored-By: Adam J Esslinger <esslinger@gmail.com>

---------

Co-authored-by: Adam J. Esslinger <14128427@aesslinger@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working prerelease:rc Version suggestion targets a release candidate

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Table copy follow-up: wide NUMERIC reads as NULL, column types on empty pages, skip-on-conflict

1 participant