Repository navigation
OpenConceptLab/ocl_issues#3058 | Queue the active count tasks once the caller's transaction commits - #1020
Conversation
… count tasks once the caller's transaction commits Collection.add_expressions runs in one transaction, and add_references queued the two count tasks at its end, before the commit. A worker that picked them up at once counted the expansion as it was before the references were added (0 for a new collection) and, finding no change, saved nothing. Production's task rows show it: the counts queued by add_references are left PENDING with no start or finish time, because the worker looked up rows the uncommitted transaction hadn't written yet. The tasks are now queued with transaction.on_commit, which runs at once outside a transaction, so views and other callers queue as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qTsdWcp2GgLWvv3gqD
…ey start; a failed publish is logged; the test goes through the async PUT
- The four active count tasks take once={'unlock_before_run': True}. QueueOnce otherwise holds the lock until
a count finishes, so a count queued for a write that committed while one was running was dropped, and the
stored count stayed one write behind.
- The on-commit callback is robust: a failure to publish one count is logged, and neither fails the write
that already committed nor skips the other count.
- The test now submits PUT references/?async=true, runs the add_references job it queued as a worker would,
and runs the count tasks with the arguments they were published with. Tests that call a count task
directly call its run(), as releasing the lock needs Redis.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AaZ4qTsdWcp2GgLWvv3gqD
|
Codex review, pass 1 (codex-cli 0.169.0, commit 294e8d8) Verdict: findings (3 findings)
findings.json{
"reviewer": "codex-cli 0.169.0",
"perspective": "defects",
"mode": "full",
"commit": "294e8d81",
"verdict": "findings",
"prior": [],
"findings": [
{
"id": "F1.1",
"severity": "P1",
"tag": null,
"file": "core/common/models.py",
"line": 893,
"claim": "The QueueOnce lock can still cause the recount for a committed reference addition to be dropped.",
"scenario": "A recount reads one active concept. A second reference addition commits another active concept before the recount releases its lock. The second enqueue raises AlreadyQueued and is discarded. The first recount stores 1, and HEAD stays at 1 while the expansion has 2 active concepts.",
"action": "Preserve a recount request rejected by QueueOnce and process it after the in-flight job releases its lock. Add a test that commits a second addition after the first recount has read the expansion.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "F1.2",
"severity": "P2",
"tag": null,
"file": "core/common/models.py",
"line": 896,
"claim": "A recount publication failure can now report a committed reference addition as failed and skip the remaining recount callback.",
"scenario": "The reference and expansion writes commit, then Redis fails during publication of the concept recount. The exception escapes the commit callback, Django skips the mapping recount callback, and Celery marks the reference addition as failed. The references are already present, so retrying the same request encounters duplicates.",
"action": "Record the need to recount in the write transaction and dispatch it with independent retries so a publication failure neither changes the result of the committed addition nor drops a recount.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "F1.3",
"severity": "P2",
"tag": null,
"file": "core/collections/tests/tests.py",
"line": 2147,
"claim": "The regression test can pass while the messages produced by the async path leave HEAD stale.",
"scenario": "If a recount message carries the wrong collection ID, the new test still passes because it records only the task names and later calls both tasks with the correct ID. The existing async PUT test mocks the reference task, so it never checks the resulting count.",
"action": "Submit the async PUT, execute the captured reference job, and run the recounts using the arguments captured from publication after commit. Assert the stored HEAD counts against the expansion.",
"lines_delta": null,
"confidence": "high"
}
]
} |
…ake turns, so the last to run saves last With the QueueOnce lock released as a count starts, two counts of one repo version can run at once on the concurrent queue, and one that counted before a write could save after one that counted after it. Each count now holds a transaction-level advisory lock for its repo version and field while it counts and saves, so they run one at a time and the last to run counts what was committed last. A two-connection test pauses one count between counting and saving while a reference commits and a second count runs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qTsdWcp2GgLWvv3gqD
|
Codex review, pass 2 (codex-cli 0.169.0, commit f560f07) Verdict: findings (2 findings) Earlier findings: F1.1 regressed, F1.2 resolved, F1.3 resolved
findings.json{
"reviewer": "codex-cli 0.169.0",
"perspective": "defects",
"mode": "verify",
"commit": "f560f079",
"verdict": "findings",
"prior": [
{
"id": "F1.1",
"status": "regressed"
},
{
"id": "F1.2",
"status": "resolved"
},
{
"id": "F1.3",
"status": "resolved"
}
],
"findings": [
{
"id": "F2.1",
"severity": "P1",
"tag": null,
"file": "core/common/tasks.py",
"line": 992,
"claim": "Releasing the QueueOnce lock before counting lets an older recount overwrite a newer result.",
"scenario": "A worker counts one active concept and pauses before saving. A second reference addition commits, and another process on the production concurrent queue counts and saves two. The first worker then saves one. Both tasks finish successfully, and the stored HEAD count stays at one while the expansion has two.",
"action": "Keep post-commit enqueueing and serialize the count query and save for each container, for example with a row lock held across both. Add a regression test that commits a second addition while the first recount is running.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "F2.2",
"severity": "P2",
"tag": null,
"file": "core/common/models.py",
"line": 893,
"claim": "A failed post-commit publish can strand a recount and block subsequent attempts.",
"scenario": "A reference addition commits with a stored count of zero. QueueOnce acquires its Redis lock, but the broker connection drops before the message is accepted and publishing exhausts its retries. The callback logs the failure and leaves a PENDING task row. After the broker recovers, another addition can hit AlreadyQueued for the default one-hour lock lifetime even though no recount was queued. The count stays at zero if nothing requests another recount after the lock expires.",
"action": "Record the need to recount in the reference transaction and retry failed dispatches. Ensure a lock from an unpublished attempt cannot suppress the retry.",
"lines_delta": null,
"confidence": "high"
}
]
} |
…ve; one 64-bit lock key; an unqueued count leaves no task - A count writes its field with a queryset update, so no post-save indexing publish runs inside the count's transaction (search documents hold no counts) and can't roll the count back. - The advisory lock takes one bigint key hashed from the model, field and id, so ids past 32 bits work. - A count task row is deleted when its publish fails, not left PENDING with nothing queued. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qTsdWcp2GgLWvv3gqD
|
Codex review, pass 3 (codex-cli 0.169.0, commit 8b94646) Verdict: findings (4 findings) Earlier findings: F1.1 regressed, F1.2 resolved, F1.3 resolved, F2.1 regressed, F2.2 unresolved
findings.json{
"reviewer": "codex-cli 0.169.0",
"perspective": "defects",
"mode": "verify",
"commit": "8b946468",
"verdict": "findings",
"prior": [
{
"id": "F1.1",
"status": "regressed"
},
{
"id": "F1.2",
"status": "resolved"
},
{
"id": "F1.3",
"status": "resolved"
},
{
"id": "F2.1",
"status": "regressed"
},
{
"id": "F2.2",
"status": "unresolved"
}
],
"findings": [
{
"id": "F3.1",
"severity": "P2",
"tag": null,
"file": "core/common/tasks.py",
"line": 1012,
"claim": "The new count transaction rolls back a successful recount if its post-save indexing publish fails.",
"scenario": "With ES_SYNC enabled, a worker calculates the correct count and updates the row. The post-save signal then fails to publish the indexing job, so the transaction rolls back the count and HEAD stays stale. On the base branch the count update had already committed when the signal ran.",
"action": "Use a field-only queryset update inside the lock. The count fields are absent from the search documents.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "F3.2",
"severity": "P2",
"tag": null,
"file": "core/common/tasks.py",
"line": 1004,
"claim": "The two-argument advisory lock rejects valid 64-bit repository IDs.",
"scenario": "A source or collection version with ID 2147483648 is valid under BigAutoField. PostgreSQL receives pg_advisory_xact_lock(integer, bigint), which has no matching overload, so every queued recount for that version fails before reading its members.",
"action": "Use the single-bigint advisory-lock overload with a stable key derived from the model, field, and full repository ID. Test an ID above the signed 32-bit limit.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "F3.3",
"severity": "P2",
"tag": null,
"file": "core/common/tasks.py",
"line": 993,
"claim": "Releasing the Redis lock before the task body can discard a recount that was already delivered.",
"scenario": "The worker receives the recount, then the Redis lock deletion fails after connection retries. QueueOnce raises before the database recount runs. Celery treats this as a task failure and does not redeliver it, so HEAD can retain its old count after Redis recovers. The base branch attempted the deletion after saving the count.",
"action": "Make lock-release failures retryable at the task entry point, where QueueOnce releases the lock, and test that path with a failing lock backend.",
"lines_delta": null,
"confidence": "high"
},
{
"id": "F3.4",
"severity": "P2",
"tag": null,
"file": "core/common/models.py",
"line": 891,
"claim": "A failed recount publish leaves a visible PENDING task with no message to execute.",
"scenario": "An async reference add commits, then the concepts callback inserts its task row and fails to connect to Redis before acquiring a QueueOnce lock. The add job succeeds, but the task list shows a PENDING recount until the seven-day cleanup. No worker received the message.",
"action": "Record the publish failure on the task row so it does not stay PENDING, and assert that state in the existing publish-failure test.",
"lines_delta": null,
"confidence": "high"
}
]
} |
…he id past 32 bits (simplification review S2) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01AaZ4qTsdWcp2GgLWvv3gqD
|
Simplification review (claude subagent, Sonnet 5.5, commit bd345c8) Verdict: findings (4 findings)
findings.json{
"reviewer": "claude subagent",
"perspective": "simplify",
"mode": "full",
"commit": "bd345c87",
"verdict": "findings",
"prior": [],
"findings": [
{
"id": "S1",
"severity": null,
"tag": "dup-test",
"file": "core/collections/tests/tests.py",
"line": 2140,
"claim": "test_count_tasks_release_their_lock_as_they_start asserts a task option (unlock_before_run) rather than behavior. The F1.1 fix is already pinned by the async-path test in tests_collections.py, so this config check is an implementation-detail duplicate. Judgement call: it is cheap and does pin the P1 fix, so confidence is low.",
"scenario": null,
"action": "Delete the test; nothing replaces it.",
"lines_delta": -5,
"confidence": "low"
},
{
"id": "S2",
"severity": null,
"tag": "dup-test",
"file": "core/collections/tests/tests.py",
"line": 2162,
"claim": "test_update_active_count_takes_its_turn_for_any_repo_version_id mostly pins the hashtextextended key format against 64-bit ids. It tests an implementation detail, the first call hits a nonexistent collection, and the second call repeats the basic count already covered by the existing task tests (test_update_collection_active_concepts_count).",
"scenario": null,
"action": "Delete it, or reduce it to the single 2**31+1 call with no assertions. Nothing else replaces it.",
"lines_delta": -11,
"confidence": "medium"
},
{
"id": "S3",
"severity": null,
"tag": "shrink",
"file": "core/common/tasks.py",
"line": 1002,
"claim": "update_active_count reads the value back from the instance three times and does the before/after comparison by hand. The `before != after` guard only skips one cheap UPDATE of the same value.",
"scenario": null,
"action": "After the `set_<field>()` call, do `value = getattr(instance, field)` once and run `model.objects.filter(id=instance_id).update(**{field: value})` unconditionally, with no `before` variable or comparison.",
"lines_delta": -3,
"confidence": "medium"
},
{
"id": "S4",
"severity": null,
"tag": "yagni",
"file": "core/common/models.py",
"line": 882,
"claim": "queue_count_task has a `queued` flag with try/except/finally to delete the Task when nothing was queued. The `except AlreadyQueued: pass` plus the flag can be a single `except BaseException: task.delete(); raise`-style form. Because robust=True already logs and swallows errors, the flag is redundant.",
"scenario": null,
"action": "Write `try: job.apply_async(...)` then `except AlreadyQueued: task.delete()` and `except Exception: task.delete(); raise`. This drops the `queued` variable and the finally block.",
"lines_delta": -3,
"confidence": "low"
}
]
} |
|
Codex check of commits 8b94646..538c081 (codex-cli 0.169.0) Verdict: findings (1 findings)
findings.json{
"reviewer": "codex-cli 0.169.0",
"perspective": "defects",
"mode": "final",
"commit": "538c081e",
"verdict": "findings",
"prior": [],
"findings": [
{
"id": "FC.1",
"severity": "P2",
"tag": null,
"file": "core/common/models.py",
"line": 900,
"claim": "Publish cleanup can delete the tracking row for a count task that Redis accepted.",
"scenario": "Redis enqueues the task, but the producer loses the reply and raises after exhausting retries. The cleanup deletes the task row even if a worker has already started or finished the count. The task disappears from the task API, and later worker hooks cannot record its outcome.",
"action": "Delete the row only when publication is known to have been refused or never attempted. Preserve it when delivery is uncertain, and test a publish that delivers the message before raising a connection error.",
"lines_delta": null,
"confidence": "high"
}
]
} |
snyaggarwal
left a comment
There was a problem hiding this comment.
Approving at 538c081. Merge master first: the only conflict is the django.db import in core/common/tasks.py. Master's #1010 added transaction there and this branch adds connection, so it should be from django.db import DatabaseError, connection, transaction. Everything else, core/common/models.py included, merges cleanly. CI needs to pass on the merge.
The three changes hold on the paths I traced:
- Queued after the commit.
queue_count_taskputsTask.newand the publish both inside theon_commitcallback. A worker can no longer start before the task row or the references are committed, which is what left thosePENDINGrows. A rolled-back write queues nothing, androbust=Truekeeps a broker failure from failing the committed write or skipping the other count.on_commit(robust=...)needs Django 4.2 or later, and we're on 5.2. - Not dropped while one runs. The four tasks pass their own
once, replacingQueueOnce's class default, andQueueOnceCustomTaskreads onlytask_idfrom it, so nothing it relied on is lost. Withunlock_before_run,QueueOnce.__call__clears the lock before the count, so a count queued meanwhile is kept. One queued before the running count starts is still dropped, correctly, since that count reads the commit anyway. - One at a time.
pg_advisory_xact_lock(hashtextextended(...))takes a bigint, so ids past 32 bits are fine, and the lock is released whenupdate_active_count's transaction ends. The querysetupdate()loses nothing:- neither the source nor the collection document has
active_conceptsoractive_mappings; Source'spost_saveonly acts on_should_update_*flags, which a count never sets;Collection.saveonly acts on acanonical_urlchange.
- neither the source nor the collection document has
I agree with leaving FC.1 and F2.2 as accepted. They only affect the task-tracking row or the lock's expiry on an ambiguous broker failure, and the count itself still runs. The recount after removing references is right as a follow-up on the ticket.
I haven't run the tests.
|
@snyaggarwal, master's Pylint fails since this merge (Build 45144177412 on 1e037b1): |
OpenConceptLab/ocl_issues#3058
What
Three changes to how a collection's (and a source's) stored
active_concepts/active_mappingsare recounted:update_concepts_countandupdate_mappings_countqueue their count task withtransaction.on_commit(newqueue_count_task), so it's published only once the caller's transaction has committed. Outside a transactionon_commitruns at once, so views and other callers queue as before. The callback isrobust: a failure to publish is logged, neither fails the committed write nor skips the other count, and leaves noPENDINGtask row behind. The sync andTEST_MODEpaths are unchanged.once={'unlock_before_run': True}. QueueOnce otherwise holds its lock until a count finishes, so a count queued for a write that committed while one was running was dropped.concurrentqueue. Each count now holds a transaction-level advisory lock (pg_advisory_xact_lock, one 64-bit key hashed from the model, field and id) while it counts and writes, so the last to run counts last. It doesn't block other writes to the collection row. The count is written with a queryset update rather than a save: search documents hold no counts, so there's nothing to reindex.Why
Collection.add_expressionsis one transaction, andadd_referencesqueued both count tasks at its end, before the commit. That's the path for everyPUT …/references/(with or without?async=true, since both run theadd_referencestask on a worker) and for bulk-import reference lines. A worker that picked a count task up at once counted the default expansion as it was before the commit: 0 for a new collection, the old total for an existing one. Seeing no change, it saved nothing, so the stale count stayed until something recounted it.Production shows this happening. The count task's
celery_tasksrow is written in the same transaction, so a worker that runs early can't find it to mark it started or finished:PENDINGwith no start or finish time. Every one of the 20 was queued during anadd_referencestask, and 136 of the 141 during bulk imports. Count tasks queued outside a transaction (on collection create or version seeding) all finished normally.add_referencesat 16:33:36 stayedPENDING; that task finished, and committed, at 16:33:37.9. The stored count stayed 0 until a manualPUT …/summary/.Sources use the same methods and tasks, so they get the same three changes (2 source concept-count tasks show the same pattern).
Tests
CollectionReferencesViewTest.test_put_async_counts_what_the_references_added_once_they_commitsubmitsPUT references/?async=truewithTEST_MODEoff and task publishing recorded, runs the queuedadd_referencesjob as a worker would, and checks that no count is queued before the commit, that both are queued after with the collection's id, and that the counts they save exclude the retired member.ActiveCountConcurrencyTestruns two counts of one collection on separate connections: the first pauses between counting and saving while a reference commits and the second count runs. Without the lock the first saves last and leaves 1 of 2.TasksTest: a failed publish of one count still queues the other, doesn't raise and leaves no task row; all four count tasks release their lock as they start; the lock takes an id past 32 bits.core/common/models.pyandtasks.pyand pass here.TEST_MODEoff queues the count tasks now run their request undercaptureOnCommitCallbacks(execute=True)(a test's transaction never commits). Tests that call a count task directly call itsrun(), as releasing the lock in__call__needs Redis.Not in this PR
PUT …/summary/; aggregate numbers go on the ticket.🤖 Generated with Claude Code
https://claude.ai/code/session_01AaZ4qTsdWcp2GgLWvv3gqD