Skip to content

docs: Design binary result transport - #667

Draft
krlmlr wants to merge 12 commits into
mainfrom
claude/binary-transport
Draft

krlmlr wants to merge 12 commits into
mainfrom
claude/binary-transport

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

This PR records the design for fetching query results in libpq's binary format instead of text, following the discussion of money in #659, with a benchmark of text versus binary transport. The design is in design/binary-transport.md, the experiment record (prototype patch, scripts, raw results, differential check) in design/binary-transport-bench/. Implementation follows in separate PRs.

What the design proposes:

  • Per-result choice: libpq picks text or binary for a whole execution, not per column. Prepared queries are described before they run, so an execution requests binary only when every result column has a binary decoder; otherwise the whole result stays text, exactly as today. The format is fixed per result, across all dbBind() groups. immediate = TRUE (simple query protocol) stays text.
  • Decoders: bool, int2/int4/int8, float4/float8, numeric, text-like types, json/jsonb, bytea, void, uuid, date, time, timetz, timestamp, timestamptz (infinities included; requires integer_datetimes = on), and "char" on servers from PostgreSQL 15. Each reproduces today's R value; the exceptions are listed under "Behavior changes".
  • Not binary-eligible: money, oid, interval, xml, arrays, ranges, enums, composites, extension types and unknown OIDs, so their columns keep today's text values and classes.
  • Shared decoders: resolved per column in the row sink's begin() (which gains a formats vector on top of refactor: Fetch rows through a pluggable row sink #638), returning a status instead of warning, used by the legacy column sources, the ALTREP columns of docs: Design ALTREP-backed result columns #632 and an Arrow sink. This work owns docs: Design ALTREP-backed result columns #632's phase 1, after fix: Read money columns as numbers instead of 0 #659 and fix: Parse infinity, BC dates, and years beyond 9999 in dates and timestamps #660 merge.
  • Servers (decided in question 1): a dbConnect() argument whose "auto" default requests binary only for servers detected as PostgreSQL 10 or later from values libpq has at connection time; Redshift and other recognizable compatible servers stay on text. Parameters stay text.
  • Behavior changes: float4 widens to the exact stored value (0.1 → 0.100000001490116); float8 from servers before PostgreSQL 12 becomes exact; infinite and BC dates and timestamps and historical offsets with seconds become correct; rare one-ulp rounding differences for timestamptz in non-UTC sessions.

Benchmark (comment): binary fetches are 20–40% faster for timestamptz, float8, bytea, int8 and a wide mixed table, with no measurable difference for int4, date, bool, text, numeric and uuid. The per-row overhead of single-row mode likely caps the gain. A prototype differential check found only the behavior changes above.

Relation to other PRs: #659 (money) stays needed, since results with money stay text under the recommended option. #660 (dates) stays needed for text results (immediate = TRUE, Redshift, fallback), but binary results don't depend on it. #638 stays as it is. #632 decides its chunk layout itself; altrep = TRUE connections get text results until ALTREP phase 2b, through a per-connection "binary allowed" flag added in this work's phase 2.

The design went through three rounds of clean review. Resolved: 1 default and switch. Open questions (one comment each): 2 immediate = TRUE, 3 money, 4 float4, 5 parameters, 6 oid, 7 numeric.

Accepted limitations: #667 (comment)

Session: https://claude.ai/code/session_01Hr1rd4DRzYu5618pRoCxJ3

https://claude.ai/code/session_01Hr1rd4DRzYu5618pRoCxJ3


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Resolved (Question 1): Is binary the default, and how is it switched?

Design doc, lines 38–60 and 126–143

Binary transport is chosen per result: binary when every column has a binary decoder, text otherwise, so ineligible types behave exactly as today. Eligible types change in the few ways listed under "Behavior changes" (mainly float4, question 4). The benchmark shows 20–40% faster fetches for timestamps, doubles, bytea, int8 and wide tables, and no measurable difference elsewhere. Binary support on Redshift, CockroachDB, YugabyteDB and other PostgreSQL-compatible servers is not verified, and they can be reached through Postgres() too. If nobody decides, the implementation goes ahead with the recommended option.

  • (recommended) A dbConnect() argument, for example result_format = c("auto", "binary", "text"). "auto" means binary only for servers that report PostgreSQL 10 or later in a form PostgreSQL itself uses (distribution suffixes such as (Debian ...) allowed, -YB- and similar rejected) and announce no other product in their parameter status, text otherwise. A version check cannot exclude a compatible server that copies PostgreSQL's version format exactly, so the argument remains the way out; Redshift() defaults to text. The detection uses values libpq has at connection time, so no round trip.
  • The same argument, but text by default for one release, then "auto". Safer for reverse dependencies, slower to deliver the fixes.
  • Binary by default for every server except Redshift(), without detection. Simpler, but untested servers reached through Postgres() get binary.
  • Binary always when eligible, with no switch. Leaves no way out for servers with incomplete binary support.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 2: What happens with immediate = TRUE?

Design doc, line 48

immediate = TRUE uses PQsendQuery(), the simple query protocol, which always returns text. It is used for multi-statement strings and for statements that cannot be prepared, and by dbConnect() itself. If nobody decides, the recommended option applies.

  • (recommended) Keep text for immediate = TRUE. Both decoders coexist anyway, and the text path keeps the fixes from fix: Read money columns as numbers instead of 0 #659 and fix: Parse infinity, BC dates, and years beyond 9999 in dates and timestamps #660. Results of the same query can then differ in the cases listed under "Behavior changes" (float4) depending on immediate.
  • Send immediate = TRUE queries without parameters through PQsendQueryParams() with binary results. This breaks multi-statement strings, which is the main reason to use immediate = TRUE.
  • Make the text path match binary exactly (for example, widen float4 text to the nearest float4 first), so the format never shows in results. Extra code on the text path for a small gain.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 3: Does money get a binary decoder?

Design doc, lines 98–99

In binary, money is an int64 count of minor units, so values are exact and separators no longer matter. The number of fractional digits still follows lc_monetary, which the server does not report. A probe such as SELECT 1::money::numeric costs a round trip and, as a simple query, destroys the unnamed prepared statement, so the user query would have to be prepared again (two extra round trips, the same trade-off as #632's question 10). If nobody decides, the recommended option applies.


Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 4: Is the float4 widening accepted?

Design doc, lines 156–159

PostgreSQL 12 and later send float4 as the shortest decimal that round-trips, for example 0.1, which RPostgres reads as the double nearest to 0.1. In binary, the client gets the float4 itself, which widens to 0.100000001490116. Both are "correct"; text matches what users typed, binary matches what is stored. The prototype's differential test will show the full list of differences. If nobody decides, the recommended option applies.

  • (recommended) Accept the widening, with a NEWS.md entry. float4 is rare in R workflows, and the binary value is the one the server holds.
  • Reproduce the text result: format the float4 with the shortest round-trip digits (C++17 std::to_chars(), which needs GCC 11 or a vendored algorithm) and strtod() it. Identical to text on PostgreSQL 12 and later, at some cost per value and a toolchain requirement.
  • float4 is not binary-eligible, so results with a float4 column stay text.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 5: Are parameters sent in binary format too?

Design doc, lines 121–125

Parameters are formatted as text in R today, except blob parameters, which already go in binary. Binary parameters require the client to state each parameter's type, which the server infers from the query today; RPostgres writes tables with COPY, so parameters matter mostly for dbBind() loops. If nobody decides, the recommended option applies.

  • (recommended) Keep text parameters; this design changes results only. Binary parameters can be a separate design if dbBind() benchmarks show a need.
  • Send numbers, logicals, dates and timestamps in binary, with their types taken from the PQdescribePrepared() parameter description. Saves formatting in R, but changes how the server sees typed parameters.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 6: Does oid stay on text until its own fix?

Design doc, lines 71–73

oid maps to DT_INT and is parsed with atoi(), which wraps above 2^31 - 1 with glibc (reprex in #632) but saturates at INT_MAX on Windows, as the clean review pointed out. No single binary decoder reproduces both, so a binary oid would change results on one platform. oid columns are rare outside catalog queries. If nobody decides, the recommended option applies.

  • (recommended) oid is not binary-eligible, so results with an oid column stay text. Fix oid on both paths (map it to double) in its own issue and PR, as proposed in docs: Design ALTREP-backed result columns #632, and make it eligible then.
  • Reproduce the platform's atoi() behavior in the binary decoder (wrap on glibc, saturate on Windows). Identical results, but it preserves a bug deliberately.
  • Fix it in the binary decoder only (map to double). Text and binary results then differ for oid.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 7: How is binary numeric converted to double?

Design doc, lines 76–78

Binary numeric arrives as base-10000 digits with a weight and a scale. Accumulating them directly into a double is fast but can differ from today's atof() in the last bit; writing the digits out and calling strtod() is correctly rounded and identical to today. The prototype measures how often the fast path differs. If nobody decides, the recommended option applies.

  • (recommended) Write the digits and call strtod(): identical results, still no server-side formatting.
  • Direct accumulation, accepting rare last-bit differences, if the benchmark shows a clear gain.
  • numeric is not binary-eligible, so results with numeric stay text.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Benchmark: text vs binary result transport

Setup. A throwaway prototype (prototype.patch, branch claude/binary-transport-prototype at 5956dfb) adds the binary decoders of the design behind RPOSTGRES_RESULT_FORMAT=binary: a prepared query requests binary results when every column has a decoder, otherwise text. PostgreSQL 16.15 and libpq 16.15 (Ubuntu packages) on the same 4-vCPU cloud machine, TCP to localhost, R 4.5.3, bench 1.1.4, base main at f764ba1. dbGetQuery("SELECT * FROM t LIMIT n") on tables pre-filled with generate_series(), median of at least 5 iterations, both formats in the same R session, every binary result checked identical() to text. Code: binary-transport-bench.R, binary-transport-diff.R; raw data: results.csv; full write-up: README.md.

Binary/text ratio of the median time (below 1 means binary is faster):

  • int4: 0.97 / 0.98 / 0.90 / 0.98 at 1e3 / 1e4 / 1e5 / 1e6 rows (text at 1e6: 201 ms)
  • int8: 1.04 / 0.83 / 0.81 / 0.79 (250 ms)
  • float8: 0.89 / 0.68 / 0.65 / 0.86 (346 ms)
  • numeric(12,2), exact strtod() decoding: 1.01 / 1.07 / 1.05 / 1.05 (302 ms)
  • numeric(12,2), direct accumulation: 0.88 / 0.83 / 0.72 / 0.71
  • timestamptz: 0.85 / 0.70 / 0.68 / 0.58 (367 ms)
  • date: 0.86 / 0.89 / 1.03 / 0.98 (197 ms)
  • text, ~10 chars: 0.96 / 0.94 / 1.05 / 0.88 (569 ms)
  • text, ~200 chars: 0.94 / 1.07 / 1.01 / 0.99 (957 ms)
  • bytea, ~100 bytes: 0.78 / 0.67 / 0.67 / 0.83 (977 ms)
  • uuid: 1.12 / 1.02 / 1.05 / 1.20 (555 ms)
  • bool: 0.66 / 0.98 / 1.01 / 1.00 (182 ms)
  • wide, 20 mixed columns: 0.78 / 0.77 / 0.72 / 0.81 (4620 ms)

Memory allocation is identical in both formats. Timings at 1e6 rows rest on 5 iterations and vary by about 10% between runs.

Differential check (output): identical results for bool, int2, int4, oid (including the wrap above 2^31), int8, float8, numeric, text types, "char", json, jsonb, bytea, uuid, void, time, timetz, and dates and timestamps between years 1 and 9999 in UTC, on edge values and on 1e5 random values for float8, numeric and timestamptz. Differences: float4 widens (90% of random values, up to 6e-8 relative; question 4); infinities, BC dates and years beyond 9999 are correct only in binary (#655, fixed for text by #660); offsets with seconds (local mean time before about 1900) are off by up to 59 s in text on main, also fixed by #660; and under a non-UTC session time zone, 7 of 1e5 timestamptz values differ by one ulp. The test suite passes in binary mode except one float4 expectation in test-dbWriteTable.R.

My reading.

  • Binary is a solid but not dramatic speedup: 20–40% for timestamps, doubles, bytea, int8 and wide mixed tables, nothing for int4, date, bool and text.
  • The ceiling is the fetch loop: the whole int4 fetch costs about 200 ns per row in either format. My hypothesis, not yet profiled, is that single-row mode's one PGresult per row dominates, so decoding is only part of the cost. Once chunked rows mode (libpq 17) and the ALTREP chunk of docs: Design ALTREP-backed result columns #632 remove that overhead, binary's share of the savings grows.
  • numeric (1.05) and uuid (up to 1.2) look slightly slower, but text and binary iterations were not interleaved and runs vary by about 10%, so only the effects in the first bullet are clearly outside the noise. Both decoders build the string that text format delivers ready-made. For numeric, direct accumulation is 15–30% faster than text but differs in the last bit for values with more than about 15 significant digits (none of 1e5 numeric(12,2) values), see question 7.
  • The stronger case for binary is correctness: binary values don't depend on DateStyle, TimeZone, extra_float_digits or the text parsers' fixed positions, and infinite and BC timestamps come out right without parsing.
  • After the clean review, question 1 now recommends detecting the server before defaulting to binary, and question 6 keeps oid on text.

Generated by Claude Code

krlmlr pushed a commit that referenced this pull request Nov 29, 2026
Follow the points agreed with the binary transport design in #667:
the result format is chosen once per result at prepare time and passed to begin(),
fixed-width binary columns are stored densely at native width,
and the shared decoders of phase 1 are owned by that effort.
Update the chunk layout, memory estimates, phase plan, and the open questions on copying,
user-defined type storage, and unknown types, citing the #667 benchmark.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd4c819TffvkRZJ1V2T

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Accepted limitations

These remain after three rounds of clean review of the design and its experiment record.

  • design/binary-transport.md#L128-L129: binary support on Redshift and other PostgreSQL-compatible servers is not verified, since none was available. The "auto" default decided in question 1 keeps them on text where they can be recognized, and the connection argument is the way out for the rest. Relevance: medium for users of such servers. Confidence: high. (recorded)
  • design/binary-transport.md#L150-L153: the differential check ran on PostgreSQL 16 with UTF-8 only; the version-dependent paths (float8 before 12, numeric infinities before 14, "char" before 15) were not run. Phase 2 adds a server version matrix. Relevance: medium. Confidence: high. (recorded)
  • design/binary-transport.md#L184-L192: the benchmark did not interleave text and binary iterations and has 5 iterations at 1e6 rows, so ratios within about ±10% are noise, and the per-row overhead of single-row mode is a hypothesis, not profiled. The conclusions claim only effects outside that band. Relevance: low. Confidence: high. (recorded)
  • design/binary-transport.md#L140-L141: PostgreSQL builds with extra version text (Percona, --with-extra-version) fail the detection and stay on text, losing the speedup but not correctness. Relevance: low. Confidence: medium. (recorded)

Generated by Claude Code

@krlmlr
krlmlr marked this pull request as ready for review November 29, 2026 16:46
krlmlr pushed a commit that referenced this pull request Nov 29, 2026
Force text results on ALTREP connections in phase 2, and make phase 2b
depend on both ALTREP phase 2 and the binary switch of #667.
Decode numeric at copy in both formats, and legacy text timetz into seconds as today.
State the binary blob fallback as the one exception to OID-based storage,
give the legacy mismatch its own error, and list the stored widths per type.
Qualify the exactness of pq_text() under the legacy mapping,
and attach pq_format to the blob that pq_raw() returns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd4c819TffvkRZJ1V2T
@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

The binary format has too many drawbacks to be useful at this stage. We won't be able to fully switch:

  • Single query only
  • Unclear support across database implementations

@krlmlr
krlmlr marked this pull request as draft November 29, 2026 16:50

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Two small points from the ALTREP design (#632) for line 221 of design/binary-transport.md. The binary transport session is inactive, so I'm leaving them here for it to pick up.

  1. The "binary allowed" check is added by whichever of docs: Design binary result transport #667's phase 2 and ALTREP phase 2 lands second, so that neither merge order breaks altrep = TRUE. The current wording assumes ALTREP lands first.
  2. altrep = TRUE keeps text results even when binary was explicitly requested through the connection argument, until ALTREP phase 2b lifts that. It would help to say this explicitly.

Also, on open question 6 here: #632 treats binary oid as conditional on its answer, and oid stays text until then.


Generated by Claude Code

krlmlr pushed a commit that referenced this pull request Nov 29, 2026
Compare identity runs in the same result format and name the accepted
binary behavior changes of #667 for text-versus-binary tests.
Describe oid as today on each platform and binary oid as pending #667,
name the "binary allowed" flag, move legacy timetz to the date and time phase,
complete the width lists, and attribute the legacy error and the v2 blob to their phases.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd4c819TffvkRZJ1V2T

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants