Skip to content

fix(bot): atomically persist cron store - #4733

Merged
qin-ctx merged 1 commit into
volcengine:mainfrom
wutongyuonce:fix/cron-store-atomic-write
Sep 8, 2026
Merged

qin-ctx merged 1 commit into
volcengine:mainfrom
wutongyuonce:fix/cron-store-atomic-write

Conversation

@wutongyuonce

Copy link
Copy Markdown
Contributor

Description

Make VikingBot Cron store writes crash-safe by writing the JSON to a same-directory temporary file and replacing the canonical store only after the temporary write succeeds. A partial write can no longer leave the existing store truncated or invalid.

Human Involvement

  • A human participated in the implementation or review loop
  • This PR was generated entirely by AI agents without human participation in the loop

Type of Change

  • Bug fix (non-breaking change)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement
  • Test update

Changes Made

  • Persist CronStore through a same-directory temporary file and atomic Path.replace().
  • Remove the temporary file on both success and failure.
  • Add a regression test showing an interrupted write preserves the existing valid store.

Testing

  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • I have tested this on the following platforms:
    • Linux
    • macOS
    • Windows

Checklist

  • My code follows the project's coding style
  • I have performed a self-review of my code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

Additional Notes

Validation: .venv/bin/python -m pytest -q bot/vikingbot/tests/unit/test_cron_service.py --no-cov (1 passed). Ruff was unavailable in the local virtual environment.

@now-ing

now-ing commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Review: fix(bot): atomically persist cron store

Verified at head a01fe8d4 (local checkout). The fix is correct and I support merging it. Independent evidence below.

Why this matters more than the PR body states

_load_store raises RuntimeError on any parse failure (service.py, the except Exception around json.loads). So under the old direct write_text, a partial write (disk full, process kill mid-write) didn't just risk stale data — it bricked the cron service permanently: every subsequent start() raises until someone hand-deletes the store file. The crash-safety framing is correct and arguably understated.

Correctness verification

  • Same-directory temp file ⇒ same filesystem ⇒ Path.replace (= os.replace) is atomic on POSIX and covers existing targets on Windows. ✔
  • finally: temporary.unlink(missing_ok=True) — on the success path the temp file was already consumed by replace, so missing_ok makes the cleanup a no-op without raising; on failure it removes the residue. ✔
  • The .{name}.{uuid4}.tmp naming avoids collisions if two saves ever interleave (single asyncio loop today, but the naming is future-proof). ✔
  • This matches the repo's existing convention: bot/vikingbot/compile/store.py:_write_atomic uses the identical same-directory-tmp + os.replace shape (with a pid suffix; the uuid here is fine too) — except this PR additionally adds the finally cleanup, which _write_atomic lacks.

Test discrimination check (mutation verified)

I reverted _save_store to the old self.store_path.write_text(...) one-liner and re-ran the new test: it fails precisely on json.loads(path.read_text()) == original_data (the canonical file holds the truncated 10-byte prefix). So the test genuinely pins the atomicity property and is not vacuously green. ✔ Suite passes at head (1 passed).

I also exercised the success path by hand (not covered by the test): overwriting an existing store yields correct content, and two consecutive saves leave zero .tmp residue in the directory.

Non-blocking suggestions

  1. Durability gap (fsync): write_text doesn't flush to disk, so on power loss the rename can be committed while the temp file's contents aren't — leaving a truncated store despite the atomic rename. The repo already has the fsync'd variant in two places: openviking/storage/vectordb/store/file_store.py (f.flush(); os.fsync(f.fileno()) before os.replace) and openviking/models/vlm/backends/codex_auth.py:_atomic_write_json_file (mkstemp + fsync + chmod + replace). For a cron store, losing job definitions + last-run state to a power cut is a medium-tolerance risk, so aligning with one of those would be a nice follow-up:
    with open(temporary, "w", encoding="utf-8") as f:
        f.write(json.dumps(data, indent=2))
        f.flush()
        os.fsync(f.fileno())
    temporary.replace(self.store_path)
  2. Lock the success path too: adding two lines to the existing test (assert json.loads(path.read_text())["jobs"][0]["id"] == "new" and a no-.tmp-residue assert after a clean save) would pin the finally/missing_ok branch as well.

Minor note for the record: concurrent writers to the same store file (separate processes) still get last-writer-wins rather than corruption — an improvement over interleaved partial writes, and consistent with the service's single-loop design today.

@now-ing

now-ing commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Verified: import uuid is already in place (service.py:6), the temp-then-replace pattern gives kill-safe atomicity on both POSIX and Windows, the finally: unlink(missing_ok=True) covers both outcomes (after a successful replace the temp no longer exists), and the interrupted-write test asserts both the original file's integrity and the absence of temp litter — good, focused change.

Two notes, neither blocking:

  1. (Low) No fsync before the rename — a process kill leaves either the old or the new content (the point of this PR), but a machine power-loss can still theoretically leave an unflushed rename on some filesystems. For a cron store that trade is reasonable; mentioning it only so it's a documented choice rather than an accident.
  2. (CI) bot/vikingbot/tests/unit/ doesn't run in any current PR lane (pr.yml has no Python unit tier), so the new test is author-local only right now — the unit-test lane proposed in ci(pr): run unit-test directories in PR validation #4677 would close exactly this gap. No action needed in this PR.

From my side this is ready.

@qin-ctx
qin-ctx merged commit d3bdd54 into volcengine:main Sep 8, 2026
6 checks passed
@github-project-automation github-project-automation Bot moved this from Backlog to Done in OpenViking project Sep 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants