Skip to content

fix(orchestrator): never return an already-expired lock lease - #22

Open
waldemort-auto[bot] wants to merge 1 commit into
mainfrom
waldemort/fix-21-expired-orchestration-lock-lease
Open

fix(orchestrator): never return an already-expired lock lease#22
waldemort-auto[bot] wants to merge 1 commit into
mainfrom
waldemort/fix-21-expired-orchestration-lock-lease

Conversation

@waldemort-auto

Copy link
Copy Markdown

Fixes #21.

Problem

fetch_orchestration_item could return an orchestration item whose lock lease had already expired at the moment it was returned. Every ack against that lease failed with Invalid lock token, so the turn's work was discarded, the message became visible again immediately, and the cycle repeated indefinitely.

The max_attempts poison path could not stop it either: poison marking, backoff, and the attempt-count increment all commit through an ack keyed on that same dead lease, so all three failed together. The message was never poisoned, never backed off, and never abandoned with a delay — its retry interval collapsed to the lock lease, the most aggressive retry the system can produce, applied to the message that most needed to be left alone.

Two defects combined to produce this, both in the stored procedure:

  1. Deterministic candidate selection followed by a blocking advisory lock. ORDER BY q.visible_at, q.id LIMIT 1 is deterministic, so every dispatcher in the fleet independently computed the same candidate and then blocked on the same advisory key. The FOR UPDATE ... SKIP LOCKED re-verification could not prevent this — the blocking had already happened.

  2. The lease was computed from a pre-wait timestamp. p_now_ms is minted by the Rust caller before the call and was never refreshed. When the advisory wait exceeded p_lock_timeout_ms, locked_until was written already in the past. The same stale value was also the liveness reference for candidate visibility and for stealing expired locks, so a long-running call became progressively less able to make progress.

These compound: a trapped message never commits, so its visible_at never advances, so it remains permanently the oldest row and is selected first by every dispatcher on every poll.

Changes

Migration 0024 rebuilds fetch_orchestration_item on top of the 0019 definition. Signature, return shape, and all downstream behavior (message batching, history/metadata fallback, KV snapshot) are unchanged.

Change Rationale
pg_try_advisory_xact_lock replaces pg_advisory_xact_lock Contended instances are skipped, not waited on, and excluded from re-selection within the call. Same-instance mutual exclusion is preserved — this is still the deadlock guard from the instance-level locking fix; only the waiting is removed.
Lease derived from v_now_ms = p_now_ms + elapsed-inside-call The lease is always p_lock_timeout_ms in the future relative to when it is actually written.
Advisory key scoped to <schema>.<instance_id> See below.
Retry loop bounded (50 iterations) Exhausting it returns no item, which the dispatcher already treats as "nothing available"; the next poll starts with a fresh clock.

On the clock

Migrations 0006 and 0012 deliberately moved these procedures onto a Rust-supplied timestamp to avoid app/database clock skew. This change does not walk that back. Only an elapsed duration is taken from the server clock:

v_now_ms := p_now_ms + (EXTRACT(EPOCH FROM (clock_timestamp() - v_call_start)) * 1000)::BIGINT

No absolute server timestamp is ever used, so the caller's epoch remains the single time reference and no cross-clock skew is introduced against visible_at / locked_until values written elsewhere.

Second defect found while fixing the first

PostgreSQL advisory locks live in a single database-wide space, but the key was hashtext() of the instance id alone. Two duroxide schemas in the same database therefore serialized against each other whenever they happened to use the same instance id — entirely unrelated work contending on one key.

While acquisition blocked, this was invisible: the loser waited, then proceeded. With non-blocking acquisition it would surface as a spurious skip. It was caught here because duroxide's own provider_validation suite (atomicity_tests::test_concurrent_ack_prevention) began failing under parallel test execution, where each test uses its own schema but shares one database. It passes in isolation and passes now that the key is scoped.

Rolling-upgrade note: during a mixed deployment, nodes on the previous migration hash the unscoped key while upgraded nodes hash the scoped one, so the advisory layer does not mutually exclude across that boundary for the duration of the rollout. Correctness does not depend on it — instance_locks plus FOR UPDATE ... SKIP LOCKED still serialize the claim — and the provider already retries deadlock (40P01) errors, so the window degrades to the pre-advisory-lock behavior rather than to incorrect results.

Verification

Measured against disposable PostgreSQL 17.11 and 18.6 (the versions the downstream consumer supports; CI itself pins postgres:15). Contended fetch = a competing session holding the instance advisory lock for 3s while the fetch runs with a 1s lock timeout.

Measurement Before After
Contended fetch, time blocked 2.61 s 0.05 s
Contended fetch, lease returned −1,658 ms (already expired) none returned
Contended, with other work available picked the contended instance after 2.61 s picked the free instance in 0.06 s
Uncontended fetch, lease 4,958 ms 4,958 ms (unchanged)

Full suite, both versions: 353 passed / 0 failed / 9 ignored. cargo fmt --all --check clean.

The test proves the bug

tests/expired_lease_regression_test.rs fails with migration 0024 removed, on both 17.11 and 18.6:

fetch_orchestration_item blocked for 2.607683209s behind a contended instance
(limit 2s); the advisory lock is convoying

and passes with it. The competing session holds both the legacy unscoped key and the new scoped key, so the test reproduces contention against the procedure either side of this migration rather than silently failing to contend.

Notes for reviewers

  • Repro A in fetch_orchestration_item writes an already-expired lock lease when the advisory lock wait exceeds the lock timeout #21 does not actually fire. Passing a deliberately stale p_now_ms also makes the row invisible via visible_at <= TO_TIMESTAMP(p_now_ms / 1000.0), so the function returns 0 rows. The real mechanism is a genuine advisory-lock wait with a fresh caller clock. I will correct the issue text.
  • 0022 is intentionally skipped — reserved by the concurrent worker_queue dequeue PR (perf(worker_queue): partial index + two-phase fetch_work_item dequeue #18). This migration is independent and applies cleanly whether or not 0022 is present.
  • include_dir! has no rerun-if-changed. Adding a migration file alone does not rebuild the crate, and CI restores a cargo build cache keyed on Cargo.lock, so a migration-only PR can silently test a stale migration set. This bit during development — the suite reported a failure against a binary that still had the old procedure embedded. Worth considering a build.rs emitting cargo:rerun-if-changed=migrations.
  • cargo clippy fails on pre-existing code (src/provider.rs:2492, if_same_then_else) on unmodified main. CI does not run clippy; left alone here rather than mixing an unrelated change into this PR.
  • The core-side half of this failure — poison disposition depending on the lease it is trying to escape — is tracked separately in Poison disposition rides the very lease it is trying to escape, so max_attempts cannot terminate a message with an expired lock duroxide#47. A provider that never returns an expired lease is necessary but not sufficient; the runtime should also survive being handed one.

fetch_orchestration_item could return an orchestration item whose lock
lease had already expired at the moment it was returned. Every ack
against that lease failed with 'Invalid lock token', so the turn's work
was discarded, the message became visible again immediately, and the
cycle repeated indefinitely -- including the max_attempts poison path,
which commits through the same ack and so could never terminate it.

Migration 0024 rebuilds the procedure on top of 0019:

- pg_try_advisory_xact_lock replaces the blocking pg_advisory_xact_lock.
  Candidate selection is deterministic (ORDER BY visible_at, id LIMIT 1),
  so every dispatcher converged on the same key and queued behind it.
  Contended instances are now skipped and excluded from re-selection
  within the call. Same-instance mutual exclusion -- the deadlock guard
  -- is preserved; only the waiting is removed.

- The lease is derived from an effective clock, v_now_ms, equal to the
  caller's p_now_ms advanced by time actually elapsed inside the call.
  Only the elapsed duration comes from the server clock, never an
  absolute server timestamp, so the Rust-supplied epoch established by
  0006/0012 remains the single time reference.

- The advisory key is scoped to '<schema>.<instance_id>'. PostgreSQL
  advisory locks share one database-wide space, so the previous unscoped
  key made two duroxide schemas in the same database serialize against
  each other on identical instance ids. Blocking acquisition hid this;
  non-blocking acquisition would surface it as a spurious skip.

- The retry loop is bounded; exhausting it returns no item, which the
  dispatcher already treats as 'nothing available'.

Signature, return shape, and all downstream behavior are unchanged.

Measured on PostgreSQL 17.11 and 18.6 (contended fetch, 1s lock timeout,
3s competing hold):

  before: blocked 2.61s, lease returned 1658ms already expired
  after:  blocked 0.05s, contended instance skipped, live lease

tests/expired_lease_regression_test.rs fails without this migration
('the advisory lock is convoying') and passes with it. Full suite:
353 passed / 0 failed on both 17.11 and 18.6.

Fixes #21

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@microsoft-github-policy-service

Copy link
Copy Markdown
Contributor

@waldemort-auto[bot] please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

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.

fetch_orchestration_item writes an already-expired lock lease when the advisory lock wait exceeds the lock timeout

0 participants