Skip to content

driver/postgres: a statement that finishes quickly no longer arms the context watch - #1511

Merged
FumingPower3925 merged 3 commits into
mainfrom
pg-lazy-ctx-watch
Dec 1, 2026
Merged

FumingPower3925 merged 3 commits into
mainfrom
pg-lazy-ctx-watch

Conversation

@FumingPower3925

@FumingPower3925 FumingPower3925 commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Refs #1501, #1447

What changes and why

On a native Postgres connection in direct mode, every statement whose context can end used to register a context.AfterFunc before it read the reply and stop it afterwards. That is what makes a call end when its context ends (#1447), and it costs about 0.8 us of CPU and four allocations (384 B) per statement on the driver-pg-read cell, the largest single piece of the gap to v1.5.11 (#1501).

Now a statement that gets its reply quickly arms nothing. The connection carries one rolling read deadline (now plus 2 ms), refreshed only when less than half of it is left. A read that times out on it with the context still alive has waited past the bound: from there the statement is watched exactly as before (the same AfterFunc, the same settle-before-drain order). A context deadline inside the bound is put on the socket as it is, so a deadline is not delayed.

Every read deadline of a direct connection is now set through three methods that keep the rolling-deadline flag true only while the socket carries that deadline, and a test fails if any other call sets one.

What the caller sees

A cancel is noticed up to 2 ms after it lands, plus the platform's timer latency; a statement that finishes in that window returns its result; a deadline is not delayed.

The same text is in the Context section of the Pool documentation. A statement that has waited longer than 2 ms ends as soon as its context does, as before.

Release note: The native Postgres pool and database/sql connections in direct mode no longer arm a context watch for a statement that finishes quickly, which gives back most of the per-statement cost of ending a call when its context ends. A cancel is noticed up to 2 ms after it lands, plus the platform's timer latency; a statement that finishes in that window returns its result. A deadline is not delayed.

Cost, measured

Linux arm64 VM, Postgres 16 in a separate container (fsync off), one connection, one statement per iteration (SELECT 1 FROM pg_sleep($1)) under a fresh context.WithTimeout(5 s), three builds interleaved in rotating order, 12 rounds each, benchstat. "main" is main before this change. The CPU of the client process is within the run-to-run noise at every row (at the slow rows the spread is 33 to 70 % of a mostly idle process; on the quick statement it is 14.06 us here against 14.15 us on main).

Statement wall v1.5.11 wall main wall this change allocs v1.5.11 / main / this change bytes v1.5.11 / main / this change
quick (pg_sleep 0) 31.3 us 31.7 us 31.9 us 11 / 16 / 12 504 / 1080 / 696
3 ms 4.997 ms 5.214 ms 5.128 ms 12 / 17 / 18 512 / 1091 / 1177
10 ms 12.33 ms 12.41 ms 11.81 ms 12 / 17 / 18 512 / 1097 / 1178
50 ms 53.10 ms 53.21 ms 53.04 ms 12 / 17 / 18 512 / 1132 / 1319

Wall time differs by less than the run-to-run spread at every row. The same run with a separate-process fake backend (3, 10 and 50 ms) gives the same picture.

The quick statement drops four allocations and 384 B. A statement that waits longer than 2 ms allocates ONE more object than main: the net.OpError that the standard library builds when the rolling read deadline fires (80 to 190 B per such statement). It cannot be avoided while the first wake of a waiting read is a read deadline, and it was accepted for the slow path.

Cancel latency, and what is not ours

400 cancels at random instants of a statement that never answers, ten runs each, GOMAXPROCS 2, same VM, the cancel exchange included:

  • main: 0 of 4000 cancels took more than 3 ms to return; the largest was 2.35 ms.
  • this change: 10 of 4000 took more than 3 ms, 4 took more than 5 ms; the largest was 20 ms.
  • A bare net.Conn read with a 2 ms read deadline, no celeris code at all, three runs of 4000 reads: 9 reads returned more than 3 ms after the deadline, 2 more than 5 ms, the largest 31 ms (12000 reads). The program and its output are kept with the measurements.

The tail comes from the timer wake of the platform (the VM here), not from the driver: a cancel inside the bound is noticed by a read deadline firing, and a read deadline fires late by the same amount for any program. Main has no such tail because its watch is woken by the cancel itself, not by a timer.

Tests

Eight tests asserted how the watch is armed rather than what a call returns, and change their expectation:

  1. The test that every statement under a cancellable context arms the watch now asserts it for statements that wait (the backend answers after 30 ms), and a new test asserts that a statement answered at once arms nothing.
  2. The test that the watch callback exists after a statement now runs the statement with the reply held back 10 ms, and has rows for a statement answered at once.
  3. The test of a callback held in flight across the end of a statement holds the reply back 12 ms so that the watch is armed before the context ends; the handshake it checks is the same.
  4. The test that a timer-context statement that answers sets no socket deadline now asserts it puts only the rolling deadline on the socket (no deadline of the context's, and the statement after it, under no context, clears it).
  5. to 8. The three tests of the socket-deadline sequence of a timer or other context that ends mid-statement and the test of the callback in flight at the end of a timer-context statement expect the sequence rolling deadline, its clear, the callback's wake, the final clear, where they expected the wake and the clear. That is right because the watch is armed once the statement has waited past the bound; what they pin about the guarantee (the call returns the context's error, at the deadline, the conn is reused) is unchanged.

The 17 tests that pin the guarantee itself (cancel at each point of a statement, the 20,000-iteration stale-cancel loop, a deadline mid-statement, the foreign context deadline, the drain dropping rows, a deadline racing the end, a callback in flight when the drain begins, a completed request winning over an ended context, a cancel of a statement that answers on its own, an unconfirmed cancel replacing the conn, a timer context already past its deadline, a timer-context deadline racing the reply, the read deadline cleared at the end, and the COPY cancel tests) are unchanged.

Later commits add tests for what a first review asked: a deadline inside a bound of 1.5 s (deadlines of 30 and 200 ms) ends the call at the deadline, for a timer context and for a value context over one, and a deadline beyond a short bound does the same; the tests that cancel a waiting statement run the call with a 5 s limit, so a statement that is never woken fails where it stands; and a call with two rounds that are each slower than the bound (a write the connection prepares and then executes), cancelled or ended by a deadline during the second round, ends within the bound plus the timer's latency, and at the deadline, respectively.

New tests, in their own first commit where they could fail before the change: a quick statement arms no watch (fails before); a statement that waits is watched; a cancel at any instant of a waiting statement ends the call within a bound and leaves the conn usable. In the second commit: the rolling deadline does not survive a cancel drain, a COPY, or a statement under no context (the next statement is still cancellable); a cancel inside the bound is noticed when the bound ends; a statement that finishes inside it returns its result; a deadline is not delayed; a quick statement under one context sets the rolling deadline once; a statement shorter than half the bound is never watched; an idle conn serves any context after the rolling deadline expired; the bound is 2 ms (as documented); and a scan that no other read deadline is set.

Mutation check of the new flag (19 mutants, one per place the flag is read, written or set; each run against the cancel and timeout tests): 13 killed, 6 equivalent.

  • Killed: the clear in each of the two setters; the set in the rolling setter and the recording of its expiry; the Background branch (its read, and its clear done raw); both refresh conditions; the slow-path trigger; the slow path leaving the rolling deadline on the socket; the cancel drain (cleared raw); the COPY reader's stop (cleared raw); the drain's bound set raw (caught by the scan only).
  • Equivalent: a raw exact-deadline set, a raw context-deadline set in the slow path, a raw clear in the slow path, a raw clear at the end of a statement, the COPY reader's entry reset, and arming the watch before settling the deadline. Each leaves the flag true only when the stored expiry is already past, is cleared by the next setter call, or is caught by the context check at the top of the read loop.

The new deadline test kills two further mutants (the exact socket deadline kept only for deadlines already past, and removed), and the hang mutant (no watch armed once the statement is past the bound) now fails the waiting-statement tests by the 5 s limit, not by go test's timeout.

What ran

  • go build ./..., go vet of the driver packages, gofmt: clean.
  • go -C .github/tools run ./apidump: clean (api/ matches 53 packages).
  • golangci-lint 2.15.0 (the installed one; CI pins another version) on ./driver/postgres/...: two findings, both in files this change does not touch (an unchecked channel receive in two older tests); none in the changed files.
  • driver/postgres with -race -count=1 on macOS and on Linux (Docker, golang 1.27.4); internal/driver/postgres with -race (its only package with tests is the protocol package).
  • The cancel, timeout and watch tests with -race -count=20 on macOS and Linux; the 20,000-iteration stale-cancel loop with -race at count 20 on macOS and count 5 on Linux. The five tests that CI runs against a server under the postgres tag in driver/postgres (streamed infinity, connector on a started engine) also pass.
  • The Postgres conformance suite (test/conformance/postgres, -race) against Postgres 16 with scram-sha-256 in Docker: default mode and the default-engine, default-engine-ready and epoll-ready modes. All passed (Postgres 16.16, one run each, no failure).

The last commit changes tests and two comments only: the syntax tree of every non-test file of the package, comments dropped, is identical to the commit before it. Its tests were run with -race -count=20 and the package with -race on Linux (Docker).

Run separately on this head (Linux arm64 VM, Postgres 16, race and plain binaries, the native pool in direct mode and database/sql):

  • 30 cancellation and timeout cells ran to the end: no wrong value, no panic, no hang, no data race.
  • Some calls returned more than 1 s after their deadline, only in the race builds at a host load of 10 to 19, and about as often on main. With the same artificial CPU load beside each cell, alternating the two trees: main had 273 late calls of 7,004 cancelled calls (3.9 %), this change 280 of 6,659 (4.2 %); the spread between runs of one tree (3.4 to 5.0 %) is as large as that gap.
  • 320 stack dumps taken at one second late (160 per tree) all show the call inside the drain that follows a cancel, reading the rest of the cancelled statement's reply, and each returned the context's error 1.1 to 2.1 s after the deadline. That code is not changed here.
  • A call therefore returns its context's error once the connection is clean again: bounded by one second for the cancel request and thirty for the drain; on an idle machine that is at once. The Pool text above says "as soon as its context does"; it is corrected in a separate comment-only change.
  • Cluster pair on the amd64 benchmark host, native Postgres read, eight engine configurations: 1.013 over main (2 below 1.00) and 0.983 against v1.5.11 (8 below 1.00).

Not run here: the loop-path cells (they run in the release-candidate run on the cut commit), Windows, other Postgres versions.

…atched only once it waits (Refs #1501, #1447)

A statement answered at once arms no watch; one that waits is watched; a cancel
at any instant of a waiting statement ends the call within a bound and leaves the
conn usable. The first test fails on this tree (every statement under a context
that can end arms the watch); the other two pass on it and guard the guarantee
while the watch is made lazy.
…s context only once it has waited past 2 ms (Refs #1501, #1447)

A statement that gets its reply quickly no longer registers a context.AfterFunc or
puts a deadline on the socket: the conn carries one rolling read deadline,
refreshed when less than half of the bound is left, and a read that times out on
it with the context alive arms the watch exactly as before. A context deadline
inside the bound is put on the socket as it is; a cancel is noticed up to the
bound after it lands, and a statement that finishes in that window returns its
result.

Every read deadline of a direct conn goes through three methods that keep the
rolling-deadline flag true only while the socket carries the deadline. The tests
that asserted how the watch is armed (at the start of every statement, the
sequence of socket deadlines) now assert it for a statement that waits.
@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Explain Change →

Caution

Review failed

The pull request is closed.

  • Autofix · 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

@FumingPower3925 FumingPower3925 added the driver/postgres PostgreSQL driver label Dec 1, 2026
@FumingPower3925 FumingPower3925 added this to the v1.6.0 milestone Dec 1, 2026
@codecov

codecov Bot commented Dec 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

…the slow path, and a call with two slow rounds; two comments corrected (Refs #1501, #1447)

The deadline test now uses a bound of 1.5 s with deadlines of 30 and 200 ms, for a
timer context and a value context, and fails if the call ends later than the
deadline. The two tests that cancel a waiting statement run the call in a goroutine
with a 5 s limit, so a statement that is never woken fails where it stands. A new
backend answers the extended protocol in rounds, and two new tests cancel, and
end by a deadline, a call whose second round is slower than the bound.

The comment on the Background case says what the check is (context.Background()
itself), and the comment on the order of the deadline and the watch says why the
order is kept. No change to the code.
@FumingPower3925
FumingPower3925 marked this pull request as ready for review December 1, 2026 20:25
@FumingPower3925
FumingPower3925 merged commit 4bdb658 into main Dec 1, 2026
61 of 62 checks passed
@FumingPower3925
FumingPower3925 deleted the pg-lazy-ctx-watch branch December 1, 2026 20:27
FumingPower3925 added a commit that referenced this pull request Dec 2, 2026
FumingPower3925 added a commit that referenced this pull request Dec 2, 2026
… and their fake backend routes a cancel like a real one (#1515)

* tests: the postgres context-watch tests order their events by events, and their fake backend routes a cancel like a real one (Refs #1511, #1513)

TestAStatementThatFinishesInsideTheBoundReturnsItsResult failed once on a CI
runner: its first call dialled under a 5 ms timer, and the cancel landed during
the dial. It now warms up the conn, cancels when the backend has the statement,
and the backend answers only after the cancel.

The fake backends give each conn a key of its own and route a CancelRequest by
it: a cancel that reaches the backend before it has read the statement is no
longer dropped, and a discarded conn can no longer take the next conn's cancel.
Timers that ordered events are replaced by events (the backend's report, the
arming of the watch, a held callback that signals it started); the tests that
keep a timer, because the timer is what they are about, say so. Every helper
that starts a statement goroutine joins it, so a failure cannot also produce a
race report. Test files only.

* tests: drop the embedded Conn from two selectors in the postgres cancel test helper (Refs #1511)
FumingPower3925 added a commit that referenced this pull request Dec 2, 2026
…s when the kernel's send buffer is full, a Postgres call returns when its connection is clean, SocketBusyPoll as measured (#1516)

Comments only. No code, test or exported-API change.

- Config.WriteTimeout, the SSE package documentation, the WebSocket IdleTimeout
  documentation and the two engines' stall comments: the engine queues only the
  bytes the kernel's send buffer did not take, so the "no progress for
  WriteTimeout" clock starts when that buffer is full; the buffer grows up to
  net.ipv4.tcp_wmem's maximum and Config.SocketSendBuf fixes it. The wrong
  "(the write only queues the event in the engine)" is gone. On epoll only an
  acknowledgement restarts the clock; on io_uring a send completion that took
  bytes also does.
- Config.SocketSendBuf and Config.SocketRecvBuf: the std engine ignores both.
- Config.SocketBusyPoll: what measuring it on and off from one binary showed,
  and that busy polling spends CPU.
- Pool, "Context": what a cancelled call waits for before it returns.
- Context.Detach: the native engines' WriteTimeout bound on a detached
  connection.

Refs #888, Refs #1511, Refs #1513
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

driver/postgres PostgreSQL driver

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant