Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,092 changes: 415 additions & 677 deletions Cargo.lock

Large diffs are not rendered by default.

58 changes: 54 additions & 4 deletions atomic-agent/src/record/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,13 +216,63 @@ pub fn record_turn(
if repo.is_sandbox() {
repo.set_current_view_in_memory(&options.session.view_name);
} else {
// A missing session view here is NOT the normal first-turn
// case (that path creates the view during `apply_after_record`, well
// after we already aligned successfully once). If we reach this
// branch it means the SessionStart fork that should have created
// `options.session.view_name` either never ran or failed silently,
// leaving `record()` to fall back to whatever view happened to be
// `current_view` — frequently `Shared` or an unrelated sibling view.
// Recording onto that wrong view duplicates every file already
// present there once the two views are later merged, because the
// diff is computed against the wrong parent state.
//
// Instead of silently recording onto the wrong view, fork the
// session view here, just-in-time, from its intended parent (or the
// current view as a last resort) so the diff is computed against
// the correct baseline.
match repo.align_to_view(&options.session.view_name) {
Ok(()) => {}
Err(atomic_repository::RepositoryError::ViewNotFound { .. }) => {
log::debug!(
"session view '{}' not yet created; first-turn apply will create it",
options.session.view_name
);
let parent = options
.session
.parent_view()
.map(|s| s.to_string())
.unwrap_or_else(|| repo.current_view().to_string());

match repo.create_view_from(&options.session.view_name, &parent) {
Ok(()) => {
log::warn!(
"session view '{}' was missing at record time (SessionStart fork \
likely skipped or failed); forked it from '{}' just-in-time",
options.session.view_name,
parent,
);
}
Err(atomic_repository::RepositoryError::ViewAlreadyExists { .. }) => {}
Err(e) => {
return Err(AgentError::RecordFailed {
session_id: options.session.session_id.clone(),
turn_number: options.turn_number,
reason: format!(
"Session view '{}' does not exist and could not be forked \
from '{}': {} (refusing to record onto an implicitly-created \
orphan view, which would duplicate existing content)",
options.session.view_name, parent, e
),
});
}
}

repo.align_to_view(&options.session.view_name)
.map_err(|e| AgentError::RecordFailed {
session_id: options.session.session_id.clone(),
turn_number: options.turn_number,
reason: format!(
"Failed to align to session view '{}' after forking it: {}",
options.session.view_name, e
),
})?;
}
Err(e) => {
return Err(AgentError::RecordFailed {
Expand Down
154 changes: 154 additions & 0 deletions atomic-agent/src/record/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1016,3 +1016,157 @@ fn test_outcome_recorded_file_list_empty() {

assert!(outcome.recorded_file_list().is_empty());
}

// Orphaned session view duplication

/// Build a Go-like source file with `count` distinct top-level functions,
/// each with a unique, greppable marker line.
fn build_source(count: usize) -> String {
let mut out = String::new();
out.push_str("package main\n\n");
for i in 0..count {
out.push_str(&format!(
"func step{i}() int {{\n // marker[{i}]\n return {i}\n}}\n\n"
));
}
out
}

fn count_occurrences(content: &str, pattern: &str) -> usize {
content.matches(pattern).count()
}

/// Reproduces the real-world mechanism behind the orphan-view duplication
/// bug: a session whose `SessionStart` fork never ran (or failed silently),
/// so its view doesn't exist yet when `record_turn()` is called for the
/// first time.
///
/// Before the fix, `record_turn()` would fall through to whatever view
/// happened to be `current_view` on the raw `Repository` handle it opens
/// internally — not necessarily this session's intended parent — and record
/// the turn there. Once that view and the session's own (separately
/// forked) view were both later merged into `dev`, the divergent baselines
/// meant the same pre-existing content could be recorded twice.
///
/// This test drives two sessions through `record_turn()` directly: session
/// A whose view is properly forked from `dev` beforehand (the normal path),
/// and session B whose view is deliberately left unforked (the orphan
/// path). Per the fix, `record_turn()` must self-heal session B by forking
/// its view just-in-time from its intended parent (`dev`) rather than
/// silently recording onto the wrong view. After merging both sessions'
/// views into `dev`, every function in the file must appear exactly once.
#[test]
fn test_orphaned_session_view_duplicates_content_on_merge() {
use atomic_repository::apply::CrossViewInsertOptions;
use atomic_repository::Repository;
use tempfile::TempDir;

let temp_dir = TempDir::new().unwrap();
let repo_root = temp_dir.path();
let file = repo_root.join("main.go");

let initial = build_source(80);
std::fs::write(&file, &initial).unwrap();

{
let repo = Repository::init(repo_root).unwrap();
repo.add(
"main.go",
atomic_repository::tracking::TrackingOptions::default(),
)
.unwrap();
let header = atomic_core::change::ChangeHeader::new("Add main.go");
let options = atomic_repository::record::RecordOptions::new()
.with_all(true)
.save_to_store(true)
.apply_after_record(true);
repo.record(header, options).unwrap();
}

// Session A: SessionStart properly forks its view from "dev" before any
// turn is recorded — the normal, non-buggy path.
{
let mut repo = Repository::open_existing(repo_root).unwrap();
repo.create_view_from("session-a", "dev").unwrap();
}

let mut session_a = AgentSession::new("session-a", "claude-code", "Claude Code");
session_a.view_name = "session-a".to_string();
session_a.set_parent_view("dev");

let edited_a = initial.replacen("return 10\n", "return 1000\n", 1);
std::fs::write(&file, &edited_a).unwrap();

let event_a = TurnEvent::new("session-a", HookType::TurnEnd);
let options_a = TurnRecordOptions {
session: &session_a,
event: &event_a,
turn_number: 1,
turn_duration_ms: 1000,
prompt: Some("Bump step10".to_string()),
};
record_turn(repo_root, &options_a).unwrap();

// Session B: simulates a SessionStart fork that never ran (or failed) —
// its view does not exist yet when record_turn() is called. Per the
// orphan-view duplication fix, record_turn() must self-heal by forking
// it just-in-time from its intended parent ("dev"), NOT from whatever
// view happens to be current on the internally-opened Repository handle
// (which after session A's turn is "session-a" — forking from there
// would leak session A's edit into session B's history and, once both
// are merged into dev, resurrect it as a duplicate).
let mut session_b = AgentSession::new("session-b", "claude-code", "Claude Code");
session_b.view_name = "session-b".to_string();
session_b.set_parent_view("dev");

let edited_b = initial.replacen("return 70\n", "return 7000\n", 1);
std::fs::write(&file, &edited_b).unwrap();

let event_b = TurnEvent::new("session-b", HookType::TurnEnd);
let options_b = TurnRecordOptions {
session: &session_b,
event: &event_b,
turn_number: 1,
turn_duration_ms: 1000,
prompt: Some("Bump step70".to_string()),
};
record_turn(repo_root, &options_b)
.expect("record_turn should self-heal an orphaned session view rather than fail");

// Merge both session views into dev.
{
let repo = Repository::open_existing(repo_root).unwrap();
repo.insert_from_view(CrossViewInsertOptions::new("session-a", "dev"))
.unwrap();
repo.insert_from_view(CrossViewInsertOptions::new("session-b", "dev"))
.unwrap();
repo.materialize().unwrap();
}

let repo = Repository::open_existing(repo_root).unwrap();
let content = repo
.get_file_content_on_view("main.go", "dev")
.unwrap()
.expect("file should exist on dev");
let content = String::from_utf8(content).unwrap();

for i in 0..80 {
let marker = format!("// marker[{i}]");
let occurrences = count_occurrences(&content, &marker);
assert_eq!(
occurrences, 1,
"step{} should appear exactly once after merging both session views, \
found {} (orphan-view duplication bug)",
i, occurrences
);
}

assert!(
content.contains("return 1000"),
"session A's edit should survive the merge"
);
assert!(
content.contains("return 7000"),
"session B's edit should survive the merge"
);
}
19 changes: 12 additions & 7 deletions atomic-cli/src/commands/diff/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,13 +495,18 @@ impl Diff {
let rm_orig_idx = rm_entries[*ri].0;
let add_orig_idx = add_entries[*ai].0;

// Only pull an add forward if there are no other Added lines
// between the remove and the matched add in the original order.
// Intervening Added lines represent genuinely new content that
// belongs before the matched line in the new file — moving the
// matched add past them would put it in the wrong position.
let has_intervening_adds = (rm_orig_idx + 1..add_orig_idx).any(|i| lines[i].is_added());
if has_intervening_adds {
// Only pull an add forward, never backward — the add must come
// after the remove in the original order, or "pulling it
// forward" would instead duplicate a line already emitted at
// its earlier original position.
//
// Intervening Added lines between the remove and its matched add
// are allowed: pairing readability (showing what a buried
// modification actually changed) matters more here than
// preserving their exact relative display position, which is
// the whole point of this heuristic — see the "buried
// modification" and "pairing at scale" cases this exists for.
if add_orig_idx <= rm_orig_idx {
continue;
}

Expand Down
4 changes: 2 additions & 2 deletions atomic-cli/src/commands/git/parallel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3316,7 +3316,7 @@ impl ParallelImporter {
}
CommitClassification::Merge => {
stats.merges += 1;
let tag_name = format!("merge-{}", &info.short_sha);
let tag_name = format!("merge-{}", info.short_sha);
let metadata = serde_json::json!({
"git": {
"sha": info.git_sha,
Expand Down Expand Up @@ -3344,7 +3344,7 @@ impl ParallelImporter {
let tag_name = if let Some(pr) = pr_number {
format!("pr-{}", pr)
} else {
format!("squash-{}", &info.short_sha)
format!("squash-{}", info.short_sha)
};
let metadata = serde_json::json!({
"git": {
Expand Down
14 changes: 11 additions & 3 deletions atomic-core/src/output/repo/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -856,6 +856,13 @@ where
/// A tuple of:
/// - `Vec<u8>` - The file content at the filtered state
/// - `Vec<FileConflict>` - Any conflicts detected
/// - `bool` - Whether retrieval had to resolve fork/cyclic structure via
/// [`resolve_conflicts_semantically`] (`!resolved.is_empty()`). Callers
/// that use this content as `old_content` for a subsequent positional
/// diff (see `record_modified_file`) must consult this: a
/// semantic-merge resolution is not guaranteed to structurally match
/// what a plain, unambiguous checkout would render for the same graph
/// state, so a positional diff against it can produce a corrupted hunk.
///
/// # Errors
///
Expand Down Expand Up @@ -898,7 +905,7 @@ pub fn output_file_to_buffer_with_options<T, C>(
position: Position<NodeId>,
_file_options: FileOutputOptions,
retrieve_options: RetrieveOptions,
) -> Result<(Vec<u8>, Vec<FileConflict>), OutputError>
) -> Result<(Vec<u8>, Vec<FileConflict>, bool), OutputError>
where
T: GraphTxnT,
C: ChangeStore,
Expand All @@ -909,7 +916,7 @@ where

// Handle empty graph (no content at this state)
if retrieve_result.graph.is_empty() {
return Ok((Vec::new(), Vec::new()));
return Ok((Vec::new(), Vec::new(), false));
}

// Compute SCC ordering
Expand All @@ -934,6 +941,7 @@ where

// Attempt semantic merge for any conflicting SCCs
let resolved = resolve_conflicts_semantically(txn, changes, &graph, &order);
let had_fork_structure = !resolved.is_empty();

// Output the graph content (with semantic merge resolution)
output_graph_content_resolved(changes, hash_fn, &graph, &order, &mut writer, &resolved)?;
Expand All @@ -953,7 +961,7 @@ where
}
}

Ok((content, conflicts))
Ok((content, conflicts, had_fork_structure))
}

// TESTS
Expand Down
Loading
Loading