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
14 changes: 14 additions & 0 deletions docs/incidents/xy_merge_keeps_both_sides_and_parses.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# xy. `xy_merge_keeps_both_sides_and_parses`

**What happened:** CoderHelm merged the base into a pull request's branch, and one file both sides had changed, a dashboard component, conflicted. The base had changed many of its lines; the branch had added two. CoderHelm sent all three versions of the whole file to the model, cut at a size limit, and committed what came back: a few lines of prose ("I'll analyze the differences between the three versions: ...") and then a different file, with most of the base's changes gone. It failed to compile at its first line, and it was pushed. The right result was the base's file with the branch's two lines.

**Why:** the conflicted merge (`pr::resolve_conflicts`) handed every file both sides changed to the model whole, even where the two sides' changes didn't touch. The reply was checked only for being empty, for losing most of the smaller side, and with a bracket scan compared with the branch's version. A prose lead-in and a rewritten file passed all three.

**The guarantee:** CoderHelm never commits a merge result that adds prose, drops either side's changes, or fails to parse.

- Each file is merged three ways (`merge3::merge_text`). Every change only one side made, or both made the same way, is applied mechanically, with no model.
- Only a hunk both sides changed differently goes to the model, alone with its ancestor, ours and theirs and a few unchanged lines around it. Its reply must be that hunk's lines: prose, markdown fences and conflict markers are stripped where they wrap it and refused inside it, it can't be longer than both sides together, and every identifier either side added must still be there.
- The merged file is checked before anything is committed (`merge3::check_merged`): no conflict markers or prose, a line count within both sides' changes together, both sides' added identifiers present, and it parses for its language as well as the sides do (TypeScript, TSX, JavaScript, Python and Rust by their parsers; JSON, YAML and TOML must parse; other code by the bracket scan).
- A merge that fails is tried once more with smaller hunks. Failing again, nothing is pushed and the branch stays as it was. The failure is CoderHelm's own problem: an internal alert, a line on the run page, and the reason as the stop reason.

The case replays it with invented content: a TSX file where the base changed many lines and the branch added two merges mechanically without asking the model, the result that was pushed fails every check, and a model reply of prose plus a rewritten file for a real overlapping hunk pushes nothing.
10 changes: 9 additions & 1 deletion services/worker/src/passes/await_merge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2252,7 +2252,15 @@ async fn bring_base_in(
);
let ticket = gate_ticket(msg)?;
let mut usage = crate::models::TokenUsage::default();
super::pr::resolve_conflicts(state, &ticket, github, branch, &provider, &mut usage).await?;
// A merge that failed its checks pushed nothing: the head is unchanged
// and the conflict stands (said below).
match super::pr::resolve_conflicts(state, &ticket, github, branch, &provider, &mut usage).await
{
Err(e) if e.is::<super::merge3::Refused>() => {}
other => {
other?;
}
}
let head = github.get_ref(owner, repo, branch).await?;
if head == msg.head_sha {
let files = changed_on_both_sides(github, owner, repo, base, branch).await;
Expand Down
9 changes: 8 additions & 1 deletion services/worker/src/passes/branch_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,14 @@ impl Branches for OnGithub<'_> {
)
.await;
self.usage.lock().unwrap().merge(&usage);
resolved?;
match resolved {
// A merge that failed its checks pushed nothing: the conflict
// stands.
Err(e) if e.is::<super::merge3::Refused>() => return Ok(None),
other => {
other?;
}
}
// Merged when the branch now has all of the base.
if self.behind(base, branch).await? == 0 {
Ok(Some(self.head(branch).await?))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,348 @@
//! xy. CoderHelm merged the base into a pull request's branch. One file
//! both sides changed, a dashboard component, conflicted. The base had
//! changed many of its lines and the branch had added two. CoderHelm sent
//! all three versions of the whole file to the model, cut at a size limit,
//! and committed what came back: eight lines of prose ("I'll analyze the
//! differences between the three versions: ...") and then a different
//! file, with most of the base's changes gone. It didn't compile at its
//! first line, and it was pushed.
//!
//! Why: the conflicted merge (`pr::resolve_conflicts`) gave every file both
//! sides changed to the model whole, even where the two sides' changes
//! didn't touch. The reply was checked only for being empty, for losing
//! most of the smaller side, and with a bracket scan compared with the
//! branch's version; a prose lead-in and a rewritten file passed all three.
//!
//! Guarantee: CoderHelm never commits a merge result that adds prose, drops
//! either side's changes, or fails to parse. Each file is merged three ways
//! (`merge3::merge_text`): every change only one side made is applied
//! mechanically, with no model. Only a hunk both sides changed differently
//! goes to the model, alone with its ancestor, ours and theirs, and its
//! reply must be the hunk's lines (prose, fences and markers refused, no
//! longer than both sides together, every identifier either side added
//! kept). The merged file is checked before anything is committed
//! (`merge3::check_merged`): no prose or markers, a size within both sides'
//! changes, both sides' added identifiers there, and it parses for its
//! language as well as the sides do. A failed merge is tried once more with
//! smaller hunks; failing again, nothing is pushed, the branch stays as it
//! was, and the failure is CoderHelm's own problem (an internal alert) with
//! the reason as the stop reason.

use crate::passes::merge3::{self, HunkAsk, HunkModel};

const PATH: &str = "web/src/components/app-frame.tsx";

/// The common ancestor.
const BASE: &str = r#"import { useState } from "react";
import { NavLink } from "./nav-link";
import { useAccount } from "../hooks/use-account";

export function AppFrame({ children }: { children: React.ReactNode }) {
const account = useAccount();
const [open, setOpen] = useState(false);

if (!account) {
return <div className="frame-loading">Loading</div>;
}

return (
<div className="frame">
<aside className="frame-side">
<NavLink href="/">Home</NavLink>
<NavLink href="/runs">Runs</NavLink>
<NavLink href="/settings">Settings</NavLink>
</aside>
<main className="frame-main">
<header className="frame-top">
<button onClick={() => setOpen(!open)}>Menu</button>
</header>
{children}
</main>
</div>
);
}
"#;

/// The base branch: many lines changed (a verification step, a paused
/// workspace screen, a tools group, a help menu).
const MAIN: &str = r#"import { useState } from "react";
import { NavLink } from "./nav-link";
import { useAccount } from "../hooks/use-account";
import { VerifyStep } from "./verify-step";
import { PausedScreen } from "./paused-screen";
import { HelpLinks } from "./help-links";

export function AppFrame({ children }: { children: React.ReactNode }) {
const account = useAccount();
const [open, setOpen] = useState(false);
const [helpOpen, setHelpOpen] = useState(false);

if (!account) {
return <div className="frame-loading">Loading</div>;
}

if (account.needsVerifyStep) {
return <VerifyStep onDone={account.refresh} />;
}

if (account.workspacePaused) {
return <PausedScreen owner={account.workspaceOwner} />;
}

return (
<div className="frame">
<aside className="frame-side">
<NavLink href="/">Home</NavLink>
<NavLink href="/runs">Runs</NavLink>
<NavLink href="/settings">Settings</NavLink>
<section className="frame-tools-group">
<h4>Tools</h4>
<NavLink href="/tools/keys">Keys</NavLink>
<NavLink href="/tools/usage">Usage</NavLink>
</section>
</aside>
<main className="frame-main">
<header className="frame-top">
<button onClick={() => setOpen(!open)}>Menu</button>
<button onClick={() => setHelpOpen(!helpOpen)}>Help</button>
{helpOpen && <HelpLinks onClose={() => setHelpOpen(false)} />}
</header>
{children}
</main>
</div>
);
}
"#;

/// The pull request's branch: two lines added.
const BRANCH: &str = r#"import { useState } from "react";
import { NavLink } from "./nav-link";
import { ReviewCount } from "./review-count";
import { useAccount } from "../hooks/use-account";

export function AppFrame({ children }: { children: React.ReactNode }) {
const account = useAccount();
const [open, setOpen] = useState(false);

if (!account) {
return <div className="frame-loading">Loading</div>;
}

return (
<div className="frame">
<aside className="frame-side">
<NavLink href="/">Home</NavLink>
<NavLink href="/runs">Runs</NavLink>
<NavLink href="/reviews">Reviews <ReviewCount /></NavLink>
<NavLink href="/settings">Settings</NavLink>
</aside>
<main className="frame-main">
<header className="frame-top">
<button onClick={() => setOpen(!open)}>Menu</button>
</header>
{children}
</main>
</div>
);
}
"#;

/// The model's reply as it came: prose, then a file of its own that keeps
/// the branch's two lines and loses the base's changes.
const PROSE_AND_REWRITE: &str = r#"I'll analyze the differences between the three versions:

1. **main branch changes**: added a verification step, a paused screen, a tools group and a help menu.
2. **feature branch changes**: added a Reviews link with a count.

The merged file keeps both:

import { useState } from "react";
import { NavLink } from "./nav-link";
import { ReviewCount } from "./review-count";

export function AppFrame({ children }: { children: React.ReactNode }) {
return (
<div className="frame">
<NavLink href="/reviews">Reviews <ReviewCount /></NavLink>
{children}
</div>
);
}
"#;

/// What the merge must be: the base branch's file with the branch's two
/// lines.
fn expected() -> String {
MAIN.replace(
"import { NavLink } from \"./nav-link\";\n",
"import { NavLink } from \"./nav-link\";\nimport { ReviewCount } from \"./review-count\";\n",
)
.replace(
" <NavLink href=\"/runs\">Runs</NavLink>\n",
" <NavLink href=\"/runs\">Runs</NavLink>\n <NavLink href=\"/reviews\">Reviews <ReviewCount /></NavLink>\n",
)
}

/// A model that always answers with `reply`, counting what it is asked.
struct Stub {
reply: Vec<String>,
asked: Vec<HunkAsk>,
}

impl Stub {
fn new(replies: &[&str]) -> Self {
Stub {
reply: replies.iter().map(|s| s.to_string()).collect(),
asked: Vec::new(),
}
}
}

#[async_trait::async_trait]
impl HunkModel for Stub {
async fn resolve(&mut self, ask: &HunkAsk) -> Result<String, String> {
self.asked.push(ask.clone());
let n = self.asked.len() - 1;
Ok(self.reply[n.min(self.reply.len() - 1)].clone())
}
}

fn run<F: std::future::Future>(f: F) -> F::Output {
tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(f)
}

#[test]
fn the_sides_apart_merge_mechanically_and_the_model_is_never_asked() {
let mut model = Stub::new(&[PROSE_AND_REWRITE]);
let merged = run(merge3::merge_text(
PATH,
Some(BASE),
MAIN,
BRANCH,
"main branch",
&mut model,
))
.expect("the mechanical merge");
assert_eq!(merged.text, expected());
assert_eq!(merged.by_model, 0);
assert!(
model.asked.is_empty(),
"no model for changes that don't overlap"
);
assert_eq!(merge3::parse_errors(PATH, &merged.text), Some(0));
}

#[test]
fn the_result_that_was_pushed_fails_every_check() {
let err = merge3::check_merged(PATH, BASE, BRANCH, MAIN, PROSE_AND_REWRITE).unwrap_err();
assert!(err.contains("starts with prose"), "{err}");

// Without its prose, the rewritten file still drops the base's work.
let code = &PROSE_AND_REWRITE[PROSE_AND_REWRITE.find("import").unwrap()..];
let err = merge3::check_merged(PATH, BASE, BRANCH, MAIN, code).unwrap_err();
assert!(err.contains("lines") || err.contains("drops"), "{err}");
let err = merge3::check_merged(
PATH,
BASE,
BRANCH,
MAIN,
&expected().replace(" </section>\n", ""),
)
.unwrap_err();
assert!(err.contains("parse"), "{err}");

// The prose alone fails the parser too.
assert!(merge3::parse_errors(PATH, PROSE_AND_REWRITE).unwrap() > 0);
// And the right merge passes.
assert!(merge3::check_merged(PATH, BASE, BRANCH, MAIN, &expected()).is_ok());
}

/// The branch's link next to a line the base changed: one real hunk.
fn touching() -> (String, String) {
let main = MAIN.replace(
" <NavLink href=\"/settings\">Settings</NavLink>\n",
" <NavLink href=\"/settings\">Workspace settings</NavLink>\n",
);
(main, BRANCH.to_string())
}

#[test]
fn an_overlapping_hunk_reaches_the_model_alone_and_a_prose_reply_pushes_nothing() {
let (main, branch) = touching();
let mut model = Stub::new(&[PROSE_AND_REWRITE]);
let err = run(merge3::merge_text(
PATH,
Some(BASE),
&main,
&branch,
"main branch",
&mut model,
))
.unwrap_err();
assert!(err.0.contains("merging each conflicting hunk"), "{err}");
assert!(err.0.contains("smaller pieces"), "{err}");
// It saw the hunk, never the whole file.
assert!(!model.asked.is_empty());
for ask in &model.asked {
assert!(!ask.ours.contains("export function AppFrame"), "{ask:?}");
assert!(ask.ours.lines().count() <= 2, "{ask:?}");
assert!(ask.theirs.lines().count() <= 6, "{ask:?}");
}

// A reply that is the hunk's lines lands in place; the rest stays
// mechanical.
let hunk = concat!(
" <NavLink href=\"/reviews\">Reviews <ReviewCount /></NavLink>\n",
" <NavLink href=\"/settings\">Workspace settings</NavLink>\n",
" <section className=\"frame-tools-group\">\n",
" <h4>Tools</h4>\n",
" <NavLink href=\"/tools/keys\">Keys</NavLink>\n",
" <NavLink href=\"/tools/usage\">Usage</NavLink>\n",
" </section>\n",
);
let mut model = Stub::new(&[&format!("<resolved>\n{hunk}</resolved>")]);
let merged = run(merge3::merge_text(
PATH,
Some(BASE),
&main,
&branch,
"main branch",
&mut model,
))
.expect("the hunk merged");
assert_eq!(model.asked.len(), 1);
assert_eq!(
merged.text,
expected().replace(">Settings</NavLink>", ">Workspace settings</NavLink>")
);
}

/// The wiring: the conflicted merge of the base goes through the three way
/// merge, a refused merge pushes nothing and is CoderHelm's own problem,
/// and no prompt asks the model for a whole merged file.
#[test]
fn the_conflicted_merge_goes_through_the_three_way_merge() {
let pr = include_str!("../pr.rs");
let resolve = super::fixture::fn_src(pr, "pub async fn resolve_conflicts(");
assert!(resolve.contains("merge_file_or_why("));
assert!(resolve.contains("Err(why) => return Err(refuse_merge("));
assert!(!resolve.contains("return Ok(false);\n };"));
let refuse = super::fixture::fn_src(pr, "async fn refuse_merge(");
assert!(refuse.contains("own_problems::record(") && refuse.contains("own_problems::alert("));
assert!(refuse.contains("OwnSubject::Tooling"));
let file = super::fixture::fn_src(pr, "pub async fn merge_file_or_why(");
assert!(file.contains("merge3::merge_text("));
assert!(!pr.contains("Produce the correctly merged file"));
// The rebuilt stack merges through the same path.
assert!(include_str!("../restack.rs").contains("super::pr::merge_file("));
// A refused merge leaves the conflict standing where it was reported.
for src in [
include_str!("../await_merge.rs"),
include_str!("../branch_update.rs"),
] {
assert!(src.contains("e.is::<super::merge3::Refused>()"));
}
}
Loading