Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .Rbuildignore
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@
^\.clang-format$
^\.ccache$
^\.clang-format-ignore$
^design$
138 changes: 138 additions & 0 deletions design/binary-transport-bench/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# Binary result transport: prototype benchmark and differential check

Experiment record for the design in [`../binary-transport.md`](../binary-transport.md) (https://github.com/r-dbi/RPostgres/pull/667).
The throwaway prototype lives on branch `claude/binary-transport-prototype` at commit 5956dfbb100e258f3c2653c8ac006df6fd9bc5fc;
its source changes are copied here as [`prototype.patch`](prototype.patch), to be applied to `main` at f764ba1818cbf41c8c57915a7a2bfdd5d0fe52f1.
The scripts expect to run from a checkout of the prototype, where they live in `bench/`.

## What the prototype does

- The environment variable `RPOSTGRES_RESULT_FORMAT=binary`, read at send time, requests results in libpq binary format.
Unset (or any other value) keeps today's text format.
- Only prepared queries (`immediate = FALSE`) switch.
After `PQdescribePrepared()`, the whole result is sent with `resultFormat = 1` if every column OID is binary-eligible,
and in text otherwise.
`immediate = TRUE` always stays text.
- Eligible: bool, int2, int4, oid, int8, float4, float8, numeric, text, varchar, bpchar, name, `"char"`, unknown, json, jsonb, void,
bytea, uuid, and date, time, timetz, timestamp, timestamptz (the date/time types only with `integer_datetimes = on`).
Anything else (money, interval, arrays, xml, inet, ...) makes the whole result fall back to text.
- Decoders in `src/PqColumnDataSource.cpp` branch on `PQfformat()` and use `PQftype()` and `PQgetlength()`.
Numeric builds an exact decimal string and parses it with `strtod()`, to stay bit-identical to `atof()` on the text form.
`RPOSTGRES_NUMERIC_DECODE=direct` switches numeric to a direct double accumulation for comparison.
Date/time arithmetic mirrors the text parser so that results match bit for bit where the text parser is correct.

## Setup and how to run

```sh
sudo apt-get install -y postgresql libpq-dev
sudo pg_ctlcluster 16 main start
sudo -u postgres psql -c "CREATE ROLE $USER SUPERUSER LOGIN PASSWORD 'pw'"
sudo -u postgres createdb -O $USER $USER
export PGHOST=localhost PGPASSWORD=pw
R CMD INSTALL -l ~/rlib-proto .
R_LIBS=~/rlib-proto Rscript bench/binary-transport-diff.R
R_LIBS=~/rlib-proto Rscript bench/binary-transport-bench.R bench/results.csv
```

The test suite runs in either mode with `RPOSTGRES_RESULT_FORMAT=binary Rscript -e 'devtools::test()'`.

## Environment

- CPU: Intel(R) Xeon(R) Processor @ 2.10GHz, 4 vCPUs (cloud container)
- PostgreSQL 16.15 (Ubuntu 16.15-0ubuntu0.24.04.1), server and client on the same machine, TCP to localhost
- libpq 16.15 (Ubuntu package `libpq5` 16.15-0ubuntu0.24.04.1)
- R 4.5.3, bench 1.1.4, RPostgres 1.4.10.9021
- Base commit: `main` at f764ba1818cbf41c8c57915a7a2bfdd5d0fe52f1

## Test suite

- Text mode: all tests pass.
- Binary mode: one failure, in `test-dbWriteTable.R` ("New table creation respects the field.types argument").
It writes `iris` into a `real` (float4) column and expects `5.1` back;
binary gives the float4 value widened to double, `5.099999904632568`.
This is the expected float4 difference below.
- In both modes, the three tests that run RPostgres in a callr subprocess
(`test-checkInterrupts.R`, two in `test-immediate.R`) need RPostgres installed in the library, and pass once it is.

## Differences between text and binary

Full output: [`diff-output.txt`](diff-output.txt).
Identical in all edge cases tested:
bool, int2, int4, oid (incl. wrap-around above 2^31 - 1, as on Linux and macOS), int8, float8 (incl. denormals, ±0, NaN, ±Inf), numeric (incl. NaN, ±Inf,
`1e400` → `Inf`, `1e-400` → `0`, negative scale, 50 significant digits), text (incl. UTF-8, 10000 chars), varchar, bpchar, name,
`"char"` (incl. NUL and high bytes, escaped as `\ooo` as `charout()` does), json, jsonb, bytea (all 256 byte values), uuid, void,
time (incl. `24:00:00`), timetz, and date/timestamp/timestamptz between years 0001 and 9999 in UTC.
Random samples of 1e5 values each are identical for float8, numeric and timestamptz in UTC.

Differences found:

- **float4**: binary returns the exact float widened to double (`0.1` → `0.10000000149011612`),
text returns the shortest decimal digits parsed as double (`0.10000000000000001`).
90226 of 1e5 random values differ, relative difference up to 6e-8.
- **date, timestamp, timestamptz `infinity` / `-infinity`**: text gives garbage (e.g. date `infinity` → 22600860 days),
binary gives `Inf` / `-Inf`.
For `timestamp` (without time zone), `fix_timezone()` (`lubridate::force_tz()`) then turns `±Inf` into `NA`.
- **Years before 0001 (BC) and after 9999**: text ignores the ` BC` suffix and assumes four-digit years, giving wrong values;
binary is correct (e.g. `10000-01-01` text → year 997, binary → 10000-01-01).
Known on `main` as https://github.com/r-dbi/RPostgres/issues/655.
- **timestamptz in a session time zone whose UTC offset has seconds** (historical local mean time,
e.g. Europe/Amsterdam `+00:19:32` in 1900, off by 32 s; America/St_Johns `-03:30:52` before 1935, off by 52 s;
Asia/Kolkata in 1900, off by 10 s; America/New_York in 1850, off by 2 s):
the text parser reads only hours and minutes of the offset, so text is off by up to 59 seconds; binary is correct.
22802 of 1e5 random timestamps (1906–2033) differ under America/St_Johns.
The text parser on `main` reads only hours and minutes of the offset; #660 (for #655) also honors `+HH:MM:SS`.
- **timestamptz in a session time zone with a nonzero offset**: last-bit rounding differences.
Text adds the fraction to the local seconds and then subtracts the offset; binary works in UTC.
`1969-12-31 23:59:59.999999+00` under America/New_York is `-1.0000003385357559e-06` in text and `-9.9999999747524271e-07` in binary.
7 of 1e5 random timestamps differ under Asia/Kolkata, by up to 6e-8 seconds in this sample (one ulp of the result, up to about 2.4e-7 s for present-day timestamps).
In UTC (the RPostgres default), there is no difference.

Numeric decoding alternatives (binary mode):

- `strtod()` on the exact decimal string: identical to text on all 1e5 random values and all edge cases.
- Direct double accumulation: 4811 of 1e5 random numerics (up to 30 significant digits) differ from `strtod()` by up to 4e-16 relative,
but none of 1e5 random `numeric(12,2)` values differ.

## Benchmark results

`dbGetQuery()` of `SELECT * FROM <table> LIMIT n`, tables pre-filled with `generate_series()`,
median of at least 5 iterations, both modes in the same R session.
Raw data: [`results.csv`](results.csv) (median, min, itr/sec, mem_alloc, iteration count, payload bytes per row).
Every binary result was checked to be `identical()` to the text result.

Payload bytes per row (field data only; length words and row headers are the same in both formats):
int4 5.9 → 4, int8 11.9 → 8, float8 18.3 → 8, numeric(12,2) 11.9 → 15.8, timestamptz 26.7 → 8, date 10 → 4,
short text 10 → 10, long text 200 → 200, bytea 202 → 100, uuid 36 → 16, bool 4.5 → 1, wide 242 → 154.

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

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

`mem_alloc` is the same in both modes for every workload, since the R vectors are the same.

## Reading

- The fetch loop costs about 200 ns per row in either format (int4, date, bool hardly move).
The hypothesis, not profiled, is that single-row mode's one `PGresult` per row dominates.
Decoding is a small share of the total, so binary saves at most about a third even where the text parser is expensive.
- Binary helps most where text parsing is expensive: timestamptz (0.6–0.7), float8 (0.65–0.85), bytea (0.67–0.83, half the bytes and no unescaping),
int8 (0.8, no `boost::lexical_cast`), and the wide mixed table (0.72–0.81).
- Binary is slightly slower for numeric with exact `strtod()` decoding (about 1.05) and for uuid (up to 1.2):
both build a string that text receives ready-made.
Direct accumulation makes numeric 0.71–0.88, at the cost of last-bit differences for values with more than about 15 significant digits.
- Timings at 1e6 rows rest on 5 iterations and vary by about 10% between runs.
- Benchmark pitfall: `LIMIT` without `ORDER BY` on large tables returned different rows between runs until `synchronize_seqscans` was turned off.
Loading