Skip to content

fix(flow): make resumed flows checkpoint the instance that runs - #8448

Closed
ShiYuan Xiong (hehe764) wants to merge 13 commits into
crewAIInc:mainfrom
hehe764:fix/8438-flow-checkpoint-root
Closed

ShiYuan Xiong (hehe764) wants to merge 13 commits into
crewAIInc:mainfrom
hehe764:fix/8438-flow-checkpoint-root

Conversation

@hehe764

@hehe764 ShiYuan Xiong (hehe764) commented Oct 23, 2026 •

Copy link
Copy Markdown

Related issue

Fixes #8438

Summary

A flow resumed with kickoff(from_checkpoint=...) wrote checkpoints that serialized a blank flow, so a second resume started the flow over from its first method: methods that already completed ran again (side effects such as a charge repeat) and the kickoff inputs were gone.

Root cause: Flow.from_checkpoint called crewai_event_bus.set_runtime_state(state) while the runtime-state root still held the deserialized (blank) Flow. The rebuilt instance that actually ran was never part of the state, so the checkpoint listener serialized the blank entity, and the next restore picked that blank entity first.

Changes in Flow.from_checkpoint:

  • Replace the deserialized entity in state.root with the restored instance before set_runtime_state, so later checkpoints serialize the flow that actually runs.

  • Select the flow entity by the stable definition name recorded in checkpoint_flow_name, matching the requested class or declaration. The name is captured before the public name field overrides _definition.name, so flows created with a custom name remain restorable. Legacy checkpoints without the field fall back to restore data only when it identifies a single flow; ambiguous multi-flow checkpoints fail explicitly instead of restoring the wrong state.

  • Suppress FlowCreatedEvent while the restored instance is constructed and while checkpoint entities are deserialized, then emit the restored flow's creation event only after its data is hydrated and it is installed in the runtime state. Both the rebuilt-instance and in-place restore branches emit it, so base Flow and declarative restores keep notifying listeners and telemetry. Construction keeps using the subclass's own constructor (including a no-argument __init__), and the class/declaration suppress_flow_events setting is respected.

  • Preserve the checkpointed public name when rebuilding a subclass. The saved name is applied during post-init for the rebuilt class, after recording the stable definition name, so memory scope, lifecycle events, and later checkpoints keep the configured name without requiring constructor keywords.

  • Pass the declarative flow's definition through apply_checkpoint from kickoff. A declarative flow's concrete class stays Flow, so without the passed definition the restore matched the base Flow name instead of the declaration name.

  • Copy the checkpointed suppress_flow_events value onto rebuilt subclass instances before evaluating whether to emit FlowCreatedEvent.

Verification

  • Tests added or updated for the changed behavior

  • Relevant tests and quality checks pass locally (Windows and static-analysis baseline limitations below)

  • test_flow_can_resume_twice_from_checkpoints — reproduces the issue scenario (fails on main, passes with this fix): a flow that fails twice resumes correctly on the second from_checkpoint, running only the remaining methods and preserving inputs and state.

  • test_from_checkpoint_prefers_flow_entity_with_restore_data — restoring from a checkpoint that stores a blank duplicate ahead of the real flow picks the entity with the restore data.

  • The issue's reproduction script now matches the expected behavior: runs ['reserve', 'charge', 'charge', 'ship', 'ship'], final state {'order': 42, 'reserved': True}, and the final checkpoint contains a single flow entity with the full restore data.

  • pytest tests/test_checkpoint.py tests/test_flow.py tests/test_flow_turns.py tests/test_flow_resumability_regression.py tests/test_flow_from_definition.py tests/test_flow_persistence.py tests/test_event_record.py tests/events/test_event_replay.py tests/telemetry/test_checkpoint_telemetry.py: all pass except pre-existing failures that also fail on unmodified main on Windows (TestJsonProviderFork branch-subdir tests, test_persist_complex_types_dict_state).

  • Event-state regression: four class/declaration × events-enabled/suppressed combinations pass. Before the follow-up fix, the events-enabled class case appended the new instance to the old runtime state.

  • test_in_place_restore_emits_creation_event_after_state_install — covers the base Flow in-place restore path found in review: with events enabled the creation event fires once after the restored state is installed; with suppress_flow_events it does not fire. It fails before the review fix and passes after.

  • test_from_checkpoint_matches_stable_name_when_name_is_overridden — writes a checkpoint with two live flows that have custom public names, then restores the requested subclass. It fails before the fix with No Flow named ... found and passes after.

  • test_from_checkpoint_preserves_public_name_override — checkpoints OrderFlow(name="custom-order"), restores it, and asserts the public and definition names, completed methods, and state survive. It failed before the fix with restored.name == None.

  • test_declarative_kickoff_resumes_from_checkpoint — kickoff-level resume of a declarative flow; it failed before the fix with No Flow named 'Flow' found.

  • test_from_checkpoint_preserves_suppress_flow_events — a subclass created with suppress_flow_events=True restores with that setting and emits no creation event.

  • Follow-up local results (merged upstream main at 5e9be90, head 9526e3e): test_checkpoint.py 85 passed / 2 existing Windows path failures; the eight adjacent suites 344 passed / 1 existing Windows path failure; LanceDB-backed memory tests 40 passed with lancedb 0.40.0 matching uv.lock. The no-argument-constructor, in-place restore, custom-name, public-name, declarative-resume, and event-suppression regressions fail before their respective fixes and pass after. Ruff reports the same 11 existing source findings as the baseline; mypy output is unchanged (missing crewai_files and existing type findings). These do not establish fully green CI.

Additional context

AI assistance

Tool used: OpenAI Codex.

Codex assisted with diagnosing the checkpoint-restore issue, implementing the fix and regression tests, running local verification, and drafting this PR description and review replies. The verification section above records the checks actually run and the remaining Windows and static-analysis limitations.

Please apply the required llm-generated label; I do not have permission to add repository labels.


Note

Medium Risk
Changes flow checkpoint restore, runtime-state wiring, and lifecycle events; incorrect behavior could break multi-resume workflows or event listeners, but scope is isolated to checkpoint restore with extensive regression tests.

Overview
Fixes resumed flows writing checkpoints that serialized a blank deserialized Flow instead of the instance that actually ran, which caused a second kickoff(from_checkpoint=...) to restart from the first method.

Flow.from_checkpoint now swaps the selected checkpoint entity in state.root with the rebuilt/restored instance before set_runtime_state, so later checkpoint writes target the running flow. Restore picks the right entity via new checkpoint_flow_name (stable definition name, not overridden public name), with explicit errors for ambiguous multi-flow checkpoints and legacy fallbacks when restore data identifies a single flow.

Restore also defers FlowCreatedEvent until after hydration and runtime-state install (context vars suppress construction/deserialize noise), copies suppress_flow_events and reapplies checkpointed name on subclass rebuild without constructor kwargs. apply_checkpoint and kickoff pass self._declaration for declarative Flow.from_declaration resumes.

RuntimeState sync persists checkpoint_flow_name when checkpointing flows.

Reviewed by Cursor Bugbot for commit 9526e3e. Bugbot is set up for automated code reviews on this repo. Configure here.

Flow.from_checkpoint set the event bus runtime state while its root
still held the deserialized (blank) Flow, so checkpoints written by a
resumed flow serialized the blank entity and a later restore reran the
flow from its first method.

Replace the deserialized entity in state.root with the restored
instance before set_runtime_state, and pick the flow entity that
carries restore data instead of the first Flow, since checkpoints
written by resumed runs before this fix stored blank duplicates ahead
of the instance that ran.
Copilot AI balanced review requested due to automatic review settings October 23, 2026 10:25
@strix-security

strix-security Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Strix Security Review

Warning

This pull request has 40 commits after the last Strix review (b1f33ec). Strix has not reviewed these changes.
Automatic review on push is off for this repository. To review the latest changes, tag @strix-security in a comment, or turn on re-review on push.

✅ No open security findings.

PR summary: This PR fixes flow checkpointing for resumed runs: `Flow.from_checkpoint` now selects the checkpointed flow entity that actually carries restore data and installs the rebuilt instance into the runtime state before restoring it, so a second `kickoff(from_checkpoint=...)` no longer restarts completed methods or loses kickoff inputs. It also adds regression tests covering double resume and legacy checkpoints containing a blank duplicate entity.

Review summary

Reviewed the full diff of both changed files (lib/crewai/src/crewai/flow/runtime/__init__.py and lib/crewai/tests/test_checkpoint.py) plus the surrounding checkpoint machinery (RuntimeState.from_checkpoint/checkpoint, _restore_from_checkpoint, _sync_checkpoint_fields, apply_execution_context, and the event bus runtime-state scope/registry) and ran semgrep/bandit over the changed source.

The change reworks Flow.from_checkpoint entity selection: it now prefers the stored flow entity that carries restore data, applies that entity's execution context, and installs the rebuilt instance into state.root before set_runtime_state, so subsequent checkpoints serialize the flow that actually runs. Data flow reviewed: the checkpoint payload (operator-supplied restore artifact) → RuntimeState deserialization → entity selection → _restore_from_checkpoint (private attrs, memory binding, state restore) → runtime-state registration and later serialization.

No security control was removed, and no untrusted input reaches a new sink: restore selection stays within the caller's own checkpoint, the execution-context application is the pre-existing behavior, and nothing in _restore_from_checkpoint emits events or registers entities, so the reordering of set_runtime_state is not observable to listeners. Static analysis reported no findings on the changed lines (the single bandit B110 hit at line 2684 is pre-existing and outside the diff). No vulnerabilities identified in the changed code.

Ruled out (3)
  • Can a crafted checkpoint file inject a platform integration token or forged flow context through the execution context applied during restore?
    The `apply_execution_context(entity.execution_context)` call is unchanged in nature from the previous code (which applied the same stored context from a deserialized flow entity), and the checkpoint is a caller-supplied local restore artifact, so the PR neither widens nor narrows that existing trus…
  • Does moving `set_runtime_state(state)` to after `_restore_from_checkpoint()` let events or entity registrations attach to a stale runtime state and leak or ove…
    `_restore_from_checkpoint` only assigns private attributes, binds memory, and resets event-scope contextvars; it emits no events and registers no entities, so the checkpoint listener and the entity registry never observe the pre-existing runtime state during the reordered window.
  • Can selecting the entity with restore data copy another flow class's completed methods and state onto the restored instance, skipping required methods?
    Selection happens only among flow entities inside the caller's own checkpoint file and is the intended fix for blank duplicate entities; it crosses no privilege or tenant boundary and its worst case is a functional resume mismatch, not an unauthorized effect.

Review 1 on this PR · b1f33ec · requested Oct 23 10:25 UTC when the PR was opened


Reviewed by Strix
Re-run review · Configure security review settings

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

Checkpoint restore passed suppress_flow_events into the constructor, which fails for Flow subclasses that only define a no-argument __init__. Suppress the creation event around construction instead, and while deserializing checkpoint entities, so neither event can register against the caller's runtime state. The restored flow's creation event is emitted after the instance is installed.
@hehe764
ShiYuan Xiong (hehe764) force-pushed the fix/8438-flow-checkpoint-root branch from f13b605 to 2db918d Compare October 23, 2026 14:08

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Checkpoint deserialization now suppresses FlowCreatedEvent so it cannot register against the caller's runtime state. The in-place restore branch must emit it after installing the restored state, matching the rebuilt-instance branch, or listeners and telemetry stop receiving flow creation events for base Flow and declaration restores.

Copy link
Copy Markdown
Author

Strix (@strix-security) Please re-review the latest PR head (4be9bb07a54a812b3d18b7bd666006cc3e3edecc). The current security review covers b1f33ec and flags later commits as unreviewed. Thanks!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The checkpoint restore heuristic can select the wrong flow when multiple live flow entities contain restore metadata, potentially restoring incorrect inputs and completion state.

1 open issue

Review effort: Lite

Copy link
Copy Markdown
Author

Follow-up on the latest multi-flow restore review, addressed in e275b59.

The previous fallback selected the first Flow with non-empty restore metadata. That was sufficient for a legacy blank-duplicate checkpoint, but ambiguous when multiple live flows had completed methods.

Each checkpointed flow now records its stable definition name in checkpoint_flow_name. from_checkpoint matches the requested class/declaration to that name instead of relying on RuntimeState.root order, and the recorded name is preserved on other deserialized plain-Flow entities until their slots are rebuilt. Duplicate names, or legacy checkpoints with multiple restorable flows and no identity, now fail explicitly rather than silently restoring the wrong state. The original single-candidate legacy fallback remains supported.

Regression coverage includes two restorable flow entities in reversed order, preservation of the unselected flow's identity, the existing legacy blank-duplicate case, and chained resume. The focused tests pass; the complete checkpoint test file has 81 passing tests with only the two pre-existing Windows path-separator assertions failing.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit e275b59. Configure here.

The public name field rewrites _definition.name, so checkpointing that value made custom-named flows unrestorable: from_checkpoint matches on the class or declaration definition name. Record the pre-override name privately and use it when syncing checkpoint fields. Adds a round-trip test with two custom-named flows.
@hehe764

Copy link
Copy Markdown
Author

Follow-up on the custom-name finding in review 5648779020, fixed in da3dfd4f.

The stable-name change records a definition name per checkpointed flow, but the first version read _definition.name after the public name field had already overwritten it. Restore matches against the class/declaration definition name, so a flow created with a custom name was stored under that override and could not be found.

da3dfd4f captures the pre-override definition name in _stable_definition_name and writes that to checkpoint_flow_name. Legacy checkpoints still use the single-candidate restore-data fallback, and ambiguous multi-flow checkpoints still fail explicitly instead of restoring the wrong state.

Coverage: test_from_checkpoint_matches_stable_name_when_name_is_overridden checkpoints two flows with custom public names and restores the requested subclass. It failed before the fix with No Flow named 'OrderFlow' found and passes after.

Verification on da3dfd4f: test_checkpoint.py 81 passed with the two pre-existing Windows path failures; the eight adjacent suites 344 passed / 1 pre-existing Windows path failure; ruff and mypy reports are unchanged from the baseline. Bugbot re-review on this head: no issues found.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The rebuilt flow currently loses its configured public name, affecting subsequent lifecycle events and checkpoints.

No open issues 🎉

1 resolved since last review

Review effort: Lite

Reconstructed subclass flows were created without keyword arguments, so the saved public name was dropped and later lifecycle events and checkpoints used the class definition name instead. Apply the checkpointed name during post-init for the rebuilt class, after recording the stable definition name, so memory scope and events keep the saved name without requiring constructor keywords.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved restore-path issues include a critical declarative-flow regression and two moderate state-preservation issues.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Restore suppress_flow_events configuration

lib/​crewai/​src/​crewai/​flow/​runtime/​__init__.py:781

The rebuilt instance does not inherit the serialized suppress_flow_events value. For example, an OrderFlow(suppress_flow_events=True) is deserialized with that field set, but cls() defaults it back to False; the new post-restore block then emits FlowCreatedEvent even though the original flow suppressed events. Copy this configuration field from entity before the restored creation event is evaluated.

Review effort: Lite

…restore

apply_checkpoint only called type(instance).from_checkpoint, so a declarative flow (whose concrete class stays Flow) matched the base Flow name instead of its declaration. Pass the declaration from kickoff through apply_checkpoint. Rebuilt subclasses also now inherit the checkpointed suppress_flow_events value before deciding whether to emit FlowCreatedEvent. Adds kickoff-level declarative and suppression regression tests.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

Copy link
Copy Markdown
Author

The remaining declarative checkpoint-restore review is addressed in 9526e3e, now included in head 1ad5d0b. Both kickoff paths pass the declaration through apply_checkpoint; subclass restores also preserve the checkpointed suppress_flow_events setting and public name. I rechecked the six focused restore regressions on this head: 6 passed on Windows/Python 3.13. The related review thread is resolved.

The latest test, lint, type-check, and security workflows are still action_required. Could a maintainer please approve them and add the required llm-generated label? AI assistance is disclosed in the PR body.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] A flow resumed from a checkpoint writes checkpoints of a blank flow, so a second resume starts over

2 participants