diff --git a/MEMORY.md b/MEMORY.md index 9e30e31..780f486 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -322,3 +322,4 @@ 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, ADR-0098 제안, 구현 전): 기준선 응답 1,482개 중 146개(9.9%)가 형식 거절이다. 갈래별로 문자열 escape 62(대부분 `bash -c` 안의 여러 줄 코드), 봉투 구조 71(Step 필드를 최상위에 펼침 46, 봉투 없는 Step 14), 안전 필터 문구 13이다. 제안은 고정 code `responseDefect`와 code별 문장으로 구체 이유를 전달하는 것이고, 선택으로 뜻이 하나뿐인 문자열 보정(날 제어 문자, 잘못된 escape; 오프라인 22건 회복)을 둔다. 2026-11-30 사용자 승인으로 1번 구현: 기준선 거절 146건 모두 구체 code로 분류(unclassified 0). agy transport의 응답 사전 JSON 검사를 빼서 agy도 같은 decoder 판정과 ADR-0068 보정을 받는다. 실측은 ADR-0097 실측 뒤. diff --git a/bench/harbor/classify_responses.py b/bench/harbor/classify_responses.py new file mode 100644 index 0000000..3ad8c77 --- /dev/null +++ b/bench/harbor/classify_responses.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Classify rejected-shape bridge responses with xgen's response contract (ADR-0098 analysis). + +Usage: python3 bench/harbor/classify_responses.py [--since EPOCH] [--log-dir /tmp/hb/bridge] [--repair] + +Mirrors decode_chat_response: strict JSON (no raw control characters, no duplicate keys), +the four-field envelope, and step/dependency shapes. --repair also reports what the +unambiguous string repair (raw control characters, invalid escapes) would recover. +The rules are approximate; xgen's Rust decoder is authoritative. +""" +import argparse, collections, glob, json, os, re +class Dup(Exception): pass +def hook(pairs): + keys=[k for k,_ in pairs] + if len(keys)!=len(set(keys)): raise Dup(keys) + return dict(pairs) +PROP={"formatVersion","kind","steps","summary"} +STEP={"key","objective","dependsOn","capability","arguments"} +def classify(text): + t=text.strip() + if t.startswith("```"): return "markdown_fence" + try: v=json.loads(text, object_pairs_hook=hook) + except Dup: return "duplicate_key" + except json.JSONDecodeError as e: + m=e.msg + if "control character" in m: return "control_char_in_string" + if "Extra data" in m: return "trailing_data" + if "Invalid \\escape" in m or "escape" in m: return "invalid_escape" + if e.pos>=len(text.rstrip())-1 or "Expecting" in m and e.pos>len(text)-3: return "truncated_or_unclosed" + return "json_syntax:"+m.split(":")[0] + if not isinstance(v,dict): return "not_object" + missing=PROP-set(v); extra=set(v)-PROP + if missing: return "missing:"+",".join(sorted(missing)) + if extra: return "unknown_field:"+",".join(sorted(extra)) + if v["formatVersion"]!=1: return "format_version" + k=v["kind"] + if k not in ("plan","completion_candidate","response_candidate"): return "bad_kind:"+str(k)[:20] + if k=="plan": + if v["summary"]: return "plan_with_summary" + if not isinstance(v["steps"],list): return "steps_not_list" + for s in v["steps"]: + if not isinstance(s,dict): return "step_not_object" + if STEP-set(s): return "step_missing:"+",".join(sorted(STEP-set(s))) + if set(s)-STEP: return "step_unknown_field:"+",".join(sorted(set(s)-STEP)) + c=s["capability"] + if not isinstance(c,dict) or set(c)!={"capabilityId","contractVersion"}: return "step_capability_shape" + for d in s["dependsOn"]: + if not isinstance(d,dict) or set(d)!={"kind","stepId","key"}: return "dependency_shape" + if d["kind"]=="existing_step" and not (d["stepId"] and not d["key"]): return "dependency_fields" + if d["kind"]=="proposed_step" and not (d["key"] and not d["stepId"]): return "dependency_fields" + if d["kind"] not in ("existing_step","proposed_step"): return "dependency_kind" + return "ok_plan" + if v["steps"] or not v["summary"]: return "candidate_with_steps_or_empty_summary" + return "ok_"+k + + +VALID = set('"\\/bfnrtu') + + +def repair_strings(text): + """Escape raw control characters and lone backslashes inside strings; None if unchanged.""" + out, in_string, i, changed = [], False, 0, False + while i < len(text): + ch = text[i] + if in_string: + if ch == "\\": + nxt = text[i + 1] if i + 1 < len(text) else "" + if nxt in VALID and not (nxt == "u" and not re.fullmatch(r"[0-9a-fA-F]{4}", text[i + 2:i + 6])): + out.append(ch + nxt) + i += 2 + continue + out.append("\\\\") + changed = True + i += 1 + continue + if ch == '"': + in_string = False + elif ord(ch) < 0x20: + out.append({"\n": "\\n", "\t": "\\t", "\r": "\\r"}.get(ch, "\\u%04x" % ord(ch))) + changed = True + i += 1 + continue + elif ch == '"': + in_string = True + out.append(ch) + i += 1 + return "".join(out) if changed else None + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--since", type=float, default=0) + parser.add_argument("--log-dir", default="/tmp/hb/bridge") + parser.add_argument("--repair", action="store_true") + args = parser.parse_args() + counts, repaired = collections.Counter(), collections.Counter() + for path in sorted(glob.glob(f"{args.log_dir}/*.json")): + if int(os.path.basename(path).split("-")[0]) < args.since: + continue + record = json.load(open(path)) + messages = record["request"].get("messages") or [] + if record.get("error") or record.get("response") is None \ + or any(m.get("content") == "ping" for m in messages): + continue + kind = classify(record["response"]) + counts[kind] += 1 + if args.repair and not kind.startswith("ok"): + fixed = repair_strings(record["response"]) + if fixed is not None: + repaired[(kind, classify(fixed))] += 1 + total = sum(counts.values()) + bad = total - sum(n for k, n in counts.items() if k.startswith("ok")) + print(f"{total} responses, {bad} rejected-shape") + for kind, n in counts.most_common(): + print(f"{n:6} {kind}") + for (before, after), n in sorted(repaired.items()): + print(f"repair {n:4} {before} -> {after}") + + +if __name__ == "__main__": + main() diff --git a/crates/xgen-cli/src/agy.rs b/crates/xgen-cli/src/agy.rs index 2fe560c..2939578 100644 --- a/crates/xgen-cli/src/agy.rs +++ b/crates/xgen-cli/src/agy.rs @@ -20,7 +20,7 @@ use sha2::{Digest, Sha256}; use tempfile::TempDir; use url::Url; use xgen_provider_openai::parse_unique_json; -use xgen_runtime::PlannerPortFailure; +use xgen_runtime::{PlannerPortFailure, ResponseDefect}; pub const DEFAULT_MODEL: &str = "gemini-3.8-flash-low"; const AGENT: &str = include_str!("agy-agent.md"); @@ -384,12 +384,12 @@ impl Transport { if request["model"].as_str() != Some(self.model.as_str()) { return Err(PlannerPortFailure::ProviderLimit); } - let system = request["messages"][0]["content"] - .as_str() - .ok_or(PlannerPortFailure::InvalidResponse)?; - let user = request["messages"][1]["content"] - .as_str() - .ok_or(PlannerPortFailure::InvalidResponse)?; + let system = request["messages"][0]["content"].as_str().ok_or( + PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified), + )?; + let user = request["messages"][1]["content"].as_str().ok_or( + PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified), + )?; let prompt = format!( "HOST SYSTEM INSTRUCTIONS:\n{system}\nHOST REQUEST AND OBSERVATIONS:\n{user}\n{}", self.closing @@ -420,19 +420,24 @@ impl Transport { || finals.len() != 1 || finals[0]["result"]["status"] != "SUCCESS" { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } let result = &finals[0]["result"]; let response = result["response"] .as_str() - .ok_or(PlannerPortFailure::InvalidResponse)?; - parse_unique_json(response.as_bytes(), 64)?; + .ok_or(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + ))?; + // The shared decoder parses the content and classifies a defect (ADR-0098), so it is not + // checked here. let mut envelope = json!({"model":self.model,"choices":[{"index":0,"finish_reason":"stop","message":{"role":"assistant","content":response}}]}); if let Some(usage) = normalized_usage(&result["usage"]) { envelope["usage"] = usage; } - let encoded = - serde_json::to_vec(&envelope).map_err(|_| PlannerPortFailure::InvalidResponse)?; + let encoded = serde_json::to_vec(&envelope) + .map_err(|_| PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified))?; if encoded.len() > max_response_bytes { return Err(PlannerPortFailure::ProviderLimit); } diff --git a/crates/xgen-cli/src/composition.rs b/crates/xgen-cli/src/composition.rs index 239764b..e2e859a 100644 --- a/crates/xgen-cli/src/composition.rs +++ b/crates/xgen-cli/src/composition.rs @@ -2726,7 +2726,7 @@ fn map_planner_unavailable(run_id: String, failure: PlannerPortFailure) -> Local ), }; } - PlannerPortFailure::InvalidResponse => ModelCallRejectionReason::PlannerInvalidResponse, + PlannerPortFailure::InvalidResponse(_) => ModelCallRejectionReason::PlannerInvalidResponse, PlannerPortFailure::ProviderLimit => ModelCallRejectionReason::ProviderLimit, PlannerPortFailure::RequestTooLarge => ModelCallRejectionReason::RequestTooLarge, PlannerPortFailure::RateLimited => ModelCallRejectionReason::RateLimited, diff --git a/crates/xgen-cli/src/driver.rs b/crates/xgen-cli/src/driver.rs index e58d059..5604a8e 100644 --- a/crates/xgen-cli/src/driver.rs +++ b/crates/xgen-cli/src/driver.rs @@ -612,7 +612,8 @@ impl RunDriver { // is usually a rare runaway repetition that a fresh sample avoids (ADR-0073). if matches!( failure, - PlannerPortFailure::InvalidResponse | PlannerPortFailure::OutputTruncated + PlannerPortFailure::InvalidResponse(_) + | PlannerPortFailure::OutputTruncated ) && rejected_responses_in_a_row < MAX_REJECTED_RESPONSE_RETRIES { rejected_responses_in_a_row += 1; diff --git a/crates/xgen-cli/src/final_response.rs b/crates/xgen-cli/src/final_response.rs index 716ff43..2dfb672 100644 --- a/crates/xgen-cli/src/final_response.rs +++ b/crates/xgen-cli/src/final_response.rs @@ -5,7 +5,9 @@ use serde_json::{Value, json}; use xgen_adapter_process::PROCESS_EXECUTE_CAPABILITY_ID; use xgen_local_store::{RunStore, SqliteRunStore}; use xgen_provider_openai::{CompletionCheck, OpenAiPlanner}; -use xgen_runtime::{PlanProposal, PlannerCallRequest, PlannerPort, PlannerPortFailure}; +use xgen_runtime::{ + PlanProposal, PlannerCallRequest, PlannerPort, PlannerPortFailure, ResponseDefect, +}; use xgen_workgraph::{EffectClass, RunEventBody, validate_completion_summary_candidate}; use crate::material_catalog::RunMaterialCatalog; @@ -49,8 +51,8 @@ impl ReceiptReportPlanner { // Read-only preflight can return a private snapshot. Open it after this // call has been reserved, not when the planner is constructed. let store = SqliteRunStore::open_existing_read_only(&self.database) - .map_err(|_| PlannerPortFailure::InvalidResponse)?; - let invalid = || PlannerPortFailure::InvalidResponse; + .map_err(|_| PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified))?; + let invalid = || PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified); let (snapshot, mut receipts) = store .load_with_execution_receipts() .map_err(|_| invalid())?; @@ -245,7 +247,7 @@ fn completion_report( report["verification"] = completion_evidence(checks, commands, check_steps, boundary) .map_err(|reason| { eprintln!("XGEN_COMPLETION_CHECK reason={reason}"); - PlannerPortFailure::InvalidResponse + PlannerPortFailure::InvalidResponse(ResponseDefect::CompletionCheckFailed) })?; report["format_version"] = json!(2); } diff --git a/crates/xgen-cli/tests/live_go50902_public.rs b/crates/xgen-cli/tests/live_go50902_public.rs index 033fa9f..c3edbc3 100644 --- a/crates/xgen-cli/tests/live_go50902_public.rs +++ b/crates/xgen-cli/tests/live_go50902_public.rs @@ -1328,6 +1328,7 @@ fn require_workspace_completion(output: &Output, state_root: &Path) { ModelCallSettlement::Rejected { reason, proposal: None, + .. }, .. } = record.event.body diff --git a/crates/xgen-cli/tests/workspace_discovery.rs b/crates/xgen-cli/tests/workspace_discovery.rs index f0bd3a3..33ce6b7 100644 --- a/crates/xgen-cli/tests/workspace_discovery.rs +++ b/crates/xgen-cli/tests/workspace_discovery.rs @@ -2435,6 +2435,56 @@ fn a_truncated_response_is_sampled_again_with_its_reason() { assert_eq!(result.status.code(), Some(0), "{}", stderr(&result)); } +#[test] +fn a_malformed_response_is_retried_with_its_defect_class() { + // ADR-0098: the retry names the broken part of the contract, not just "invalid". + let fixture = tempdir().unwrap(); + let state = fixture.path().join("state"); + let workspace = fixture.path().join("workspace"); + fs::create_dir(&workspace).unwrap(); + let answer = provider_response(&json!({ + "formatVersion": 1, "kind": "response_candidate", "steps": [], "summary": "answer" + })); + let mut flattened: Value = serde_json::from_slice(&answer).unwrap(); + flattened["choices"][0]["message"]["content"] = json!( + r#"{"formatVersion":1,"kind":"plan","key":"a","objective":"b","dependsOn":[],"capability":{"capabilityId":"x","contractVersion":"1"},"arguments":{},"summary":""}"# + ); + let server = + SequentialServer::spawn_responses(vec![serde_json::to_vec(&flattened).unwrap(), answer]); + let result = bounded_output(xgen(&state).args([ + "run", + "--workspace", + path_text(&workspace), + "--base-url", + &server.base_url, + "--model", + MODEL, + "--tokenizer", + TOKENIZER, + "--allow-dir", + ".", + "--allow-remote-model-egress", + "--conversation-responses", + "Answer.", + ])) + .unwrap(); + let requests: Vec<_> = (0..2) + .map(|_| server.requests.recv_timeout(TEST_TIMEOUT).unwrap()) + .collect(); + server.handle.join().unwrap(); + let rejection = &planning_context(&requests[1])["previousResponseRejection"]; + assert_eq!( + rejection["reason"], "planner_invalid_response", + "{rejection}" + ); + assert_eq!( + rejection["responseDefect"], "step_fields_at_top_level", + "{rejection}" + ); + assert!(rejection["meaning"].to_string().contains("inside")); + assert_eq!(result.status.code(), Some(0), "{}", stderr(&result)); +} + #[test] #[cfg(unix)] fn run_names_collections_that_must_be_rebuilt_and_does_not_start() { diff --git a/crates/xgen-provider-openai/src/lib.rs b/crates/xgen-provider-openai/src/lib.rs index acb5f40..c54dbc6 100644 --- a/crates/xgen-provider-openai/src/lib.rs +++ b/crates/xgen-provider-openai/src/lib.rs @@ -18,7 +18,7 @@ use url::{Host, Url}; use xgen_domain::CapabilityRef; use xgen_runtime::{ PlanDependency, PlanProposal, PlannerCallRequest, PlannerPort, PlannerPortFailure, - ProposedPlanStep, + ProposedPlanStep, ResponseDefect, }; mod completion; @@ -883,12 +883,16 @@ impl OpenAiPlanner { (self.config.evaluation_step_limit, &proposal) && (steps.is_empty() || steps.len() > limit.max_steps()) { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } if matches!(proposal, PlanProposal::ResponseCandidate { .. }) && !self.config.conversation_responses { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } if let Some(validator) = &self.config.completion_validator { let summary = match &proposal { @@ -898,9 +902,13 @@ impl OpenAiPlanner { }; if let Some(summary) = summary { let value = parse_unique_json(summary.as_bytes(), self.config.max_json_depth) - .map_err(|_| PlannerPortFailure::InvalidResponse)?; + .map_err(|_| { + PlannerPortFailure::InvalidResponse(ResponseDefect::CompletionCheckFailed) + })?; if !validator.is_valid(&value) { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::CompletionCheckFailed, + )); } } } @@ -1660,7 +1668,9 @@ impl Transport for UreqTransport { .and_then(|value| value.parse::().ok()) .is_some_and(|length| length > request.max_response_bytes as u64) { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } let read_limit = u64::try_from(request.max_response_bytes) .unwrap_or(u64::MAX) @@ -1672,7 +1682,9 @@ impl Transport for UreqTransport { .read_to_vec() .map_err(|error| map_transport_error(&error))?; if body.len() > request.max_response_bytes { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } Ok(body) } @@ -1762,7 +1774,9 @@ fn read_rejection( fn map_transport_error(error: &ureq::Error) -> PlannerPortFailure { match error { ureq::Error::Timeout(_) => PlannerPortFailure::Timeout, - ureq::Error::BodyExceedsLimit(_) => PlannerPortFailure::InvalidResponse, + ureq::Error::BodyExceedsLimit(_) => { + PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified) + } _ => PlannerPortFailure::Unavailable, } } @@ -1801,7 +1815,7 @@ const fn map_compatibility_transport_failure( match failure { PlannerPortFailure::Timeout => OpenAiCompatibilityCheckFailure::Timeout, PlannerPortFailure::Unavailable => OpenAiCompatibilityCheckFailure::Unavailable, - PlannerPortFailure::InvalidResponse | PlannerPortFailure::OutputTruncated => { + PlannerPortFailure::InvalidResponse(_) | PlannerPortFailure::OutputTruncated => { OpenAiCompatibilityCheckFailure::InvalidResponse } PlannerPortFailure::ProviderLimit | PlannerPortFailure::RateLimited => { @@ -1914,16 +1928,22 @@ fn decode_chat_response_with_codec( atomic_json: bool, ) -> Result { let envelope = parse_unique_json(body, max_json_depth)?; - let response: ChatCompletionResponse = - serde_json::from_value(envelope).map_err(|_| PlannerPortFailure::InvalidResponse)?; + let response: ChatCompletionResponse = serde_json::from_value(envelope) + .map_err(|_| PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified))?; if response.model != expected_model { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } let [choice] = response.choices.as_slice() else { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); }; if choice.index != 0 || choice.message.role != "assistant" { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } if choice.finish_reason == "length" { return Err(PlannerPortFailure::OutputTruncated); @@ -1933,33 +1953,24 @@ fn decode_chat_response_with_codec( || choice.message.tool_calls.is_some() || choice.message.function_call.is_some() { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } let content = choice .message .content .as_deref() - .ok_or(PlannerPortFailure::InvalidResponse)?; - if content.len() > max_proposal_bytes { - return Err(PlannerPortFailure::InvalidResponse); - } - let proposal_value = - parse_unique_json(content.as_bytes(), max_json_depth).or_else(|error| { - // ADR-0068: a model that drops a closer inside nested arguments gets one rebalance. - rebalance_json_closers(content) - .filter(|repaired| repaired.len() <= max_proposal_bytes) - .and_then(|repaired| parse_unique_json(repaired.as_bytes(), max_json_depth).ok()) - .ok_or(error) - })?; - let proposal: ProposalDocument = - serde_json::from_value(proposal_value).map_err(|_| PlannerPortFailure::InvalidResponse)?; - if proposal.format_version != 1 { - return Err(PlannerPortFailure::InvalidResponse); - } + .ok_or(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + ))?; + let proposal = decode_proposal_document(content, max_proposal_bytes, max_json_depth)?; match proposal.kind { ProposalKind::Plan => { if !proposal.summary.is_empty() { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::KindShape, + )); } let steps = proposal .steps @@ -1987,7 +1998,9 @@ fn decode_chat_response_with_codec( } ProposalKind::CompletionCandidate | ProposalKind::ResponseCandidate => { if !proposal.steps.is_empty() || proposal.summary.is_empty() { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::KindShape, + )); } Ok(match proposal.kind { ProposalKind::ResponseCandidate => { @@ -2043,10 +2056,12 @@ fn validate_artifact_response( validator: &jsonschema::Validator, ) -> Result<(), PlannerPortFailure> { let envelope = parse_unique_json(body, config.max_json_depth)?; - let response: ChatCompletionResponse = - serde_json::from_value(envelope).map_err(|_| PlannerPortFailure::InvalidResponse)?; + let response: ChatCompletionResponse = serde_json::from_value(envelope) + .map_err(|_| PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified))?; let [choice] = response.choices.as_slice() else { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); }; // Preserve the existing truncation classification; full envelope validation follows. if choice.finish_reason == "length" { @@ -2056,22 +2071,28 @@ fn validate_artifact_response( .message .content .as_deref() - .ok_or(PlannerPortFailure::InvalidResponse)?; + .ok_or(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + ))?; if content.len() > config.max_proposal_bytes { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } let proposal: ProposalDocument = serde_json::from_value(parse_unique_json( content.as_bytes(), config.max_json_depth, )?) - .map_err(|_| PlannerPortFailure::InvalidResponse)?; + .map_err(|_| PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified))?; for step in proposal.steps { if !step .arguments .get("jsonContent") .is_some_and(|value| validator.is_valid(value)) { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } } Ok(()) @@ -2081,13 +2102,17 @@ fn decode_atomic_json_arguments( capability: &CapabilityRef, value: Value, ) -> Result { - let capability = - serde_json::to_value(capability).map_err(|_| PlannerPortFailure::InvalidResponse)?; + let capability = serde_json::to_value(capability) + .map_err(|_| PlannerPortFailure::InvalidResponse(ResponseDefect::StepShape))?; if capability != json!({"capabilityId":"xgeny.fs/write-atomic", "contractVersion":"1.0.0"}) { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::StepShape, + )); } let Value::Object(mut args) = value else { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::StepShape, + )); }; if args.len() != 3 || !args.get("path").is_some_and(Value::is_string) @@ -2096,13 +2121,17 @@ fn decode_atomic_json_arguments( .is_some_and(|v| v.is_null() || v.is_string()) || !args.get("jsonContent").is_some_and(Value::is_object) { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::StepShape, + )); } let object = args .remove("jsonContent") - .ok_or(PlannerPortFailure::InvalidResponse)?; - let content = - serde_json::to_string(&object).map_err(|_| PlannerPortFailure::InvalidResponse)?; + .ok_or(PlannerPortFailure::InvalidResponse( + ResponseDefect::StepShape, + ))?; + let content = serde_json::to_string(&object) + .map_err(|_| PlannerPortFailure::InvalidResponse(ResponseDefect::StepShape))?; args.insert("content".into(), Value::String(content)); Ok(Value::Object(args)) } @@ -2214,10 +2243,138 @@ fn decode_dependency(dependency: DependencyDocument) -> Result { - Err(PlannerPortFailure::InvalidResponse) + DependencyKind::ExistingStep | DependencyKind::ProposedStep => Err( + PlannerPortFailure::InvalidResponse(ResponseDefect::StepShape), + ), + } +} + +/// Parse proposal text into the proposal document, classifying any defect (ADR-0098). +fn decode_proposal_document( + content: &str, + max_proposal_bytes: usize, + max_json_depth: usize, +) -> Result { + let invalid = PlannerPortFailure::InvalidResponse; + if content.len() > max_proposal_bytes { + return Err(invalid(ResponseDefect::ResponseTooLarge)); + } + let value = parse_unique_json(content.as_bytes(), max_json_depth) + .or_else(|error| { + // ADR-0068: a model that drops a closer inside nested arguments gets one rebalance. + rebalance_json_closers(content) + .filter(|repaired| repaired.len() <= max_proposal_bytes) + .and_then(|repaired| parse_unique_json(repaired.as_bytes(), max_json_depth).ok()) + .ok_or(error) + }) + .map_err(|_| invalid(diagnose_json_text(content)))?; + let proposal = ProposalDocument::deserialize(&value) + .map_err(|_| invalid(diagnose_proposal_value(&value)))?; + if proposal.format_version != 1 { + return Err(invalid(ResponseDefect::KindShape)); + } + Ok(proposal) +} + +const ENVELOPE_FIELDS: [&str; 4] = ["formatVersion", "kind", "steps", "summary"]; +const STEP_FIELDS: [&str; 5] = ["key", "objective", "dependsOn", "capability", "arguments"]; + +/// Classify proposal text that failed to parse as JSON (ADR-0098). +/// +/// A scan that tracks only string state finds the first raw control character or undefined escape +/// inside a string. It is reported only when the parser stopped there; a parser error earlier in +/// the text (for example an unescaped quote that ended a string) is a general syntax error. +fn diagnose_json_text(text: &str) -> ResponseDefect { + if !text.trim_start().starts_with('{') { + return ResponseDefect::NotJson; + } + let Err(error) = serde_json::from_str::(text) else { + return ResponseDefect::Unclassified; + }; + let stopped_at = byte_offset(text, error.line(), error.column()); + if let Some((offset, defect)) = first_string_defect(text) + && offset <= stopped_at.saturating_add(1) + { + return defect; + } + if error.is_eof() { + ResponseDefect::JsonTruncated + } else { + ResponseDefect::JsonSyntax + } +} + +/// Byte offset of a `serde_json` error position (1-based line, byte column). +fn byte_offset(text: &str, line: usize, column: usize) -> usize { + let line_start = text + .match_indices('\n') + .nth(line.saturating_sub(2)) + .map_or(0, |(index, _)| index + 1); + if line <= 1 { + column + } else { + line_start + column + } +} + +fn first_string_defect(text: &str) -> Option<(usize, ResponseDefect)> { + let bytes = text.as_bytes(); + let mut in_string = false; + let mut index = 0; + while index < bytes.len() { + let byte = bytes[index]; + if !in_string { + in_string = byte == b'"'; + } else if byte == b'"' { + in_string = false; + } else if byte < 0x20 { + return Some((index, ResponseDefect::JsonControlCharacter)); + } else if byte == b'\\' { + let valid = match bytes.get(index + 1) { + Some(b'"' | b'\\' | b'/' | b'b' | b'f' | b'n' | b'r' | b't') => true, + Some(b'u') => bytes + .get(index + 2..index + 6) + .is_some_and(|hex| hex.iter().all(u8::is_ascii_hexdigit)), + Some(_) => false, + None => return None, + }; + if !valid { + return Some((index, ResponseDefect::JsonInvalidEscape)); + } + index += 1; } + index += 1; } + None +} + +/// Classify a parsed proposal value that does not match the proposal document (ADR-0098). +fn diagnose_proposal_value(value: &Value) -> ResponseDefect { + let Some(object) = value.as_object() else { + return ResponseDefect::NotJson; + }; + if STEP_FIELDS.iter().any(|field| object.contains_key(*field)) { + return ResponseDefect::StepFieldsAtTopLevel; + } + if ENVELOPE_FIELDS + .iter() + .any(|field| !object.contains_key(*field)) + { + return ResponseDefect::EnvelopeMissingField; + } + if object + .keys() + .any(|key| !ENVELOPE_FIELDS.contains(&key.as_str())) + { + return ResponseDefect::EnvelopeUnknownField; + } + let known_kind = object["kind"] + .as_str() + .is_some_and(|kind| matches!(kind, "plan" | "completion_candidate" | "response_candidate")); + if !known_kind || !object["formatVersion"].is_u64() || !object["summary"].is_string() { + return ResponseDefect::KindShape; + } + ResponseDefect::StepShape } /// Decode bounded JSON while rejecting duplicate object keys. @@ -2226,11 +2383,13 @@ fn decode_dependency(dependency: DependencyDocument) -> Result Result { if !json_depth_within(body, max_depth) { - return Err(PlannerPortFailure::InvalidResponse); + return Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); } serde_json::from_slice::(body) .map(|value| value.0) - .map_err(|_| PlannerPortFailure::InvalidResponse) + .map_err(|_| PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified)) } /// Insert the closers implied by each mismatched `}` or `]` (ADR-0068). @@ -2738,7 +2897,12 @@ mod tests { ); let decoded = planner.decode_proposal(&response(&plan.to_string(), "stop")); if count == 0 || count > limit.max_steps() { - assert!(matches!(decoded, Err(PlannerPortFailure::InvalidResponse))); + assert!(matches!( + decoded, + Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified + )) + )); } else { assert!( matches!(decoded, Ok(PlanProposal::Plan { steps }) if steps.len() == count) @@ -3029,7 +3193,12 @@ mod tests { other["key"] = json!("other"); other["capability"]["capabilityId"] = json!("xgeny.process/execute"); mixed["steps"].as_array_mut().unwrap().push(other); - assert_eq!(decode(&mixed), Err(PlannerPortFailure::InvalidResponse)); + assert_eq!( + decode(&mixed), + Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::StepShape + )) + ); let duplicate = plan .to_string() .replace("\"value\":1", "\"value\":1,\"value\":2"); @@ -3041,7 +3210,9 @@ mod tests { 64, true, ), - Err(PlannerPortFailure::InvalidResponse) + Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::JsonSyntax + )) ); let mut deep = json!({}); for _ in 0..65 { @@ -3049,7 +3220,12 @@ mod tests { } let mut too_deep = plan.clone(); too_deep["steps"][0]["arguments"]["jsonContent"] = deep; - assert_eq!(decode(&too_deep), Err(PlannerPortFailure::InvalidResponse)); + assert_eq!( + decode(&too_deep), + Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified + )) + ); assert_eq!( decode_chat_response_with_codec( &response(&plan.to_string(), "stop"), @@ -3058,7 +3234,9 @@ mod tests { 64, true, ), - Err(PlannerPortFailure::InvalidResponse) + Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::ResponseTooLarge + )) ); assert_eq!( decode_chat_response_with_codec( @@ -3575,10 +3753,14 @@ mod tests { let duplicate = r#"{"formatVersion":1,"kind":"completion_candidate","steps":[],"summary":"one","summary":"two"}"#; let unknown = r#"{"formatVersion":1,"kind":"completion_candidate","steps":[],"summary":"done","extra":true}"#; let fenced = "```json\n{\"formatVersion\":1}\n```"; - for content in [duplicate, unknown, fenced] { + for (content, defect) in [ + (duplicate, ResponseDefect::JsonSyntax), + (unknown, ResponseDefect::EnvelopeUnknownField), + (fenced, ResponseDefect::NotJson), + ] { assert_eq!( decode_chat_response(&response(content, "stop"), MODEL, 256 * 1024, 64), - Err(PlannerPortFailure::InvalidResponse) + Err(PlannerPortFailure::InvalidResponse(defect)) ); } assert_eq!( @@ -3587,7 +3769,9 @@ mod tests { ); assert_eq!( decode_chat_response(&response(&valid_plan(), "stop"), MODEL, 8, 64), - Err(PlannerPortFailure::InvalidResponse) + Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::ResponseTooLarge + )) ); let deep = format!( "{{\"formatVersion\":1,\"kind\":\"plan\",\"steps\":[],\"summary\":\"\",\"x\":{}}}", @@ -3595,7 +3779,9 @@ mod tests { ); assert_eq!( decode_chat_response(&response(&deep, "stop"), MODEL, 256 * 1024, 64), - Err(PlannerPortFailure::InvalidResponse) + Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified + )) ); } @@ -3618,18 +3804,21 @@ mod tests { #[test] fn closers_are_not_invented_for_truncated_or_unmatched_json() { - for content in [ + for (content, defect) in [ // still open at the end: truncation is never completed - r#"{"formatVersion":1,"kind":"plan","steps":[{"key":"a""#, + ( + r#"{"formatVersion":1,"kind":"plan","steps":[{"key":"a""#, + ResponseDefect::JsonTruncated, + ), // a closer with no matching open container - r#"{"formatVersion":1}]"#, + (r#"{"formatVersion":1}]"#, ResponseDefect::JsonSyntax), // the extra closer after a full object - r#"{"steps":[{"a":1}]}}"#, + (r#"{"steps":[{"a":1}]}}"#, ResponseDefect::JsonSyntax), ] { assert_eq!(rebalance_json_closers(content), None, "{content}"); assert_eq!( decode_chat_response(&response(content, "stop"), MODEL, 256 * 1024, 64), - Err(PlannerPortFailure::InvalidResponse) + Err(PlannerPortFailure::InvalidResponse(defect)) ); } // brackets inside strings never count @@ -3654,7 +3843,9 @@ mod tests { for body in [no_choices, two_choices] { assert_eq!( decode_chat_response(&body, MODEL, 256 * 1024, 64), - Err(PlannerPortFailure::InvalidResponse) + Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified + )) ); } @@ -3683,7 +3874,9 @@ mod tests { for body in [wrong_model, legacy_function_call] { assert_eq!( decode_chat_response(&body, MODEL, 256 * 1024, 64), - Err(PlannerPortFailure::InvalidResponse) + Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified + )) ); } } @@ -3735,7 +3928,12 @@ mod tests { max_response_bytes: 4, }); server.join().expect("server should finish"); - assert_eq!(result, Err(PlannerPortFailure::InvalidResponse)); + assert_eq!( + result, + Err(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified + )) + ); } #[test] @@ -4542,4 +4740,108 @@ mod tests { .request_profile_digest() ); } + + fn defect_of(content: &str) -> ResponseDefect { + let body = serde_json::to_vec(&json!({ + "model": MODEL, + "choices": [{"index": 0, "finish_reason": "stop", + "message": {"role": "assistant", "content": content}}], + })) + .unwrap(); + match decode_chat_response( + &body, + MODEL, + DEFAULT_MAX_PROPOSAL_BYTES, + DEFAULT_MAX_JSON_DEPTH, + ) { + Err(PlannerPortFailure::InvalidResponse(defect)) => defect, + other => panic!("expected an invalid response, got {other:?}"), + } + } + + const STEP: &str = r#""key":"run","objective":"Run it","dependsOn":[],"capability":{"capabilityId":"xgeny.process/execute","contractVersion":"1.0.0"},"arguments":{"args":["-c","echo hi"]}"#; + + #[test] + fn json_text_defects_are_classified_where_the_parser_stopped() { + let plan = |arg: &str| { + format!( + r#"{{"formatVersion":1,"kind":"plan","steps":[{{"key":"run","objective":"Run","dependsOn":[],"capability":{{"capabilityId":"xgeny.process/execute","contractVersion":"1.0.0"}},"arguments":{{"args":["-c","{arg}"]}}}}],"summary":""}}"# + ) + }; + assert_eq!( + defect_of(&plan("cat <, + #[serde(skip_serializing_if = "Option::is_none")] + response_defect: Option, meaning: &'static str, } @@ -509,7 +511,77 @@ impl PreviousResponseRejection { Self { reason: feedback.reason, proposal_rejection: feedback.proposal, - meaning: rejection_meaning(feedback.reason, feedback.proposal), + response_defect: feedback.response_defect, + meaning: match (feedback.reason, feedback.response_defect) { + (ModelCallRejectionReason::PlannerInvalidResponse, Some(defect)) => { + response_defect_meaning(defect) + } + _ => rejection_meaning(feedback.reason, feedback.proposal), + }, + } + } +} + +/// Fixed statement of which part of the response contract a discarded response broke (ADR-0098). +/// Names contract fields only; never echoes the response. +const fn response_defect_meaning(defect: ResponseDefect) -> &'static str { + match defect { + ResponseDefect::NotJson => { + "The previous response was discarded: it was not a single JSON object. Return only \ + the JSON object, with no prose or Markdown around it. Nothing was changed." + } + ResponseDefect::JsonControlCharacter => { + "The previous response was discarded: a JSON string contained a raw line break, tab \ + or other control character. Inside strings write them as \\n, \\t or \\uXXXX. \ + Nothing was changed." + } + ResponseDefect::JsonInvalidEscape => { + "The previous response was discarded: a JSON string contained a backslash escape \ + that JSON does not define. Write a literal backslash as \\\\. Nothing was changed." + } + ResponseDefect::JsonTruncated => { + "The previous response was discarded: the JSON ended before every string, object \ + and array was closed. Return a complete object. Nothing was changed." + } + ResponseDefect::JsonSyntax => { + "The previous response was discarded: it was not valid JSON. A common cause is a \ + double quote inside a string that is not written as \\\". Long multi-line text in \ + one string makes this more likely. Nothing was changed." + } + ResponseDefect::EnvelopeMissingField => { + "The previous response was discarded: the top-level object needs exactly \ + formatVersion, kind, steps and summary, and one was missing. Nothing was changed." + } + ResponseDefect::EnvelopeUnknownField => { + "The previous response was discarded: the top-level object had a field other than \ + formatVersion, kind, steps and summary. Nothing was changed." + } + ResponseDefect::StepFieldsAtTopLevel => { + "The previous response was discarded: Step fields (key, objective, dependsOn, \ + capability, arguments) were written at the top level. Put each Step object inside \ + the steps array of the top-level object with formatVersion, kind, steps and \ + summary. Nothing was changed." + } + ResponseDefect::StepShape => { + "The previous response was discarded: a Step or dependency did not match the \ + contract. A Step has exactly key, objective, dependsOn, capability and arguments; a \ + dependency has kind, stepId and key. Nothing was changed." + } + ResponseDefect::KindShape => { + "The previous response was discarded: formatVersion must be 1, kind plan needs Steps \ + and an empty summary, and a candidate kind needs no Steps and a non-empty summary. \ + Nothing was changed." + } + ResponseDefect::ResponseTooLarge => { + "The previous response was discarded: it was larger than the response size limit. \ + Propose fewer or smaller Steps. Nothing was changed." + } + ResponseDefect::CompletionCheckFailed => { + "The previous response was discarded: its completion or response candidate failed a \ + host completion check. Nothing was changed." + } + ResponseDefect::Unclassified => { + rejection_meaning(ModelCallRejectionReason::PlannerInvalidResponse, None) } } } @@ -857,8 +929,9 @@ pub enum PlannerPortFailure { Timeout, #[error("planner is unavailable")] Unavailable, + /// The response broke the response contract; the defect class is journaled (ADR-0098). #[error("planner response could not be decoded")] - InvalidResponse, + InvalidResponse(ResponseDefect), #[error("planner request exceeded provider limits")] ProviderLimit, #[error("planner request is too large")] @@ -1963,14 +2036,15 @@ impl AgentLoop { ), ModelCallConflictIntent::MarkUnknown(ModelCallUnknownReason::TransportUnavailable), ), - PlannerPortFailure::InvalidResponse => ( - append_model_call_rejection( + PlannerPortFailure::InvalidResponse(defect) => ( + append_model_call_rejection_with_defect( store, events, reserved_state, call_id, ModelCallRejectionReason::PlannerInvalidResponse, None, + Some(defect), ), ModelCallConflictIntent::RejectStale, ), @@ -2169,6 +2243,22 @@ fn append_model_call_rejection( reason: ModelCallRejectionReason, proposal: Option, ) -> Result +where + S: RunStore, + F: EventFactory, +{ + append_model_call_rejection_with_defect(store, events, state, call_id, reason, proposal, None) +} + +fn append_model_call_rejection_with_defect( + store: &mut S, + events: &mut F, + state: &RunState, + call_id: &str, + reason: ModelCallRejectionReason, + proposal: Option, + response_defect: Option, +) -> Result where S: RunStore, F: EventFactory, @@ -2178,7 +2268,11 @@ where state, RunEventBody::ModelCallSettled { call_id: call_id.to_owned(), - settlement: ModelCallSettlement::Rejected { reason, proposal }, + settlement: ModelCallSettlement::Rejected { + reason, + proposal, + response_defect, + }, }, )?; Ok(store.append(ExpectedHead::from_state(state), event)?) diff --git a/crates/xgen-runtime/src/lib.rs b/crates/xgen-runtime/src/lib.rs index e43a770..df0a74d 100644 --- a/crates/xgen-runtime/src/lib.rs +++ b/crates/xgen-runtime/src/lib.rs @@ -26,7 +26,7 @@ pub use registry::*; pub use router::*; pub use runtime::*; pub use verification::*; -pub use xgen_workgraph::StepFailureCode; +pub use xgen_workgraph::{ResponseDefect, StepFailureCode}; pub(crate) const LOCAL_EXECUTOR_ID: &str = "xgeny-local"; diff --git a/crates/xgen-runtime/tests/durable_agent_loop.rs b/crates/xgen-runtime/tests/durable_agent_loop.rs index def389a..66eaa70 100644 --- a/crates/xgen-runtime/tests/durable_agent_loop.rs +++ b/crates/xgen-runtime/tests/durable_agent_loop.rs @@ -17,7 +17,7 @@ use xgen_runtime::{ AgentLoop, AgentLoopError, AgentLoopQuiescence, AgentLoopTick, EventFactory, EventFactoryError, EventMetadata, PlanDependency, PlanMaterializationRequest, PlanMaterializer, PlanMaterializerFailure, PlanProposal, PlannerCallRequest, PlannerPort, PlannerPortFailure, - ProposalRejection, ProposedPlanStep, RunLease, + ProposalRejection, ProposedPlanStep, ResponseDefect, RunLease, }; use xgen_workgraph::{ AgentLoopBudget, AgentLoopState, CompletionOutputRecord, ContinuationAction, EventRecord, @@ -613,6 +613,7 @@ impl RunStore for StalePlanOutcomeStore { settlement: ModelCallSettlement::Rejected { reason: ModelCallRejectionReason::PlannerInvalidResponse, proposal: None, + response_defect: None, }, }, }; @@ -1452,7 +1453,9 @@ fn invalid_provider_response_is_durably_rejected_without_an_accepted_turn() { create_run(&mut store, run_id); let agent_loop = configure(&mut store, run_id, &loop_budget); let before = store.load_current().unwrap().unwrap(); - let mut planner = ScriptedPlanner::failing(PlannerPortFailure::InvalidResponse); + let mut planner = ScriptedPlanner::failing(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); let tick = agent_loop .tick( &mut store, @@ -1467,7 +1470,7 @@ fn invalid_provider_response_is_durably_rejected_without_an_accepted_turn() { assert!(matches!( tick, AgentLoopTick::PlannerUnavailable { - failure: PlannerPortFailure::InvalidResponse, + failure: PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified), .. } )); @@ -3036,7 +3039,7 @@ fn model_call_budget_is_independent_from_accepted_turn_budget() { let agent_loop = configure_instance(&mut store, run_id, agent_loop); for failure in [ - PlannerPortFailure::InvalidResponse, + PlannerPortFailure::InvalidResponse(ResponseDefect::Unclassified), PlannerPortFailure::ProviderLimit, PlannerPortFailure::ProviderRejected, ] { @@ -3171,7 +3174,9 @@ fn known_failure_settlement_head_conflict_closes_the_call_as_stale() { let mut store = OutcomeConflictStore::new(OutcomeConflictTarget::Settled); create_run(&mut store, run_id); let agent_loop = configure(&mut store, run_id, &loop_budget); - let mut planner = ScriptedPlanner::failing(PlannerPortFailure::InvalidResponse); + let mut planner = ScriptedPlanner::failing(PlannerPortFailure::InvalidResponse( + ResponseDefect::Unclassified, + )); let outcome = agent_loop .tick( &mut store, diff --git a/crates/xgen-workgraph/src/lib.rs b/crates/xgen-workgraph/src/lib.rs index 0e755c3..ebe3510 100644 --- a/crates/xgen-workgraph/src/lib.rs +++ b/crates/xgen-workgraph/src/lib.rs @@ -1611,6 +1611,41 @@ pub enum ProposalRejectionCode { InvalidCompletionSummary, } +/// Closed, value-free class of a response the provider adapter could not decode (ADR-0098). +/// +/// It names which part of the response contract was broken, never the response content, so it is +/// safe to journal and to show the planner on its next turn. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ResponseDefect { + /// The text was not a JSON object at all (prose, a refusal notice, an array). + NotJson, + /// A string held a raw newline, tab or other control character. + JsonControlCharacter, + /// A string held a backslash escape JSON does not define. + JsonInvalidEscape, + /// The JSON ended before every string, object and array was closed. + JsonTruncated, + /// Any other JSON syntax error, typically an unescaped `"` inside a string. + JsonSyntax, + /// A response envelope field was missing. + EnvelopeMissingField, + /// The response envelope had a field the contract does not define. + EnvelopeUnknownField, + /// Step fields were written at the top level instead of inside `steps`. + StepFieldsAtTopLevel, + /// A step or dependency did not have the contract's fields and values. + StepShape, + /// `formatVersion` or the fields required by `kind` did not match. + KindShape, + /// The response was larger than the proposal limit. + ResponseTooLarge, + /// A completion or response candidate failed a host completion check. + CompletionCheckFailed, + /// The provider reply itself was malformed, or the defect has no finer class. + Unclassified, +} + /// The latest settled model call, kept only while it was a rejection and no call followed it. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -1618,6 +1653,8 @@ pub struct ModelCallRejectionFeedback { pub reason: ModelCallRejectionReason, #[serde(default, skip_serializing_if = "Option::is_none")] pub proposal: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub response_defect: Option, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -1650,6 +1687,10 @@ pub enum ModelCallSettlement { /// reasons and for settlements recorded before it existed. #[serde(default, skip_serializing_if = "Option::is_none")] proposal: Option, + /// Fixed class of a `planner_invalid_response` settlement (ADR-0098); absent for other + /// reasons and for settlements recorded before it existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + response_defect: Option, }, Abandoned { reason: ModelCallAbandonmentReason, @@ -4091,11 +4132,15 @@ fn settle_model_call( ModelCallSettlement::Abandoned { .. } => {} } calls.last_rejection = match settlement { - ModelCallSettlement::Rejected { reason, proposal } - if reason != ModelCallRejectionReason::StaleHead => - { - Some(ModelCallRejectionFeedback { reason, proposal }) - } + ModelCallSettlement::Rejected { + reason, + proposal, + response_defect, + } if reason != ModelCallRejectionReason::StaleHead => Some(ModelCallRejectionFeedback { + reason, + proposal, + response_defect, + }), _ => None, }; calls.settled_calls = calls diff --git a/crates/xgen-workgraph/tests/durable_model_call.rs b/crates/xgen-workgraph/tests/durable_model_call.rs index 5569150..f82732b 100644 --- a/crates/xgen-workgraph/tests/durable_model_call.rs +++ b/crates/xgen-workgraph/tests/durable_model_call.rs @@ -489,6 +489,7 @@ fn rejected_calls_consume_call_budget_but_not_accepted_turn_budget() { settlement: ModelCallSettlement::Rejected { reason: ModelCallRejectionReason::PlannerInvalidResponse, proposal: None, + response_defect: None, }, }, ); @@ -785,6 +786,7 @@ fn unknown_call_blocks_late_response_until_explicit_abandonment() { settlement: ModelCallSettlement::Rejected { reason: ModelCallRejectionReason::ProposalRejected, proposal: None, + response_defect: None, }, }, ), @@ -856,6 +858,7 @@ fn stale_head_requires_stale_rejection_and_other_rejections_require_immediate_he settlement: ModelCallSettlement::Rejected { reason: ModelCallRejectionReason::ProposalRejected, proposal: None, + response_defect: None, }, }, ), @@ -869,6 +872,7 @@ fn stale_head_requires_stale_rejection_and_other_rejections_require_immediate_he settlement: ModelCallSettlement::Rejected { reason: ModelCallRejectionReason::StaleHead, proposal: None, + response_defect: None, }, }, ); @@ -901,6 +905,7 @@ fn stale_head_requires_stale_rejection_and_other_rejections_require_immediate_he settlement: ModelCallSettlement::Rejected { reason: ModelCallRejectionReason::StaleHead, proposal: None, + response_defect: None, }, }, ), diff --git a/docs/adr/0098-specific-response-defect-feedback.md b/docs/adr/0098-specific-response-defect-feedback.md new file mode 100644 index 0000000..d92f7fb --- /dev/null +++ b/docs/adr/0098-specific-response-defect-feedback.md @@ -0,0 +1,134 @@ +# ADR-0098: 형식 거절의 구체 이유를 다음 요청에 전달하기 + +- 날짜: 2026-11-29 +- 상태: 1번 구현(2026-11-30, 사용자 승인). 2번(문자열 보정)은 1번 실측 뒤 별도 판단. 실측 대기. +- 변경 분류: 범용 provider 응답 해석·planning feedback. 특정 과업·언어·모델 규칙 없음. +- 기존 경계: ADR-0061(거절 응답 2회 재시도), ADR-0064(`previousResponseRejection`), ADR-0068(닫는 괄호 보정) +- protocol·journal 변경: `Rejected` settlement와 `previousResponseRejection`에 선택 필드 `responseDefect` + (고정 code)가 붙는다. 없으면 직렬화하지 않는다. 거절이 없던 요청은 바이트가 같다. + +## 문제 + +약한 모델 하네스 연구(Terminal-Bench 2.1, agy `gemini-3.8-flash-low`, 89과업 기준선 34개 통과)에서 bridge가 +받은 정상 응답 1,482개 중 146개(9.9%)가 `planner_invalid_response`로 거절됐다. 8과업은 3연속 거절로 +Run이 끝났다. + +거절된 응답을 xgen과 같은 규칙으로 다시 분류했다(`bench/harbor/classify_responses.py --repair`). + +| 갈래 | 세부 | 건수 | +|---|---|---| +| 문자열 escape | 문자열 안 날 줄바꿈·제어 문자 | 28 | +| | 잘못된 escape(`\d`, `\s` 등) | 17 | +| | escape 안 한 `"`로 문법 깨짐(`,` 기대) | 14 | +| | 끝 잘림·뒤에 남은 데이터 | 3 | +| 봉투 구조 | Step 필드를 봉투 최상위에 펼침(`steps` 없음) | 46 | +| | 봉투 없이 Step 하나만 | 14 | +| | `plan`인데 `summary` 없음 | 9 | +| | 기타 필드 누락·알 수 없는 필드 | 2 | +| JSON 아님 | 모델 쪽 안전 필터 문구 | 13 | + +- 문자열 escape 오류는 거의 모두 `bash -c` 인자에 여러 줄 코드를 넣을 때 났다. +- 봉투 구조 오류는 내용은 맞는데 감싸는 모양이 틀렸다. + +거절된 다음 응답은 대부분 정상이었다(구조 56/71, escape 44/60). 같은 갈래를 다시 틀린 건 23건이다. +3연속 거절로 끝난 8과업을 보면 4과업은 세 번 모두 같은 갈래였다(escape 2, 구조 1, 필터 1). 나머지 4과업은 escape와 +구조 오류가 섞였다. + +지금 모델이 받는 건 고정 문장 하나뿐이다. "contract에 안 맞거나 completion check에 실패했다." 무엇이 틀렸는지 +모르니, 같은 모양을 다시 내면 고칠 단서가 없다. + +## 결정 (제안) + +### 1. 거절 이유를 고정 code로 분류해 전달 + +Provider가 응답 해석에 실패하면 이유를 고정 code `responseDefect`로 낸다. 응답 내용(경로, 인자, 위치)은 담지 +않는다. ADR-0064와 같이 code마다 고정 영어 문장 `meaning`이 붙는다. + +| code | 판정 | meaning 요지 | +|---|---|---| +| `not_json` | JSON으로 시작하지 않음 | 응답 전체가 JSON 객체 하나여야 한다 | +| `json_control_character` | 문자열 안 날 제어 문자 | 줄바꿈·탭은 `\n`, `\t`로 escape | +| `json_invalid_escape` | 허용 안 된 escape | 역슬래시 자체는 `\\`로 | +| `json_syntax` | 그 밖의 문법 오류 | 문자열 안 `"`는 `\"`로. 긴 여러 줄 내용은 escape 실수를 늘린다 | +| `json_truncated` | 끝나기 전에 끊김 | 응답을 끝까지 닫을 것 | +| `envelope_missing_field` | 봉투 필드 누락 | `formatVersion`, `kind`, `steps`, `summary` 네 필드가 모두 있어야 한다 | +| `step_fields_at_top_level` | Step 필드가 봉투 최상위에 있음 | Step은 `steps` 배열 안에 넣는다 | +| `envelope_unknown_field` | 알 수 없는 필드 | 계약에 있는 필드만 | +| `step_shape` | Step·dependency 모양 위반 | Step 필드 목록 | +| `kind_shape` | `plan`에 summary, candidate에 steps | kind별 필드 규칙 | +| `completion_check_failed` | 형식은 맞으나 host completion check 실패 | 기존 문장 유지 | + +필드 이름은 계약 상수라 응답을 되돌려 보내는 게 아니다. 분류는 serde 오류 범주와 계약 검사 순서로 정한다. +특정 모델 출력 모양에 맞춘 문자열 비교는 하지 않는다. + +**구현** +- `PlannerPortFailure::InvalidResponse(ResponseDefect)`가 code를 싣는다. +- runtime이 `ModelCallSettlement::Rejected.response_defect`로 journal에 남기고, 다음 context의 + `previousResponseRejection.responseDefect`와 code별 `meaning`으로 넘긴다. +- JSON 문법 오류는 serde가 멈춘 위치와, 문자열 상태만 추적하는 스캔이 찾은 첫 결함 위치가 같을 때만 + 제어 문자·escape로 본다. 그래서 escape 안 한 `"`가 문자열을 일찍 닫은 경우는 뒤에 있는 줄바꿈 때문에 + 잘못 분류되지 않는다. +- 봉투 오류는 Step 필드가 최상위에 있는지 먼저 보고, 그다음 봉투 필드 누락, 알 수 없는 필드, + kind·formatVersion 순으로 본다. +- agy transport는 응답을 미리 JSON 검사하던 단계를 뺐다. 이제 HTTP와 같은 decoder가 판정하고 분류한다. + 그 결과 agy 응답도 ADR-0068 닫는 괄호 보정을 받는다(전에는 사전 검사에서 먼저 거절됐다). +- provider 응답 봉투 자체의 결함과 그 밖의 경우는 `unclassified`이고, 기존 문장을 쓴다. + +**검증** +- 기준선 bridge 응답 1,511개에 Rust decoder를 직접 돌렸다. 거절 146건이 모두 구체 code로 분류됐고 + `unclassified`는 0건이다. Python 분석과 갈래가 일치한다. 빈 응답 2건은 `not_json`이다. +- `diff-model-requests`: 8개 사례 중 거절 재시도 사례만 `meaning`이 바뀌고 `responseDefect`가 붙었다. + 다른 요청은 같다(`durationMs` 실행 시간 차이 제외). + +### 2. 뜻이 하나뿐인 문자열 보정 (선택, 별도 판단) + +ADR-0068(닫는 괄호 보정)과 같은 성격의 보정이다. 문자열 안의 두 경우는 뜻이 하나뿐이다. + +- **날 제어 문자:** 그 문자를 쓰려던 것밖에 없다. escape해서 넣는다. +- **허용 안 된 `\x`:** 역슬래시 글자를 쓰려던 것밖에 없다. `\\x`로 바꾼다. + +이 보정은 기존 해석이 실패했을 때 한 번만 시도한다. 보정 결과도 같은 계약 검사를 모두 통과해야 받는다. + +오프라인 재분류에서는 escape 갈래 62건 중 22건(문자열 오류 146건의 15%)이 그대로 유효한 plan이 됐다. escape +안 한 `"`는 어디서 문자열이 끝났는지 모호하다. 그래서 보정하지 않고, 1번의 이유 전달에 맡긴다. + +### 범위 밖 + +- **안전 필터 문구**(13건)는 모델이 아니라 provider 쪽 거절이다. transport가 이를 구분할 수 있는지는 별도 + 과제다(agy 쪽). +- **3연속 한도(ADR-0061) 조정**은 하지 않는다. 이유를 준 뒤에도 같은 갈래가 이어지는지 먼저 본다. +- **Structured output(json_schema)으로 강제하기:** 지원하는 HTTP provider는 이미 쓸 수 있다. agy처럼 강제할 + 수 없는 transport를 위한 결정이다. + +## 측정 계획 + +**설계와 held-out 분리** +- 위 분류는 ADR-0097 이전 기준선 bridge 기록(1,482응답)으로 만들었다. 이게 설계 데이터다. +- held-out 1: ADR-0097 실측(설계 16·held-out 16과업)에서 새로 쌓이는 응답에 같은 분류기를 돌린다. 같은 code + 집합이 거절의 95% 이상을 덮는지 본다. +- held-out 2(실측): 3연속으로 끝난 8과업은 설계 쪽이다. held-out은 기준선에서 invalid가 많았던 다른 과업 8개다. + 결과를 보기 전에 고정했다. + - 설계: break-filter-js-from-html, circuit-fibsqrt, feal-differential-cryptanalysis, + feal-linear-cryptanalysis, gcode-to-text, headless-terminal, protein-assembly, write-compressor + - held-out: large-scale-text-editing, extract-elf, vulnerable-secret, crack-7z-hash, + llm-inference-batching-scheduler, extract-moves-from-video, gpt2-codegolf, path-tracing-reverse + - 비교는 ADR-0097만 적용한 바이너리와 ADR-0097+0098 바이너리다(요청 크기로 일찍 멈추는 효과를 빼려고). + +**지표** +- 호출당 invalid 비율 +- 거절 뒤 같은 갈래 반복률(지금 23/131) +- 3연속 종료 과업 수 +- 통과율 +- 과업당 호출 수 + +**회귀 확인** +- 거절이 없는 요청은 `diff-model-requests` 바이트 동일 +- 거절 뒤 요청은 `meaning`과 `responseDefect`만 달라야 한다 + +## 예상 한계 + +- 이유를 알아도 약한 모델이 긴 코드를 JSON 문자열에 넣는 한 escape 실수는 남는다. 근본적으로 줄이려면 여러 줄 + 내용을 escape 없이 전달하는 경로가 필요하다. 예: 파일 쓰기 capability를 쓰도록 유도하기. 이건 측정 뒤 다음 + 후보로 본다. +- code 집합은 이 모델의 오류 분포에서 나왔다. 다른 provider에서 다른 갈래가 많으면 `json_syntax`로 모인다. + 그래도 지금보다 나빠지지는 않는다.