Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
reviewer: add bounded preparation attempts
Bound daemon baseline and prerequisite preparation before AI execution.
Default to a 30-minute deadline and three fresh-worktree retries,
matching the AI retry count while keeping its budget independent. Retry
only timeouts, and stop if bounded cleanup cannot finish safely.

Retain worktree ownership across cancellation and pause the attempt
deadline during separately bounded cleanup. Shield shared remote config,
ref, and timestamp writes with owned locks. Join only the attempt's own
writers before retrying. Use SIGTERM for shared writers on shutdown so
Git can clean its lockfiles. Query remote HEAD outside config locks,
bound its output, and tolerate unrelated non-UTF-8 refs. Retain
ownership through post-fetch HEAD initialization so retries can reuse
local refs without skipping unfinished setup. Treat baseline database
errors as preparation failures, not failed patch application.

Publish typed preparation stages, attempt counters, timing, and timeout
history through claim-fenced baseline logs. Show progress in the web UI
using fixed public labels without interpolating subprocess diagnostics.
Publish the application stage once per baseline rather than per patch,
preserving its start time without redundant database writes. Continue
polling while queued or in review, including through reruns and late
baseline metadata publication. Preserve legacy baseline entries and
ordinary application failures.

Cover successful retries, exhaustion, cleanup failure, cancellation,
supersession, persistence failure, settings, multi-patch progress, and
shared-writer ownership with synthetic fixtures and controlled timeouts.
Document the new configuration and keep the existing CI setup.

Fixes: db16ef0 ("refactor: move baseline/model/prompts to patchset level and log baseline detection")
Fixes: 04bd858 ("baseline: add branch patterns for selective remote refspec fetching")
Signed-off-by: James Hilliard <james.hilliard1@gmail.com>
  • Loading branch information
jameshilliard committed Nov 9, 2026
commit ffa8b3489407dd5cea6558fcffb6a4667131f1d3
4 changes: 4 additions & 0 deletions Settings.toml
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ concurrency = 16
worktree_dir = "review_trees"
timeout_seconds = 7200
max_retries = 3
# Preparation has a separate per-attempt deadline and retry budget.
# Each cleanup pauses that deadline and has its own 120-second budget.
# preparation_timeout_seconds = 1800
# preparation_max_retries = 3
ignore_files = ["MAINTAINERS", ".mailmap", ".gitignore", "LICENSES/"]
# Reasoning effort on Argon models: "low", "mid" (default), "high", or
# "dynamic". Other models ignore it.
Expand Down
2 changes: 2 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -419,6 +419,8 @@ pass.
| `worktree_dir` | string | -- | Directory for git worktrees used during daemon reviews. The daemon empties it on startup, so it must hold nothing else. |
| `timeout_seconds` | integer | `3600` | Maximum time per review (seconds). Idle wait time spent parked on shared rate limits (RPS/TPM pacing or 429 backoff) while no requests of this review are in flight is credited back to the deadline. |
| `max_retries` | integer | `3` | Retry count on transient failures. |
| `preparation_timeout_seconds` | positive integer | `1800` | Maximum time per daemon preparation attempt, before AI execution, excluding cleanup. Covers input loading, baseline/prerequisite resolution, checkout and patch application. Each cleanup has a separate 120-second budget and pauses the preparation deadline. See the [configuration fragment](examples/review-preparation.example.toml). |
| `preparation_max_retries` | integer | `3` | Additional preparation attempts after a timeout, using fresh worktrees after cleanup and 5-second incremental backoff capped at 30 seconds. Set to `0` to disable retries. Cleanup failures stop retries; ordinary application failures do not consume this retry budget. Independent of AI retries. |
| `max_lines_changed` | integer | `10000` | Skip patches with more changed lines than this. |
| `max_files_touched` | integer | `200` | Skip patches touching more files than this. |
| `ignore_files` | list | `[]` | File patterns to skip during review (e.g. `MAINTAINERS`). |
Expand Down
9 changes: 9 additions & 0 deletions docs/examples/review-preparation.example.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Merge these keys into your existing [review] table in Settings.toml.
# This fragment is not a complete daemon configuration.
[review]
# Positive per-attempt preparation deadline, independent of AI execution.
# Each cleanup pauses that deadline and has its own 120-second budget.
preparation_timeout_seconds = 1800
# Additional fresh-worktree attempts after timeouts; 0 disables retries.
# Three retries matches the AI retry default, but is configured independently.
preparation_max_retries = 3
21 changes: 21 additions & 0 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15101,6 +15101,27 @@ impl Database {
Ok(count)
}

/// Publish preparation progress without replacing a forced baseline or
/// model metadata. A superseded attempt cannot overwrite the current run.
pub async fn update_patchset_preparation_logs(&self, id: i64, logs: &str) -> Result<()> {
let (claim_ps_id, claim_gen) = self.claim_params();
let compressed = crate::compression::compress_opt_string_async(Some(logs)).await;
self.execute(
"UPDATE patchsets SET baseline_logs = ?
WHERE id = ? AND status = 'In Review'
AND (? IS NULL OR (
patchsets.id = ? AND EXISTS (
SELECT 1 FROM meta m
WHERE m.key = 'patchset_active_gen:' || CAST(patchsets.id AS TEXT)
AND CAST(m.value AS INTEGER) = ?
)
))",
libsql::params![compressed, id, claim_ps_id, claim_ps_id, claim_gen],
)
.await?;
Ok(())
}

pub async fn update_patchset_baseline_info(
&self,
id: i64,
Expand Down
107 changes: 98 additions & 9 deletions src/git_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,28 @@ pub fn detached_async() -> tokio::process::Command {
}

tokio::task_local! {
static ISOLATE_PROCESSES: ();
static ISOLATE_PROCESSES: Isolation;
}

#[derive(Clone, Copy)]
enum Isolation {
Cancellable,
SharedWriter,
}

/// Daemon preparation owns its Git hooks and transports. Other callers retain
/// the foreground process group for terminal prompts and terminal signals.
#[allow(dead_code)]
pub(crate) async fn with_isolated_processes<F: std::future::Future>(future: F) -> F::Output {
ISOLATE_PROCESSES.scope((), future).await
ISOLATE_PROCESSES
.scope(Isolation::Cancellable, future)
.await
}

pub(crate) async fn with_shared_writer_processes<F: std::future::Future>(future: F) -> F::Output {
ISOLATE_PROCESSES
.scope(Isolation::SharedWriter, future)
.await
}

pub(crate) fn processes_are_isolated() -> bool {
Expand Down Expand Up @@ -159,9 +173,45 @@ async fn wait_for_exit(
pub(crate) async fn output(
command: &mut tokio::process::Command,
input: Option<&[u8]>,
) -> std::io::Result<std::process::Output> {
output_with_limit(command, input, None).await
}

/// Limit both output streams of a read-only query. Exceeding either limit
/// cancels the command rather than returning a silently truncated response.
pub(crate) async fn output_limited(
command: &mut tokio::process::Command,
max_bytes: usize,
) -> std::io::Result<std::process::Output> {
output_with_limit(command, None, Some(max_bytes)).await
}

async fn read_output(
pipe: impl tokio::io::AsyncRead + Unpin,
max_bytes: Option<usize>,
) -> std::io::Result<Vec<u8>> {
use tokio::io::AsyncReadExt;
let limit = match max_bytes {
Some(limit) => limit.checked_add(1).ok_or_else(|| {
std::io::Error::new(std::io::ErrorKind::InvalidInput, "Invalid Git output limit")
})? as u64,
None => u64::MAX,
};
let mut bytes = Vec::new();
pipe.take(limit).read_to_end(&mut bytes).await?;
if max_bytes.is_some_and(|limit| bytes.len() > limit) {
return Err(std::io::Error::other("Git output limit exceeded"));
}
Ok(bytes)
}

async fn output_with_limit(
command: &mut tokio::process::Command,
input: Option<&[u8]>,
max_bytes: Option<usize>,
) -> std::io::Result<std::process::Output> {
use std::process::Stdio;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::io::AsyncWriteExt;

command
.stdin(if input.is_some() {
Expand All @@ -177,8 +227,15 @@ pub(crate) async fn output(
} else {
command.spawn()?
};
let mut group =
crate::process_group::GroupGuard::new(child.id().filter(|_| isolated).map(|id| id as i32));
let pgid = child.id().filter(|_| isolated).map(|id| id as i32);
let mut group = if ISOLATE_PROCESSES
.try_with(|mode| matches!(mode, Isolation::SharedWriter))
.unwrap_or(false)
{
crate::process_group::GroupGuard::shared_writer(pgid)
} else {
crate::process_group::GroupGuard::new(pgid)
};
let stdin = child.stdin.take();
let stdout = child.stdout.take();
let stderr = child.stderr.take();
Expand All @@ -192,12 +249,13 @@ pub(crate) async fn output(
Ok::<_, std::io::Error>(result)
};
let read = async {
let (Some(mut stdout), Some(mut stderr)) = (stdout, stderr) else {
let (Some(stdout), Some(stderr)) = (stdout, stderr) else {
return Err(std::io::Error::other("Git output pipes are missing"));
};
let (mut out, mut err) = (Vec::new(), Vec::new());
tokio::try_join!(stdout.read_to_end(&mut out), stderr.read_to_end(&mut err))?;
Ok::<_, std::io::Error>((out, err))
tokio::try_join!(
read_output(stdout, max_bytes),
read_output(stderr, max_bytes)
)
};
let (write_result, (stdout, stderr), status) =
tokio::try_join!(write, read, wait_for_exit(&mut child, &mut group, isolated))?;
Expand Down Expand Up @@ -288,6 +346,37 @@ mod tests {
Ok(())
}

#[tokio::test]
async fn bounded_output_rejects_excess_on_either_stream() -> anyhow::Result<()> {
for isolated in [false, true] {
for redirect in ["", ">&2"] {
let mut command = tokio::process::Command::new("sh");
command.kill_on_drop(true).args([
"-c",
&format!("head -c 1048576 /dev/zero {redirect}; exec sleep 300"),
]);
let result = tokio::time::timeout(std::time::Duration::from_secs(10), async {
if isolated {
with_isolated_processes(output_limited(&mut command, 4096)).await
} else {
output_limited(&mut command, 4096).await
}
})
.await?;
assert_eq!(result.unwrap_err().to_string(), "Git output limit exceeded");
}
}
let mut command = tokio::process::Command::new("sh");
command
.kill_on_drop(true)
.args(["-c", "printf done; printf warn >&2"]);
let output = output_limited(&mut command, 4).await?;
assert!(output.status.success());
assert_eq!(output.stdout, b"done");
assert_eq!(output.stderr, b"warn");
Ok(())
}

#[tokio::test]
async fn process_isolation_is_scoped_to_preparation() -> anyhow::Result<()> {
for isolated in [false, true] {
Expand Down
Loading
Loading