← Back to Pull requests

[Bug] Let batch finalization run again after a restart #3715

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Dec 02, 2026 04:26 UTC
Author

Pull Request Description

Problem and impact

A batch job whose driver stops during finalize can stay finalizing for good. On restart, finalize runs again and fails with "Upload ID ... not found or corrupted". Nothing retries it. After a metadata-service restart, including during a rolling update, finalization should resume and finish. While the job stays finalizing, the batch API returns neither result file ID. The bug is on main (54057443) and tracked in #3583.

Root cause: finalize deletes its inputs before the terminal save. The inputs are the staged upload parts with their metadata, and the per-request done keys batch:<job_id>:done/<idx>.

  • Each complete_multipart_upload normally releases its staging when no parts remain unresolved (storage/base2.py:147, 195, 222, 239). For rerouted output, the adapter aborts the output upload after error assembly.

  • finalize_job_output_data then deletes only the done keys it counted as valid (batch/storage/adapter.py:830).

  • Only after that does mark_job_done save FINALIZED. This is the terminal save.
  • A stop in between leaves a FINALIZING job without its inputs. The restart's _resume_finalizing_job (job_driver/base.py:1323) runs finalize again, and the completes find no staging (storage/base2.py:127). Jobs that main already left in this state stay stuck after an upgrade, because their staging is gone.

    What changed

    This PR implements option D from the design I posted in #3583, which was agreed there. Finalize records the cleanup it still owes in a metastore key, the cleanup marker. A background reclaimer then releases the job's inputs.

    The fix:
    1. Assembly keeps its inputs (release_staging=False). Before each final write it checks that the staging metadata still exists. If the metadata is gone, it raises StagingMissingError. If the check itself errors, finalize still writes, as main does.
    2. finalize_job reads the stored job doc on entry, after assembly and after an error. If the doc is already FINALIZED, finalize adopts it and returns the finished job instead of writing again. The manager can return an already-finished cached job, or adopt the stored job and update its cache. If a read fails, finalize skips adoption at that check. An adoption error on entry fails finalize. An adoption error after assembly gets another adoption attempt in the error handler.
    3. Just before the terminal save, finalize writes a cleanup marker, batchjob_gc/<job_id>.
    4. The terminal save retries after 1, 2 and 4 s. conclude_job can return False even when the doc was saved (batch_manager.py:1184), so each retry first re-reads the stored state.
    5. Right after a confirmed terminal save, finalize tries to delete the two staging metadata objects. A late finalizer is one still assembling after another finalize saved the job. Once the metadata is gone, its staging check fails before it writes, so it can't rebuild the saved files.
    6. A new JobDataReclaimer runs at startup and every 60 s. For each cleanup marker, it checks whether the job has been FINALIZED for at least 120 s. If so, it releases the job's inputs. It deletes the staged parts and the done keys in [0, request_counts.total). Then it checks that the staging prefixes are empty and deletes the cleanup marker.

    Some jobs get no cleanup marker:

  • A job that finalize skips for missing file ids keeps its data, as on main.

  • If the marker write fails 4 times, or the job has no stored doc, the terminal save still runs. Finalize then releases the inputs right after it. If the driver stops before that release finishes, or the release fails, the inputs stay for good. No cleanup marker points to them, so nothing retries.
  • The release runs after the terminal save on purpose. A metastore outage can affect both the marker write and the terminal save. Releasing first, as main does, would then leave the job finalizing without its inputs again.

    A resumed finalize reads the staged parts again. If one of those reads fails, that request is reported failed, as in a first run. The output files and the counts agree with each other. A resumed assembly can produce different files and counts from an earlier attempt that wrote files but never saved the terminal job state.

    Compared with the posted design, this PR adds step 5. It also no longer keeps the job in finalizing when the marker write fails.

    Failed finalize: a finalize attempt that fails before writing the cleanup marker leaves its inputs in place. Without a marker, the reclaimer skips the job. On main, a failed error assembly has normally released the output staging already. As agreed in #3583, whether such jobs get a cleanup marker is left to #3667.

    Behavior changes:

  • Staged parts and done keys now stay about 2 to 3 minutes after the job finishes. A failed release, a slow sweep or a stopped driver makes that longer.

  • The metastore gets one cleanup marker per job until release. A batchjob_gc/_header key stays for good. Once that key is indexed, RedisStorage keeps an index for the batchjob_gc/ prefix even when no cleanup marker exists. Listing the markers then doesn't fall back to reading timestamps:all. Like job listing, this relies on Redis keeping its index keys.

  • The output upload of a job with rerouted parts is no longer aborted at finalize. It is released with the rest.

  • BatchDriver.clear_job, the test helper, also releases the job's temp data and cleanup marker after it deletes the job. If that release fails, the leftovers stay, because the job doc is gone.
  • Overlap with #3668: it changes the done-key deletion in finalize_job_output_data, which this PR removes. Here the release deletes the whole index range, pending and missing done keys included. On Redis each delete also drops the key from batch:<job_id>:done:index, timestamps:batch:<job_id>:done and timestamps:all (storage/redis.py:341-349). A successful release removes the index entries for each done key in the range. A request that finishes after its index was processed can recreate those entries. The range [0, total) covers every done key the adapter writes. total is at least the highest listed index plus one (adapter.py:610-611). Whichever PR lands second needs a rebase.

    Not covered: two finalizers on one job. This can happen in a rolling update, while the old and new metadata-service pods overlap. The job doc is last-writer-wins, as on main, so neither main nor this PR is safe there. They fail in different orderings:

  • On main, a late finalizer that read the parts before the first finalizer's completes can write over the saved files.

  • Here, step 5 stops a late finalizer before it writes. A write still gets through if its staging check ran before the delete, or if the delete failed or never ran. It also gets through if the check itself errored.

  • On main, the first finalizer's completes delete the staging. So main rejects some late finalizers that this PR lets through.
  • In all three orderings, the files disagree with the saved counts only if the two finalizers assembled different results. This happens when one finalizer reroutes an unreadable output part and the other reads it. A late write can then leave a different number of output records than the saved completed count. Closing every ordering needs one owner per job. Main already checks ownership for runtimes through a lease on the job's runtime ref, in runtime.session() (runtime/base.py:1309). The resumed finalize runs before that check (job_driver/base.py:387). Extending the lease to it is a separate change.

    Tests:

  • New tests/batch/test_e2e_finalize_restart.py stops the driver at 8 points, with and without a failed request, then restarts it. It asserts the API status completed, the counts, and the request ids in the output file. When a request failed, it also checks the request ids in the error file. When the first output write finished before the stop, it asserts the same output bytes. It also asserts that no staging, done key or cleanup marker is left.

  • New tests/batch/test_e2e_finalize_two_finalizers.py pauses the scheduler's finalize before it reads the output parts. A second finalize on the same job completes its terminal save. Then the paused one resumes with one failing part read. The test asserts that the saved files keep their bytes and the job stays completed. Without step 5 it fails, because the late finalizer rewrites both files.

  • New unit tests cover:

  • - finalize_job: adoption on entry and after StagingMissingError, an unconfirmed terminal save, and a failed read of the stored doc.
    - finalize_job: a job without file ids, and the release after the terminal save.
    - adoption in the manager and in the job store, the reclaimer, and the release order.
    - kept staging and the staging check. One test fails with the check disabled.
    - the per-object fallback after a failed bulk delete of staged parts.
  • The restart e2e file also covers clear_job during the 120 s grace.

  • Changed tests: six adapter tests now assert that finalize deletes no done keys. The reroute test asserts no abort. The driver lifecycle test asserts finalizing, then the cleanup marker, then the terminal save, then the metadata delete.
  • Related Issues


    Fixes #3583

    Review Conduct


  • I have read every change in this PR and can explain it.

  • No agent will reply to reviews or push to this PR unless I have read and approved each reply and push.
  • Verification

    External contributors must verify changes that affect AIBrix runtime behavior
    or deployment on a live Kubernetes cluster before marking the PR ready for
    review. Changes to CRDs, upgrade behavior, scheduling, routing, autoscaling, or
    inference-engine integration require scenario-specific cluster evidence from
    every author. Pure documentation changes use documentation checks and report
    not_required. A reviewing maintainer may waive the author-run requirement for
    a listed maintainer or a verified open-source AIBrix user and record the waiver
    below.

    <!--
    The same requirements apply to AI-assisted changes.
    For test-only or mechanical edits that leave runtime behavior and deployment
    unchanged, report the relevant checks and mark cluster verification not_required.
    For a cluster run, deploy the changed code or manifests from the PR head and
    exercise the affected behavior.

    Local Kind or Minikube and dedicated Kubernetes test clusters qualify. Use the
    engine, GPU, scheduler, or storage backend the scenario depends on. Follow the
    [live-cluster test guide](../test/README.md#end-to-end-tests)
    for setup and test commands.

    A verified open-source AIBrix user is someone whose prior deployment has been
    confirmed by a maintainer.

    Keep the PR in draft while required cluster verification is pending or failing.
    Reviewers must confirm any required cluster evidence before approving the PR
    for merge.

    Remove any fields that do not apply.
    -->

  • Cluster verification status — passed

  • Tested commit and image — 01794b08, deployed as aibrix-3583/metadata-service:01794b08. The comparison used aibrix-3583/metadata-service:54057443, built from the base commit.

  • Cluster — Kind with Kubernetes v1.37.0, one arm64 node. config/metadata with the in-cluster Redis as metastore, Local file storage on a PVC, and extra RBAC for the per-job Deployment. Jobs use runtime Kubernetes with the mock engine.

  • Scenario and result — A 5000-request batch runs until it reports finalizing. Then the metadata service is stopped by SIGKILL or a pod force-delete, at different points in finalize. Expected: the job completes with all 5000 results, and its temp data is released after the grace period.

  • - 54057443: stopping the metadata service after output staging was deleted but before the terminal save left the job in finalizing. The resumed finalize fails with "Upload ID ... not found or corrupted". 18 minutes later the job was still finalizing, with 3000 done keys left.
    - 01794b08: the job completed at all 4 stop points, two before the terminal save and two after it. Each output had all 5000 custom_ids with status 200. No done keys, cleanup marker or staging directory was left.
    - A job that 54057443 already left in finalizing stays there after the upgrade to 01794b08.
  • Evidence — restarted-service logs, client results and a later Redis and PVC check:
  •   54057443, SIGKILL 0.5 s after the output file was written
      [restarted] Error finalizing job output data: Upload ID ded6195e-... not found or corrupted
      18 min later: status finalizing, 3000 done keys left
    
      01794b08, SIGKILL right after the output file was written
      [restarted] Job is finalized
      [restarted] Runtime-backed job resumed directly into finalization.
      status completed, 5000 output lines; no done keys, cleanup marker or staging left
      

  • Other checks — on macOS arm64 with Python 3.12:

  • - ruff check, ruff format --check and mypy . in python/aibrix: clean.
    - pytest -q tests: 2229 passed, 27 skipped.
    - On this branch, both e2e files pass all 18 cases on the Local metastore and all 18 on the Redis metastore. The Redis run used a local redis-server. tests/batch/conftest.py passes test=True to redis.Redis, which rejects it, so I dropped that argument locally.
    - On main (dee032bf), I ran a copy with 4 of the stop points: during output assembly, after each file completes, and after the terminal save. It fails 4 of 8. The failures are the stops after the output complete and after the error complete, each with and without a failed request. Each fails assert 'finalizing' == 'completed', and the log shows "not found or corrupted".
    - Not tested: S3 and TOS storage, the k8s_job runtime, and two MDS processes, as in a rolling update.

    Important: Before submitting, please complete the description above and review the checklist below.

    ---

    <details>
    <summary><strong>Contribution Guidelines (Expand for Details)</strong></summary>

    <p>We appreciate your contribution to aibrix! To ensure a smooth review process and maintain high code quality, please adhere to the following guidelines:</p>

    <h3>Pull Request Title Format</h3>
    <p>Your PR title should start with one of these prefixes to indicate the nature of the change:</p>
    <ul>
    <li><code>[Bug]</code>: Corrections to existing functionality</li>
    <li><code>[CI]</code>: Changes to build process or CI pipeline</li>
    <li><code>[Docs]</code>: Updates or additions to documentation</li>
    <li><code>[API]</code>: Modifications to aibrix's API or interface</li>
    <li><code>[CLI]</code>: Changes or additions to the Command Line Interface</li>
    <li><code>[Feat]</code>: New functionality</li>
    <li><code>[Misc]</code>: For changes not covered above (use sparingly)</li>
    </ul>
    <p><em>Note: For changes spanning multiple categories, use multiple prefixes in order of importance.</em></p>

    <h3>Submission Checklist</h3>
    <ul>
    <li>[ ] PR title includes appropriate prefix(es)</li>
    <li>[ ] Changes are clearly explained in the PR description</li>
    <li>[ ] New and existing tests pass successfully</li>
    <li>[ ] Code adheres to project style and best practices</li>
    <li>[ ] Documentation updated to reflect changes (if applicable)</li>
    <li>[ ] Thorough testing completed, no regressions introduced</li>
    <li>[ ] Required cluster evidence and any author-run waiver are recorded in Verification</li>
    </ul>

    <p>By submitting this PR, you confirm that you've read these guidelines and your changes align with the project's contribution standards.</p>

    </details>

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: yaokaiy Review duration: 4670m
    All Vouch review confidence checks passed
    Residual risk 0.30 = Change Risk (0.52) × (1 − Review Confidence (0.43)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #3715"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 43.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 43.0% · Lower = rushed or shallow review
    43.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 29.7% · Safe to merge
    29.7%