Settle expired image results by their original request

This commit is contained in:
WuYongJie 2026-11-26 17:45:29 +08:00
parent f4648cbfc3
commit aa4c9868de
11 changed files with 448 additions and 88 deletions

View File

@ -426,7 +426,7 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay
};
const earlier=verifiedProduction&&!needsOriginal&&sameSlotHistory.find(row=>row.phase==='unknown');
const historicalFailed=start?.heldOriginalProjectId&&sameSlotHistory.some(row=>row.projectId===start.heldOriginalProjectId
&& row.candidateId===start.heldOriginalId&&row.phase==='failed');
&& row.candidateId===start.heldOriginalId&&['failed','expired'].includes(row.phase));
if(!recheck&&earlier&&(historicalFailed||
(!start||start.state==='planning')&&!fresh.candidates.some(item=>!item.reused))){
await save(slot,{state:'unknown',source:'generate',heldGeneration:true,heldOriginalId:earlier.candidateId,
@ -439,7 +439,7 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay
}
if(recheck&&(fresh.selectedCandidateId!==initialSelection||fresh.manuallyEdited))return;
if(!recheck&&(revisedRecipe||retryGuidedCrop)){
if(fresh.candidates.some(candidate=>!['complete','failed'].includes(candidate.status)))return;
if(fresh.candidates.some(candidate=>!['complete','failed','expired'].includes(candidate.status)))return;
const existing=!retryGuidedCrop&&fresh.candidates.some(candidate=>candidate.id===start.candidateId&&candidate.status==='complete');
await save(slot,{state:existing?'candidate':'planning',requestedView:rule.focus,
candidateId:existing?start.candidateId:null,attempts:0,review:null,reason:null,
@ -448,7 +448,7 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay
}
if(!recheck&&retryUpdatedReferences&&start.state==='rejected'&&
fresh.candidates.some(candidate=>candidate.id===start.candidateId&&candidate.status==='complete')&&
fresh.candidates.every(candidate=>['complete','failed'].includes(candidate.status))){
fresh.candidates.every(candidate=>['complete','failed','expired'].includes(candidate.status))){
await save(slot,{state:'reviewed',referenceRepair:true});
start=journal.items[slot.id];
}
@ -934,6 +934,12 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay
}
const waitMs=source==='generate'&&operation.retryableFailure
? gatewayImageRetryDelay(retries, operation.retryAfterSeconds) : null;
if(operation.phase==='expired'){
await store.appendEvent({type:'production_image_expired',slotId:slot.id,...operation});
await save(slot,{state:'rejected',candidateId:operation.candidateId,reason:operation.message});
return report({status:'expired',candidateId:operation.candidateId,requestId:operation.requestId,
retryable:false,resultExpiry:operation.resultExpiry,reason:operation.message},true);
}
if(waitMs===null){
await save(slot,{state:'rejected',candidateId:operation.candidateId,reason:operation.message});
return report({status:'failed',reason:operation.message},!approvals(slot,item).length);
@ -1928,12 +1934,17 @@ export async function runWholeDetail(host, runAgent, loadKnowledge, {pause=delay
}
if(!candidateId||typeof canvas.detailRecover!=='function')return;
const receipt=await canvas.detailRecover(slot.id,{projectId,candidateId});
if(receipt?.id!==candidateId||!['complete','failed'].includes(receipt.status))return;
if(receipt?.id!==candidateId||!['complete','failed','expired'].includes(receipt.status))return;
if(receipt.status==='expired'){
await store.appendEvent({type:'production_image_expired',slotId:slot.id,candidateId,projectId,...receipt});
await save(slot,{state:'rejected',candidateId,pendingOperation:null,heldGeneration:false,
heldOriginalId:null,heldOriginalProjectId:null,reason:receipt.message});
}
if(projectId){
imageHistory=imageHistory.map(row=>row.slotId===slot.id&&row.projectId===projectId&&row.candidateId===candidateId?
{...row,phase:receipt.status}:row);
}
recovered.push(slot);
if(receipt.status!=='expired')recovered.push(slot);
}catch(error){
await store.appendEvent({type:'whole_detail_original_query_waiting',slotId:slot.id,candidateId,reason:error.message});
}

View File

@ -144,9 +144,10 @@ export function nativeTools(host, make) {
&& typeof original.operationId === 'string' && original.operationId) {
const receipt = await host.canvas.workflowReconcile({run:original.run,documentId:original.documentId,operationId:original.operationId});
if (receipt?.run !== original.run || receipt?.documentId !== original.documentId || receipt?.operationId !== original.operationId) throw Error('核查回执身份不一致,原操作仍待核查');
const complete = receipt.phase === 'complete', failed = receipt.phase === 'failed';
if ((complete || failed)) scope.settle(original);
return {status:complete ? 'completed' : failed ? 'failed' : 'unknown',receipt};
const complete = receipt.phase === 'complete';
const terminal = ['complete','failed','expired'].includes(receipt.phase);
if (terminal) scope.settle(original);
return {status:complete ? 'completed' : terminal ? receipt.phase : 'unknown',receipt};
}
if (original.kind !== 'native' || !Number.isSafeInteger(original.job) || original.job < 1 || !Number.isSafeInteger(original.documentId) || typeof original.run !== 'string' || !original.run) {
return {status:'unknown',message:'原操作缺少可核查的原生任务编号;保留阻断,请在原项目人工核查',kind:original.kind};

View File

@ -22,6 +22,17 @@ const nextOutput=optional(obj({outputId:text,variantId:text}));
const productImageArgs={
referenceIndex:optional(page),referenceCrop:optional(Type.Tuple(Array.from({length:4},()=>Type.Integer({minimum:0,maximum:1000})))),
};
const settledImagePhases=['complete','failed','retired','expired'];
const expiryFields=receipt=>receipt?.resultExpiry?
{requestId:receipt.requestId,retryable:false,resultExpiry:receipt.resultExpiry}:{};
function rememberImageExpiry(item,candidateId,receipt){
const expiry=expiryFields(receipt);
if(!expiry.resultExpiry)return;
const attempts=item.attempts??=[];
let attempt=attempts.find(row=>row.candidateId===candidateId);
if(!attempt){attempt={candidateId,source:'generate'};attempts.push(attempt);}
Object.assign(attempt,{phase:'expired',...expiry});
}
const preparationArgs={
prompt:text,
candidateSetId:optional(Type.String({description:'按自动采用政策准备同批下一张时,使用首张回执的 candidateSet.id,保持正式请求内容相同。'})),
@ -68,7 +79,7 @@ export const productionOperationTools = [
})],
['adopt_production_image','采用你选择的候选,返回实际的画布放置回执。',obj({slotId:slotRef,candidateId:text,fit:optional(fit)})],
['retire_production_image','清理你已判为失败的当前图位候选,保留原因、提示词和原请求记录。返工需要旧图时,先让子代理读取再清理。若该图已在画布上,回执会给出应替换的图层。',obj({slotId:slotRef,candidateId:text,reason:text})],
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。',obj({slotIds:optional(ids)})],
['reconcile_image_slots','按已保存的原操作或原候选号核查结果。unknown 继续核查原号;expired 表示原结果已过期,可以为同图位另备新请求。',obj({slotIds:optional(ids)})],
['read_output_screen','读取当前画布的实际像素。page 指定单屏。用 pages 一次查看多屏,再分别记录结论。屏号从 0 开始。',obj({
page:optional(page),pages:optional(Type.Array(page)),
})],
@ -305,6 +316,7 @@ export async function openProductionOperations(host) {
if(decision&&state==='applied')item.autoAdoptions[decision.candidateSetId]={...decision,
state:operation.persistence==='session'?'placed':'adopted',receipt:operation};
rememberAttempt(item,operation.candidateId);
rememberImageExpiry(item,operation.candidateId,operation);
},operation.candidateId?{evidence:[slot.id,operation.candidateId,adopting?'adoption':'candidate',
{...prepared,...operation,actor:'agent',fieldId:slot.fieldId,...decision}]}:undefined);
return {...operation,...(operation.phase==='unknown'?{pendingOriginal:operation.candidateId??operation.operationId}:null)};
@ -349,13 +361,13 @@ export async function openProductionOperations(host) {
throw Error('请先按政策准备齐全同批候选,再分别确认派发');
}
const {claimed,pending,request:record,original}=await commit(()=>
repository.claimImageRequest(approval,binding,saved=>pendingGeneration(slot,saved)));
repository.claimImageRequest(approval,binding,(saved,prior)=>pendingGeneration(slot,saved)??prior));
const {requestId:candidateId}=approval;
if(!claimed){
if(pending)return {phase:'unknown',...pending,pendingOriginal:pending.candidateId??pending.operationId};
const {state,operationId,receipt}=record;
const phase=['complete','failed','retired'].includes(state)?state:'unknown';
return {phase,candidateId,operationId,reason:receipt?.message,
const phase=settledImagePhases.includes(state)?state:'unknown';
return {phase,candidateId,operationId,reason:receipt?.message,...expiryFields(receipt),
...(phase==='unknown'?{pendingOriginal:candidateId}:null)};
}
const {operationId}=original;
@ -371,7 +383,7 @@ export async function openProductionOperations(host) {
throw error;
}
const phase=receipt.status??receipt.phase;
const settled=['complete','failed','retired'].includes(phase);
const settled=settledImagePhases.includes(phase);
await update(journal=>{
const item=journal.items[slot.id]??={};
if(settled)delete item.pendingGenerations[candidateId];
@ -380,10 +392,11 @@ export async function openProductionOperations(host) {
const attempts=item.attempts??=[];
if(!attempts.some(row=>row.candidateId===candidateId))attempts.push({candidateId,source:'generate',
prompt:request.prompt,reworkOf:request.reworkOf,change:request.reworkChange});
rememberImageExpiry(item,candidateId,receipt);
},{receipt:[candidateId,settled?phase:'unknown',receipt],
evidence:[slot.id,candidateId,'candidate',{...receipt,requestId:candidateId,operationId,reworkOf:request.reworkOf}]});
evidence:[slot.id,candidateId,'candidate',{requestId:candidateId,...receipt,operationId,reworkOf:request.reworkOf}]});
return {candidateId,operationId,phase:settled?phase:'unknown',reason:receipt.message,
requestedSource:'generate',...(request.reworkOf?{reworkOf:request.reworkOf}:null),
requestedSource:'generate',...expiryFields(receipt),...(request.reworkOf?{reworkOf:request.reworkOf}:null),
...(!settled?{pendingOriginal:candidateId}:null),
...(receipt.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:receipt.retryAfterSeconds}:null)};
};
@ -415,14 +428,18 @@ export async function openProductionOperations(host) {
const {candidateId,operationId}=original;
signal?.throwIfAborted();
const receipt=await canvas.detailRecover(slot.id,{candidateId});
const phase=receipt?.id===candidateId&&['complete','failed','retired'].includes(receipt.status)?receipt.status:'unknown';
const phase=receipt?.id===candidateId&&settledImagePhases.includes(receipt.status)?receipt.status:'unknown';
if(phase!=='unknown')await update(journal=>{
const item=journal.items[slot.id];
delete item.pendingGenerations[candidateId];
Object.assign(item,{state:phase==='complete'?'candidate':phase,candidateId,source:'generate'});
rememberImageExpiry(item,candidateId,receipt);
if(item.pendingGenerations?.[candidateId]){
delete item.pendingGenerations[candidateId];
Object.assign(item,{state:phase==='complete'?'candidate':phase,candidateId,source:'generate'});
}
},{receipt:[candidateId,phase,receipt],
evidence:[slot.id,candidateId,'candidate',{...receipt,requestId:candidateId,operationId}]});
return {slotId:slot.id,candidateId,operationId,phase,reason:receipt?.id===candidateId?receipt.message:undefined};
evidence:[slot.id,candidateId,'candidate',{requestId:candidateId,...receipt,operationId}]});
return {slotId:slot.id,candidateId,operationId,phase,reason:receipt?.id===candidateId?receipt.message:undefined,
...(receipt?.id===candidateId?expiryFields(receipt):null)};
};
const reconcile=async(slot,signal,adopting=false)=>{
@ -434,14 +451,21 @@ export async function openProductionOperations(host) {
if(archivedCandidate){
if(original&&original.candidateId!==archivedCandidate)await save(slot,{pendingOperation:{...original,candidateId:archivedCandidate}});
const receipt=await canvas.detailRecover(slot.id,{projectId:item.heldOriginalProjectId,candidateId:archivedCandidate});
const phase=receipt?.id===archivedCandidate&&['complete','failed','retired'].includes(receipt.status)?receipt.status:'unknown';
if(phase!=='unknown')await save(slot,{state:phase==='complete'?'candidate':phase,candidateId:archivedCandidate,
pendingOperation:null,heldOriginalId:null,heldOriginalProjectId:null},{
const phase=receipt?.id===archivedCandidate&&settledImagePhases.includes(receipt.status)?receipt.status:'unknown';
if(phase!=='unknown')await update(journal=>{
const saved=journal.items[slot.id];
rememberImageExpiry(saved,archivedCandidate,receipt);
if(originalCandidate(saved)===archivedCandidate)Object.assign(saved,{
state:phase==='complete'?'candidate':phase,candidateId:archivedCandidate,
pendingOperation:null,heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null,
});
},{
...(original?.kind==='frozen-image'?{receipt:[archivedCandidate,phase,receipt]}:null),
evidence:[slot.id,archivedCandidate,'candidate',{...receipt,sourceProjectId:item.heldOriginalProjectId}],
});
const reason=receipt?.id===archivedCandidate?receipt.message:undefined;
return {slotId:slot.id,candidateId:archivedCandidate,phase,reason,...(original?{operationId:original.operationId}:null)};
return {slotId:slot.id,candidateId:archivedCandidate,phase,reason,
...(receipt?.id===archivedCandidate?expiryFields(receipt):null),...(original?{operationId:original.operationId}:null)};
}
if(!original)return {slotId:slot.id,phase:'none'};
const adoption=adopting?{outputId,productVariantId:variantId,slotId:slot.id}:undefined;
@ -449,23 +473,25 @@ export async function openProductionOperations(host) {
const candidateId=operation.candidateId??original.candidateId;
const receipt=!adoption&&candidateId&&operation.phase==='unknown'
? await canvas.detailRecover(slot.id,{candidateId}) : null;
const phase=receipt?.id===candidateId&&['complete','failed','retired'].includes(receipt.status)?receipt.status:operation.phase;
if(['complete','failed','not_executed','retired'].includes(phase)){
const phase=receipt?.id===candidateId&&settledImagePhases.includes(receipt.status)?receipt.status:operation.phase;
const expiry=expiryFields(receipt?.id===candidateId?receipt:operation);
if(settledImagePhases.includes(phase)||phase==='not_executed'){
const applied=phase==='complete'&&adoption;
if(applied)filled.add(slot.id);
const decision=original.decision;
await update(journal=>{
const record=journal.items[slot.id];
rememberImageExpiry(record,candidateId,expiry);
Object.assign(record,{state:applied?'applied':phase==='complete'?'candidate':phase,candidateId,
...(applied&&operation.persistence==='session'?null:{[pendingKey]:null}),
...(!adopting?{heldOriginalId:null,heldOriginalProjectId:null}:null)});
...(!adopting?{heldGeneration:false,heldOriginalId:null,heldOriginalProjectId:null}:null)});
if(decision&&applied)record.autoAdoptions[decision.candidateSetId]={...decision,
state:operation.persistence==='session'?'placed':'adopted',receipt:operation};
if(decision&&phase==='not_executed')record.autoAdoptions[decision.candidateSetId]={...decision,state:'selected'};
},candidateId?{evidence:[slot.id,candidateId,adopting?'adoption':'candidate',{...operation,phase,...decision}]}:undefined);
},candidateId?{evidence:[slot.id,candidateId,adopting?'adoption':'candidate',{...operation,phase,...expiry,...decision}]}:undefined);
}
const reason=receipt?.id===candidateId?receipt?.message??operation.message:operation.message;
return {slotId:slot.id,phase,candidateId,operationId:original.operationId,reason};
return {slotId:slot.id,phase,candidateId,operationId:original.operationId,reason,...expiry};
};
const autoAdopt=(slot,candidateSet,signal)=>serialize(async()=>{
const {id,policy}=candidateSet;

View File

@ -261,9 +261,10 @@ export class ProjectRepository {
#readRequest(db, requestId) {
const row = db.prepare(`SELECT * FROM image_requests WHERE ${scopeWhere} AND request_id = ?`).get(...this.scope, requestId);
if (!row) return null;
const receipt = row.receipt_json === null ? null : JSON.parse(row.receipt_json);
return { requestId, operationId: row.operation_id, slotId: row.slot_id, requestSpecHash: row.request_spec_hash,
revision: row.revision, frozenAt: row.frozen_at, state: row.state, prepared: JSON.parse(row.prepared_json),
receipt: row.receipt_json === null ? null : JSON.parse(row.receipt_json) };
revision: row.revision, frozenAt: row.frozen_at, state: receipt?.resultExpiry ? 'expired' : row.state,
prepared: JSON.parse(row.prepared_json), receipt };
}
readImageRequest(requestId) {
@ -293,15 +294,19 @@ export class ProjectRepository {
if (!slotId) throw Error('生图请求不属于本轮工作画布或委托图位');
const item = journal.items[slotId] ??= {};
const sameOperation = item.pendingGenerations?.[requestId];
const expired = !request && item.attempts?.find(attempt => attempt.candidateId === requestId && attempt.phase === 'expired');
if (expired) return { journal, request: { state: 'expired', operationId: requestId, receipt: expired }, claimed: false };
if (sameOperation || request && request.state !== 'prepared') {
return { journal, pending: sameOperation, request, claimed: false };
}
const priorUnknown = Object.values(item.pendingGenerations ?? {}).find(original => {
const priorGeneration = Object.values(item.pendingGenerations ?? {}).find(original => {
const prior = this.#readRequest(db, original.candidateId);
return prior?.state === 'unknown' && (!request?.prepared.candidateSet ||
prior.prepared.candidateSet?.id !== request.prepared.candidateSet.id);
return !request?.prepared.candidateSet ||
prior?.prepared.candidateSet?.id !== request.prepared.candidateSet.id;
});
const pending = pendingGeneration?.(journal) ?? priorUnknown;
const priorState = priorGeneration && this.#readRequest(db, priorGeneration.candidateId)?.state;
const pending = pendingGeneration?.(journal, priorGeneration) ??
(priorState !== 'dispatching' ? priorGeneration : undefined);
if (pending) return { journal, pending, request, claimed: false };
const operationId = request?.operationId ?? requestId;
if (request) {
@ -321,8 +326,11 @@ export class ProjectRepository {
}
#recordImageReceipt(db, requestId, state, receipt) {
// Expiration is a terminal failure to retrieve the result. Its receipt carries
// the exact outcome, with the same durable schema as earlier projects.
db.prepare(`UPDATE image_requests SET state = ?, receipt_json = ?
WHERE ${scopeWhere} AND request_id = ?`).run(state, json(receipt), ...this.scope, requestId);
WHERE ${scopeWhere} AND request_id = ? AND json_extract(receipt_json, '$.resultExpiry') IS NULL`)
.run(state === 'expired' ? 'failed' : state, json(receipt), ...this.scope, requestId);
}
recordImageReceipt(requestId, state, receipt) {

View File

@ -37,7 +37,7 @@ async function acquireWrite(host, scope, signal, checkTurn, wait, onWait) {
export async function reconcileWorkflowReceipt(canvas, {run, documentId, operationId, adoption}) {
const receipt=await canvas.workflowReconcile({run, documentId, operationId, ...(adoption?{adoption}:null)});
if(!receipt||receipt.run!==run||receipt.documentId!==documentId||receipt.operationId!==operationId||
!(['submitted','complete','failed','unknown'].includes(receipt.phase)||adoption&&receipt.phase==='not_executed')){
!(['submitted','complete','failed','unknown','expired'].includes(receipt.phase)||adoption&&receipt.phase==='not_executed')){
throw Error('原画布操作的核查回执与提交身份不一致');
}
return receipt;
@ -145,7 +145,7 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d
intent:args.intent,slotId:args.slotId,productVariantId:args.productVariantId,code:result.error.code,message});
throw new BridgeError(message,'local_precondition_failed');
}
const phases=observedOriginal?['submitted','complete','failed','unknown']:['submitted'];
const phases=observedOriginal?['submitted','complete','failed','unknown','expired']:['submitted'];
if (result?.operationId !== operationId || !phases.includes(result.phase)) throw Error('工作流操作提交状态无效,原操作需核查;不会重发');
await onSubmitted?.(result);
if (result.phase !== 'unknown') {
@ -158,14 +158,16 @@ export async function executeWorkflow(host, args, signal, { timeoutMs, pause = d
await pause(args.intent === 'generate_candidate' ? 500 : 200, undefined, { signal });
result = await pollReceipt();
checkTurn();
if (result?.operationId !== operationId || !['submitted','complete','failed','unknown'].includes(result.phase)) throw Error('工作流操作回执无效,原操作需核查;不会重发');
if (result?.operationId !== operationId || !['submitted','complete','failed','unknown','expired'].includes(result.phase)) throw Error('工作流操作回执无效,原操作需核查;不会重发');
}
terminal = result.phase === 'complete' || result.phase === 'failed';
if (keepFailedCandidate && args.intent === 'generate_candidate' && result.phase === 'failed'
terminal = ['complete','failed','expired'].includes(result.phase);
if (keepFailedCandidate && args.intent === 'generate_candidate' && ['failed','expired'].includes(result.phase)
&& typeof result.candidateId === 'string' && result.candidateId) {
const message = workflowResult(result).message || '这次生图已失败,请查看图位记录';
await host.store.appendEvent({type:'whole_detail_generation_failed',slotId:args.slotId,operationId,candidateId:result.candidateId,message});
return {operation:{candidateId:result.candidateId,phase:'failed',message,...(result.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:result.retryAfterSeconds}:{})}};
return {operation:{candidateId:result.candidateId,phase:result.phase,message,
...(result.phase==='expired'?{requestId:result.requestId,retryable:false,resultExpiry:result.resultExpiry}:null),
...(result.retryableFailure===true?{retryableFailure:true,retryAfterSeconds:result.retryAfterSeconds}:{})}};
}
if (detailBatch && args.intent==='generate_candidate' && !terminal) {
scope.retain({kind:'workflow',operationId,run,documentId,identity,epoch});

View File

@ -545,6 +545,92 @@ test('a lost native acknowledgement can be recovered with the saved generation o
assert.deepEqual(journal().items[slotId].pendingGenerations,{});
});
test('410 settles only the original result and permits an explicitly prepared replacement',async t=>{
for(const legacy of [false,true])await t.test(legacy?'imported R28 ledger':'frozen SQLite request',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-expiry-'));
t.after(()=>cleanup(dir));
const store=productionStore(dir);
const ledger=store.ledger('main_images','ink');
const {repository}=ledger;
const slotId='main-photo';
const originalId=randomUUID(), remoteRequestId=randomUUID();
const resultExpiry={httpStatus:410,source:'retained-result',requestId:remoteRequestId,observedAt:1795685081};
const expiry={id:originalId,status:'expired',requestId:remoteRequestId,retryable:false,resultExpiry,message:'原生图结果已过期'};
let response='timeout';
const posted=[], reads=[];
const host={store,productionGoal:{outputId:'main_images',variantId:'ink'},canvas:{
workflowRead:async()=>({available:true,canvasFirst:true,outputId:'main_images',productVariantId:'ink',
template:{contentHash:'fixture'},totalSlots:1,slots:[{id:slotId,fieldId:'M02-I01'}]}),
detailCopyFields:async()=>({fields:[]}),delta:async()=>{},
async detailRecover(slot,{candidateId}){
reads.push({slot,candidateId});
if(response==='timeout'||response==='connection lost')throw Error(response);
return response==='410'?expiry:{id:originalId,status:'unknown',message:'HTTP '+response};
},
}};
if(legacy){
await fs.writeFile(path.join(dir,'production-main_images-ink.json'),JSON.stringify({
binding:JSON.stringify(['fixture','ink']),preparedRequests:{[originalId]:{slotId,prompt:'旧提示词'}},
items:{[slotId]:{state:'unknown',candidateId:originalId,source:'generate',
pendingOperation:{candidateId:originalId,operationId:originalId,kind:'frozen-image'},
attempts:[{candidateId:originalId,prompt:'旧提示词',source:'generate'}]}},
}));
}
imageBridge(host,async(_args,id)=>{
posted.push(id);
return {id,status:id===originalId?'unknown':'complete'};
},()=>!legacy&&!posted.length?originalId:randomUUID());
let actions=await openProductionOperations(host);
const input={slotId:'M02-I01',source:'generate',prompt:'旧提示词'};
if(!legacy)assert.equal((await generateAndWait(actions,input)).phase,'unknown');
const before=legacy?[]:[originalId];
await actions.close();
actions=await openProductionOperations(host);
for(response of ['timeout','connection lost','429','503']){
const [receipt]=await actions.reconcile_image_slots({slotIds:[slotId]});
assert.equal(receipt.phase,'unknown');
assert.equal(receipt.candidateId,originalId);
assert.equal((await generateAndWait(actions,{...input,prompt:'新提示词'})).pendingOriginal,originalId);
assert.deepEqual(posted,before);
if(!legacy)assert.equal(repository.readImageRequest(originalId).state,'unknown');
}
response='410';
const [expired]=await actions.reconcile_image_slots({slotIds:[slotId]});
assert.deepEqual(expired,{slotId,candidateId:originalId,operationId:originalId,phase:'expired',
reason:expiry.message,requestId:remoteRequestId,retryable:false,resultExpiry});
assert.deepEqual(posted,before);
const replacements=reads.length;
assert.ok(reads.every(read=>read.slot===slotId&&read.candidateId===originalId));
if(!legacy)assert.equal(repository.readImageRequest(originalId).state,'expired');
await actions.close();
actions=await openProductionOperations(host);
assert.equal((await actions.reconcile_image_slots({slotIds:[slotId]}))[0].phase,'none');
assert.equal(reads.length,replacements);
const same=await actions.dispatch_image_request({requestId:originalId,expectedRevision:1,expectedHash:'fixture-digest'});
assert.equal(same.phase,'accepted');
assert.equal((await actions.await_image_slots({slotIds:[slotId]})).generation[0].phase,'expired');
assert.deepEqual(posted,before);
const replacement=await generateAndWait(actions,{...input,prompt:'新提示词'});
assert.equal(replacement.phase,'complete');
assert.notEqual(replacement.candidateId,originalId);
assert.deepEqual(posted,[...before,replacement.candidateId]);
const {items}=JSON.parse(await fs.readFile(path.join(dir,'production-main_images-ink.json'),'utf8'));
assert.equal(items[slotId].candidateId,replacement.candidateId);
assert.equal(items[slotId].pendingOperation??null,null);
assert.deepEqual(items[slotId].pendingGenerations,{});
assert.deepEqual(items[slotId].attempts.find(item=>item.candidateId===originalId),{
candidateId:originalId,source:'generate',prompt:'旧提示词',phase:'expired',
requestId:remoteRequestId,retryable:false,resultExpiry,
});
assert.deepEqual(repository.candidateEvidence(slotId,originalId).at(-1).detail.resultExpiry,resultExpiry);
await actions.close();
});
});
test('Pi chooses each image operation and keeps an unresolved paid request on its original',async t=>{
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'jiansun-pi-'));
t.after(()=>cleanup(dir));

View File

@ -772,7 +772,7 @@ fn read_candidate(dir: &Path, id: &str) -> R<Value> {
|| record["id"] != id
|| record["binding"]["candidateId"] != id
|| record["binding"]["taskId"] != id
|| !matches!(record["phase"].as_str(), Some("prepared" | "dispatched" | "running" | "unknown" | "complete" | "failed"))
|| !matches!(record["phase"].as_str(), Some("prepared" | "dispatched" | "running" | "unknown" | "complete" | "failed" | "expired"))
{
return Err("候选记录或原请求身份无效".into());
}
@ -808,7 +808,7 @@ fn pending_candidate(record: &Value) -> Value {
// The caller owns the dispatch lock and has checked that task.json is absent.
fn recover_candidate_without_task(dir: &Path, record: &Value) -> R<Value> {
match record["phase"].as_str() {
Some("failed") => Ok(record.clone()),
Some("failed" | "expired") => Ok(record.clone()),
Some("prepared") if record["requestId"].is_null() =>
reconcile_candidate(dir, &json!({"id":record["id"],"slotBinding":record["binding"],
"phase":"prepared","notDispatched":true,"message":"这张图未提交生成,可以重新发起"})),
@ -884,7 +884,7 @@ pub(super) fn pending_summary(dir: &Path) -> R<Vec<Value>> {
let state = load(dir)?;
let mut pending = Vec::new();
for record in records(dir, &state)? {
if !matches!(record["phase"].as_str(), Some("complete" | "failed")) {
if !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
pending.push(json!({"id":record["id"],"phase":record["phase"],"kind":"canvas-candidate"}));
}
}
@ -1049,6 +1049,11 @@ fn candidate_receipt(record: &Value) -> Value {
receipt["message"] = record["retirement"]["reason"].clone();
}
if record["phase"] == "complete" { receipt["materialTaskId"] = material_task_id(record).clone(); }
if record["phase"] == "expired" {
receipt["requestId"] = record["requestId"].clone();
receipt["retryable"] = json!(false);
receipt["resultExpiry"] = record["resultExpiry"].clone();
}
if record["retryableFailure"] == true {
receipt["retryableFailure"] = json!(true);
receipt["retryAfterSeconds"] = record["retryAfterSeconds"].clone();
@ -1103,6 +1108,7 @@ fn retire_candidate(dir: &Path, target: &Value, reason: &str) -> R<Value> {
{
return Err("原候选不属于本轮项目、花色或图位".into());
}
if record["phase"] == "expired" { return Ok(candidate_receipt(&record)); }
if !matches!(record["phase"].as_str(), Some("complete" | "failed")) {
return Ok(json!({"status":"pending","candidateId":id,"requestId":record["requestId"]}));
}
@ -1218,6 +1224,7 @@ fn production_image_history(dir: &Path, state: &Value, variant_id: &str, scope:
Some("complete") if record["phase"] == "complete" && record["requestId"].is_string()
&& record["requestId"] == task["requestId"] => "complete",
Some("failed") if record["phase"] == "failed" => "failed",
Some("expired") => "expired",
Some("dispatched" | "running" | "unknown" | "complete" | "failed") => "unknown",
_ => continue,
};
@ -1225,11 +1232,16 @@ fn production_image_history(dir: &Path, state: &Value, variant_id: &str, scope:
preferred_sources.insert((project.clone(), id.to_owned()));
}
if target.is_none() && phase != "complete" { continue; }
result.push((project.clone(), id.to_owned(), json!({
let mut row = json!({
"slotId":target.is_some().then_some(slot),"projectId":project,"candidateId":id,"phase":phase,
"requestId":task["requestId"],"createdAt":record["createdAt"],"originalFieldId":source_field,
"originalOutputId":binding["outputId"],"originalTemplateHash":binding["templateHash"],
"originalColor":old_variant["colorName"]})));
"originalColor":old_variant["colorName"]});
if phase == "expired" {
row["retryable"] = json!(false);
row["resultExpiry"] = task["resultExpiry"].clone();
}
result.push((project.clone(), id.to_owned(), row));
}
}
let mut result: Vec<_> = result.into_iter().map(|(project, id, row)| {
@ -1462,7 +1474,7 @@ fn local_pending(dir: &Path, state: &Value, except: Option<&Value>, batch: Optio
return Ok(true);
}
for record in records(dir, state)? {
if !matches!(record["phase"].as_str(), Some("complete" | "failed"))
if !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired"))
&& !except.is_some_and(|binding| record["binding"] == *binding && matches!(record["phase"].as_str(), Some("prepared" | "dispatched")))
&& !batch.is_some_and(|binding| {
let sibling = &record["binding"];
@ -1495,7 +1507,7 @@ pub(super) fn reconcile_candidate(dir: &Path, journal: &Value) -> R<Value> {
if journal["id"] != record["id"] || record["requestId"].is_string() && journal["requestId"].is_string() && record["requestId"] != journal["requestId"] {
return Err("原候选请求号不匹配,未修改记录".into());
}
if matches!(record["phase"].as_str(), Some("complete" | "failed")) {
if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
return Ok(record);
}
let phase = match journal["phase"].as_str() {
@ -1504,6 +1516,7 @@ pub(super) fn reconcile_candidate(dir: &Path, journal: &Value) -> R<Value> {
Some("running") => "running",
Some("unknown") => "unknown",
Some("failed") => "failed",
Some("expired") => "expired",
Some("complete" | "applied") => "complete",
_ => return Err("原候选任务状态无效".into()),
};
@ -1512,6 +1525,7 @@ pub(super) fn reconcile_candidate(dir: &Path, journal: &Value) -> R<Value> {
record["artifact"] = artifact;
}
record["phase"] = json!(phase);
if phase == "expired" { record["resultExpiry"] = journal["resultExpiry"].clone(); }
let preflight_retry = journal["phase"] == "prepared" && journal["notDispatched"] == true
&& journal["requestId"].is_null() && record["requestId"].is_null()
&& journal["message"].as_str().is_some_and(transient_image_preflight);
@ -1701,7 +1715,7 @@ impl Backend {
let history = production_image_history(&dir, &state, &variant_id, &self.scope(), false)?;
if !history.as_array().into_iter().flatten().any(|item|
item["slotId"] == target["slotId"] && item["projectId"] == local && item["candidateId"] == candidate
&& matches!(item["phase"].as_str(), Some("unknown" | "complete" | "failed")))
&& matches!(item["phase"].as_str(), Some("unknown" | "complete" | "failed" | "expired")))
{
return Err("历史候选不属于同款图位".into());
}
@ -1729,7 +1743,7 @@ impl Backend {
return Err("原候选任务身份已变化".into());
}
let record = reconcile_candidate(&source_dir, &original)?;
if matches!(record["phase"].as_str(), Some("complete" | "failed")) {
if matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
return Ok(record);
}
// Query the saved task by its original request information.
@ -2926,7 +2940,7 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>) -> R<Value> {
};
let active = state["activeVariantId"].as_str().ok_or("当前花色缺失")?;
for record in &mut history {
if !matches!(record["phase"].as_str(), Some("complete" | "failed")) {
if !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired")) {
let task = dir.join("image-jobs").join(uuid(&record["id"], "候选")?).join("task.json");
if task.is_file() {
*record = reconcile_candidate(dir, &read_json(&task)?)?;
@ -2939,7 +2953,7 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>) -> R<Value> {
let legacy = if dir.join("template-slots.json").exists() { template_slots::load(dir)? } else { json!({"slots":{}}) };
let other_local = template_workflow::other_local_pending(dir, &current, &legacy, None)?
|| !creation::pending_text_tasks(dir)?.is_empty();
let image_pending: Vec<_> = history.iter().filter(|record| !matches!(record["phase"].as_str(), Some("complete" | "failed"))).collect();
let image_pending: Vec<_> = history.iter().filter(|record| !matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired"))).collect();
let pi = template_workflow::pending_pi(dir)?;
let pending = other_local || !image_pending.is_empty() || !pi.is_empty();
let scoped = pending && !other_local
@ -2989,8 +3003,13 @@ fn snapshot_for_view(dir: &Path, view: Option<Value>) -> R<Value> {
let candidate_id = record["id"].as_str().unwrap_or("");
let review = &reviews[candidate_id];
let decision = (review["slotId"] == id).then(|| &review["decision"]);
json!({"id":record["id"],"taskId":record["id"],"variant":record["id"],"sequence":record["sequence"],"status":record["phase"],"requestId":record["requestId"],
"materialTaskId":material_task_id(record),"sourceRequestId":record["sourceRequestId"],"instructions":record["instructions"],"parentCandidateId":record["parentCandidateId"],"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],"previewUri":format!("bytes://template-candidate-{candidate_id}"),"error":record["message"],"reviewDecision":decision,"retryableFailure":record["retryableFailure"],"retryAfterSeconds":record["retryAfterSeconds"]})
let mut row = json!({"id":record["id"],"taskId":record["id"],"variant":record["id"],"sequence":record["sequence"],"status":record["phase"],"requestId":record["requestId"],
"materialTaskId":material_task_id(record),"sourceRequestId":record["sourceRequestId"],"instructions":record["instructions"],"parentCandidateId":record["parentCandidateId"],"sourceType":record["sourceType"],"reusedFrom":record["reusedFrom"],"previewUri":format!("bytes://template-candidate-{candidate_id}"),"error":record["message"],"reviewDecision":decision,"retryableFailure":record["retryableFailure"],"retryAfterSeconds":record["retryAfterSeconds"]});
if record["phase"] == "expired" {
row["retryable"] = json!(false);
row["resultExpiry"] = record["resultExpiry"].clone();
}
row
}).collect();
let production_rule = profile
.filter(|_| component == active_output)
@ -3294,7 +3313,7 @@ impl Backend {
let start_product = !browsing && (input["generateProduct"] == true || input["resumeProduct"] == true);
if start_product {
let unrelated = records(&dir, &state)?.iter().any(|record|
!matches!(record["phase"].as_str(), Some("complete" | "failed"))
!matches!(record["phase"].as_str(), Some("complete" | "failed" | "expired"))
&& (input["resumeProduct"] != true || !product_slot_binding(&state, &record["binding"])));
if unrelated { return Err("请先查询原任务结果".into()); }
let remaining = remaining_stages(&dir, &state, &creation::load(&dir)?["revision"], true);
@ -5171,6 +5190,32 @@ mod tests {
assert_eq!(pending_summary(&fixture.dir).unwrap().len(), 1);
}
#[test]
fn expired_candidate_releases_its_slot_and_preserves_the_original_receipt() {
let fixture = fixture();
let original = candidate(&fixture.dir, "dispatched");
let next = candidate(&fixture.dir, "dispatched");
assert_eq!(original["binding"]["slotId"], next["binding"]["slotId"]);
reserve(&fixture.dir, load(&fixture.dir).unwrap(), &original).unwrap();
let request_id = Uuid::new_v4().to_string();
let mut task = json!({"id":original["id"],"slotBinding":original["binding"],"phase":"unknown","requestId":request_id});
reconcile_candidate(&fixture.dir, &task).unwrap();
assert!(reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).is_err());
let old = task.clone();
task["phase"] = json!("expired");
task["resultExpiry"] = json!({"httpStatus":410,"source":"retained-result","requestId":request_id});
let record = reconcile_candidate(&fixture.dir, &task).unwrap();
assert_eq!(reconcile_candidate(&fixture.dir, &old).unwrap(), record);
assert!(pending_summary(&fixture.dir).unwrap().is_empty());
reserve(&fixture.dir, load(&fixture.dir).unwrap(), &next).unwrap();
let receipt = candidate_receipt(&read_candidate(&fixture.dir, original["id"].as_str().unwrap()).unwrap());
assert_eq!(receipt["status"], "expired");
assert_eq!(receipt["retryable"], false);
assert_eq!(receipt["requestId"], request_id);
assert_eq!(receipt["resultExpiry"]["httpStatus"], 410);
assert_eq!(pending_summary(&fixture.dir).unwrap()[0]["id"], next["id"]);
}
#[test]
fn distinct_frozen_requests_can_reserve_the_same_slot_while_the_first_is_pending() {
let fixture = fixture();

View File

@ -240,7 +240,7 @@ fn job_save_locked(dir: &Path, t: &Value, current_only: bool) -> R<()> {
// Settled outcomes are monotonic. In particular, an older processing GET
// cannot reopen a confirmed failure, and a late failure cannot erase an
// image already completed or applied. No terminal state authorizes POST.
if existing["phase"] == "applied" || existing["phase"] == "failed" || existing["phase"] == "complete" && t["phase"] != "applied" {
if matches!(existing["phase"].as_str(), Some("applied" | "failed" | "expired")) || existing["phase"] == "complete" && t["phase"] != "applied" {
settled = existing;
}
}
@ -334,12 +334,14 @@ struct TerminalFailure {
enum LocatedOriginal {
Available(String),
Unavailable(String),
TerminalFailure(TerminalFailure),
}
enum OriginalResponse {
Completed(Value),
DeferredCompleted(Value),
Expired(&'static str),
TerminalFailure(TerminalFailure),
}
@ -349,6 +351,14 @@ enum OriginalResponse {
/// though no result is available. A missing, null or different path remains
/// unknown; result HTTP 410 alone is never evidence of a failed execution.
fn located_original(code: u16, response: &Value, task: &Value) -> R<LocatedOriginal> {
if code == 200 && response["status"] == "succeeded" && response["result_available"] == false
&& original_lookup_fields(response)
{
let observation = lookup_observation(code, response);
if let Some(request) = observation["requestId"].as_str().filter(|_| observation["resultPath"].is_string()) {
return Ok(LocatedOriginal::Unavailable(request.to_owned()));
}
}
if response["status"] != "failed" {
return located_recovery_request_id(code, response).map(LocatedOriginal::Available);
}
@ -408,7 +418,7 @@ fn locate_original(
let (code, body) = get("/api/external/requests/by-idempotency-key", Some(&task_id))?;
let located = located_original(code, &body, task);
let binding = match &located {
Ok(LocatedOriginal::Available(request)) => json!({"requestId":request}),
Ok(LocatedOriginal::Available(request) | LocatedOriginal::Unavailable(request)) => json!({"requestId":request}),
Ok(LocatedOriginal::TerminalFailure(failure)) => json!({"requestId":failure.request_id}),
Err(_) if code == 200 && matches!(body["status"].as_str(), Some("processing" | "unresolved"))
&& body["result_available"] == false && body["result_expires_at"].is_null()
@ -471,17 +481,28 @@ fn original_response(
mut persist: impl FnMut(&Value) -> R<()>,
) -> R<OriginalResponse> {
let looked_up = task["requestId"].is_null();
if looked_up && let LocatedOriginal::TerminalFailure(failure) = locate_original(task, &mut get, &mut persist)? {
return Ok(OriginalResponse::TerminalFailure(failure));
let mut unavailable = false;
if looked_up {
match locate_original(task, &mut get, &mut persist)? {
LocatedOriginal::TerminalFailure(failure) => return Ok(OriginalResponse::TerminalFailure(failure)),
LocatedOriginal::Unavailable(_) => unavailable = true,
LocatedOriginal::Available(_) => {}
}
}
let rid = task["requestId"].as_str().filter(|id| Uuid::parse_str(id).is_ok()).ok_or("原请求缺少可查询编号,请保持待核查;不会重发")?;
let (code, body) = get(&format!("/api/external/requests/{rid}/result"), None)?;
if code != 200 {
// A missing/expired result is not failure. An independent authenticated
// original-idempotency lookup may establish only its own exact terminal
// statement; otherwise preserve the original unknown outcome.
if !looked_up && let LocatedOriginal::TerminalFailure(failure) = locate_original(task, &mut get, &mut persist)? {
return Ok(OriginalResponse::TerminalFailure(failure));
// A retained-response 410 also occurs for deferred or unresolved work.
// Settle expiry only when the original lookup confirms success without a retained result.
if !looked_up {
match locate_original(task, &mut get, &mut persist)? {
LocatedOriginal::TerminalFailure(failure) => return Ok(OriginalResponse::TerminalFailure(failure)),
LocatedOriginal::Unavailable(_) => unavailable = true,
LocatedOriginal::Available(_) => {}
}
}
if code == 410 && unavailable && task["protocol"]["path"] != "/extensions/v1/tasks" {
return Ok(OriginalResponse::Expired("retained-result"));
}
return Err(format!("原结果尚未取回(HTTP {code});不会重发"));
}
@ -489,7 +510,7 @@ fn original_response(
Ok(body) => Ok(OriginalResponse::Completed(body)),
Err(reason) if !looked_up => match locate_original(task, &mut get, &mut persist)? {
LocatedOriginal::TerminalFailure(failure) => Ok(OriginalResponse::TerminalFailure(failure)),
LocatedOriginal::Available(_) => Err(reason),
LocatedOriginal::Available(_) | LocatedOriginal::Unavailable(_) => Err(reason),
},
Err(reason) => Err(reason),
}
@ -516,6 +537,10 @@ fn recover_deferred_result(
_ => return Err("原任务暂无可确认的图片结果,保留待核查".into()),
}
let (code, result) = get(&format!("/extensions/v1/tasks/{id}/result"), None)?;
if code == 410 {
task["upstreamTaskId"] = json!(id.to_string());
return Ok(OriginalResponse::Expired("task-result"));
}
if code != 200 || result["object"] != "extension.task.result"
|| result["id"].as_str().and_then(|value| Uuid::parse_str(value).ok()) != Some(id)
|| result["ready"] != true || !matches!(result["status"].as_str(), Some("succeeded" | "partially_succeeded"))
@ -590,10 +615,22 @@ pub(super) fn retry_original_queries(
}
}
pub(super) fn public(t: &Value, doc: u64, account: &Value, origin: &str) -> Value {
json!({"doc":doc,"revision":t["revision"],"accountId":account["id"],"origin":origin,"projectId":t["localProjectId"],"artifactSha256":t["sha256"],"image":true,"isSlotCandidate":t["slotBinding"].is_object(),"taskId":t["id"],"requestId":t["requestId"],"upstreamTaskId":t["upstreamTaskId"],"unknown":matches!(t["phase"].as_str(),Some("dispatched"|"unknown"|"running")),"phase":t["phase"],"path":t["artifact"],"target":t["target"],"mode":t["mode"],"referenceCount":t["references"].as_array().map_or(0,Vec::len),"modelId":t["modelId"],"reply":t["message"],"center":t["center"]})
let mut receipt = json!({"doc":doc,"revision":t["revision"],"accountId":account["id"],"origin":origin,"projectId":t["localProjectId"],"artifactSha256":t["sha256"],"image":true,"isSlotCandidate":t["slotBinding"].is_object(),"taskId":t["id"],"requestId":t["requestId"],"upstreamTaskId":t["upstreamTaskId"],"unknown":matches!(t["phase"].as_str(),Some("dispatched"|"unknown"|"running")),"phase":t["phase"],"path":t["artifact"],"target":t["target"],"mode":t["mode"],"referenceCount":t["references"].as_array().map_or(0,Vec::len),"modelId":t["modelId"],"reply":t["message"],"center":t["center"]});
if t["phase"] == "expired" {
receipt["retryable"] = json!(false);
receipt["resultExpiry"] = t["resultExpiry"].clone();
}
receipt
}
fn settled_recovery(task: &Value, doc: u64, account: &Value, origin: &str) -> Option<Value> {
matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed")).then(|| public(task, doc, account, origin))
matches!(task["phase"].as_str(), Some("complete" | "applied" | "failed" | "expired")).then(|| public(task, doc, account, origin))
}
fn retain_result_expiry(task: &mut Value, source: &str) {
task["phase"] = json!("expired");
task["resultExpiry"] = json!({"httpStatus":410,"source":source,"observedAt":now(),
"requestId":task["requestId"],"upstreamTaskId":task["upstreamTaskId"]});
task["message"] = json!("原生图结果已过期(HTTP 410),可为此图位准备新请求");
}
fn asset_url(s: &str) -> R<url::Url> {
let u = url::Url::parse(s).map_err(|_| "图片下载地址无效")?;
@ -915,6 +952,9 @@ impl Backend {
last["status"] = json!(response.status().as_u16());
}
job_json(&dir, &diagnostic_file, &diagnostic)?;
if matches!(kind, "result" | "task-result") && response.status() == reqwest::StatusCode::GONE {
return Ok((410, Value::Null));
}
let decoded = body(response, if matches!(kind, "lookup" | "task-status") { 64 * 1024 } else { RESPONSE_BYTES })?;
if let Some(last) = diagnostic["attempts"].as_array_mut().and_then(|a| a.last_mut()) {
match kind {
@ -933,6 +973,10 @@ impl Backend {
deferred_result_ready = true;
body
}
OriginalResponse::Expired(source) => {
retain_result_expiry(&mut t, source);
return Ok(());
}
OriginalResponse::TerminalFailure(failure) => {
retain_terminal_failure(&dir, &mut t, &failure)?;
return Err("网关确认原请求已终止且无可取回结果;原候选保留,不会重发".into());
@ -1008,15 +1052,17 @@ impl Backend {
}
let uid = t["upstreamTaskId"].as_str().filter(|s| protocol::token(s)).ok_or("任务号无效")?;
progress(if recover { "正在等待原任务结果…" } else { "正在生成图片…" }, false);
let (code, v) = body(
self.http
.get(format!("{UPSTREAM}/extensions/v1/tasks/{uid}/result"))
.bearer_auth(key)
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
.send()
.map_err(|_| "任务查询连接中断")?,
RESPONSE_BYTES,
)?;
let response = self.http
.get(format!("{UPSTREAM}/extensions/v1/tasks/{uid}/result"))
.bearer_auth(key)
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
.send()
.map_err(|_| "任务查询连接中断")?;
if response.status() == reqwest::StatusCode::GONE {
retain_result_expiry(&mut t, "task-result");
return Ok(());
}
let (code, v) = body(response, RESPONSE_BYTES)?;
if code == 202 && v["ready"] == false {
return Err("原任务仍在生成,可继续查询进度".into());
}
@ -1057,6 +1103,10 @@ impl Backend {
.timeout(recovery_timeout(deadline, Duration::from_secs(30))?)
.send()
.map_err(|_| "图片下载连接中断,保留原结果后可重取")?;
if r.status() == reqwest::StatusCode::GONE {
retain_result_expiry(&mut t, "image-asset");
return Ok(());
}
if !r.status().is_success() {
return Err(format!("98k图片下载 HTTP {},原结果已保留", r.status().as_u16()));
}
@ -1423,7 +1473,7 @@ mod tests {
assert_eq!(writes, 1);
let failure = match outcome {
OriginalResponse::TerminalFailure(failure) => failure,
OriginalResponse::Completed(_) | OriginalResponse::DeferredCompleted(_) => panic!("a failed lookup cannot become image pixels"),
OriginalResponse::Completed(_) | OriginalResponse::DeferredCompleted(_) | OriginalResponse::Expired(_) => panic!("a failed lookup cannot become image pixels"),
};
assert_eq!(task["phase"], "unknown");
retain_terminal_failure(&dir, &mut task, &failure).unwrap();
@ -1483,6 +1533,75 @@ mod tests {
assert_eq!(task, original, "GET evidence alone must not mutate the canonical phase");
}
}
#[test]
fn certified_retained_result_gone_settles_the_original_without_posting() {
let dir = std::env::temp_dir().join(format!("image-expiry-{}", Uuid::new_v4()));
let mut task = unknown_image();
task["localProjectId"] = Value::Null;
task["requestId"] = json!(FAILURE_REQUEST);
let original = task.clone();
job_save(&dir, &task).unwrap();
let lookup = json!({"request_id":FAILURE_REQUEST,"status":"succeeded","result_available":false,
"result_path":format!("/api/external/requests/{FAILURE_REQUEST}/result"),"result_expires_at":"2026-11-26T08:00:00Z"});
let bound_result = format!("/api/external/requests/{FAILURE_REQUEST}/result");
for http in [Some(429), Some(500), Some(503), None, Some(410)] {
let mut paths = Vec::new();
let outcome = checked_original_response(&mut task, |path, key| {
paths.push(path.to_owned());
if path == bound_result {
assert!(key.is_none());
http.map(|status| (status, Value::Null)).ok_or_else(|| "GET timed out or connection was interrupted".into())
} else {
assert_eq!(path, "/api/external/requests/by-idempotency-key");
assert_eq!(key, original["id"].as_str());
Ok((200, lookup.clone()))
}
}, |_| panic!("the original ID is already bound"));
assert_eq!(paths[0], bound_result);
assert_eq!(paths.len(), if http.is_some() { 2 } else { 1 });
if http == Some(410) {
let OriginalResponse::Expired(source) = outcome.unwrap() else { panic!("explicit 410 must settle expiry") };
retain_result_expiry(&mut task, source);
} else {
assert!(outcome.is_err());
assert_eq!(task, original);
assert!(pending(&dir).unwrap());
}
}
job_save(&dir, &task).unwrap();
job_save(&dir, &original).unwrap(); // A late unknown GET cannot reopen the task.
let stored = read_json(&dir.join("image-task.json")).unwrap();
let receipt = settled_recovery(&stored, 1, &json!({"id":"account"}), "origin").unwrap();
assert_eq!(receipt["phase"], "expired");
assert_eq!(receipt["unknown"], false);
assert_eq!(receipt["retryable"], false);
assert_eq!(receipt["requestId"], FAILURE_REQUEST);
assert_eq!(receipt["resultExpiry"]["httpStatus"], 410);
assert_eq!(receipt["resultExpiry"]["source"], "retained-result");
assert!(!pending(&dir).unwrap());
fs::remove_dir_all(dir).unwrap();
}
#[test]
fn deferred_result_gone_is_distinct_from_an_expired_generic_envelope() {
let id = Uuid::new_v4();
let mut task = json!({"requestId":FAILURE_REQUEST,"upstreamTaskId":null});
let mut paths = Vec::new();
let outcome = recover_deferred_result(&mut task, &mut |path, key| {
assert!(key.is_none());
paths.push(path.to_owned());
if path.ends_with("/result") {
Ok((410, Value::Null))
} else {
Ok((200, json!({"object":"extension.task","id":id,"status":"succeeded","result_available":true})))
}
}, &mut |_| panic!("expiry is persisted by the task settlement"));
assert!(matches!(outcome, Ok(OriginalResponse::Expired("task-result"))));
assert_eq!(paths, [format!("/extensions/v1/tasks/{FAILURE_REQUEST}"),format!("/extensions/v1/tasks/{id}/result")]);
assert_eq!(task["requestId"], FAILURE_REQUEST);
assert_eq!(task["upstreamTaskId"], id.to_string());
}
#[test]
fn failed_lookup_requires_http200_exact_identity_and_a_known_no_result_envelope() {
let mut variants = Vec::new();
@ -1550,7 +1669,7 @@ mod tests {
task["requestId"] = json!(FAILURE_REQUEST);
let failure = match located_original(200, &failure_lookup(), &task).unwrap() {
LocatedOriginal::TerminalFailure(failure) => failure,
LocatedOriginal::Available(_) => panic!("failure evidence required"),
LocatedOriginal::Available(_) | LocatedOriginal::Unavailable(_) => panic!("failure evidence required"),
};
task[key] = if key == "phase" { json!("complete") } else { json!("changed-original-binding") };
assert!(failure_evidence(&failure, &task).is_err(), "{key}");
@ -1716,6 +1835,7 @@ mod tests {
.map(|response| match response {
OriginalResponse::Completed(value) | OriginalResponse::DeferredCompleted(value) => value,
OriginalResponse::TerminalFailure(_) => json!({"phase":"failed"}),
OriginalResponse::Expired(_) => json!({"phase":"expired"}),
});
assert_eq!(task["id"], "42e84e04-4738-48c0-b3c0-31ee097b7a35");
assert_eq!(task["phase"], "unknown");

View File

@ -1418,7 +1418,7 @@ impl Workspace {
let count = models.len() + images.len();
models.retain(|id| !has_result(id));
let candidate = &value["candidateResult"];
if matches!(candidate["status"].as_str(), Some("complete" | "failed"))
if matches!(candidate["status"].as_str(), Some("complete" | "failed" | "expired"))
&& candidate["variantId"] == stage.variant
{
images.retain(|id| candidate["id"] != *id);
@ -1691,6 +1691,39 @@ mod tests {
}
}
#[test]
fn an_expired_image_receipt_releases_its_waiting_output_without_marking_it_delivered() {
let (tx, requests) = mpsc::channel();
let (_, rx) = mpsc::channel();
let mut w = Workspace::new(tx, rx);
let _ = requests.try_recv().unwrap();
w.account = json!({"id":"local"});
w.origin = "https://example.test".into();
w.library = false;
let mut session = photocraft_engine::Session::new();
session.execute("file.new", json!({"width":40,"height":50})).unwrap();
let app = PhotocraftApp::new(session, crate::Services::default());
let doc = app.session.active().unwrap().doc.id.0;
let project = w.local_identity("project");
w.open_projects.insert(doc, project.clone());
w.template_workflow = json!({"workspaceId":"workspace","outputId":"main_images","variantId":"wood"});
let stages = VecDeque::from([Stage { output:"main_images".into(), variant:"wood".into() }]);
w.product_production = Some(Run::new(doc, project, json!("workspace"), stages, None,
Phase::WaitingOriginals { models:vec![], images:vec!["original".into()], goal:None }));
let mut receipt = json!({"accountId":"local","origin":w.origin,"doc":doc,
"workflow":{"workspaceId":"workspace"},"candidateResult":{"id":"original","status":"unknown","variantId":"wood"}});
w.production_recovery_received(&app, &receipt);
assert!(w.product_production.as_ref().unwrap().waiting_for_image("original"));
receipt["candidateResult"]["status"] = json!("expired");
receipt["candidateResult"]["resultExpiry"] = json!({"httpStatus":410});
w.production_recovery_received(&app, &receipt);
let run = w.product_production.as_ref().unwrap();
assert!(run.awaiting_canvas_save());
assert_eq!(run.stages.front().unwrap().output, "main_images");
assert_eq!(run.completed, 0);
assert!(requests.try_recv().is_err());
}
#[test]
fn a_clicked_output_reuses_its_inflight_preload_and_shows_download_progress() {
let (tx, requests) = mpsc::channel();

View File

@ -149,10 +149,15 @@ impl State {
}
op["candidateId"] = candidate["id"].clone();
op["message"] = candidate["message"].clone();
if candidate["status"] == "expired" {
op["retryable"] = json!(false);
op["requestId"] = candidate["requestId"].clone();
op["resultExpiry"] = candidate["resultExpiry"].clone();
}
op["retryableFailure"] = candidate["retryableFailure"].clone();
op["retryAfterSeconds"] = candidate["retryAfterSeconds"].clone();
op["phase"] = json!(match candidate["status"].as_str() {
Some("complete") => "complete", Some("failed" | "rejected" | "not_dispatched") => "failed", _ => "unknown",
Some("complete") => "complete", Some("expired") => "expired", Some("failed" | "rejected" | "not_dispatched") => "failed", _ => "unknown",
});
true
}
@ -161,7 +166,7 @@ impl State {
let candidate = &value["candidateResult"];
let Some(id) = candidate["id"].as_str() else { return false };
let phase = match candidate["status"].as_str() {
Some("complete") => "complete", Some("failed" | "rejected" | "not_dispatched") => "failed", _ => return false,
Some("complete") => "complete", Some("expired") => "expired", Some("failed" | "rejected" | "not_dispatched") => "failed", _ => return false,
};
if value["accountId"] != *account || value["origin"] != origin || value["doc"].as_u64() != doc || project.is_none() { return false; }
let Some(op) = self.operations.iter_mut().find(|op| op["intent"] == "generate_candidate" && op["phase"] == "unknown"
@ -170,6 +175,11 @@ impl State {
&& op["slotId"] == candidate["slotId"] && op["productVariantId"] == candidate["variantId"]) else { return false };
op["phase"] = json!(phase);
op["message"] = candidate["message"].clone();
if candidate["status"] == "expired" {
op["retryable"] = json!(false);
op["requestId"] = candidate["requestId"].clone();
op["resultExpiry"] = candidate["resultExpiry"].clone();
}
true
}
@ -375,11 +385,21 @@ pub(super) fn reconcile(w: &Workspace, app: &PhotocraftApp, input: &Value) -> Re
"phase":if not_executed { "not_executed" } else { "unknown" }}));
};
if matches.next().is_some() { return Err("原操作身份不唯一".into()); }
let phase = op["phase"].as_str().filter(|phase| matches!(*phase, "submitted" | "unknown" | "complete" | "failed"))
let phase = op["phase"].as_str().filter(|phase| matches!(*phase, "submitted" | "unknown" | "complete" | "failed" | "expired"))
.ok_or("原操作状态无效")?;
Ok(json!({"run":run,"documentId":doc,"operationId":id,"phase":phase,"candidateId":op["candidateId"],
let mut receipt = json!({"run":run,"documentId":doc,"operationId":id,"phase":phase,"candidateId":op["candidateId"],
"message":op["message"],"retryableFailure":op["retryableFailure"],"retryAfterSeconds":op["retryAfterSeconds"],
"persistence":op["persistence"]}))
"persistence":op["persistence"]});
copy_expiry(op, &mut receipt);
Ok(receipt)
}
fn copy_expiry(source: &Value, receipt: &mut Value) {
if source["resultExpiry"].is_object() {
for key in ["requestId", "retryable", "resultExpiry"] {
receipt[key] = source[key].clone();
}
}
}
fn run_scope(w: &Workspace) -> Option<&Value> {
@ -676,7 +696,7 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u
let held_generation = completed_placement && same_slot && op["detailBatch"] == true
&& op["intent"] == "generate_candidate" && op["phase"] == "unknown"
&& op["candidateId"] != input["candidateId"];
!held_generation && !matches!(op["phase"].as_str(), Some("complete" | "failed"))
!held_generation && !matches!(op["phase"].as_str(), Some("complete" | "failed" | "expired"))
&& op["accountId"] == w.account["id"] && op["origin"] == w.origin
&& op["documentId"].as_u64() == w.owner_doc && op["projectLocalId"] == w.pi_request_scope["project"]["localId"]
&& (!batch || op["detailBatch"] != true || same_slot
@ -685,7 +705,7 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u
return Err("原操作尚未落定,未执行新操作".into());
}
let excess = if batch { 0 } else { w.workflow.operations.len().saturating_add(1).saturating_sub(64) };
if w.workflow.operations.iter().filter(|op| matches!(op["phase"].as_str(), Some("complete" | "failed"))).count() < excess {
if w.workflow.operations.iter().filter(|op| matches!(op["phase"].as_str(), Some("complete" | "failed" | "expired"))).count() < excess {
return Err("本次会话操作记录已达上限,未执行新操作".into());
}
if !available || w.pending_project_open.is_some() {
@ -813,7 +833,7 @@ fn execute(w: &mut Workspace, app: &mut PhotocraftApp, input: &Value, version: u
"workerNumber":worker,"slotLabel":slot_label,
"referenceIndex":input["referenceIndex"],"referenceCrop":input["referenceCrop"]});
for _ in 0..excess {
if let Some(index) = w.workflow.operations.iter().position(|old| matches!(old["phase"].as_str(), Some("complete" | "failed"))) {
if let Some(index) = w.workflow.operations.iter().position(|old| matches!(old["phase"].as_str(), Some("complete" | "failed" | "expired"))) {
w.workflow.operations.remove(index);
}
}
@ -870,6 +890,7 @@ pub(super) fn action(w: &mut Workspace, app: &mut PhotocraftApp, method: &str, i
let op = w.workflow.operations.iter().find(|op| op["operationId"] == id && op["run"] == run).ok_or("原操作不存在")?;
let mut receipt = json!({"operationId":id,"phase":op["phase"],"candidateId":op["candidateId"],
"message":op["message"],"retryableFailure":op["retryableFailure"],"retryAfterSeconds":op["retryAfterSeconds"]});
copy_expiry(op, &mut receipt);
if let Some(persistence) = op.get("persistence") { receipt["persistence"] = persistence.clone(); }
Ok(receipt)
}

View File

@ -2,6 +2,13 @@
开发线 `codex/xiaoyi-whole-detail-fidelity`。2026-11-26 从 [实施记录](./implementation.md) 接续。逐项证据见 [验收矩阵](./acceptance.md)。
## 架构 1.2 整合与原结果过期 · 2026-11-26
- 六条架构分支已合入开发线。首张模板画布须通过映射和保存修订校验,目录读取可等待,失败后仍可用原 Pi 回合重开。商品规格与备注进入首次及分输出计划,空 `retryOf` 在冻结前省略。
- 正式生图的原结果 GET 返回 HTTP 410 且同号查询确认成功、无保留结果时,原请求记为 `expired`。任务、候选和项目账本保存网关原号及过期回执,图位可另备新单。超时、断连、429 和 5xx 保留原请求待核查。
- 本地 Pi 全量 313 项、Docker Skill 5 项、Rust 后端 118 项、原生 UI 90 项通过。Rust 有 15 项标记忽略,31 个 crate 的分层检查通过。
- R28 同一工程在阶段 2 续做主图和详情,沿用已验证的 SKU 成品。阶段 1 使用本地回归与 debug 构建验证,实机续跑留待阶段 2。
## R28 实机 · QA-SZ012616 · 2026-11-26
- 隔离配置的素材库返回 HTTP 200。顾家电脑桌资源组的 `visual_guides` 发布版本为 `001e54ccc1584383a70630e218e20ddd`,15 份指引和 4 份附件。Pi 使用同一套资源分别绑定详情、主图和 SKU,每类实际加载 4 个 Skill。