Skip to content

Feat job queue phase 2a - #4725

Merged
objecttothis merged 112 commits into
feat-job-queue-phase-1from
feat-job-queue-phase-2a
Nov 19, 2026
Merged

objecttothis merged 112 commits into
feat-job-queue-phase-1from
feat-job-queue-phase-2a

Conversation

@objecttothis

@objecttothis objecttothis commented Oct 2, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 2a of the background job queue (#3833). Builds on Phase 1's trigger/scheduling scaffolding (web/auto/manual modes, throttling) to add the actual CI4 Queue-backed execution engine, convert Items/Customers CSV imports to background jobs, and ship an admin UI for monitoring and managing the queue.

Queue execution engine

  • codeigniter4/queue added as dependency; app/Config/Queue.php and app/Config/Services.php wire it up.
  • app/Jobs/BoundedQueueWorker.php — deadline-bounded worker draining queues within a time budget, compatible with all three Phase 1 trigger modes.
  • app/Jobs/BaseOsposJob.php — base class for job handlers.
  • app/Jobs/JobThrottleGate.php — enforces Phase 1's per-job throttle rules before a job runs.
  • app/Config/Tasks.php updated to drain all queues via a single auto-mode scheduler, with per-queue logging (app/Logging/JobsFileHandler.php).

Queued CSV imports

  • app/Jobs/ItemImportJob.php, app/Jobs/CustomerImportJob.php, with row-processing logic extracted into app/Jobs/Support/ItemCsvRowProcessor.php and CustomerCsvRowProcessor.php.
  • Controllers/Items.php and Controllers/Customers.php import flows now push rows onto the queue instead of processing synchronously — large reduction in Items.php (379 lines removed) from extracting row logic into the processor classes.
  • Batch tracking: app/Models/ImportBatch.php, ImportBatchContext.php, app/Libraries/ImportBatchService.php track per-row progress so batch completion/failure is known once all rows finish.

Admin UI: Jobs Manage grid

  • app/Controllers/Jobs.php grows substantially to serve the manage grid, job edit, and queue actions.
  • app/Models/JobQueueManage.php, app/Views/jobs/manage_grid.php, job_edit.php — grid for viewing/editing queued jobs.
  • Per-job pause and queue-level pause tied to import batch context.
  • Requeue and CRUD actions on the grid.
  • Configurable table polling frequency for the grid (app/Views/configs/general_config.php, new migration).

Migration consolidation

  • Phase 1's three incremental Jobs migrations are squashed into a single 20260916000000_AddJobsModule.php for this branch's schema needs.

Translations

  • Jobs/Config language strings expanded across all locales for the new UI and job statuses.

Test plan

  • tests/Jobs/BoundedQueueWorkerTest.php, JobThrottleGateTest.php pass
  • tests/Libraries/ImportBatchServiceTest.php, tests/Models/ImportBatchTest.php, ImportBatchContextTest.php pass
  • tests/Controllers/JobsControllerTest.php, tests/Controllers/CustomersCsvImportTest.php pass
  • Manually import a large Items/Customers CSV and confirm rows are queued and processed by the worker, not synchronously
  • Verify Jobs Manage grid shows live job status and supports pause/requeue/delete
  • Verify pausing a queue doesn't drop in-flight (reserved) jobs

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added job management tools to search, edit, process, pause, resume, and delete jobs, with batch tracking and controls.
    • Customer and item CSV imports now run in the background; import pages report queued rows, and batches display progress and outcomes.
    • Added settings for retries, job retention, automatic cleanup, and queue throttling.
    • Added table refresh-frequency settings and live updates for job listings.
  • Bug Fixes
    • Added validation for table refresh frequency and improved CSV upload and header checks.
  • Documentation
    • Updated background job scheduling guidance.

objecttothis and others added 15 commits September 24, 2026 20:00
Backing library for the job queue execution engine (issue #3833 Phase 2).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Adds the queue_jobs, queue_jobs_failed, and job_throttles tables and wires
up BoundedQueueWorker (deadline-bounded queue draining, shared by the
JobRunner filter for web/auto mode and the manual "Process Jobs" UI) gated
by JobThrottleGate. Adds retry limit, retention, and auto-purge settings
to the Job Queue settings tab, and a manual per-queue processing UI on the
Utilities tab. Also adds a second-granularity throttle period and
BaseOsposJob as the shared base for core queue jobs.

This is issue #3833 Phase 2 — no real job types are queued yet.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Replaces the synchronous CSV import loop in Customers and Items with one
queued job per row (CustomerImportJob / ItemImportJob, processed via
CustomerCsvRowProcessor / ItemCsvRowProcessor). Only structural checks
that would make every row's job meaningless (upload failure, missing or
mismatched headers) are done in the controller; per-row validation
happens in the job itself so one bad row can't block the rest of the
file. ImportBatch / ImportBatchService track per-import progress so
completion can be reported once all rows finish.

Issue #3833 Phase 3.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Updates the Background Job Scheduling section for the new queue
execution engine: auto-mode cron/Task Scheduler entries and Docker
worker examples now also run `queue:work` alongside `tasks:run`, and
manual-mode docs reflect that Process All/Selected Jobs now actually
drain the queues instead of returning stubs.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…e logging

- Simplify 'auto' mode to run only `spark tasks:run` on cron/Task
  Scheduler; new `jobs_queue_worker` task (app/Config/Tasks.php) now
  drains core queues in-process using BoundedQueueWorker, so the
  separate `queue:work` cron entry/Task Scheduler task and Docker
  compose/sidecar commands are no longer needed (INSTALL.md).
- Extend BoundedQueueWorker to cover 'auto' mode alongside 'web' and
  'manual', removing the old single-mode restriction in its docblock.
- Add job_log() helper (app/Helpers/job_helper.php) and
  JobsFileHandler (app/Logging/JobsFileHandler.php) to write job
  activity to per-queue log files (jobsLog-{queue}-{date}.log)
  instead of the shared application log; register 'job' helper in
  app/Config/Autoload.php.
- Route job-related log_message() calls in BoundedQueueWorker,
  CustomerCsvRowProcessor, and ItemCsvRowProcessor to job_log(),
  and add extra per-row import logging (item id/name/barcode) for
  easier troubleshooting of CSV imports.

Signed-off-by: objecttothis <[email protected]>
Extend Jobs controller to support full lifecycle management of
queued/failed jobs from the Manage tab UI.

- Add getView/postSave to edit a pending/reserved job's payload,
  priority, and available_at via modal (job_edit view)
- Add getSearch to back the AJAX-driven jobs table, using new
  JobQueueManage model for search/sort/pagination and payload
  decoding
- Add postDelete to bulk-delete pending/failed jobs, blocking
  deletion of reserved (in-progress) jobs
- Add postProcessJob to manually run a single job immediately,
  requeuing failed jobs back into queue_jobs first via new
  requeueFailedJob helper
- Add splitUid helper to parse "source:id" row identifiers shared
  across the new endpoints
- Extend queue_jobs_failed migration with attempts column since
  codeigniter4/queue's DatabaseHandler::failed() doesn't carry it
  over; BoundedQueueWorker now records it on failure so Manage
  grid can show real error counts

BREAKING CHANGE: queue_jobs_failed table gains required attempts
column; run new migration before deploying.

Signed-off-by: objecttothis <[email protected]>
Introduce new Jobs admin section to view and manage queued and
failed jobs from codeigniter4/queue tables (queue_jobs,
queue_jobs_failed).

- Add JobQueueManage model: unions queue_jobs (pending/reserved)
  and queue_jobs_failed into one virtual grid, tagging each row
  with a synthetic uid ("{source}:{id}") since the two tables
  share no common identity; supports search, sort, and pagination
- Add manage_grid.php view: Bootstrap table grid listing jobs
  across selectable queues, with per-row "process job" action
  wired to jobs/processJob endpoint
- Add job_edit.php view: form for editing a single job's priority,
  available_at, and payload, with client-side validation before
  ajax submit to jobs/save

Signed-off-by: objecttothis <[email protected]>
- Rename Jobs::getView to getEditJob and Jobs::postSave to
  postSaveJob for clearer, action-specific route naming
- Update tabular_helper edit link and job_edit form action to
  use new jobs/editJob and jobs/saveJob routes
- Add confirm_delete, confirm_restore, and no_jobs_to_display
  strings to Jobs language file for upcoming bulk actions UI
- Fix alignment/formatting of Jobs language array entries

Signed-off-by: objecttothis <[email protected]>
Expand Jobs.php language files to support new job queue management
features (previously only basic mode/throttle settings existed).

- Add ~35 new translation keys per locale (ar-EG, ar-LB) covering
  job lifecycle (status, retry, requeue, process, delete, restore),
  queue management (all_queues, auto_purge, retention settings),
  and job metadata (payload, priority, code, error_count)
- New keys left as empty strings pending translation
- Realign array value alignment (=>) for all existing and new
  entries due to added longer keys
- Rename web_max_seconds-related keys to task_max_seconds in
  some entries, reflecting broader task-based terminology

Signed-off-by: objecttothis <[email protected]>
- Add import_batch_contexts table plus ImportBatchContext model so
  per-batch data (e.g. Items CSV attribute definitions) is stored
  once and referenced by context_id, instead of duplicated into
  every queued row's job payload.
- Extend queue_jobs, queue_jobs_failed, and new queue_paused_jobs
  tables with batch_id/context_id columns and FKs (ON DELETE
  RESTRICT) back to import_batch_contexts, so context rows cannot
  be purged while any job still references them.
- Introduce ImportBatchService.pushRow() to centralize queuing a
  batch row with batch/context stamping and priority; update
  Customers and Items controllers to use it instead of calling
  importBatch->create() and queue->push() separately.
- Add queue_paused_jobs table and Jobs::postPauseJobs()/pauseQueues()
  to move pending jobs out of queue_jobs into a paused table per
  queue (all core queues or a selected subset), leaving in-flight
  jobs untouched (issue #3833 pause/resume design).
- Change Jobs::getEditJob()/postSaveJob() routes to accept separate
  source/id path segments instead of a combined uid string.
- Add test coverage for ImportBatchContext, ImportBatchService, and
  ImportBatch (including purge-retains-while-referenced guards).

Signed-off-by: objecttothis <[email protected]>
- Introduce pause icon for individual jobs in the manage grid.
- Add `Jobs::postPauseJob` controller method to handle pausing of single jobs.
- Update tabular helper to include pause link for pending jobs.
- Extend language files with translation for "pause job."
- Implement client-side logic for pausing jobs with AJAX in manage_grid.js.
- Update CSV import logic to correctly handle escaped headers.

Signed-off-by: objecttothis <[email protected]>
- Config.php: add validation rules (required, natural number,
  max 60) and localized error messages for new
  table_polling_frequency setting; persist value from POST
  into config save handler alongside existing fields
- Language files: add table_polling_frequency,
  table_polling_frequency_number, table_polling_frequency_range,
  table_polling_frequency_required keys across all locale
  Config.php files (en-GB populated with full text, other
  locales added as empty placeholders for translation)

Signed-off-by: objecttothis <[email protected]>
Add new migration to seed app_config table with default
table_polling_frequency setting (value: 0).

- Up: insert key/value pair into app_config, ignoring duplicates
- Down: remove the table_polling_frequency row on rollback

Signed-off-by: objecttothis <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

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

No actionable comments were generated in the recent review.

Walkthrough

The PR adds queue-backed job execution and management, moves customer and item CSV imports to per-row jobs, and adds batch tracking. It also adds table-polling configuration and related locale, documentation, and test changes.

Changes: Queue jobs and supporting features

Layer / File(s) Summary
Queue configuration and execution
composer.json, app/Config/*, app/Database/Migrations/*, app/Jobs/*, app/Filters/JobRunner.php, app/Helpers/job_helper.php, app/Logging/JobsFileHandler.php, tests/Jobs/*, tests/Logging/*
Adds queue configuration, storage, bounded worker execution, throttling, queue-specific logging, and scheduled queue processing. The new migration consolidates the jobs tables, settings, and module registration.
Queued imports and batch tracking
app/Controllers/Customers.php, app/Controllers/Items.php, app/Jobs/CustomerImportJob.php, app/Jobs/ItemImportJob.php, app/Jobs/Support/*, app/Libraries/ImportBatchService.php, app/Models/ImportBatch*.php, app/Helpers/importfile_helper.php, tests/Controllers/*CsvImportTest.php, tests/Models/ImportBatch*.php, tests/Libraries/ImportBatchServiceTest.php, app/Language/*/{Customers,Items}.php
Import endpoints validate CSV structure, create batches, and enqueue row jobs. Row processors handle customer and item validation and writes. Batch records track completed and failed rows.
Job and batch management
app/Controllers/Jobs.php, app/Models/JobQueueManage.php, app/Helpers/tabular_helper.php, app/Views/jobs/*, app/Views/partial/job_throttles.php, app/Models/JobThrottle.php, tests/Controllers/JobsControllerTest.php, tests/Models/JobQueueManageTest.php, tests/Models/JobThrottleModelTest.php, app/Language/*/Jobs.php
Adds job and batch search, editing, processing, deletion, pause and resume actions, and queue-scoped throttle settings. The views add job and batch tables and controls.
Polling settings and supporting updates
app/Controllers/Config.php, app/Views/configs/general_config.php, app/Models/Stock_location.php, docs/INSTALL.md, tests/Controllers/*, tests/Models/*, app/Language/*/Config.php
Adds table-polling frequency validation and persistence. The jobs grid uses this setting for polling. Stock-location methods accept an optional person ID. Documentation, locale entries, and test setup are updated.

Estimated code review effort: 5 (Critical) | ~120 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant ImportController
  participant ImportBatchService
  participant QueueStorage
  participant ImportJob
  participant RowProcessor
  ImportController->>ImportBatchService: Create batch and enqueue CSV rows
  ImportBatchService->>QueueStorage: Store row jobs with batch references
  QueueStorage->>ImportJob: Deliver row job
  ImportJob->>RowProcessor: Validate and save row
  ImportJob->>ImportBatchService: Record row result
Loading
Merge Risk: Moderate · previous review da90c

The queue-backed job and import features introduce several unresolved data-integrity and availability concerns. These include production database compatibility, migration upgrade and rollback behavior, duplicate or stranded job execution, and inconsistent import batch accounting. Resolve or explicitly accept them before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "Feat job queue phase 2a" matches the main change: the PR adds a CI4 Queue-backed job execution engine, a jobs admin UI, and converts Items and Customers CSV imports to queued per-row jobs. …
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.
Full details: Title check

Explanation

The title "Feat job queue phase 2a" matches the main change: the PR adds a CI4 Queue-backed job execution engine, a jobs admin UI, and converts Items and Customers CSV imports to queued per-row jobs. It names the feature area but does not describe the import conversion or the admin UI, and "phase 2a" is a project-internal label that a teammate may not recognize from the title alone. The title is related to the main change and is specific enough for a teammate scanning history to find the primary feature.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7e21e054-e798-40a1-9e96-82fb375c983f
Commits

Reviewing files that changed from the base of the PR and between 9df83ea and da90c9f.

Files selected for processing: 13

  • app/Language/az/Jobs.php
  • app/Language/sv/Jobs.php
  • app/Language/sw-KE/Jobs.php
  • app/Language/sw-TZ/Jobs.php
  • app/Language/ta/Jobs.php
  • app/Language/th/Jobs.php
  • app/Language/tl/Jobs.php
  • app/Language/tr/Jobs.php
  • app/Language/uk/Jobs.php
  • app/Language/ur/Jobs.php
  • app/Language/vi/Jobs.php
  • app/Language/zh-Hans/Jobs.php
  • app/Language/zh-Hant/Jobs.php
Files skipped from review as they are similar to previous changes: 13

  • app/Language/az/Jobs.php
  • app/Language/sv/Jobs.php
  • app/Language/sw-KE/Jobs.php
  • app/Language/sw-TZ/Jobs.php
  • app/Language/ta/Jobs.php
  • app/Language/th/Jobs.php
  • app/Language/tl/Jobs.php
  • app/Language/tr/Jobs.php
  • app/Language/uk/Jobs.php
  • app/Language/ur/Jobs.php
  • app/Language/vi/Jobs.php
  • app/Language/zh-Hans/Jobs.php
  • app/Language/zh-Hant/Jobs.php

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 4 remain after this review.

@objecttothis
objecttothis added this pull request to stack #4740 October 7, 2026 13:54
objecttothis and others added 11 commits October 7, 2026 17:55
Backing library for the job queue execution engine (issue #3833 Phase 2).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Adds the queue_jobs, queue_jobs_failed, and job_throttles tables and wires
up BoundedQueueWorker (deadline-bounded queue draining, shared by the
JobRunner filter for web/auto mode and the manual "Process Jobs" UI) gated
by JobThrottleGate. Adds retry limit, retention, and auto-purge settings
to the Job Queue settings tab, and a manual per-queue processing UI on the
Utilities tab. Also adds a second-granularity throttle period and
BaseOsposJob as the shared base for core queue jobs.

This is issue #3833 Phase 2 — no real job types are queued yet.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Replaces the synchronous CSV import loop in Customers and Items with one
queued job per row (CustomerImportJob / ItemImportJob, processed via
CustomerCsvRowProcessor / ItemCsvRowProcessor). Only structural checks
that would make every row's job meaningless (upload failure, missing or
mismatched headers) are done in the controller; per-row validation
happens in the job itself so one bad row can't block the rest of the
file. ImportBatch / ImportBatchService track per-import progress so
completion can be reported once all rows finish.

Issue #3833 Phase 3.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Updates the Background Job Scheduling section for the new queue
execution engine: auto-mode cron/Task Scheduler entries and Docker
worker examples now also run `queue:work` alongside `tasks:run`, and
manual-mode docs reflect that Process All/Selected Jobs now actually
drain the queues instead of returning stubs.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…e logging

- Simplify 'auto' mode to run only `spark tasks:run` on cron/Task
  Scheduler; new `jobs_queue_worker` task (app/Config/Tasks.php) now
  drains core queues in-process using BoundedQueueWorker, so the
  separate `queue:work` cron entry/Task Scheduler task and Docker
  compose/sidecar commands are no longer needed (INSTALL.md).
- Extend BoundedQueueWorker to cover 'auto' mode alongside 'web' and
  'manual', removing the old single-mode restriction in its docblock.
- Add job_log() helper (app/Helpers/job_helper.php) and
  JobsFileHandler (app/Logging/JobsFileHandler.php) to write job
  activity to per-queue log files (jobsLog-{queue}-{date}.log)
  instead of the shared application log; register 'job' helper in
  app/Config/Autoload.php.
- Route job-related log_message() calls in BoundedQueueWorker,
  CustomerCsvRowProcessor, and ItemCsvRowProcessor to job_log(),
  and add extra per-row import logging (item id/name/barcode) for
  easier troubleshooting of CSV imports.

Signed-off-by: objecttothis <[email protected]>
Extend Jobs controller to support full lifecycle management of
queued/failed jobs from the Manage tab UI.

- Add getView/postSave to edit a pending/reserved job's payload,
  priority, and available_at via modal (job_edit view)
- Add getSearch to back the AJAX-driven jobs table, using new
  JobQueueManage model for search/sort/pagination and payload
  decoding
- Add postDelete to bulk-delete pending/failed jobs, blocking
  deletion of reserved (in-progress) jobs
- Add postProcessJob to manually run a single job immediately,
  requeuing failed jobs back into queue_jobs first via new
  requeueFailedJob helper
- Add splitUid helper to parse "source:id" row identifiers shared
  across the new endpoints
- Extend queue_jobs_failed migration with attempts column since
  codeigniter4/queue's DatabaseHandler::failed() doesn't carry it
  over; BoundedQueueWorker now records it on failure so Manage
  grid can show real error counts

BREAKING CHANGE: queue_jobs_failed table gains required attempts
column; run new migration before deploying.

Signed-off-by: objecttothis <[email protected]>
Introduce new Jobs admin section to view and manage queued and
failed jobs from codeigniter4/queue tables (queue_jobs,
queue_jobs_failed).

- Add JobQueueManage model: unions queue_jobs (pending/reserved)
  and queue_jobs_failed into one virtual grid, tagging each row
  with a synthetic uid ("{source}:{id}") since the two tables
  share no common identity; supports search, sort, and pagination
- Add manage_grid.php view: Bootstrap table grid listing jobs
  across selectable queues, with per-row "process job" action
  wired to jobs/processJob endpoint
- Add job_edit.php view: form for editing a single job's priority,
  available_at, and payload, with client-side validation before
  ajax submit to jobs/save

Signed-off-by: objecttothis <[email protected]>
- Rename Jobs::getView to getEditJob and Jobs::postSave to
  postSaveJob for clearer, action-specific route naming
- Update tabular_helper edit link and job_edit form action to
  use new jobs/editJob and jobs/saveJob routes
- Add confirm_delete, confirm_restore, and no_jobs_to_display
  strings to Jobs language file for upcoming bulk actions UI
- Fix alignment/formatting of Jobs language array entries

Signed-off-by: objecttothis <[email protected]>
Expand Jobs.php language files to support new job queue management
features (previously only basic mode/throttle settings existed).

- Add ~35 new translation keys per locale (ar-EG, ar-LB) covering
  job lifecycle (status, retry, requeue, process, delete, restore),
  queue management (all_queues, auto_purge, retention settings),
  and job metadata (payload, priority, code, error_count)
- New keys left as empty strings pending translation
- Realign array value alignment (=>) for all existing and new
  entries due to added longer keys
- Rename web_max_seconds-related keys to task_max_seconds in
  some entries, reflecting broader task-based terminology

Signed-off-by: objecttothis <[email protected]>
- Add import_batch_contexts table plus ImportBatchContext model so
  per-batch data (e.g. Items CSV attribute definitions) is stored
  once and referenced by context_id, instead of duplicated into
  every queued row's job payload.
- Extend queue_jobs, queue_jobs_failed, and new queue_paused_jobs
  tables with batch_id/context_id columns and FKs (ON DELETE
  RESTRICT) back to import_batch_contexts, so context rows cannot
  be purged while any job still references them.
- Introduce ImportBatchService.pushRow() to centralize queuing a
  batch row with batch/context stamping and priority; update
  Customers and Items controllers to use it instead of calling
  importBatch->create() and queue->push() separately.
- Add queue_paused_jobs table and Jobs::postPauseJobs()/pauseQueues()
  to move pending jobs out of queue_jobs into a paused table per
  queue (all core queues or a selected subset), leaving in-flight
  jobs untouched (issue #3833 pause/resume design).
- Change Jobs::getEditJob()/postSaveJob() routes to accept separate
  source/id path segments instead of a combined uid string.
- Add test coverage for ImportBatchContext, ImportBatchService, and
  ImportBatch (including purge-retains-while-referenced guards).

Signed-off-by: objecttothis <[email protected]>
- Introduce pause icon for individual jobs in the manage grid.
- Add `Jobs::postPauseJob` controller method to handle pausing of single jobs.
- Update tabular helper to include pause link for pending jobs.
- Extend language files with translation for "pause job."
- Implement client-side logic for pausing jobs with AJAX in manage_grid.js.
- Update CSV import logic to correctly handle escaped headers.

Signed-off-by: objecttothis <[email protected]>
@objecttothis

Copy link
Copy Markdown
Member Author

@coderabbitai I pushed 630e871 to address the two items from your last review of 709b193. The full PHPUnit suite passes locally. Please re-check once CI finishes, resolve every thread you can verify, and comment on the thread of any problem that remains.

  • ImportBatch::increment(): it now uses a balanced begin/commit/rollback sequence and throws on a failed lock query. After a rollback at the outermost level it resets the connection's transaction status, as do BoundedQueueWorker and ImportRowJob. A new test checks that the transaction depth is back to 0 after a query exception and that a later increment works.
  • Migration coverage: new tests roll back a later batch while earlier batches exist, then re-migrate, and also exercise migrate --all followed by a rollback. The --all test found a real bug: AddJobsModule::up() recorded the vendor queue migrations even when --all had already run them. That left duplicate history rows, and a rollback then ran the vendor down() methods twice. It now records only the missing rows.
  • Failed commit on item import: I found a safe way to test this. The row transaction in ItemCsvRowProcessor is now runInTransaction(). Unit tests drive it with a mocked connection, so a failed commit is simulated without touching the database. They cover success, a rejected row, a failed transaction status, a failed commit, and an exception.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -o pipefail
echo '=== Current PR head and checks ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup --jq '{headRefOid, checks:[.statusCheckRollup[]? | {name,context,status,conclusion,state}]}'
echo '=== Revision and change summary ==='
git rev-parse HEAD
git show --no-patch --format='%H%n%P%n%s' 630e87134
git diff --stat 709b19340 HEAD
echo '=== Repository instructions ==='
fd -H -t f -g AGENTS.md -E vendor -E node_modules -E .git . | while IFS= read -r f; do
  echo "--- $f"
  cat "$f"
done
echo '=== Unresolved CodeRabbit review threads ==='
gh api graphql --paginate -F owner=opensourcepos -F name=opensourcepos -F number=4725 -f query='
query($owner:String!, $name:String!, $number:Int!, $endCursor:String) {
  repository(owner:$owner,name:$name) {
    pullRequest(number:$number) {
      reviewThreads(first:100,after:$endCursor) {
        pageInfo { hasNextPage endCursor }
        nodes {
          id isResolved isOutdated path line originalLine
          comments(first:50) {
            pageInfo { hasNextPage }
            nodes { author { login } url body }
          }
        }
      }
    }
  }
}' | jq -r '.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false and (.comments.nodes[0].author.login // "" | ascii_downcase | startswith("coderabbit"))) | "THREAD \(.id) \(.path):\(.line // .originalLine) more=\(.comments.pageInfo.hasNextPage)\n" + ([.comments.nodes[] | "  \(.author.login) \(.url) " + (.body | gsub("<details>[\\s\\S]*?</details>"; " ") | gsub("<!--[^>]*-->"; " ") | gsub("\\s+"; " ") | .[0:1800])] | join("\n"))'
echo '=== Changed file outlines ==='
git diff --name-only 709b19340 HEAD | while IFS= read -r f; do
  if [ -f "$f" ]; then
    echo "--- $f"
    ast-grep outline "$f" --items all 2>/dev/null || true
  fi
done

Length of output: 56335


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Latest changes ==='
git diff --unified=4 709b19340 HEAD -- app/Database/Migrations/20261110000000_AddJobsModule.php app/Jobs/BoundedQueueWorker.php app/Jobs/ImportRowJob.php app/Jobs/Support/ItemCsvRowProcessor.php app/Models/ImportBatch.php tests/Database/Migrations/AddJobsModuleTest.php tests/Jobs/Support/ItemCsvRowProcessorTest.php tests/Models/ImportBatchTest.php
echo '=== Worker failure and peer paths ==='
cat -n app/Jobs/BoundedQueueWorker.php | sed -n '100,340p'
echo '=== Batch row execution ==='
cat -n app/Jobs/ImportRowJob.php
cat -n app/Jobs/CustomerImportJob.php
cat -n app/Jobs/ItemImportJob.php
echo '=== Batch progress and replay ==='
cat -n app/Models/ImportBatch.php | sed -n '25,175p;230,310p'
echo '=== Batch controls ==='
cat -n app/Helpers/tabular_helper.php | sed -n '1100,1175p'
ast-grep outline app/Controllers/Jobs.php --items all --match 'requeueFailedJob|postPauseBatch|postResumeBatch'
ast-grep outline app/Models/QueueJobPausedModel.php --items all
rg -n -A65 -B5 'function (requeueFailedJob|postPauseBatch|postResumeBatch|moveToPaused|moveToPending)\(' app/Controllers/Jobs.php app/Models/QueueJobPausedModel.php
echo '=== CI status polling ==='
for attempt in 1 2 3 4 5 6; do
  data=$(gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup) || { echo CHECK_LOOKUP_FAILED; break; }
  echo "POLL $attempt"
  printf '%s' "$data" | jq -r '"head=\(.headRefOid)", ([.statusCheckRollup[]? | select((.name // "") | endswith(" Tests"))] | group_by(.status + ":" + (.conclusion // ""))[] | "\(length) \(.[0].status) \(.[0].conclusion)")'
  if [ "$(printf '%s' "$data" | jq -r .headRefOid)" != 630e8713490715d21d007338977c846e0aef0a69 ]; then echo HEAD_CHANGED; break; fi
  if printf '%s' "$data" | jq -e '[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests"))] | length > 0 and all(.[]; .status == "COMPLETED")' >/dev/null; then
    printf '%s' "$data" | jq -r '.statusCheckRollup[]? | select((.name // "") | endswith(" Tests")) | "\(.name): \(.conclusion)"'
    echo TESTS_COMPLETED
    break
  fi
  if [ "$attempt" -lt 6 ]; then sleep 5; else echo TESTS_STILL_RUNNING; fi
done

Length of output: 56293


@objecttothis At the last check, all 16 PHPUnit matrix jobs were still running on 630e87134.

I did not resolve or reply to any threads. Repository guidance requires the relevant tests to finish first. I cannot monitor CI in the background, so please ask me to re-check after it finishes.


Learnings added

Learnt from: objecttothis
URL: https://github.com/opensourcepos/opensourcepos/pull/4725

Timestamp: 2026-11-18T08:41:46.276Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Database/Migrations/20261110000000_AddJobsModule.php"]: For the jobs feature, the intended migration path uses core App migrations rather than requiring CodeIgniter Queue vendor migrations. In app/Database/Migrations/20261110000000_AddJobsModule.php, migrate --all can already have run the vendor queue migrations before AddJobsModule::up() records their history. Record only missing vendor migration rows: duplicate history rows make rollback run vendor down() methods twice.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


Learnings used

Learnt from: CR
Repo: opensourcepos/opensourcepos PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-11-16T14:24:28.736Z
Learning: Applies to **/*.php : Source excerpt:
# Agent Instructions

## Conventions

### Database Queries, Transactions & Migrations

- **Balanced transactions**: Never mix `$this->db->transStart()` / `$this->db->transComplete()` with manual `$this->db->transRollback()` or early `return` statements before `transComplete()`. Returning before `transComplete()` leaves `transDepth` incremented on the shared DB connection and corrupts subsequent transactions in the request.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:40:46.694Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Database/Migrations/20261110000000_AddJobsModule.php"]: For the jobs feature in opensourcepos/opensourcepos, the intended migration path uses core App migrations rather than codeigniter4/queue vendor migrations. When reviewing app/Database/Migrations/20261110000000_AddJobsModule.php, evaluate the application migration's queue schema instead of assuming that vendor migrations are a required production upgrade path.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:25:09.048Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, when verifying a review fix and relevant tests are still running, wait for them to finish before commenting. If the tests fail, do not resolve the finding. If they pass and the code fixes the finding, resolve it, subject to applicable thread-resolution restrictions.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-09T10:46:20.615Z
Learning: Within repository "opensourcepos/opensourcepos": When assessing whether to resolve a review conversation in this repository, keep it open while any aspect of the request remains incomplete.

You are interacting with an AI system.

@objecttothis

Copy link
Copy Markdown
Member Author

@coderabbitai CI on 630e871 has finished and all 16 PHPUnit jobs passed. Please re-check the open threads against 630e871 and resolve every one you can verify. For any thread where work remains, please comment on that thread describing the outstanding problem.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -o pipefail
echo '=== checkout ==='
git rev-parse HEAD
git show --no-patch --format='%H %P %s' 630e87134
echo '=== PR head and checks ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup --jq '{headRefOid,checks:[.statusCheckRollup[]? | {name,context,status,conclusion,state}]}'
echo '=== unresolved review threads ==='
gh api graphql --paginate -F owner=opensourcepos -F name=opensourcepos -F number=4725 -f query='
query($owner:String!, $name:String!, $number:Int!, $endCursor:String) {
 repository(owner:$owner,name:$name) { pullRequest(number:$number) {
  reviewThreads(first:100,after:$endCursor) {
   pageInfo { hasNextPage endCursor }
   nodes { id isResolved isOutdated path line originalLine
    comments(first:100) { pageInfo { hasNextPage } nodes { author { login } url body } }
   }
  }
 } }
}' | jq -r '.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false) | "THREAD \(.id) \(.path):\(.line // .originalLine) more=\(.comments.pageInfo.hasNextPage)\n" + ([.comments.nodes[] | "  \(.author.login) \(.url) " + (.body | gsub("<details>[\\s\\S]*?</details>"; " ") | gsub("<!--.*?-->"; " ") | gsub("\\s+"; " ") | .[0:2800])] | join("\n"))'
echo '=== repository instruction files ==='
fd -H -t f -g AGENTS.md -E vendor -E node_modules -E .git . | while IFS= read -r f; do echo "--- $f"; cat "$f"; done
echo '=== affected file outlines ==='
for f in app/Jobs/BoundedQueueWorker.php app/Jobs/ImportRowJob.php app/Jobs/CustomerImportJob.php app/Jobs/ItemImportJob.php app/Jobs/Support/ItemCsvRowProcessor.php app/Models/ImportBatch.php app/Controllers/Jobs.php app/Helpers/tabular_helper.php app/Database/Migrations/20261110000000_AddJobsModule.php tests/Database/Migrations/AddJobsModuleTest.php tests/Jobs/BoundedQueueWorkerTest.php tests/Jobs/ImportRowJobTest.php tests/Models/ImportBatchTest.php tests/Controllers/JobsControllerTest.php tests/Jobs/Support/ItemCsvRowProcessorTest.php; do
  if [ -f "$f" ]; then echo "--- $f"; ast-grep outline "$f" --items all; else echo "--- MISSING $f"; fi
done

Length of output: 67751


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Worker failure handling and peer collection ==='
cat -n app/Jobs/BoundedQueueWorker.php | sed -n '85,370p'
echo '=== Import job transaction ==='
cat -n app/Jobs/ImportRowJob.php
cat -n app/Jobs/CustomerImportJob.php
cat -n app/Jobs/ItemImportJob.php
echo '=== Item row transaction ==='
cat -n app/Jobs/Support/ItemCsvRowProcessor.php | sed -n '40,185p'
echo '=== Batch accounting ==='
cat -n app/Models/ImportBatch.php | sed -n '25,200p;245,330p'
echo '=== Batch controls ==='
cat -n app/Helpers/tabular_helper.php | sed -n '1100,1166p'
cat -n app/Controllers/Jobs.php | sed -n '275,415p;840,1060p'
echo '=== Migration history and rollback ==='
cat -n app/Database/Migrations/20261110000000_AddJobsModule.php | sed -n '105,205p;255,345p'
echo '=== Migration tests ==='
cat -n tests/Database/Migrations/AddJobsModuleTest.php
echo '=== Regression tests ==='
cat -n tests/Jobs/BoundedQueueWorkerTest.php | sed -n '380,480p'
cat -n tests/Jobs/ImportRowJobTest.php | sed -n '25,115p'
cat -n tests/Jobs/Support/ItemCsvRowProcessorTest.php | sed -n '30,180p'
cat -n tests/Models/ImportBatchTest.php | sed -n '55,145p;195,285p'
rg -n -A70 -B4 'function (testPostProcessJob_RequeueReleasesPriorFailedCountAndReopensBatch|testPostPauseBatch_KeepsBatchTotalAndPayloadBatchId|testPostPauseJob_DetachesJobFromBatch|testPostResumeJob_DetachedJobLeavesBatchUntouched|testPauseBatchResume_BatchCompletesOnlyAfterResumedJobFinishes|testPostDelete_PausedJobWithBatch_DecrementsTotalOnce)\(' tests/Controllers/JobsControllerTest.php
echo '=== CI4 transaction implementation ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/BaseConnection.php | rg -n -A90 -B5 'function transBegin\(|function transCommit\(|function transRollback\(|function resetTransStatus\('

Length of output: 90848


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Current head ==='
git rev-parse HEAD
echo '=== Migration implementation ==='
cat -n app/Database/Migrations/20261110000000_AddJobsModule.php | sed -n '1,105p;200,258p'
echo '=== Migration runner semantics ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/MigrationRunner.php | rg -n -A115 -B8 'function regress\(|function latest\(|function migrate\(|function findMigrations\('
echo '=== Replay transaction ==='
rg -n -A90 -B4 'function\s+requeueFailedJob\s*\(' app/Controllers/Jobs.php
echo '=== Import batch query exception test ==='
cat -n tests/Models/ImportBatchTest.php | sed -n '270,320p'
echo '=== Import batch service and detached payload ==='
ast-grep outline app/Libraries/ImportBatchService.php --items all
cat -n app/Libraries/ImportBatchService.php | sed -n '55,145p'
echo '=== Test for progress transaction rollback ==='
ast-grep outline tests/Support/Jobs/BatchProgressTestJob.php --items all
cat -n tests/Support/Jobs/BatchProgressTestJob.php
echo '=== Commit and failure injection test locations ==='
rg -n -i -C 3 'commit.*fail|fail.*commit|transCommit|progress.*fail|row.*roll.?back|rollback.*row|failed.*insert|peer.*pop|batch.*progress' tests/Jobs tests/Models/ImportBatchTest.php tests/Controllers/JobsControllerTest.php | head -260
echo '=== Transaction depth accessibility and query behavior ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/BaseConnection.php | rg -n -C 5 'transDepth|handleTransStatus\(' | head -130

Length of output: 55142


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Queue and framework versions ==='
rg -n -A8 -B4 '"name": "codeigniter4/queue"|"name": "codeigniter4/framework"' composer.lock
echo '=== Queue later implementation ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/queue/87f736a69a0d64bce0c40bcb1a3f966250f70f03/src/Handlers/DatabaseHandler.php | rg -n -A75 -B8 'function (later|pop|done)\('
echo '=== Queue config and peer test setup ==='
cat -n tests/Jobs/BoundedQueueWorkerTest.php | sed -n '25,85p;265,345p;420,450p'
echo '=== Batch search control data ==='
cat -n app/Controllers/Jobs.php | sed -n '180,245p;403,452p'
echo '=== Migration batches and command selection ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Commands/Database/Migrate.php | rg -n -A90 -B5 'function run\('
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/MigrationRunner.php | rg -n -A45 -B5 'function getBatchHistory\(|function getLastBatch\(|function getBatches\('

Length of output: 20549


Script executed:

#!/bin/bash
set -o pipefail
echo '=== transComplete semantics ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/BaseConnection.php | rg -n -A50 -B8 'function transComplete\('
echo '=== Item processor callers ==='
rg -n -C 4 'ItemCsvRowProcessor|processBatchRow\s*\(' app tests/Jobs
echo '=== Manual process flow ==='
cat -n app/Controllers/Jobs.php | sed -n '450,545p'
echo '=== Pause and resume entry points ==='
cat -n app/Controllers/Jobs.php | sed -n '275,325p;570,625p;780,845p'
echo '=== Migration tests and vendor history assertions ==='
cat -n tests/Database/Migrations/AddJobsModuleTest.php | sed -n '19,105p'
echo '=== Tests asserting progress label ==='
rg -n -i -C 3 "progress.*(10/10|failed|processed)|10/10|8/10|get_batch_data_row" tests/Controllers/JobsControllerTest.php tests/Helpers || true

Length of output: 23677


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Locked vendor queue migration files ==='
gh api 'repos/codeigniter4/queue/git/trees/87f736a69a0d64bce0c40bcb1a3f966250f70f03?recursive=1' --jq '.tree[].path | select(contains("Database/Migrations/"))'
echo '=== Vendor rollback source ==='
for name in 2023-10-12-112040_AddQueueTables.php 2023-11-05-064053_AddPriorityField.php 2024-12-27-110712_ChangePayloadFieldTypeInSqlsrv.php; do
  path=$(gh api 'repos/codeigniter4/queue/git/trees/87f736a69a0d64bce0c40bcb1a3f966250f70f03?recursive=1' --jq ".tree[].path | select(endswith(\"$name\"))")
  if [ -n "$path" ]; then
    echo "--- $path"
    curl -fsSL --max-time 20 "https://raw.githubusercontent.com/codeigniter4/queue/87f736a69a0d64bce0c40bcb1a3f966250f70f03/$path" | rg -n -A35 -B3 'function down\('
  fi
done

Length of output: 2913


Script executed:

#!/bin/bash
set -u
set -o pipefail
repo=opensourcepos/opensourcepos
expected=630e8713490715d21d007338977c846e0aef0a69

info=$(gh pr view 4725 -R "$repo" --json headRefOid,statusCheckRollup) || { echo 'PRECHECK_FAILED: cannot read PR checks'; exit 0; }
if [ "$(printf '%s' "$info" | jq -r '.headRefOid')" != "$expected" ]; then
  echo 'PRECHECK_FAILED: PR head changed'
  exit 0
fi
if ! printf '%s' "$info" | jq -e '[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests"))] | length == 16 and all(.[]; .status == "COMPLETED" and .conclusion == "SUCCESS")' >/dev/null; then
  echo 'PRECHECK_FAILED: the 16 test checks are missing, pending, or unsuccessful'
  exit 0
fi
echo 'PRECHECK_OK: matching head and 16 successful PHPUnit checks'

eligible() {
  local id="$1" number="$2" head data
  head=$(gh pr view 4725 -R "$repo" --json headRefOid --jq '.headRefOid' 2>/dev/null) || { echo 'SKIP: head lookup failed'; return 1; }
  if [ "$head" != "$expected" ]; then echo "SKIP: head changed to $head"; return 1; fi
  data=$(gh api graphql -F id="$id" -f query='
query($id:ID!) {
 node(id:$id) {
  ... on PullRequestReviewThread {
   id isResolved comments(first:1) { nodes { author { login } url } }
  }
 }
}') || { echo "SKIP: thread lookup failed for $id"; return 1; }
  if ! printf '%s' "$data" | jq -e --arg url "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r$number" \
    '.data.node.isResolved == false and .data.node.comments.nodes[0].author.login == "coderabbitai" and .data.node.comments.nodes[0].url == $url' >/dev/null; then
    echo "SKIP: thread state or ownership changed for $id"
    return 1
  fi
}

reply() {
  local id="$1" number="$2" label="$3" body="$4" result
  if ! eligible "$id" "$number"; then return; fi
  result=$(gh api -X POST "repos/$repo/pulls/4725/comments/$number/replies" -f body="$body" 2>&1) || {
    echo "REPLY_FAILED $label: $result"; return;
  }
  if printf '%s' "$result" | jq -e '.html_url != null' >/dev/null 2>&1; then
    echo "REPLIED $label $(printf '%s' "$result" | jq -r .html_url)"
  else
    echo "REPLY_FAILED $label: $result"
  fi
}

echo '=== Replies on findings with remaining work ==='
reply PRRT_kwDOAOCvWs63DAqh 4562173520 'Migration rollback' \
'The new tests cover a later-batch rollback and an all-namespace rollback. A different-batch case remains: if the vendor queue migrations were already recorded in an earlier batch, `down()` takes the other branch, deletes their earlier history, and drops their tables. A one-batch rollback then changes the earlier batch; a rollback across both batches can also run the already-collected vendor `AddPriorityField::down()` against the dropped tables. Please preserve the earlier vendor state and add a test with vendor migrations in an earlier batch. The `--all` test also stops after rollback, so please verify re-migration and history there.'

reply PRRT_kwDOAOCvWs63DAqp 4562173534 'Failed-job persistence' \
'The insert, delete, and batch increment now share a transaction. One commit-failure path remains: `moveToFailed()` returns a false `transCommit()` result without rolling back. In CI4 4.7.4, a failed commit leaves the transaction depth unchanged. The subsequent `later()` can therefore run on the still-open transaction rather than releasing the committed live job. Please roll back or otherwise recover safely before retrying, and add a failed-commit test.'

reply PRRT_kwDOAOCvWs63DAqr 4562173537 'Handler preparation and peers' \
'Matching peers are now tracked before the next pop. A differently typed candidate is not tracked: `popPeers()` calls `later()` before adding it to `$peers`, and ignores a false return. If that call fails or throws after the candidate was reserved, the candidate can remain reserved without being handled by the catch block. Please track and safely release that candidate separately, and test both a false return and an exception.'

reply PRRT_kwDOAOCvWs63DAqv 4562173541 'Import row failures' \
'Rejected rows now reach the worker, and the failed-row move and batch count share a transaction. If the outer commit of `moveToFailed()` returns false, the code does not roll it back before `later()` runs. The failed move and failure count can remain uncommitted while the original job remains reserved. Please make that commit-failure path recoverable and test the payload and batch count after recovery.'

reply PRRT_kwDOAOCvWs63DAq5 4562173559 'Item row transaction' \
'The new test confirms that a false commit result throws. `runInTransaction()` does not roll back after that result, however. CI4 4.7.4 leaves the transaction depth unchanged when an outer commit fails. In the queued path, the item transaction is nested and the actual outer commit is in `ImportRowJob::processBatchRow()`, which also throws without rolling back. Please cover and recover both outer commit-failure paths, including the connection state and row persistence.'

reply PRRT_kwDOAOCvWs63DAq7 4562173564 'Replay completion accounting' \
'The replay count is reversed and completion is now transition-aware. One replay failure path remains: `requeueFailedJob()` ignores `transComplete()` and checks only `transStatus()`. If the outer commit returns false while the status remains true, it can return the uncommitted job and start processing it on an open transaction. Please handle the commit result, restore the connection safely, and add a failed-commit replay test.'

reply PRRT_kwDOAOCvWs63DArC 4562173571 'Progress transaction failures' \
'Query exceptions now roll back, and the new test checks transaction depth afterward. Failed outer commits are still not balanced: `ImportBatch::increment()` and `ImportRowJob::processBatchRow()` throw after `transCommit()` returns false without rolling back. CI4 leaves the transaction depth unchanged in that case. Please recover the transaction before propagating the failure, and test that row writes and progress are rolled back and a later operation works. The current progress-failure fixture does not persist a row before throwing.'

reply PRRT_kwDOAOCvWs63DivP 4562394087 'Batch pause and resume' \
'The controls and batch associations now follow the requested pause/resume behavior. The batch pause and resume endpoints still ignore `transComplete()` and check only `transStatus()`. If the outer commit returns false while the status remains true, the endpoint can report success with an open, uncommitted move. The single-job and queue paths use the same pattern. Please handle commit failure safely and test that the response and batch/job state match the committed result.'

echo '=== Resolve verified progress label ==='
if eligible PRRT_kwDOAOCvWs63DivJ 4562394078; then
  result=$(gh api graphql -F threadId=PRRT_kwDOAOCvWs63DivJ -f query='
mutation($threadId:ID!) {
 resolveReviewThread(input:{threadId:$threadId}) { thread { id isResolved } }
}' 2>&1) || result="API_ERROR: $result"
  if printf '%s' "$result" | jq -e '.data.resolveReviewThread.thread.isResolved == true' >/dev/null 2>&1; then
    echo 'RESOLVED Progress label https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r4562394078'
  else
    echo "RESOLUTION_FAILED Progress label: $result"
  fi
fi

Length of output: 8485


@objecttothis I checked 630e87134. All 16 PHPUnit matrix jobs passed.

I resolved the progress-label thread. I did not resolve the other eight threads. I replied to each with the remaining work:

I followed the repository guidance to leave incomplete findings unresolved.


Learnings used

Learnt from: objecttothis
URL: https://github.com/opensourcepos/opensourcepos/pull/4725

Timestamp: 2026-11-18T08:41:47.545Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Database/Migrations/20261110000000_AddJobsModule.php"]: For the jobs feature, the intended migration path uses core App migrations rather than requiring CodeIgniter Queue vendor migrations. In app/Database/Migrations/20261110000000_AddJobsModule.php, migrate --all can already have run the vendor queue migrations before AddJobsModule::up() records their history. Record only missing vendor migration rows: duplicate history rows make rollback run vendor down() methods twice.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:40:46.694Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Database/Migrations/20261110000000_AddJobsModule.php"]: For the jobs feature in opensourcepos/opensourcepos, the intended migration path uses core App migrations rather than codeigniter4/queue vendor migrations. When reviewing app/Database/Migrations/20261110000000_AddJobsModule.php, evaluate the application migration's queue schema instead of assuming that vendor migrations are a required production upgrade path.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:25:09.048Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, when verifying a review fix and relevant tests are still running, wait for them to finish before commenting. If the tests fail, do not resolve the finding. If they pass and the code fixes the finding, resolve it, subject to applicable thread-resolution restrictions.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos PR: 4725
File: app/Database/Migrations/20261110000000_AddJobsModule.php:11-11
Timestamp: 2026-11-17T08:23:17.297Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, limit migrations to one per feature while the feature is unreleased; jobs are one feature. For PR #4725, Phase 1 was not merged into master or run on production databases, so do not require an incremental migration solely to preserve a Phase 1 production upgrade path.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-09T10:46:20.615Z
Learning: Within repository "opensourcepos/opensourcepos": When assessing whether to resolve a review conversation in this repository, keep it open while any aspect of the request remains incomplete.

You are interacting with an AI system.

…migrations

- add Transaction helpers that roll back and reset the connection when an
  outermost commit fails, and use them in the worker failed-job move,
  ImportRowJob, item row processing, ImportBatch::increment and every
  transaction in the Jobs controller (pause, resume, replay, delete)
- worker: track a popped job of a different class until it is released so
  a failed or throwing release is handled instead of left reserved
- AddJobsModule::down only removes what it added to the queue tables and
  never drops them or deletes vendor history that other batches own
- tests: add a connection whose commit fails and cover the worker,
  ImportBatch, ImportRowJob, pause batch and failed-job replay with it,
  vendor migrations in an earlier batch and re-migration after --all

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@objecttothis

Copy link
Copy Markdown
Member Author

@coderabbitai I pushed 69c4171 to address the work you listed on the eight open threads. The full PHPUnit suite passes locally; CI is still running, so please re-check once it finishes. Resolve every thread you can verify, and comment on the thread of any problem that remains.

  • Failed outer commits: a new App\Libraries\Transaction helper rolls back and resets the connection when an outermost commit fails. It is used in BoundedQueueWorker::moveToFailed(), ImportRowJob, ItemCsvRowProcessor, ImportBatch::increment() and every transaction in the Jobs controller (pause, resume, replay, delete). A failed commit or failed transaction status now throws or reports failure after the rollback instead of leaving the transaction open.
  • Different-class peer release: popPeers() tracks the popped job until later() succeeds. If later() returns false or throws, the job is handled with the batch instead of staying reserved.
  • AddJobsModule::down(): it only removes what it added to the queue tables and never drops them or deletes vendor history. This covers vendor migrations in the same batch and in an earlier batch.

New tests use a test connection whose outermost commit fails, so a failed commit is simulated without touching the database. They cover:

  • the worker failed-job move;
  • ImportBatch::increment();
  • ImportRowJob, including that the row write and progress are rolled back and a later operation works;
  • pause batch;
  • failed-job replay;
  • release failure of a different-class job, both a false return and an exception;
  • vendor migrations in an earlier batch;
  • re-migration and history after --all.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -o pipefail
repo=opensourcepos/opensourcepos
for attempt in 1 2 3 4 5 6; do
  data=$(gh pr view 4725 -R "$repo" --json headRefOid,statusCheckRollup) || { echo 'CHECK_LOOKUP_FAILED'; exit 1; }
  echo "=== Poll $attempt ==="
  printf '%s\n' "$data" | jq '{headRefOid, tests:[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests")) | {name,status,conclusion}], otherChecks:[.statusCheckRollup[]? | select(((.name // "") | endswith(" Tests")) | not) | {name,context,status,conclusion,state}]}'
  head=$(printf '%s' "$data" | jq -r .headRefOid)
  case "$head" in 69c4171e1*) ;; *) echo 'HEAD_DIFFERS_FROM_REQUESTED_COMMIT'; exit 0;; esac
  if printf '%s' "$data" | jq -e '[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests"))] | length == 16 and all(.[]; .status == "COMPLETED")' >/dev/null; then
    echo 'TEST_MATRIX_COMPLETED'
    exit 0
  fi
  if [ "$attempt" -lt 6 ]; then sleep 5; fi
done
echo 'TEST_MATRIX_NOT_COMPLETE'

Length of output: 18947


@objecttothis At my last check, all 16 PHPUnit jobs were still running on 69c4171e1. The Docker image build was also running.

I have not rechecked the fixes, resolved threads, or posted thread replies. The repository’s review guidance requires the relevant tests to finish first.

I cannot monitor CI in the background. Please ask me to re-check once it finishes.


Learnings used

Learnt from: CR
Repo: opensourcepos/opensourcepos PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-11-16T14:24:28.736Z
Learning: Applies to **/*.php : Source excerpt:
# Agent Instructions

## Conventions

### Database Queries, Transactions & Migrations

- **Balanced transactions**: Never mix `$this->db->transStart()` / `$this->db->transComplete()` with manual `$this->db->transRollback()` or early `return` statements before `transComplete()`. Returning before `transComplete()` leaves `transDepth` incremented on the shared DB connection and corrupts subsequent transactions in the request.
Learnt from: objecttothis
URL: https://github.com/opensourcepos/opensourcepos/pull/4725

Timestamp: 2026-11-18T08:41:47.545Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Database/Migrations/20261110000000_AddJobsModule.php"]: For the jobs feature, the intended migration path uses core App migrations rather than requiring CodeIgniter Queue vendor migrations. In app/Database/Migrations/20261110000000_AddJobsModule.php, migrate --all can already have run the vendor queue migrations before AddJobsModule::up() records their history. Record only missing vendor migration rows: duplicate history rows make rollback run vendor down() methods twice.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:40:46.694Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Database/Migrations/20261110000000_AddJobsModule.php"]: For the jobs feature in opensourcepos/opensourcepos, the intended migration path uses core App migrations rather than codeigniter4/queue vendor migrations. When reviewing app/Database/Migrations/20261110000000_AddJobsModule.php, evaluate the application migration's queue schema instead of assuming that vendor migrations are a required production upgrade path.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:25:09.048Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, when verifying a review fix and relevant tests are still running, wait for them to finish before commenting. If the tests fail, do not resolve the finding. If they pass and the code fixes the finding, resolve it, subject to applicable thread-resolution restrictions.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos PR: 4725
File: app/Database/Migrations/20261110000000_AddJobsModule.php:11-11
Timestamp: 2026-11-17T08:23:17.297Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, limit migrations to one per feature while the feature is unreleased; jobs are one feature. For PR #4725, Phase 1 was not merged into master or run on production databases, so do not require an incremental migration solely to preserve a Phase 1 production upgrade path.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-09T10:46:20.615Z
Learning: Within repository "opensourcepos/opensourcepos": When assessing whether to resolve a review conversation in this repository, keep it open while any aspect of the request remains incomplete.

You are interacting with an AI system.

@objecttothis

Copy link
Copy Markdown
Member Author

@coderabbitai the unit tests are all green. Please recheck all of the open review comments for completion. Mark any completed as resolved and comment on any that have remaining work in their individual threads.

@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -o pipefail
echo '=== Checkout and change summary ==='
git rev-parse HEAD
git log -1 --format='%H %s'
git diff --stat 630e87134 HEAD

echo '=== PR head and CI checks ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup --jq '{headRefOid,checks:[.statusCheckRollup[]? | {name,context,status,conclusion,state}]}'

echo '=== Open review threads ==='
gh api graphql --paginate -F owner=opensourcepos -F name=opensourcepos -F number=4725 -f query='
query($owner:String!, $name:String!, $number:Int!, $endCursor:String) {
 repository(owner:$owner,name:$name) { pullRequest(number:$number) {
  reviewThreads(first:100,after:$endCursor) {
   pageInfo { hasNextPage endCursor }
   nodes { id isResolved isOutdated path line originalLine
    comments(first:100) { pageInfo { hasNextPage } nodes { author { login } url body } }
   }
  }
 } }
}' | jq -r '.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false) |
  "THREAD \(.id) \(.path):\(.line // .originalLine) more=\(.comments.pageInfo.hasNextPage)\n" +
  ([.comments.nodes[] | "  \(.author.login) \(.url) " +
  (.body | gsub("<details>[\\s\\S]*?</details>"; " ") | gsub("<!--.*?-->"; " ") | gsub("\\s+"; " ") | .[0:2200])] | join("\n"))'

echo '=== Repository instruction files ==='
fd -H -t f -g AGENTS.md -E vendor -E node_modules -E .git . | while IFS= read -r f; do
  echo "--- $f"
  cat "$f"
done

echo '=== Relevant file outlines ==='
for name in Transaction.php BoundedQueueWorker.php ImportRowJob.php ItemCsvRowProcessor.php ImportBatch.php Jobs.php 20261110000000_AddJobsModule.php AddJobsModuleTest.php BoundedQueueWorkerTest.php ImportRowJobTest.php ImportBatchTest.php JobsControllerTest.php; do
  fd -H -t f -g "$name" -E vendor -E node_modules -E .git . | while IFS= read -r f; do
    echo "--- $f"
    ast-grep outline "$f" --items all 2>/dev/null || true
  done
done

Length of output: 71385


Script executed:

#!/bin/bash
set -o pipefail

echo '=== Transaction helper and import job ==='
cat -n app/Libraries/Transaction.php
cat -n app/Jobs/ImportRowJob.php
echo '=== Worker transaction and peer handling ==='
cat -n app/Jobs/BoundedQueueWorker.php | sed -n '105,360p'
echo '=== Item transaction and batch progress ==='
cat -n app/Jobs/Support/ItemCsvRowProcessor.php | sed -n '40,175p'
cat -n app/Models/ImportBatch.php | sed -n '25,205p'
echo '=== Controller transaction changes ==='
git diff --unified=7 630e87134 HEAD -- app/Controllers/Jobs.php
echo '=== Migration implementation ==='
cat -n app/Database/Migrations/20261110000000_AddJobsModule.php | sed -n '1,105p;155,340p'
echo '=== Migration regression tests ==='
cat -n tests/Database/Migrations/AddJobsModuleTest.php | sed -n '1,210p'
echo '=== Worker regression tests ==='
cat -n tests/Jobs/BoundedQueueWorkerTest.php | sed -n '375,540p'
echo '=== Import row regression tests ==='
cat -n tests/Jobs/ImportRowJobTest.php | sed -n '25,160p'
echo '=== Commit failure fixture ==='
for f in tests/Support/FailingCommitConnection.php tests/Support/FailingCommitBuilder.php tests/Support/FailingCommitResult.php tests/Support/Jobs/BatchProgressTestJob.php; do
  echo "--- $f"
  ast-grep outline "$f" --items all
  cat -n "$f"
done
echo '=== Focused controller and batch regression tests ==='
rg -n -A75 -B4 'function (testPostPauseBatch_RollsBackAndReportsFailureWhenCommitFails|testPostProcessJob_FailedJobReplayRollsBackWhenCommitFails|testIncrement_RollsBackAndRecoversWhenCommitFails)\(' tests/Controllers/JobsControllerTest.php tests/Models/ImportBatchTest.php
echo '=== Framework transaction implementation ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/BaseConnection.php | rg -n -A65 -B5 'function transComplete\(|function transBegin\(|function transCommit\(|function transRollback\(|function resetTransStatus\('

Length of output: 86200


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Different-class peer fixtures and job policy ==='
for f in tests/Support/Jobs/BatchableTestJob.php tests/Support/Jobs/SucceedingTestJob.php app/Jobs/BaseOsposJob.php; do
  echo "--- $f"
  ast-grep outline "$f" --items all
  cat -n "$f"
done
echo '=== Queue handler and BaseJob at the locked revision ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/queue/87f736a69a0d64bce0c40bcb1a3f966250f70f03/src/BaseJob.php | rg -n -A55 -B5 'getTries|getRetryAfter|tries|retryAfter' || true
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/queue/87f736a69a0d64bce0c40bcb1a3f966250f70f03/src/Handlers/DatabaseHandler.php | rg -n -A45 -B5 'function (later|pop)\('

echo '=== Full migration regression setup and applicable test database policy ==='
cat -n tests/Database/Migrations/AddJobsModuleTest.php | sed -n '8,110p'
rg -n -A18 -B3 'Only app-namespace migrations may ever touch the test database|Always set.*namespace' AGENTS.md

echo '=== Failed-job failure coverage ==='
rg -n -A65 -B5 'testRun_(ReleasesJobWhenBatchFailureCannotBeRecorded|RollsBackAndReleasesJobWhenFailedMoveCommitFails|HandlesDifferentClassJobWhenReleasingItFails)' tests/Jobs/BoundedQueueWorkerTest.php
echo '=== Item commit failure unit test ==='
ast-grep outline tests/Jobs/Support/ItemCsvRowProcessorTest.php --items all
cat -n tests/Jobs/Support/ItemCsvRowProcessorTest.php | sed -n '35,190p'

echo '=== Migration runner batch and namespace behavior ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/MigrationRunner.php | rg -n -A100 -B6 'function (latest|regress|findMigrations)\('

Length of output: 33142


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Migration runner batch history timestamps ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/MigrationRunner.php | rg -n -A45 -B5 'function (addHistory|getLastBatch|getBatchHistory)\('
echo '=== Migration batch detection ==='
cat -n app/Database/Migrations/20261110000000_AddJobsModule.php | sed -n '162,212p'
echo '=== Batch-failure and payload regression coverage ==='
rg -n -i -C4 'commit.fail|failed.*payload|payload.*failed|batch.*failed|failed.*batch|progress.*fail' tests/Jobs/BoundedQueueWorkerTest.php tests/Jobs/ImportRowJobTest.php tests/Controllers/CustomersCsvImportTest.php tests/Controllers/ItemsControllerTest.php tests/Controllers/JobsControllerTest.php | head -350
echo '=== Relevant transaction test names ==='
ast-grep outline tests/Jobs/BoundedQueueWorkerTest.php --items all --match 'Commit|Failure|Different|Peer'
ast-grep outline tests/Controllers/JobsControllerTest.php --items all --match 'Replay|PauseBatch|Commit'
echo '=== Current PR head and test check summary ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup --jq '{headRefOid,tests:[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests")) | {name,status,conclusion}]}'

Length of output: 23971


Script executed:

#!/bin/bash
set -u
set -o pipefail
repo=opensourcepos/opensourcepos
expected=69c4171e1ac109b2dce26b234fdffbc4118db39d

info=$(gh pr view 4725 -R "$repo" --json headRefOid,statusCheckRollup) || { echo 'PRECHECK_FAILED: cannot read PR checks'; exit 0; }
if [ "$(printf '%s' "$info" | jq -r '.headRefOid')" != "$expected" ]; then
  echo 'PRECHECK_FAILED: PR head changed'
  exit 0
fi
if ! printf '%s' "$info" | jq -e '[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests"))] | length == 16 and all(.[]; .status == "COMPLETED" and .conclusion == "SUCCESS")' >/dev/null; then
  echo 'PRECHECK_FAILED: the 16 test checks are missing, pending, or unsuccessful'
  exit 0
fi
echo 'PRECHECK_OK: matching head and 16 successful PHPUnit checks'

eligible() {
  local id="$1" number="$2" last="$3" head data
  head=$(gh pr view 4725 -R "$repo" --json headRefOid --jq '.headRefOid' 2>/dev/null) || { echo "SKIPPED $id: head lookup failed"; return 1; }
  if [ "$head" != "$expected" ]; then echo "SKIPPED $id: head changed to $head"; return 1; fi
  data=$(gh api graphql -F id="$id" -f query='
query($id:ID!) {
 node(id:$id) {
  ... on PullRequestReviewThread {
   id isResolved
   first: comments(first:1) { nodes { author { login } url } }
   last: comments(last:1) { nodes { url } }
  }
 }
}') || { echo "SKIPPED $id: thread lookup failed"; return 1; }
  if ! printf '%s' "$data" | jq -e \
    --arg first "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r$number" \
    --arg last "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r$last" \
    '.data.node.isResolved == false and .data.node.first.nodes[0].author.login == "coderabbitai" and .data.node.first.nodes[0].url == $first and .data.node.last.nodes[0].url == $last' >/dev/null; then
    echo "SKIPPED $id: thread state, ownership, or latest comment changed"
    return 1
  fi
}

reply() {
  local id="$1" number="$2" last="$3" label="$4" body="$5" result
  if ! eligible "$id" "$number" "$last"; then return; fi
  result=$(gh api -X POST "repos/$repo/pulls/4725/comments/$number/replies" -f body="$body" 2>&1) || {
    echo "REPLY_FAILED $label: $result"
    return
  }
  if printf '%s' "$result" | jq -e '.html_url != null' >/dev/null 2>&1; then
    echo "REPLIED $label $(printf '%s' "$result" | jq -r .html_url)"
  else
    echo "REPLY_FAILED $label: $result"
  fi
}

resolve() {
  local id="$1" number="$2" last="$3" label="$4" result
  if ! eligible "$id" "$number" "$last"; then return; fi
  result=$(gh api graphql -F threadId="$id" -f query='
mutation($threadId:ID!) {
 resolveReviewThread(input:{threadId:$threadId}) { thread { id isResolved } }
}' 2>&1) || {
    echo "RESOLUTION_FAILED $label: $result"
    return
  }
  if printf '%s' "$result" | jq -e '.data.resolveReviewThread.thread.isResolved == true' >/dev/null 2>&1; then
    echo "RESOLVED $label https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r$number"
  else
    echo "RESOLUTION_FAILED $label: $result"
  fi
}

echo '=== Replies on incomplete findings ==='
reply PRRT_kwDOAOCvWs63DAqh 4562173520 4612436951 'Migration rollback' \
'The earlier-vendor-batch and re-migration tests now cover the requested cases. Batch assignment still has a gap at `app/Database/Migrations/20261110000000_AddJobsModule.php` Lines 170–175. If `AddJobsModule` is the only pending migration and an earlier batch has a history timestamp equal to the current `REQUEST_TIME`, the heuristic assigns the synthetic vendor rows to that earlier batch. CI4 assigned `AddJobsModule` to the next batch before calling `up()`. A one-batch rollback then leaves the synthetic history and queue tables in the earlier batch, even though that batch did not create them. Please make the batch assignment independent of timestamp collisions and add a regression for this case.

The `--all` test also runs vendor migrations on the `tests` database group. `AGENTS.md` says only App-namespace migrations may touch that database. Please use a separate isolated database for this coverage, or establish an explicit repository exception.'

reply PRRT_kwDOAOCvWs63DAqr 4562173537 4612438027 'Different-class peer recovery' \
'The different-class candidate is now tracked. If its first `later()` call fails, however, the catch block sends it through `failWork()` with the original job’s retry policy. The regression test uses two jobs with the default one-try policy and confirms that both are moved to the failed table, although neither ran. A transient failure to release an unrelated candidate should not consume its attempt or fail it permanently. Please recover the candidate separately, and test that a later successful release leaves it available for its own handler after both a false return and an exception.'

reply PRRT_kwDOAOCvWs63DAqv 4562173541 4612438550 'Import row failure accounting' \
'The failed-row move and batch increment now share a transaction, and the helper rolls back a failed outer commit. The requested batch-specific recovery remains unverified: `testRun_RollsBackAndReleasesJobWhenFailedMoveCommitFails()` queues a job without a `batch_id` and does not check its payload or batch failure count. Please add a test with a real import batch and the same connection for the move and increment. Assert that the failed commit preserves the pending payload and leaves the count unchanged, then verify that a successful retry records the failure exactly once.'

echo '=== Resolve verified findings ==='
resolve PRRT_kwDOAOCvWs63DAqp 4562173534 4612437470 'Failed-job persistence'
resolve PRRT_kwDOAOCvWs63DAq5 4562173559 4612439170 'Item row transaction'
resolve PRRT_kwDOAOCvWs63DAq7 4562173564 4612439710 'Replay accounting'
resolve PRRT_kwDOAOCvWs63DArC 4562173571 4612440288 'Progress transactions'
resolve PRRT_kwDOAOCvWs63DivP 4562394087 4612440896 'Batch pause and resume'
echo '=== Action pass completed ==='

Length of output: 7080


@objecttothis I rechecked the eight threads at 69c4171e1. All 16 PHPUnit matrix jobs passed.

I resolved five threads: failed-job persistence, item-row transactions, replay accounting, progress transactions, and batch pause/resume.

I replied to three threads and did not resolve them:

  • Migration rollback: batch assignment can use an earlier batch after a timestamp collision. The --all test also needs isolation from the shared test database.
  • Peer recovery: a release failure can mark an unrelated job as failed before it runs.
  • Import failure accounting: batch-specific commit-failure recovery still needs a regression test.

I followed the repository guidance to leave incomplete findings unresolved. I recommend addressing the remaining findings before merging.


Learnings used

Learnt from: CR
Repo: opensourcepos/opensourcepos PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-11-16T14:24:28.736Z
Learning: Applies to **/*.php : Source excerpt:
# Agent Instructions

## Conventions

### Database Queries, Transactions & Migrations

- **Balanced transactions**: Never mix `$this->db->transStart()` / `$this->db->transComplete()` with manual `$this->db->transRollback()` or early `return` statements before `transComplete()`. Returning before `transComplete()` leaves `transDepth` incremented on the shared DB connection and corrupts subsequent transactions in the request.
Learnt from: objecttothis
URL: https://github.com/opensourcepos/opensourcepos/pull/4725

Timestamp: 2026-11-18T08:41:47.545Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Database/Migrations/20261110000000_AddJobsModule.php"]: For the jobs feature, the intended migration path uses core App migrations rather than requiring CodeIgniter Queue vendor migrations. In app/Database/Migrations/20261110000000_AddJobsModule.php, migrate --all can already have run the vendor queue migrations before AddJobsModule::up() records their history. Record only missing vendor migration rows: duplicate history rows make rollback run vendor down() methods twice.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:25:09.048Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, when verifying a review fix and relevant tests are still running, wait for them to finish before commenting. If the tests fail, do not resolve the finding. If they pass and the code fixes the finding, resolve it, subject to applicable thread-resolution restrictions.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-09T10:46:20.615Z
Learning: Within repository "opensourcepos/opensourcepos": When assessing whether to resolve a review conversation in this repository, keep it open while any aspect of the request remains incomplete.

You are interacting with an AI system.

… vendor batch assignment

- worker: a job of a different class that cannot be released while
  collecting peers is retried separately and never failed or charged an
  attempt
- AddJobsModule: record vendor queue history in the newest existing batch
  instead of guessing from timestamps; down() already only detaches what
  this migration added, so either batch is consistent
- tests: drop the --all migration test that ran vendor migrations on the
  shared test database, make the earlier-batch test independent of
  timestamps, cover release failure by return value and exception, and
  cover failed-move commit recovery with a real import batch

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@objecttothis

Copy link
Copy Markdown
Member Author

@coderabbitai I pushed 2d4201a for the three threads you left open at 69c4171. CI has finished and all 16 PHPUnit jobs passed. Please re-check, resolve every thread you can verify, and comment on the thread of any problem that remains.

  • AddJobsModule batch assignment: the timestamp heuristic is gone. The vendor queue history rows now go into the newest existing batch, which is either this migration's own batch or an earlier one. down() only detaches what this migration added to the queue tables, so a rollback is consistent either way. The earlier-batch test no longer depends on timestamps, so it covers the collision case. I removed the --all test that ran vendor migrations on the shared test database. The earlier-batch test exercises the same up() path with the vendor rows already recorded, and it asserts there are no duplicates.
  • Peer recovery: a job of a different class that cannot be released while collecting peers is retried separately. It is never failed or charged an attempt. Tests cover a false return and an exception on the first release. In both cases the other job ends up pending with zero attempts and nothing is moved to the failed table.
  • Import failure accounting: a new worker test uses a real import batch and the same failing-commit connection for the move and the batch increment. After the failed commit the pending payload and the batch failure count are unchanged. A successful retry then records the failure exactly once.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -o pipefail
echo '=== Commit and diff summary ==='
git rev-parse HEAD
git show --no-patch --format='%H%n%P%n%s' 2d4201a6f
git diff --stat 69c4171e1 2d4201a6f
echo '=== PR head and checks ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup --jq '{headRefOid,checks:[.statusCheckRollup[]? | {name,context,status,conclusion,state}]}'
echo '=== Unresolved review threads ==='
gh api graphql --paginate -F owner=opensourcepos -F name=opensourcepos -F number=4725 -f query='
query($owner:String!, $name:String!, $number:Int!, $endCursor:String) {
 repository(owner:$owner,name:$name) { pullRequest(number:$number) {
  reviewThreads(first:100,after:$endCursor) {
   pageInfo { hasNextPage endCursor }
   nodes { id isResolved isOutdated path line originalLine
    comments(first:100) { pageInfo { hasNextPage } nodes { author { login } url body } }
   }
  }
 } }
}' | jq -r '.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false) |
  "THREAD \(.id) \(.path):\(.line // .originalLine) more=\(.comments.pageInfo.hasNextPage)\n" +
  ([.comments.nodes[] | "  \(.author.login) \(.url) " +
  (.body | gsub("<details>[\\s\\S]*?</details>"; " ") | gsub("<!--.*?-->"; " ") | gsub("\\s+"; " ") | .[0:1800])] | join("\n"))'
echo '=== Repository instruction files ==='
fd -H -t f -g AGENTS.md -E vendor -E node_modules -E .git . | while IFS= read -r f; do echo "--- $f"; cat "$f"; done
echo '=== Changed files and outlines ==='
git diff --name-only 69c4171e1 2d4201a6f | while IFS= read -r f; do
  if [ -f "$f" ]; then echo "--- $f"; ast-grep outline "$f" --items all 2>/dev/null || true; fi
done
echo '=== Exact change ==='
git diff --unified=5 69c4171e1 2d4201a6f -- app/Database/Migrations/20261110000000_AddJobsModule.php app/Jobs/BoundedQueueWorker.php tests/Database/Migrations/AddJobsModuleTest.php tests/Jobs/BoundedQueueWorkerTest.php

Length of output: 62111


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Migration implementation ==='
cat -n app/Database/Migrations/20261110000000_AddJobsModule.php | sed -n '1,145p;155,320p'
echo '=== Migration tests ==='
cat -n tests/Database/Migrations/AddJobsModuleTest.php | sed -n '1,210p'
echo '=== Worker handling and tests ==='
cat -n app/Jobs/BoundedQueueWorker.php | sed -n '110,370p'
cat -n tests/Jobs/BoundedQueueWorkerTest.php | sed -n '395,580p'
echo '=== Batch service and test connection ==='
ast-grep outline app/Libraries/ImportBatchService.php --items all
cat -n app/Libraries/ImportBatchService.php | sed -n '1,150p'
ast-grep outline tests/Support/FailingCommitConnection.php --items all
cat -n tests/Support/FailingCommitConnection.php | sed -n '1,180p'
echo '=== Locked migration runner rollback and history ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/MigrationRunner.php | rg -n -A100 -B8 'function (regress|latest|getBatchHistory|addHistory)\('
echo '=== Queue handler release ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/queue/87f736a69a0d64bce0c40bcb1a3f966250f70f03/src/Handlers/DatabaseHandler.php | rg -n -A60 -B6 'function (later|pop)\('

Length of output: 62267


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Reserved-job management and recovery references ==='
rg -n -C 4 'reserved|RESERVED|status.*1|releaseHeld|tryRelease|later\(' app/Controllers/Jobs.php app/Jobs/BoundedQueueWorker.php app/Models/JobQueueManage.php app/Helpers/tabular_helper.php tests/Controllers/JobsControllerTest.php tests/Jobs/BoundedQueueWorkerTest.php | head -300
echo '=== Queue job UI actions ==='
ast-grep outline app/Helpers/tabular_helper.php --items all --match 'get_job_data_row'
rg -n -A110 -B4 'function\s+get_job_data_row\s*\(' app/Helpers/tabular_helper.php
echo '=== Manual job processing entry point ==='
ast-grep outline app/Controllers/Jobs.php --items all --match 'postProcessJob|postResumeJob|postPauseJob'
rg -n -A85 -B5 'function\s+(postProcessJob|postResumeJob|postPauseJob)\s*\(' app/Controllers/Jobs.php
echo '=== Prior and current changes for migration regression ==='
git diff --unified=8 69c4171e1 2d4201a6f -- tests/Database/Migrations/AddJobsModuleTest.php app/Database/Migrations/20261110000000_AddJobsModule.php

Length of output: 43851


Script executed:

#!/bin/bash
set -u
set -o pipefail
repo=opensourcepos/opensourcepos
expected=2d4201a6fa66fb638c4c650b8620e1a7a6cd64f0

info=$(gh pr view 4725 -R "$repo" --json headRefOid,statusCheckRollup) || { echo 'PRECHECK_FAILED: could not read PR checks'; exit 0; }
if [ "$(printf '%s' "$info" | jq -r '.headRefOid')" != "$expected" ]; then
  echo 'PRECHECK_FAILED: PR head changed'
  exit 0
fi
if ! printf '%s' "$info" | jq -e '[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests"))] | length == 16 and all(.[]; .status == "COMPLETED" and .conclusion == "SUCCESS")' >/dev/null; then
  echo 'PRECHECK_FAILED: test checks missing, pending, or unsuccessful'
  exit 0
fi
echo 'PRECHECK_OK: matching head and 16 successful PHPUnit checks'

eligible() {
  local id="$1" number="$2" last="$3" head data
  head=$(gh pr view 4725 -R "$repo" --json headRefOid --jq '.headRefOid' 2>/dev/null) || { echo "SKIPPED $id: head lookup failed"; return 1; }
  if [ "$head" != "$expected" ]; then echo "SKIPPED $id: head changed to $head"; return 1; fi
  data=$(gh api graphql -F id="$id" -f query='
query($id:ID!) {
 node(id:$id) {
  ... on PullRequestReviewThread {
   id isResolved
   first: comments(first:1) { nodes { author { login } url } }
   last: comments(last:1) { nodes { url } }
  }
 }
}') || { echo "SKIPPED $id: thread lookup failed"; return 1; }
  if ! printf '%s' "$data" | jq -e \
    --arg first "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r$number" \
    --arg last "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r$last" \
    '.data.node.isResolved == false and .data.node.first.nodes[0].author.login == "coderabbitai" and .data.node.first.nodes[0].url == $first and .data.node.last.nodes[0].url == $last' >/dev/null; then
    echo "SKIPPED $id: thread state, ownership, or latest comment changed"
    return 1
  fi
}

reply() {
  local id="$1" number="$2" last="$3" label="$4" body="$5" result
  if ! eligible "$id" "$number" "$last"; then return; fi
  result=$(gh api -X POST "repos/$repo/pulls/4725/comments/$number/replies" -f body="$body" 2>&1) || {
    echo "REPLY_FAILED $label: $result"
    return
  }
  if printf '%s' "$result" | jq -e '.html_url != null' >/dev/null 2>&1; then
    echo "REPLIED $label $(printf '%s' "$result" | jq -r .html_url)"
  else
    echo "REPLY_FAILED $label: $result"
  fi
}

reply PRRT_kwDOAOCvWs63DAqh 4562173520 4615000984 'Migration rollback' \
'The timestamp heuristic is gone, and the earlier-batch test checks that existing vendor history is not duplicated. Removing the shared-database `--all` test also avoids the repository test-database restriction.

The requested actual `migrate --all` → rollback → re-migrate cycle remains unverified. The earlier-batch test uses vendor history created by the App migration; it does not run the vendor `up()` and `down()` methods in that cycle. Please run or add this cycle against a separate isolated database and check the queue tables and history after each step. This is a verification gap, not a confirmed defect.'

reply PRRT_kwDOAOCvWs63DAqr 4562173537 4615001642 'Different-class peer recovery' \
'The new tests verify recovery when the first release fails and the next release succeeds. If both release attempts fail, `releaseHeld()` only logs the error and leaves the candidate reserved. The worker cannot pop it again, and the jobs UI rejects processing reserved jobs. A temporary database failure that lasts through both attempts can therefore strand an unrelated job after the database recovers.

Please provide a safe recovery path for this case without charging an attempt or taking a job that is still running. Add a test where both releases fail and the job can be recovered after the failure clears.'

if eligible PRRT_kwDOAOCvWs63DAqv 4562173541 4615002198; then
  result=$(gh api graphql -F threadId=PRRT_kwDOAOCvWs63DAqv -f query='
mutation($threadId:ID!) {
 resolveReviewThread(input:{threadId:$threadId}) { thread { id isResolved } }
}' 2>&1) || result="API_ERROR: $result"
  if printf '%s' "$result" | jq -e '.data.resolveReviewThread.thread.isResolved == true' >/dev/null 2>&1; then
    echo 'RESOLVED Import failure accounting https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r4562173541'
  else
    echo "RESOLUTION_FAILED Import failure accounting: $result"
  fi
fi

Length of output: 4886


@objecttothis I rechecked 2d4201a6f. All 16 PHPUnit jobs passed.

I resolved the import failure accounting thread.

I replied to two threads and did not resolve them, following the repository guidance for incomplete findings:

  • Migration rollback: the --all migration, rollback, and re-migration cycle still needs verification in an isolated database.
  • Peer recovery: if both release attempts fail, the unrelated job remains reserved.

I recommend completing those checks and fixing peer recovery before merging.


Learnings used

Learnt from: CR
Repo: opensourcepos/opensourcepos PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-11-16T14:24:28.736Z
Learning: Applies to **/*.php : Source excerpt:
# Agent Instructions

## Conventions

### Database Queries, Transactions & Migrations

- **Balanced transactions**: Never mix `$this->db->transStart()` / `$this->db->transComplete()` with manual `$this->db->transRollback()` or early `return` statements before `transComplete()`. Returning before `transComplete()` leaves `transDepth` incremented on the shared DB connection and corrupts subsequent transactions in the request.
Learnt from: objecttothis
URL: https://github.com/opensourcepos/opensourcepos/pull/4725

Timestamp: 2026-11-18T08:41:47.545Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Database/Migrations/20261110000000_AddJobsModule.php"]: For the jobs feature, the intended migration path uses core App migrations rather than requiring CodeIgniter Queue vendor migrations. In app/Database/Migrations/20261110000000_AddJobsModule.php, migrate --all can already have run the vendor queue migrations before AddJobsModule::up() records their history. Record only missing vendor migration rows: duplicate history rows make rollback run vendor down() methods twice.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:40:46.694Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Database/Migrations/20261110000000_AddJobsModule.php"]: For the jobs feature in opensourcepos/opensourcepos, the intended migration path uses core App migrations rather than codeigniter4/queue vendor migrations. When reviewing app/Database/Migrations/20261110000000_AddJobsModule.php, evaluate the application migration's queue schema instead of assuming that vendor migrations are a required production upgrade path.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos PR: 4725
File: app/Database/Migrations/20261110000000_AddJobsModule.php:11-11
Timestamp: 2026-11-17T08:23:17.297Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, limit migrations to one per feature while the feature is unreleased; jobs are one feature. For PR #4725, Phase 1 was not merged into master or run on production databases, so do not require an incremental migration solely to preserve a Phase 1 production upgrade path.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-09T10:46:20.615Z
Learning: Within repository "opensourcepos/opensourcepos": When assessing whether to resolve a review conversation in this repository, keep it open while any aspect of the request remains incomplete.

You are interacting with an AI system.

… back

- worker: when releasing a different-class job popped during peer
  collection fails twice, remember its id in the cache and put it back to
  pending at the start of the next run; attempts are not charged and only
  rows that are still reserved are touched
- QueueJobModel: add releaseReservedByIds()
- tests: cover a job that stays stranded after both releases fail and is
  recovered and processed by the next run, without touching an unrelated
  reserved job

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@objecttothis

Copy link
Copy Markdown
Member Author

@coderabbitai I pushed 4187176 for the two threads you left open at 2d4201a. CI has finished and all 16 PHPUnit jobs passed. Please re-check, resolve every thread you can verify, and comment on the thread of any problem that remains.

Peer recovery. If both release attempts fail for a job of a different class that was popped during peer collection, its id is now remembered in the cache. The job is put back to pending at the start of the next worker run. Attempts are not charged, and only rows that are still reserved are touched. A new test covers a stranded job that is recovered and processed by the next run, and an unrelated reserved job stays reserved.

Migration --all cycle. php spark migrate in any form is not a supported case for this project. Migrations, and initialization of the database beyond merely creating the empty database, are handled in the web application:

  • app/Controllers/Login.php runs MY_Migration with setNamespace('App')->runLocked() on login, or through the migrate action.
  • docker-compose.yml only runs php spark env:provision to generate the encryption and throttle keys. It does not migrate.
  • CI only runs composer test, which migrates the App namespace on ospos_tests.

A migrate --all migrate → rollback → re-migrate cycle is therefore out of scope. The supported path is the App-namespace web migration, which the tests drive through the same MigrationRunner. The earlier-batch test covers the case where the vendor queue history was already recorded.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -o pipefail
echo '=== Checkout and requested commit ==='
git rev-parse HEAD
git show --no-patch --format='%H%n%P%n%s' 418717691
git diff --stat 2d4201a6f 418717691

echo '=== Current PR head and checks ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup \
  --jq '{headRefOid,checks:[.statusCheckRollup[]? | {name,context,status,conclusion,state}]}'

echo '=== Open review threads ==='
gh api graphql --paginate -F owner=opensourcepos -F name=opensourcepos -F number=4725 -f query='
query($owner:String!, $name:String!, $number:Int!, $endCursor:String) {
 repository(owner:$owner,name:$name) { pullRequest(number:$number) {
  reviewThreads(first:100,after:$endCursor) {
   pageInfo { hasNextPage endCursor }
   nodes { id isResolved path line originalLine
    comments(first:100) { pageInfo { hasNextPage } nodes { author { login } url body } }
   }
  }
 } }
}' | jq -r '.data.repository.pullRequest.reviewThreads.nodes[] | select(.isResolved == false) |
  "THREAD \(.id) \(.path):\(.line // .originalLine) more=\(.comments.pageInfo.hasNextPage)\n" +
  ([.comments.nodes[] | "  \(.author.login) \(.url) " +
  (.body | gsub("<details>[\\s\\S]*?</details>"; " ") | gsub("<!--.*?-->"; " ") | gsub("\\s+"; " ") | .[0:1800])] | join("\n"))'

echo '=== Repository instructions ==='
fd -H -t f -g AGENTS.md -E vendor -E node_modules -E .git . | while IFS= read -r f; do
  echo "--- $f"
  cat "$f"
done

echo '=== Relevant outlines ==='
for f in app/Jobs/BoundedQueueWorker.php tests/Jobs/BoundedQueueWorkerTest.php app/Database/Migrations/20261110000000_AddJobsModule.php tests/Database/Migrations/AddJobsModuleTest.php app/Controllers/Login.php; do
  if [ -f "$f" ]; then
    echo "--- $f"
    ast-grep outline "$f" --items all
  fi
done

echo '=== Exact changes ==='
git diff --unified=6 2d4201a6f 418717691 -- app/Jobs/BoundedQueueWorker.php tests/Jobs/BoundedQueueWorkerTest.php app/Database/Migrations/20261110000000_AddJobsModule.php tests/Database/Migrations/AddJobsModuleTest.php

echo '=== Migration entry points and test coverage ==='
rg -n -C 4 'MY_Migration|runLocked|setNamespace|function.*[Mm]igrat' app/Controllers/Login.php tests/Database/Migrations/AddJobsModuleTest.php
rg -n -i -C 3 'spark (migrate|env:provision)|composer test' docker-compose.yml .github docs README.md 2>/dev/null || true

echo '=== Cache configuration and recovery references ==='
fd -H -t f -g Cache.php -E vendor -E node_modules -E .git . | while IFS= read -r f; do
  echo "--- $f"
  ast-grep outline "$f" --items all 2>/dev/null || true
  rg -n -C 3 'handler|backupHandler|ttl|prefix|validHandlers|file' "$f" || true
done
rg -n -C 4 'releaseHeld|tryRelease|recover|cache\(|cache->|reserved' app/Jobs/BoundedQueueWorker.php tests/Jobs/BoundedQueueWorkerTest.php

Length of output: 76364


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Queue job model ==='
ast-grep outline app/Models/QueueJobModel.php --items all
cat -n app/Models/QueueJobModel.php | sed -n '1,160p'

echo '=== Worker recovery and peer collection ==='
cat -n app/Jobs/BoundedQueueWorker.php | sed -n '35,105p;225,415p'

echo '=== Worker execution entry points ==='
rg -n -C 5 'new BoundedQueueWorker\s*\(' app/Config/Tasks.php app/Filters/JobRunner.php app/Controllers/Jobs.php
cat -n app/Config/Tasks.php | sed -n '1,120p'
cat -n app/Filters/JobRunner.php | sed -n '1,180p'

echo '=== App migration and regression tests ==='
cat -n app/Database/Migrations/20261110000000_AddJobsModule.php | sed -n '1,90p;135,310p'
cat -n tests/Database/Migrations/AddJobsModuleTest.php | sed -n '1,170p'

echo '=== Migration library ==='
ast-grep outline app/Libraries/MY_Migration.php --items all
rg -n -A50 -B5 'function\s+(runLocked|migrateToCI4)\s*\(' app/Libraries/MY_Migration.php

echo '=== Additional review-resolution restrictions ==='
fd -H -t f -g AGENTS.md -E vendor -E node_modules -E .git . | while IFS= read -r f; do
  rg -n -i -C 2 '(resolv(e|ing|ed|ution).*(thread|conversation|comment))|((thread|conversation|comment).*(resolv(e|ing|ed|ution)|human))' "$f" || true
done

Length of output: 48392


Script executed:

#!/bin/bash
set -u
set -o pipefail
repo=opensourcepos/opensourcepos
expected=41871769140dac6e9f4cca89e8ea54406040b51c

info=$(gh pr view 4725 -R "$repo" --json headRefOid,statusCheckRollup) || { echo 'PRECHECK_FAILED: PR lookup failed'; exit 0; }
if [ "$(printf '%s' "$info" | jq -r '.headRefOid')" != "$expected" ]; then
  echo 'PRECHECK_FAILED: PR head changed'
  exit 0
fi
if ! printf '%s' "$info" | jq -e '[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests"))] | length == 16 and all(.[]; .status == "COMPLETED" and .conclusion == "SUCCESS")' >/dev/null; then
  echo 'PRECHECK_FAILED: the 16 PHPUnit checks are missing, pending, or unsuccessful'
  exit 0
fi
echo 'PRECHECK_OK: matching head and 16 successful PHPUnit checks'

eligible() {
  local id="$1" number="$2" last="$3" head data
  head=$(gh pr view 4725 -R "$repo" --json headRefOid --jq '.headRefOid' 2>/dev/null) || { echo "SKIPPED $id: head lookup failed"; return 1; }
  if [ "$head" != "$expected" ]; then echo "SKIPPED $id: head changed to $head"; return 1; fi
  data=$(gh api graphql -F id="$id" -f query='
query($id:ID!) {
 node(id:$id) {
  ... on PullRequestReviewThread {
   id isResolved
   first: comments(first:1) { nodes { author { login } url } }
   last: comments(last:1) { nodes { url } }
  }
 }
}') || { echo "SKIPPED $id: thread lookup failed"; return 1; }
  if ! printf '%s' "$data" | jq -e \
    --arg first "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r$number" \
    --arg last "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r$last" \
    '.data.node.isResolved == false and .data.node.first.nodes[0].author.login == "coderabbitai" and .data.node.first.nodes[0].url == $first and .data.node.last.nodes[0].url == $last' >/dev/null; then
    echo "SKIPPED $id: thread state, ownership, or latest comment changed"
    return 1
  fi
}

echo '=== Migration thread ==='
if eligible PRRT_kwDOAOCvWs63DAqh 4562173520 4615826321; then
  result=$(gh api graphql -F threadId=PRRT_kwDOAOCvWs63DAqh -f query='
mutation($threadId:ID!) {
 resolveReviewThread(input:{threadId:$threadId}) { thread { id isResolved } }
}' 2>&1) || result="API_ERROR: $result"
  if printf '%s' "$result" | jq -e '.data.resolveReviewThread.thread.isResolved == true' >/dev/null 2>&1; then
    echo 'RESOLVED migration https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r4562173520'
  else
    echo "RESOLUTION_FAILED migration: $result"
  fi
fi

echo '=== Peer recovery thread ==='
if eligible PRRT_kwDOAOCvWs63DAqr 4562173537 4615827047; then
  body='The new test verifies recovery on the next worker run. A concurrency problem remains in `recoverUnreleased()`: two workers can read the same cached ID. The first can release the job and reserve it for processing before the second calls `releaseReservedByIds()`. Because that method checks only `status = RESERVED`, the second worker can put the running job back to pending, allowing duplicate processing.

The shared cache list also uses unsynchronized read/merge/write and read/delete operations. Concurrent recovery or recording can discard another stranded ID. Please make recording and recovery atomic, preserve ownership of active reservations, and add tests for concurrent recovery and concurrent recording.'
  result=$(gh api -X POST "repos/$repo/pulls/4725/comments/4562173537/replies" -f body="$body" 2>&1) || result="API_ERROR: $result"
  if printf '%s' "$result" | jq -e '.html_url != null' >/dev/null 2>&1; then
    echo "REPLIED peer recovery $(printf '%s' "$result" | jq -r .html_url)"
  else
    echo "REPLY_FAILED peer recovery: $result"
  fi
fi

Length of output: 4093


@objecttothis I rechecked 418717691. All 16 PHPUnit jobs passed. The Docker image build was still running at my last check.

  • I resolved the migration thread. I withdraw the request for a migrate --all cycle because that path is unsupported. The App-namespace tests cover rollback and re-migration.
  • I replied to the peer-recovery thread and did not resolve it. Concurrent workers can return a running job to pending or lose a stranded job ID. I recommend fixing that race before merging.

I followed the repository guidance to leave incomplete findings unresolved.


Learnings added

Learnt from: objecttothis
URL: https://github.com/opensourcepos/opensourcepos/pull/4725

Timestamp: 2026-11-18T21:07:29.390Z
Learning: Within repository "opensourcepos/opensourcepos": OpenSourcePOS does not support `php spark migrate` in any form, including `--all`. Database initialization and migrations use the web path: `Login::index()` or `Login::migrate()` invokes `MY_Migration::setNamespace('App')->runLocked()`. Do not require a `migrate --all` rollback and re-migration cycle as a supported upgrade path; assess the App-namespace migration path instead.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


Learnings used

Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:40:46.694Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Database/Migrations/20261110000000_AddJobsModule.php"]: For the jobs feature in opensourcepos/opensourcepos, the intended migration path uses core App migrations rather than codeigniter4/queue vendor migrations. When reviewing app/Database/Migrations/20261110000000_AddJobsModule.php, evaluate the application migration's queue schema instead of assuming that vendor migrations are a required production upgrade path.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos PR: 4725
File: app/Database/Migrations/20261110000000_AddJobsModule.php:11-11
Timestamp: 2026-11-17T08:23:17.297Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, limit migrations to one per feature while the feature is unreleased; jobs are one feature. For PR #4725, Phase 1 was not merged into master or run on production databases, so do not require an incremental migration solely to preserve a Phase 1 production upgrade path.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-09T10:46:20.615Z
Learning: Within repository "opensourcepos/opensourcepos": When assessing whether to resolve a review conversation in this repository, keep it open while any aspect of the request remains incomplete.

You are interacting with an AI system.

- replace the shared cache list with UnreleasedJobRegistry, a file-backed
  list updated under an exclusive lock; claim() empties the list in the
  same locked step so no two workers receive the same id and ids recorded
  concurrently are not lost
- worker: claim stranded ids before releasing them and record them again
  if the database is still failing
- tests: run real parallel PHP processes against the registry to cover
  concurrent recording and concurrent claiming

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@objecttothis

Copy link
Copy Markdown
Member Author

@coderabbitai I pushed ce9d237 for the peer-recovery thread you left open at 4187176. CI has finished and all 16 PHPUnit jobs passed. Please re-check, resolve it if you can verify it, and comment on the thread if any problem remains.

  • The shared cache list is replaced by App\Jobs\UnreleasedJobRegistry, a file-backed list. Every read-modify-write holds an exclusive file lock, so ids recorded concurrently are not lost.
  • claim() empties the list in the same locked step. Two workers can therefore never receive the same stranded job id, and the second worker can no longer put a job the first one already released and started back to pending.
  • The worker claims the ids before releasing them. releaseReservedByIds() still only touches rows that are RESERVED. If the database is still failing, the claimed ids are recorded again for the next run.
  • UnreleasedJobRegistryTest runs 8 real parallel PHP processes to cover concurrent recording and concurrent claiming. Both concurrency tests fail when the lock is removed.
  • BoundedQueueWorkerTest still covers a stranded job being recovered and processed on the next run while an unrelated reserved job stays reserved.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -o pipefail
echo '=== revision and change summary ==='
git rev-parse HEAD
git show --no-patch --format='%H%n%P%n%s' ce9d237b4
git diff --stat 418717691 ce9d237b4
echo '=== PR head and CI ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup --jq '{headRefOid, tests:[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests")) | {name,status,conclusion}], otherPending:[.statusCheckRollup[]? | select(.status != "COMPLETED") | {name,status}]}'
echo '=== target thread ==='
gh api graphql -F id=PRRT_kwDOAOCvWs63DAqr -f query='query($id:ID!) { node(id:$id) { ... on PullRequestReviewThread { id isResolved path line originalLine comments(last:30) { pageInfo { hasPreviousPage } nodes { author { login } url body } } } } }' | jq '.data.node | {id,isResolved,path,line,originalLine,comments}'
echo '=== instructions ==='
fd -H -t f -g AGENTS.md -E vendor -E node_modules -E .git . | while IFS= read -r f; do echo "--- $f"; cat "$f"; done
echo '=== relevant outlines and contents ==='
for name in UnreleasedJobRegistry.php BoundedQueueWorker.php QueueJobModel.php UnreleasedJobRegistryTest.php BoundedQueueWorkerTest.php; do
  fd -H -t f -g "$name" -E vendor -E node_modules -E .git . | while IFS= read -r f; do
    echo "--- outline $f"
    ast-grep outline "$f" --items all
    case "$name" in
      UnreleasedJobRegistry.php|UnreleasedJobRegistryTest.php|QueueJobModel.php)
        echo "--- numbered $f"; cat -n "$f" ;;
      *)
        echo "--- recovery references $f"
        rg -n -C 14 'UnreleasedJobRegistry|recoverUnreleased|releaseHeld|tryRelease|releaseReservedByIds|[Rr]ecover|[Pp]eer' "$f" ;;
    esac
  done
done
echo '=== exact changes ==='
git diff --unified=5 418717691 ce9d237b4

Length of output: 76136


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Database configuration ==='
fd -H -t f -g Database.php -E vendor -E node_modules -E .git . | while IFS= read -r f; do
  echo "--- $f"
  ast-grep outline "$f" --items all
  rg -n -C 3 'DBDebug|defaultGroup|testing|mysqli|failover' "$f" || true
done
echo '=== Worker and test recovery windows ==='
ast-grep outline app/Jobs/BoundedQueueWorker.php --items all --match 'recoverUnreleased|releaseHeld'
cat -n app/Jobs/BoundedQueueWorker.php | sed -n '292,361p'
ast-grep outline tests/Jobs/BoundedQueueWorkerTest.php --items all --match 'ReleasesStranded'
cat -n tests/Jobs/BoundedQueueWorkerTest.php | sed -n '540,605p'
echo '=== CI4 4.7.4 update and query error contract ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/BaseBuilder.php | rg -n -A55 -B8 'function update\('
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/CodeIgniter4/v4.7.4/system/Database/BaseConnection.php | rg -n -A110 -B8 'function query\('
echo '=== Relevant CI checks and head refresh ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup --jq '{headRefOid,tests:[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests")) | {name,status,conclusion}]}'

Length of output: 18306


Script executed:

#!/bin/bash
set -euo pipefail
repo=opensourcepos/opensourcepos
expected=ce9d237b4d55f47abd496491890d0fa6d76e1df1
thread=PRRT_kwDOAOCvWs63DAqr
number=4562173537

info=$(gh pr view 4725 -R "$repo" --json headRefOid,statusCheckRollup) || { echo 'PRECHECK_FAILED: cannot read PR checks'; exit 0; }
if ! printf '%s' "$info" | jq -e --arg expected "$expected" '.headRefOid == $expected and ([.statusCheckRollup[]? | select((.name // "") | endswith(" Tests"))] | length == 16 and all(.[]; .status == "COMPLETED" and .conclusion == "SUCCESS"))' >/dev/null; then
  echo 'PRECHECK_FAILED: head changed or PHPUnit checks are missing, pending, or unsuccessful'
  exit 0
fi

data=$(gh api graphql -F id="$thread" -f query='query($id:ID!) { node(id:$id) { ... on PullRequestReviewThread { id isResolved first:comments(first:1) { nodes { author { login } url } } last:comments(last:1) { nodes { url } } } } }') || { echo 'PRECHECK_FAILED: cannot read thread'; exit 0; }
if ! printf '%s' "$data" | jq -e '.data.node.isResolved == false and .data.node.first.nodes[0].author.login == "coderabbitai" and .data.node.first.nodes[0].url == "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r4562173537" and .data.node.last.nodes[0].url == "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r4620868863"' >/dev/null; then
  echo 'PRECHECK_FAILED: thread state, ownership, or latest comment changed'
  exit 0
fi

body='The locked registry addresses the concurrent recording and claiming race. Recovery can still lose a stranded ID in two cases:

- `claim()` removes the ID before the database update. If the worker stops between those operations, the row remains reserved and no later worker can claim the ID.
- `releaseReservedByIds()` ignores the result of `update()`. In production, `DBDebug` is false, so CI4 can return `false` without throwing. `recoverUnreleased()` then does not re-record the claimed ID.

Please retain a recoverable, ownership-safe claim until the database update succeeds, and handle a false update result. Add tests for an interrupted claim and for a false database update, followed by successful recovery. A successful update affecting zero rows can mean the row is no longer reserved, so distinguish that from an update failure.'

result=$(gh api -X POST "repos/$repo/pulls/4725/comments/$number/replies" -f body="$body") || { echo 'REPLY_FAILED'; exit 0; }
if printf '%s' "$result" | jq -e '.html_url != null' >/dev/null; then
  echo "REPLIED $(printf '%s' "$result" | jq -r .html_url)"
else
  echo "REPLY_FAILED: $result"
fi

Length of output: 2797


@objecttothis I rechecked ce9d237b4. All 16 PHPUnit jobs passed. The locked registry addresses the concurrent recording and claiming race.

I replied on the peer-recovery thread and did not resolve it, following the repository guidance for incomplete findings. Recovery can still lose a stranded job ID if the worker stops after claiming it or if the database update returns false without throwing.

The Docker image build was still running at my last check.


Learnings used

Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:25:09.048Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, when verifying a review fix and relevant tests are still running, wait for them to finish before commenting. If the tests fail, do not resolve the finding. If they pass and the code fixes the finding, resolve it, subject to applicable thread-resolution restrictions.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-09T10:46:20.615Z
Learning: Within repository "opensourcepos/opensourcepos": When assessing whether to resolve a review conversation in this repository, keep it open while any aspect of the request remains incomplete.

You are interacting with an AI system.

- UnreleasedJobRegistry: claim() now leases ids to the claiming worker
  instead of deleting them; complete() drops the lease after a successful
  release, abandon() returns the ids to the list, and a lease that is never
  completed expires so the next worker takes the ids over
- QueueJobModel::releaseReservedByIds throws when update() returns false;
  zero affected rows stays a success because the row is no longer reserved
- worker: complete the lease only after the update succeeds, abandon it
  otherwise
- tests: cover an interrupted claim and lease expiry, complete and abandon,
  a false update result, and recovery on the next run after a failed
  release update

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@objecttothis

Copy link
Copy Markdown
Member Author

@coderabbitai I pushed b09cdab for the peer-recovery thread you left open at ce9d237. CI has finished and all 16 PHPUnit jobs passed. Please re-check, resolve the thread if you can verify it, and comment on the thread if any problem remains.

  • UnreleasedJobRegistry::claim() now leases the stranded ids to the claiming worker instead of deleting them. complete() drops the lease only after the database update succeeds, and abandon() returns the ids to the list if it fails. A lease that is never completed because the worker stopped expires after 300 seconds, and the next worker takes the ids over. An id is therefore never lost and never held by two live workers at once.
  • QueueJobModel::releaseReservedByIds() throws when update() returns false, which can happen in production because DBDebug is off. Zero affected rows stays a success, because it means the row is no longer reserved.
  • The worker completes the lease only after the update succeeds, and abandons it otherwise.
  • New tests cover an interrupted claim and lease expiry, complete() and abandon(), a false update result, and recovery on the next worker run after a failed release update. The 8-process concurrency tests now use the lease API.

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -o pipefail

echo '=== Checkout and requested commit ==='
git rev-parse HEAD
git show --no-patch --format='%H%n%P%n%s' b09cdabbc
git diff --stat ce9d237b4 b09cdabbc

echo '=== PR head and checks ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup \
  --jq '{headRefOid,tests:[.statusCheckRollup[]? | select((.name // "") | endswith(" Tests")) | {name,status,conclusion}],otherPending:[.statusCheckRollup[]? | select(.status != "COMPLETED") | {name,status}]}'

echo '=== Target review thread ==='
gh api graphql -F id=PRRT_kwDOAOCvWs63DAqr -f query='
query($id:ID!) {
  node(id:$id) {
    ... on PullRequestReviewThread {
      id isResolved path line originalLine
      comments(last:30) {
        pageInfo { hasPreviousPage }
        nodes { author { login } url body }
      }
    }
  }
}' | jq '.data.node'

echo '=== Repository instructions ==='
fd -H -t f -g AGENTS.md -E vendor -E node_modules -E .git . | while IFS= read -r f; do
  echo "--- $f"
  cat "$f"
done

echo '=== Relevant files ==='
for name in UnreleasedJobRegistry.php BoundedQueueWorker.php QueueJobModel.php UnreleasedJobRegistryTest.php BoundedQueueWorkerTest.php; do
  fd -H -t f -g "$name" -E vendor -E node_modules -E .git . | while IFS= read -r f; do
    echo "--- outline $f"
    ast-grep outline "$f" --items all
    case "$name" in
      UnreleasedJobRegistry.php|QueueJobModel.php|UnreleasedJobRegistryTest.php)
        echo "--- contents $f"
        cat -n "$f"
        ;;
      *)
        echo "--- recovery references $f"
        rg -n -C 12 'UnreleasedJobRegistry|recoverUnreleased|releaseHeld|releaseReservedByIds|[Ll]ease|[Rr]ecover|[Pp]eer' "$f"
        ;;
    esac
  done
done

echo '=== Exact change ==='
git diff --unified=5 ce9d237b4 b09cdabbc -- app/Jobs/BoundedQueueWorker.php app/Models/QueueJobModel.php
git diff --name-only ce9d237b4 b09cdabbc

Length of output: 84691


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Requester repository permission ==='
gh api repos/opensourcepos/opensourcepos/collaborators/objecttothis/permission \
  --jq '{user:.user.login,permission,role_name}' || echo 'PERMISSION_LOOKUP_FAILED'

Length of output: 485


Script executed:

#!/bin/bash
set -euo pipefail
repo=opensourcepos/opensourcepos
expected=b09cdabbc5053d416045c79a5f5571ea939d25f3
thread=PRRT_kwDOAOCvWs63DAqr
number=4562173537

info=$(gh pr view 4725 -R "$repo" --json headRefOid,statusCheckRollup) || {
  echo 'PRECHECK_FAILED: cannot read PR head and checks'
  exit 0
}
if ! printf '%s' "$info" | jq -e --arg expected "$expected" \
  '.headRefOid == $expected and ([.statusCheckRollup[]? | select((.name // "") | endswith(" Tests"))] | length == 16 and all(.[]; .status == "COMPLETED" and .conclusion == "SUCCESS"))' >/dev/null; then
  echo 'PRECHECK_FAILED: head changed or PHPUnit checks are missing, pending, or unsuccessful'
  exit 0
fi

data=$(gh api graphql -F id="$thread" -f query='
query($id:ID!) {
  node(id:$id) {
    ... on PullRequestReviewThread {
      id isResolved
      first:comments(first:1) { nodes { author { login } url } }
      last:comments(last:1) { nodes { url } }
    }
  }
}') || {
  echo 'PRECHECK_FAILED: cannot read thread'
  exit 0
}
if ! printf '%s' "$data" | jq -e \
  '.data.node.isResolved == false and .data.node.first.nodes[0].author.login == "coderabbitai" and .data.node.first.nodes[0].url == "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r4562173537" and .data.node.last.nodes[0].url == "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r4621322847"' >/dev/null; then
  echo 'PRECHECK_FAILED: thread state, ownership, or latest comment changed'
  exit 0
fi

body='The lease preserves an interrupted claim, and the model now handles a false update result. An ownership race remains between the database update and `complete()`.

If a worker releases a stranded job and stops before `complete()`, another worker can reserve that job for processing. After 300 seconds, a new worker can reclaim the expired lease. `releaseReservedByIds()` checks only the ID and `RESERVED` status, so it can return the running job to pending and allow duplicate processing. A live claimant that pauses past its lease expiry can also perform a stale release after another claimant takes over.

Please make recovery ownership-safe across lease expiry and the database update, using an atomic or fenced transition. Add a test that releases the job, interrupts the claimant before `complete()`, reserves the job for a new worker, and expires the lease. Verify that recovery does not release the new reservation. Also test a claimant that resumes after its lease expires.'

result=$(gh api -X POST "repos/$repo/pulls/4725/comments/$number/replies" -f body="$body") || {
  echo 'REPLY_FAILED'
  exit 0
}
if printf '%s' "$result" | jq -e '.html_url != null' >/dev/null; then
  printf 'REPLIED %s\n' "$(printf '%s' "$result" | jq -r .html_url)"
else
  echo 'REPLY_FAILED: response did not confirm the comment'
fi

Length of output: 3032


@objecttothis I rechecked b09cdabbc. All 16 PHPUnit jobs passed.

The lease preserves interrupted claims, and the model handles a false update result. An ownership race remains: after a release succeeds but before complete(), another worker can reserve the job. When the lease expires, recovery can return that running job to pending and allow duplicate processing.

I replied on the thread with the failure scenario and requested tests. I did not resolve it, following the repository guidance for incomplete findings. I recommend fixing the race before merging.

The Docker image build was still running at my last check.


Learnings used

Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:25:09.048Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, when verifying a review fix and relevant tests are still running, wait for them to finish before commenting. If the tests fail, do not resolve the finding. If they pass and the code fixes the finding, resolve it, subject to applicable thread-resolution restrictions.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-09T10:46:20.615Z
Learning: Within repository "opensourcepos/opensourcepos": When assessing whether to resolve a review conversation in this repository, keep it open while any aspect of the request remains incomplete.

You are interacting with an AI system.

objecttothis and others added 2 commits November 19, 2026 12:27
…nto feat-job-queue-phase-2a

# Conflicts:
#	docs/INSTALL.md

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
…served job

Record each stranded job with the available_at its row had when it was
stranded, and release it only while it is still reserved with that value.
A release moves available_at one second back, so a reservation taken by
another worker afterwards, or a claimant resuming after its lease expired,
no longer matches and cannot put a running job back to pending.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@objecttothis

Copy link
Copy Markdown
Member Author

@coderabbitai Please re-review the stranded-job recovery thread on BoundedQueueWorker.php (commit 5da05b8).

Recovery is now fenced. Each stranded job is recorded with the available_at its row had when it was stranded, and QueueJobModel::releaseStrandedJobs() releases a row only while it is still RESERVED with that exact value. A release moves available_at one second back (the job stays due), so a reservation taken by another worker afterwards, or a claimant resuming after its lease expired, no longer matches and releases zero rows.

New tests:

  • BoundedQueueWorkerTest: a claimant is interrupted before complete(), a new worker reserves the job, the lease expires, and recovery leaves the reservation alone.
  • QueueJobModelTest: a reservation taken after a release is not released again, and a stalled claimant resuming after its lease expired is ignored.
  • UnreleasedJobRegistryTest: fences survive record, claim, lease expiry and abandon.

@coderabbitai

coderabbitai Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -o pipefail
echo '=== revision ==='
git rev-parse HEAD
git show --no-patch --format='%H%n%P%n%s' 5da05b879
echo '=== PR head and checks ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup --jq '{headRefOid,checks:[.statusCheckRollup[]? | {name,context,status,conclusion,state}]}'
echo '=== target thread ==='
gh api graphql -F id=PRRT_kwDOAOCvWs63DAqr -f query='query($id:ID!) { node(id:$id) { ... on PullRequestReviewThread { id isResolved path line originalLine comments(last:12) { pageInfo { hasPreviousPage } nodes { author { login } url body } } } } }' | jq '.data.node'
echo '=== instruction files ==='
fd -H -t f -g AGENTS.md -E vendor -E node_modules -E .git . | while IFS= read -r f; do echo "--- $f"; cat "$f"; done
echo '=== changes since prior review ==='
git diff --stat b09cdabbc 5da05b879
git diff --unified=5 b09cdabbc 5da05b879 -- app/Jobs/BoundedQueueWorker.php app/Models/QueueJobModel.php app/Jobs/UnreleasedJobRegistry.php
echo '=== relevant outlines ==='
for name in BoundedQueueWorker.php QueueJobModel.php UnreleasedJobRegistry.php BoundedQueueWorkerTest.php QueueJobModelTest.php UnreleasedJobRegistryTest.php; do
  fd -H -t f -g "$name" -E vendor -E node_modules -E .git . | while IFS= read -r f; do echo "--- $f"; ast-grep outline "$f" --items all; done
done
echo '=== queue dependency version ==='
rg -n -A12 -B3 '"name": "codeigniter4/queue"' composer.lock

Length of output: 63823


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Worker recovery and peer handling ==='
cat -n app/Jobs/BoundedQueueWorker.php | sed -n '35,90p;115,225p;270,470p'
echo '=== Registry ==='
cat -n app/Jobs/UnreleasedJobRegistry.php | sed -n '1,180p'
echo '=== Queue model ==='
cat -n app/Models/QueueJobModel.php | sed -n '1,105p'
echo '=== Queue model tests ==='
cat -n tests/Models/QueueJobModelTest.php | sed -n '1,230p'
echo '=== Worker recovery tests ==='
cat -n tests/Jobs/BoundedQueueWorkerTest.php | sed -n '520,760p'
echo '=== Registry tests ==='
cat -n tests/Jobs/UnreleasedJobRegistryTest.php | sed -n '1,230p'
echo '=== Queue schema and relevant updates ==='
rg -n -C 4 'available_at|reserved_at|releaseStrandedJobs|tryRelease' app/Database/Migrations/20261110000000_AddJobsModule.php app/Controllers/Jobs.php app/Jobs/BoundedQueueWorker.php app/Models/QueueJobModel.php
echo '=== Locked queue handler ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/queue/87f736a69a0d64bce0c40bcb1a3f966250f70f03/src/Handlers/DatabaseHandler.php | rg -n -A80 -B8 'function (later|pop|push|done)\('
echo '=== Locked queue entity ==='
curl -fsSL --max-time 20 https://raw.githubusercontent.com/codeigniter4/queue/87f736a69a0d64bce0c40bcb1a3f966250f70f03/src/Entities/QueueJob.php | sed -n '1,180p'

Length of output: 62910


@objecttothis I rechecked 5da05b879. All PHPUnit checks passed. The Docker image build was still running at the last check.

The ownership race can still occur. The fence in QueueJobModel::releaseStrandedJobs() uses available_at, but the queue handler can reuse that value:

  1. A recovery claimant releases a job with fence T, then stops before complete().
  2. In the same second T, peer collection pops the job and calls later(0). That call sets available_at back to T.
  3. Another worker reserves the job. When the old lease expires, recovery can match T and release that new reservation.

The new tests cover re-reservation after the fenced release, but not a later(0) cycle that restores the old value. Please use a reservation-specific fence that cannot be reused, and add a test for this sequence.

I did not resolve the thread. I followed the repository guidance to leave incomplete findings unresolved. I recommend fixing the race before merging.


Learnings used

Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-09T10:46:20.615Z
Learning: Within repository "opensourcepos/opensourcepos": When assessing whether to resolve a review conversation in this repository, keep it open while any aspect of the request remains incomplete.

You are interacting with an AI system.

The available_at fence could be recreated when the queue handler's later(0)
set it back to the stranded value within the same second, letting recovery
release a reservation another worker had since taken.

Add release_epoch to queue_jobs and queue_jobs_paused. Only a stranded-job
release increments it, and the release is conditional on the epoch recorded
when the job was stranded, so a stale claim can never match a later
reservation. Releases no longer touch available_at.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
@objecttothis

Copy link
Copy Markdown
Member Author

@coderabbitai Thanks, you're right that the available_at fence could be recreated by later(0). Fixed in d8f79a3; please re-review and reply in the open review thread on app/Jobs/BoundedQueueWorker.php (not as a separate PR comment) so the thread shows the outcome.

The fence is now a reservation-specific release_epoch column on queue_jobs and queue_jobs_paused. Only a stranded-job release changes it (release_epoch + 1); pop(), later(), retries and pause/resume never write it, and it never decreases, so normal queue activity cannot recreate a recorded fence. QueueJobModel::releaseStrandedJobs() releases a row only while it is RESERVED with the epoch recorded when it was stranded, and no longer touches available_at.

Tests:

  • BoundedQueueWorkerTest::testRun_DoesNotReleaseReservationWhenLaterRestoresTheStrandedAvailableAt covers your sequence: release, pop, later(0), available_at restored to the stranded value, pop again, then recovery with the expired lease. It fails without the epoch guard and passes with it.
  • QueueJobModelTest covers a reservation taken after a release and a claimant resuming after its lease expired.
  • JobsControllerTest::testPauseResume_KeepsReleaseEpoch covers the epoch surviving a pause/resume round trip.

@coderabbitai

coderabbitai Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

Analysis chain

Script executed:

#!/bin/bash
set -o pipefail
echo '=== Revision ==='
git rev-parse HEAD
git show --no-patch --format='%H%n%P%n%s' d8f79a307
echo '=== PR checks ==='
gh pr view 4725 -R opensourcepos/opensourcepos --json headRefOid,statusCheckRollup --jq '{headRefOid,checks:[.statusCheckRollup[]? | {name,context,status,conclusion,state}]}'
echo '=== Target review thread ==='
gh api graphql -F id=PRRT_kwDOAOCvWs63DAqr -f query='query($id:ID!) { node(id:$id) { ... on PullRequestReviewThread { id isResolved path line originalLine comments(last:30) { pageInfo { hasPreviousPage } nodes { author { login } url body } } } } }' | jq '.data.node'
echo '=== Repository instruction files ==='
fd -H -t f -g AGENTS.md -E vendor -E node_modules -E .git . | while IFS= read -r f; do echo "--- $f"; cat "$f"; done
echo '=== Changes ==='
git diff --stat 5da05b879 d8f79a307
git diff --unified=5 5da05b879 d8f79a307
echo '=== Source outlines ==='
for name in BoundedQueueWorker.php QueueJobModel.php QueueJobPausedModel.php UnreleasedJobRegistry.php 20261110000000_AddJobsModule.php Jobs.php BoundedQueueWorkerTest.php QueueJobModelTest.php UnreleasedJobRegistryTest.php JobsControllerTest.php; do
  fd -H -t f -g "$name" -E vendor -E node_modules -E .git . | while IFS= read -r f; do
    echo "--- $f"
    ast-grep outline "$f" --items all
  done
done
echo '=== Epoch references ==='
rg -n -C 4 'release_epoch|releaseStrandedJobs|recoverUnreleased|recordUnreleased' app tests
echo '=== Queue dependency ==='
rg -n -A12 -B3 '"name": "codeigniter4/queue"' composer.lock

Length of output: 98090


Script executed:

#!/bin/bash
set -o pipefail
echo '=== Worker reservation and recovery ==='
cat -n app/Jobs/BoundedQueueWorker.php | sed -n '115,160p;225,445p'
echo '=== Queue models ==='
cat -n app/Models/QueueJobModel.php | sed -n '1,125p'
cat -n app/Models/QueueJobPausedModel.php | sed -n '1,145p'
echo '=== Pause and resume ==='
rg -n -A95 -B4 'function\s+(moveToPaused|moveToPending)\s*\(' app/Controllers/Jobs.php
echo '=== Epoch migration ==='
cat -n app/Database/Migrations/20261110000000_AddJobsModule.php | sed -n '42,105p;115,145p;245,335p'
echo '=== Registry ==='
cat -n app/Jobs/UnreleasedJobRegistry.php | sed -n '1,210p'
echo '=== Recovery tests ==='
cat -n tests/Jobs/BoundedQueueWorkerTest.php | sed -n '490,725p'
cat -n tests/Models/QueueJobModelTest.php | sed -n '20,120p'
echo '=== Locked queue handler and entity ==='
for path in src/Handlers/DatabaseHandler.php src/Models/QueueJobModel.php src/Entities/QueueJob.php; do
  echo "--- $path"
  curl -fsSL --max-time 20 "https://raw.githubusercontent.com/codeigniter4/queue/87f736a69a0d64bce0c40bcb1a3f966250f70f03/$path" |
    rg -n -A65 -B5 'function (pop|later|push|done|find|reserve)|allowedFields|returnType|class QueueJob|datamap|casts'
done

Length of output: 64421


Script executed:

#!/bin/bash
set -euo pipefail
repo=opensourcepos/opensourcepos
expected=d8f79a3076e5908f338b83621921d14f973852ef
thread=PRRT_kwDOAOCvWs63DAqr
number=4562173537

info=$(gh pr view 4725 -R "$repo" --json headRefOid,statusCheckRollup) || {
  echo 'PRECHECK_FAILED: cannot read PR head and checks'
  exit 0
}
if ! printf '%s' "$info" | jq -e --arg expected "$expected" '
  .headRefOid == $expected and
  ([.statusCheckRollup[]? | select((.name // "") | endswith(" Tests"))] |
   (map(.name) | unique | length) == 16 and
   all(.[]; .status == "COMPLETED" and .conclusion == "SUCCESS"))
' >/dev/null; then
  echo 'PRECHECK_FAILED: head changed or PHPUnit checks are missing, pending, or unsuccessful'
  exit 0
fi

data=$(gh api graphql -F id="$thread" -f query='
query($id:ID!) {
  node(id:$id) {
    ... on PullRequestReviewThread {
      id isResolved path
      first:comments(first:1) { nodes { author { login } url } }
      last:comments(last:1) { nodes { url } }
    }
  }
}') || {
  echo 'PRECHECK_FAILED: cannot read review thread'
  exit 0
}
if ! printf '%s' "$data" | jq -e '
  .data.node.isResolved == false and
  .data.node.path == "app/Jobs/BoundedQueueWorker.php" and
  .data.node.first.nodes[0].author.login == "coderabbitai" and
  .data.node.first.nodes[0].url == "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r4562173537" and
  .data.node.last.nodes[0].url == "https://github.com/opensourcepos/opensourcepos/pull/4725#discussion_r4625644298"
' >/dev/null; then
  echo 'PRECHECK_FAILED: thread state, ownership, or latest comment changed'
  exit 0
fi

body='@objecttothis I rechecked `d8f79a307`. The `release_epoch` update addresses the `later(0)` fence-reuse scenario. `releaseStrandedJobs()` checks the recorded epoch and increments it in the same database update. A stale claim cannot match a reservation after that release, even if `available_at` returns to its earlier value.

The new worker test covers that sequence. The model tests cover an expired claimant and a new reservation. The pause/resume test checks that the epoch is preserved. The 16 PHPUnit matrix configurations passed in CI.

I did not resolve this thread; you requested a review and a reply.'

result=$(gh api -X POST "repos/$repo/pulls/4725/comments/$number/replies" -f body="$body") || {
  echo 'REPLY_FAILED'
  exit 0
}
if printf '%s' "$result" | jq -e '.html_url != null' >/dev/null; then
  printf 'REPLIED %s\n' "$(printf '%s' "$result" | jq -r .html_url)"
else
  echo 'REPLY_FAILED: response did not confirm the comment'
fi

Length of output: 2768


@objecttothis I re-reviewed the fix and replied in the review thread. The 16 PHPUnit configurations passed.


Learnings added

Learnt from: objecttothis
URL: https://github.com/opensourcepos/opensourcepos/pull/4725

Timestamp: 2026-11-19T09:33:59.091Z
Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Jobs/BoundedQueueWorker.php","app/Models/QueueJobModel.php"]: In stranded-job recovery in app/Jobs/BoundedQueueWorker.php and app/Models/QueueJobModel.php, do not use available_at as the sole reservation fence. The queue handler's later(0) can restore an earlier available_at value within the same second, so a stale claim can match a new reservation. Use a fence that cannot be reused across releases.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


Learnings used

Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-17T08:25:09.048Z
Learning: Within repository "opensourcepos/opensourcepos": In opensourcepos/opensourcepos, when verifying a review fix and relevant tests are still running, wait for them to finish before commenting. If the tests fail, do not resolve the finding. If they pass and the code fixes the finding, resolve it, subject to applicable thread-resolution restrictions.
Learnt from: objecttothis
Repo: opensourcepos/opensourcepos

Timestamp: 2026-11-09T10:46:20.615Z
Learning: Within repository "opensourcepos/opensourcepos": When assessing whether to resolve a review conversation in this repository, keep it open while any aspect of the request remains incomplete.

You are interacting with an AI system.

@objecttothis
objecttothis merged commit d8f79a3 into master Nov 19, 2026
52 checks passed
@objecttothis
objecttothis deleted the feat-job-queue-phase-2a branch November 19, 2026 10:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant