diff --git a/crates/aien-omega-compose/build.rs b/crates/aien-omega-compose/build.rs index 3d64938b..45569c97 100644 --- a/crates/aien-omega-compose/build.rs +++ b/crates/aien-omega-compose/build.rs @@ -21,6 +21,7 @@ use std::process::Command; fn main() { println!("cargo:rustc-check-cfg=cfg(has_omega_compose)"); + println!("cargo:rustc-check-cfg=cfg(has_omega_wait_ms)"); for v in [ "AIEN_FORCE_CPU_STUB", "AIEN_OMEGA_COMPOSE_LIB", @@ -63,6 +64,7 @@ fn main() { "AIEN_OMEGA_COMPOSE_LIB {} is not a file", lib.display() ); + require_wait_ms_symbol(&lib); link(&lib); return; } @@ -110,9 +112,68 @@ fn main() { "make librx_compose.a failed in {}", dir.display() ); + detect_wait_ms(&dir); + require_wait_ms_symbol(&out.join("librx_compose.a")); link(&out.join("librx_compose.a")); } +/// Check the omega checkout's host header. omega.lock pins a commit that +/// declares `rxc_host_set_wait_ms`, so a real link without it is a build error, never a silent +/// downgrade (the 120 s document budget would be refused at runtime). +fn detect_wait_ms(dir: &Path) { + let h = dir.join("src/runtime/rxc_host_abi.h"); + let text = + std::fs::read_to_string(&h).unwrap_or_else(|e| panic!("cannot read {}: {e}", h.display())); + assert!( + header_declares_wait_ms(&text), + "omega header {} does not declare rxc_host_set_wait_ms; omega.lock pins a commit that has it, so this checkout is not usable. Use AIEN_FORCE_CPU_STUB=1 for a stub build.", + h.display() + ); +} + +/// A real declaration, not a mention in a comment: a line that starts with +/// `int rxc_host_set_wait_ms(`. +fn header_declares_wait_ms(header: &str) -> bool { + header + .lines() + .any(|l| l.trim_start().starts_with("int rxc_host_set_wait_ms(")) +} + +/// Fail the build unless the linked archive defines `rxc_host_set_wait_ms` (checked with `nm` +/// on both the make path and a prebuilt `AIEN_OMEGA_COMPOSE_LIB`), then set `has_omega_wait_ms`. +fn require_wait_ms_symbol(lib: &Path) { + let out = Command::new("nm") + .arg("-g") + .arg("--defined-only") + .arg(lib) + .output() + .unwrap_or_else(|e| { + panic!( + "cannot run `nm` to check {} for rxc_host_set_wait_ms ({e}); install binutils or use AIEN_FORCE_CPU_STUB=1", + lib.display() + ) + }); + assert!( + out.status.success(), + "`nm` failed on {}: {}", + lib.display(), + String::from_utf8_lossy(&out.stderr) + ); + let text = String::from_utf8_lossy(&out.stdout); + assert!( + archive_defines_wait_ms(&text), + "{} does not define rxc_host_set_wait_ms; omega.lock pins a commit that has it. Rebuild the archive from that omega, or use AIEN_FORCE_CPU_STUB=1 for a stub build.", + lib.display() + ); + println!("cargo:rustc-cfg=has_omega_wait_ms"); +} + +fn archive_defines_wait_ms(nm_out: &str) -> bool { + nm_out + .lines() + .any(|l| l.split_whitespace().last() == Some("rxc_host_set_wait_ms")) +} + fn link(lib: &Path) { let dir = lib.parent().expect("lib has a parent dir"); println!("cargo:rustc-link-search=native={}", dir.display()); diff --git a/crates/aien-omega-compose/src/ffi.rs b/crates/aien-omega-compose/src/ffi.rs index a2ce401d..88ca3eb5 100644 --- a/crates/aien-omega-compose/src/ffi.rs +++ b/crates/aien-omega-compose/src/ffi.rs @@ -182,3 +182,14 @@ extern "C" { ) -> c_int; pub fn rxc_host_close(h: *mut RxcHost); } + +// Present only when the omega checkout exposes it (build.rs sets +// `has_omega_wait_ms` after finding the symbol in rxc_host_abi.h). +#[cfg(has_omega_wait_ms)] +extern "C" { + /// Wraps omega `rx_compose_set_wait_ms` on the handle's composition. + pub fn rxc_host_set_wait_ms(h: *mut RxcHost, wait_ms: u32) -> c_int; +} + +/// omega settle wait when `rxc_host_set_wait_ms` is never called. +pub const WAIT_MS_DEFAULT: u32 = 30_000; diff --git a/crates/aien-omega-compose/src/lib.rs b/crates/aien-omega-compose/src/lib.rs index 7ef0cd96..cf4184de 100644 --- a/crates/aien-omega-compose/src/lib.rs +++ b/crates/aien-omega-compose/src/lib.rs @@ -15,6 +15,10 @@ pub mod ffi; use std::fmt; use std::path::Path; +/// The wait (ms) most recently accepted by `Compose::set_wait_ms`, 0 before any. A test +/// observation point: the value omega was actually told, not a recomputation. +pub static LAST_WAIT_MS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + /// True when `librx_compose.a` is linked (not the stub). pub const LINKED: bool = cfg!(has_omega_compose); /// The omega commit this build expected (omega.lock or `AIEN_OMEGA_COMPOSE_SHA`). @@ -257,6 +261,32 @@ mod linked { )) } + /// Set how long omega waits for a run to settle (default 30 000 ms, 1..=600 000). + /// Needs an omega that exposes `rxc_host_set_wait_ms`; against an older omega only + /// the unchanged default 30 000 ms is accepted and anything else is refused. + pub fn set_wait_ms(&mut self, wait_ms: u32) -> Result<(), ComposeError> { + #[cfg(has_omega_wait_ms)] + { + // SAFETY: valid open handle. + let rc = unsafe { ffi::rxc_host_set_wait_ms(self.h, wait_ms) }; + check(rc, 0)?; + LAST_WAIT_MS.store(wait_ms, std::sync::atomic::Ordering::SeqCst); + Ok(()) + } + #[cfg(not(has_omega_wait_ms))] + { + if wait_ms == ffi::WAIT_MS_DEFAULT { + LAST_WAIT_MS.store(wait_ms, std::sync::atomic::Ordering::SeqCst); + Ok(()) + } else { + Err(ComposeError::Arg(format!( + "wait {wait_ms} ms needs omega with rxc_host_set_wait_ms; this omega waits a fixed {} ms", + ffi::WAIT_MS_DEFAULT + ))) + } + } + } + pub fn register_skill( &mut self, name: &str, @@ -455,6 +485,9 @@ impl Compose { { Err(ComposeError::Unavailable) } + pub fn set_wait_ms(&mut self, _: u32) -> Result<(), ComposeError> { + Err(ComposeError::Unavailable) + } pub fn run(&mut self, _: u64, _: u64) -> Result { Err(ComposeError::Unavailable) } diff --git a/crates/aien-runtime/src/server.rs b/crates/aien-runtime/src/server.rs index 28ef62d3..792570f3 100644 --- a/crates/aien-runtime/src/server.rs +++ b/crates/aien-runtime/src/server.rs @@ -97,6 +97,11 @@ impl AienRuntimeServer { } } + // Bad compose limits stop the daemon here, loudly, before anything is served. + crate::spine::compose_budgets_from_env().map_err(|e| format!("compose limits: {e}"))?; + crate::spine::compose_doc_max_tokens_from_env() + .map_err(|e| format!("compose limits: {e}"))?; + let listener = UnixListener::bind(&self.socket_path).map_err(|e| { format!( "Failed to bind runtime UNIX domain socket at {}: {}", @@ -166,15 +171,22 @@ impl AienRuntimeServer { // NEXT-PHASE-1: the compose bridge (opened on the first RunComposeTask). let compose = match compose_dir_from_env() { - Ok(dir) => Some(Arc::new(ComposeBridge::new( - dir, - model_proposer( + Ok(dir) => Some(Arc::new( + ComposeBridge::new( + dir, + model_proposer( + self.spine.clone(), + self.tokenizer.clone(), + tokio::runtime::Handle::current(), + ), + "model:StreamTurn-path", + ) + .with_doc_proposer(doc_model_proposer( self.spine.clone(), self.tokenizer.clone(), tokio::runtime::Handle::current(), - ), - "model:StreamTurn-path", - ))), + )?), + )), Err(e) => { tracing::warn!("compose bridge disabled: {e}"); None @@ -463,15 +475,15 @@ async fn generate_text( }; tokio::time::timeout(limit, collect) .await - .map_err(|_| format!("model proposal exceeded {} ms", limit.as_millis()))? + .map_err(|_| crate::spine::wall_clock_reason(limit.as_millis()))? } /// The compose "model" Skill: real inference through `generate_text`, run /// from an omega World worker thread (not a tokio thread) via `block_on`. /// Greedy, at most `AIEN_COMPOSE_MAX_TOKENS` (default 48) tokens per reply; /// each call gets the limit `propose_with_retries` passes (what is left of -/// the 29 s budget, under rx_compose_run's 30 s quiescence wait), so a slow -/// model fails the Skill (no proposal) instead of failing the run. +/// the task budget: 29 s for an edit, 120 s for a document; omega waits that +/// plus 1 s), so a slow model fails the Skill (no proposal) instead of failing the run. pub fn model_proposer( spine: Arc>, tokenizer: Arc>>, @@ -481,6 +493,26 @@ pub fn model_proposer( .ok() .and_then(|v| v.trim().parse::().ok()) .unwrap_or(48); + proposer_with_cap(spine, tokenizer, handle, max_tokens) +} + +/// The proposer for full-document tasks: the same inference path with its own +/// token cap, `AIEN_COMPOSE_DOC_MAX_TOKENS` (default 1024). A bad value is refused. +pub fn doc_model_proposer( + spine: Arc>, + tokenizer: Arc>>, + handle: tokio::runtime::Handle, +) -> Result { + let cap = crate::spine::compose_doc_max_tokens_from_env()?; + Ok(proposer_with_cap(spine, tokenizer, handle, cap)) +} + +fn proposer_with_cap( + spine: Arc>, + tokenizer: Arc>>, + handle: tokio::runtime::Handle, + max_tokens: usize, +) -> ComposeProposer { Arc::new(move |prompt: &str, limit: std::time::Duration| { let messages = vec![crate::control::ChatTurn { role: "user".into(), diff --git a/crates/aien-runtime/src/spine.rs b/crates/aien-runtime/src/spine.rs index aeaa1158..28bd185b 100644 --- a/crates/aien-runtime/src/spine.rs +++ b/crates/aien-runtime/src/spine.rs @@ -839,11 +839,193 @@ pub const COMPOSE_MAX_ATTEMPTS: u32 = 3; /// Wall budget for all attempts of one task: rx_compose_run's 30 s /// quiescence wait (not raised) less a 1 s margin (ACCEPTANCE-v3 Section 3b). pub const COMPOSE_SKILL_BUDGET: std::time::Duration = std::time::Duration::from_secs(29); +/// Wall budget of a full-document task (one that creates a new file): 120 s. +pub const COMPOSE_DOC_BUDGET: std::time::Duration = std::time::Duration::from_secs(120); +/// Env: wall budget of a small edit, in ms. Unset = `COMPOSE_SKILL_BUDGET` (29 s). +pub const COMPOSE_EDIT_BUDGET_ENV: &str = "AIEN_COMPOSE_EDIT_BUDGET_MS"; +/// Env: wall budget of a full-document task, in ms. Unset = `COMPOSE_DOC_BUDGET` (120 s). +pub const COMPOSE_DOC_BUDGET_ENV: &str = "AIEN_COMPOSE_DOC_BUDGET_MS"; +/// Env: output token cap of a full-document task. Unset = `COMPOSE_DOC_MAX_TOKENS_DEFAULT`. +/// (Small edits keep `AIEN_COMPOSE_MAX_TOKENS`, read by the daemon, default 48.) +pub const COMPOSE_DOC_MAX_TOKENS_ENV: &str = "AIEN_COMPOSE_DOC_MAX_TOKENS"; +/// The one-budget setting this replaced. Setting it is refused, never ignored. +pub const COMPOSE_BUDGET_ENV_RETIRED: &str = "AIEN_COMPOSE_BUDGET_MS"; +/// Default output token cap of a full-document task. +pub const COMPOSE_DOC_MAX_TOKENS_DEFAULT: usize = 1024; +/// Accepted range of `AIEN_COMPOSE_DOC_MAX_TOKENS`. +pub const COMPOSE_DOC_MAX_TOKENS_RANGE: std::ops::RangeInclusive = 16..=4096; +/// Accepted range of both budget settings: omega waits budget + 1 000 ms and accepts at most 600 000 ms. +pub const COMPOSE_BUDGET_MS_RANGE: std::ops::RangeInclusive = 1_000..=599_000; +/// Margin between the skill budget and omega's settle wait. +pub const COMPOSE_WAIT_MARGIN: std::time::Duration = std::time::Duration::from_millis(1_000); + +/// What a compose task is, for limits: a small edit of an existing file, or +/// the creation of a whole new document. Decided by `classify_target`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ProposalKind { + Edit, + Document, +} + +/// What the goal's named target is, decided by whether the path EXISTS (not by +/// whether an edit block can be built from it). +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum TargetClass { + /// No existing file is named: the task creates a new document. + New, + /// An existing small UTF-8 file inside the workspace: path and content. + Edit(String, String), + /// An existing path that no edit block can be built for (too large, + /// non-UTF-8, unreadable, or resolving outside the workspace). Never a + /// new document, never overwritten. + Refused(String), +} + +impl TargetClass { + pub fn kind(&self) -> ProposalKind { + match self { + Self::Edit(..) => ProposalKind::Edit, + _ => ProposalKind::Document, + } + } +} + +/// The two wall budgets in force. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ComposeBudgets { + pub edit: std::time::Duration, + pub doc: std::time::Duration, +} + +impl Default for ComposeBudgets { + fn default() -> Self { + Self { + edit: COMPOSE_SKILL_BUDGET, + doc: COMPOSE_DOC_BUDGET, + } + } +} + +impl ComposeBudgets { + pub fn for_kind(&self, kind: ProposalKind) -> std::time::Duration { + match kind { + ProposalKind::Edit => self.edit, + ProposalKind::Document => self.doc, + } + } +} + +/// Parse one budget setting named `name`. `None` (unset) gives `default`; an +/// empty, non-numeric or out-of-range value is refused, never replaced by the default. +pub fn parse_compose_budget( + name: &str, + default: std::time::Duration, + v: Option<&str>, +) -> Result { + let Some(raw) = v else { + return Ok(default); + }; + let ms: u64 = raw + .trim() + .parse() + .map_err(|_| format!("{name}={raw:?} is not a whole number of milliseconds"))?; + if !COMPOSE_BUDGET_MS_RANGE.contains(&ms) { + return Err(format!( + "{name}={ms} is outside {}..={} ms", + COMPOSE_BUDGET_MS_RANGE.start(), + COMPOSE_BUDGET_MS_RANGE.end() + )); + } + Ok(std::time::Duration::from_millis(ms)) +} + +/// Parse `AIEN_COMPOSE_DOC_MAX_TOKENS` (same refusal rule as the budgets). +pub fn parse_compose_doc_max_tokens(v: Option<&str>) -> Result { + let Some(raw) = v else { + return Ok(COMPOSE_DOC_MAX_TOKENS_DEFAULT); + }; + let n: usize = raw.trim().parse().map_err(|_| { + format!("{COMPOSE_DOC_MAX_TOKENS_ENV}={raw:?} is not a whole number of tokens") + })?; + if !COMPOSE_DOC_MAX_TOKENS_RANGE.contains(&n) { + return Err(format!( + "{COMPOSE_DOC_MAX_TOKENS_ENV}={n} is outside {}..={} tokens", + COMPOSE_DOC_MAX_TOKENS_RANGE.start(), + COMPOSE_DOC_MAX_TOKENS_RANGE.end() + )); + } + Ok(n) +} + +fn env_opt(name: &str) -> Result, String> { + match std::env::var(name) { + Ok(v) => Ok(Some(v)), + Err(std::env::VarError::NotPresent) => Ok(None), + Err(e) => Err(format!("{name} unreadable: {e}")), + } +} + +/// Both budgets from the environment. Refuses the retired single-budget +/// setting (a stale `AIEN_COMPOSE_BUDGET_MS` must not be silently ignored). +pub fn compose_budgets_from_env() -> Result { + if std::env::var_os(COMPOSE_BUDGET_ENV_RETIRED).is_some() { + return Err(format!( + "{COMPOSE_BUDGET_ENV_RETIRED} is retired; set {COMPOSE_EDIT_BUDGET_ENV} and {COMPOSE_DOC_BUDGET_ENV}" + )); + } + Ok(ComposeBudgets { + edit: parse_compose_budget( + COMPOSE_EDIT_BUDGET_ENV, + COMPOSE_SKILL_BUDGET, + env_opt(COMPOSE_EDIT_BUDGET_ENV)?.as_deref(), + )?, + doc: parse_compose_budget( + COMPOSE_DOC_BUDGET_ENV, + COMPOSE_DOC_BUDGET, + env_opt(COMPOSE_DOC_BUDGET_ENV)?.as_deref(), + )?, + }) +} + +/// The document token cap from the environment. +pub fn compose_doc_max_tokens_from_env() -> Result { + parse_compose_doc_max_tokens(env_opt(COMPOSE_DOC_MAX_TOKENS_ENV)?.as_deref()) +} + +/// Stable prefix of `wall_clock_reason`: `propose_task_with_retries` classes an +/// attempt as "timeout" by it, and the token-limit cut (`length_cut_refusal`) never has it. +pub const WALL_CLOCK_REASON_PREFIX: &str = "model proposal exceeded "; + +/// Reason text of a wall-clock timeout. +pub fn wall_clock_reason(limit_ms: u128) -> String { + format!("{WALL_CLOCK_REASON_PREFIX}{limit_ms} ms") +} + /// Time one full attempt needs, from the v3 measurement: 173-token retry /// prompt prefill (2 839 + 896 ms) + 47 decode steps x 166.6 ms + 60 ms /// = 11 625 ms, rounded up (ACCEPTANCE-v3 Section 3b). Attempt k > 1 starts /// only if at least this much budget is left. pub const COMPOSE_ATTEMPT_BUDGET: std::time::Duration = std::time::Duration::from_millis(12_000); +/// Same rule for a full document. DIAGNOSTIC-LONG-1 (sovereign-core branch +/// 031756/oq3-long-diag) measured replies of 313..649 tokens finishing by +/// themselves in 28.6..61.9 s (~88 ms/token plus prefill), so a retry that +/// has to write a whole document needs about the shortest measured one: +/// 28.6 s, rounded up to 30 s. With the 120 s budget, a first attempt up to the +/// longest measured (61.9 s) leaves 58 s and still allows a retry; one that ran +/// to the token cap (1024 tokens, ~90 s) leaves ~30 s and may not. Capped at +/// half the budget so a small custom doc budget keeps the retry rule meaningful. +pub const COMPOSE_DOC_ATTEMPT_BUDGET: std::time::Duration = std::time::Duration::from_secs(30); + +/// The per-attempt budget for `kind` under wall budget `budget`. +pub fn compose_attempt_budget( + kind: ProposalKind, + budget: std::time::Duration, +) -> std::time::Duration { + match kind { + ProposalKind::Edit => COMPOSE_ATTEMPT_BUDGET, + ProposalKind::Document => COMPOSE_DOC_ATTEMPT_BUDGET.min(budget / 2), + } +} /// Assistant-response prefix of the production RunComposeTask template: the /// assistant turn starts with it and the model generates the path and the @@ -893,24 +1075,73 @@ pub const COMPOSE_EDIT_MAX_BYTES: u64 = 8192; /// Returns that path and the file's content. None when the goal names no /// existing file, so a new-file goal keeps the v5 prompt byte for byte. pub fn existing_target(goal: &str, ws: &Path) -> Option<(String, String)> { - let ws = std::fs::canonicalize(ws).ok()?; - goal.split_whitespace().find_map(|w| { + match classify_target(goal, ws) { + TargetClass::Edit(p, c) => Some((p, c)), + _ => None, + } +} + +/// Decide the task kind from whether the named target path EXISTS in the +/// workspace (same word scan and `check_relative_path` as `existing_target`). +/// A word that names an existing file or symlink decides the class: small +/// UTF-8 file inside the workspace is `Edit`; any other existing file +/// (over `COMPOSE_EDIT_MAX_BYTES`, non-UTF-8, unreadable, dangling or +/// resolving outside the workspace) is `Refused`. Words naming nothing, or +/// only a directory, are skipped; no word names a file means `New`. +pub fn classify_target(goal: &str, ws: &Path) -> TargetClass { + let Ok(ws) = std::fs::canonicalize(ws) else { + return TargetClass::New; + }; + for w in goal.split_whitespace() { let w = w .trim_matches(|c| matches!(c, '"' | '\'' | '`' | '(' | ')' | '[' | ']')) .trim_end_matches(['.', ',', ';', ':', '!', '?']) .trim_matches(|c| matches!(c, '"' | '\'' | '`' | '(' | ')' | '[' | ']')); - check_relative_path(w).ok()?; - let full = std::fs::canonicalize(ws.join(w)).ok()?; + if check_relative_path(w).is_err() { + continue; + } + let joined = ws.join(w); + // symlink_metadata: a dangling or outward symlink still EXISTS. + let Ok(lmeta) = std::fs::symlink_metadata(&joined) else { + continue; + }; + let refuse = |why: &str| { + TargetClass::Refused(format!( + "target {w} already exists but cannot be edited safely ({why}); refusing instead of treating it as a new document" + )) + }; + let full = match std::fs::canonicalize(&joined) { + Ok(f) => f, + Err(_) if lmeta.file_type().is_symlink() => return refuse("unresolvable symlink"), + Err(_) => return refuse("unresolvable path"), + }; if !full.starts_with(&ws) { - return None; + return refuse("resolves outside the workspace"); } - let meta = std::fs::metadata(&full).ok()?; - if !meta.is_file() || meta.len() > COMPOSE_EDIT_MAX_BYTES { - return None; + let Ok(meta) = std::fs::metadata(&full) else { + return refuse("unreadable"); + }; + if meta.is_dir() { + continue; } - let content = String::from_utf8(std::fs::read(&full).ok()?).ok()?; - Some((w.to_string(), content)) - }) + if !meta.is_file() { + return refuse("not a regular file"); + } + if meta.len() > COMPOSE_EDIT_MAX_BYTES { + return refuse(&format!( + "{} bytes is over the {COMPOSE_EDIT_MAX_BYTES}-byte edit limit", + meta.len() + )); + } + let Ok(bytes) = std::fs::read(&full) else { + return refuse("unreadable"); + }; + return match String::from_utf8(bytes) { + Ok(content) => TargetClass::Edit(w.to_string(), content), + Err(_) => refuse("not UTF-8 text"), + }; + } + TargetClass::New } /// The additive edit-mode block (NEXT-PHASE-1 v6 T5), appended to the fixed @@ -935,12 +1166,30 @@ pub fn task_prompt(goal: &str, ws: &Path) -> String { /// merges an edit reply into this same content, so the bytes the model saw /// are the bytes the merge keeps. pub fn task_prompt_and_target(goal: &str, ws: &Path) -> (String, Option<(String, String)>) { + let (prompt, target, _) = task_plan(goal, ws).unwrap_or_else(|_| { + ( + proposal_prompt(goal, &ws.display().to_string()), + None, + ProposalKind::Document, + ) + }); + (prompt, target) +} + +/// Prompt, edit target and kind of a task, or the refusal when the goal names +/// an existing file that no edit block can be built for. +pub fn task_plan(goal: &str, ws: &Path) -> Result { let mut prompt = proposal_prompt(goal, &ws.display().to_string()); - let target = existing_target(goal, ws); - if let Some((path, content)) = &target { - prompt.push_str(&edit_block(path, content)); + let class = classify_target(goal, ws); + let kind = class.kind(); + match class { + TargetClass::Refused(why) => Err(format!("RunComposeTask: {why}")), + TargetClass::Edit(path, content) => { + prompt.push_str(&edit_block(&path, &content)); + Ok((prompt, Some((path, content)), kind)) + } + TargetClass::New => Ok((prompt, None, kind)), } - (prompt, target) } /// Largest prior-lines x reply-lines table `merge_edit_reply` builds. @@ -1163,7 +1412,7 @@ pub fn propose_task_with_retries( } } Err(e) => { - a.outcome = if e.contains("exceeded") { + a.outcome = if e.starts_with(WALL_CLOCK_REASON_PREFIX) { "timeout" } else { "error" @@ -1229,6 +1478,8 @@ pub(crate) struct ComposeHome { mark: Option, /// seq of the last mark this home knows of (0 = none yet). mark_seq: u64, + /// Wall budgets in force; every run sets omega's wait from its own. + budgets: ComposeBudgets, } impl ComposeHome { @@ -1266,13 +1517,15 @@ impl ComposeHome { } type SkillOutput = (Result, Vec); -/// The prompt of one task and its edit target (`task_prompt_and_target`). -type TaskPrompt = (String, Option<(String, String)>); +/// The prompt of one task, its edit target and its kind (`task_plan`). +pub type TaskPrompt = (String, Option<(String, String)>, ProposalKind); /// Owns the composition home of this process. pub struct ComposeBridge { dir: PathBuf, proposer: ComposeProposer, + /// Proposer for full-document tasks (own token cap); `None` = `proposer`. + doc_proposer: Option, proposer_label: String, home: std::sync::Mutex>, /// Set when the start-up reconcile failed or was refused (ACCEPTANCE-v3 @@ -1285,12 +1538,19 @@ impl ComposeBridge { Self { dir, proposer, + doc_proposer: None, proposer_label: proposer_label.to_string(), home: std::sync::Mutex::new(None), reconcile_failed: std::sync::Mutex::new(None), } } + /// Use `doc_proposer` (its own token cap) for full-document tasks. + pub fn with_doc_proposer(mut self, doc_proposer: ComposeProposer) -> Self { + self.doc_proposer = Some(doc_proposer); + self + } + pub fn dir(&self) -> &Path { &self.dir } @@ -1303,6 +1563,9 @@ impl ComposeBridge { /// `rebuilt_from` = the seq of a mark RecoverComposeHome just set aside: /// the home then opens without a mark and gets a fresh one. fn open_home_marked(&self, rebuilt_from: Option) -> Result { + // Refuse a bad budget before anything is opened (never fall back). + let budgets = compose_budgets_from_env() + .map_err(|e| format!("compose home {} refused: {e}", self.dir.display()))?; let root = machine_root(&self.dir)?; let mark_path = cortex_mark::mark_path(&self.dir); let existing = match rebuilt_from { @@ -1318,6 +1581,12 @@ impl ComposeBridge { let (mut compose, info) = Compose::open(&self.dir, RootKind::Provisioned, &root, 0xA1E4_0001) .map_err(|e: ComposeError| refusal(&self.dir, &e))?; + // omega settles after a fixed wait. Every run sets it again to its own + // budget + 1 s (run_task_inner); here the edit value is checked once, so an + // old omega without rxc_host_set_wait_ms refuses a changed edit budget at open. + compose + .set_wait_ms((budgets.edit + COMPOSE_WAIT_MARGIN).as_millis() as u32) + .map_err(|e| refusal(&self.dir, &e))?; let plan = cortex_mark::plan( existing.as_ref(), &info.machine_id, @@ -1329,16 +1598,22 @@ impl ComposeBridge { let proposals: Arc>> = Arc::default(); let approved: Arc>> = Arc::default(); let (pr, pp, proposer) = (prompts.clone(), proposals.clone(), self.proposer.clone()); + let doc_proposer = self + .doc_proposer + .clone() + .unwrap_or_else(|| self.proposer.clone()); let pa = approved.clone(); compose .register_skill(COMPOSE_MODEL_SKILL, None, 10, move |task| { - let (prompt, target) = pr.lock().get(&task).cloned()?; + let (prompt, target, kind) = pr.lock().get(&task).cloned()?; // Proposer hook (crate::approved): an approved proposal for this // task replaces the model's reply. One attempt, the same // template check, the same AEGIS contract and commit below. // edit = None: an approved whole-file proposal never goes // through merge_edit_reply, so the committed bytes are the // approved bytes even when the path already exists. + let budget = budgets.for_kind(kind); + let attempt_budget = compose_attempt_budget(kind, budget); let fixed = pa.lock().get(&task).cloned(); let (out, attempts) = match fixed { Some(text) => { @@ -1349,26 +1624,23 @@ impl ComposeBridge { ..Default::default() }) }; - propose_task_with_retries( - &one, - &prompt, - None, - COMPOSE_SKILL_BUDGET, - COMPOSE_ATTEMPT_BUDGET, - 1, - ) + propose_task_with_retries(&one, &prompt, None, budget, attempt_budget, 1) } // Fixed template + bounded automatic retry (ACCEPTANCE-v2 3a, 3b), // measured per-attempt budget (ACCEPTANCE-v3 3b); an edit reply // is merged into the content the model was shown (v7 T5). None => { let edit = target.as_ref().map(|(p, c)| (p.as_str(), c.as_str())); + let p = match kind { + ProposalKind::Edit => &proposer, + ProposalKind::Document => &doc_proposer, + }; propose_task_with_retries( - proposer.as_ref(), + p.as_ref(), &prompt, edit, - COMPOSE_SKILL_BUDGET, - COMPOSE_ATTEMPT_BUDGET, + budget, + attempt_budget, COMPOSE_MAX_ATTEMPTS, ) } @@ -1406,6 +1678,7 @@ impl ComposeBridge { allen_gate(&self.dir, &mut compose, &info.machine_id); let mut home = ComposeHome { compose, + budgets, machine_id: hex(&info.machine_id), prompts, approved, @@ -1498,7 +1771,7 @@ impl ComposeBridge { ws.display() )); } - let prompt = task_prompt_and_target(goal, &ws); + let prompt = task_plan(goal, &ws)?; let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_err(|e| format!("clock: {e}"))?; @@ -1518,6 +1791,20 @@ impl ComposeBridge { *guard = Some(self.open_home()?); } let home = guard.as_mut().expect("opened above"); + // Deadlines agree on both sides: omega settles budget + 1 s after the run + // starts, the Skill gives up at budget. Set only here, under the lock that + // serializes runs, never while rx_compose_run is in flight. An omega without + // rxc_host_set_wait_ms refuses a budget that needs a longer wait (no silent 30 s wait). + let kind = prompt.2; + let wait = home.budgets.for_kind(kind) + COMPOSE_WAIT_MARGIN; + home.compose + .set_wait_ms(wait.as_millis() as u32) + .map_err(|e| { + format!( + "compose run refused: {kind:?} budget needs omega settle wait {} ms: {e}", + wait.as_millis() + ) + })?; if let Some(t) = approved_text { home.approved.lock().insert(task, t.to_string()); } diff --git a/crates/aien-runtime/tests/compose_env_test.rs b/crates/aien-runtime/tests/compose_env_test.rs new file mode 100644 index 00000000..58308435 --- /dev/null +++ b/crates/aien-runtime/tests/compose_env_test.rs @@ -0,0 +1,46 @@ +//! Startup refusal of compose limit settings. Its own test binary with one +//! test, because it sets process environment variables. +use aien_runtime::spine::{compose_budgets_from_env, compose_doc_max_tokens_from_env}; +use std::time::Duration; + +#[test] +fn environment_limits_are_read_and_bad_ones_refused() { + let all = [ + "AIEN_COMPOSE_EDIT_BUDGET_MS", + "AIEN_COMPOSE_DOC_BUDGET_MS", + "AIEN_COMPOSE_DOC_MAX_TOKENS", + "AIEN_COMPOSE_BUDGET_MS", + ]; + for k in all { + std::env::remove_var(k); + } + let b = compose_budgets_from_env().expect("defaults"); + assert_eq!(b.edit, Duration::from_secs(29)); + assert_eq!(b.doc, Duration::from_secs(120)); + assert_eq!(compose_doc_max_tokens_from_env(), Ok(1024)); + + std::env::set_var("AIEN_COMPOSE_DOC_BUDGET_MS", "90000"); + std::env::set_var("AIEN_COMPOSE_DOC_MAX_TOKENS", "512"); + assert_eq!( + compose_budgets_from_env().expect("set").doc, + Duration::from_secs(90) + ); + assert_eq!(compose_doc_max_tokens_from_env(), Ok(512)); + + std::env::set_var("AIEN_COMPOSE_DOC_BUDGET_MS", "5"); + assert!(compose_budgets_from_env() + .expect_err("out of range") + .contains("AIEN_COMPOSE_DOC_BUDGET_MS")); + std::env::set_var("AIEN_COMPOSE_DOC_BUDGET_MS", "90000"); + std::env::set_var("AIEN_COMPOSE_DOC_MAX_TOKENS", "0"); + assert!(compose_doc_max_tokens_from_env().is_err()); + + // the retired single-budget name is refused, not ignored + std::env::set_var("AIEN_COMPOSE_BUDGET_MS", "29000"); + assert!(compose_budgets_from_env() + .expect_err("retired") + .contains("retired")); + for k in all { + std::env::remove_var(k); + } +} diff --git a/crates/aien-runtime/tests/compose_task_test.rs b/crates/aien-runtime/tests/compose_task_test.rs index 172f8dd7..303116dc 100644 --- a/crates/aien-runtime/tests/compose_task_test.rs +++ b/crates/aien-runtime/tests/compose_task_test.rs @@ -6,8 +6,11 @@ //! in a stub build they check that the bridge reports the missing library. use aien_runtime::control::{ComposeRecallReport, ComposeTaskReport, ControlResponse}; use aien_runtime::spine::{ - check_file_proposal, parse_file_proposal, propose_with_retries, ComposeBridge, ComposeProposer, - Generation, COMPOSE_ATTEMPT_BUDGET, COMPOSE_MAX_ATTEMPTS, COMPOSE_SKILL_BUDGET, + check_file_proposal, compose_attempt_budget, parse_compose_budget, + parse_compose_doc_max_tokens, parse_file_proposal, propose_with_retries, wall_clock_reason, + ComposeBridge, ComposeBudgets, ComposeProposer, Generation, ProposalKind, + COMPOSE_ATTEMPT_BUDGET, COMPOSE_DOC_BUDGET, COMPOSE_MAX_ATTEMPTS, COMPOSE_SKILL_BUDGET, + COMPOSE_WAIT_MARGIN, }; use std::sync::Arc; @@ -422,6 +425,7 @@ ok fn measured_attempt_budget_admits_a_second_attempt() { use std::time::Duration; assert!(COMPOSE_SKILL_BUDGET < Duration::from_secs(30)); + // the default (AIEN_COMPOSE_EDIT_BUDGET_MS unset): omega's 30 s wait less 1 s assert_eq!(COMPOSE_SKILL_BUDGET, Duration::from_secs(29)); assert_eq!(COMPOSE_ATTEMPT_BUDGET, Duration::from_millis(12_000)); // 2 839 + 896 + 47 x 166.6 + 60 ms, the measured full retry attempt @@ -683,3 +687,135 @@ fn proposal_fence_many_examples_and_trailing_text_keep_every_byte() { let p = check_file_proposal(&format!("filename: g.md\n{doc}")).unwrap(); assert_eq!(p.content, doc); } + +/// Both budget settings: unset gives the default; 1 000..=599 000 ms is +/// accepted; anything else is refused with a message naming the setting. +#[test] +fn compose_budget_settings_parse_and_refuse() { + use std::time::Duration; + let edit = |v| parse_compose_budget("AIEN_COMPOSE_EDIT_BUDGET_MS", COMPOSE_SKILL_BUDGET, v); + let doc = |v| parse_compose_budget("AIEN_COMPOSE_DOC_BUDGET_MS", COMPOSE_DOC_BUDGET, v); + assert_eq!(edit(None), Ok(Duration::from_secs(29))); + assert_eq!(doc(None), Ok(Duration::from_secs(120))); + assert_eq!(edit(Some("29000")), Ok(COMPOSE_SKILL_BUDGET)); + assert_eq!(doc(Some("90000")), Ok(Duration::from_secs(90))); + assert_eq!(doc(Some(" 1000 ")), Ok(Duration::from_secs(1))); + assert_eq!(doc(Some("599000")), Ok(Duration::from_millis(599_000))); + for bad in [ + "", + "abc", + "-5", + "1.5", + "999", + "0", + "599001", + "600000", + "99999999999999999999", + ] { + let e = edit(Some(bad)).expect_err(bad); + assert!(e.contains("AIEN_COMPOSE_EDIT_BUDGET_MS"), "{bad}: {e}"); + let e = doc(Some(bad)).expect_err(bad); + assert!(e.contains("AIEN_COMPOSE_DOC_BUDGET_MS"), "{bad}: {e}"); + } +} + +/// AIEN_COMPOSE_DOC_MAX_TOKENS: default 1024, 16..=4096, bad values refused. +#[test] +fn compose_doc_token_cap_parses_and_refuses() { + assert_eq!(parse_compose_doc_max_tokens(None), Ok(1024)); + assert_eq!(parse_compose_doc_max_tokens(Some("16")), Ok(16)); + assert_eq!(parse_compose_doc_max_tokens(Some(" 4096 ")), Ok(4096)); + for bad in ["", "x", "-1", "15", "0", "4097", "1e3"] { + let e = parse_compose_doc_max_tokens(Some(bad)).expect_err(bad); + assert!(e.contains("AIEN_COMPOSE_DOC_MAX_TOKENS"), "{bad}: {e}"); + } +} + +/// A task that names an existing file is an edit (29 s); a task with no +/// existing target creates a new document (120 s). Omega's wait follows by +1 s. +#[test] +fn kind_selects_budget() { + use std::time::Duration; + let ws = tempfile::tempdir().expect("tempdir"); + std::fs::write(ws.path().join("notes.md"), "# notes\n").expect("write"); + let (_, _, edit_kind) = + aien_runtime::spine::task_plan("add a line to notes.md", ws.path()).expect("plan"); + let (_, _, new_kind) = + aien_runtime::spine::task_plan("write a new file faq.md", ws.path()).expect("plan"); + assert_eq!(edit_kind, ProposalKind::Edit); + assert_eq!(new_kind, ProposalKind::Document); + let b = ComposeBudgets::default(); + assert_eq!(b.for_kind(ProposalKind::Edit), Duration::from_secs(29)); + assert_eq!(b.for_kind(ProposalKind::Document), Duration::from_secs(120)); + assert_eq!( + b.for_kind(ProposalKind::Document) + COMPOSE_WAIT_MARGIN, + Duration::from_millis(121_000) + ); + // edits keep the measured 12 s attempt budget; documents need ~the shortest + // measured full document (30 s), capped at half a small custom budget + assert_eq!( + compose_attempt_budget(ProposalKind::Edit, b.edit), + COMPOSE_ATTEMPT_BUDGET + ); + assert_eq!( + compose_attempt_budget(ProposalKind::Document, b.doc), + Duration::from_secs(30) + ); + assert_eq!( + compose_attempt_budget(ProposalKind::Document, Duration::from_secs(20)), + Duration::from_secs(10) + ); +} + +/// The two ways a long reply can fail leave different, stable reasons: a cut +/// at the token limit is refused ("reply cut at the token limit ... +/// finish_reason max_tokens"), a slow model times out ("model proposal +/// exceeded N ms"). Neither text contains the other's marker. +#[test] +fn token_cut_and_wall_clock_reasons_are_distinct() { + use std::time::Duration; + // token-limit cut + let cut = |_: &str, _: Duration| { + Ok(Generation { + text: "filename: a.md\nline\n".into(), + tokens: 1024, + finish_reason: Some("max_tokens".into()), + ..Default::default() + }) + }; + let (out, a) = propose_with_retries( + &cut, + "p", + Duration::from_secs(120), + Duration::from_secs(30), + 1, + ); + let why = out.expect_err("a cut reply is never a proposal"); + assert_eq!(a[0].outcome, "refused"); + assert!( + why.contains("reply cut at the token limit after 1024 tokens (finish_reason max_tokens)"), + "{why}" + ); + assert!(!why.contains("exceeded"), "{why}"); + // wall-clock timeout (the text the daemon proposer emits) + let slow = |_: &str, limit: Duration| -> Result { + Err(wall_clock_reason(limit.as_millis())) + }; + let (out, a) = propose_with_retries( + &slow, + "p", + Duration::from_secs(120), + Duration::from_secs(30), + 1, + ); + let why = out.expect_err("timed out"); + assert_eq!(a[0].outcome, "timeout"); + assert!( + why.starts_with("model proposal exceeded ") && why.ends_with(" ms"), + "{why}" + ); + assert!( + !why.contains("token limit") && !why.contains("max_tokens"), + "{why}" + ); +} diff --git a/crates/aien-runtime/tests/compose_wait_test.rs b/crates/aien-runtime/tests/compose_wait_test.rs new file mode 100644 index 00000000..602f2957 --- /dev/null +++ b/crates/aien-runtime/tests/compose_wait_test.rs @@ -0,0 +1,148 @@ +//! The omega settle wait really set before each run, and the target-kind +//! decision (existing path => Edit/refused, missing path => Document). +//! One test binary, one wait test: `LAST_WAIT_MS` is process-global. +use aien_runtime::control::ControlResponse; +use aien_runtime::spine::{ + classify_target, propose_task_with_retries, task_plan, ComposeBridge, ComposeBudgets, + ComposeProposer, Generation, ProposalKind, TargetClass, COMPOSE_WAIT_MARGIN, +}; +use std::sync::atomic::Ordering; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +/// Linked build only: run_task_inner tells omega budget + 1000 ms for each +/// kind before compose.run (observed inside the proposer, i.e. during the run). +#[test] +#[cfg_attr(not(compose_linked), ignore = "needs librx_compose.a: stub build")] +fn run_task_sets_omega_wait_to_budget_plus_margin_for_both_kinds() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + std::fs::write(ws.join("notes.md"), "# notes\n").unwrap(); + let seen: Arc>> = Arc::default(); + let s = seen.clone(); + let proposer: ComposeProposer = Arc::new(move |_p: &str, _l: Duration| { + s.lock() + .unwrap() + .push(aien_omega_compose::LAST_WAIT_MS.load(Ordering::SeqCst)); + Ok(Generation { + text: "filename: faq.md\nconstraint: x\n".into(), + tokens: 4, + finish_reason: Some("eos".into()), + ..Default::default() + }) + }); + let b = ComposeBudgets::default(); + let bridge = ComposeBridge::new(tmp.path().join("home"), proposer, "test:wait"); + for goal in ["add a line to notes.md", "write a new file faq.md"] { + match bridge.run_task(goal, ws.to_str().unwrap()) { + ControlResponse::ComposeTaskResult(_) | ControlResponse::Error(_) => {} + other => panic!("{other:?}"), + } + } + let seen = seen.lock().unwrap().clone(); + let want = |k| (b.for_kind(k) + COMPOSE_WAIT_MARGIN).as_millis() as u32; + assert_eq!( + seen, + vec![want(ProposalKind::Edit), want(ProposalKind::Document)], + "wait seen during each run: edit 30000, document 121000" + ); +} + +/// One deadline across attempts: each retry is given only what is left of +/// the document budget, never a fresh budget. +#[test] +fn one_deadline_is_shared_across_attempts() { + let limits: Mutex> = Mutex::default(); + let proposer = |_: &str, l: Duration| { + limits.lock().unwrap().push(l); + std::thread::sleep(Duration::from_millis(60)); + Ok(Generation { + text: "not a proposal".into(), + tokens: 2, + finish_reason: Some("eos".into()), + ..Default::default() + }) + }; + let budget = Duration::from_millis(400); + let (out, a) = propose_task_with_retries( + &proposer, + "base", + None, + budget, + Duration::from_millis(50), + 3, + ); + assert!(out.is_err()); + let l = limits.lock().unwrap().clone(); + assert!(l.len() >= 2, "{l:?}"); + assert!(l[0] <= budget); + for w in l.windows(2) { + assert!(w[1] + Duration::from_millis(55) <= w[0], "{l:?}"); + } + assert_eq!(a.len(), l.len()); +} + +fn ws_with(files: &[(&str, &[u8])]) -> (tempfile::TempDir, std::path::PathBuf) { + let d = tempfile::tempdir().unwrap(); + let ws = d.path().join("ws"); + std::fs::create_dir_all(&ws).unwrap(); + for (n, c) in files { + std::fs::write(ws.join(n), c).unwrap(); + } + let ws = std::fs::canonicalize(ws).unwrap(); + (d, ws) +} + +#[test] +fn missing_file_is_document() { + let (_d, ws) = ws_with(&[]); + assert_eq!(classify_target("write faq.md", &ws), TargetClass::New); + let (_, t, k) = task_plan("write faq.md", &ws).unwrap(); + assert_eq!((t, k), (None, ProposalKind::Document)); +} + +#[test] +fn small_existing_file_is_edit() { + let (_d, ws) = ws_with(&[("notes.md", b"# notes\n")]); + let (p, t, k) = task_plan("add a line to notes.md", &ws).unwrap(); + assert_eq!(k, ProposalKind::Edit); + assert_eq!(t, Some(("notes.md".into(), "# notes\n".into()))); + assert!(p.contains("already exists")); +} + +#[test] +fn large_existing_file_is_refused_not_document() { + let big = vec![b'a'; 11 * 1024]; + let (_d, ws) = ws_with(&[("big.md", &big)]); + let e = task_plan("rewrite big.md", &ws).unwrap_err(); + assert!(e.contains("big.md") && e.contains("already exists"), "{e}"); + assert!(matches!( + classify_target("rewrite big.md", &ws), + TargetClass::Refused(_) + )); + assert_eq!(std::fs::read(ws.join("big.md")).unwrap(), big); +} + +#[test] +fn non_utf8_existing_file_is_refused() { + let (_d, ws) = ws_with(&[("bin.md", &[0xff, 0xfe, 0x00, 0x80])]); + let e = task_plan("rewrite bin.md", &ws).unwrap_err(); + assert!(e.contains("not UTF-8"), "{e}"); +} + +#[test] +fn outward_symlink_is_refused_and_directory_is_skipped() { + let d = tempfile::tempdir().unwrap(); + let outside = d.path().join("secret.txt"); + std::fs::write(&outside, "s\n").unwrap(); + let ws = d.path().join("ws"); + std::fs::create_dir_all(ws.join("docs")).unwrap(); + std::os::unix::fs::symlink(&outside, ws.join("link.md")).unwrap(); + let ws = std::fs::canonicalize(ws).unwrap(); + assert!(task_plan("rewrite link.md", &ws).is_err()); + assert_eq!( + classify_target("put it in docs faq.md", &ws), + TargetClass::New + ); +} diff --git a/omega.lock b/omega.lock index 0ca61039..b8b87611 100644 --- a/omega.lock +++ b/omega.lock @@ -1 +1 @@ -459b46133550a39ed391ea11eeb5aa5968052611 +01f6a74636b8383b010cdb95597839582c415c27