Prompt Details
Model
Chat - (gpt-5.6)
Token size
2,525
Example input
[AGENT_ARCHITECTURE]: Long-running customer support AI agent with planner, memory store, PostgreSQL state DB, Redis queue, tool executor, and human escalation service.
[STATE_SCHEMA_AND_STORED_STATE]: task_status, goal_status, current_step, subtasks, tool_status, memory_version, checkpoint_id, retry_count, session_id, external_job_id.
[AGENT_WORKFLOW_AND_STATE_TRANSITIONS]: Receive ticket β create goal β generate plan β execute subtasks β call tools β validate result β complete or escalate.
[MEMORY_CONTEXT_AND_CHECKPOINT_DESIGN]: Conversation summary + recent messages stored in memory. Checkpoint saved after major workflow steps
[LOGS_TRACES_TESTS_AND_KNOWN_ISSUES]: Logs show occasional duplicate CRM updates, stale checkpoints after concurrent workers, and tasks marked complete after partial tool execution.
Example output
π PHASE 1 β AGENT STATE INVENTORY
State Type Risk
Task status Persistent π΄ High
Goal status Persistent π΄ High
Current step Persistent π High
Subtask status Persistent π΄ High
Tool execution status Persistent/External π΄ Critical
Memory version Persistent π High
Working context Ephemeral π High
Session state Persistent π‘ Medium
Checkpoint Persistent π΄ High
External job state External π΄ Critical
Finding: The most dangerous state boundary is between internal tool status and external API reality.
---
π§© PHASE 2 β STATE SCHEMA FORENSICS
Critical fields
task_status
Owner: Workflow engine
Source of truth: PostgreSQL
Lifecycle: Entire task
Validation: Cannot become completed while mandatory subtasks remain incomplete.
tool_status
Owner: Tool executor
Source of truth: Execution record + external result
Validation: success requires verified tool outcome.
checkpoint_id
Owner: Checkpoint manager
Source of truth: PostgreSQL
Validation: Must reference a complete, internally consistent snapshot.
β οΈ Schema weaknesses
No explicit state_version.
No transition ID.
No guaranteed idempotency key.
External execution outcome is not clearly separated from internal interpretation.
Checkpoint freshness is not explicitly validated.
Risk: π΄ Critical
---
π PHASE 3 β STATE MACHINE RECONSTRUCTION
Expected lifecycle:
RECEIVED
β
PLANNING
β
READY
β
RUNNING
β
WAITING_FOR_TOOL
β
VALIDATING
β
COMPLETED
Failure path:
RUNNING
β
FAILED
β
RECOVERING
β
RUNNING
Escalation path:
RUNNING
β
WAITING_FOR_HUMAN
β
HUMAN_RESOLVED
β
RUNNING / COMPLETED
Terminal states:
COMPLETED
CANCELLED
PERMANENTLY_FAILED
---
β οΈ PHASE 4 β INVALID TRANSITION ANALYSIS
β Invalid transition 1
COMPLETED β RUNNING
Invariant violated: Terminal states must not automatically re-enter execution.
β Invalid transition 2
WAITING_FOR_TOOL β COMPLETED
Invariant violated: Required external execution has not been validated.
β Invalid transition 3
FAILED β COMPLETED
Invariant violated: Failure must have a successful recovery or validated alternative completion.
β Invalid transition 4
RUNNING β COMPLETED while mandatory subtasks remain active.
Invariant violated: Parent completion requires all completion conditions to be satisfied.
β Invalid transition 5
TOOL_TIMEOUT β TOOL_SUCCESS without execution evidence.
Invariant violated: A timeout represents an unknown outcome, not confirmed failure or success.
---
π PHASE 5 β STALE STATE DETECTION
Potential stale state:
π Old checkpoint restored after a newer state was committed.
π§ Old memory summary overrides newer user instructions.
π§ Cached tool result used after external data changed.
π¦ Old CRM status treated as current.
π Worker uses outdated task version.
Example
Worker A:
task_version = 10
status = RUNNING
Worker B:
task_version = 11
status = COMPLETED
Worker A later writes:
task_version = 10
status = RUNNING
Without optimistic concurrency control, the newer state can be overwritten.
Risk: π΄ Critical
---
βοΈ PHASE 6 β CONTRADICTORY STATE ANALYSIS
Contradiction
task_status = COMPLETED
subtask_status = PAYMENT_REFUND_PENDING
Authoritative source: Completion validator + mandatory subtask state.
The task must remain incomplete.
Another contradiction
tool_status = SUCCESS
external_api = TIMEOUT / UNKNOWN
The system must classify this as:
OUTCOME_UNKNOWN
βnot success.
Memory contradiction
Old memory: "User approved refund."
Latest instruction: "Do not issue refund."
The latest authorized instruction should supersede stale memory where applicable.
---
π§ PHASE 7 β LOST CONTEXT ANALYSIS
Critical information that must survive:
Task ID
Goal
Current state
State version
Completed subtasks
Pending subtasks
Tool execution IDs
Idempotency keys
Retry count
Latest validated external result
Latest user instruction
Checkpoint ID
Recovery reason
β οΈ Context-loss scenario
Worker crashes after:
Refund API request β sent
but before:
refund_success β persisted
After restart, the agent may issue the refund again.
Required protection: persistent execution ID + idempotency key + reconciliation.
---
πΎ PHASE 8 β CHECKPOINT & PERSISTENCE AUDIT
Current design:
Major step
β
Checkpoint
Weaknesses
Checkpoint may become stale.
Concurrent workers can overwrite state.
State and external action may not be atomic.
No clear state-version validation.
Partial checkpoint writes can create impossible combinations.
Dangerous sequence
1. Agent calls refund API
2. Refund succeeds
3. Worker crashes
4. Checkpoint still says "refund_pending"
5. Recovery retries refund
This creates duplicate side effects unless the refund operation is idempotent.
Risk: π΄ Critical
---
π PHASE 9 β EXTERNAL STATE CONSISTENCY
Internal:
refund_status = PENDING
External:
refund_status = COMPLETED
This is:
INTERNAL STATE β EXTERNAL REALITY
Recommended reconciliation
Use:
Internal State
β
External Verification
β
Reconciliation Engine
β
Corrected State
For critical operations, external verification should occur before irreversible retry.
---
π PHASE 10 β RETRY, DUPLICATION & IDEMPOTENCY AUDIT
Major risks
CRM update
Attempt 1 β timeout
Attempt 2 β update sent
Attempt 1 actually succeeded
Potential duplicate operation.
Required identifiers
task_id
execution_id
tool_call_id
attempt_id
idempotency_key
state_version
event_id
Deduplication rule
Same:
idempotency_key
must not create multiple irreversible external effects.
Risk: π΄ Critical
---
π PHASE 11 β FAILURE & RECOVERY CONSISTENCY
Crash scenario
RUNNING
β
Tool request sent
β
Worker crashes
Recovery must NOT blindly assume:
Tool failed
Correct state:
OUTCOME_UNKNOWN
Then:
Reconcile external system
β
Known success β continue
Known failure β retry safely
Still unknown β human review
This prevents duplicate side effects.
---
π‘οΈ PHASE 12 β STATE INVARIANT & VALIDATION DESIGN
Invariant 1
Rule: Completed task requires all mandatory subtasks completed.
Pre-transition: Verify every mandatory subtask.
Post-transition: Recalculate completion state.
Invariant 2
Rule: Every external side effect requires unique execution identity.
Validation: idempotency_key != null.
Failure: Block execution.
Invariant 3
Rule: Older state cannot overwrite newer state.
Validation:
incoming_version > stored_version
or use compare-and-swap semantics.
Invariant 4
Rule: Tool success requires verified evidence.
Validation: Tool response/event must match execution ID.
Invariant 5
Rule: Unknown external outcome cannot automatically trigger an irreversible retry.
Action: Reconcile first.
---
π§ͺ PHASE 13 β CONSISTENCY TEST STRATEGY
Unit Tests
Valid state transitions.
Invalid state transitions.
Completion validation.
Version validation.
Retry counter validation.
Checkpoint integrity.
Integration Tests
CRM timeout.
Refund API timeout.
Duplicate events.
Database failure.
Queue replay.
Workflow Tests
Task β Tool β Success β Completion
Task β Tool β Timeout β Recovery β Success
Chaos Tests
Kill worker after external API request.
Kill worker before checkpoint.
Kill worker after checkpoint.
Disconnect network during tool execution.
Run two workers simultaneously.
Recovery Tests
Restore old checkpoint.
Restore corrupted checkpoint.
Replay duplicate event.
Recover unknown tool outcome.
Most important test: crash immediately after an irreversible external action but before internal state persistence.
---
π§ PHASE 14 β RECOVERY STRATEGY DESIGN
Failure Recovery Automatic?
Worker crash Restore checkpoint β
Tool timeout Reconcile + retry β
if idempotent
Duplicate event Deduplicate β
Stale checkpoint Reject using version β
External mismatch Reconcile β
Unknown refund outcome External lookup β
Conflicting financial state Human approval π€
Irreversible ambiguous action Freeze execution π€
Safe recovery architecture
Detect Failure
β
Classify State
β
Check Version
β
Check Execution History
β
Reconcile External Reality
β
Validate Recovery
β
Resume / Retry / Compensate / Escalate
---
π PHASE 15 β STATE RISK & PRIORITY MATRIX
Risk Probability Impact Priority
Duplicate external action High Critical π΄ Critical
Stale checkpoint overwrite Medium Critical π΄ Critical
Internal/external divergence High Critical π΄ Critical
Invalid completion transition Medium High π High
Lost context after restart Medium High π High
Duplicate events High Medium π High
Memory staleness Medium Medium π‘ Medium
Missing observability Medium Medium π‘ Medium
Highest priority
Prevent the agent from repeating irreversible external actions when the previous outcome is unknown.
---
π§Ύ PHASE 16 β FINAL STATE CONSISTENCY AUDIT REPORT
Executive Summary
Overall health: π High Risk
The architecture has the basic components required for long-running agents, but state consistency is vulnerable around:
External side effects
Checkpoint freshness
Concurrent workers
Retry behavior
Unknown tool outcomes
Internal/external divergence
The most dangerous weakness is treating an unknown external outcome as a normal failure that can safely be retried.
---
π§ State Model
Recommended model:
RECEIVED
β
PLANNING
β
READY
β
RUNNING
β
WAITING_FOR_TOOL
β
VALIDATING
β
COMPLETED
Failure:
FAILED
β
RECOVERING
β
RECONCILING
β
RUNNING
Ambiguous external outcome:
OUTCOME_UNKNOWN
β
RECONCILIATION
β
SUCCESS / FAILURE / HUMAN_REVIEW
---
π State Transition Rules
Valid
RECEIVED β PLANNING
PLANNING β READY
READY β RUNNING
RUNNING β WAITING_FOR_TOOL
WAITING_FOR_TOOL β VALIDATING
VALIDATING β COMPLETED
RUNNING β FAILED
FAILED β RECOVERING
RECOVERING β RECONCILING
RECONCILING β RUNNING
Invalid
COMPLETED β RUNNING
CANCELLED β RUNNING
WAITING_FOR_TOOL β COMPLETED
FAILED β COMPLETED without validation
UNKNOWN β RETRY_IRREVERSIBLE_ACTION without reconciliation
---
β οΈ Consistency Findings
π΄ Critical
Missing strong idempotency protection.
Unknown tool outcomes can cause duplicate actions.
Checkpoints may be stale.
Concurrent workers may overwrite newer state.
Internal state may diverge from external systems.
π High
Completion validation is insufficient.
Context recovery is incomplete.
State transitions need stronger version control.
π‘ Medium
Memory freshness needs explicit versioning.
Observability should expose state inconsistencies directly.
---
π§© Hidden Failure Scenarios
1. Crash-after-success
External action succeeds.
Internal state remains pending.
Recovery repeats action.
2. Concurrent-worker overwrite
Worker B commits version 11.
Worker A later commits version 10.
Newer state gets overwritten.
3. Duplicate event replay
Same event processed twice.
Agent performs duplicate state transition.
4. Stale memory decision
Old instruction remains in compressed context.
Agent follows outdated information.
5. False completion
Parent task becomes completed while a mandatory child task remains active.
---
π‘οΈ State Invariants
The production system should enforce:
Completed β all mandatory subtasks completed
External side effect β unique execution ID
Irreversible retry β previous outcome reconciled
New state version > previous state version
Tool success β verified execution evidence
Checkpoint β internally consistent state snapshot
Terminal state β no automatic execution restart
---
π§ͺ Verification Strategy
Minimum production test suite:
100% state-transition unit coverage
Invalid-transition tests
Concurrent-worker tests
Duplicate-event tests
Checkpoint corruption tests
Crash-recovery tests
Tool-timeout tests
Unknown-outcome tests
External reconciliation tests
Context-compression tests
Multi-agent handoff tests
Chaos tests around irreversible operations
---
π Recovery Architecture
Use this pattern:
State Machine
+
Versioned Persistent State
+
Execution IDs
+
Idempotency Keys
+
Event Deduplication
+
Checkpoint Validation
+
External Reconciliation
+
Invariant Validation
+
Human Escalation
The agent should never blindly retry an irreversible action whose previous outcome is unknown.
---
π Risk Matrix
π΄ CRITICAL
βββ Duplicate irreversible actions
βββ External/internal state divergence
βββ Stale checkpoint overwrite
βββ Unknown outcome treated as failure
π HIGH
βββ Invalid completion
βββ Lost recovery context
βββ Duplicate events
βββ Weak transition validation
π‘ MEDIUM
βββ Stale memory
βββ Limited state observability
π’ LOW
βββ Minor ephemeral-state inconsistencies
---
π£οΈ IMPLEMENTATION ROADMAP
0β30 DAYS
Add state-versioning.
Add execution IDs.
Add idempotency keys.
Block invalid transitions.
Add completion invariants.
Introduce OUTCOME_UNKNOWN.
Validate checkpoints before restoration.
Add critical crash-recovery tests.
31β90 DAYS
Implement optimistic concurrency control.
Build external reconciliation service.
Add event deduplication.
Version memory/context.
Improve checkpoint architecture.
Build workflow-level recovery testing.
Add multi-worker consistency tests.
3β6 MONTHS
Build centralized state-consistency engine.
Add continuous invariant monitoring.
Implement automated reconciliation.
Add advanced distributed tracing.
Introduce state corruption detection.
Build chaos-testing infrastructure.
Create human approval workflows for ambiguous irreversible actions.
---
π― FINAL RECOMMENDATION
The highest-value architectural change is to treat agent state as a versioned state machine with explicit invariants, execution identities, idempotency, and external reconciliation.
The critical principle is:
Never assume:
"Last known internal state = current reality"
Instead:
Persisted State
β
Validate Version
β
Validate Invariants
β
Inspect Execution History
β
Reconcile External Reality
β
Recover Safely
β
Commit New State
This transforms the agent from a system that merely remembers what it was doing into one that can reliably determine what actually happened, what state should exist now, and what action is safe to perform next.
By purchasing this prompt, you agree to our terms of service
GPT-5.6
Long-running AI agents can silently fail when their internal state becomes stale, contradictory, incomplete, or incorrectly restored after failures.
π Detect stale & contradictory state
π§ Find lost task context
π Audit incorrect state transitions
β οΈ Identify post-recovery inconsistencies
π‘οΈ Design state validation rules
π§ͺ Generate consistency checks & tests
π Build reliable recovery strategies
Turn fragile agent state management into a validated, recoverable state architecture. π
...more
Added 1 week ago
