Skip to content

fix(sqs): confirm standard queue drain with queue attributes before exit_on_empty - #142

Open
rahulpatra-pattern wants to merge 2 commits into
mainfrom
fix/sqs-standard-queue-drain-before-exit
Open

rahulpatra-pattern wants to merge 2 commits into
mainfrom
fix/sqs-standard-queue-drain-before-exit

Conversation

@rahulpatra-pattern

Copy link
Copy Markdown

Description

Make exit_on_empty on the SQS reader confirm the queue is drained for standard queues too, instead of exiting on the first empty ReceiveMessage.

1. Problem

With exit_on_empty: true, the reader on a standard queue exits successfully on the first empty receive. Messages that another worker, or an earlier failed attempt, received but did not delete are invisible until the visibility timeout ends (for example 1800 s). If the reader polls while they are in flight, it sees an empty receive and exits green. The messages reappear about 30 minutes later with no reader.

2. Root cause

In internal/pkg/pipeline/task/sqs/sqs.go, shouldExitOnEmpty had a shortcut:

if !s.isFifo() {
    return true
}

Only FIFO queues got a real drain check (no outstanding receipts held by this process, and GetQueueAttributes showing visible, in-flight and delayed counts all 0, added in #123). messageAck.Ack(failed=true) deliberately leaves the receipt alone so SQS redelivers after the visibility timeout. Those messages are therefore invisible to the reader's empty receive by design.

3. Incident evidence

Pattern data-acquisition, Amazon PDP daily_v1 DAG, 23 Nov 2026 (DATA-11609, amazon_pdp_daily_v1, data-airflow PR #8237). After worker failures the US queue was left with 84 messages in the queue plus 150 in its DLQ after the recovery run, even though the reader exited green. The downstream Airflow queue_drained check then failed the run.

4. Fix and behaviour change

  • The drain check now applies to standard queues. After an empty receive the reader calls GetQueueAttributes and exits only if ApproximateNumberOfMessages, ApproximateNumberOfMessagesNotVisible and ApproximateNumberOfMessagesDelayed are all 0. Otherwise it logs and keeps polling.
  • FIFO behaviour is unchanged: any receipt held by this process blocks the exit, and the attribute counts must all be 0.
  • Deviation for standard queues: receipts this process itself still holds are subtracted from the in-flight count (in_flight - outstanding). Without this, a pipeline whose downstream task holds acks until its input closes (for example the unflushed tail of a join, as in test/pipelines/sqs_fanout_fanin_dag.yaml, which uses a standard queue) would never exit, because the reader would wait on acks that can only settle after the reader stops. For FIFO the existing rule (outstanding > 0 blocks) is kept as is.
  • Other consumers: if another consumer holds in-flight messages, the reader now keeps polling until their visibility timeout expires, then receives and processes them in the same run. This can be as long as the visibility timeout. It is intended. Use end_after to bound a run.
  • Messages that failed in this process (Ack(failed=true)) are no longer counted as held once the ack settles, so they also keep the reader polling until the visibility timeout expires and they are redelivered. They then move toward the DLQ via the queue's maxReceiveCount redrive policy rather than being silently left behind.
  • IAM: sqs:GetQueueAttributes is now required for standard queues too. Before this change it was only called for FIFO queues. It was already listed under AWS Requirements in the README, but existing standard-queue pipelines may not have it granted. Roles must be checked before rollout.
  • Missing permission or other GetQueueAttributes errors:
    • Existing FIFO behaviour was that any error returns false, so the reader keeps polling indefinitely (only end_after or max_records stop it). That is kept for FIFO and for non-permission errors (throttling, network), since a transient error should not cause a false drain.
    • Infinite polling is a real risk for standard queues that today work only because they never call GetQueueAttributes. To avoid turning a missing IAM grant into a hung run, an AccessDenied error (codes AccessDenied, AccessDeniedException, AWS.SimpleQueueService.AccessDenied) on a standard queue logs a WARN and falls back to the previous behaviour of exiting on the empty receive. This is no worse than before, but it does not give the drain guarantee. Reviewers who prefer fail-fast (return an error) can say so; it is a one-line change.
  • Small refactor for testability: client is now a minimal sqsClient interface (ReceiveMessage, DeleteMessage, SendMessage, GetQueueAttributes) satisfied by *qs.Client. fifoQueueConfirmedEmpty / fifoDrainAttributes were generalised to queueDepth / queueDrainAttributes. A missing or non-numeric attribute is now an error (logged, keeps polling); previously it was a silent "not drained". Both keep polling.
  • README for the sqs task documents the exit_on_empty semantics (new "Exit on empty" section) and the IAM requirement.

5. Tests

New internal/pkg/pipeline/task/sqs/sqs_test.go with a fake client (table test, 18 cases plus a cancelled-context test):

  • standard queue, empty receive, all 0: exit
  • standard queue, NotVisible > 0, visible > 0 or delayed > 0: no exit
  • standard queue, NotVisible equal to own outstanding receipts: exit; NotVisible greater than own receipts: no exit
  • GetQueueAttributes error, missing or non-numeric attribute: no exit
  • standard queue, AccessDenied: exit with warning (legacy fallback)
  • exit_on_empty: false: never exits and does not call the API
  • FIFO: all 0 exits; in flight or outstanding receipts do not; errors including AccessDenied keep polling (unchanged)

Run:

gofmt -l internal/        # no output
go build ./...            # ok
go vet ./internal/pkg/pipeline/task/sqs/...   # ok
go test ./internal/pkg/pipeline/task/sqs/...  # ok

Not run: an integration run against LocalStack or real SQS.

6. Rollout and risk notes

  • Before deploying, confirm every role that reads a standard queue with exit_on_empty: true has sqs:GetQueueAttributes on that queue. Without it the run still exits (with a WARN in the logs) but without the drain guarantee.
  • Runs on standard queues with in-flight messages held elsewhere can now take up to the visibility timeout longer. Check Airflow task timeouts and end_after on those pipelines.
  • ApproximateNumber* attributes are eventually consistent, so the check reduces rather than eliminates the race. A queue can briefly read 0 right after messages are sent.
  • Repo usage: the only in-repo pipelines with exit_on_empty: true are the LocalStack fixtures test/pipelines/sqs_with_context_concurrency.yaml and test/pipelines/sqs_fanout_fanin_dag.yaml (both standard queues), plus a docs example in the top-level README. Production pipelines live outside this repo.
  • To disable: set exit_on_empty: false (default; the reader then never exits on an empty receive, as before), or bound the run with end_after. FIFO behaviour is unchanged, so no action is needed there. Reverting this PR restores the old standard-queue behaviour.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • Docs change / refactoring / dependency upgrade
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • My code follows the code style of this project.
  • My change requires a change to the documentation and I have updated the documentation accordingly.
  • I have added tests to cover my changes.

…xit_on_empty

An empty ReceiveMessage on a standard queue does not mean the queue is drained: messages held in flight by other consumers or left by failed acks reappear after the visibility timeout with no reader. Apply the GetQueueAttributes drain check to standard queues, ignoring receipts held by this process, and keep FIFO behaviour unchanged. Add unit tests with a fake client and document exit_on_empty semantics.
@rahulpatra-pattern
rahulpatra-pattern requested a review from a team as a code owner November 23, 2026 10:36
Copilot AI balanced review requested due to automatic review settings November 23, 2026 10:36

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

Critical SQS receipt-accounting flaws can falsely declare the queue drained and stop polling while failed acknowledgements or other consumers’ messages remain in flight.

3 open issues
What changed in this PR

Extends the SQS reader’s FIFO drain check from #123 to standard queues, reducing premature exit_on_empty shutdowns while messages remain invisible or delayed.

Changes:

  • Checks queue attributes for standard queues, subtracting locally held receipts while preserving FIFO rules.
  • Adds a warning and legacy-exit fallback for standard-queue permission errors.
  • Introduces a mockable client interface, drain-check tests, and documentation of polling and IAM requirements.
File Description
internal/​pkg/​pipeline/​task/​sqs/​sqs.go Implements standard-queue drain checks and permission-error handling.
internal/​pkg/​pipeline/​task/​sqs/​sqs_test.go Tests drain decisions, receipt counts, API errors, and cancellation.
internal/​pkg/​pipeline/​task/​sqs/​README.md Documents exit behavior, receipt exemptions, and required permissions.

Review effort: Balanced

}
if s.outstanding.Load() > 0 {

held := int64(s.outstanding.Load())
}
if s.outstanding.Load() > 0 {

held := int64(s.outstanding.Load())
// not a reason to keep polling on a standard queue, where a downstream task
// (e.g. an unflushed join) may hold them until the output channel closes.
if !fifo {
depth.inFlight -= held
@rahulpatra-pattern

Copy link
Copy Markdown
Author

/argus review

// not a reason to keep polling on a standard queue, where a downstream task
// (e.g. an unflushed join) may hold them until the output channel closes.
if !fifo {
depth.inFlight -= held

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Concurrent buffering readers on one standard queue wait on each other until the visibility timeout
Severity: Medium

held only covers this process's receipts. Say two processes read the same standard queue with exit_on_empty: true, and both feed a fan-in task that holds acks until its input closes (the join case this subtraction exists for). Then each process counts the other's buffered receipts as in_flight_elsewhere. Neither reader can exit, and neither can release its receipts until it exits. This lasts until the visibility timeout expires. The messages then become visible again and get redelivered, so they are processed twice, and the stale receipt handles from the first delivery can no longer delete them. Before this PR, both readers exited on the empty receive. Parallel workers on one queue are a common Airflow pattern, so this is a likely configuration rather than an edge case.

Fix: State this limitation in the README "Exit on empty" section, and tell users to put an end_after shorter than the visibility timeout on fan-in pipelines that run more than one reader process. You could also add an opt-out (for example exit_on_empty_strict: false) that skips the "elsewhere" check for those pipelines.

Comment thread internal/pkg/pipeline/task/sqs/sqs.go Resolved

@argus-pattern argus-pattern 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.

Argus review of fbbacac: I posted 4 inline findings (3 Medium, 1 Low).

The core change does what the PR description says. Standard queues now call GetQueueAttributes before exiting on an empty receive, and FIFO behaviour is unchanged. The new unit tests pass locally (go test ./internal/pkg/pipeline/task/sqs/...).

The findings cover:

  • Concurrent buffering readers on one queue wait on each other until the visibility timeout.
  • The not-drained path busy-loops when wait_time_seconds is 0.
  • The README does not say a redrive policy is needed to avoid an endless reader.
  • Two of the three AccessDenied codes have no tests.

Copilot already flagged the races where held is stale or over-counted, so I did not repeat them.

…ccessDenied codes; document redrive policy

Addresses Argus review on #142: the not-drained path spun on ReceiveMessage and GetQueueAttributes when wait_time_seconds is 0; the README did not say a redrive policy is needed to bound a always-failing message; only one of the three AccessDenied codes was tested.
@rahulpatra-pattern

Copy link
Copy Markdown
Author

Pushed 4761d49 for the Argus items that are small and do not change the drain logic:

  • Busy loop on the not-drained path with wait_time_seconds: 0: the not-drained path now waits one second (context-aware) before returning under short polling. Thread resolved.
  • README: redrive policy: the "Exit on empty" section now says a redrive policy (maxReceiveCount plus a DLQ) is required to bound a message that always fails; without one, only end_after stops the reader. Thread resolved.
  • AccessDenied tests: added cases for AccessDeniedException, the query-compat AWS.SimpleQueueService.AccessDenied and a wrapped error. Thread resolved.

Still open, by design for now:

  • Concurrent buffering readers on one queue (Argus): this needs a decision on an opt-out or a README limitation, so it is not changed here.
  • Copilot's three high-severity receipt-accounting threads (failed ack during tracker wait, ack during GetQueueAttributes, delivery attempts versus distinct messages): these change the drain logic itself, so they are left for a separate rework. This PR should not be merged until they are addressed or the design is agreed.

Build, vet, gofmt and the internal/pkg/pipeline/task/sqs tests pass.

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