Skip to content

fix(db): align PostgreSQL advisory lock with MySQL blocking semantics - #16346

Closed
zeed-w-beez wants to merge 13 commits into
infiniflow:mainfrom
zeed-w-beez:fix/postgres-advisory-lock-progress
Closed

zeed-w-beez wants to merge 13 commits into
infiniflow:mainfrom
zeed-w-beez:fix/postgres-advisory-lock-progress

Conversation

@zeed-w-beez

Copy link
Copy Markdown

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: PostgresDatabaseLock used pg_try_advisory_lock (non-blocking). Under multi-replica task executor contention, TaskService.update_progress frequently failed to acquire the lock. set_progress swallowed the exception, the Redis message was still acked, and task.progress never reached 1.0 — so DocumentService._sync_progress kept 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 + blocking pg_advisory_lock, aligned with MySQL semantics:

timeout Behavior
< 0 (e.g. update_progress) SET lock_timeout = 0 → block indefinitely
> 0 (e.g. init_database_tables) SET lock_timeout = 'Ns' → PG raises lock timeout (SQLSTATE 55P03) on expiry
always SET lock_timeout = DEFAULT in finally to avoid polluting pooled connections

Also re-raise terminal set_progress failures (prog >= 1 or prog < 0) so completion/error states are not silently dropped.

Changes

  • api/db/db_models.py — rewrite PostgresDatabaseLock.lock()
  • rag/svr/task_executor.py — re-raise terminal progress update failures
  • test/unit_test/api/db/test_postgres_database_lock.py — unit tests for lock behavior

Test plan

  • Local PostgreSQL 15 integration test: lock_timeout + pg_advisory_lock behaves as expected (2s/5s timeout, infinite wait, immediate acquire)

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

zeed-w-beez and others added 3 commits June 25, 2026 13:42
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]>
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Jun 25, 2026
@coderabbitai

coderabbitai Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR updates PostgreSQL advisory lock handling to centralize connection-error detection, manage session lock_timeout during lock acquire and release, add timeout-specific behavior and tests, and change set_progress() to re-raise selected exceptions.

Changes

PostgreSQL lock timeout handling

Layer / File(s) Summary
Retry and timeout handling
api/db/db_models.py
Centralized PostgreSQL connection-error detection is added, with_retry(...) skips PostgresLockTimeoutError, and advisory-lock acquisition now distinguishes connection failures from lock-timeout failures while managing session lock_timeout.
Advisory lock lifecycle
api/db/db_models.py
Advisory lock acquisition and release now set and reset session lock_timeout, track acquisition state, and manage pooled connection context cleanup.
Advisory lock tests
test/unit_test/api/db/test_postgres_database_lock.py
Unit tests cover lock acquisition ordering, timeout failures, unlock behavior when the lock is not held, and reconnection behavior during acquisition.

Progress exception propagation

Layer / File(s) Summary
Exception propagation guard
rag/svr/task_executor.py
set_progress() now raises from the generic exception path when prog matches the new range checks.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

A bunny found a lock so neat,
With timeout paws and retry feet.
It hopped past errors, soft and bright,
Then let some progress glitches take flight,
🐇✨ A tidy hop through code tonight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 3.13% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change to PostgreSQL advisory locking behavior.
Description check ✅ Passed The description covers the problem, root cause, fix, test plan, and change type, though it uses a Summary section instead of the template's exact heading.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d443598 and c48173c.

📒 Files selected for processing (3)
  • api/db/db_models.py
  • rag/svr/task_executor.py
  • test/unit_test/api/db/test_postgres_database_lock.py

Comment thread api/db/db_models.py Resolved
Comment thread api/db/db_models.py Resolved
zeed-w-beez and others added 2 commits June 25, 2026 14:40
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]>
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jun 25, 2026

@coderabbitai coderabbitai Bot 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.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4837bb5 and cf169e3.

📒 Files selected for processing (2)
  • api/db/db_models.py
  • test/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

zeed-w-beez and others added 2 commits June 25, 2026 15:58
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]>

@coderabbitai coderabbitai Bot 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.

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 win

Keep _acquired in sync for public lock() / unlock() callers.

lock() currently acquires the advisory lock but leaves _acquired=False, so a later unlock() returns without releasing it. Also clear _acquired only 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

📥 Commits

Reviewing files that changed from the base of the PR and between cf169e3 and 5532f3b.

📒 Files selected for processing (2)
  • api/db/db_models.py
  • test/unit_test/api/db/test_postgres_database_lock.py

Comment thread api/db/db_models.py Resolved

@coderabbitai coderabbitai Bot 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.

♻️ Duplicate comments (1)
test/unit_test/api/db/test_postgres_database_lock.py (1)

137-145: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Fallback 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 reaches close()/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

📥 Commits

Reviewing files that changed from the base of the PR and between 5532f3b and c2ebecf.

📒 Files selected for processing (1)
  • test/unit_test/api/db/test_postgres_database_lock.py

zeed-w-beez and others added 4 commits June 25, 2026 16:11
Avoid returning pooled connections with a stale session lock_timeout
after lock-timeout or other failed acquire paths.

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)
@zeed-w-beez
zeed-w-beez force-pushed the fix/postgres-advisory-lock-progress branch from 59ebcd9 to 79d9177 Compare July 1, 2026 02:40
# 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
@zeed-w-beez
zeed-w-beez force-pushed the fix/postgres-advisory-lock-progress branch from 79d9177 to 86ba44a Compare July 4, 2026 03:36
JinHai-CN pushed a commit that referenced this pull request Aug 20, 2026
### 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants