Skip to content

Adapt updated_since page selection to recent-result size - #1865

Merged
rdimitrov merged 8 commits into
mainfrom
codex/bounded-updated-page-query
Nov 20, 2026
Merged

rdimitrov merged 8 commits into
mainfrom
codex/bounded-updated-page-query

Conversation

@rdimitrov

@rdimitrov rdimitrov commented Nov 18, 2026 •

Copy link
Copy Markdown
Member

Incremental listing queries can scan a large name range for sparse results or sort too much recent history for an early page. This change selects page keys before fetching payloads and adapts first-page selection to the number of recent matches, while preserving the API's name/version order and full filtering.

Query behavior

  • Plain first-page updated_since&limit=100 requests probe up to 513 matching keys in timestamp order. A complete set of at most 512 is sorted into public order; larger sets use the name-ordered path. Other first-page incremental shapes without substring search retain the 128-match boundary.
  • Bounded per-app hints let first-page requests skip a likely-discarded probe: one in 16 eligible requests can observe results, with at most 32 hints retained for five seconds, separated by deletion filtering. Hints contain no response rows. All requests apply the complete predicate in one statement snapshot; stale hints can affect efficiency, not response freshness.
  • Plain cursor pages inspect at most 512 eligible keys in name/version order. A full requested page or exhausted suffix can be returned immediately; otherwise the query tries bounded timestamp selection before falling back to the full name scan. This preserves sparse-page efficiency and avoids consumed timestamp-prefix scans for dense deep pages. It covers default page size, limit=1, and legacy name-only cursors. Timestamp probes bound returned keys, not every visited index entry; sparse deep pages can still be expensive.
  • Materializing cutoff and cursor bounds in one row allows plan reuse across varying parameter values without overriding the configured connection execution mode.
  • Plain page sizes 1 and 100 embed only the validated page-size constant; watermarks/cursors remain bound parameters. All incremental queries respect the connection's configured execution mode, including disabled statement caches. The default retains binary payload transfer and prepared-statement reuse. Substring searches keep their existing execution behavior.
  • Transaction-owned reads and additional filters bypass strategy hints. Internal observation markers are excluded from API results, pagination and row metrics. No replica, connection-limit, cache TTL, infrastructure or global planner changes.

Migration and rollout

Migration 020 adds (server_name, version, updated_at) INCLUDE (is_latest, status) and (updated_at DESC, server_name, version). On busy databases, prebuild both concurrently and verify their definitions/readiness before application deployment. The migration checks index existence before issuing CREATE INDEX and validates both replacements. It retains old indexes to avoid startup DROP INDEX table locks.

The deployment guide documents a separate post-rollout DROP INDEX CONCURRENTLY cleanup after validation and the rollback observation window. Retaining old and new indexes temporarily increases storage and write maintenance. Missing-index startup builds can still block writes; concurrent prebuilds are required for a busy deployment. Application rollback is schema-compatible, but not a guarantee of identical planner performance.

Copilot review fixes

All five findings are addressed in the review-fix commit:

  1. Skip CREATE INDEX entirely when the prebuilt relation exists; keep definition validation.
  2. Retain old indexes at startup and document separate concurrent removal.
  3. Preserve configured execution mode and binary results for incremental shapes such as the default limit=30.
  4. Stop forcing cache-statement mode when the connection may have disabled its cache.
  5. Avoid timestamp-prefix rescans for dense deep cursor pages; the follow-up fix bounds the initial name scan so sparse cursor pages retain a cheap timestamp path.

Regression tests cover migrations with held-open reader/writer transactions, execution modes cache_statement/describe_exec/exec (including disabled caches), pooled JSON and transaction-owned reads, binary bytea transfer, and deep cursors over 50,000 inversely timestamp-ordered rows at limits 1/30/100 under forced custom and generic plans. Existing response, pagination, watermark, hint, deletion-filter and concurrency tests remain.

Staging evidence — earlier commit 5dbdbe8

The following November 19 results belong to 5dbdbe8, before the review fixes above. They must not be presented as performance validation of the revised head.

Both configurations used the same candidate binary/data fingerprint and request corpus, six fixed apps with max20/min5 connections each, PostgreSQL 17.5 with a 4 GiB memory limit and 512 MiB shared buffers, and an isolated generator. Each cycle had 30s at 150 reads/s, 60s at 1,500 reads/s plus 10 publishes/s, then 30s recovery. Small and large histories began with 101 and 10,101 recent rows; small history was repeated. The workload included sparse/empty incremental queries, limit=1 and publishing.

DB configuration History Successful/offered burst reads Unsent reads Worst read-group scheduled p99 Publish p99 Max sampled pool pending
4-vCPU VM / 3 PostgreSQL CPUs Small, first 83,190 / 90,000 6,810 3,269.6 ms 2,138.9 ms 917
4-vCPU VM / 3 PostgreSQL CPUs Large 87,676 / 90,000 2,324 2,339.3 ms 2,074.8 ms 913
4-vCPU VM / 3 PostgreSQL CPUs Small, repeat 82,639 / 90,000 7,361 2,682.6 ms 1,446.4 ms 912
8-vCPU VM / 6 PostgreSQL CPUs Small, first 90,000 / 90,000 0 17.9 ms 16.3 ms 0
8-vCPU VM / 6 PostgreSQL CPUs Large 90,000 / 90,000 0 10.8 ms 17.2 ms 0
8-vCPU VM / 6 PostgreSQL CPUs Small, repeat 90,000 / 90,000 0 17.6 ms 14.4 ms 0

Across quiet/burst/recovery, the larger configuration completed all 297,000 reads; the current-size configuration completed 280,505/297,000. Both persisted all 1,980 acknowledged publishes, and both completed all quiet/recovery reads with zero sampled recovery pool queues. Current-size bursts showed CPU throttling/pressure; the measurements do not isolate CPU quota from VM topology or other contention.

Unsent reads are bounded-generator backpressure, not gateway 429s. Scheduled p99 includes scheduling delay for issued requests and excludes unsent demand. Direct app traffic bypassed gateway/cache/rate limiting and autoscaling. These short controlled tests are not a long soak, production replay, or proof that production needs an immediate DB resize. The current-size configuration did not demonstrate comfortable 1,500 uncached reads/s at the tested connection settings. Local ARM results are not GKE capacity predictions.

Both staging exercises restored the original small setup and removed temporary resources. Production was not changed. Raw evidence remains private.

Validation of the review fixes

Local PostgreSQL 17.11: focused regression tests and go test -race ./internal/... ./cmd/... passed; make build validate passed. GitHub Actions run 44646558033 passed on review-fix commit 1fccf887fcab45c8b2e2320190236ef259be0008: lint, schema/example validation, build, govulncheck, full unit/integration tests, and deployment-configuration/staging-adoption tests. The first attempt passed the database suite but failed the unchanged authentication test TestHTTPKeyFetcherRetryHonorsEarlierCallerDeadline; it passed ten consecutive local race-enabled repeats and the CI retry. No authentication code was changed. The subsequent staging comparison of 1fccf88 exposed a mixed-workload regression: only 35–39% of offered burst reads were issued under generator backpressure, with pool queues above 900. Its deep-pagination diagnostic passed. These results supersede any assumption that the earlier staging pass validated that revision.

Cursor regression fix — 8e80c8d

A local four-way comparison isolated unconditional cursor name scans as the main CPU regression; reverting planning alone did not fix it. The bounded cursor selection above restores the sparse path, while materialized bounds permit reusable plans. Migration safety fixes, replicas and connection limits are unchanged.

With six apps at max20/min5 connections, six PostgreSQL CPUs and 4 GiB memory, local direct-API tests at 1,500 reads/s plus publishing completed all 486,000 reads and 3,240 publishes across final quiet/burst/recovery cycles. Small-history DB CPU fell from 5.06 cores in the revised repeat to 0.85 cores; final worst per-shape scheduled p99 was 4.8 ms. Deep-page p99 was 2.5 ms versus 2.4 ms for the revised control, with about 0.10 extra DB core. Larger histories and limit=1 were covered. These short ARM/Colima results diagnose the regression; they are not GKE capacity claims.

Local correctness/race tests, lint, build and schema/example validation passed. New tests cover selection boundaries, changing data, legacy/compound cursor plan reuse, and deep pages under custom/generic plans. The focused staging comparison of this commit is complete; see the results below. Production is unchanged; this PR is not merged.

Paired staging comparison — November 20, 8e80c8d

Compared the previous review revision 1fccf88 with this fix on the same eight-vCPU e2-standard-8 DB VM (PostgreSQL six CPUs, 4 GiB memory, 512 MiB shared buffers). Both used six fixed apps at max20/min5 connections, identical disposable data copies and corpus, and retained old indexes alongside the replacements. Each cycle ran 30s at 150 reads/s, 60s at 1,500 reads/s plus 10 publishes/s, then 30s recovery. Direct app traffic bypassed gateway/cache/rate limiting and autoscaling.

Revision / workload Successful/offered burst reads Unsent Worst read-shape scheduled p99 Publish scheduled p99 Max sampled pool pending
Previous / 101 recent rows 20,435 / 90,000 69,565 7,700.8 ms 10,001.3 ms 920
Fixed / 101 recent rows 90,000 / 90,000 0 17.8 ms 12.0 ms 0
Previous / 10,101 recent rows 21,955 / 90,000 68,045 8,291.7 ms 10,001.4 ms 921
Fixed / 10,101 recent rows 90,000 / 90,000 0 147.8 ms 182.5 ms 0
Fixed / deep 50k diagnostic 90,000 / 90,000 0 7.2 ms 12.9 ms 0

The fixed candidate completed all 297,000 reads and 1,980 publishes across its three quiet/burst/recovery cycles, with stored publishes reconciled and no request failures. All recovery phases passed. Across the paired comparison, 160 response/pagination checks and all 15 phase measurement audits passed; no app container restarts occurred. Approximate sampled DB CPU fell from 5.4–6.0 cores in the failed mixed controls to 2.6–2.8 cores in the fixed mixed runs. No new DB quota throttling was measured in the fixed bursts.

The larger-history tail needs qualification: the first app histogram interval spanning burst onset recorded 891 listing responses above 100 ms, and later intervals recorded none. Sampled queues were zero, checkpoint counters did not change during that cycle, and the measurements do not establish the brief slowdown's cause. The 147.8 ms p99 must not be discarded or described as a uniformly low-latency result.

Unsent demand is generator backpressure, not HTTP429; scheduled percentiles cover issued requests and exclude unsent demand. Control publishing had timeouts. The deep diagnostic covers default30 and limits1/100 with 50,000 synthetic inversely ordered rows and smaller payloads; it is not the mixed workload or a paired deep-page latency comparison in this run. These short tests validate this configuration, not a long soak, production replay or current-size DB capacity.

Staging was restored to its original two nodes, one app and one gateway. Original app/HPA/DB/gateway configuration, data/schema fingerprints, PVC identities and weekly restore configuration were verified. Temporary pools, VMs/disks, generator, databases, credentials and inactive test ReplicaSets were removed. Raw evidence remains private.

Final pre-rollout review checks — 5a37df9

Two follow-up review findings are addressed: migration 020 now validates each key's expected built-in operator class and source-column collation, and listing diagnostics return to row_fetch before the next database wait. Four malformed-prebuild regression cases failed against the prior validation and pass with this correction; fresh/upgrade/prebuilt migrations and held-open reader/writer cases still pass. Local database and telemetry race-enabled suites and lint passed. The query/index definitions and selection strategy tested in staging are unchanged.

The unrelated auth timing test fixture now remains stalled until FetchKey completes, preventing server handler completion from racing timeout assertions with a normal response EOF. Runtime authentication behavior and all deadline/request-count assertions are unchanged. Three Linux repeats and three local race-enabled auth package runs passed; the earlier fixture also passed locally, so local testing alone did not reproduce the CI race.

Current CI status

CI run 44707315178 passed on 5a37df9e60fcaadc704b338e524ac9305111edfa: build, lint, schemas/examples, vulnerability scan, full unit/integration tests and deployment configuration checks. Query/index definitions and query selection match the November 20 staging candidate; subsequent changes strengthen index validation, correct diagnostic attribution and stabilize timeout test fixtures.

@rdimitrov
rdimitrov marked this pull request as ready for review November 20, 2026 00:05
@rdimitrov
rdimitrov requested a max review from Copilot November 20, 2026 00:05

Copilot AI 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.

🟡 Changes recommended

Query-mode and pagination regressions can degrade throughput or break configured connections, while blocking startup index operations can stall live traffic.

5 open issues
What changed in this PR

Optimizes incremental server listings by selecting page keys before fetching payloads and adapting between timestamp- and name-ordered scans.

Changes:

  • Adds bounded recent-key probes and short-lived strategy hints.
  • Reuses prepared statements for common page sizes and replaces listing indexes.
  • Expands correctness and plan-reuse coverage, with deployment and recovery guidance.
File Description
internal/​database/​updated_page.go Implements adaptive page selection and bounded strategy hints.
internal/​database/​updated_page_test.go Tests probe boundaries, pagination, and payload equivalence.
internal/​database/​updated_page_strategy_internal_test.go Tests hint scope, expiry, concurrency, markers, and bound parameters.
internal/​database/​updated_page_hints_internal_test.go Checks stale-hint correctness, changing filters, transaction isolation, and plan reuse.
internal/​database/​updated_page_cache_internal_test.go Verifies statement reuse across changing watermarks and cursors.
internal/​database/​updated_indexes_internal_test.go Covers fresh, upgraded, prebuilt, and incorrectly defined index migrations.
internal/​database/​postgres.go Integrates adaptive queries, execution modes, and marker exclusion.
internal/​database/​migrations/​020_replace_updated_listing_indexes.sql Creates and validates replacement indexes before removing old indexes.
deploy/​README.md Documents adaptive behavior, index prebuilds, recovery, and rollback considerations.

Review effort: Max

Comment thread internal/database/postgres.go Resolved
Comment thread internal/database/postgres.go Resolved
Comment thread internal/database/updated_page.go Resolved

Copilot AI 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.

🔵 Needs a closer look

Database fetch time is misattributed to decoding, and migration validation can accept replacement indexes with incompatible operator classes or collations.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Validate replacement index operator classes and collations

internal/​database/​migrations/​020_replace_updated_listing_indexes.sql:30

These per-column pg_get_indexdef checks omit operator classes and collations, so a prebuilt server_name varchar_pattern_ops index can pass without supporting the normal name ordering and cursor comparisons. After cleanup removes the old covering index, this can force more heap reads. Validate the expected operator classes and column collations for both replacement indexes (same issue at lines 45–47), and add malformed-prebuild cases.

Medium severity Switch diagnostics back to row_fetch after decoding each row

internal/​database/​postgres.go:424

After RowReceived() switches diagnostics to row_decode, the next rows.Next() wait and final close are charged to decoding rather than fetching. This makes slow database streams appear as application decode time. Switch back to row_fetch after counting a response row while continuing to exclude observation markers.

5 resolved since last review

Review effort: Max

@rdimitrov
rdimitrov merged commit fa88719 into main Nov 20, 2026
8 checks passed
@rdimitrov
rdimitrov deleted the codex/bounded-updated-page-query branch November 20, 2026 09:31
rdimitrov added a commit that referenced this pull request Nov 20, 2026
Grow only the dedicated production database node from e2-standard-4 to
e2-standard-8 and give PostgreSQL six CPUs, matching the configuration
tested with #1865. Application workers remain e2-standard-4; app HPA,
connection pools, memory, shared buffers, storage, and node-count bounds
remain unchanged.

The databaseNodeMachineType override defaults to the existing
worker-sized pool when omitted and is guarded to isolated production.
PostgreSQL 3/3 remains supported on the larger node for staged
upgrade/rollback. The protected pool keeps its identity and SURGE
settings; resizing restarts the singleton DB and reattaches its existing
PVC. App image promotion is separate.

Validation: deployment Go tests and 61 deployment-script Python tests
passed. Full production preview shows three updates only: DB pool
machine type, registry-pg CPU request/limit and Kubernetes provider
metadata; 216 resources unchanged, no replacements/deletions. Worker
pool, Grafana, networking and all PVCs are unchanged. Region quota has
headroom, no competing GKE operation was present, and the DB volume has
about 48 GiB free. Latest production backup completed November 20.

Rollout requires a temporary CNPG node maintenance window with
reusePVC=true to permit graceful movement of the protected singleton
primary. Restore normal maintenance/PDB protection after DB readiness
and PVC identity verification. The application release is promoted after
index prebuild/validation and DB recovery. Raw production state and
preview remain private.
rdimitrov added a commit that referenced this pull request Nov 20, 2026
Promote production from 1.8.9 to 1.8.10 (source
fa88719), including #1865's
updated-since query and covering-index improvements. Replicas, HPA,
connection pools, cache settings, and database resources are unchanged
by this PR.

Validation: release build succeeded and amd64 image digest was verified.
Both covering indexes were built concurrently and validated in
production; previous indexes remain for rollback. #1873 deployed the
eight-vCPU database node with six CPUs allocated to PostgreSQL; database
identity and PVCs are preserved, database is Ready, and the primary PDB
is restored. CI and CodeQL pass. A fresh production preview shows
exactly one deployment update (image and rollout annotation), no
replacements or deletions.

After deployment, verify migration 020, the released image digest, API
readiness, errors, latency, and pool queues. The database node/resource
upgrade involved maintenance interruptions; monitor recovery separately
from application performance.
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