Step 8 of 16
Turn long agent runs into durable jobs with progress, continuation state, retries, and cancellation.
ย้ายงานยาวออกจาก HTTP request พร้อม job state, idempotency และ resume หลัง process restart ครับ
Level: Advanced
Research, document ingestion และ report generation อาจใช้เวลานานกว่า HTTP request ครับ เปลี่ยนงานเหล่านี้เป็น durable job แล้วคืน job ID ให้ client แทนการเปิด connection รอ
ย้ายงานยาวไป durable execution ที่ resume ข้าม process และ worker ได้ โดยไม่ทำ completed step หรือ side effect ซ้ำครับ
queued -> running -> waiting_for_approval -> completed
-> failed
-> cancelled
API รับ request แล้ว validate input, สร้าง job record และส่ง message ไป queue ส่วน worker โหลด session หรือ workflow checkpoint แล้วทำงานต่อ ทุก transition ควรเขียน timestamp, attempt และ correlation ID
Agent Framework มี samples สำหรับ background responses และ persisted conversations ครับ Provider อาจคืน continuation data เพื่อให้ application กลับมาตรวจงานภายหลัง อย่าเก็บ continuation token ไว้ใน browser log หรือ URL เพราะอาจเชื่อมไปยังงานของ user
เลือก persistence ให้เข้ากับ failure model:
| Need | Use |
|---|---|
| Resume workflow ใน process/runtime เดิม | CheckpointManager with persistent store |
| Scale across stateless workers | Durable Extension |
| Provider ทำ response ต่อให้ | Provider background response plus persisted continuation data |
| Simple short task | Queue plus idempotent worker |
โครงสร้าง service ที่เล็กพอเริ่มได้:
record AgentJob(
Guid Id,
string UserId,
string Status,
string? SessionState,
string? ContinuationToken,
int Attempt);
Worker ต้องรองรับ cancellation และ idempotency ครับ หาก message ถูกส่งซ้ำ งานรอบใหม่ต้องไม่ publish report หรือส่ง email ซ้ำ ใช้ idempotency key ที่ผูกกับ job ID และ action name
แยก progress event จาก final response เพื่อให้ UI แสดงสถานะได้โดยไม่อ่าน internal chain-of-thought ตัวอย่าง event ที่ปลอดภัยคือ documents_retrieved, draft_created และ approval_requested
ตั้ง retry เฉพาะ transient failure พร้อม exponential backoff ส่วน invalid input, authorization failure และ token overflow ควรจบงานพร้อม error code ที่แก้ได้ครับ เก็บ session state หรือ checkpoint ก่อน external side effect และหลัง side effect พร้อม provider receipt
เปลี่ยน report request ให้คืน 202 Accepted กับ job ID จากนั้นสร้าง endpoint สำหรับ status, cancel และ approval ทดสอบ process restart ระหว่าง running กับ waiting_for_approval
Kill worker หลังแต่ละ state transition แล้ว restart ตรวจว่า completed step ไม่รันซ้ำ ส่ง queue message ซ้ำและพิสูจน์ว่า idempotency key กัน duplicate publish ได้ครับ
กำหนด TTL, retry ceiling, poison-message path, dead-letter alert, cancellation deadline และ operator recovery command หากใช้ reliable streaming บนหลาย instances ให้ใช้ stream broker ที่ทนต่อ reconnect ตาม hosting design
ส่ง durable job model, worker, status API, retry policy, recovery tests และ runbook สำหรับ stuck job