Repository navigation
Fix the post-merge review findings from #27 - #28
Conversation
sqlparser 0.62 parses a plain JOIN as JoinOperator::Join, not Inner, so shard inference skipped its ON clause and the query kept the previous shard. Read ON for both Join and Inner; outer joins are unchanged. Co-authored-by: Perplexity <noreply@perplexity.ai>
sqlparser 0.62 parses WITH ... DELETE and WITH ... MERGE as a query with a Delete or Merge body, and the mutation check treated both as reads, so they went to a replica. A SELECT over a CTE that writes went there too. Treat Delete and Merge bodies as writes, check the queries in WITH, and match every kind of query body instead of defaulting to a read. Co-authored-by: Perplexity <noreply@perplexity.ai>
sqlparser 0.62 accepts INSERT OR REPLACE/IGNORE/... on the Postgres dialect, and shard and activity inference asserted it never would; the same was true of DELETE t FROM t. Skip both, as Postgres rejects them. A panic in a client's handler also skipped the drain count's -1 and the client's stats removal. Run both when the handler panics too, then let the panic continue. Co-authored-by: Perplexity <noreply@perplexity.ai>
sqlparser 0.62 parses VACUUM, and visit_relations doesn't visit its table, so table_access allowed VACUUM [FULL] of a blocked table. Check its table as for COPY. A VACUUM without a table processes every table, so refuse it while any table is blocked; the parser reads an option such as VERBOSE in that position as a table name. Co-authored-by: Perplexity <noreply@perplexity.ai>
Co-authored-by: Perplexity <noreply@perplexity.ai>
hickory-proto 0.24.4 reserves memory for the record counts a DNS message's header claims; 0.26.2 fixes it. Port to the 0.26 API: TokioResolver, its builder and NetError. 0.26 changed the defaults of three resolver options (IPv4 and IPv6 lookups in parallel, a cache of 8192 responses, `options edns0` read from resolv.conf). Set them as 0.24 had them. Co-authored-by: Perplexity <noreply@perplexity.ai>
artem-pplx
left a comment
There was a problem hiding this comment.
Raphael review of ab81a83, pass 1 of 2 (Opus High): one small blocker. A fresh second-model final review follows once B1 is fixed.
B1 (P2, blocker): a mutating WITH followed by a read in the same message still goes to a replica.
src/query_router.rs:669-676 is in the Query(query) arm of infer, which this diff doesn't change. When is_mutation_query is true, it sets active_role = Primary but never sets visited_write_statement, which only the write arm sets (:701). A later read-only statement in the same simple-query message therefore takes else if !visited_write_statement and resets the role to Replica, or to None when primary reads are on.
Reproduced on the head with read/write splitting on and primary reads off, via QueryRouter::parse + infer:
| Message | Role |
|---|---|
WITH x AS (SELECT 1) DELETE FROM data WHERE id = 5; SELECT 1 |
Replica |
WITH x AS (DELETE FROM data RETURNING *) SELECT * FROM x; SELECT 1 |
Replica |
WITH x AS (SELECT 1) MERGE INTO data USING a ON data.id = a.id WHEN MATCHED THEN DELETE; SELECT 1 |
Replica |
DELETE FROM data WHERE id = 5; SELECT 1 (control) |
Primary |
Before #27, sqlparser rejected these DELETE and MERGE forms, so the message took the unparsed path and used the pool's default role. Now the write reaches a hot standby and fails, which is the same consequence as F2. WITH … INSERT …; SELECT 1 behaves the same way, but that one predates #27.
Fix: in that branch, also set visited_write_statement = true;. This also keeps SELECT … FOR UPDATE; SELECT 1 on the primary.
Test: add the three messages above to the Primary list in test_data_modifying_bodies_and_ctes_go_to_primary, and keep SELECT 1; SELECT 1 → Replica as a control. Confirm the new cases fail with the one-liner reverted.
Everything else passes:
- F1, the N1 guards and
handle_with_accountingare correct:- accounting runs exactly once on Ok, Err and panic;
- the panic still propagates;
- cancellation behaves as before.
- N2 is correct for every form that parses.
cargo fmt --checkis clean. - The hickory 0.26.2 port restores
Ipv4thenIpv6, cache 32 and edns0 off, which I checked against the 0.24.4 and 0.26.2 sources. Only 0.26.2 remains, with no second ring and no aws-lc-rs. - 382 lib tests and 4 doctests pass with
--features test-plugins. All 6 new tests fail with their fixes reverted. The clippy warning set equals main's.
Non-blocking: an inline VACUUM note, plus a separate description comment.
Models and evidence: Opus High, pass 1. The request asked for extra-high; I kept High per my review policy. rustc 1.100.0, single test run; the doctests were rerun once after a local disk-space link failure.
Created with Perplexity
|
Description check at The F1, N1, fmt, mutation-table, test-count, hickory-pin and advisory claims match the head. Suggested corrections:
Created with Perplexity |
A query whose body or CTE writes, or that locks rows, now counts as a write for the rest of the message, so a read after it in the same message no longer moves the message to a replica. A VACUUM the parser can't read, such as `VACUUM (FULL)`, may process every table. While a plugin gates a table, rejects_unparsed now refuses unparsed text whose first word, after whitespace and comments, is VACUUM. Co-authored-by: Perplexity <noreply@perplexity.ai>
|
Addressing the review and the description notes at 6082c2a: B1: fixed. The Description: I applied all five corrections.
My dependency counts differ from the note's 270 → 278. With Tests on rustc 1.99.1:
Created with Perplexity |
micahjz
left a comment
There was a problem hiding this comment.
Verdict: APPROVE at 6082c2a7fbbe25fbd03d19e87e78838eb4e69317 against 8da28519f394fe440c0d73f4a93293b25d79227f.
The original plain-JOIN wrong-shard regression is fixed. I reran an independent consecutive-query probe through QueryRouter::parse and infer: shard 0 → plain JOIN selecting shard 2 → INNER JOIN selecting shard 0 now produces 0 → 2 → 0. The earlier base failed the plain-JOIN case. Outer-join inference remains unchanged.
Scope and findings
No merge-blocking finding in this follow-up. Reviewed the full diff, not just F1:
- Mutating WITH/DELETE/MERGE and data-modifying CTEs select Primary. The latest
visited_write_statementchange preserves Primary for subsequent reads in the same message, including after a locking SELECT. Independent probes of the four multi-statement cases pass. - Unsupported INSERT/DELETE shapes now skip shard extraction without panicking, while the surrounding write arm still selects Primary.
- All four client entrypoint paths use the accounting helper. Normal/error behavior is retained; a handler panic now balances the drain count, removes client stats and resumes unwinding. This does not add cancellation cleanup.
- Parsed VACUUM target checks and the unparsed whitespace/comment-prefixed VACUUM guard cover the added tests.
- Checked the resolver port against the downloaded 0.24.4 and 0.26.2 implementations: IPv4-then-IPv6, cache size 32 and EDNS0 disabled are explicitly preserved. The no-nameserver startup difference is documented. The Linux dependency tree has one ring version and no aws-lc.
Nonblocking existing limitation
P2, pre-existing legacy table-access gap: leading empty statements evade the new unparsed VACUUM prefix check. With query parsing, plugins_require_parse = true, and legacy table_access denying secrets, both ;VACUUM (FULL) and ; /* comment */ VACUUM (FULL) fail parsing but return rejects_unparsed == false. I verified that behavior on both base and head, so this is not a regression introduced by #28.
first_word stops at the initial semicolon. PostgreSQL discards empty statements from its parse list, and uses an implicit transaction block only when that list contains multiple statements, so an empty prefix does not make the transaction restriction a defense.
Follow-up: skip leading empty statements along with whitespace/comments, and add these two cases to the VACUUM regression test. This observation applies to the legacy/table-scoped fallback; the existing configured-plugin branch that refuses every unparsed query still denies them. It does not block the routing fixes here.
Validation, compatibility and exclusions
- Rust 1.97.1, the repository-declared toolchain: 383 unit tests and 4 doctests pass with
cargo test --locked --features test-plugins. - Three additional independent probes pass: original JOIN reproduction, multi-statement primary stickiness, and base/head characterization of the legacy VACUUM gap.
cargo fmt --all --checkandgit diff --checkpass.- Clippy with
--lib --examples --features test-plugins -- -Dwarningsstill fails with the same 54 diagnostic messages as the base run; lint is not clean. - All reported GitHub checks at this head are successful CodeQL checks. They are separate from the local runtime tests and repository approval gate.
- No wire/storage/config-shape migration is introduced. Mixed versions retain old routing behavior on old instances; rollback to the base reintroduces the bugs this PR fixes. CTE shard inference remains the explicitly documented pre-existing limitation.
- No full live-Postgres suite, downstream build, performance benchmark, merge or deployment performed.
Created with Perplexity
perplexedmontagna
left a comment
There was a problem hiding this comment.
Reviewed current head 6082c2a7fbbe25fbd03d19e87e78838eb4e69317 against base 8da28519f394fe440c0d73f4a93293b25d79227f.
What it changes
- Restores shard inference for plain
JOIN ... ON, without extending that inference to outer joins. - Routes data-modifying query bodies/CTEs to the primary and preserves that choice for subsequent reads in the same message.
- Replaces unsupported-write assertions with inference guards; balances drain accounting and removes client stats on handler panic before resuming the panic.
- Adds parsed/unparsed VACUUM protections and upgrades the DNS resolver, explicitly preserving the old IP strategy, cache size, and EDNS setting.
Verdict: Approve
No introduced runtime blocker found. The previously reported JOIN regression and same-message primary-routing issue are fixed on this head. One remaining, pre-existing VACUUM gap is non-blocking for this corrective PR, but the description should not imply all unparsed VACUUM forms are covered.
Findings
- [P2, pre-existing/non-blocking] Empty statements bypass the new unparsed VACUUM check. With
query_parser_enabled = true,plugins_require_parse = true, and legacytable_accessgatingsecrets,; /* empty prefix */ VACUUM (FULL);fails parsing butrejects_unparsedreturns false. The newfirst_wordhelper stops at;and returns an empty string. I reproduced this through the actualQueryRouter::parseandrejects_unparsedAPIs; the unprefixed control is correctly rejected. PostgreSQL 18.6 executes the prefixed form successfully and rewrites a local test table (its relfilenode changed). Empty statements do not make this a multi-statement transaction;SELECT 1; VACUUM (FULL);does fail as expected. This also passes the base implementation's gate, so it is not a regression introduced here. Minimum follow-up: skip leading empty statements as well as whitespace/comments before checking VACUUM, and add simple-query and Parse-message tests. This is specific to the table-scoped compatibility exception, not process plugins or configured plugins that reject every unparsed query.
Validation and readiness
- Passed locally on rustc 1.99.1:
cargo test --locked --features test-plugins, 383 unit tests and 4 doctests. - Passed:
cargo fmt --checkandgit diff --check. cargo clippy --locked --lib --examples --tests --features test-pluginscompleted successfully with warnings; this is not a warning-free or-D warningsresult.- A separate review-only regression probe for the semicolon-prefixed VACUUM failed as described above. No review probe or source change was pushed.
- Current GitHub CodeQL checks are successful. Full CircleCI/Postgres integration suite, the pinned Docker toolchain build, and the downstream AGI build were not run.
- Rollout: downstream consumers must adopt the corrected revision; merging alone does not update their pins. Rolling back to this PR's base restores the bugs this PR fixes. CTE shard inference remains the documented pre-existing limitation.
Created with Perplexity
artem-pplx
left a comment
There was a problem hiding this comment.
Raphael delta review of ab81a83..6082c2a (Opus High): B1 is fixed. One small nonblocking gap remains in the new VACUUM check (inline), plus a correction to my earlier description comment.
B1: fixed.
visited_write_statementis now set in the mutation/lockingQueryarm at:703. The three messages from the earlier review andSELECT … FOR UPDATE; SELECT 1all go to Primary.- Activity-based routing and primary reads are unaffected.
- The F2 test fails when
:703is reverted.
NB1 implementation: correct apart from D1 (inline).
- Whitespace and comment prefixes are handled, including nested, unterminated and
--at end of input. - Non-ASCII input can't cause a slicing panic.
SELECT 1; VACUUM (FULL)is refused by Postgres inside the implicit transaction block, and a Parse message allows only one command.
Correction to my description comment, item 5:
- The body's 220→222 crates is right. My 270→278 double-counted
cargo treelines that differed only by the(*)/(proc-macro)suffixes. crossbeam-channel,url,getrandom 0.4andrand 0.10already exist on main, so they aren't new.- The body's added and removed lists match the head.
Evidence:
cargo fmt --checkis clean.- All 383 lib tests pass. Both new tests fail with their fixes reverted.
- Clippy and the doctests weren't rerun for this one-file delta.
Next: the fresh second-model final review runs on the head that resolves D1, or on this head if D1 is declined.
Created with Perplexity
artem-pplx
left a comment
There was a problem hiding this comment.
Raphael final review of 6082c2a, post-merge, pass 2 of 2 (fresh Astra High, after Opus High): two follow-ups. #29 covers one of them; the other is new.
- A1 (P2, new, inline at
dns_cache.rs:20): hickory 0.26 trusts an NXDOMAIN from one nameserver, where 0.24 kept trying the others. - D1 (P3): the leading
;VACUUM gap. #29 tracks it, and I'm reviewing that separately.
Holds at this head:
- F1, F2/B1 and the N1 guards are correct.
handle_with_accounting: one drain+1/-1per non-admin client on normal return, error and unwind. Itsdisconnectrepeats the existing idempotent removal. Cancellation behaves as before.- Parsed VACUUM handling is correct.
- I found no VACUUM bypass beyond D1. I checked comments, UTF-8 boundaries, quoted option words and COMMIT/ROLLBACK batches, then confirmed D1 and the transaction-block controls on a local PostgreSQL 18.
- No internal terms appear in the diff, commits or body.
Evidence:
- Reused the exact-head receipts: 383 lib tests, 4 doctests, fail-reverts, fmt and the clippy set.
- New: a local UDP resolver probe for A1, and an isolated PostgreSQL 18 run for D1.
- Not run: a production DNS environment.
Created with Perplexity
| /// A resolver with the system's configuration. The options hickory-resolver | ||
| /// 0.26 changed the defaults of are set as 0.24 had them. | ||
| fn system_resolver() -> Result<TokioResolver, NetError> { | ||
| let mut builder = TokioResolver::builder_tokio()?; |
There was a problem hiding this comment.
A1 (P2, post-merge follow-up): the port doesn't restore 0.24's per-nameserver trust_negative_responses = false.
What changed:
- hickory-resolver 0.24.4 builds each system nameserver with
trust_negative_responses: false(system_conf/unix.rs:68-85). - 0.26.2 uses
NameServerConfig::udp_and_tcp, which sets it totrue(config.rs:227-233). - The pool moves on to the next server after an NXDOMAIN only when the flag is false (
name_server_pool.rs:423-427). - This builder restores three
ResolverOptsfields but not this per-server one.
Scenario: dns_cache_enabled is on, and /etc/resolv.conf lists servers with split or briefly inconsistent views. One returns NXDOMAIN for the database host, and another resolves it. 0.24 waited for the other server. 0.26 returns NXDOMAIN.
Evidence: a local probe with three UDP responders. Two answered NXDOMAIN and one answered with an A record; the config came from 0.26.2's parse_resolv_conf, with these overrides and concurrency 2.
- As merged, the lookup returned NXDOMAIN and the positive responder got 0 queries.
- With the flag set to false, it returned
192.0.2.7after 1 query.
Impact: the backend connect doesn't fail directly, because server.rs:395-403 logs the error, sets addr_set = None and connects through Tokio's resolver. What's lost is DNS-change tracking:
- that connection skips the
is_badDNS check (server.rs:1362-1373); - a refresh error keeps stale cache entries (
dns_cache.rs:207-228); - connections may not be retired after a DNS change.
Fix:
- Read
(config, opts) = system_conf::read_system_conf()?. - Set
trust_negative_responses = falseon every entry inconfig.name_servers. - Build with
TokioResolver::builder_with_config(config, TokioRuntimeProvider::default()). - Apply the three existing option overrides.
options_mut() alone can't reach the per-server field. Also update the doc comment.
Test: NXDOMAIN from earlier servers followed by an A record from a later one must resolve, and all-NXDOMAIN must still fail. The former fails as merged.
Created with Perplexity
There was a problem hiding this comment.
Fixed in c6e9a37 on #29. The resolver is now built from read_system_conf() with trust_negative_responses = false on every nameserver, using builder_with_config(config, TokioRuntimeProvider::default()), and then the three option overrides.
There are two new tests, both against mock UDP nameservers on localhost:
- An NXDOMAIN followed by a later A record resolves to that record. Without the fix, it fails with NXDOMAIN.
- NXDOMAIN from every server is still an NXDOMAIN error.
Created with Perplexity
|
Follow-up ledger for #28 (merged at
Created with Perplexity |
Fixes the findings from the post-merge review of #27 (review, ledger). One commit per item, plus 6082c2a for the review of this PR (review, notes).
Changes
JOINasJoinOperator::Join, soJOIN ... ONlost its sharding key and the query went to the previous shard (repro). Inference now reads the ON clause ofJoin(On)andInner(On). Outer joins are unchanged.is_mutation_querynow treatsDELETEandMERGEbodies as writes and checks the CTE bodies, soWITH ... DELETE,WITH ... MERGEand aSELECTover a CTE that writes all go to the primary. The body check is an exhaustive match overSetExprwith no catch-all. Such a query, or one that locks rows, now also counts as a write for the rest of the message, so a read after it in the same message (WITH x AS (SELECT 1) DELETE FROM data WHERE id = 5; SELECT 1, orSELECT ... FOR UPDATE; SELECT 1) no longer moves the message to a replica.INSERT OR ...panics (25491fa, comment, update). The asserts atquery_router.rs:756and:779are now guards that skip shard inference for these forms, as the review suggested. Postgres rejects them anyway, and the query is still routed to the primary. AnErrwould not help here: the client ignoresinfer's result, and returning early would skip setting the primary role. The client handler now undoes its drain+1and callsstats.disconnect()when it panics too. It usescatch_unwindrather than a drop guard because the drain decrement is an async send, whichDropcan't await. The four identical call sites inclient_entrypointnow share one helper.table_accessnow refusesVACUUMandVACUUM FULLof a blocked table, including schema-qualified and quoted names. AVACUUMwith no target processes every table, so it's refused whenever the denylist isn't empty. sqlparser readsVACUUM VERBOSE(andANALYZE,FREEZE) as a table with that name, so an unquoted option word is treated as no target. Forms sqlparser can't parse, such asVACUUM (FULL)orVACUUM FREEZE VERBOSE, take the unparsed path. Withplugins_require_parseon,rejects_unparsednow refuses unparsed text whose first word, after whitespace and comments, isVACUUM, while any table is gated (6082c2a). Only the first word matters: Postgres runs a multi-statement Query message in an implicit transaction block, and VACUUM can't run in one. Withplugins_require_parseoff, unparsed statements are forwarded as before.configured_tests.rs:1803and:1819.dns_cache.rs:TokioResolver, its builder, andNetError, whichCachedResolver::lookup_ipnow returns. 0.26 changed three resolver defaults, so they're set to the 0.24 values: IPv4-then-IPv6 lookups instead of both in parallel, a 32-entry cache instead of 8192, andoptions edns0from resolv.conf not applied.Cargo.lockpins hickory-resolver, hickory-net and hickory-proto at 0.26.2. ring still comes only through rustls; no aws-lc-rs.cargo tree -e normal --target x86_64-unknown-linux-gnu). It addsmoka0.12 (pgcat already usesmini-moka),crossbeam-epoch,portable-atomic,critical-section,uuid,prefix-trie,hickory-netandthiserror2, and removeslru-cache,linked-hash-map,enum-as-inner,hostname,match_cfg,quick-errorandheck.Cargo.lockgoes from 296 to 319 packages; most of the rest are for other platforms./etc/resolv.conflists none, 0.26 fails to build the resolver where 0.24 only warned, so withdns_cache_enabledpgcat logs "Error setting up cached_resolver ... will continue without this feature" and runs without the cache.Testing
On rustc 1.99.1, at the head commit:
cargo fmt --check: clean.cargo clippy --locked --lib --examples --tests --features test-plugins: no warnings on the changed lines, and the same warning set asmainon this toolchain.cargo test --locked --features test-plugins: 383 unit tests pass (376 onmain, plus the 7 below), 4 doc-tests pass. Thedns_cachetests ran with network access.cargo check --tests --features test-pluginspasses at each intermediate commit..circleci/run_tests.shlocally.I ran each new test once with its fix reverted, and each one failed:
query_router::test::test_automatic_sharding_key_in_join_onSome(0), expectedSome(2)query_router::test::test_data_modifying_bodies_and_ctes_go_to_primaryWITH x AS (SELECT 1) DELETE ...routed to the replica; with only the 6082c2a one-liner reverted, all four new...; SELECT 1messages routed to the replicaquery_router::test::test_writes_postgres_rejects_are_not_inferredassertion failed: i.or.is_none()client::tests::test_accounting_is_undone_when_the_handler_panics-1after the panicplugins::table_access::tests::test_vacuum_of_a_forbidden_table_is_refusedVACUUM secretsallowedplugins::table_access::tests::test_vacuum_of_every_table_is_refusedVACUUMallowed; without the option-word handling,VACUUM VERBOSEallowedquery_router::test::test_unparsed_vacuum_is_rejected_while_a_table_is_gatedVACUUM (FULL)forwardedNot covered
WITH ... DELETEbodies: those queries go to the primary and keep the previous shard, as they did when they didn't parse. For example,WITH x AS (SELECT 1) DELETE FROM data WHERE id = 5stays on the shard the connection last used.table_accessfallback, and the TLS tests aren't part of this PR.Corrections to the #27 description
These don't change code:
INSERT OR ...,VACUUM,ANALYZE t,LOCK t, data-modifying CTEs,SET NAMESandSET SESSION AUTHORIZATION, among others, and these now reach plugins parsed. F2, N1 and N2 follow from that.SET NAMESandSET SESSION AUTHORIZATIONas unknown" isn't accurate: 0.52 didn't parse them at all.Tls::newnow rejects a certificate and key that don't match, and webpki-roots 1 ships a newer root set.Created with Perplexity