Skip to content

chore(jobsdb): release dsList read lock early during store - #6963

Merged
atzoum merged 2 commits into
masterfrom
feat.storeDsListLock
May 22, 2026
Merged

atzoum merged 2 commits into
masterfrom
feat.storeDsListLock

Conversation

@atzoum

@atzoum atzoum commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

🔒 Scanned for secrets using gitleaks 8.30.1

Description

jobsdb currently retains the dsList read lock for the full duration of the store callback. As a result, long-running store transactions can block dsList writers (addNewDS, migrateDSLoop). Once a writer begins waiting on the write lock, new dsList readers may also become blocked.

Therefore, we are now snapshoting the last dataset under the read lock and release the lock immediately, so the store transaction can take as long as it needs without holding dsList writers back. If this turns out to cause regressions in production, the new reloadable config jobsDB.holdDSListLockDuringStore (default false) reverts to the previous hold-the-lock-throughout behavior, so no redeployment is required.

Uncovered latent bugs

Releasing the read lock early exposed two latent bugs in existing tests:

  1. WithStoreSafeTxFromTx couldn't retry on a stale ds. When the caller owned the outer *Tx and the store returned errStaleDsList, the savepoint inside doStoreJobsInTx was never rolled back. The retry inherited an aborted savepoint and the whole transaction failed. Fixed by rolling back to the savepoint before returning ErrStaleDsList.

  2. The JSON sanitize path was missing the same stale-ds handling. Once the rollback was in place, it became obvious that the post-sanitize store() retry could itself hit the read-only table and was not handling it either. doStoreJobsInTx is now a single loop that handles both conditions uniformly; the sanitize retry still runs at most once.

Bonus

  • inStoreSafeCtx no longer logs stale-ds at error level, since it's an expected retryable condition, not a failure.
  • When many goroutines hit a stale ds at the same time (which is exactly what happens during a dataset swap), only the first one to grab the dsList write lock actually refreshes. The rest see that the last dataset has already moved past the one they failed on and skip the refresh, going straight back to the retry. This avoids a thundering herd of redundant refreshes.

Linear Ticket

resolves PIPE-2993

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

This is part 1 of 4 in a stack made with GitButler:

@atzoum
atzoum marked this pull request as ready for review May 15, 2026 17:10
@codecov

codecov Bot commented May 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 67.24138% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.74%. Comparing base (045fdc0) to head (9ca950c).
⚠️ Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
jobsdb/jobsdb.go 79.59% 6 Missing and 4 partials ⚠️
gateway/handle.go 0.00% 5 Missing ⚠️
gateway/handle_lifecycle.go 0.00% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #6963      +/-   ##
==========================================
+ Coverage   79.66%   79.74%   +0.08%     
==========================================
  Files         565      565              
  Lines       63750    63753       +3     
==========================================
+ Hits        50785    50841      +56     
+ Misses       9952     9897      -55     
- Partials     3013     3015       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@atzoum
atzoum force-pushed the feat.storeDsListLock branch from 19df09b to 3655142 Compare May 20, 2026 14:09
🔒 Scanned for secrets using gitleaks 8.30.1
@atzoum
atzoum force-pushed the feat.storeDsListLock branch from 3655142 to ac6689e Compare May 21, 2026 07:08
Comment thread gateway/handle_lifecycle.go Resolved
🔒 Scanned for secrets using gitleaks 8.30.1
@atzoum
atzoum force-pushed the feat.storeDsListLock branch from ac6689e to 9ca950c Compare May 22, 2026 13:57
@atzoum
atzoum enabled auto-merge (squash) May 22, 2026 14:52
@atzoum
atzoum merged commit a172404 into master May 22, 2026
106 of 109 checks passed
@atzoum
atzoum deleted the feat.storeDsListLock branch May 22, 2026 15:07
This was referenced May 25, 2026
mihir20 pushed a commit that referenced this pull request May 25, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.76.0-rc.1](v1.75.0...v1.76.0-rc.1)
(2026-05-25)


### Features

* per-workspace PyT routing + cold-start handling
([#6978](#6978))
([d81e175](d81e175))
* periodic cleanup of rsources shared db tables
([#6945](#6945))
([ed0dfe7](ed0dfe7))


### Bug Fixes

* **batchrouter:** preserve prior LastJobStatus error on drain
([#6958](#6958))
([af31e62](af31e62))
* **batchrouter:** preserve prior LastJobStatus error on drain
([#6958](#6958))
([193f797](193f797))
* clickhouse quarter partition type
([#6965](#6965))
([af31e62](af31e62))
* continuous backend config cache cause postgres disk bloat
([#6983](#6983))
([f45aa06](f45aa06))
* ignore failed messages when source job run id exists
([#6981](#6981))
([045fdc0](045fdc0))
* server getting stuck during startup while initializing rsources
([#6943](#6943))
([62791fa](62791fa))
* snowpipe streaming bulk status offset
([#6966](#6966))
([af31e62](af31e62))


### Miscellaneous

* **ci:** workflow cleanup (SEC-284)
([#6949](#6949))
([516ba5b](516ba5b))
* **deps:** bump actions/upload-artifact from 7.0.0 to 7.0.1
([#6892](#6892))
([866f04d](866f04d))
* **deps:** bump aws-actions/amazon-ecr-login from 2.0.1 to 2.1.4
([#6956](#6956))
([89f1168](89f1168))
* **deps:** bump docker/login-action from 4.0.0 to 4.1.0
([#6881](#6881))
([5bca875](5bca875))
* **deps:** bump rudderlabs/build-scan-push-action from 1.8.2 to 2.2.0
([#6955](#6955))
([78cc895](78cc895))
* **deps:** bump step-security/harden-runner from 2.16.0 to 2.19.1
([#6957](#6957))
([cc5b578](cc5b578))
* **jobsdb:** disable no results cache state filter optimization
([#6964](#6964))
([c20dad2](c20dad2))
* **jobsdb:** release dsList read lock early during store
([#6963](#6963))
([a172404](a172404))
* pyt contracts for ipc and multi threading
([#6942](#6942))
([d570865](d570865))
* remove unused sed deletion method from GZIPLocalFileHandler
([#6974](#6974))
([d788760](d788760))
* replace deprecated WithCredentialsJSON with WithAuthCredentialsJSON
([#6986](#6986))
([8395174](8395174))
* sync release v1.75.0 to main branch
([#6954](#6954))
([f16fe93](f16fe93))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: rudderstack-github-actions[bot] <236995729+rudderstack-github-actions[bot]@users.noreply.github.com>
atzoum added a commit that referenced this pull request May 25, 2026
…ted datasets (#6962)

🔒 Scanned for secrets using gitleaks 8.30.1

# Description

Introducing support for dropping completed dataset tables in a
non-blocking fashion without a migration lock:

### 1. Versioned dataset list with reader-drain semantics

A new `versionedDSList` replaces the bare `datasetList` /
`datasetRangeList` fields on `Handle`. Each update bumps a version;
readers acquire a snapshot tagged with that version and release it when
done reading. An additional `wait(through)` API returns a channel that
closes once no reader is still using a version `<= through`, so a
dropper can block until in-flight queries that still see the old list
have finished.

### 2. `nonBlockingCompletedDSDrop` fast path and async drop loop

- A new `dropDSLoop` consumes a `dropDSList` queue. Each entry records
the dslist version that must drain before the table can be dropped.
- `addToDropDSList` republishes the dslist without the queued datasets,
writes the persistent pre-drop marker (see §3), and pings the loop. The
actual `DROP TABLE` happens off the hot path.
- `doMigrateDS` gains a fast path gated by
**`jobsdb.<prefix>.nonBlockingCompletedDSDrop`** (default `false`):
datasets with zero pending jobs are routed through the async drop loop
instead of the in-lock `postMigrateHandleDS` path. When disabled,
behavior is unchanged.

### 3. Persistent `pre_drop:v1` table marker

`COMMENT ON TABLE … IS 'rudder:pre_drop:v1'` is written as part of
queuing a dataset for drop. This makes the queue crash-safe — the source
of truth lives in Postgres, not just in-memory `dropDSList`.

- `getAllTableNames` now joins
`pg_class`/`pg_namespace`/`pg_description` and filters out marked
tables, masking half-pairs (drops both the jobs and status table when
either is marked).
- New SQL migration `000019_jobsdb_functions_pre_drop_filter.up.sql`
rewrites `unionjobsdb`, `unionjobsdbmetadata`, and `joborderlog` to
apply the same `pg_description` filter, so server-side discovery skips
marked tables too.
- `cleanupPreDropTables` runs once at startup of `read` or `readwrite`
jobsdbs and after journal recovery, dropping any tables left marked by a
previous crashed run.

If there isn't any marker present, behavior remains identical as before.

### 4. `RS001` tolerance on the `UpdateJobStatus` path

The readonly-trigger error code `RS001` was previously only handled on
the `Store` path. The `Update` path now wraps each
`internalUpdateJobStatusInTx` call in a savepoint: on `ErrStaleDsList`
it rolls back to the savepoint, refreshes the dslist under the write
lock, updates the `UpdateSafeTx`'s embedded dslist/rangeList snapshot,
and retries the whole command. We do **not** replay the caller-owned
outer transaction.

To support this, `UpdateSafeTx` now carries its own
`dsList`/`dsRangeList` (with a `setDSList` setter) so retries reroute
against the refreshed snapshot without re-running `inUpdateSafeCtx`.

This change is harmless until a follow-up PR starts marking status
tables readonly during compaction.

## Linear Ticket

resolves PIPE-2996

## Security

- [x] The code changed/added as part of this pull request won't create
any security issues with how the software is being used.

<!-- GitButler Footer Boundary Top -->
---
This is **part 2 of 4 in a stack** made with GitButler:
- <kbd>&nbsp;4&nbsp;</kbd> #6979 
- <kbd>&nbsp;3&nbsp;</kbd> #6967 
- <kbd>&nbsp;2&nbsp;</kbd> #6962 👈 
- <kbd>&nbsp;1&nbsp;</kbd> #6963 
<!-- GitButler Footer Boundary Bottom -->
mihir20 pushed a commit that referenced this pull request May 26, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.76.0](v1.75.0...v1.76.0)
(2026-05-25)


### Features

* per-workspace PyT routing + cold-start handling
([#6978](#6978))
([d81e175](d81e175))
* periodic cleanup of rsources shared db tables
([#6945](#6945))
([ed0dfe7](ed0dfe7))


### Bug Fixes

* **batchrouter:** preserve prior LastJobStatus error on drain
([#6958](#6958))
([af31e62](af31e62))
* **batchrouter:** preserve prior LastJobStatus error on drain
([#6958](#6958))
([193f797](193f797))
* clickhouse quarter partition type
([#6965](#6965))
([af31e62](af31e62))
* continuous backend config cache cause postgres disk bloat
([#6983](#6983))
([f45aa06](f45aa06))
* ignore failed messages when source job run id exists
([#6981](#6981))
([045fdc0](045fdc0))
* server getting stuck during startup while initializing rsources
([#6943](#6943))
([62791fa](62791fa))
* snowpipe streaming bulk status offset
([#6966](#6966))
([af31e62](af31e62))


### Miscellaneous

* **ci:** workflow cleanup (SEC-284)
([#6949](#6949))
([516ba5b](516ba5b))
* **deps:** bump actions/upload-artifact from 7.0.0 to 7.0.1
([#6892](#6892))
([866f04d](866f04d))
* **deps:** bump aws-actions/amazon-ecr-login from 2.0.1 to 2.1.4
([#6956](#6956))
([89f1168](89f1168))
* **deps:** bump docker/login-action from 4.0.0 to 4.1.0
([#6881](#6881))
([5bca875](5bca875))
* **deps:** bump rudderlabs/build-scan-push-action from 1.8.2 to 2.2.0
([#6955](#6955))
([78cc895](78cc895))
* **deps:** bump step-security/harden-runner from 2.16.0 to 2.19.1
([#6957](#6957))
([cc5b578](cc5b578))
* **jobsdb:** disable no results cache state filter optimization
([#6964](#6964))
([c20dad2](c20dad2))
* **jobsdb:** release dsList read lock early during store
([#6963](#6963))
([a172404](a172404))
* pyt contracts for ipc and multi threading
([#6942](#6942))
([d570865](d570865))
* remove unused sed deletion method from GZIPLocalFileHandler
([#6974](#6974))
([d788760](d788760))
* replace deprecated WithCredentialsJSON with WithAuthCredentialsJSON
([#6986](#6986))
([8395174](8395174))
* sync release v1.75.0 to main branch
([#6954](#6954))
([f16fe93](f16fe93))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: rudderstack-github-actions[bot] <236995729+rudderstack-github-actions[bot]@users.noreply.github.com>
atzoum added a commit that referenced this pull request May 26, 2026
🔒 Scanned for secrets using gitleaks 8.30.1

# Description

Introduces a non-blocking compaction flow for the jobsdb migration loop,
gated behind the `nonBlockingCompaction` flag. When enabled it
dramatically shrinks the lock window taken during dataset migration:

- **`dsMigrationLock` is no longer taken.** Concurrent readers
(`getJobs`, `GetPileUpCounts`, `GetDistinctParameterValues`) are not
blocked by an in-flight compaction.
- **Caveat:** an `UpdateJobStatus` call that targets a source dataset
*while it is being compacted* will block at the PG level on the
`EXCLUSIVE` lock held against that source's status table, until the
compaction TX commits — bounded by the per-source `COPY` duration. After
commit, late writers landing on the old status table are fenced by the
readonly trigger and routed to the new destination via the existing
`ErrStaleDsList` retry path.

Compared to the legacy path, the writer side of `dsListLock` is reduced
from "entire migration TX, including bulk `COPY` of all non-terminal
jobs and `DROP TABLE` of every source" down to "`COMMIT` + a single
`getDSList` + a `MIN/MAX` scan of the new destination".

## New maintenance pool

Introducing a new maintenance pool which can be used by maintenance
operations, such as:

- adding new dataset
- refreshing dataset list
- compacting datasets
- compacting job status tables

This pool helps closing a connection-pool deadlock vector where jobsdb
readers and writers could fully exhaust the pool, blocking an active
maintenance goroutine while it still held a mutex (e.g. post-commit
compaction which requires acquiring a new connection to refresh the
dataset list). In addition, all maintenance goroutines were updated to
ensure they require no more than a single connection at any time,
eliminating pool-related deadlock risks caused by previously nested
connection usage.
If no maintenance pool is injected, the calls fall back to `dbHandle`
(backwards compatibility).

## Lock stats

`dsListLock` and `dsMigrationLock` now emit timing metrics, tagged by
lock type (`read`/`write`) and whether the acquisition was async:

| Metric | Description |
|---|---|
| `jobsdb_lock_wait_time` | Time spent waiting to acquire the lock |
| `jobsdb_lock_time` | Time the lock was held (excluding wait) |
| `jobsdb_lock_total_time` | End-to-end time (wait + hold) |

All metrics carry a `name` tag so lock contention can be tracked per
jobsdb instance.

## Flags

- `JobsDB.<prefix>.nonBlockingCompaction` (default `false`) — gates the
new flow. When off, `doMigrateDS` falls back to the legacy in-TX
migrate+drop path.
- `JobsDB.<prefix>.getJobsRetryOnCompaction` (default `true`) — gates
the `getJobs` snapshot revalidation. When on, if a dataset that
`getJobs` queried was compacted mid-read, the call returns
`ErrStaleDsList` and is retried against the freshly published list.
**Why:** while `getJobs` is reading the source's status table, an
`UpdateJobStatus` for one of the same jobs could commit against the new
dataset. Without the retry, `getJobs` would miss that status update,
risking out-of-order processing downstream. This option has no effect
unless `nonBlockingCompaction` is also on.

## Testing
#6979 runs all tests with non-blocking partition migration enabled

## Linear Ticket

resolves PIPE-2997

## Security

- [x] The code changed/added as part of this pull request won't create
any security issues with how the software is being used.

<!-- GitButler Footer Boundary Top -->
---
This is **part 3 of 4 in a stack** made with GitButler:
- <kbd>&nbsp;4&nbsp;</kbd> #6979 
- <kbd>&nbsp;3&nbsp;</kbd> #6967 👈 
- <kbd>&nbsp;2&nbsp;</kbd> #6962 
- <kbd>&nbsp;1&nbsp;</kbd> #6963 
<!-- GitButler Footer Boundary Bottom -->
atzoum added a commit that referenced this pull request Jun 3, 2026
…s been dropped (#7041)

# Description

Since #6963, `Store` operates against a snapshot of the dataset list. In
the rare case where a compaction manages to drop the previous rightmost
dataset between when the snapshot was taken and when the store
transaction executes, the `COPY INTO` fails with PostgreSQL error
`42P01` (undefined table), treated as an unrecoverable error, causing
server to panic.

**Fix:** Treat `42P01` (undefined table) the same as `RS001` (readonly
trigger): return `ErrStaleDsList` so `inStoreSafeCtx` refreshes the
dataset list and retries on the current last dataset. Set a maximum
number of stale ds list retries to avoid infinite loops in test
scenarios (default: 3).

## Linear Ticket

resolves PIPE-3080

## Security

- [x] The code changed/added as part of this pull request won't create
any security issues with how the software is being used.
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