← Back to Pull requests

[18.0][IMP] queue_job: use queue_job row lock instead of queue_job_lock table #991

Open
florentx opened this pull request with 444 lines diff across 14 files
View on GitHub
florentx florentx commented on Sep 22, 2026 22:15 UTC
Author

Refactor the logic for Job locks and requeuing dead jobs:

  • Get rid of queue.job.lock model

  • It is supposedly more performant, since there's no INSERT or DELETE needed
  • PR rebased on top of:

  • #1016
  • ---
    A next step, to improve what was done there:

  • #716
  • Diff: 444 lines (+218 / -226) across 14 files Reviewer: guewen Review duration: 70000m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.66) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.66 · 444 lines diff across 14 files
    0.66
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.90 · 5 substantive comment(s)
    0.90
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    89%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.365
    Real PR Conversation Timeline
    18 items
    OCA-git-bot OCA-git-bot commented on Sep 22, 2026 22:15 UTC
    Bot

    Hi @guewen, @sbidoul,
    some modules you are maintaining are being modified, check this out!

    florentx florentx commented on Sep 23, 2026 08:10 UTC
    Author

    Please review, @guewen, @sbidoul

    Using transaction-level advisory lock, we achieve the same as what was done by @AnizR earlier, but with locks only in pg_locks without need for INSERT/UPDATE/DELETE on a side table.

    guewen guewen commented on code on Sep 23, 2026 08:27 UTC
    Code Review
    queue_job/job.py:1
    @@ -243,55 +246,23 @@ def load_many(cls, env, job_uuids):
             recordset = cls.db_records_from_uuids(env, job_uuids)
             return {cls._load_from_db_record(record) for record in recordset}
     
    -    def add_lock_record(self) -> None:
    -        """
    -        Create row in db to be locked while the job is being performed.
    -        """
    -        self.env.cr.execute(
    -            """
    -            INSERT INTO
    -                queue_job_lock (id, queue_job_id)
    -            SELECT
    -                id, id
    -            FROM
    -                queue_job
    -            WHERE
    -                uuid = %s
    -            ON CONFLICT(id)
    -            DO NOTHING;
    -        """,
    -            [self.uuid],
    -        )
    -
         def lock(self) -> bool:
    -        """Lock row of job that is being performed.
    +        """Lock job that is being performed.
     
             Return False if a job cannot be locked: it means that the job is not in
             STARTED state or is already locked by another worker.
    +        Lock is released at the commit or rollback of the transaction.
             """
    -        self.env.cr.execute(
    -            """
    -            SELECT
    -                *
    -            FROM
    -                queue_job_lock
    -            WHERE
    -                queue_job_id in (
    -                    SELECT
    -                        id
    -                    FROM
    -                        queue_job
    -                    WHERE
    -                        uuid = %s
    -                        AND state = %s
    -                )
    -            FOR NO KEY UPDATE SKIP LOCKED;
    -        """,
    -            [self.uuid, STARTED],
    +        lock_query = (
    +            "SELECT uuid FROM queue_job"
    +            " WHERE uuid = %s AND state = %s AND pg_try_advisory_xact_lock(%s, id);"

    The parameters are integers of 32 bits, I don't remember if ids of odoo tables are int or bigint, but in any case shouldn't we apply a modulo to the 32 bits max value on the ID to be on the safe side?

    florentx florentx commented on code on Sep 23, 2026 08:29 UTC
    Code Review
    queue_job/job.py:1
    @@ -243,55 +246,23 @@ def load_many(cls, env, job_uuids):
             recordset = cls.db_records_from_uuids(env, job_uuids)
             return {cls._load_from_db_record(record) for record in recordset}
     
    -    def add_lock_record(self) -> None:
    -        """
    -        Create row in db to be locked while the job is being performed.
    -        """
    -        self.env.cr.execute(
    -            """
    -            INSERT INTO
    -                queue_job_lock (id, queue_job_id)
    -            SELECT
    -                id, id
    -            FROM
    -                queue_job
    -            WHERE
    -                uuid = %s
    -            ON CONFLICT(id)
    -            DO NOTHING;
    -        """,
    -            [self.uuid],
    -        )
    -
         def lock(self) -> bool:
    -        """Lock row of job that is being performed.
    +        """Lock job that is being performed.
     
             Return False if a job cannot be locked: it means that the job is not in
             STARTED state or is already locked by another worker.
    +        Lock is released at the commit or rollback of the transaction.
             """
    -        self.env.cr.execute(
    -            """
    -            SELECT
    -                *
    -            FROM
    -                queue_job_lock
    -            WHERE
    -                queue_job_id in (
    -                    SELECT
    -                        id
    -                    FROM
    -                        queue_job
    -                    WHERE
    -                        uuid = %s
    -                        AND state = %s
    -                )
    -            FOR NO KEY UPDATE SKIP LOCKED;
    -        """,
    -            [self.uuid, STARTED],
    +        lock_query = (
    +            "SELECT uuid FROM queue_job"
    +            " WHERE uuid = %s AND state = %s AND pg_try_advisory_xact_lock(%s, id);"

    I've checked with psql, they are INTEGER.
    We could add a % (1<<31) to be explicit, even if it's not needed.

    guewen guewen commented on Sep 23, 2026 08:35 UTC
    Contributor

    Thanks!

    Just to references the history of discussions on this topic, I link #907, where I attempted a similar thing but with a session advisory lock. I abandoned the idea because of potential issues between db poolers and a session level advisory lock. However, I was trying to solve the issue of commits that break isolation at the same time, so if we keep the no commit in jobs rule, a transaction advisory lock should be fine indeed.
    I will try to take more time between OCA talks to review more attentively

    sbidoul sbidoul commented on Sep 23, 2026 18:36 UTC
    Contributor

    Is the lock based on the job record id? What if there is the same job id in different databases? Reviewing on mobile so I may have misread.

    florentx florentx commented on Sep 23, 2026 20:11 UTC
    Author

    Is the lock based on the job record id? What if there is the same job id in different databases?

    I've re-checked doc:

    _Advisory locks are local to each database, so the database column is meaningful for an advisory lock._

    https://www.postgresql.org/docs/18/view-pg-locks.html

    guewen guewen approved these changes on Sep 24, 2026 06:56 UTC
    Approved Reviewer

    Looks good to me. I like the simplification it brings along. Thanks!

    florentx florentx commented on Sep 24, 2026 07:45 UTC
    Author

    Looks good to me. I like the simplification it brings along. Thanks!

    I wonder if we can make it even simpler. I will test locally, I'll keep you posted.

    florentx florentx commented on Sep 24, 2026 08:26 UTC
    Author

    This is the proposed simplification: https://github.com/camptocamp/queue/commit/49d4c9e

    Tests are passing locally, and it makes sense to me:

  • change queue_job.job.Job.lock() method to receive a state argument

  • use the same locking mechanism for ENQUEUED then for STARTED job -> lock row FOR UPDATE

  • logic is clear to read and understand, we don't even need advisory locks
  • @guewen and @sbidoul ~if OK, I will replace code of this PR with the suggested commit above~

    ----

    [UPDATE]

    I've replaced the content of this PR, since I am confident on this change.

    sbidoul sbidoul commented on Sep 24, 2026 08:34 UTC
    Contributor

    @florentx locking the job records themselves was tried in https://github.com/OCA/queue/pull/423 and led to deadlocks.I believe this still applies.

    florentx florentx commented on Sep 24, 2026 08:43 UTC
    Author

    @florentx locking the job records themselves was tried in #423 and led to deadlocks.I believe this still applies.

    This PR I've seen before.
    It seems to have a flaw: there's no FOR UPDATE SKIP LOCKED on the Job.lock() method.
    https://github.com/OCA/queue/pull/423/changes#diff-23034efd8360efc0b59b169eb4834058fd91f6eabf06cf8a04bac0142e3cc385

    sbidoul sbidoul commented on Sep 24, 2026 14:09 UTC
    Contributor

    @florentx I'm not sure that flaw you mention was the cause ot the deadlocks. In some circumstances the job runner writes on the job record using another cursor. That part is quite complex and I'm not quite sure the new lock will be released in all circumstances when that happens.

    florentx florentx commented on Sep 25, 2026 08:06 UTC
    Author

    @florentx I'm not sure that flaw you mention was the cause ot the deadlocks. In some circumstances the job runner writes on the job record using another cursor. That part is quite complex and I'm not quite sure the new lock will be released in all circumstances when that happens.

    Code is clean and easier to understand.
    It's correct that with this patch, queue.job record cannot be modified while it is running (in "started" state).
    But I do not see how it can trigger a deadlock.
    Before, an admin could change a record while it was "started", but changes were overwritten when the job finishes and values are written back to the record.

    I suggest to test these changes on some project, and report feedback here.

    florentx florentx commented on Oct 20, 2026 17:14 UTC
    Author

    After testing on real data, I had to adapt the changes: d9c971817daa84d0b61b967db9fc85397c1590ba

  • use a savepoint for job.perform() so that cursor can be re-used in case of OperationalError

  • do not use separate cursor for saving error result on the "queue.job" record

  • -use the same cursor, which is in good shape thanks to the savepoint
  • it is necessary, because the runner holds a Lock on the job row, and it is not possible to change it from another transaction

  • and it should be more performant: no need of multiple cursors (except for the allow_commit=True use case)
  • sbidoul sbidoul commented on Oct 27, 2026 08:23 UTC
    Contributor

    I have heard that some people have jobs that write on job records. Now with allow_commit=True, such use cases won't work anymore because the job record is locked by another transaction.

    florentx florentx commented on Nov 03, 2026 10:35 UTC
    Author

    I have heard that some people have jobs that write on job records. Now with allow_commit=True, such use cases won't work anymore because the job record is locked by another transaction.

    If this is the case, then probably the job function has to be rewritten.

    What will be supported:

  • with allow_commit = False, then the job function can write on the job record itself, since it holds an exclusive lock

  • with allow_commit = True, the cursor which holds the exclusive lock is not the one which runs the job function. So it should not write anything on the job record.
  • Prior to this change:

  • in case of failure, a separate cursor was used to save result and to postpone the job (with risk of concurrent access)
  • This important change can be added to the documentation, as a warning, at the same place where we document prohibited commits.

    Reviewers
    Assignees
    florentx florentx
    Labels
    risk: low confidence: 89.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 65.5% (HIGH) · Higher = larger blast radius
    65.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 89.2% · Lower = rushed or shallow review
    89.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 7.1% · Safe to merge
    7.1%
    Repository