project-pegaprox icon indicating copy to clipboard operation
project-pegaprox copied to clipboard

[Bug] Race condition on LXC Replication job causing migration failure due to duplicate job occuring before the first is finished.

Open DarmokNoob opened this issue 6 months ago • 2 comments

[!CAUTION] API Limitation with certain feature flags In the course of testing this bug I found out that LXC containers with any feature flags other than nesting=1 will still fail at the config step regardless of this fix, due to a separate Proxmox API restriction. Apparently, feature flags mknod, keyctl, fuse, mount, nfs, cifs, or similar capability flags are restricted from being configured via API. Additional bug report on this issue specifically is forth coming.

Describe the bug

Cross-cluster LXC replication fails on every attempt due to a race condition in the scheduler. The scheduler loop checks elapsed >= interval every 60 seconds, but last_run is only updated after a job completes. Any migration that takes longer than 60 seconds — which is every real-world LXC migration — will trigger a second run before the first finishes. The scheduler has no awareness of whether a job is already executing.

The second run then attempts to delete the "old replica" on the target cluster, finds it locked (still being created by the first migration), and aborts, which in turn also kills the first migration! Both runs fail, leftover artifacts (temp clone, orphaned snapshots) are left on the source node, and the job is marked as errored.

Because the race condition is triggered by any duplicate execution and not just the scheduler the same failure occurs if the manual trigger button is pressed while a job is already running. The proposed fix addresses both paths: the scheduler skips in-flight jobs, and the manual trigger endpoint returns 409 Conflict when a job is already running.

Steps to Reproduce

  1. Configure a cross-cluster replication job for an LXC container (no feature flags)
  2. Trigger the job — either via schedule auto-fire on creation or manual trigger
  3. Watch the Proxmox task list on the source node
  4. Within 60 seconds of the first snapshot/clone starting, a second snapshot fires
  5. Both migrations abort, temp clone CT left orphaned on source node

Expected behavior

If a replication job is already in progress, subsequent scheduler ticks should skip that job until it completes. Manual trigger attempts against an already-running job should return 409 Conflict instead of spawning a duplicate thread.

Proof

pveproxy access log showing overlapping snapshot tasks 60 seconds apart:

vzsnapshot:102 started 18:05:04 → OK 18:05:05
vzclone:102 started 18:05:10 → OK 18:06:43
vzmigrate:104 started 18:06:44 ← first migration in progress
vzsnapshot:102 started 18:05:21 ← second job fires 60s later, still migrating
vzclone:102 started 18:05:26
vzmigrate:104 aborted 18:08:57 ← first migration killed by second run's cleanup

PegaProx log confirming second xcrepl token created while first migration still running:

[PegaProx] INFO: [OK] Created API token: root@pam!xcrepl-aaae8c82-45965
[PegaProx] INFO: Remote migration started for 105
[PegaProx] INFO: [OK] Created API token: root@pam!xcrepl-aaae8c82-46025  ← second run
[XCREPL] Job aaae8c82: could not remove old replica: CT is locked (create)
[XCREPL] Job aaae8c82: migration task failed: migration aborted

Fix

pegaprox/background/cross_cluster_replication.py — add an in-flight job tracking set. Before spawning a thread, check if the job ID is already running. If yes, skip. Remove from the set in a finally block after the job completes.

_running_jobs = set()
_running_jobs_lock = threading.Lock()
 
# In _xcrepl_loop, replace the thread spawn block:
if elapsed >= interval:
    with _running_jobs_lock:
        if job['id'] in _running_jobs:
            logger.info(f"[XCREPL] Job {job['id']} (VM {job['vmid']}) already in flight, skipping until complete")
            continue
        _running_jobs.add(job['id'])
 
    def run_and_cleanup(j=job, h=handler):
        try:
            h(j)
        except Exception as e:
            logger.error(f"[XCREPL] Job {j['id']} raised unhandled exception: {e}")
        finally:
            with _running_jobs_lock:
                _running_jobs.discard(j['id'])
            logger.info(f"[XCREPL] Job {j['id']} (VM {j['vmid']}) released from in-flight tracking")
 
    try:
        threading.Thread(target=run_and_cleanup, daemon=True).start()
    except Exception as e:
        with _running_jobs_lock:
            _running_jobs.discard(job['id'])
        logger.error(f"[XCREPL] Failed to start job {job['id']}: {e}")

pegaprox/api/vms.py — apply the same guard to the manual trigger endpoint run_cross_cluster_replication. Import _running_jobs and _running_jobs_lock from the background module and check before spawning. Returns 409 Conflict if job is already running:

from pegaprox.background.cross_cluster_replication import _running_jobs, _running_jobs_lock
 
with _running_jobs_lock:
    if job_dict['id'] in _running_jobs:
        return jsonify({'success': False, 'message': 'Replication job already in progress'}), 409
    _running_jobs.add(job_dict['id'])
 
def run_and_cleanup(j=job_dict, h=handler):
    try:
        h(j)
    except Exception as e:
        pass
    finally:
        with _running_jobs_lock:
            _running_jobs.discard(j['id'])
 
threading.Thread(target=run_and_cleanup, daemon=True).start()

Both patches were tested live and confirmed working:

  • Scheduler no longer spawns duplicate runs
  • Manual trigger while job running returns 409 and shows "Failed to start" in UI
  • Single clean migration completes end to end with no artifacts left behind

Environment

  • PegaProx Version: v0.9.11
  • Installation Method: Docker
  • OS: Arch Linux ARM64 (PiKVM, Raspberry Pi 4)
  • Browser: Chrome
  • Behind Reverse Proxy? No
  • UI: Modern Layout

Logs

PegaProx log showing second job token created while first migration still running:

[PegaProx] INFO: [OK] Created API token: root@pam!xcrepl-aaae8c82-45965
[PegaProx] INFO: Remote migration started for 105
[PegaProx] INFO: [OK] Created API token: root@pam!xcrepl-aaae8c82-46025  ← second run
[XCREPL] Job aaae8c82: could not remove old replica: CT is locked (create)
[XCREPL] Job aaae8c82: migration task failed: migration aborted

Checklist

  • [x] I have searched existing issues to make sure this is not a duplicate
  • [x] I am using the latest version of PegaProx

DarmokNoob avatar May 25 '26 03:05 DarmokNoob

@DarmokNoob — confirmed, fixed on Testing in d0bec84.

Two paths were spawning duplicate threads — the scheduler loop and the manual trigger endpoint. Both now consult a shared in-flight set:

  • Scheduler skips the tick when the job is already running
  • Manual trigger returns 409 Conflict with a "wait for current run" detail

The set is released by a thread-wrapper that fires on both success and exception paths, so a crashing handler can't leave a phantom in-flight marker. Closing on the merge — will land in the next release.

Thanks for the pveproxy log paste, made the RCA a one-read job.

— Marcus

mkellermann97 avatar May 25 '26 07:05 mkellermann97

@DarmokNoob — race-fix d0bec84 rode the v0.9.12 train, so the in-flight guard is now live on Docker :latest and the in-app updater. Manual trigger gives you a clean 409 Conflict instead of spawning a duplicate, scheduler-loop skips the tick when the job's still running.

Closing against the released fix — if you ever see two threads land on the same replication job again after the upgrade, ping the ticket back open.

Volunteer-built, opencollective.com/pegaprox is where the coffee budget goes if you're feeling generous.

— Marcus

mkellermann97 avatar Jun 01 '26 14:06 mkellermann97