Skip to content

fix(restart): refuse to clobber an armed reboot snapshot - #409

Closed
KooshaPari wants to merge 2 commits into
masterfrom
fix/restart-save-armed
Closed

KooshaPari wants to merge 2 commits into
masterfrom
fix/restart-save-armed

Conversation

@KooshaPari

@KooshaPari KooshaPari commented Nov 28, 2026 •

Copy link
Copy Markdown
Owner

User description

Fixes #394.

jcode restart save silently overwrote an armed reboot snapshot, which clobbered the pending
restore and disarmed it. It now refuses, and only replaces an armed snapshot when explicitly
asked to.

Behaviour

  • An existing armed snapshot is never overwritten implicitly: the command bails with the
    snapshot path, creation time and session count, and names the two ways forward
    (jcode restart restore to consume it, or --replace-armed to replace it).
  • --replace-armed replaces it and reports the replaced snapshot's creation time and session
    count in the output.
  • restart save --auto-restore with zero captured sessions writes the snapshot unarmed and
    says so, instead of arming a restore with nothing to restore.
  • An unarmed snapshot is still replaced without ceremony, as before.

How it is tested

The tests write a snapshot file directly into an isolated KCODE_HOME and assert both the
refusal and that the file is byte-identical afterwards, which keeps the file seam honest
without needing a live daemon.

Validation

[mac fallback: nixos unreachable, no other Linux node]
test result: ok. 11 passed; 0 failed; 0 ignored; 0 measured; 298 filtered out

cargo +stable fmt --all -- --check exit 0. scripts/check_swallowed_error_budget.py exit 0
(3847 -> 3814, shrank). The first commit on this branch did not compile (E0596) and discarded two
io::Result values; both are fixed in 02db72f54.


CodeAnt-AI Description

Protect pending reboot restores when saving a snapshot

What Changed

  • Saving no longer overwrites an armed reboot snapshot unless you pass --replace-armed; the refusal shows the snapshot details and explains how to restore it or replace it.
  • With --replace-armed, the save replaces the pending snapshot and reports the replaced snapshot’s details.
  • Saving with --auto-restore and no captured sessions leaves the snapshot unarmed and explains why.

Impact

✅ Fewer lost pending reboot restores
✅ Clearer choices when replacing an armed snapshot
✅ No empty automatic restores

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Validation run:
- cargo +stable fmt --all -- --check: exit 0, no diffs
- python3 scripts/check_swallowed_error_budget.py: exit 0, total 3847 -> 3814
- NBUILD_REMOTE_ROOT=/home/kooshapari/builds/restart-save ~/bin/nbuild <wtree> test -p kcode --lib restart_: twice exit 2, nbuild cannot reach nixos, direct ssh timed out. ENV-BLOCKED.

tx-agent: jcode
tx-validated: lint
tx-task: G1-restart-save-safety
tx-scope: src/cli
tx-intent: restart save must never silently clobber an armed snapshot
tx-lane: jcode:session_koala_1795837517661_8c5572f0003a474a
…errors

Two defects in the previous commit, both found by actually building it:

- `restart_tests.rs:215` bound `let crashed = Session::create_with_id(...)` and
  then called `mark_active_with_pid(&mut self)`, so the test target failed to
  compile with E0596. The binding needs `mut`.
- Two `writeln!(output, ...)` calls in `run_restart_save_command` discarded their
  `io::Result`, which trips `unused_must_use` under `-D warnings`. They now
  propagate with `?`, matching the four sibling calls in the same function.

tx-agent: jcode
tx-validated: test
tx-task: PR-save-armed
tx-scope: src/cli/commands/restart.rs,src/cli/commands/restart_tests.rs
tx-intent: Make the branch build and pass its own restart tests.
tx-lane: jcode:session_daisy_1795074744352_88932230960f4f43
Copilot AI balanced review requested due to automatic review settings November 28, 2026 04:11
@codeant-ai

codeant-ai Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

CodeAnt  CodeAnt Review Status

✅  Review completed

Status Commit Started (UTC) Finished (UTC)
✅  #4c007 Reviewed your PR 02db72f Nov 28, 2026 · 04:11 04:16

@codeant-ai

codeant-ai Bot commented Nov 28, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@coderabbitai

coderabbitai Bot commented Nov 28, 2026

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 22 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: b4485397-87d0-45e2-8d83-44cee52f932b
Commits

Reviewing files that changed from the base of the PR and between e38809c and 02db72f.

Files selected for processing: 5

  • src/cli/args.rs
  • src/cli/args/tests.rs
  • src/cli/commands/restart.rs
  • src/cli/commands/restart_tests.rs
  • src/cli/dispatch.rs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Nov 28, 2026
@sonarqubecloud

Copy link
Copy Markdown

@codeant-ai

codeant-ai Bot commented Nov 28, 2026

Copy link
Copy Markdown

CodeAnt  CodeAnt Nitpicks

3 code suggestions

1. maybe_run_pending_restart_restore_on_startup clears the armed flag before restoring; a save during that interval passes this check, then restore may clear the newly written snapshot.

Race condition · src/cli/commands/restart.rs:18-22


2. When --replace-armed replaces a snapshot but captures no sessions, this early return omits the replaced snapshot’s creation time and session count.

Api mismatch · src/cli/commands/restart.rs:41-50


3. When --replace-armed replaces an armed snapshot with captured sessions, this output incorrectly describes the replaced snapshot as unarmed.

Logic error · src/cli/commands/restart.rs:59-63

@codeant-ai

codeant-ai Bot commented Nov 28, 2026

Copy link
Copy Markdown

CodeAnt  CodeAnt PR Risk

🟢  Low Risk

  • The PR appears safe to merge; no actionable issues were identified in the review.

Assessed commit: 02db72f5414f

path.display(),
if let Some(existing) = &existing {
format!(
" (replaced unarmed snapshot created {} with {} session(s))",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Misleading message: the replaced snapshot is always described as "unarmed".

This branch is reached when an unarmed snapshot was replaced without --replace-armed, but also when an armed snapshot was replaced with --replace-armed. In the latter case the message still says "replaced unarmed snapshot", which contradicts the PR's stated behavior of reporting the replaced snapshot's details accurately. Branch on existing.auto_restore_on_next_start to say "armed" vs "unarmed".

Suggested change
" (replaced unarmed snapshot created {} with {} session(s))",
" (replaced {} snapshot created {} with {} session(s))",
if existing.auto_restore_on_next_start { "armed" } else { "unarmed" },
existing.created_at,
existing.sessions.len()

@Kilo fix this

Fix these issues in Kilo Cloud

}
println!("\nNo active jcode windows were detected.");
writeln!(output, "\nNo active jcode windows were detected.")?;
return Ok(());

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: The replaced-snapshot report is skipped on the empty-capture early return.

When --replace-armed is used but zero sessions are captured, this early return fires before the "replaced ... snapshot" message (lines 53-67). The PR description says --replace-armed "reports the replaced snapshot's creation time and session count in the output", but that report is silently omitted in the empty case. Consider emitting the replaced-snapshot detail here too when existing is Some.

@Kilo fix this

Fix these issues in Kilo Cloud

crate::restart_snapshot::capture_current_snapshot()?
};
snapshot.auto_restore_on_next_start = auto_restore;
snapshot.auto_restore_on_next_start = auto_restore && !snapshot.sessions.is_empty();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: --auto-restore is silently ignored when no sessions are captured.

auto_restore && !snapshot.sessions.is_empty() forces the flag off for empty captures. The user does get a message (lines 43-48), but the requested --auto-restore intent is dropped with no way to override. This is intentional per the PR description, but consider whether an explicit warning/exit code would be clearer for scripted callers who pass --auto-restore expecting it to be honored.

@Kilo fix this

Fix these issues in Kilo Cloud

&& !replace_armed
{
// The restore-side claim that serializes competing restores belongs to #389.
let snapshot = existing.as_ref().expect("armed snapshot present");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Redundant expect after is_some_and guard.

existing.as_ref().expect("armed snapshot present") is unreachable-as-None because the enclosing if already proved existing is Some and armed. It is safe, but the double-handling is easy to misread. Consider if let Some(snapshot) = existing.as_ref().filter(|s| s.auto_restore_on_next_start) { ... } to make the invariant structural.

@Kilo fix this

Fix these issues in Kilo Cloud

path.display(),
error
)
})? || matches!(nested_io_error(&error), Some(std::io::ErrorKind::NotFound));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Corrupt/unreadable existing snapshot is silently treated as "missing".

existing_snapshot_for_save returns Ok(None) when the file does not exist OR when load_snapshot failed with a NotFound io error. But read_json (jcode-storage) wraps parse failures and backup-recovery failures in anyhow without a NotFound io cause, so a corrupt snapshot yields Err here and aborts the save — which is the safe choice. However, a file that disappears between load_snapshot and try_exists is also treated as missing, which is fine. The subtle risk: if read_json ever changes to wrap io errors differently, the NotFound detection via nested_io_error could misfire and either (a) abort on a genuinely missing file or (b) treat a real read error as missing and overwrite. Consider matching on the snapshot path's existence first and only then loading, to make the missing-vs-corrupt decision explicit and robust to error-type changes.

@Kilo fix this

Fix these issues in Kilo Cloud

.expect_err("plain save must refuse an armed snapshot");

let after = fs::read(&path).expect("read snapshot after refusal");
assert_eq!(after, before, "refusal must leave the file byte-identical");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Byte-identical assertion is good, but the test does not assert the error message contains the snapshot path.

The refusal message includes path.display() (restart.rs:27); the test checks the message contains the created-at, session count, and --replace-armed, but not the path. Adding assert!(message.contains(&path.display().to_string())) would lock in the "names the snapshot path" guarantee from the PR description.

@Kilo fix this

Fix these issues in Kilo Cloud

@kilo-code-bot

kilo-code-bot Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: 6 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 4
SUGGESTION 2
Issue Details (click to expand)

WARNING

File Line Issue
src/cli/commands/restart.rs 60 Replaced snapshot always described as "unarmed", even when an armed snapshot was replaced with --replace-armed.
src/cli/commands/restart.rs 50 Empty-capture early return skips the replaced-snapshot report that --replace-armed promises.
src/cli/commands/restart.rs 38 --auto-restore silently ignored when no sessions captured; no override for scripted callers.
src/cli/commands/restart.rs 107 Missing-vs-corrupt snapshot detection relies on nested_io_error NotFound matching; fragile if error wrapping changes.

SUGGESTION

File Line Issue
src/cli/commands/restart.rs 24 Redundant expect after is_some_and guard; prefer if let Some(...).filter(...).
src/cli/commands/restart_tests.rs 82 Refusal test does not assert the message contains the snapshot path.
Files Reviewed (5 files)
  • src/cli/args.rs - 0 issues
  • src/cli/args/tests.rs - 0 issues
  • src/cli/commands/restart.rs - 5 issues
  • src/cli/commands/restart_tests.rs - 1 issue
  • src/cli/dispatch.rs - 0 issues

The core guard logic is sound: an armed snapshot is refused without --replace-armed, the file is left byte-identical on refusal (verified by test), and the empty-capture auto-restore case is handled. The warnings are about message accuracy and edge-case robustness, not the central safety property. No security, compilation, or clippy concerns found in the diff.

Fix these issues in Kilo Cloud


Reviewed by free · Input: 74.9K · Output: 3.2K · Cached: 334.3K

@KooshaPari

Copy link
Copy Markdown
Owner Author

Superseded by #416. The branch here is still based on 1d42e78, so the size-ratchet change no longer applies cleanly and a rebase cannot be pushed without rewriting this branch. Same change set rebased onto a3c41a9 is in #416, including the dispatch extraction that lets the size ratchet and cargo fmt agree.

@KooshaPari KooshaPari closed this Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

restart save silently overwrites an armed snapshot (clobbers pending restore, disarms it)

2 participants