Skip to content

executor: report a chain of lock holders as the whole wait - #700

Open
Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd139-holder-chain-whole-wait
Open

Kiran01bm wants to merge 1 commit into
mainfrom
kiran01bm/pd139-holder-chain-whole-wait

Conversation

@Kiran01bm

Copy link
Copy Markdown
Collaborator

When the wait outside the lock queue runs out on a chain of overlapping readers, the error and the verdict's lock_holder.held_ns now report the whole wait, not just the last reader's share.

Why

Before taking a strong lock, pg-sprite waits for existing lock holders to finish, so other sessions do not queue up behind it. If the table is never free for the whole wait, the step stops and names who held the lock. When many short readers overlapped with no gap between them, it named the last one and said that one backend "held a lock for the whole 0s the step waited", which is both wrong and confusing to an operator.

What

  • awaitLockQueue sets LingeringHolderError.Watched to the whole wait. The wait only runs out when every read shared a holder with the read before, so the table was held with no gap for all of it. since still picks the PID to name.
  • The message no longer claims one backend held the table throughout.
  • A single long reader reports the same values as before: it is seen from the first read, so its share is the whole wait.
  • Doc comments on LingeringHolderError, verdict.LockHolder.Held and migrate.lockHolder, and the held_ns text in docs/schemabot-integration.md and docs/cli-output-examples.md, now say it is the whole wait.
  • Test: TestAwaitLockQueueReportsTheWholeWaitOnAChainOfOverlappingReaders runs test(executor): pin the lock-queue wait stopping on chained readers #687's chain through awaitLockQueue and asserts PID (reader 4), Watched 950 ms exactly (fake clock), and budget-lock-exceeded. It fails without the fix with expected: 950ms, actual: 150ms.

Before / after

Five short readers on public.orders overlap with no gap during a 950 ms wait; reader 4 is the last and was seen for the final 150 ms.

Before
  wait runs out ──▶ Watched = 950 ms - reader 4's start = 150 ms
  held_ns       ──▶ 150000000
  message       ──▶ "backend 4 (...) held a lock on public.orders for
                     the whole 0s the step waited, ..."

After
  wait runs out ──▶ Watched = whole wait = 950 ms
  held_ns       ──▶ 950000000
  message       ──▶ "one transaction, or several overlapping without a
                     break, held a lock on public.orders for the whole 1s
                     the step waited, and backend 4 (...) still held it
                     when the wait ran out, ..."

A wait that ran out on overlapping readers reported only the last
reader's share, printed as "0s"; report the unbroken hold instead.
@Kiran01bm
Kiran01bm marked this pull request as ready for review December 2, 2026 08:36
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-12-02T08:36:45.378249Z
We couldn’t complete this review. Comment @codex review to try again.
d71452e 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@aparajon

aparajon commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

🤖 Review 1/2 (correctness) of d71452e: 0 blocking, 1 non-blocking in this comment (3 across both comments).

Inspected the whole change at d71452ea79b9a79ee0df337c399117b3e55fdc05 (+103/-46, 11 files), against the full wait it edits, pkg/executor/lock_holder_wait.go, every exit of waitOutsideLockQueue, and the places that read LingeringHolderError.Watched (pkg/migrate/lock_holder.go, the cutover and live-run tests). CI at the time of posting: every reported check green, including unit tests (no Docker; docs guards), lint, smoke test (built pg-sprite artifact), Supabase compatibility, the PostgreSQL 14 to 17 legs, and both PostgreSQL 18 legs.

The PR changes only what is reported, not what is bounded. waitOutsideLockQueue is untouched (its sampling, its one deadline, its read reserve and its exit conditions are the same lines as on main), and awaitLockQueue still returns a *LingeringHolderError in exactly the cases it did. The one behavioural edit is Watched: outcome.waited in place of outcome.waited - outcome.holder.since, plus the message and the doc comments that follow from it. For a single long reader the two expressions are equal (it is first seen at the first read, so since is 0), which is why the existing integration assertion TransactionAge >= Watched still holds; for a chain of overlapping readers the old value was the last reader's share (150 ms of a 950 ms wait in the PR's example) and read as "the whole 0s the step waited". The chain-continuity argument the new comment makes is right for every exit that follows a completed read: the loop only continues when some transaction in the new read was also in the one before it (L318-L320), so at every instant between the first and the last completed read at least one transaction held a conflicting lock. The new test, TestAwaitLockQueueReportsTheWholeWaitOnAChainOfOverlappingReaders, pins that with the fake clock (950 ms exactly) and fails on the old expression with expected: 950ms, actual: 150ms, as the PR body says.

Invariants (docs/invariants.md at the head): LK-2 ("every strong lock is bounded", #L840) is the entry this sits under, since the wait outside the lock queue is one of its enforcement points (its *Enforced:* text at #L871-L878 names LingeringHolderError). The PR upholds it: no lock_timeout, statement_timeout, HolderWait, retry or backoff value moves, and the step still ends without requesting its lock. Nothing in the entry needs rewording, and the files it names are unchanged.

Non-blocking

  1. The new comment, and the new message, state "held without a break for the whole wait" and "still held it when the wait ran out" for exits that did not establish either. The comment at #L457-L459 says a wait runs out only when every read shared a holder with the read before it, and Error() (#L392) now adds that the named backend "still held it". Two exits of waitOutsideLockQueue produce an exhausted outcome without a completed read behind that claim:

    • The in-loop read the deadline cut off (#L312-L313). After the last sleep the read has at least the 50 ms reserve; on a loaded catalog it can exceed that and bounded reports the timeout. The outcome then names the holder from the last read that finished, with waited taken after the failed read. The table is known held without a break up to that earlier read, and nothing is known after it. A holder that committed during the last sleep is reported as one that "still held it when the wait ran out"; the code comment inside the loop (#L295-L299) is written to avoid exactly that outcome, and this branch is where it can still happen. This predates the PR (the old message said "held a lock ... for the whole"), but the PR is what adds the unconditional "still held it".
    • A wait with a limit of 50 ms or less (#L301-L302). left <= 0 right after the first read exits with one completed read, so "several overlapping without a break" is not established. A cutover whose lock_timeout is that short reaches it, since AwaitAccessExclusive is called with the attempt's lock timeout as its limit.

    Neither changes what is bounded or what the step does; the error still names a real session that held the table at a read inside the wait. The fix is wording, not logic: say "at the wait's last read" in the message (true on every branch) and narrow the comment to "every read that completed". Reasoned from the code, not run: no test in the package reaches the in-loop timeout with a holder (TestWaitOutsideLockQueueBoundsItsCatalogReads times out on the first read, where no holder is known, and returns no error).

Test case (not run here: needs a live PostgreSQL): the in-loop deadline names a holder no read saw at the deadline
// A holder is seen at the first read; the wait's whole budget is spent
// during the sleep, so the second read is cut off before it starts. The wait
// still reports the holder, for the whole wait, though nothing read after
// the first sample.
func TestAwaitLockQueueNamesAHolderItNeverReReadAtTheDeadline(t *testing.T) {
	f := newHolderWaitFixture(t)
	f.exec(t, "CREATE TABLE %s.t (id int PRIMARY KEY)")
	readerPID := holdLock(t, f.admin, fmt.Sprintf("SELECT count(*) FROM %s.t", f.schema))
	tables, err := nativeLockedTables(parseStatement(t, fmt.Sprintf("ALTER TABLE %s.t ADD COLUMN note text", f.schema)), f.schema, "t")
	require.NoError(t, err)

	const limit = 500 * time.Millisecond
	start := time.Unix(0, 0)
	slept := false
	clock := holderWaitClock{
		now: func() time.Time {
			if slept {
				return start.Add(limit)
			}
			return start
		},
		sleep: func(context.Context, time.Duration) error { slept = true; return nil },
	}
	err = awaitLockQueue(t.Context(), f.admin, tables, limit, clock, func(*progress.LockHolderWait) {})

	var lingering *LingeringHolderError
	require.ErrorAs(t, err, &lingering)
	assert.Equal(t, uint32(readerPID), lingering.PID)
	assert.Equal(t, limit, lingering.Watched)
	assert.Contains(t, lingering.Error(), "at the wait's last read", "the message claims only what the last completed read showed")
}

The last assertion is the one a wording fix would make pass; at the head the message says "still held it when the wait ran out". Not run here, because it needs a PostgreSQL container.

Verified

  • Read every exit of waitOutsideLockQueue against the new claim: an empty first read passes; left <= 0 after at least one completed read (finding 1); the in-loop deadline (finding 1); a read with no shared holder passes; the loop never falls out of its for while holders is non-empty. Chain continuity holds on every exit that follows a completed read.
  • Cycles and deadlocks: the wait reads granted locks from pg_locks only (conflictingLockHolders, l.granted), not the waits-for graph (pg_blocking_pids is not used), so a holder that is itself waiting on a third session is simply a holder and no cycle can form in what is sampled.
  • The engine's own session: l.pid <> pg_backend_pid() excludes only the connection that runs the read. The PR does not touch it.
  • A holder that ends between the last read and the report: describeHolder returns on pgx.ErrNoRows leaving State empty and the typed error intact (TestDescribeHolderFailureKeepsTheTypedError covers the failed read); the message is still the truthful "held it at the last read" case. Holders are keyed by virtual transaction ID, so the same backend in two reads is one holder, and a backend with a new transaction is a new one. Among holders first seen at the same read, oldestHolder breaks the tie by map order, so which one is named varies; unchanged by this PR and harmless, since each of them had held the table equally long.
  • Output shape: verdict.LockHolder and the lock_holder JSON keys are unchanged; only the meaning of held_ns is widened and documented (verdict/lock_holder.go, docs/schemabot-integration.md#L1247-L1249, docs/cli-output-examples.md). The verdict has no format-version field (the format_version the docs mention belongs to the plan report), so nothing needs a bump. code stays budget-lock-exceeded.
  • Mutation table (by reading; the new tests need a PostgreSQL, and the PostgreSQL legs, which run the pkg/executor and pkg/migrate tests, were green at this head):
Mutant Caught by
Watched: outcome.waited - outcome.holder.since restored TestAwaitLockQueueReportsTheWholeWaitOnAChainOfOverlappingReaders (950 ms expected, 150 ms actual)
Error() returns the old single-backend sentence TestLingeringHolderErrorNamesWhatTheRoleCouldSee, TestDescribeHolderFailureKeepsTheTypedError, TestExecuteNativeEndsWithoutQueueingWhenAReaderOutlastsTheWait, TestVerdictNamesTheLingeringHolder, the TestExecRefusal subtest
migrate.lockHolder maps Held from something other than Watched TestVerdictNamesTheLingeringHolder
exhausted(oldest) on the in-loop timeout names no holder not caught (no test reaches that branch with a holder; finding 1)
docs/cli-output-examples.md example drifts from the formatter TestCLIOutputExamplesMatchPipelineOutput

This review was generated by Claude Code (claude-sonnet-5-5).

@aparajon

aparajon commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

🤖 Review 2/2 (OSS adoption and integration) of d71452e: 0 blocking, 2 non-blocking in this comment (3 across both comments).

Read the change from two seats: an operator or CI log reader who meets the new error text, and a host or downstream importer (the SchemaBot adapter and anyone else decoding the verdict JSON) that shows lock_holder to its own users. The exported surface that moves is one field's meaning, verdict.LockHolder.Held (held_ns), and one error string. No type, key, code or exit status changes, and the verdict carries no format-version field, so nothing needs a bump.

Non-blocking

  1. The wording is now hedged for every case, and the per-session figure is gone from both the text and the JSON, though the engine can tell the two cases apart. For the common incident, one session left idle in a transaction, the message reads "one transaction, or several overlapping without a break, held a lock on public.orders for the whole 3s the step waited, and backend 4123 (...) still held it" (Error(), #L392). The previous sentence named the one backend plainly, and an operator reading it had one thing to do; the new one makes them wonder whether there is a chain. The loop already knows which case it is in: a holder first seen after the first read is the holder.since = waited branch (#L321-L322), and if that never fires, one session held the table throughout. Carrying that as a bool on the outcome and the error would let the text keep the crisp single-backend sentence and use the hedged one only for a real chain.

    The same applies to a host. held_ns is now always the whole wait (pkg/migrate/lock_holder.go maps it from Watched), and how long pid itself was seen is no longer recoverable from the verdict: transaction_age_ns says how long its transaction has been open but is absent when the role cannot see the session, which is the case the wait is built to work without (pg_locks needs no privilege). A host that renders "blocked by backend 4123 for 2.9s" from pid and held_ns will now over-state a chain's last session; the docs warn about that, but a field would let the host get it right. An additive field on the verdict (for example overlapped: true, or the last session's own seen_ns) keeps held_ns's new meaning and costs a key that is omitempty for the single-holder case, so existing decoders are unaffected.

  2. Four places that tell a host or reader what lock_holder means still describe a single session that held the table for the whole wait. The PR updates verdict.LockHolder and docs/schemabot-integration.md, but not these, which now contradict them:

    • the Verdict.LockHolder field comment, pkg/verdict/verdict.go#L882-L885, which is the comment go doc and an IDE show first: "the session that held the table through a step's or a copy-and-swap cutover's whole wait";
    • the CodeBudgetLockExceeded comment, pkg/executor/code.go#L24-L27: "a transaction held a lock ... for the whole wait";
    • the budget-lock-exceeded row of the outcome-code table, docs/execution-model.md#L399: "a transaction held the table for the whole wait ... When a transaction held the table, the verdict's lock_holder names it";
    • the paragraph that lists the lock_holder keys, docs/execution-model.md#L82-L85, which names held_ns and says nothing about what it measures.

    The code comment and the table row can take "a transaction, or transactions that overlapped without a break"; the key list can link to the held_ns explanation in schemabot-integration.md#L1247-L1249. None of these is a behaviour change, but the Verdict.LockHolder comment is what an adopter reads first and it now says the opposite of the type it points at.

What reads well for adopters

  • The PR body is a model: one concrete incident (five overlapping readers, 950 ms), a before and after of the three things an operator or host sees (Watched, held_ns, the message), and the exact failing assertion without the fix (expected: 950ms, actual: 150ms).
  • The old text claimed something false in the chain case ("backend 4 ... held a lock for the whole 0s the step waited"); the new one cannot be wrong in that way, and held_ns finally lines up with the wait the operator set (--lock-timeout or the holder wait), which is what they compare it to.
  • The change stays inside reporting: the typed error, its Code() (budget-lock-exceeded), the verdict keys and the exit status are all the same, so a host that routes on code and lock_holder.pid needs no change to keep working, and the doc examples are executable (TestCLIOutputExamplesMatchPipelineOutput fails if the example and the formatter drift, which is how the two example blocks stayed in step here).
  • The refactor of the chain test into readerChainClock lets the existing and the new test share one setup, so a later test for another chain shape starts from the same helper.

This review was generated by Claude Code (claude-sonnet-5-5).

@aparajon aparajon left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 Stamping with comments: 0 blocking, 3 non-blocking (see the review comments above).

This stamp was left by Claude Code (claude-sonnet-5-5).

@JashLal

JashLal commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator

🤖 I reviewed head d71452e. The overlapping-reader regression test pins the right distinction between the 950 ms wait and the final reader’s 150 ms share. I found a diagnostic issue in the timeout path.

  1. Use the last completed sample to describe the holder. The final catalog read can time out, as traced in the earlier review. The new error then says the sampled backend still held the lock when the wait ran out. The native verdict also says the statement will run once that particular transaction ends. A later holder can still block the step. Phrase this as a last observation and tell operators the statement can be retried after the conflicting locks clear.
  2. Keep meaningful precision for short waits. Watched.Round(time.Second) still prints 0s for waits under 500 ms, even though held_ns carries a nonzero value. A formatter test for a subsecond wait would keep the text and JSON useful together.

I read the full diff, PR discussion and current checks, including the unit and PostgreSQL 14–18 jobs. I did not run local tests.

@JashLal JashLal left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🤖 Approved on the maintainer’s behalf after reviewing head d71452e. The diagnostic issue remains documented in the review comment.

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.

3 participants