Repository navigation
fix(db): align PostgreSQL advisory lock with MySQL blocking semantics - #16346
zeed-w-beez wants to merge 13 commits into
Conversation
Use pg_advisory_lock when timeout is negative so update_progress waits instead of failing immediately under multi-replica contention. Re-raise terminal set_progress failures so completion/error states are not silently dropped before the Redis message is acked. Co-authored-by: Cursor <[email protected]>
Replace client-side polling with server-side pg_advisory_lock plus lock_timeout so finite waits are handled natively by PostgreSQL. Co-authored-by: Cursor <[email protected]>
Always set session lock_timeout before pg_advisory_lock: 0 for infinite wait, Ns for finite wait; reset to DEFAULT afterward. Co-authored-by: Cursor <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe PR updates PostgreSQL advisory lock handling to centralize connection-error detection, manage session ChangesPostgreSQL lock timeout handling
Progress exception propagation
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/db/db_models.py`:
- Around line 570-582: The retry wrapper around lock() is treating the
intentional PostgreSQL lock timeout as a retriable failure, causing repeated
waits. Update lock() to raise a dedicated timeout exception (for example a
PostgresLockTimeoutError) instead of a generic Exception, and adjust with_retry
to skip retries for that type; alternatively, remove `@with_retry` from lock() and
keep retries only for transient DB errors outside the locking path. Use the
lock() method, the with_retry decorator, and the timeout branch in
OperationalError handling as the main places to update.
- Line 576: The PostgreSQL advisory lock flow in the lock acquisition helper is
missing the required instrumentation. Add a debug log in the successful path of
the lock-taking method (the one that calls execute_sql with pg_advisory_lock)
using the existing lock_name/lock_id context, and add matching traceable logging
in the lock release/reset path so both acquisition and release are visible in
logs. Keep the change localized to the lock management methods in db_models and
preserve the current locking behavior.
In `@test/unit_test/api/db/test_postgres_database_lock.py`:
- Around line 13-48: Add the appropriate pytest priority markers to each test in
TestPostgresDatabaseLock so they comply with the test priority convention.
Update the three test methods
test_lock_blocks_indefinitely_when_timeout_negative,
test_lock_uses_postgres_lock_timeout, and
test_lock_raises_when_postgres_lock_timeout with the correct p1/p2/p3 marker
based on their importance, keeping the existing assertions and behavior
unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: fbbb6f97-219f-456b-b4e2-023dc6c250c8
📒 Files selected for processing (3)
api/db/db_models.pyrag/svr/task_executor.pytest/unit_test/api/db/test_postgres_database_lock.py
Raise PostgresLockTimeoutError so with_retry does not re-enter timed-out lock waits; add debug logs for acquire/release/reset; mark unit tests p1/p2. Co-authored-by: Cursor <[email protected]>
Pin a connection for the lock context, defer lock_timeout reset until unlock, and treat missing-session unlock as a warning instead of failing set_progress after the critical section completes. Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/unit_test/api/db/test_postgres_database_lock.py`:
- Around line 22-24: The PostgresDatabaseLock context-manager tests are skipping
lock acquisition because the unspecced MagicMock does not satisfy the
isinstance(self.db, PooledPostgresqlDatabase) check inside PostgresDatabaseLock.
Update the db setup in these tests to use a mock that matches the expected
PooledPostgresqlDatabase type (and add the needed import) so the
__enter__/__exit__ path actually exercises the SQL lock logic; apply the same
change to each db initialization in test_postgres_database_lock.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 9bb0d7bc-b0cf-4d6a-acfb-9949d12f226b
📒 Files selected for processing (2)
api/db/db_models.pytest/unit_test/api/db/test_postgres_database_lock.py
🚧 Files skipped from review as they are similar to previous changes (1)
- api/db/db_models.py
Detect pooled connection failures during lock acquisition, call _handle_connection_loss when available, and retry with backoff without retrying lock-timeout errors. Co-authored-by: Cursor <[email protected]>
Exercise the with-lock code path by mocking pooled PG connections with the expected isinstance target and connection_context manager. Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
api/db/db_models.py (1)
701-708: 🩺 Stability & Availability | 🔴 Critical | ⚡ Quick winKeep
_acquiredin sync for publiclock()/unlock()callers.
lock()currently acquires the advisory lock but leaves_acquired=False, so a laterunlock()returns without releasing it. Also clear_acquiredonly after_release_lock()returns so a failed release does not hide a possibly-held lock.Proposed fix
def lock(self): - return self._acquire_lock() + acquired = self._acquire_lock() + self._acquired = bool(acquired) + return acquired def unlock(self): if not self._acquired: return False - self._acquired = False - return self._release_lock() + released = self._release_lock() + self._acquired = False + return released🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@api/db/db_models.py` around lines 701 - 708, The lock state in the public lock()/unlock() flow is not kept in sync, so lock() should mark the instance as acquired after _acquire_lock() succeeds, and unlock() should only clear _acquired after _release_lock() succeeds. Update the lock and unlock methods in the lock helper so public callers cannot end up with _acquired staying false after locking, and avoid hiding a still-held lock if _release_lock() fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@api/db/db_models.py`:
- Around line 629-633: The timeout path in `acquire_lock` raises
`PostgresLockTimeoutError` before the session cleanup runs, so make sure the
per-session `lock_timeout` is cleared when `_is_lock_timeout_error` matches.
Update the `OperationalError` handling in the lock acquisition flow to
explicitly reset the timeout on the same connection/session before raising, and
keep the existing `_release_lock()` cleanup for the non-timeout path.
In `@test/unit_test/api/db/test_postgres_database_lock.py`:
- Around line 123-126: The test for PostgresDatabaseLock::_reconnect_db is using
an unspecced MagicMock, so _handle_connection_loss exists as a callable and the
reconnect handler branch is taken instead of the close/connect fallback. Replace
the db mock in this test with a specced mock tied to the real DB interface so
_handle_connection_loss is not auto-created, then verify the intended fallback
path by exercising PostgresDatabaseLock._reconnect_db and asserting close() and
connect() are reached.
---
Outside diff comments:
In `@api/db/db_models.py`:
- Around line 701-708: The lock state in the public lock()/unlock() flow is not
kept in sync, so lock() should mark the instance as acquired after
_acquire_lock() succeeds, and unlock() should only clear _acquired after
_release_lock() succeeds. Update the lock and unlock methods in the lock helper
so public callers cannot end up with _acquired staying false after locking, and
avoid hiding a still-held lock if _release_lock() fails.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 6d6640cd-f657-4901-8eab-30bfcd67880a
📒 Files selected for processing (2)
api/db/db_models.pytest/unit_test/api/db/test_postgres_database_lock.py
There was a problem hiding this comment.
♻️ Duplicate comments (1)
test/unit_test/api/db/test_postgres_database_lock.py (1)
137-145: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winFallback reconnect test is using a mock that masks the fallback branch.
On Line 139,
MagicMock()auto-creates_handle_connection_loss, so_reconnect_db()returns early and never reachesclose()/connect(). This test does not actually exercise the fallback path it asserts.Suggested fix
- db = MagicMock() + db = MagicMock(spec=["close", "connect"]) lock = PostgresDatabaseLock("update_progress", db=db)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test/unit_test/api/db/test_postgres_database_lock.py` around lines 137 - 145, The reconnect fallback test is using a plain MagicMock for the database, which auto-mocks _handle_connection_loss and prevents PostgresDatabaseLock._reconnect_db from reaching the close/connect fallback branch. Update test_reconnect_db_falls_back_to_close_and_connect to use a db mock that either does not define _handle_connection_loss or explicitly makes it unavailable/falsey so the fallback path is exercised, while still asserting db.close and db.connect are called once.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@test/unit_test/api/db/test_postgres_database_lock.py`:
- Around line 137-145: The reconnect fallback test is using a plain MagicMock
for the database, which auto-mocks _handle_connection_loss and prevents
PostgresDatabaseLock._reconnect_db from reaching the close/connect fallback
branch. Update test_reconnect_db_falls_back_to_close_and_connect to use a db
mock that either does not define _handle_connection_loss or explicitly makes it
unavailable/falsey so the fallback path is exercised, while still asserting
db.close and db.connect are called once.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 80d611e7-747f-4e7d-9faa-5becc6794eec
📒 Files selected for processing (1)
test/unit_test/api/db/test_postgres_database_lock.py
Avoid returning pooled connections with a stale session lock_timeout after lock-timeout or other failed acquire paths. Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
…infiniflow#16396) Ported retrieval node, added Keenable web search tool - [x] New Feature (non-breaking change which adds functionality)
59ebcd9 to
79d9177
Compare
# Conflicts: # agent/canvas.py # agent/component/fillup.py # agent/component/list_operations.py # api/db/joint_services/tenant_model_service.py # cmd/server_main.go # internal/agent/tool/registry_test.go # internal/handler/agent.go # internal/handler/agent_upload_test.go # internal/handler/searchbot_test.go # internal/service/agent.go # internal/service/model_service.go # internal/service/think_tag.go # internal/service/think_tag_test.go # test/testcases/test_web_api/test_canvas_app/test_fillup_unit.py # test/testcases/test_web_api/test_canvas_app/test_iteration_runtime_unit.py # uv.lock
# Conflicts: # api/db/db_models.py
79d9177 to
86ba44a
Compare
### Summary The fix turns a negative timeout into a finite 60 second wait inside `MysqlDatabaseLock`, which both servers accept. Callers keep expressing "block until available", and the equivalent PostgreSQL and GaussDB work on the same `-1` semantics (#16346, #18506) is untouched. Non-negative timeouts keep their current behaviour. --------- Co-authored-by: Krim <[email protected]>
Summary
Fixes a bug where documents stay RUNNING in the UI on K8s deployments using PostgreSQL, even though task workers are idle and chunks have already been indexed.
Root cause:
PostgresDatabaseLockusedpg_try_advisory_lock(non-blocking). Under multi-replica task executor contention,TaskService.update_progressfrequently failed to acquire the lock.set_progressswallowed the exception, the Redis message was still acked, andtask.progressnever reached1.0— soDocumentService._sync_progresskept the document in RUNNING state.MySQL was unaffected because
GET_LOCK(name, -1)blocks until the lock is available.Fix: Use session-level
lock_timeout+ blockingpg_advisory_lock, aligned with MySQL semantics:timeout< 0(e.g.update_progress)SET lock_timeout = 0→ block indefinitely> 0(e.g.init_database_tables)SET lock_timeout = 'Ns'→ PG raiseslock timeout(SQLSTATE55P03) on expirySET lock_timeout = DEFAULTinfinallyto avoid polluting pooled connectionsAlso re-raise terminal
set_progressfailures (prog >= 1orprog < 0) so completion/error states are not silently dropped.Changes
api/db/db_models.py— rewritePostgresDatabaseLock.lock()rag/svr/task_executor.py— re-raise terminal progress update failurestest/unit_test/api/db/test_postgres_database_lock.py— unit tests for lock behaviorTest plan
lock_timeout+pg_advisory_lockbehaves as expected (2s/5s timeout, infinite wait, immediate acquire)Type of change