[Bug] Let batch finalization run again after a restart #3715
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
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.02 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
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
yaokaiy
Pull Request Description
Problem and impact
A batch job whose driver stops during finalize can stay
finalizingfor 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 staysfinalizing, 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>.complete_multipart_uploadnormally 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_datathen deletes only the done keys it counted as valid (batch/storage/adapter.py:830).mark_job_donesave 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 raisesStagingMissingError. If the check itself errors, finalize still writes, as main does.2.
finalize_jobreads 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_jobcan 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
JobDataReclaimerruns 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:
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
finalizingwithout 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
finalizingwhen 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:
batchjob_gc/_headerkey stays for good. Once that key is indexed, RedisStorage keeps an index for thebatchjob_gc/prefix even when no cleanup marker exists. Listing the markers then doesn't fall back to readingtimestamps:all. Like job listing, this relies on Redis keeping its index keys.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 frombatch:<job_id>:done:index,timestamps:batch:<job_id>:doneandtimestamps: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.totalis 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:
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:
tests/batch/test_e2e_finalize_restart.pystops the driver at 8 points, with and without a failed request, then restarts it. It asserts the API statuscompleted, 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.tests/batch/test_e2e_finalize_two_finalizers.pypauses 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.-
finalize_job: adoption on entry and afterStagingMissingError, 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.
clear_jobduring the 120 s grace.Related Issues
Fixes #3583
Review Conduct
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 fora 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.
-->
passedaibrix-3583/metadata-service:01794b08. The comparison usedaibrix-3583/metadata-service:54057443, built from the base commit.config/metadatawith the in-cluster Redis as metastore, Local file storage on a PVC, and extra RBAC for the per-job Deployment. Jobs use runtimeKuberneteswith themockengine.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 stillfinalizing, 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
finalizingstays there after the upgrade to 01794b08.-
ruff check,ruff format --checkandmypy .inpython/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.pypassestest=Truetoredis.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>