Skip to content

feat(postgres): prepare dump import reader and isolation spike - #399

Open
clvsh wants to merge 5 commits into
mainfrom
feat/postgres-import-351
Open

clvsh wants to merge 5 commits into
mainfrom
feat/postgres-import-351

Conversation

@clvsh

@clvsh clvsh commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Related to #351.

This branch establishes the PostgreSQL dump reader and isolation feasibility work for a future pv postgres:import / pv pg:import command.

  • Adds a bounded, read-only postgres-import reader with PostgreSQL parser checks and snapshot coverage for plain SQL, COPY framing, quoted identifiers, and hostile psql commands.
  • Adds PostgreSQL 17.11 / 18.6 dump fixtures and disposable-container probes for multi-database role isolation, HBA rules, and ownership cleanup.
  • Records the agreed import policy in DESIGN.md and the feasibility findings in docs/superpowers/specs/2026-09-23-postgres-import-feasibility-spike.md.
  • Updates the PostgreSQL artifact recipe to 17.11 / 18.6 and packages pg_restore.

This is a draft because it does not yet implement the import command, complete statement policy, database mapping, script transformation, or production HBA lifecycle and crash recovery. Dump inspection does not authorize execution. Native macOS artifact smoke testing also remains necessary.

Existing reader snapshots and reproduction scripts are included in the branch. Tests were not rerun during repository cleanup; no implementation changes were made while opening this PR.

Summary by CodeRabbit

  • New Features
    • Added PostgreSQL dump format detection and plain-dump inspection, including checks for unsupported or unsafe commands before SQL is executed.
    • PostgreSQL artifacts now include pg_restore, supporting inspection of restore archives.
  • Updates
    • Updated PostgreSQL 17 and 18 artifacts to versions 17.11 and 18.6.

@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 59 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: QUIET
  • Plan: Advanced
  • Run ID: 22a3692f-0e1c-431f-900e-c3cc37d8eaf7
Commits

Reviewing files that changed from the base of the PR and between 4a35676 and e56b830.

Files ignored due to path filters: 21

  • Cargo.lock is excluded by !**/*.lock
  • crates/postgres-import/tests/snapshots/reader__copy_data_requires_its_exact_terminator.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__copy_options_that_change_data_framing_are_rejected.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__generated_dumps_frame_without_treating_data_as_commands.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__hostile_meta_commands_fail_before_execution.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__nested_comments_dollar_quotes_and_crlf_are_framed.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__postgres_parser_marks_security_definer_functions.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__postgres_scanner_exposes_database_identifier_byte_spans.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__regular_file_format_is_detected_from_contents.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__restriction_key_must_match_and_close.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__server_side_copy_program_is_rejected.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__very_large_copy_row_does_not_hit_statement_limit.snap is excluded by !**/*.snap
  • crates/pv-release/tests/it/snapshots/it__smoke__postgres_linux_build_packages_relocatable_elf_and_rejects_newer_glibc.snap is excluded by !**/*.snap
  • it/fixtures/postgres-import/17.11/directory/3498.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/17.11/directory/3499.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/17.11/directory/blob_16438.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/17.11/directory/toc.dat is excluded by !**/*.dat
  • it/fixtures/postgres-import/18.6/directory/3516.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/18.6/directory/3517.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/18.6/directory/blob_16440.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/18.6/directory/toc.dat is excluded by !**/*.dat
Files selected for processing: 32

  • .github/workflows/ci.yml
  • CONTRIBUTING.md
  • Cargo.toml
  • DESIGN.md
  • crates/postgres-import/Cargo.toml
  • crates/postgres-import/src/lib.rs
  • crates/postgres-import/src/reader.rs
  • crates/postgres-import/tests/reader.rs
  • crates/pv-release/tests/it/smoke.rs
  • docs/superpowers/specs/2026-09-23-postgres-import-feasibility-spike.md
  • it/fixtures/postgres-import/.gitattributes
  • it/fixtures/postgres-import/17.11/all.sql
  • it/fixtures/postgres-import/17.11/create.sql
  • it/fixtures/postgres-import/17.11/custom.dump
  • it/fixtures/postgres-import/17.11/directory/blobs_3501.toc
  • it/fixtures/postgres-import/17.11/plain.sql
  • it/fixtures/postgres-import/17.11/tar.dump
  • it/fixtures/postgres-import/18.6/all.sql
  • it/fixtures/postgres-import/18.6/create.sql
  • it/fixtures/postgres-import/18.6/custom.dump
  • it/fixtures/postgres-import/18.6/directory/blobs_3519.toc
  • it/fixtures/postgres-import/18.6/plain.sql
  • it/fixtures/postgres-import/18.6/tar.dump
  • it/fixtures/postgres-import/generate.sh
  • it/fixtures/postgres-import/hostile.sql
  • it/fixtures/postgres-import/isolation.sh
  • it/fixtures/postgres-import/source.sql
  • release/artifacts/recipes/postgres/THIRD-PARTY-NOTICES
  • release/artifacts/recipes/postgres/build.sh
  • release/artifacts/recipes/postgres/recipe.toml
  • release/artifacts/recipes/postgres/smoke.sh
  • scripts/linux/builder.Dockerfile
Walkthrough

The change adds a crate that detects PostgreSQL dump formats and inspects plain dumps without executing SQL. It also adds import-policy documentation, PostgreSQL fixtures and isolation probes, and packages pg_restore in updated PostgreSQL artifacts.

Changes: PostgreSQL import preparation

Layer / File(s) Summary
Import policy and reader API
DESIGN.md, Cargo.toml, crates/postgres-import/*
The design documents planned import mapping, filtering, and isolation rules. The workspace adds a crate with public dump-format detection and plain-dump inspection APIs.
PostgreSQL dump fixtures
it/fixtures/postgres-import/*, docs/superpowers/specs/2026-09-23-postgres-import-feasibility-spike.md
Fixtures cover PostgreSQL 17.11 and 18.6 dump formats, database objects, hostile input, and fixture generation. The feasibility report records parser and fixture observations.
Plain-dump scanning and validation
crates/postgres-import/src/reader.rs, crates/postgres-import/tests/reader.rs
The reader scans SQL statement boundaries and validates COPY framing and supported psql commands. Tests cover dump fixtures, malformed or unsupported inputs, and framing edge cases.
Restricted-role isolation probe
it/fixtures/postgres-import/isolation.sh, docs/superpowers/specs/2026-09-23-postgres-import-feasibility-spike.md
The script tests database access limits, role restrictions, persistence after role cleanup, and HBA restoration. The feasibility report lists remaining requirements for import execution.
PostgreSQL artifact and restore-tool packaging
release/artifacts/recipes/postgres/*, crates/pv-release/tests/recipe_fixtures.rs, crates/pv-release/tests/recipe_metadata.rs, crates/pv-release/tests/smoke.rs
The artifact includes and validates pg_restore. PostgreSQL tracks advance to 17.11 and 18.6 with revision pv1, and the recipe tests reflect those updates.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature

Merge Risk: Low · previous review 4a356

The new dump reader can misframe some hand-written SQL dumps when an identifier ends in E before a quote. The change only inspects dumps and does not run an import, so the impact is narrow; fix it before relying on the reader for import preflight.

Security architecture risk: Low · up to 4a356

The new reader does not execute dumps or connect to databases, which substantially limits current exposure. Its per-command limits do not bound the memory retained across an entire dump. Import execution remains explicitly deferred until statement policy, database mapping, isolation, and recovery controls are implemented.

Retained concerns

  • Low · security · observed: The new inspection API lacks a dump-wide memory boundary: each accepted connection or encoding directive appends another string to DumpSummary. Repeated valid directives can therefore exhaust the invoking process despite the 1 KiB command and 8 MiB statement limits. This contradicts the stated bounded-memory reader property. No production caller or remotely reachable invocation was established, so current exposure is limited to callers that explicitly invoke this new API.
Security review details

Security Blast Radius

  • inferred — The demonstrated inspection risk is confined to resource consumption in the invoking process. No production consumer or execution-capable dependency was established for the new API, so this assessment does not infer access to project databases, track-wide superuser privileges, host command execution, or cross-project data.

Security Findings and Attack Paths

  • observed — Repeated valid encoding or connection commands outside a restriction append heap-allocated strings without an aggregate limit. An attacker who can supply a dump to an invoking caller can drive growing memory consumption. Per-command checks and streamed COPY rows constrain individual buffers but do not contain this path; external reachability is not established.

Trust Boundaries and Controls

  • observed — The implemented boundary rejects unsupported psql commands, connection parameters outside its accepted database-name forms, server-file/program COPY, and framing-changing COPY options. Parsing remains distinct from SQL-effect authorization and database isolation; a restricted database role would not itself constrain client-side psql commands.

Resilience and Maintainability Implications

  • observed — Fixture scripts use process-owned container cleanup traps and explicit final removal, without published host ports or host mounts. Abrupt process loss can bypass cleanup and leave a running fixture container; default container networking is not explicitly disabled. This is bounded fixture-environment exposure, not evidence that production import roles or HBA rules can be stranded.

Hardening Proposals

  • proposed — Define an explicit inspection budget for retained summary entries and bytes, and document how callers bound total input and processing time. Budget exhaustion should return a typed error rather than relying on per-statement limits to imply dump-wide containment.
  • proposed — Before connecting this reader to execution, preserve the documented fail-closed gate and verify the complete role/HBA lifecycle under interruption, retries, concurrent imports, and recovery. Ownership reassignment must remain conditional on statement policy preventing privilege inheritance through SECURITY DEFINER objects.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 10 files. (15 skipped… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)

Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main changes: preparing the PostgreSQL dump import reader and isolation feasibility spike.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 10 files. (15 skipped: 15 unsupported.)

Finishing Touches

Resolve merge conflicts

  • Resolve merge conflict in branch feat/postgres-import-351
🧪 Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The archive prerequisite still cannot render default-compressed custom dumps, the reader rejects SQL-standard function bodies emitted by pg_dump, and the IPv6 probe can pass without proving HBA isolation.

Reviewed changes Full review of the reader, feasibility evidence, fixtures, design policy, and PostgreSQL artifact prerequisites in this draft.

  • Dump inspection: A standalone postgres-import crate frames SQL, supported psql commands, and streamed COPY data, with PostgreSQL parser checks and snapshot coverage.
  • Isolation evidence: PostgreSQL 17.11/18.6 dump corpora and disposable-container scripts exercise multi-database connections, restricted roles, HBA rules, and ownership cleanup.
  • Import policy: DESIGN.md and the feasibility report define the future mapping and safety boundary while explicitly deferring execution policy, transformation, CLI integration, and production lifecycle recovery.
  • Artifact prerequisites: PostgreSQL recipes advance to 17.11/18.6, declare and validate pg_restore, and update release tests and snapshots.

Validation passed for all 11 reader tests, 27 release metadata/fixture tests, 13 runnable PostgreSQL smoke tests, reader Clippy, formatting, and the new fixture scripts' ShellCheck. The remaining PostgreSQL dependency-contract test failed with error: missing required command: codesign; native macOS artifact smoke and the committed Docker probes were not run. Temporary native PostgreSQL probes reproduced the framing failure and the IPv6 false-positive mechanism. No production-import omissions are flagged because they are explicitly outside this draft's scope.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

Comment thread crates/postgres-import/src/reader.rs Resolved
@clvsh
clvsh marked this pull request as ready for review October 8, 2026 00:55
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T03:45:45.126330Z e56b830 New commits
🔒 Security Review ✅ Completed 2026-10-08T00:57:58.961448Z 4a35676 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

Quiet mode is enabled, so only the most important comments were posted inline. Other review comments are grouped below.

🟡 Other comments (1)
crates/postgres-import/src/reader.rs (1)

286-289: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Single-quote escape detection misreads identifiers that end in E.

The escape flag is set whenever the byte before ' is E or e. The check does not confirm that this byte starts a new token. For example, in SELECT name'x' or WHERE type='a\', the code does not apply this rule correctly. In the e' case, the identifier name followed directly by ' puts the scanner into backslash-escape mode. A literal ending in \' then keeps the scanner inside the string, so the reader joins the following statements together. Such input is uncommon in pg_dump output, but hand-written plain dumps can contain it. Set escape only when the byte before the E/e is not an identifier character.

🐛 Proposed fix
-                        let escape = statement
-                            .get(statement.len().saturating_sub(2))
-                            .is_some_and(|previous| matches!(previous, b'E' | b'e'));
+                        let len = statement.len();
+                        let escape = len >= 2
+                            && matches!(statement[len - 2], b'E' | b'e')
+                            && (len < 3
+                                || !(statement[len - 3].is_ascii_alphanumeric()
+                                    || matches!(statement[len - 3], b'_' | b'$')
+                                    || statement[len - 3] >= 0x80));

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: QUIET
  • Plan: Advanced
  • Run ID: 3e2b4eb2-1ca2-4017-aa03-610f7c1513ce
📥 Commits

Reviewing files that changed from the base of the PR and between 9dc5de3 and 4a35676.

⛔ Files ignored due to path filters (23)
  • Cargo.lock is excluded by !**/*.lock
  • crates/postgres-import/tests/snapshots/reader__copy_data_requires_its_exact_terminator.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__copy_options_that_change_data_framing_are_rejected.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__generated_dumps_frame_without_treating_data_as_commands.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__hostile_meta_commands_fail_before_execution.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__nested_comments_dollar_quotes_and_crlf_are_framed.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__postgres_parser_marks_security_definer_functions.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__postgres_scanner_exposes_database_identifier_byte_spans.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__regular_file_format_is_detected_from_contents.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__restriction_key_must_match_and_close.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__server_side_copy_program_is_rejected.snap is excluded by !**/*.snap
  • crates/postgres-import/tests/snapshots/reader__very_large_copy_row_does_not_hit_statement_limit.snap is excluded by !**/*.snap
  • crates/pv-release/tests/snapshots/recipe_fixtures__recipe_fixture_generation_validates_archives_records_and_manifest.snap is excluded by !**/*.snap
  • crates/pv-release/tests/snapshots/smoke__postgres_build_recipe_packages_pv1_supplied_extensions.snap is excluded by !**/*.snap
  • crates/pv-release/tests/snapshots/smoke__postgres_pv1_recipe_contract_is_pinned_and_complete.snap is excluded by !**/*.snap
  • it/fixtures/postgres-import/17.11/directory/3498.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/17.11/directory/3499.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/17.11/directory/blob_16438.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/17.11/directory/toc.dat is excluded by !**/*.dat
  • it/fixtures/postgres-import/18.6/directory/3516.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/18.6/directory/3517.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/18.6/directory/blob_16440.dat.gz is excluded by !**/*.gz
  • it/fixtures/postgres-import/18.6/directory/toc.dat is excluded by !**/*.dat
📒 Files selected for processing (29)
  • Cargo.toml
  • DESIGN.md
  • crates/postgres-import/Cargo.toml
  • crates/postgres-import/src/lib.rs
  • crates/postgres-import/src/reader.rs
  • crates/postgres-import/tests/reader.rs
  • crates/pv-release/tests/recipe_fixtures.rs
  • crates/pv-release/tests/recipe_metadata.rs
  • crates/pv-release/tests/smoke.rs
  • docs/superpowers/specs/2026-09-23-postgres-import-feasibility-spike.md
  • it/fixtures/postgres-import/17.11/all.sql
  • it/fixtures/postgres-import/17.11/create.sql
  • it/fixtures/postgres-import/17.11/custom.dump
  • it/fixtures/postgres-import/17.11/directory/blobs_3501.toc
  • it/fixtures/postgres-import/17.11/plain.sql
  • it/fixtures/postgres-import/17.11/tar.dump
  • it/fixtures/postgres-import/18.6/all.sql
  • it/fixtures/postgres-import/18.6/create.sql
  • it/fixtures/postgres-import/18.6/custom.dump
  • it/fixtures/postgres-import/18.6/directory/blobs_3519.toc
  • it/fixtures/postgres-import/18.6/plain.sql
  • it/fixtures/postgres-import/18.6/tar.dump
  • it/fixtures/postgres-import/generate.sh
  • it/fixtures/postgres-import/hostile.sql
  • it/fixtures/postgres-import/isolation.sh
  • it/fixtures/postgres-import/source.sql
  • release/artifacts/recipes/postgres/build.sh
  • release/artifacts/recipes/postgres/recipe.toml
  • release/artifacts/recipes/postgres/smoke.sh

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4a35676e53

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/postgres-import/src/reader.rs Outdated
};
}
(_, b'"') => *lex = Lex::Double,
(_, b'$') => *lex = Lex::DollarOpening(vec![b'$']),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check token boundaries before opening dollar quotes

When a valid unquoted PostgreSQL identifier contains dollar signs, such as CREATE TABLE foo$bar$ (id int);, this branch interprets $bar$ as a dollar-quote delimiter even though it is part of the identifier. The lexer then ignores the statement terminator and returns IncompleteSql (or merges content until another $bar$ appears), so the inspector rejects or misframes otherwise valid SQL. Only enter DollarOpening when $ occurs at a valid dollar-quote boundary, and enforce PostgreSQL's tag-start rules.

Useful? React with 👍 / 👎.

Comment on lines +191 to +194
if statement.is_empty() {
statement_line = line;
}
statement.push(byte);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Record the line of the first SQL token

After a statement-ending semicolon, the following newline is appended to the newly empty statement buffer and fixes statement_line to the preceding line before line is incremented. Consequently, errors in the next statement are reported at least one line early—the existing COPY terminator test places COPY on line 2 but reports line 1—and additional leading blank lines make the location even less useful. Set the starting line when the first substantive SQL byte is buffered rather than on inter-statement whitespace.

Useful? React with 👍 / 👎.

trap cleanup 0 1 2 3 15

validate_packaged_macho_tree
"$pg_restore" --list "$ROOT/it/fixtures/postgres-import/17.11/custom.dump" >"$tmpdir/pg-restore-list.txt"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Enable compressed-archive support in pg_restore

The new smoke only runs pg_restore --list, but the packaged binary is still configured with --without-zlib in build.sh:229. PostgreSQL documents that this option disables compressed-archive support in pg_restore, while custom and directory dumps are gzip-compressed by default; the newly generated directory fixtures even contain .dat.gz files. Consequently, listing the uncompressed TOC can pass while the archive-to-SQL rendering required by this change fails as soon as pg_restore reads ordinary table data. Build and package zlib support and smoke a full pg_restore --file render rather than only --list. (PostgreSQL build documentation, pg_dump format documentation)

Useful? React with 👍 / 👎.

docker exec "$container" psql -X -v ON_ERROR_STOP=1 -U postgres -d mapped_target -c 'GRANT CREATE ON DATABASE mapped_target TO pv_import_fixture;'
docker exec "$container" psql -X -v ON_ERROR_STOP=1 -U postgres -d mapped_target -c 'GRANT CREATE ON SCHEMA public TO pv_import_fixture;'
docker exec "$container" psql -X -v ON_ERROR_STOP=1 -U postgres -d second_target -c 'GRANT CREATE ON SCHEMA public TO pv_import_fixture;'
docker exec -u postgres "$container" sh -c 'printf "%s\n" "127.0.0.1:5432:mapped_target:pv_import_fixture:fixture-only" "127.0.0.1:5432:second_target:pv_import_fixture:fixture-only" > /tmp/pv-import-fixture.pass; chmod 600 /tmp/pv-import-fixture.pass'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Authenticate the IPv6 isolation probe

Neither passfile entry created here matches the later -h ::1 -d unrelated_project probe. PostgreSQL obtains a password only from an entry matching the connection's host, port, database, and user, so that psql invocation can fail because no password is available—or because no IPv6 listener is reachable—without ever exercising the host all ... ::/0 reject rule. This leaves the spike's claimed IPv6 isolation unverified; provide matching credentials and distinguish an HBA rejection from authentication or transport failures. (PostgreSQL password-file documentation)

Useful? React with 👍 / 👎.

Comment thread Cargo.toml Outdated
linemux = "0.3.0"
nix = { version = "0.31.3", features = ["socket", "user"] }
object_store = { version = "0.13.2", default-features = false, features = ["aws"] }
pg_query = "=6.2.0"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Use a PostgreSQL 18 parser for PostgreSQL 18 dumps

The pinned pg_query 6.2 release embeds PostgreSQL 17 grammar, but this reader is tested and documented for PostgreSQL 18.6 dumps. PostgreSQL 18 added virtual generated columns and made them the default, allowing GENERATED ALWAYS AS (...) without a storage mode, whereas PostgreSQL 17 requires the trailing STORED keyword. A valid PostgreSQL 18 dump containing a virtual generated column therefore fails here with ImportError::Sql, even though track 18 is supported and is the default track. Use a PostgreSQL 18 parser, or select grammar matching the dump version, and add a virtual-column fixture. (libpg_query releases, PostgreSQL 18 generated columns, PostgreSQL 17 generated columns)

Useful? React with 👍 / 👎.

if let Some(node) = &raw.stmt
&& let Some(Node::CopyStmt(copy)) = &node.node
{
if copy.is_program || !copy.filename.is_empty() {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Distinguish an empty server filename from STDIN

For COPY t FROM '';, pg_query exposes the explicit empty filename as the same empty String used when the filename is absent for STDIN, so this condition accepts a server-file COPY and switches the reader into client-data framing. With input such as COPY t FROM '';\nDROP TABLE important;\n\\.\n, the DROP statement is consumed as COPY data and never reaches parser or policy inspection, even though PostgreSQL defines a quoted filename and STDIN as distinct COPY sources. Verify the source tokens or spans and require the literal STDIN form instead of relying on this lossy protobuf field. (PostgreSQL COPY documentation, pg_query CopyStmt documentation)

Useful? React with 👍 / 👎.

Comment thread crates/postgres-import/src/reader.rs Outdated
Comment on lines +449 to +453
|| database.contains(['\\', '\'', '"', '\n', '\r', '='])
|| (!quoted
&& !database
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_'))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Parse every pg_dump-generated connection target

Legal database names can produce generated pg_dumpall connection forms that this blacklist rejects. For example, PostgreSQL emits \connect "foo.bar" for a database named foo.bar, while foo=bar is emitted as \connect -reuse-previous=on "dbname='foo=bar'"; the former is rejected for its quotes and the latter is recognized and then rejected solely for the safely quoted =. Multi-database dumps therefore fail inspection for valid source database names. Parse PostgreSQL's generated identifier and conninfo quoting forms rather than applying this character blacklist. (PostgreSQL appendPsqlMetaConnect implementation)

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 081b848784

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

}
}
Lex::Dollar(delimiter) => {
if byte == b'$' && statement.ends_with(delimiter) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Match dollar terminators entirely after the opening delimiter

For valid SQL such as SELECT $$$;$$;, whose string value is $;, this suffix check matches a closing $$ overlapping the opening delimiter. The lexer exits the dollar quote at the third $, treats the internal semicolon as a statement boundary, and passes an unterminated string to the parser, rejecting otherwise valid input. Tagged delimiters have the same issue, for example SELECT $tag$tag$;$tag$;. Track the body start or delimiter-match state so a closing delimiter cannot reuse bytes from the opener.

Useful? React with 👍 / 👎.

Comment on lines +320 to +324
(Some(b'/'), b'*') => {
*lex = Lex::BlockComment {
depth: 1,
previous: 0,
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid reusing a block-comment terminator as another opener

For valid SQL such as SELECT 1 /* comment */*2;, the / ending the comment remains the previous statement byte when normal scanning resumes. The following multiplication * therefore opens a spurious block comment, hiding the actual statement terminator and causing IncompleteSql at EOF. Detect comment openers only from bytes consumed in normal state, rather than allowing the preceding comment's closing slash to participate.

Useful? React with 👍 / 👎.

autoconf automake autopoint bison build-essential bzip2 ca-certificates cmake curl \
file flex git jq gperf libaio-dev libncurses-dev libtool patchelf pkg-config \
python3 re2c unzip xz-utils \
python3 re2c unzip xz-utils zlib1g-dev \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Install libclang in the Linux workspace builder

The documented Linux development workflow runs workspace tests inside this image, which now builds the new postgres-import member and its pg_query dependency. That dependency requires libclang, as the updated CONTRIBUTING instructions acknowledge, but this image installs neither libclang-dev nor another package providing it. A fresh image therefore fails during binding generation before workspace tests can run. Add the native parser prerequisites here, as the Linux CI setup already does.

Useful? React with 👍 / 👎.

@codspeed

codspeed Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 7 untouched benchmarks


Comparing feat/postgres-import-351 (e56b830) with main (b2e18c7)

Open in CodSpeed

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The new Linux zlib selection breaks shared-module linking, and atomic-function inspection introduces quadratic parsing work.

Reviewed changes Reviewed the changes since 4a35676e in 081b8487.

  • Updated dump parsing: Upgraded pg_query, accepted atomic function bodies, corrected identifier boundaries, decoded generated connection names, and required an actual STDIN COPY source.
  • Hardened isolation probes: Supplied valid credentials and required explicit HBA rejection over IPv4, Unix sockets, and IPv6.
  • Enabled archive decompression: Enabled zlib and changed the pg_restore smoke to verify rendered compressed table data.
  • Aligned Linux validation: Added native prerequisites and updated artifact fixtures and snapshots for the current packaging pipeline.

Validation passed: 14 reader tests, 11 PostgreSQL release tests, nine recipe-metadata tests, reader Clippy, formatting, and ShellCheck. Focused native probes reproduced both findings; Docker probes and native macOS artifact smoke were not run.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

Comment on lines +242 to +245
zlib_archive=$(${CC:-cc} -print-file-name=libz.a)
[ -f "$zlib_archive" ] || die "missing static zlib; install zlib1g-dev"
mkdir "$work_dir/zlib"
cp "$zlib_archive" "$work_dir/zlib/libz.a"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] The Ubuntu 22.04 zlib1g-dev archive selected here is non-PIC; with zlib enabled, linking it into pgcrypto.so fails with R_X86_64_PC32 ... recompile with -fPIC. This blocks Linux PostgreSQL artifact builds for both tracks before smoke validation.

Technical details
# Selected static zlib cannot link into PostgreSQL shared modules

## Affected sites
- `release/artifacts/recipes/postgres/build.sh:242-247` — copies the builder's non-PIC `libz.a` and places it on the library search path.
- `release/artifacts/recipes/postgres/build.sh:252-263` — now enables zlib and builds `world-bin`, including `pgcrypto.so`.
- `scripts/linux/builder.Dockerfile:12` — installs the Ubuntu package providing that archive.

## Evidence
- Extracted the builder distribution's `zlib1g-dev_1.2.11.dfsg-2ubuntu9.2_amd64.deb` from https://archive.ubuntu.com/ubuntu/pool/main/z/zlib/.
- Linking a shared module calling `deflateInit`, using `-fPIC -fvisibility=hidden` and that archive, fails with `libz.a(deflate.o): relocation R_X86_64_PC32 against symbol z_errmsg can not be used when making a shared object; recompile with -fPIC`.
- PostgreSQL explicitly adds `-lz` to pgcrypto's shared-library link: https://raw.githubusercontent.com/postgres/postgres/REL_17_11/contrib/pgcrypto/Makefile.
- Its Linux module link uses `-shared`; pgcrypto supplies no export map that would hide the archive's symbols: https://raw.githubusercontent.com/postgres/postgres/REL_17_11/src/Makefile.shlib.
- The passing release fixture uses fake `make` output and does not exercise zlib linkage.

## Required outcome
- Supply position-independent zlib for shared-module linking while preserving the artifact's closed runtime dependency set.
- Verify a real shared compression/module link with the selected zlib, alongside the existing compressed-data smoke.

## Suggested approach
- Build a PIC static zlib, or bundle an appropriate shared zlib; copying the distribution's ordinary static archive is insufficient.

Comment on lines +207 to +214
let parsed = match pg_query::parse(sql, 0) {
Ok(parsed) => parsed,
// A semicolon can separate commands inside a SQL-standard function body.
Err(pg_query::Error::Parse(message))
if message == "syntax error at end of input" =>
{
at_line_start = false;
continue;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Every internal semicolon now reparses the entire retained BEGIN ATOMIC body, making inspection quadratic in the number of body statements. In an optimized release build, a valid 144 KB function containing 16,000 SELECT 1; commands took 33 seconds to inspect versus 42 ms for one complete parse; larger functions remain far below the 8 MiB cap but can stall preflight for minutes.

Technical details
# Atomic-body retries repeatedly parse growing prefixes

## Affected sites
- `crates/postgres-import/src/reader.rs:203-214` — each semicolon calls the full parser; an EOF error retains all prior commands for the next retry.

## Evidence
- Reproduced with the production reader built using `cargo build -p postgres-import --release --locked`.
- Input: `CREATE FUNCTION public.proof() RETURNS integer LANGUAGE sql BEGIN ATOMIC ` followed by repeated `SELECT 1;` commands and ` END;`.
- 1,000 / 2,000 / 4,000 commands took approximately 0.157 / 0.528 / 2.021 seconds to inspect.
- 16,000 commands produced a valid 144,078-byte single statement: direct `pg_query::parse` took 42 ms, while `inspect_plain_dump` took 32.97 seconds.
- Each pg_query call starts a fresh parse, rather than resuming the previous one: https://docs.rs/crate/pg_query/18.1.0/source/src/query.rs.

## Required outcome
- Recognize the complete outer atomic-body statement without repeatedly parsing every growing prefix, keeping parsing work amortized-bounded while preserving streamed COPY handling and the statement-size limit.

@clvsh
clvsh force-pushed the feat/postgres-import-351 branch from 081b848 to e56b830 Compare November 19, 2026 03:39

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e56b830ede

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +326 to +327
(_, b'\'') => {
let escape = matches!(previous, Some(b'E' | b'e'))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve escape mode across newline-concatenated string literals

For a valid escape string continued across a newline, such as SELECT E'a' followed by a newline and '\'';, this branch assigns escape: false to the continuation because it has no adjacent E prefix. PostgreSQL explicitly requires the prefix only on the first segment (documentation). The reader consequently mistakes the escaped quote for a terminator, reopens the string at the following quote, and misses the final semicolon, rejecting valid SQL as IncompleteSql. Preserve the preceding escape-string mode when recognizing newline-separated continuation literals.

Useful? React with 👍 / 👎.

let sql = std::str::from_utf8(&statement).map_err(|_| ImportError::NonUtf8Sql {
line: statement_line,
})?;
let parsed = match pg_query::parse(sql, 0) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Avoid reparsing the entire atomic function at each semicolon

For a large SQL-standard function containing BEGIN ATOMIC ... END, each internal semicolon invokes pg_query::parse over the entire retained function prefix, then retries after the expected end-of-input error. This makes inspection quadratic in the number of body statements: 100,000 SELECT 1; commands produce roughly 900 KB of SQL but cause more than 45 GB of cumulative parser input, despite remaining well below the 8 MiB statement limit. Valid dumps containing large atomic functions can therefore make inspection impractically slow. Frame the complete atomic body before parsing rather than repeatedly parsing every growing prefix.

Useful? React with 👍 / 👎.

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.

1 participant