Skip to content

Optimistic concurrent history append for Postgres task store and tests - #221

Merged
MisterVVP merged 10 commits into
dev-optimize-postgresql-write-saturationfrom
dev-continue-postgresql-write-path-optimization
Aug 25, 2026
Merged

MisterVVP merged 10 commits into
dev-optimize-postgresql-write-saturationfrom
dev-continue-postgresql-write-path-optimization

Conversation

@MisterVVP

@MisterVVP MisterVVP commented Aug 23, 2026 •

Copy link
Copy Markdown
Owner

Motivation

  • Replace a transaction/SELECT ... FOR UPDATE based history append with an optimistic conditional-update to avoid long locks and allow concurrent appends.

Description

  • Add cached SQL builders and members snapshot_sql_, conditional_create_sql_, and conditional_update_sql_ and construct them in PostgresTaskStore using Build* helpers.
  • Implement SelectTaskHistorySnapshot, UpdateTaskHistory, and a TaskHistorySnapshot helper struct to read a task and revision and to perform a revision-checked update (incrementing revision).
  • Replace the transactional AppendTaskHistory logic with an optimistic retry loop that reads a snapshot, checks for dedupe, appends the message, and attempts a conditional update by expected revision, retrying on contention; keep telemetry updates for dedupe.
  • Add small helpers and constants, update includes and header to expose the new members, and remove the previous FOR UPDATE + transaction path.

Testing

  • Updated store conformance tests and added PostgresAppendHistoryPreservesMetadataAndReportsWriteDiagnostics and ConcurrentPostgresHistoryAppendsPreserveBothMessages to validate diagnostics, metadata preservation, and concurrent appends.
  • Ran the store conformance suite (Postgres-backed tests); the new and modified Postgres history tests passed.
  • Existing Postgres store conformance tests including acquire-failure propagation were exercised and passed.

@MisterVVP MisterVVP added the codex Automatic label added by codex agent. Should not be used label Aug 23, 2026 — with ChatGPT Codex Connector
@MisterVVP MisterVVP self-assigned this Aug 23, 2026
@MisterVVP MisterVVP added AI agent AI agent contribution and removed codex Automatic label added by codex agent. Should not be used labels Aug 23, 2026
@MisterVVP MisterVVP added the performance Performance improvement related tasks based on benchmark results. Performance tests changes. label Aug 24, 2026
@MisterVVP
MisterVVP force-pushed the dev-continue-postgresql-write-path-optimization branch from a032e23 to bce2b14 Compare August 25, 2026 09:21
@MisterVVP
MisterVVP marked this pull request as ready for review August 25, 2026 11:02
@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this PR

@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: fc454e5d98

ℹ️ 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".

@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this PR again pls

@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: 05f2a80a96

ℹ️ 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".

@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this PR again

@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: 6658515215

ℹ️ 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 docs/performance-testing.md Resolved
@MisterVVP

Copy link
Copy Markdown
Owner Author

@codex review this PR again

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 134744a1f7

ℹ️ 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".

@MisterVVP
MisterVVP merged commit bc8e51f into dev-optimize-postgresql-write-saturation Aug 25, 2026
@MisterVVP
MisterVVP deleted the dev-continue-postgresql-write-path-optimization branch August 25, 2026 14:37
MisterVVP added a commit that referenced this pull request Aug 25, 2026
…ency (#219)

## Motivation

Issue #206 identified PostgreSQL write saturation between concurrency 16
and 64 while connection-pool acquisition remained negligible. The goal
of this PR is to remove measured SDK/SQL/schema overhead from the
affected task and push write paths without weakening correctness,
transaction safety, least-privilege behavior, or TCK compatibility.

## What changed

### PostgreSQL write-path diagnostics

- Extends the focused `postgres-write` profile with PostgreSQL-side
diagnostics for:
  - wait events;
  - WAL/database counters;
  - `MultiXactMember` / `MultiXactOffset` SLRU activity;
  - per-operation PostgreSQL phase latency and call counts.
- Distinguishes optimistic `task_history_snapshot` reads from legacy
`task_history_lock_read` attribution.
- Keeps the focused profile at pool size 64 with c1/c4/c16/c64 and five
repetitions.
- Fixes the push-create warmup fixture so warmup and measured IDs cannot
collide.
- Keeps query-plan fixtures at the configured fan-out after `EXPLAIN
ANALYZE` insert probes.

### Push-config create/delete coordination

- Replaces task-row `FOR KEY SHARE` coordination with schema-scoped
transaction advisory locks.
- Push create/update takes the shared advisory lock; task deletion takes
the matching exclusive advisory lock in a `BEFORE DELETE` trigger.
- Advisory keys include the schema-qualified task-table identity plus
the complete task ID, avoiding cross-schema interference.
- Rejects local task-aware push creation under `REPEATABLE READ` /
`SERIALIZABLE`, where a stale transaction snapshot could otherwise
survive an advisory-lock wait.
- Preserves least-privilege operation without requiring task-table
`UPDATE`.
- Hardens externally managed schema validation, including case-sensitive
validation of the delete-lock key seed.

### Push write amplification

- Removes the redundant push-config task secondary index.
- Removes the remaining push ordering index after validating that list
ordering still comes from explicit `ORDER BY created_sequence`.
- Keeps the `(task_id, config_id)` primary key as the write/conflict
index.
- Updates managed-schema and manual-migration documentation accordingly.

### Task send path

- Separates explicit task-ID resolution from authoritative task
validation.
- Reuses the already fetched task snapshot instead of performing
redundant task-store reads.
- Preserves context, terminal-state, and requested-task identity
validation.
- Updates lifecycle benchmarks to measure the extracted validation step
rather than only the ID resolver.

### Optimistic task-history writes

- Replaces transaction / `SELECT ... FOR UPDATE` history appends with
bounded optimistic revision-checked updates.
- Retries revision conflicts with a fixed upper bound instead of
allowing an unbounded loop.
- Includes `created_sequence` in the history CAS predicate to prevent
delete/recreate ABA overwrites.
- Adds deterministic concurrent-append and task-recreation coverage.
- Preserves both concurrent messages and task metadata without holding a
row lock across the append flow.

### Benchmark/API and local-build cleanup

- Keeps `PushConfig_CreateMany` on the same public executor/service path
used by production.
- Removes the benchmark-only PostgreSQL batch API and its unused SQL
builder rather than hardening an API with no production caller.
- Removes benchmark/test-only shortcuts that would make before/after
results incomparable.
- Fixes the Windows local FetchContent example path/toolchain handling.
- Updates storage and performance documentation to describe the final
advisory-lock and optimistic-history designs.

## Performance comparison

### Sources

Main-equivalent baseline:

- PR #218 final CI: `32015617204`
- PR #218 head: `d1e06d66934992e73745297e93f459c7bf41eb22`
- merged `main`: `1f5ea572b7f3528ee638c5a371b83a59f5e97660`
- baseline tree matches the merged-main tree used for the comparison.

Final combined PR (#219 + #221):

- CI: `32860693863`
- head: `bc8e51fb59e8a56e9b1eceabda061dbdbeb4615a`
- TCK: `32860693755`
- CI and TCK both passed.

The focused table below uses five-run medians from `postgres-write`,
pool size 64.

### Focused c64 results

| Scenario | Main c64 | Final PR c64 | Throughput vs main | c64 p95:
main → PR | c64 p99: main → PR | c16→c64: main → PR |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| `PushConfig_Create` | 4,817 ops/s | **5,356 ops/s** | **+11.2%** |
31.01 → **30.09 ms (-3.0%)** | 81.21 → 81.26 ms (+0.1%) | -24.9% →
**-21.9%** |
| `PushConfig_CreateMany` | 734 ops/s | **831 ops/s** | **+13.3%** |
129.03 → **115.33 ms (-10.6%)** | 167.74 → **141.35 ms (-15.7%)** |
-13.5% → **-11.3%** |
| `SendMessage_CreateTask` | 2,883 ops/s | **3,892 ops/s** | **+35.0%**
| 53.07 → **39.19 ms (-26.1%)** | 74.76 → **54.59 ms (-27.0%)** | -3.4%
→ -6.4% |
| `SendMessage_FollowUpExistingTask` | 2,202 ops/s | **2,878 ops/s** |
**+30.7%** | 58.34 → **47.26 ms (-19.0%)** | 77.05 → **63.59 ms
(-17.5%)** | -4.5% → **-2.4%** |

The important change after folding #221 into #219 is that the previous
follow-up-task regression is gone. All four focused c64 paths now have
higher throughput than the main-equivalent baseline, and three of four
also improve both p95 and p99.

`SendMessage_CreateTask` now has substantially higher absolute
throughput and materially lower tails at c64 even though its c16→c64
percentage is slightly worse because c16 improved even more strongly.

### Normal in-process PostgreSQL matrix

Across c1/c4/c16/c64 in the normal CI matrix, geometric-mean movement
versus the main-equivalent baseline is:

| Scenario | Throughput geometric mean | p95 geometric mean |
| --- | ---: | ---: |
| `PushConfig_Create` | **+13.9%** | **-6.7%** |
| `PushConfig_CreateMany` | **+22.6%** | **-46.2%** |
| `SendMessage_CreateTask` | **+30.3%** | **-22.2%** |
| `SendMessage_FollowUpExistingTask` | **+13.7%** | **-5.1%** |
| `SendMessage_FollowUpAtHistoryDepth/8` | **+12.8%** | **-6.3%** |

The normal matrix therefore supports the focused result: the final
combined branch no longer has a follow-up-task throughput regression,
while create-task remains the largest measured gain.

### Structural database evidence

The final profile also shows that the intended work was removed from the
hot paths:

| Signal | Main | Final PR |
| --- | ---: | ---: |
| `SendMessage_CreateTask` task reads/op | 1 | **0** |
| `SendMessage_FollowUpExistingTask` task reads/op | 2 | **1** |
| Push-create MultiXact SLRU activity | row-lock path could generate
MultiXact work | **0 across final focused push rows** |
| c64 connection-acquire p95 | negligible | **still negligible (sub-µs
on the focused write paths)** |

The remaining high-concurrency drop is most visible in push-create, but
the final profile still does not point to connection-pool starvation.
Residual pressure is primarily PostgreSQL-side write/WAL/buffer
contention rather than avoidable SDK connection waiting.

## Benchmark comparability note

This PR fixes a correctness bug in the push benchmark fixture: warmup
and measured push-create IDs previously overlapped, so the
main-equivalent baseline could update warmup rows instead of measuring
disjoint creates.

Because of that:

- task-path main-vs-PR absolute comparisons remain directly comparable;
- push-path **c16→c64 scaling within each run** remains the strongest
cross-version signal;
- absolute push throughput/latency deltas against the old main artifact
should still be treated as directional rather than a perfectly identical
workload comparison.

GitHub-hosted runner variability also means small single-digit movements
should not be overinterpreted. The focused five-repetition medians are
the stronger signal for this PR.

---------

Co-authored-by: Vladimir Pavlov <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI agent AI agent contribution performance Performance improvement related tasks based on benchmark results. Performance tests changes.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant