Skip to content

docs: Design ALTREP-backed result columns - #632

Open
krlmlr wants to merge 10 commits into
mainfrom
claude/altrep-columns
Open

krlmlr wants to merge 10 commits into
mainfrom
claude/altrep-columns

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

This PR records the design for returning ALTREP-backed columns from dbFetch(), before any implementation. The design is in design/altrep-columns.md. .Rbuildignore excludes the new design/ folder.

The goal, relayed from the maintainer: each dbFetch() call captures what libpq returns for the requested rows, n = Inf included, and every column is an ALTREP vector over that chunk. Double memory storage is acceptable. Numbers get the smallest R type that fits. Unknown types become blobs. "Exciting" types get an S3 class whose conversion methods can see the underlying storage.

What the design proposes:

  • Capture: Each fetch copies the cells libpq returns into one chunk of R-owned raw blocks, so R's garbage collector sees the memory. The chunk is independent of the result and the connection, so columns stay valid after dbClearResult() and dbDisconnect().
  • ALTREP views:
    • Elt and Get_region parse lazily, and Dataptr and Set_elt materialize.
    • Duplicate and Extract_subset return new views on the same chunk, so attribute changes and subsetting stay lazy.
    • The ALTREP methods keep no C++ objects alive across R API calls.
    • saveRDS() writes plain vectors.
  • Types:
    • int2 and int4 become integer. oid and int8 become double, with exact values available through pq_text(); an explicitly set bigint is still honored.
    • bytea and unmapped built-in types become blobs.
    • User-defined and other "exciting" types get a pq_vctr class with pq_text(), pq_raw(), pq_type() and pq_convert().
    • A type cache miss triggers a new catalog lookup, which addresses User defined ENUM types are NA #509. The lookup is designed so that it does not destroy the unnamed prepared statement.
  • Opt-in: ALTREP is opt-in through dbConnect(altrep = TRUE). The new type mapping can be switched separately from laziness.
  • Result format:
    • The design works with the binary result format being added in docs: Design binary result transport #667, which is chosen per result. docs: Design binary result transport #667 has since said binary cannot fully replace text; question 15 asks how much of this alignment stays.
    • Fixed-width columns are stored densely in native form: as received in binary results, and decoded at copy time in text results (question 14).
    • Variable-width columns and numeric keep their captured bytes, and a pq_format attribute records whether these bytes are text or binary.
    • altrep = TRUE connections get text results until ALTREP phase 2b adds binary support.
    • libpq 17's chunked rows mode is an optional speedup.
  • Phases:

Related: #509, #455, #444, #182, #526, #539, #638, #667.

The design went through three rounds of clean review, and its alignment with #667 through three more. Every finding is addressed in the doc. The open questions are numbered 1–15 and posted as separate comments below. Two more comments ask whether to open issues for bugs on main found along the way: the oid overflow, and zero-row immediate = TRUE results that have no columns.

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

https://claude.ai/code/session_01Hr1rd4c819TffvkRZJ1V2T


Generated by Claude Code

Add a design document for returning ALTREP columns from dbFetch(),
each referencing a chunk that holds what libpq returned for the requested rows.
It covers the data flow, the R storage per PostgreSQL type,
an S3 class for types without a native mapping,
interaction with bigint, dbBind(), immediate queries, lifetime, and serialization,
a phased implementation plan, and open questions.

The design folder is excluded from the package build.

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

Question 1: How is int8 represented, given the existing bigint argument?

Design doc, lines 899–910

Today, int8 is always parsed into integer64 and converted in R afterwards, according to the connection's bigint argument (default "integer64"). The request asks for doubles for types wider than 32 bits. When #182 was closed, the suggestion was an ALTREP-based view with conversion after fetching, so the design drops the per-query bigint argument. In both result formats, the chunk stores int8 as int64. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) In the new mapping, int8 becomes double by default. Exact values stay available from the captured bytes through pq_text() or pq_as_integer64(), and dbFetch() warns when values beyond ±2^53 lose precision. A bigint passed explicitly to dbConnect() is still honored, and the legacy path is unchanged. This matches the request and per-query bigint option #182, but changes today's default for users who switch to the new mapping without setting bigint.
  • Keep integer64 as the default, as today, applied in C++ when the column is created. This departs from the request.
  • Choose the type per chunk from the values: integer if every value fits, else double, else integer64. Not recommended, because a column's type could then change between dbFetch() calls on one result.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 2: Which types count as "exciting" and get the pq_vctr class?

Design doc, lines 911–921

An "exciting" type gets the pq_vctr class, with pq_text(), pq_raw(), pq_type() and pq_convert(). An "unknown" type becomes a blob. The line between the two decides what extension packages like sf, and users with enums or arrays (#455, #444), will see. This question now also covers whether enums should be plain character (#455). If nobody decides, the work goes ahead with the recommended option.

  • (recommended) A static list of built-in types (money, timetz, interval, uuid, json, jsonb, xml, network types, ranges, and arrays of built-in types) plus every user-defined type (enums, composites, their arrays, extension types). Built-in OIDs that are in neither table count as unknown and become blobs. This follows the request. Enums keep a class, although Option to convert "enum" types to factor or character? #455 asks for plain character.
  • Only enums, arrays, JSON, uuid and interval are exciting. Everything else, extension types included, becomes a blob with the class.
  • Only enums and arrays. Everything else keeps today's pq_<typname> character columns. This departs from the request for unknown types.
  • Enums as plain character, with the type visible only through dbColumnInfo(). This departs from the request, but it is what Option to convert "enum" types to factor or character? #455 asks for.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 11: When are columns materialized, and how long does the captured data live?

Design doc, lines 993–999

The request accepts double memory storage. Copying a column or changing its attributes does not materialize it: Duplicate returns a new ALTREP view on the same chunk, and Extract_subset keeps head() and [ lazy. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) Materialize a column only on Dataptr or Set_elt. Keep the chunk until every view that references it has been garbage collected, accepting double memory as the request does.
  • Also free a column's blocks as soon as every view of it is materialized. This removes the double storage but needs bookkeeping per column. It could be a follow-up if benchmarks show the need.
  • Materialize every column when the result is cleared, so chunks never outlive the result. This gives up laziness in the common dbGetQuery() case and departs from the request.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 3: Which R version is required?

Design doc, lines 922–927

DESCRIPTION says R ≥ 3.1.0 today. ALTREP exists from R 3.5.0, and ALTREP lists from R 4.3.0 (confirmed in R's NEWS). That ALTREP logical and raw classes need R 3.6.0 is not checked yet. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) Require R ≥ 3.6.0. List columns are lazy on R ≥ 4.3.0 and eager on older versions. The only departure from the request is that list columns are not lazy on old R.
  • Require R ≥ 4.3.0. Every column type is then lazy, and no fallback code is needed.
  • Keep R ≥ 3.1.0 and compile the ALTREP code only on R ≥ 3.5.0, with the old path kept for older R. This departs from the request on R < 3.5.0, where no column is ALTREP.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 5: Is ALTREP opt-in first, or the default right away?

Design doc, lines 936–941

Each phase is its own PR. An opt-in period lets each one merge without affecting existing users. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) Opt in through a dbConnect(altrep = TRUE) connection argument, which an option can also set, during phases 2–7. It becomes the default in phase 8, after a reverse dependency check. The request describes ALTREP as the behavior, so this departs from it only in timing.
  • The default from phase 2, with the old path as an opt-out.
  • Opt in per fetch only (dbFetch(altrep = TRUE)), never per connection.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 4: How is numeric (decimal) represented?

Design doc, lines 928–935

Under "whatever type is necessary to fit", numeric has no exact R type. Today it becomes double. In the design, a numeric column is decoded into a double in both result formats and also keeps its captured bytes. If nobody decides, it stays double.

  • (recommended) Double, as today. Exact values are available from the captured bytes through pq_text() while the column is still an RPostgres ALTREP vector. This only roughly fits "whatever type is necessary to fit", because doubles cannot hold every decimal exactly.
  • Use PQfmod(): integer for numeric(p, 0) with p <= 9, double otherwise. This changes the type of existing columns.
  • An exciting type: class pq_numeric over double storage. Risky, because arithmetic results keep the class.
  • Character. Always exact, but breaks most existing code, and departs from the request, which asks for numbers to be stored as numbers.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 12: Do unknown types become blob::blob or a plain list of raw vectors?

[Design doc, lines 1000–1007](https://github.com/r-dbi/RPostgres/pull/632/files#diff-082d1abe791d877c0d1afad61aae06177523e588bfc0caf9c30cae61458bc59aR1000-R1007)

The request says "lists of raw or blobs". Which types count as unknown depends on questions 2 and 9. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) blob::blob, with the pq_vctr classes in front. RPostgres already imports blob, and blob prints well and works with vctrs. The blob holds the bytes as captured. Unknown types force a text result (docs: Design binary result transport #667), so these are text bytes. The exception is the v2 blob from phase 6 (a type at execution with no binary decoder, in a binary result), which holds binary bytes. The pq_format attribute tells the two apart.
  • A plain list of raw vectors with only the pq_vctr classes. This avoids depending on blob's internals for ALTREP lists.
  • Character storage of the text output, as today. This departs from the request.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 8: Does the chunk copy cell bytes, or keep the PGresults?

Design doc, lines 959–968

The request says each fetch "captures whatever libpq returns and holds it". The current code uses single-row mode, where libpq returns one PGresult per row. The row-sink interface in #638 never lets the sink own a PGresult. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) Copy into R-owned blocks, so the sink never keeps a PGresult. This works in single-row mode, keeps to the sink contract, and is visible to the garbage collector (question 7). Fixed-width columns are stored densely at native width: as received in binary results (docs: Design binary result transport #667), and decoded in text results (question 14). The copy is therefore about as small as the values themselves. In chunked rows mode, only fetch_into() keeps the one partly consumed PGresult. This departs from "holds whatever libpq returns" in two ways: the bytes are held as a copy, and fixed-width text cells are held decoded (question 14).
  • Keep the PGresults when chunked rows mode (libpq ≥ 17) is available, and copy only in single-row mode. This saves one copy, but needs a change to the sink contract.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Should enums be plain character by default (#455)?

This question is now one of the options of question 2, "Which types count as exciting". Please answer it there.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: Open an issue for the oid overflow found while designing?

While writing the design, we found that oid columns overflow for values above 2^31 − 1. PqResultImpl.cpp maps oid (OID 26) to DT_INT, and PqColumnDataSource::fetch_int() parses it with atoi(). But oid is unsigned 32-bit. The design maps oid to double, so phase 1 would fix it on the ALTREP path; the current path stays broken. A search of the issues for oid found no existing report. The closest are #469 (stale Redshift OIDs) and #509.

Reprex with the CRAN version 1.4.10 against PostgreSQL 16:

library(DBI)
# PG* environment variables supply host, port and user
con <- dbConnect(RPostgres::Postgres())
res <- dbGetQuery(con, "SELECT 4000000000::oid AS x, 2147483648::oid AS y, 123::oid AS z")
str(res)
#> 'data.frame':    1 obs. of  3 variables:
#>  $ x: int -294967296
#>  $ y: int NA
#>  $ z: int 123
# Expected: x = 4000000000, y = 2147483648, z = 123 (oid is unsigned 32-bit)
dbDisconnect(con)

Created on 2026-11-29 with reprex v2.1.1

The value 4000000000 wraps around without any warning. Severity: Low, since OIDs above 2^31 are rare in user queries but do occur in system catalogs on long-lived clusters. If nobody decides, nothing is opened, and the fix arrives with ALTREP phase 1.

  • (recommended) Open an issue with this reprex, and fix it on the current path in a separate small PR that maps oid to double.
  • Open an issue only, and let ALTREP phase 1 fix it.
  • Neither, and let phase 1 fix it silently.

Generated by Claude Code

Describe the row-sink interface agreed with the Arrow effort as phase 0,
and move the parser extraction ahead of the first ALTREP phase.
Keep chunk memory in R-owned raw blocks with a specified layout,
and correct the memory, interrupt, and chunked rows mode analysis.
Re-prepare the unnamed statement after a catalog lookup,
move the type cache into C++, and keep storage stable for unresolved types.
Specify ALTREP methods per class, per-instance state, lazy duplication and subsetting,
and the exception, longjmp, warning, and thread-safety rules.
Separate the type mapping switch from laziness and list the expected differences.
Make int8 a double by default in the new mapping, following the closing comment of #182,
and add open questions on garbage collector visibility, the type mapping switch, storage of unresolved types,
and the catalog lookup.

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

Question 6: Do the type mapping changes get their own switch, separate from laziness?

Design doc, lines 942–949

The new mapping changes several column types: oid and int8 become double, money, uuid, interval, JSON and others become pq_vctr, and unknown types become blobs. If one switch controls both the mapping and laziness, tests can no longer check that lazy columns match today's results. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) Yes: a type_mapping = c("legacy", "v2") argument to dbConnect(), defaulting to "v2" when altrep = TRUE and to "legacy" otherwise. Laziness can then be tested against today's results, and users can adopt laziness without the type changes. The default combination matches the request.
  • One switch: altrep = TRUE always implies the new mapping. Simpler for users, but the identity tests are then impossible, and every ALTREP bug looks like a type change.
  • The new mapping is independent of ALTREP and on by default right away. A breaking change outside the scope of the request.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 7: How does R's garbage collector see chunk memory?

Design doc, lines 950–958

The ALTREP columns are tiny R objects. If the captured data lives outside R's heap, R never comes under pressure to collect them, and a loop of large dbGetQuery() calls can grow the process without bound. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) All chunk memory (blocks, indices and metadata) lives in R vectors owned by one R list, which the data1 of every column's view references. No external pointer or C finalizer is needed. R counts this memory toward its heap, so a loop of large queries triggers collections and memory stays bounded. An interrupted fetch leaves only collectable R objects behind.
  • malloc()-ed buffers behind an external pointer, which the collector cannot see. A loop of large queries can grow memory until some unrelated collection happens. Calling R_gc() after large fetches would help, at a cost in time.
  • Keep the PGresults themselves. This only works in chunked rows mode and has the same visibility problem as malloc().

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 9: Which storage do user-defined types get, so it does not change once an immediate = TRUE type is resolved?

Design doc, lines 969–984

With immediate = TRUE, there is no description before the results arrive. A type created after dbConnect() may therefore be unresolved on the first query and resolved on the next. If storage followed resolution, the same query would first return a blob and then a character column. Domains are not affected, because the server reports their base type (checked against PostgreSQL's printtup.c). If nobody decides, the work goes ahead with the recommended option.

  • (recommended) Storage depends on the OID alone. Every user-defined OID gets character storage with the pq_vctr classes, whether resolved or not; resolving it only adds pq_<typname> and pq_<kind>. These types have no binary decoder, so their results are text (docs: Design binary result transport #667) and their captured bytes are text. There is one exception. In the v2 mapping (phase 6), a column in a binary result whose type at execution differs from the prepare-time description, and which has no binary decoder, is stored as a blob with pq_format = "binary", whatever its OID. The legacy mapping raises an error in that case (phase 5). This departs from the request in that unknown user-defined types are character, not blobs. Blobs remain for bytea and for built-in types without a mapping.
  • The same rule, but with blob storage for every user-defined OID. This matches the request literally, but enums and arrays print as blobs until pq_convert() is called, which makes Option to convert "enum" types to factor or character? #455 worse.
  • Storage follows resolution: a blob while unresolved, the mapped storage once resolved. The first immediate = TRUE query after creating a type then returns a different type from the next one.
  • For single-statement immediate = TRUE queries with an unknown OID, describe the statement first to resolve the types. This adds round trips, and defeats the purpose of immediate = TRUE with connection poolers.

Generated by Claude Code

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question 10: How does the catalog lookup on a type-cache miss avoid destroying the prepared statement?

Design doc, lines 985–992

RPostgres prepares every query as the unnamed statement "" and executes it once per dbBind() group. Any catalog query sent in between destroys that statement. The lookup is needed to fix #509, where types created after dbConnect() show up as pq_NA. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) Run the lookup, then prepare the user query as "" again and compare the description. This costs two extra round trips, only on a miss, and uses no named statements that could clash with connection poolers.
  • Prepare the lookup as a named statement (for example rpostgres_typlookup) and run it with PQexecPrepared(). This keeps "" intact, but the statement must be created once per connection, and named statements do not survive transaction-mode poolers.
  • Prepare every user query under a name instead of "", and deallocate it in dbClearResult(). This changes the behavior of every query and interacts with poolers.

Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question: Open an issue for zero-row immediate = TRUE results having no columns?

Found while reviewing the row-sink seam in #638. An immediate = TRUE query whose first result has zero rows returns a data frame with no columns, and dbColumnInfo() is empty. The cause is in PqResultImpl.cpp (around lines 487–490 on main): the code returns early on PGRES_TUPLES_OK, before the column cache is filled, so the result is also treated as a statement. The ALTREP sink would inherit this. A search for "immediate zero rows" and "columns empty immediate" found no existing issue.

Reprex with the CRAN version 1.4.10 against PostgreSQL 16:

library(DBI)
con <- dbConnect(RPostgres::Postgres())
q <- "SELECT 1::int AS a, 'x'::text AS b WHERE false"
# Expected: 0 obs. of 2 variables (a: int, b: chr), as without `immediate`
str(dbGetQuery(con, q, immediate = TRUE))
#> Warning: Don't need to call dbFetch() for statements, only for queries
#> 'data.frame':    0 obs. of  0 variables
str(dbGetQuery(con, q))
#> 'data.frame':    0 obs. of  2 variables:
#>  $ a: int 
#>  $ b: chr
res <- dbSendQuery(con, q, immediate = TRUE)
# Expected: 2 rows (a, b) of column info, and a 0-row, 2-column data frame
dbColumnInfo(res)
#> [1] name     type     .oid     .known   .typname
#> <0 rows> (or 0-length row.names)
str(dbFetch(res))
#> Warning: Don't need to call dbFetch() for statements, only for queries
#> 'data.frame':    0 obs. of  0 variables
dbClearResult(res)

Severity: Medium. Code that relies on column names, such as a dplyr::collect() of an empty filter through a pooler that needs immediate = TRUE, gets a frame without columns. If nobody decides, nothing is opened, and the fix arrives with the ALTREP sink.

  • (recommended) Open an issue with this reprex, and fix it on main in a separate small PR that fills the cache before the early return.
  • Open an issue only, and let the ALTREP work fix it.
  • Neither.

A second observation from the same review is not proposed as an issue. When an interrupt hits the check that runs every 1024 rows during dbFetch(), the rows fetched so far are lost and the query keeps running. The result stays usable, though: a further dbFetch() returns rows, and the next query cancels the old one with a warning. That looks like acceptable behavior rather than a bug.


Generated by Claude Code

@krlmlr krlmlr mentioned this pull request Nov 29, 2026
3 of 9 tasks
Compute No_NA from NA-producing cells, including NaN and integer overflow,
and keep all chunk and view state in R objects, so no C finalizer is needed.
Limit the new warnings to the new type mapping, to keep the legacy results identical.
Write the row sink against the begin() signature proposed on #638,
leave interrupt checks to fetch_into(), and amend the sink contract for chunked rows mode.
Chain fixed-size index blocks, note the _cache changes in phase 5,
drop the domain special case because the server reports base types,
and add an open question on fixing the type cache on the default path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd4c819TffvkRZJ1V2T
Describe the row sink exactly as #638 provides it:
begin() with names, OIDs, type modifiers, and types from the column cache,
fetch_into() without a row limit, and interrupt checks in the fetch loop.
Define NA-producing cells by the storage type's NA, including the legacy NAs,
grow the chained data and index blocks geometrically, and state the fixed cost per column.
Gate chunked rows mode on the build alone, with every sink adapted first,
and add the rules for duplicating views and the attributes the sink sets.

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

Question 13: Do the C++ type cache and the refresh on a miss (phase 5) also apply to the default path, altrep = FALSE?

[Design doc, lines 1008–1015](https://github.com/r-dbi/RPostgres/pull/632/files#diff-082d1abe791d877c0d1afad61aae06177523e588bfc0caf9c30cae61458bc59aR1008-R1015)

Phase 5 moves the type cache from the conn@typnames snapshot into C++, and looks types up again on a miss. That fixes #509, where types created after dbConnect() show up as pq_NA. The open choice is whether users who have not opted in get this fix too. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) Yes. Fix User defined ENUM types are NA #509 on the default path deliberately in phase 5, with a NEWS.md entry. Default-path users then see pq_<typname> instead of pq_NA for types created after dbConnect(), and only a cache miss costs the extra round trips of question 10. This goes beyond the request, which is about the ALTREP path, and changes classes on the default path.
  • No. Only use the refresh and the C++ lookup with altrep = TRUE, and keep the default path on the conn@typnames snapshot. The default path then stays exactly as today, pq_NA bug included, until the default switch in phase 8. This keeps strictly to the request's scope, at the cost of two code paths for type lookup.

Generated by Claude Code

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
Store fixed-width text cells decoded in the dense layout, as a new open question,
so that each cell is parsed once and NA flags and warnings are exact.
Keep binary eligibility independent of the type mapping, and add a timetz formatter instead.
Do the int8 conversions from the decoded int64 in phases 2 and 3,
move binary results into their own phase after the binary switch,
and specify pq_text(), pq_raw(), and the pq_format attribute under both formats.
Handle execution types without a binary decoder per mapping, and align the warning rules.

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

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question 14: Are fixed-width text columns decoded into native form at copy time?

[Design doc, lines 1016–1031](https://github.com/r-dbi/RPostgres/pull/632/files#diff-082d1abe791d877c0d1afad61aae06177523e588bfc0caf9c30cae61458bc59aR1016-R1031)

With binary results (#667), fixed-width columns such as int4, float8 and timestamps arrive in native form and are stored densely. Text results are needed for immediate = TRUE queries, for results with types that have no binary decoder, and on altrep = TRUE connections until phase 2b. The choice is whether to decode their fixed-width cells once while copying, or to keep the text and parse it lazily. The request suggests parsing is deferred. If nobody decides, the work goes ahead with the recommended option.

  • (recommended) Yes. append() decodes each fixed-width cell of a text result once and stores the value in the dense layout, as for a binary result. This means one parse per cell and an accurate No_NA, and decoder failures and range warnings are raised by dbFetch(). Memory use for text results comes close to binary results: the same for int4, int8, float8, time and the timestamps. It is larger for bool, int2, float4, date and v2 oid, which are stored at R's width, and smaller for legacy timetz. The text bytes are kept only where pq_text() needs them for exactness (numeric). This departs from "holds whatever libpq returns" in that these text cells are held decoded and are not parsed lazily. Creating the R objects is still deferred.
  • No. Keep the text bytes in the offsets layout and parse lazily in Elt and Get_region. No_NA then reports "unknown" for text numeric columns. The warnings that need values (bigint range, money failures) require one extra pass in dbFetch(), over the affected columns only. Parsing is deferred as the request implies. The cost is parsing warned columns twice, and 16 to 20 bytes per int4 cell.

Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Question 15: How much of the binary-format alignment stays in the design?

The design (head 34f90a1, plus a merge of main that resolves a .Rbuildignore conflict) was aligned with the binary result transport of #667. Since then, #667 says that binary has too many drawbacks to be useful at this stage and cannot fully replace text: single queries only, and unclear support across database implementations. The design already assumes text for immediate = TRUE, for types without a binary decoder, and on altrep = TRUE connections until phase 2b. So it works without binary, but phase 1 has no owner and some sections no longer fit. Other changes since the design was written: #660 (dates and timestamps) is merged, which phase 1 carries; #659 (money) is closed unmerged, with the advice to cast money in queries, so legacy money keeps today's behavior. If nobody decides, the next session goes ahead with the recommended option.

  • (recommended) Keep text as the only format the ALTREP design needs. Phase 1 returns to this PR as a text-only extraction of the decoders (format, bytes, len) that return a status. The dense layout for fixed-width columns stays, through question 14. Phase 2b and the "binary allowed" flag move to an appendix, "If binary transport lands", that keeps the agreements with docs: Design binary result transport #667.
  • Remove every binary part from the design, going back to text-only as of 67540c8 while keeping question 14 and the later fixes.
  • Keep the design as it is, waiting for a decision on docs: Design binary result transport #667.

This session is archived after this comment. The design doc, the 14 questions above and this one, and the two issue questions are the durable state. A new session picks up from here.


Generated by Claude Code

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