小壹原请求查无记录超过恢复预算后按未发起收口

This commit is contained in:
WuYongJie 2026-11-30 02:12:54 +08:00
parent 194943e01d
commit 39fe1a08a0
3 changed files with 103 additions and 8 deletions

View File

@ -115,7 +115,7 @@ export const productionOperationTools = [
['delegate_image_slots','异步分派制作任务。每个 job 的 slotId 是主图位,reuseTargets 可列同花色的额外目标图位,每项含 slotId 和可选 outputId。组内助手可查同花色候选并裁切到组内图位,可写画布上的候选可显式采用。返回分派状态与待写文案字段。',obj({
...outputScope,jobs:Type.Array(obj({slotId:slotRef,goal:text,reuseTargets:optional(Type.Array(reuseTarget)),reworkCandidateId:optional(Type.String({description:'返工时,指定之前被退回的候选号。'}))})),
})],
['await_image_slots','等待在途制作、验图或生图请求返回,提供状态、编号和修改摘要。状态为 complete 的候选可用 check_image_slots 验图。waitForAll=true 等待选中范围内调用时已在途的工作。单次最多等待 3 分钟,超时后原工作继续。省略 slotIds 时也关注整屏复核,完整意见用 read_screen_review 按屏读取;图位详情用 review_image_slots。omitted 是因体积限制省略的条数。未知结果用 reconcile_image_slots 核查,waiting_canvas 表示等待可写画布。',obj({...outputScope,slotIds:optional(ids),waitForAll:optional(Type.Boolean())})],
['await_image_slots','等待在途制作、验图或生图请求返回,提供状态、编号和修改摘要。状态为 complete 的候选可用 check_image_slots 验图。waitForAll=true 等待选中范围内调用时已在途的工作。单次最多等待 3 分钟,超时后原工作继续。省略 slotIds 时也关注整屏复核,完整意见用 read_screen_review 按屏读取;图位详情用 review_image_slots。omitted 是因体积限制省略的条数。expired 表示原请求已收口,可为同图位另备新请求。未知结果用 reconcile_image_slots 核查,waiting_canvas 表示等待可写画布。',obj({...outputScope,slotIds:optional(ids),waitForAll:optional(Type.Boolean())})],
['review_image_slots','只读查看指定成品和花色的候选、验图、原请求、覆盖统计与整屏复核进度。screensReadyForReview 是图位已齐、当前画面待复核的多图位屏。waiting_canvas 的图位在等待切回可写画布。指定 slotIds 查看详情,或在 slotIds 填写一个图位并指定 candidateId 查看实际候选像素;批量详情超出预算时返回摘要,用 nextOffset 作为 offset 翻页,再用单个 slotId 查看全文。',obj({...outputScope,slotIds:optional(Type.Array(Type.String())),candidateId:optional(text),offset:optional(Type.Integer({minimum:0}))})],
['list_project_images','列出本项目已完成且可读的候选,包括有采纳记录的图。可按来源成品和花色筛选,生图次数取自宿主已派发的记录。sourceCandidateId 可引用任一成品的同花色候选做本地变换或复用。用 nextOffset 作为 offset 翻页,candidateId 展开单条。',obj({...outputScope,candidateId:optional(Type.String()),offset:optional(Type.Integer({minimum:0}))})],
['read_archived_images','只读查找其他本机项目同款的历史候选。可选 slotIds 查看有对应图位的结果。不同模板或花色的已完成候选也可放入当前图位复核。用 nextOffset 作为 offset 翻页,candidateId 展开单条,可用 projectId 指定来源项目。',obj({
@ -129,7 +129,7 @@ export const productionOperationTools = [
})],
['adopt_production_image','采用选定的候选,返回画布修订和模板叠层。可用 reason 记录采用理由。单图位屏与已有验图画面一致时附复核结论。screensReadyForReview 列出图位已齐、待复核的多图位屏。可用 read_output_screen 查看整屏合成画面。',obj({slotId:slotRef,candidateId:text,fit:optional(fit),reason:optional(text)})],
['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})],
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。状态为 complete 的候选可用 check_image_slots 验图。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号,结果有留存时按原号取回,不重新付费。expired 表示原结果已不可取回:网关确认结果过期(HTTP 410)、结果链接下载返回 404 或 410,或原请求在 180 秒恢复预算用完后仍是 unresolved。expired 可以为同图位另备新请求;已派发的原请求仍计入该图位的生图次数上限。',obj({...outputScope,slotIds:optional(ids)})],
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。状态为 complete 的候选可用 check_image_slots 验图。未绑定画布时核查本轮项目输出,可用完整图位 id 缩小范围。unknown 继续核查原号,结果有留存时按原号取回,不重新付费。expired 表示原请求已收口。网关确认结果过期(HTTP 410)、结果链接下载返回 404 或 410,或 180 秒恢复预算用完后原查询仍是 unresolved 或 404 request_not_found,都会进入此终态。404 request_not_found 收口时按未发起处理。expired 可以为同图位另备新请求;按未发起处理的请求不计入该图位的生图次数,其他已派发请求仍计入。',obj({...outputScope,slotIds:optional(ids)})],
['read_output_screen',`读取整屏合成画面、模板差异摘要、overlayLayers、slotGeometry 和 annotationLayout。局部查看用 page 和 region(画布坐标 [x,y,w,h]),zoom 为 1–4 倍,图上网格标的是原画布坐标。annotationLayout 提供可见文字、线端点、穿线长度、主体框重叠比例和双向最近距离。用 includeTemplateImage 读取模板原屏,用 templateLayerId 查具体图层的完整原值与现值。若返回 nextChangeOffset,可用 templateChangeOffset 继续读差异。subjectBounds 是画布坐标 [x,y,w,h],由放置后的像素与边缘背景的色差估测,并裁到图位可见框内。测不出时由 subjectBoundsReason 说明原因。page 指定单屏,pages 可按需查看 2–4 屏,屏号从 0 开始。只保留最新一次查看图片。${OVERLAY_SCREEN_FIELDS}`,obj({
page:optional(page),pages:optional(Type.Array(page)),
region:optional(Type.Tuple([Type.Integer(),Type.Integer(),Type.Integer({minimum:1}),Type.Integer({minimum:1})])),
@ -569,7 +569,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
const liveSlot=async slot=>(await liveSlots()).find(row=>row.id===slot.id)??slot;
const nativeGenerations=slot=>[
...(slot.generationRequestIds??(slot.candidates??[]).filter(row=>
!row.sourceType&&!row.reusedFrom&&row.status!=='prepared').map(row=>row.id)),
!row.sourceType&&!row.reusedFrom&&row.status!=='prepared'&&row.resultExpiry?.source!=='request_not_found').map(row=>row.id)),
...[...dispatchingImages].filter(([,job])=>job?.slotId===slot.id).map(([id])=>id),
];
const drawStatus=generationAttempts=>({
@ -991,7 +991,8 @@ export async function openProductionOperations(host,{target=host.productionGoal,
(receipt.operationId&&row.operationId===receipt.operationId||receipt.candidateId&&row.candidateId===receipt.candidateId));
generation.set(original?.[0]??receipt.operationId??receipt.candidateId??slot.id,receipt);
}
const heading=recoveryNotices[receipt.phase];
const heading=receipt.resultExpiry?.source==='request_not_found'
? '网关没有原请求记录,按未发起处理' : recoveryNotices[receipt.phase];
if(heading&&!(receipt.phase==='complete'&&alreadyPlaced&&journal.items[slot.id]?.pendingAdoption)){
if(receipt.candidateId){
if(adopting&&receipt.phase==='complete'){
@ -1543,8 +1544,10 @@ export async function openProductionOperations(host,{target=host.productionGoal,
(slot.candidates??[]).filter(row=>!row.sourceType&&!row.reusedFrom).map(row=>
({...row,slotId:slot.id,candidateId:row.id,operationId:row.id,phase:row.status,reason:row.message??row.error})))
.sort((a,b)=>(b.sequence??0)-(a.sequence??0));
const settledNativeIds=new Set(native.filter(row=>settledImagePhases.includes(row.phase)).map(row=>row.candidateId));
const currentReceipt=row=>settledImagePhases.includes(row.phase)||!settledNativeIds.has(row.candidateId);
const completed=(Array.isArray(receipt)?receipt:[receipt])
.filter(row=>row?.operationId&&scope.has(row.slotId));
.filter(row=>row?.operationId&&scope.has(row.slotId)&&currentReceipt(row));
const targets=new Map(live.map(slot=>[slot.id,slotTarget(slot)]));
const completedIds=new Set(completed.map(row=>row.candidateId));
const waiting=[...waitingCanvas.keys()].filter(id=>wanted.has(id)).map(slotId=>({slotId,phase:'waiting_canvas'}));
@ -1559,7 +1562,7 @@ export async function openProductionOperations(host,{target=host.productionGoal,
})),
];
return summarizeImageWait({...output,active:jobs.size,checking:pendingReviews().length,progressSummary:summary,
generation:[...waiting,...completed,...generationReceipts(scope),...native.filter(row=>!completedIds.has(row.candidateId))]
generation:[...waiting,...completed,...generationReceipts(scope).filter(currentReceipt),...native.filter(row=>!completedIds.has(row.candidateId))]
.map(row=>({...row,target:targets.get(row.slotId)??row.target})),
checks:[...reviewWork].filter(job=>scope.has(job.row.slotId)).map(job=>job.receipt),
...(screens.length?{screenChecks:screens.map(job=>job.receipt)}:null),

View File

@ -1288,6 +1288,7 @@ fn generation_was_dispatched(record: &Value, task: Option<&Value>) -> bool {
record["sourceType"].is_null() && record["reusedFrom"].is_null()
&& task.map_or_else(|| matches!(record["phase"].as_str(), Some("complete" | "expired")),
|task| task["phase"] != "prepared")
&& task.unwrap_or(record)["resultExpiry"]["source"] != "request_not_found"
}
fn project_image_index(dir: &Path, filter: &Value) -> R<Value> {
@ -7172,6 +7173,26 @@ mod tests {
assert_eq!(pending_summary(&fixture.dir).unwrap()[0]["id"], next["id"]);
}
#[test]
fn lookup_not_found_releases_the_slot_without_charging_a_generation_attempt() {
let fixture = fixture();
let original = candidate(&fixture.dir, "dispatched");
let next = candidate(&fixture.dir, "dispatched");
reserve(&fixture.dir, load(&fixture.dir).unwrap(), &original).unwrap();
let mut task = json!({"id":original["id"],"slotBinding":original["binding"],"phase":"unknown"});
let pending = reconcile_candidate(&fixture.dir, &task).unwrap();
assert!(generation_was_dispatched(&pending, Some(&task)));
assert!(reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).is_err());
task["phase"] = json!("expired");
task["resultExpiry"] = json!({"source":"request_not_found","httpStatus":404});
let record = reconcile_candidate(&fixture.dir, &task).unwrap();
assert!(!generation_was_dispatched(&record, Some(&task)));
assert!(!generation_was_dispatched(&record, None));
assert!(pending_summary(&fixture.dir).unwrap().is_empty());
reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).unwrap();
}
#[test]
fn unresolved_original_releases_its_slot_once_the_recovery_budget_is_spent() {
let fixture = fixture();

View File

@ -324,6 +324,8 @@ fn job_save_locked(dir: &Path, t: &Value, current_only: bool) -> R<()> {
// image already completed or applied. No terminal state authorizes POST.
if matches!(existing["phase"].as_str(), Some("applied" | "failed" | "expired")) || existing["phase"] == "complete" && t["phase"] != "applied" {
settled = existing;
} else if let Some(since) = existing["requestNotFoundSince"].as_u64() {
settled["requestNotFoundSince"] = json!(settled["requestNotFoundSince"].as_u64().map_or(since, |current| current.min(since)));
}
}
if !archive.exists() || read_json(&archive)? != settled {
@ -503,6 +505,12 @@ fn locate_original(
) -> R<LocatedOriginal> {
let task_id = task["id"].as_str().filter(|id| Uuid::parse_str(id).is_ok()).ok_or("原任务身份无效,未发起查询")?.to_owned();
let (code, body) = get("/api/external/requests/by-idempotency-key", Some(&task_id))?;
if observed_wait("lookup", code, &body) == Some(RecoveryWait::RequestNotFound)
&& task["requestNotFoundSince"].is_null()
{
task["requestNotFoundSince"] = json!(now());
persist(task)?;
}
let located = located_original(code, &body, task);
let binding = match &located {
Ok(LocatedOriginal::Available(request) | LocatedOriginal::Unavailable(request)) => json!({"requestId":request}),
@ -671,6 +679,8 @@ pub(super) enum RecoveryWait {
Processing,
/// The original lookup has no confirmed outcome (`unresolved`).
Unresolved,
/// The gateway has no record for the original idempotency key.
RequestNotFound,
/// The deferred upstream task is still queued, running or finalizing.
Running,
/// A GET did not deliver a readable response or met a temporary gateway status.
@ -682,6 +692,7 @@ impl RecoveryWait {
match self {
Self::Processing => "processing",
Self::Unresolved => "unresolved",
Self::RequestNotFound => "request_not_found",
Self::Running => "running",
Self::Network => "network",
}
@ -703,6 +714,7 @@ fn query_kind(path: &str, idempotency: Option<&str>) -> &'static str {
fn observed_wait(kind: &str, code: u16, body: &Value) -> Option<RecoveryWait> {
match (kind, code) {
(_, 502..=504) => Some(RecoveryWait::Network),
("lookup", 404) if body["error"]["code"] == "request_not_found" => Some(RecoveryWait::RequestNotFound),
("lookup", 200) => match body["status"].as_str() {
Some("processing") => Some(RecoveryWait::Processing),
Some("unresolved") => Some(RecoveryWait::Unresolved),
@ -734,6 +746,17 @@ pub(super) fn settle_unresolved(task: &mut Value, now: u64) {
}
}
fn settle_request_not_found(task: &mut Value, now: u64) {
let Some(since) = task["requestNotFoundSince"].as_u64() else { return };
if now.saturating_sub(since) >= IMAGE_REQUEST_TIMEOUT.as_secs() {
task["phase"] = json!("expired");
task["resultExpiry"] = json!({"source":"request_not_found","httpStatus":404,
"requestNotFoundSince":since,"observedAt":now,
"requestId":task["requestId"],"upstreamTaskId":task["upstreamTaskId"]});
task["message"] = json!("网关没有这笔请求的记录,按未发起处理;可为此图位准备新请求");
}
}
pub(super) fn retry_original_queries(
mut query: impl FnMut(Duration) -> R<Value>,
mut wait: impl FnMut(Duration),
@ -1405,8 +1428,12 @@ impl Backend {
}
t["message"] = json!(reason);
t["recoveryWait"] = json!(wait.get().map(RecoveryWait::name));
if recover && t["phase"] == "unknown" && wait.get() == Some(RecoveryWait::Unresolved) {
settle_unresolved(&mut t, now());
if recover && t["phase"] == "unknown" {
match wait.get() {
Some(RecoveryWait::Unresolved) => settle_unresolved(&mut t, now()),
Some(RecoveryWait::RequestNotFound) => settle_request_not_found(&mut t, now()),
_ => {}
}
}
}
Ok(()) => {
@ -2510,6 +2537,46 @@ mod tests {
}
}
#[test]
fn lookup_not_found_keeps_a_durable_budget_and_allows_original_result_recovery() {
let mut task = json!({"id":Uuid::new_v4().to_string(),"phase":"unknown"});
let dir = tempfile::tempdir().unwrap();
let archive = dir.path().join("image-jobs").join(task["id"].as_str().unwrap()).join("task.json");
let missing = json!({"error":{"code":"request_not_found"}});
assert!(original_response(&mut task, |_, key| {
assert!(key.is_some());
Ok((404, missing.clone()))
}, |task| job_save(dir.path(), task)).is_err());
let mut stored = read_json(&archive).unwrap();
let first = stored["requestNotFoundSince"].as_u64().unwrap();
let deadline = first + IMAGE_REQUEST_TIMEOUT.as_secs();
settle_request_not_found(&mut stored, deadline - 1);
assert_eq!(stored["phase"], "unknown");
let mut recovered = stored.clone();
let request = Uuid::new_v4().to_string();
let result_path = format!("/api/external/requests/{request}/result");
let outcome = original_response(&mut recovered, |path, key| {
if key.is_some() {
Ok((200, json!({"status":"succeeded","request_id":request,
"result_available":true,"result_path":result_path,"result_expires_at":null})))
} else {
assert_eq!(path, result_path);
Ok((200, json!({"data":[{"b64_json":"original-image"}]})))
}
}, |_| Ok(()));
assert!(matches!(outcome, Ok(OriginalResponse::Completed(_))), "{}", outcome.err().unwrap_or_default());
assert!(original_response(&mut stored, |_, _| Ok((404, missing.clone())), |_| {
panic!("a repeated missing lookup must keep the original timestamp");
}).is_err());
settle_request_not_found(&mut stored, deadline);
assert_eq!(stored["phase"], "expired");
assert_eq!(stored["resultExpiry"]["source"], "request_not_found");
assert_eq!(stored["resultExpiry"]["requestNotFoundSince"], first);
}
#[test]
fn received_statuses_map_to_structured_waits_only() {
for (kind, code, body, expected) in [
@ -2518,6 +2585,10 @@ mod tests {
("lookup", 200, json!({"status":"succeeded"}), None),
("lookup", 200, json!({"status":"failed"}), None),
("lookup", 404, json!({"status":"processing"}), None),
("lookup", 404, json!({"error":{"code":"request_not_found"}}), Some(RecoveryWait::RequestNotFound)),
("result", 404, json!({"error":{"code":"request_not_found"}}), None),
("task-result", 404, json!({"error":{"code":"request_not_found"}}), None),
("asset", 404, json!({"error":{"code":"request_not_found"}}), None),
("task-status", 200, json!({"status":"in_progress"}), Some(RecoveryWait::Running)),
("task-status", 200, json!({"status":"pending_review"}), Some(RecoveryWait::Running)),
("task-status", 200, json!({"status":"failed"}), None),