From 248e9e40ff4e0dde9eccfe16524c64c18b38685e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=86=90=EC=84=B1=EC=A4=80?= Date: Sun, 29 Nov 2026 21:02:36 +0900 Subject: [PATCH 1/3] =?UTF-8?q?ADR-0097=20=EC=B4=88=EC=95=88:=20=EC=9A=94?= =?UTF-8?q?=EC=B2=AD=20=ED=95=9C=EB=8F=84=20=EC=95=88=EC=97=90=EC=84=9C=20?= =?UTF-8?q?=EB=8F=84=EA=B5=AC=20=EC=B6=9C=EB=A0=A5=20=EC=A0=84=EB=8B=AC?= =?UTF-8?q?=ED=95=98=EA=B8=B0(=EC=A0=9C=EC=95=88)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Terminal-Bench 2.1 약한 모델 측정에서 끝난 73과업 중 실패 47개의 57%(27개)가 request_too_large로 Run이 끝났다. 평균 구성은 toolOutputs 74 KB, capabilities 22 KB, steps 14 KB다. 원인은 둘이다. planning context 예산 (512 KiB)과 agy transport 한도(100,000바이트)가 따로 있다. 그리고 도구 출력은 packing 대상이 아니라 항상 원문 전부가 들어간다. 1단계 제안: planner port 한도를 예산의 단일 출처로 쓰고, 넘칠 때만 오래된 출력 본문을 stub으로 바꾼다(최근 3개 보존, 75%까지 내려 cache 보존). 한도 안의 요청은 바이트가 같다. 생략 순서는 설계 14·held-out 13 과업으로 측정해 고른다. Co-Authored-By: Claude Opus 5.5 --- ...97-request-bounded-tool-output-delivery.md | 97 +++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 docs/adr/0097-request-bounded-tool-output-delivery.md diff --git a/docs/adr/0097-request-bounded-tool-output-delivery.md b/docs/adr/0097-request-bounded-tool-output-delivery.md new file mode 100644 index 0000000..a501c66 --- /dev/null +++ b/docs/adr/0097-request-bounded-tool-output-delivery.md @@ -0,0 +1,97 @@ +# ADR-0097: 요청 한도 안에서 도구 출력 전달하기 + +- 날짜: 2026-11-29 +- 상태: 제안(사용자 검토 대기). 구현 전. +- 변경 분류: 범용 planning context. 특정 과업·언어·모델 규칙 없음. +- protocol·journal 변경: 없음. 한도 안의 요청은 바이트가 그대로다. 한도를 넘던 요청만 바뀐다. + +## 문제 + +약한 모델 하네스 연구(Terminal-Bench 2.1, agy `gemini-3.8-flash-low`)에서 끝난 73과업 중 47개가 실패했다. +그중 27개(57%)는 Run이 `model_rejected.request_too_large`로 끝났다. 모델이 일을 계속할 수 있었는데도 host가 +요청을 보내지 못해 멈췄다. + +27개 요청의 평균 구성: + +| 부분 | 평균 크기 | +|---|---| +| `toolOutputs` (지난 도구 출력 원문) | 74 KB | +| `capabilities` (도구 설명, Run 동안 같음) | 22 KB | +| `steps` | 14 KB | +| system prompt | 3 KB | + +원인은 두 가지다. + +1. **한도가 두 곳에 따로 있다.** + - planning context 예산은 manifest의 `max_context_bytes`(512 KiB)다. + - transport 한도는 따로 있다. HTTP provider는 요청 1 MiB라 예산과 맞는다. agy transport는 prompt 100,000바이트다. + - context builder는 512 KiB 안이면 괜찮다고 보고 만들고, agy transport가 그 요청을 거절한다. 거절은 결정적이라 + 재시도해도 같고 Run이 끝난다. +2. **도구 출력은 줄일 수 없는 항목이다.** + - `steps`와 `capabilities`는 예산에 맞춰 round-robin으로 넣고, 못 넣은 개수를 `omitted*`로 남긴다. + - `toolOutputs`는 항상 전부 원문이다. 출력이 쌓이면 다른 항목을 다 빼도 넘친다. + +## 선례: 출력을 숨기면 회귀가 난다 + +ADR-0069는 나중에 바뀐 자원의 옛 관찰을 숨겼다가 held-out에서 회귀를 봤다. 첫 패키지 검색 결과를 할 일 목록으로 +쓰던 모델이 그 결과를 잃고 일부만 다시 찾은 뒤 완료를 선언했다. 그래서 0069는 출력을 남기고 표시만 붙였다. + +이번 제안도 같은 위험이 있다. 다만 지금은 한도를 넘는 순간 Run이 끝난다. 그래서 1단계는 "Run을 끝내는 대신 +일부를 생략"으로 한정한다. 한도 안의 요청은 건드리지 않는다. + +## 결정 (제안) + +### 1단계: 한도를 한 곳에서 정하고, 넘칠 때만 오래된 출력 본문을 생략 + +1. **예산의 단일 출처.** Planner port가 한 요청에 담을 수 있는 최대 바이트를 알린다. + - HTTP: 기존 `max_request_bytes` + - agy: prompt 한도 100,000바이트 + - context builder는 `min(manifest max_context_bytes, port 한도 − 고정 overhead)`를 예산으로 쓴다. + - overhead는 system prompt, 요청 envelope(`callId`, `requestDigest` 등), agy 머리말·맺음말이다. 실제 직렬화 + 크기로 계산하고, 상수로 어림하지 않는다. +2. **넘칠 때만 생략.** `toolOutputs`·`steps`·`capabilities`를 모두 넣어 예산 안이면 지금과 바이트가 같다. 넘치면: + - 가장 오래된 출력부터 본문(`output`)을 빼고 stub을 남긴다. + - stub 필드: `stepId`, `capability`, `outputDigest`, `canonicalSizeBytes`, `elided: true`, 고정 문장 + `elidedMeaning` ("This output was omitted to fit the request limit. Run an equivalent read again if you need + its current content.") + - 최근 출력 3개는 생략하지 않는다. + - 출력을 다 줄여도 넘치면 기존 `steps`·`capabilities` packing으로 넘어간다. 그래도 넘치면 지금처럼 거절한다. +3. **prefix cache.** 생략은 앞쪽 항목을 바꾼다(ADR-0036, 0072). 한 번 넘칠 때 예산의 75%까지 내려 생략한다. + 그러면 다음 여러 호출 동안 앞부분이 그대로라 cache를 다시 쓴다. +4. **journal·Receipt.** 원문은 journal과 tool_outputs 저장소에 그대로 있다. 생략은 모델에 보내는 view에서만 + 일어난다. context digest는 실제로 보낸 payload의 digest다. + +### 2단계(실험, 1단계 측정 뒤 별도 결정): 생략 순서 + +1단계 기본은 오래된 순서다. 비교할 후보는 다음과 같다. + +- A: 오래된 순서(1단계 기본) +- B: `supersededBy`가 붙은 출력 먼저, 그다음 오래된 순서 +- C: 큰 출력 먼저 + +ADR-0069의 회귀를 보면 넓은 검색 결과를 잃는 게 위험하다. 그래서 순서는 측정으로 고른다. + +### 범위 밖 + +- HTTP provider에서 한도보다 훨씬 작은 "주의 예산"을 둘지는 별도 연구 질문이다. 약한 모델에 74 KB 출력이 + 도움이 되는지 해가 되는지는 아직 데이터가 없다. 1단계 뒤 같은 과업으로 측정한다. +- 출력 요약(모델 호출이 하나 더 필요함)은 하지 않는다. + +## 측정 계획 + +- **설계·held-out 분리:** `request_too_large`로 끝난 27과업을 이름 해시로 둘로 나눈다(설계 14, held-out 13). + 설계 쪽으로만 세부를 고르고, held-out에서 개선이 유지돼야 채택한다. +- **회귀 확인:** 한도를 넘지 않은 과업은 모델 요청 비교(`scripts/diff-model-requests.py`)로 바이트 동일을 확인한다. +- **지표:** + - 통과율 + - 종료 이유 분포 + - 과업당 모델 호출 수·입력 토큰 + - 생략이 일어난 호출 비율 + - 생략 뒤 같은 read를 다시 한 횟수 +- 같은 과업을 2회 반복해 흔들림을 본다. + +## 예상 한계 + +- 생략된 출력이 할 일 목록 역할을 했다면 ADR-0069처럼 일찍 완료를 선언할 수 있다. 1단계에서는 원래 Run이 끝나던 + 경우에만 생기는 변화라 통과율이 내려갈 수는 없다. 대신 "완료 주장 후 검증 실패"로 옮겨 갈 수 있으니 따로 센다. +- `capabilities` 22 KB도 매 요청 들어간다. 줄이는 건 이 ADR 범위가 아니다. From cf3b15c5fd53632d1f8e1982643ecfac13c097c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=86=90=EC=84=B1=EC=A4=80?= Date: Sun, 29 Nov 2026 22:08:11 +0900 Subject: [PATCH 2/3] =?UTF-8?q?=EC=9A=94=EC=B2=AD=20=ED=95=9C=EB=8F=84?= =?UTF-8?q?=EB=A5=BC=20=EB=84=98=EC=9D=84=20=EB=95=8C=EB=A7=8C=20=EC=98=A4?= =?UTF-8?q?=EB=9E=98=EB=90=9C=20=EB=8F=84=EA=B5=AC=20=EC=B6=9C=EB=A0=A5=20?= =?UTF-8?q?=EB=B3=B8=EB=AC=B8=EC=9D=84=20=EC=83=9D=EB=9E=B5(ADR-0097=201?= =?UTF-8?q?=EB=8B=A8=EA=B3=84)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Terminal-Bench 2.1 약한 모델 실험에서 실패 47개 중 27개가 request_too_large로 끝났다. planning 예산(512 KiB)과 agy prompt 한도(100,000바이트)가 따로 있었고, toolOutputs는 packing 대상이 아니라 평균 74 KB가 항상 원문으로 들어갔다. - PlannerPort::max_context_bytes로 transport 한도를 context builder에 알린다. agy는 prompt_limit(), HTTP는 XGEN_OPENAI_MAX_PROMPT_BYTES(16 KiB~1 MiB)로만 켠다. 한도 = prompt 한도 - system prompt 길이 - envelope 여유 2,048바이트. - 넘칠 때만 최근 3개를 뺀 오래된 출력부터 본문을 빼고 elided stub과 고정 문장을 남긴다. 넘친 양을 예산 1/4 단위로 올림해 생략 앞부분을 고정, prefix cache 재사용을 지킨다. - 원문은 journal·tool_outputs에 그대로 있고 모델에 보내는 view만 바뀐다. 검증: cargo test --workspace 실패 0, clippy -D warnings 통과, 새 테스트 3개. diff-model-requests base/head 8개 사례 모두 차이 0(한도 안 요청 바이트 동일). Co-Authored-By: Claude Opus 5.5 --- .../examples/planning_boundary_probe/main.rs | 9 +- crates/xgen-cli/src/agy.rs | 4 +- crates/xgen-cli/src/composition.rs | 41 ++++- crates/xgen-cli/src/final_response.rs | 3 + crates/xgen-provider-openai/src/lib.rs | 26 +++ crates/xgen-runtime/src/agent_loop.rs | 170 +++++++++++++++++- ...97-request-bounded-tool-output-delivery.md | 19 +- docs/getting-started.md | 4 + 8 files changed, 255 insertions(+), 21 deletions(-) diff --git a/crates/xgen-cli/examples/planning_boundary_probe/main.rs b/crates/xgen-cli/examples/planning_boundary_probe/main.rs index 9101b17..2a6cbf9 100644 --- a/crates/xgen-cli/examples/planning_boundary_probe/main.rs +++ b/crates/xgen-cli/examples/planning_boundary_probe/main.rs @@ -145,10 +145,15 @@ impl PlannerPort for Planner { let mut completed = BTreeMap::new(); for output in request.context().tool_outputs() { completed.insert( - output.output()["operation"].as_str().unwrap().to_owned(), + output.output().expect("probe outputs are not elided")["operation"] + .as_str() + .unwrap() + .to_owned(), output.step_id().to_owned(), ); - if let Some(next) = output.output()["value"].get("next") { + if let Some(next) = + output.output().expect("probe outputs are not elided")["value"].get("next") + { visible.extend( serde_json::from_value::>(next.clone()) .map_err(|_| PlannerPortFailure::Unavailable)?, diff --git a/crates/xgen-cli/src/agy.rs b/crates/xgen-cli/src/agy.rs index 2fe560c..502bd0d 100644 --- a/crates/xgen-cli/src/agy.rs +++ b/crates/xgen-cli/src/agy.rs @@ -217,7 +217,9 @@ fn settings(workspace: &str) -> Value { "allowNonWorkspaceAccess":false,"disableSlashCommands":true,"useG1Credits":false,"notifications":false, "permissions":{"deny":["command(*)","read_file(*)","write_file(*)","read_url(*)","execute_url(*)","mcp(*)"]}}) } -fn prompt_limit() -> usize { +/// Largest prompt agy accepts through `-p` (the OS per-argument limit on Unix); larger prompts +/// fail as `request_too_large`, so the planner fits its context below it (ADR-0097). +pub(crate) fn prompt_limit() -> usize { if cfg!(windows) { 24_000 } else { 100_000 } } diff --git a/crates/xgen-cli/src/composition.rs b/crates/xgen-cli/src/composition.rs index 239764b..e74e44e 100644 --- a/crates/xgen-cli/src/composition.rs +++ b/crates/xgen-cli/src/composition.rs @@ -2210,6 +2210,13 @@ impl PlannerPort for LocalPlanner { } } + fn max_context_bytes(&self) -> Option { + match self { + Self::Remote(planner) => planner.max_context_bytes(), + Self::Disabled { .. } => None, + } + } + fn request_profile_digest(&self) -> &str { match self { Self::Remote(planner) => planner.request_profile_digest(), @@ -2589,12 +2596,36 @@ fn remote_planner( let spec = crate::agy::Spec::parse(base_url).map_err(|()| PublicRunError::Configuration)?; let mut transport = crate::agy::Transport::new(spec, config.model(), limits.timeout()) .map_err(|()| PublicRunError::Configuration)?; - return Ok(OpenAiPlanner::with_external_transport( - config, - move |body, limit| transport.send(body, limit), - )); + return Ok( + OpenAiPlanner::with_external_transport(config, move |body, limit| { + transport.send(body, limit) + }) + .with_prompt_byte_limit(crate::agy::prompt_limit()), + ); } - OpenAiPlanner::new(config, credential).map_err(map_provider_config) + let planner = OpenAiPlanner::new(config, credential).map_err(map_provider_config)?; + Ok(match http_prompt_byte_limit()? { + Some(limit) => planner.with_prompt_byte_limit(limit), + None => planner, + }) +} + +/// Smallest and largest whole-prompt limit `XGEN_OPENAI_MAX_PROMPT_BYTES` accepts. +const MIN_PROMPT_BYTE_LIMIT: usize = 16 * 1024; +const MAX_PROMPT_BYTE_LIMIT: usize = 1024 * 1024; + +/// Optional whole-prompt limit for an HTTP model whose context window is smaller than the Run's +/// context budget, such as a local model served with a short context (ADR-0097). It only bounds +/// the planning context the runtime builds; requests under it are unchanged. +fn http_prompt_byte_limit() -> Result, PublicRunError> { + let Some(raw) = std::env::var_os("XGEN_OPENAI_MAX_PROMPT_BYTES") else { + return Ok(None); + }; + raw.to_str() + .and_then(|value| value.trim().parse::().ok()) + .filter(|value| (MIN_PROMPT_BYTE_LIMIT..=MAX_PROMPT_BYTE_LIMIT).contains(value)) + .map(Some) + .ok_or(PublicRunError::Configuration) } fn map_provider_config(_error: OpenAiPlannerConfigError) -> PublicRunError { diff --git a/crates/xgen-cli/src/final_response.rs b/crates/xgen-cli/src/final_response.rs index 716ff43..59f1254 100644 --- a/crates/xgen-cli/src/final_response.rs +++ b/crates/xgen-cli/src/final_response.rs @@ -169,6 +169,9 @@ impl PlannerPort for ReceiptReportPlanner { fn request_profile_digest(&self) -> &str { self.inner.request_profile_digest() } + fn max_context_bytes(&self) -> Option { + self.inner.max_context_bytes() + } fn plan( &mut self, request: &PlannerCallRequest<'_>, diff --git a/crates/xgen-provider-openai/src/lib.rs b/crates/xgen-provider-openai/src/lib.rs index acb5f40..6607ab0 100644 --- a/crates/xgen-provider-openai/src/lib.rs +++ b/crates/xgen-provider-openai/src/lib.rs @@ -40,6 +40,9 @@ const PROVIDER_DIALECT: &str = "openai.chat-completions/json-schema-v1"; const JSON_OBJECT_DIALECT: &str = "openai.chat-completions/json-object-v1"; const DEFAULT_MAX_OUTPUT_TOKENS: u32 = 4_096; const DEFAULT_MAX_REQUEST_BYTES: usize = 1024 * 1024; +/// Room for the request envelope around the planning context (`profileVersion`, `callId`, +/// `requestDigest`, keys) and a transport's own framing of the prompt (ADR-0097). +const PROMPT_ENVELOPE_RESERVE_BYTES: usize = 2048; const DEFAULT_MAX_RESPONSE_BYTES: usize = 512 * 1024; const DEFAULT_MAX_PROPOSAL_BYTES: usize = 256 * 1024; const DEFAULT_MAX_JSON_DEPTH: usize = 64; @@ -812,6 +815,7 @@ pub struct OpenAiPlanner { transport: Box, usage_observer: Option>, rejection_observer: Option>, + prompt_byte_limit: Option, } impl OpenAiPlanner { @@ -834,6 +838,7 @@ impl OpenAiPlanner { transport: Box::new(transport), usage_observer: None, rejection_observer: None, + prompt_byte_limit: None, }) } @@ -852,6 +857,7 @@ impl OpenAiPlanner { transport: Box::new(transport), usage_observer: None, rejection_observer: None, + prompt_byte_limit: None, } } @@ -868,6 +874,7 @@ impl OpenAiPlanner { transport: Box::new(ExternalTransport(send)), usage_observer: None, rejection_observer: None, + prompt_byte_limit: None, } } @@ -910,6 +917,16 @@ impl OpenAiPlanner { Ok(proposal) } + /// Declare the transport's whole-prompt byte limit (the system prompt plus the request + /// envelope and planning context) when it is lower than the HTTP request limit, so the + /// runtime fits the planning context to it instead of building a request it rejects + /// (ADR-0097). + #[must_use] + pub const fn with_prompt_byte_limit(mut self, limit: usize) -> Self { + self.prompt_byte_limit = Some(limit); + self + } + /// Observe completed HTTP attempts without changing proposal or request semantics. #[must_use] pub fn with_usage_observer( @@ -1348,6 +1365,7 @@ impl fmt::Debug for OpenAiPlanner { .field("transport", &"") .field("usage_observer", &self.usage_observer.is_some()) .field("rejection_observer", &self.rejection_observer.is_some()) + .field("prompt_byte_limit", &self.prompt_byte_limit) .finish() } } @@ -1357,6 +1375,14 @@ impl PlannerPort for OpenAiPlanner { self.config.planner_id() } + fn max_context_bytes(&self) -> Option { + let limit = self.prompt_byte_limit?; + let capacity = limit + .saturating_sub(self.config.system_prompt().len()) + .saturating_sub(PROMPT_ENVELOPE_RESERVE_BYTES); + u64::try_from(capacity).ok() + } + fn request_profile_digest(&self) -> &str { self.config.request_profile_digest() } diff --git a/crates/xgen-runtime/src/agent_loop.rs b/crates/xgen-runtime/src/agent_loop.rs index de10a72..c5d30db 100644 --- a/crates/xgen-runtime/src/agent_loop.rs +++ b/crates/xgen-runtime/src/agent_loop.rs @@ -40,6 +40,13 @@ const MAX_PLANNING_DEFINITION_BYTES: usize = 256 * 1024; const MAX_PLANNING_STEP_BYTES: usize = 64 * 1024; /// Larger arguments, such as patch bodies, stay out of the planning context (ADR-0065). /// Fixed `supersededMeaning` beside an observation whose output was withheld (ADR-0069). +const ELIDED_OUTPUT_MEANING: &str = "This output was omitted to fit the request limit. Run an \ +equivalent read again if you need its current content."; +/// The most recent outputs are never elided: they are what the next decision usually needs. +const ELISION_KEEP_RECENT: usize = 3; +/// Elision grows in steps of a quarter of the budget, so the elided prefix, and with it the +/// provider prefix cache (ADR-0036), stays the same over several calls (ADR-0097). +const ELISION_STEP_DIVISOR: usize = 4; const SUPERSEDED_OUTPUT_MEANING: &str = "A later completed Step changed a resource this observation \ covered, so this output may no longer match the current state."; const MAX_PLANNING_STEP_ARGUMENT_BYTES: usize = 2 * 1024; @@ -238,13 +245,19 @@ pub struct PlanningToolOutput { output_digest: String, receipt_digest: String, canonical_size_bytes: u64, - output: Value, + /// Absent only when the output was elided to fit the request limit (ADR-0097). + #[serde(skip_serializing_if = "Option::is_none")] + output: Option, /// The first later completed Step that changed a resource this observation covered (ADR-0069). /// The output stays: unchanged parts of a broad observation remain the planner's only record. #[serde(skip_serializing_if = "Option::is_none")] superseded_by: Option, #[serde(skip_serializing_if = "Option::is_none")] superseded_meaning: Option<&'static str>, + #[serde(skip_serializing_if = "std::ops::Not::not")] + elided: bool, + #[serde(skip_serializing_if = "Option::is_none")] + elided_meaning: Option<&'static str>, } impl PlanningToolOutput { @@ -278,9 +291,15 @@ impl PlanningToolOutput { self.canonical_size_bytes } + /// The observation, or `None` when it was elided to fit the request limit (ADR-0097). + #[must_use] + pub const fn output(&self) -> Option<&Value> { + self.output.as_ref() + } + #[must_use] - pub const fn output(&self) -> &Value { - &self.output + pub const fn elided(&self) -> bool { + self.elided } #[must_use] @@ -302,6 +321,8 @@ impl fmt::Debug for PlanningToolOutput { .field("output", &"") .field("superseded_by", &self.superseded_by) .field("superseded_meaning", &self.superseded_meaning) + .field("elided", &self.elided) + .field("elided_meaning", &self.elided_meaning) .finish() } } @@ -924,6 +945,13 @@ pub trait PlannerPort { /// responses, errors, and credentials must never be embedded or ad hoc hashed into this value. fn request_profile_digest(&self) -> &str; + /// Largest canonical planning context this port can carry in one request, when its + /// transport limit is lower than the Run's context budget (ADR-0097). `None` keeps the + /// manifest budget alone. + fn max_context_bytes(&self) -> Option { + None + } + /// Return one proposal without executing tools or changing the Run store. /// /// # Errors @@ -1461,6 +1489,7 @@ impl AgentLoop { capabilities, &self.planning_constraints, &loop_state.budget, + planner.max_context_bytes(), ) { Ok(context) => context, Err(ContextBuildError::BudgetExceeded) => { @@ -2408,11 +2437,13 @@ fn build_planning_tool_outputs( output_digest: output.output_digest().to_owned(), receipt_digest: receipt_digest.to_owned(), canonical_size_bytes: output.canonical_size_bytes(), - output: output.output().clone(), + output: Some(output.output().clone()), superseded_by: superseded_outputs.get(step_id).cloned(), superseded_meaning: superseded_outputs .contains_key(step_id) .then_some(SUPERSEDED_OUTPUT_MEANING), + elided: false, + elided_meaning: None, }); } if seen.len() != expected_count { @@ -2443,6 +2474,7 @@ fn build_context( registry, planning_constraints, budget, + None, ) } @@ -2621,6 +2653,32 @@ where superseded } +/// Replace the bodies of the oldest outputs with a fixed stub until at least `overflow` bytes, +/// rounded up to a quarter of the budget, are saved (ADR-0097). Only a context that would not +/// fit is changed; journal records and Receipts keep every output. +fn elide_oldest_outputs( + outputs: &mut [PlanningToolOutput], + overflow: usize, + maximum_size: usize, +) -> Result<(), ContextBuildError> { + let step = (maximum_size / ELISION_STEP_DIVISOR).max(1); + let target = overflow.div_ceil(step).saturating_mul(step); + let eligible = outputs.len().saturating_sub(ELISION_KEEP_RECENT); + let mut saved = 0_usize; + for output in outputs.iter_mut().take(eligible) { + if saved >= target { + break; + } + let before = canonical_size(&*output).map_err(|_| ContextBuildError::Canonicalization)?; + output.output = None; + output.elided = true; + output.elided_meaning = Some(ELIDED_OUTPUT_MEANING); + let after = canonical_size(&*output).map_err(|_| ContextBuildError::Canonicalization)?; + saved = saved.saturating_add(before.saturating_sub(after)); + } + Ok(()) +} + #[allow(clippy::too_many_arguments, clippy::too_many_lines)] fn build_context_ordered( state: &RunState, @@ -2633,6 +2691,7 @@ fn build_context_ordered( registry: &CapabilityRegistry, planning_constraints: &[PlanningConstraint], budget: &AgentLoopBudget, + port_limit: Option, ) -> Result { if !planning_context_preflight(state, registry) { return Err(ContextBuildError::InputLimitExceeded); @@ -2843,7 +2902,27 @@ fn build_context_ordered( }; let maximum_size = usize::try_from(budget.max_context_bytes) .unwrap_or(usize::MAX) - .min(usize::try_from(MAX_PLANNING_CONTEXT_BYTES).unwrap_or(usize::MAX)); + .min(usize::try_from(MAX_PLANNING_CONTEXT_BYTES).unwrap_or(usize::MAX)) + .min(port_limit.map_or(usize::MAX, |limit| { + usize::try_from(limit).unwrap_or(usize::MAX) + })); + let packed_items = step_summaries + .iter() + .map(|(_, size)| *size) + .chain(summaries.iter().map(|(_, size)| *size)) + .fold(0_usize, |total, size| { + total.saturating_add(size.saturating_add(1)) + }); + let full_size = canonical_size(&payload) + .map_err(|_| ContextBuildError::Canonicalization)? + .saturating_add(packed_items); + if full_size > maximum_size { + elide_oldest_outputs( + &mut payload.tool_outputs, + full_size - maximum_size, + maximum_size, + )?; + } let mut conservative_size = canonical_size(&payload).map_err(|_| ContextBuildError::Canonicalization)?; if conservative_size > maximum_size { @@ -3870,6 +3949,7 @@ mod tests { &CapabilityRegistry::new(), &[], &test_budget(), + None, ) .expect("ordered context should fit"); let value = serde_json::to_value(&context).expect("context should serialize"); @@ -3894,6 +3974,7 @@ mod tests { &CapabilityRegistry::new(), &[], &test_budget(), + None, ), Err(ContextBuildError::OutputBinding) )); @@ -3909,6 +3990,7 @@ mod tests { &CapabilityRegistry::new(), &[], &test_budget(), + None, ), Err(ContextBuildError::OutputBinding) )); @@ -3958,6 +4040,7 @@ mod tests { &CapabilityRegistry::new(), &[], &test_budget(), + None, ) .expect("context should fit"); let value = serde_json::to_value(&context).expect("context should serialize"); @@ -3972,6 +4055,82 @@ mod tests { assert!(value["steps"][0].get("repeatMeaning").is_none()); } + fn sized_output(step_id: &str, bytes: usize) -> PlanningToolOutput { + PlanningToolOutput { + step_id: step_id.to_owned(), + capability: CapabilityRef { + capability_id: "xgeny.fs/read-text".to_owned(), + contract_version: "1.0.0".to_owned(), + }, + output_id: format!("output-{step_id}"), + output_digest: format!("sha256:{}", "a".repeat(64)), + receipt_digest: format!("sha256:{}", "b".repeat(64)), + canonical_size_bytes: u64::try_from(bytes).expect("size fits"), + output: Some(serde_json::json!({"text": "x".repeat(bytes)})), + superseded_by: None, + superseded_meaning: None, + elided: false, + elided_meaning: None, + } + } + + fn elided_steps(outputs: &[PlanningToolOutput]) -> Vec<&str> { + outputs + .iter() + .filter(|output| output.elided()) + .map(PlanningToolOutput::step_id) + .collect() + } + + #[test] + fn an_output_that_fits_serializes_without_elision_fields() { + // ADR-0097: requests under the limit keep their bytes. + let raw = serde_json::to_string(&sized_output("s", 1)).expect("output should serialize"); + assert!(raw.contains("\"output\":{\"text\":\"x\"}")); + assert!(!raw.contains("elided")); + } + + #[test] + fn overflow_elides_the_oldest_outputs_and_keeps_the_recent_ones() { + let mut outputs = (0..8) + .map(|index| sized_output(&format!("s{index}"), 10_000)) + .collect::>(); + // Overflow of 1 byte against a 100,000 budget still saves a whole quarter (25,000). + elide_oldest_outputs(&mut outputs, 1, 100_000).expect("elision should succeed"); + assert_eq!(elided_steps(&outputs), ["s0", "s1", "s2"]); + let stub = serde_json::to_value(&outputs[0]).expect("stub should serialize"); + assert!(stub.get("output").is_none()); + assert_eq!(stub["elided"], true); + assert_eq!(stub["elidedMeaning"], ELIDED_OUTPUT_MEANING); + assert_eq!(stub["canonicalSizeBytes"], 10_000); + assert_eq!(stub["outputDigest"], outputs[0].output_digest()); + + let mut everything = (0..8) + .map(|index| sized_output(&format!("s{index}"), 10_000)) + .collect::>(); + elide_oldest_outputs(&mut everything, 1_000_000, 100_000).expect("elision should succeed"); + assert_eq!(elided_steps(&everything), ["s0", "s1", "s2", "s3", "s4"]); + } + + #[test] + fn the_elided_prefix_holds_while_overflow_stays_in_the_same_quarter() { + // ADR-0097: a stable prefix lets the provider cache reuse it across calls. + let mut first = (0..8) + .map(|index| sized_output(&format!("s{index}"), 10_000)) + .collect::>(); + elide_oldest_outputs(&mut first, 2_000, 100_000).expect("elision should succeed"); + let mut later = (0..9) + .map(|index| sized_output(&format!("s{index}"), 10_000)) + .collect::>(); + elide_oldest_outputs(&mut later, 12_000, 100_000).expect("elision should succeed"); + assert_eq!(elided_steps(&first), elided_steps(&later)); + let mut next_quarter = (0..9) + .map(|index| sized_output(&format!("s{index}"), 10_000)) + .collect::>(); + elide_oldest_outputs(&mut next_quarter, 26_000, 100_000).expect("elision should succeed"); + assert_eq!(elided_steps(&next_quarter).len(), 6); + } + #[test] fn a_change_covers_the_same_resource_or_one_below_it() { // ADR-0069: hierarchy is `/`-separated; other resources only match exactly. @@ -4022,6 +4181,7 @@ mod tests { &CapabilityRegistry::new(), &[], &test_budget(), + None, ) .expect("context should fit"); let value = serde_json::to_value(&context).expect("context should serialize"); diff --git a/docs/adr/0097-request-bounded-tool-output-delivery.md b/docs/adr/0097-request-bounded-tool-output-delivery.md index a501c66..ea76868 100644 --- a/docs/adr/0097-request-bounded-tool-output-delivery.md +++ b/docs/adr/0097-request-bounded-tool-output-delivery.md @@ -1,7 +1,7 @@ # ADR-0097: 요청 한도 안에서 도구 출력 전달하기 - 날짜: 2026-11-29 -- 상태: 제안(사용자 검토 대기). 구현 전. +- 상태: 1단계 구현(2026-11-29). 실측 진행 중. 2단계는 측정 뒤 별도 결정. - 변경 분류: 범용 planning context. 특정 과업·언어·모델 규칙 없음. - protocol·journal 변경: 없음. 한도 안의 요청은 바이트가 그대로다. 한도를 넘던 요청만 바뀐다. @@ -44,11 +44,12 @@ ADR-0069는 나중에 바뀐 자원의 옛 관찰을 숨겼다가 held-out에서 ### 1단계: 한도를 한 곳에서 정하고, 넘칠 때만 오래된 출력 본문을 생략 1. **예산의 단일 출처.** Planner port가 한 요청에 담을 수 있는 최대 바이트를 알린다. - - HTTP: 기존 `max_request_bytes` - - agy: prompt 한도 100,000바이트 - - context builder는 `min(manifest max_context_bytes, port 한도 − 고정 overhead)`를 예산으로 쓴다. - - overhead는 system prompt, 요청 envelope(`callId`, `requestDigest` 등), agy 머리말·맺음말이다. 실제 직렬화 - 크기로 계산하고, 상수로 어림하지 않는다. + - agy: transport의 prompt 한도(Unix 100,000바이트) + - HTTP: 기본은 알리지 않는다(요청 1 MiB가 예산 512 KiB보다 커서 지금처럼 동작). Context window가 작은 + model이나 앞단 gateway가 있으면 `XGEN_OPENAI_MAX_PROMPT_BYTES`(16 KiB~1 MiB, 범위 밖이면 설정 오류)로 알린다. + - Planner는 `prompt 한도 − system prompt 실제 길이 − envelope 여유 2,048바이트`를 port 한도로 낸다. + Envelope(`callId`, `requestDigest`, agy 머리말·맺음말)는 수백 바이트라 고정 여유로 둔다. + - context builder는 `min(manifest max_context_bytes, MAX_PLANNING_CONTEXT_BYTES, port 한도)`를 예산으로 쓴다. 2. **넘칠 때만 생략.** `toolOutputs`·`steps`·`capabilities`를 모두 넣어 예산 안이면 지금과 바이트가 같다. 넘치면: - 가장 오래된 출력부터 본문(`output`)을 빼고 stub을 남긴다. - stub 필드: `stepId`, `capability`, `outputDigest`, `canonicalSizeBytes`, `elided: true`, 고정 문장 @@ -56,10 +57,12 @@ ADR-0069는 나중에 바뀐 자원의 옛 관찰을 숨겼다가 held-out에서 its current content.") - 최근 출력 3개는 생략하지 않는다. - 출력을 다 줄여도 넘치면 기존 `steps`·`capabilities` packing으로 넘어간다. 그래도 넘치면 지금처럼 거절한다. -3. **prefix cache.** 생략은 앞쪽 항목을 바꾼다(ADR-0036, 0072). 한 번 넘칠 때 예산의 75%까지 내려 생략한다. - 그러면 다음 여러 호출 동안 앞부분이 그대로라 cache를 다시 쓴다. +3. **prefix cache.** 생략은 앞쪽 항목을 바꾼다(ADR-0036, 0072). 넘친 양을 예산의 1/4 단위로 올림해 그만큼 + 생략한다. 넘친 양이 같은 1/4 구간에 있는 동안 생략되는 앞부분이 같아서 cache를 다시 쓴다. 4. **journal·Receipt.** 원문은 journal과 tool_outputs 저장소에 그대로 있다. 생략은 모델에 보내는 view에서만 일어난다. context digest는 실제로 보낸 payload의 digest다. +5. **resume.** 한도는 request profile digest에 넣지 않는다. Run 중간에 한도를 바꾸면 그 뒤 요청의 생략 범위만 + 달라지고, 이미 settle된 호출에는 영향이 없다. ### 2단계(실험, 1단계 측정 뒤 별도 결정): 생략 순서 diff --git a/docs/getting-started.md b/docs/getting-started.md index 40ad858..f9696ce 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -226,6 +226,10 @@ Planner 호출의 wall-clock 예산과 출력 token 예산은 프로필 설정 profile에 묶이므로 Run 시작 뒤 프로필에서 바꾸면 그 Run의 resume은 `configuration_mismatch`로 닫힌다. +Context window가 작은 model이나 요청 크기 제한이 있는 gateway는 `XGEN_OPENAI_MAX_PROMPT_BYTES`(16 KiB~1 MiB)로 +한 요청의 prompt 바이트 상한을 알린다. Planning context가 이 상한을 넘을 때만 오래된 도구 출력 본문을 생략하고 +stub을 남긴다(ADR-0097). 상한 안의 요청은 바뀌지 않는다. agy transport는 자체 prompt 한도를 쓴다. + ```bash xgen model setup --name qwen38 --base-url http://127.0.0.1:11434/v1 \ --model qwen3.8:27b-q4_K_M --inference-timeout 300 --max-output-tokens 1024 From 517deb4929732c10f5e9188e59050230d94018bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=86=90=EC=84=B1=EC=A4=80?= Date: Sun, 29 Nov 2026 22:49:37 +0900 Subject: [PATCH 3/3] =?UTF-8?q?=EA=B8=B0=EC=A4=80=EC=84=A0=2034/89=20?= =?UTF-8?q?=ED=99=95=EC=A0=95=EA=B3=BC=20ADR-0097=201=EB=8B=A8=EA=B3=84=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84=20=EC=83=81=ED=83=9C=EB=A5=BC=20=EC=9E=91?= =?UTF-8?q?=EC=97=85=20=EA=B8=B0=EB=A1=9D=EC=97=90=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- MEMORY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MEMORY.md b/MEMORY.md index 9e30e31..fca2136 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -322,3 +322,5 @@ Launcher의 `latest`/`next`는 rc.8이며 실제 모델 품질 평가는 인증 - 연구 방향(사용자 결정, 2026-11-29): 모델을 바꾸기보다 지금 수준 모델(agy `gemini-3.8-flash-low`)로 높은 성능을 내는 하네스를 연구한다. 핵심은 LLM에게 무엇을 어떻게 전달하고(메모리·도구·피드백) 실행 경로를 마련하느냐다. 측정은 공식 실행기 Harbor로 Terminal-Bench 2.1(89개)을 돌리고, 실패를 전달 관점(문맥 누락·도구 계약 오해·실행 경로 없음·검증 누락·형식 오류·루프/예산)으로 분류한다. 측정 도구는 `research/harbor-bench` 브랜치에 있다(아직 PR 전). - agy 내장 manage_task(ADR-0096, 구현·실제 모델 검증): agy 1.5.18은 planner-only agent와 deny 설정에서도 `manage_task`를 실행하고 끌 방법이 없다(agent `disabledTools` 무시, settings 키 없음, deny 규칙 무효). 기준선의 정상 응답 14%가 이 호출을 포함해 Run이 Unknown으로 멈췄다. `Action=list` 단독 호출만 허용하고 나머지 native step은 계속 실패로 닫는다. 유도 목표 비교에서 기존 2/8 정지, 수정 0/10 정지. agy 쪽 과제: 이 도구를 끄는 설정이 생기면 허용을 제거한다. - 기준선 중간 관찰(2026-11-29): 응답이 거절되면 모델은 `previousResponseRejection.meaning`의 일반 문구만 받고 구체 이유(빠진 필드, 문자열 안 제어 문자)를 받지 못해 같은 실수를 반복했다(write-compressor 3연속 → Run 거절). 사례를 더 모은 뒤 첫 개선 후보로 본다. agy 개인 할당량(약 3.5시간·호출 700여 회) 초과로 50개 과업이 오염되어 할당량을 확인하며 다시 돌리는 중이다. +- 기준선 확정(2026-11-29, 89개): 34개 통과(38%). 실패 55개 중 32개가 `request_too_large`였다. 원인은 planning 예산(512 KiB)과 agy prompt 한도(100,000바이트)가 따로 있고 `toolOutputs`가 packing 대상이 아니라는 점이다. 나머지는 완료 주장 후 검증 실패 10, invalid 응답 3연속 7, 기타 6이다. +- 요청 한도 안 도구 출력 전달(ADR-0097 1단계, 구현·실측 진행 중): planner port가 prompt 한도를 알리고(agy는 transport 한도, HTTP는 `XGEN_OPENAI_MAX_PROMPT_BYTES`일 때만), 넘칠 때만 최근 3개를 뺀 오래된 출력 본문을 stub으로 바꾼다. 한도 안 요청은 바이트가 같다(diff-model-requests 8/8). 실측은 too_large 32과업을 설계 16·held-out 16으로 나눠 돌린다. 2단계(생략 순서 비교)는 실측 뒤 결정한다.