Skip to content

Migration ajax request can exceed server/proxy timeouts, showing false "Connection error" #4737

Open

Description

@objecttothis

Problem

On installs with many pending migrations, the login page's migration ajax request (Login::migrate()) can exceed webserver, reverse-proxy, or PHP socket timeouts, surfacing "Connection error. Please try again." to the user even though the migrations complete successfully.

Confirmed via log inspection (Laragon/Apache + MySQL 8.4 locally): every migration step logs success, the full run completes in ~90s, but the browser still receives a connection error because no response bytes are sent to the client until the entire batch finishes. Any intermediate proxy/webserver layer with an idle-connection timeout (Apache Timeout, nginx proxy_read_timeout, corporate/AV proxies, etc.) can kill the socket mid-run.

Bumping set_time_limit, jQuery ajax timeout, default_socket_timeout, and Apache's Timeout directive does not reliably fix this, since:

  • Not all hosting environments give admins access to php.ini / httpd.conf (shared hosting, managed panels).
  • The failure point can be any hop in the chain (proxy, load balancer, AV/firewall), not just Apache or PHP.

Proposed solution

Convert the single long-running migration request into a sequence of small requests — one HTTP round-trip per pending migration — driven by a client-side loop. This removes the dependency on any server/proxy timeout configuration and works unmodified on any host.

Design

  1. app/Libraries/MY_Migration.php — add a new public method, e.g. runNextMigration(?string $group = null): ?object, that mirrors CodeIgniter\Database\MigrationRunner::latest()'s setup (ensureTable, lock acquire/release, group filtering) but executes only the next pending migration (via the existing protected migrate('up', $migration) + addHistory()), then returns the migration object that was run, or null if none remain. Throws the same RuntimeException on failure as latest() for parity. No CodeIgniter vendor/core changes required — MY_Migration already extends MigrationRunner and all needed members are protected/public and visible to the subclass.
  2. app/Controllers/Login.php — migrate() calls runNextMigration() once per request instead of ->latest(). Response JSON becomes {success: bool, done: bool, version: int|null, message?: string}, where done = true once runNextMigration() returns null.
  3. app/Views/login.php — replace the single $.ajax call with a runStep() function that calls itself recursively while done === false, updating the progress UI between steps (e.g. showing the version just migrated), and finishing with the existing success/error UI once done === true or an ajax error occurs. This is seamless to the user: no page reload, no re-entering credentials — the page and JS state stay alive across the whole loop, same as a single request today, just broken into many small ones under the hood.

Explicitly out of scope for this change

  • Login::index()'s non-ajax fallback migration path (used only when JS/ajax is unavailable) — stays a single long-running request.
  • MY_Migration::migrateToCI4() (one-time legacy CI3→CI4 migration-table conversion) — stays a single-shot call before the stepped loop begins; it's fast bookkeeping, not the slow part.
  • Server/proxy timeout configuration docs — not needed once this is implemented, since no single request runs longer than one migration step.

Notes

  • $lock defaults to false in this app's migration config (single-admin install flow); each step request would still acquire/release the lock independently if enabled, same semantics as today.
  • The existing login_check credential validation in migrate() would re-run on every step request (same values resubmitted each time) — negligible overhead, no behavior change.

Activity

  1. jekkos commented on Oct 22, 2026

    @jekkos
    Member

    This will be resolved by offloading the migration run to a background task (job queue) — same direction as noted in #4769. The client receives an immediate "migration queued" response, and the worker runs to completion regardless of connection state or proxy timeouts. No more false 'Connection error' for long migration sequences. Targeting 3.4.4 alongside the job queue infrastructure (#4703 / #4725).

  2. objecttothis commented on Oct 22, 2026

    @objecttothis
    MemberAuthor

    If each migration is run in a separate job then it would be quite rare to run into timeouts. I think probably the way to implement this is that a migration job runs one migration, then checks to see if there are more migrations and just before completing the job, schedules the next migration to kick off.

  3. objecttothis commented on Oct 23, 2026

    @objecttothis
    MemberAuthor

    Claude Issue Checker Agent (cc @objecttothis)

    Investigated against current master.

    Status: Still present (proposed fix not implemented).

    app/Controllers/Login.php still has the single-shot migration flow described in this issue:

    • index() and migrate() both call $migration->setNamespace('App')->latest() once, wrapped only in set_time_limit(3600) — there is no runNextMigration() method anywhere in the codebase (confirmed via repo-wide code search, zero matches).
    • app/Libraries/MY_Migration.php has no stepped-migration method either — it still only exposes the inherited latest()-style behavior used as one long-running call.
    • The login view/ajax flow (Login::migrate()) returns a single {success, message} JSON after the entire batch completes, not the proposed {success, done, version} per-step protocol.

    So a long migration run can still exceed webserver/proxy idle timeouts and surface the "Connection error" message even though migrations ultimately succeed, exactly as described. No related PR is currently linked to this issue.

  4. objecttothis commented on Nov 13, 2026

    @objecttothis
    MemberAuthor

    regarding @jekkos suggestion, we are already developing a job queue system in a way to have different queues. I suspect the way we should do this is to have a dedicated migration queue which gets priority for importance, and timeout length. We also need to remove throttling so that it runs. We may need to drop requirement for login to run migrations for this or at least have the migration queue bypass it. We do likely need to change the check in the login screen to prevent login until migrations complete. Each migration should finish by checking for another migration and creating the job for it if the next migration exists. The initial check for migrations and creating the first job should remain in the login screen or a CI tasks scheduled checker. It would be helpful to add a live migration status on the login screen so users can see progress. @coderabbitai please comment on feasibility and design.

  5. coderabbitai commented on Nov 13, 2026

    @coderabbitai
    Contributor
    Analysis chain

    Script executed:

    #!/bin/bash
    printf '%s\n' '--- Repository revision ---'
    git rev-parse --short HEAD
    printf '%s\n' '--- Referenced issues ---'
    for n in 4737 4703 4725 4769; do
      echo "--- #$n ---"
      gh issue view "$n" --repo opensourcepos/opensourcepos --json number,title,state,body,comments --jq '{number,title,state,body,comments: [.comments[] | {author: .author.login, body: .body}]}' 2>&1 | head -c 20000
      echo
    done
    printf '%s\n' '--- Referenced file locations ---'
    fd -i '^(Login|MY_Migration|Throttle)\.php$' .
    printf '%s\n' '--- Outlines ---'
    for f in app/Controllers/Login.php app/Libraries/MY_Migration.php app/Filters/Throttle.php; do
      if [ -f "$f" ]; then echo "--- $f ---"; ast-grep outline "$f" --items all 2>&1; fi
    done
    printf '%s\n' '--- Queue, migration and route references ---'
    rg -n -i -C2 -g '*.php' -g 'composer.json' -g '*.yml' -g '*.yaml' '\b(queue|worker|migration|migrate|throttl(e|ing))\b' app composer.json 2>/dev/null | head -n 350

    Length of output: 91898


    Script executed:

    #!/bin/bash
    printf '%s\n' '--- Login controller ---'
    cat -n app/Controllers/Login.php
    printf '%s\n' '--- Migration library ---'
    cat -n app/Libraries/MY_Migration.php
    printf '%s\n' '--- Login view structure and migration requests ---'
    ast-grep outline app/Views/login.php --items all 2>&1
    rg -n -C5 'migrat|ajax|login|submit' app/Views/login.php
    printf '%s\n' '--- Throttle filter ---'
    cat -n app/Filters/Throttle.php
    printf '%s\n' '--- Other application references ---'
    rg -n -C3 -g '*.php' -g '!app/Database/Migrations/**' '\b(runLocked|isLatest|migrateToCI4|job_throttles|JobRunner|JobThrottleGate|BoundedQueueWorker|tasks:run|jobs_mode)\b' app
    printf '%s\n' '--- Filter and route outlines ---'
    for f in app/Config/Filters.php app/Config/Routes.php app/Controllers/BaseController.php; do
      if [ -f "$f" ]; then
        echo "--- $f ---"
        ast-grep outline "$f" --items all 2>&1
        rg -n -C3 -i 'migrat|throttl|auth|login|filter|jobs' "$f"
      fi
    done
    printf '%s\n' '--- Queue PR metadata ---'
    for n in 4703 4725 4769; do
      gh pr view "$n" --repo opensourcepos/opensourcepos --json number,title,state,baseRefName,headRefName,mergedAt --jq '{number,title,state,baseRefName,headRefName,mergedAt}' 2>&1
    done
    printf '%s\n' '--- Versions and queue dependencies ---'
    rg -n -C2 '"codeigniter4/(framework|tasks|queue)"' composer.json composer.lock | head -n 50

    Length of output: 47870


    Script executed:

    #!/bin/bash
    printf '%s\n' '--- Current startup and login filter ---'
    for f in app/Events/Load_config.php app/Filters/IsLoggedIn.php; do
      echo "--- $f ---"
      if [ -f "$f" ]; then ast-grep outline "$f" --items all 2>&1; cat -n "$f"; fi
    done
    printf '%s\n' '--- Queue PR branch targeted files ---'
    repo=opensourcepos/opensourcepos
    ref=feat-job-queue-phase-2a
    for f in app/Config/Queue.php app/Config/Tasks.php app/Filters/JobRunner.php app/Jobs/BoundedQueueWorker.php app/Jobs/JobThrottleGate.php app/Database/Migrations/20260916000000_AddJobsModule.php; do
      echo "--- $f ---"
      data=$(gh api "repos/$repo/contents/$f?ref=$ref" --jq '.content' 2>&1) || { echo "$data"; continue; }
      printf '%s' "$data" | base64 -d 2>/dev/null | nl -ba | sed -n '1,220p'
    done

    Length of output: 29232


    @objecttothis The design is feasible, but the queue needs a bootstrap path that works before the queue’s database tables and settings exist. That is the main constraint for fresh installs and older upgrades.

    The current code still runs the full migration sequence in one request. One correction to the earlier investigation: Login::index() and Login::migrate() now call MY_Migration::runLocked(), which wraps latest() in a database lock. Login::index() also calls migrateToCI4() before that lock.

    I suggest this design:

    1. Bootstrap and trigger. Let the login flow or a scheduled checker detect pending migrations and request the first job. Use bootstrap-safe storage and configuration that do not depend on the schema being migrated. Preserve automatic initialization for fresh installs. The proposed queue in #4725 defaults to database storage, and its worker reads application settings and throttle tables.
    2. Run one migration per job. Add a migration runner that selects the next pending migration and preserves CI4 ordering and history semantics. Run CI3 history conversion under the same migration lock. After success, enqueue the next job if one exists.
    3. Make recovery explicit. Deduplicate jobs by migration version and serialize execution with a database-scoped lock. If a worker stops after recording history but before enqueueing the next job, the checker must reconcile the history and schedule the missing job. If a worker stops during a migration, do not blindly retry: the schema may have changed before the history was recorded. Show a failure and require a safe recovery decision.
    4. Separate worker policy from login security. Exempt the trusted migration queue from queue throttles, including global queue throttles. Keep rate limits on credential-bearing login and migration requests. A scheduled worker can run without a user login; that does not require an unauthenticated public endpoint that can start arbitrary jobs.
    5. Reserve execution capacity. Give the migration queue first access to a worker and a suitable time budget. In #4725, queue order and per-queue priority are separate, and the worker checks its deadline between jobs. A single migration can still exceed PHP, host, or reservation limits. Web-mode execution also needs a verified detached execution path; fastcgi_finish_request() is not available on every host.
    6. Gate access and show status. Block application access server-side, including existing sessions, until migrations complete successfully. Load_config already destroys sessions when the database is not current, but the gate should also cover running and failed states. Let the login page poll a read-only status endpoint for queued, running, completed, failed, and stalled states. Limit unauthenticated details and show actionable recovery guidance.

    I would test fresh installs, CI3 upgrades, simultaneous triggers, worker interruption at each handoff, a single long migration, and all supported worker modes. Also verify the login flow when no detached worker is available, so the upgrade does not remain queued indefinitely.

    You are interacting with an AI system.

  6. objecttothis commented on Nov 13, 2026

    @objecttothis
    MemberAuthor

    Even with current master changes, timeouts are hit on large pre-existing databases and the CI3 to CI4 migration does not properly complete which causes a decryption exception to be thrown as soon as you attempt to access CI3 encrypted data with a CI4 key.

    image

    Ultimately we need a solution to this problem. Ideally an interim solution since jobs is a ways off from being completed.

  7. jekkos commented on Nov 13, 2026

    @jekkos
    Member

    @CodeRabbit is there an easy way to run migration in async fashion where we just offload it to a thread for now?

  8. coderabbitai commented on Nov 13, 2026

    @coderabbitai
    Contributor
    Analysis chain

    Script executed:

    #!/bin/bash
    printf '%s\n' '--- Revision ---'
    git rev-parse --short HEAD
    printf '%s\n' '--- Source outlines ---'
    for f in app/Controllers/Login.php app/Libraries/MY_Migration.php app/Events/Load_config.php app/Database/Migrations/20220127000000_convertToCI4.php app/Helpers/security_helper.php; do
      if [ -f "$f" ]; then
        echo "--- $f ---"
        ast-grep outline "$f" --items all 2>&1
      fi
    done
    printf '%s\n' '--- Migration, CLI and async references ---'
    rg -n -C 3 -g '*.php' -g '*.md' -g 'composer.json' 'runLocked|migrateToCI4|fastcgi_finish_request|ignore_user_abort|set_time_limit|spark migrate|isLatest|checkEncryption|encryption\.key' app README.md composer.json 2>/dev/null | head -n 430
    printf '%s\n' '--- Commands and environment file locations ---'
    fd -i '(^spark$|migration|encryption|install|upgrade)' app . -t f | head -n 100

    Length of output: 24208


    web_search executed:

    According to official PHP documentation, what does fastcgi_finish_request() do under PHP-FPM, does it release the PHP-FPM worker while PHP continues, and how do script execution and timeout limits or client disconnects affect continued processing? Check PHP manual documentation.

    Length of output: 13042


    Script executed:

    #!/bin/bash
    printf '%s\n' '--- Login flow ---'
    cat -n app/Controllers/Login.php | sed -n '1,165p'
    printf '%s\n' '--- Locked migration and conversion entry ---'
    cat -n app/Libraries/MY_Migration.php | sed -n '1,165p'
    printf '%s\n' '--- Encryption migration ---'
    cat -n app/Database/Migrations/20220127000000_convertToCI4.php | sed -n '1,200p'
    printf '%s\n' '--- Security conversion and rollback ---'
    cat -n app/Helpers/security_helper.php | sed -n '296,363p;406,545p;596,650p'
    printf '%s\n' '--- Login AJAX ---'
    cat -n app/Views/login.php | sed -n '280,335p'
    printf '%s\n' '--- Startup config ---'
    cat -n app/Events/Load_config.php | sed -n '1,105p'
    printf '%s\n' '--- CLI and upgrade documentation ---'
    ast-grep outline app/Commands/EnvProvision.php --items all 2>&1
    cat -n app/Commands/EnvProvision.php | sed -n '1,150p'
    rg -n -C 3 -i 'migrat|cli|spark|backup|upgrade' docs/UPGRADE.md docs/INSTALL.md spark | head -n 160
    printf '%s\n' '--- Runtime requirements ---'
    rg -n -C 2 '"php"|codeigniter4/framework|disable_functions' composer.json

    Length of output: 44769


    @jekkos Yes. For PHP-FPM, the smallest interim option is probably fastcgi_finish_request(), rather than a thread. It sends the HTTP response and lets the same PHP process continue the migration. It does not require the job queue. PHP documentation

    It is not a durable background job. The migration still occupies a PHP-FPM worker, and PHP or host timeouts can still terminate it. A restart can also interrupt it.

    I suggest this interim flow:

    1. Authenticate as today and acquire the migration lock. Release the session lock, send a “migration started” response, then finish the FastCGI request and run the migration.
    2. Change the login page to poll for status. Today, app/Views/login.php treats a successful response as completion. Report completion only after the migration succeeds. Show failed or interrupted states and keep application access blocked until success.
    3. Move the migrateToCI4() call in app/Controllers/Login.php, Line 35, inside the same lock. It currently runs before runLocked().
    4. If fastcgi_finish_request() is unavailable, report that async execution is unavailable rather than claiming the migration started. Check FPM capacity too: with one worker, status polling may wait for the migration.

    Login::migrate() already uses ignore_user_abort(true) and a one-hour limit. Those settings do not prevent host timeouts or process termination.

    Encryption recovery remains critical. The conversion writes the new key before saving the converted secrets. A hard process termination can interrupt that sequence. Keep a matching database and .env backup before upgrading, and do not blindly retry an interrupted conversion. This also follows the existing project guidance to preserve the legacy key until conversion succeeds and keep automatic web initialization for fresh installs.


    Learnings used

    Learnt from: objecttothis
    Repo: opensourcepos/opensourcepos PR: 4656
    File: :0-0
    Timestamp: 2026-09-12T05:40:39.757Z
    Learning: For OpenSourcePOS PR #4656, non-Docker fresh installs must keep the existing automatic web initialization workflow. Users must not need to run `php spark env:provision` manually after copying `.env.example` to `.env`; missing encryption and throttle keys should be provisioned programmatically without replacing a short legacy CI3 encryption key before migration.
    
    Learnt from: objecttothis
    Repo: opensourcepos/opensourcepos PR: 0
    File: :0-0
    Timestamp: 2026-11-13T04:24:41.837Z
    Learning: Within repository "opensourcepos/opensourcepos", only for files matching one of ["app/Filters/Throttle.php","app/Helpers/security_helper.php","app/Database/Migrations/20220127000000_convertToCI4.php"]: In OpenSourcePOS CI3-to-CI4 upgrades, throttling must work on the initial page flow before conversion completes. A separate throttle key prevents throttling from calling checkEncryption() and rotating the short legacy encryption key before legacy data is migrated. When reviewing a shared-key design, preserve an equivalent safe bootstrap path and do not replace the legacy encryption key before conversion succeeds.
    

    You are interacting with an AI system.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions