Skip to content

Actor lifecycle hooks #450

Open

Description

This issue tracks the design and implementation of actor lifecycle hooks.

These are analogous to Kubernetes container lifecycle hooks. At a minimum we should support 2 new hooks (names TDB).

  1. PostResume - Triggered right after an actor is resumed.
  2. PreSuspend - Triggered right before an actor is suspended.

This area needs more investigation to determine exactly how these hooks should be implemented.

Activity

  1. changed the title [-][Feature] Actor lifecycle hooks[/-] [+]Actor lifecycle hooks[/+] on Jul 17, 2026
  2. added
    kind/feature
    on Jul 17, 2026
  3. EItanya commented on Jul 20, 2026

    @EItanya
    Collaborator

    I'm also definitely interested in this, but there's a bit of a wrinkle here i think we need to account for in this design. Specifically, at what point in the snapshot lifecycle does this happen. Before/after makes a very large difference for pre-warming etc.

  4. eliranw commented on Jul 21, 2026

    @eliranw
    Collaborator

    We are also interested in this.
    We would need lifecycle hooks for running commands post-resume + pre-suspend for cuda-checkpointing GPU actors.
    This connects to #185.

  5. HavenXia commented on Jul 24, 2026

    @HavenXia
    Member

    Scott Funkenhauser (@sfunkenhauser) I can take this one. The upgrade workstream (#473) has to define these semantics anyway: a blue/green model that batch-suspends every running actor, so the PreSuspend and PostResume are inevitable path on the upgrade.

  6. sfunkenhauser commented on Jul 27, 2026

    @sfunkenhauser
    CollaboratorAuthor

    sfunkenhauser I can take this one. The upgrade workstream (#473) has to define these semantics anyway: a blue/green model that batch-suspends every running actor, so the PreSuspend and PostResume are inevitable path on the upgrade.

    Is this required for the initial release? Or is it sufficient to push this responsibility to the actor? The actor receives a SIGTERM when the pod is deleted and decides how to proceed. This was the assumption I was proceeding with for graceful termination, and it seems like upgrades would be very similar?

  7. HavenXia commented on Jul 27, 2026

    @HavenXia
    Member

    Or is it sufficient to push this responsibility to the actor? The actor receives a SIGTERM when the pod is deleted and decides how to proceed.

    I think SIGTERM only exists when termination happens, right? On the suspend path there's no signals to actors, and according to #503 it's a good addition for in memory states.

    "required for the initial release"

    I agree, it is not for M2. We can implement post M2.

    This was the assumption I was proceeding with for graceful termination, and it seems like upgrades would be very similar?

    I think it's similar at the per-actor step, but opposite in the property that matters. Graceful termination(your #517) ends the actor with SIGTERM. But the upgrade drain I am designing wants every actor checkpointed and resumed on the new stack. So the upgrade batch suspends everything proactively, before any pod is deleted - by the time the old pods die they should already be empty, and your SIGTERM path is the safety net for outliers when we turn down the old pods.

    Overall I think we can keep this open but note it's a post M2 task. WDYT?

  8. sfunkenhauser commented on Jul 27, 2026

    @sfunkenhauser
    CollaboratorAuthor

    Yes sounds good.

  9. sfunkenhauser commented on Sep 24, 2026

    @sfunkenhauser
    CollaboratorAuthor

    Some initial thoughs.

    Actor lifecycle hooks: preCheckpoint and postRestore

    Problem

    Actors are checkpointed and restored many times over a single process lifetime. Memory survives the boundary; almost nothing else does.

    • After a restore, the wall clock has jumped, TCP connections are dead on both ends, tokens and leases have expired, timers did not fire. Nothing tells the actor this happened.
    • Before a checkpoint, the actor gets no warning. A DATA-scope checkpoint captures only the durable-dir volumes, read from the host directory. Writes still sitting in the application's buffers, or in the sandbox's page cache, are silently missing from the snapshot.

    I propose two optional HTTP hooks: one that tells the actor a checkpoint is coming so it can get ready, and one that tells it a restore has happened so it can reconcile.

    Design

    API

    One optional field on Container, alongside readyz:

    message Lifecycle {
      // pre_checkpoint is called before the actor's state is captured, on both
      // Suspend and Pause.
      //
      // +k8s:optional
      HTTPPostAction pre_checkpoint = 1;
    
      // post_restore is called after the actor is restored from a snapshot. It is
      // not called on run.
      //
      // +k8s:optional
      HTTPPostAction post_restore = 2;
    }

    The hooks are HTTP POST, to match how webhooks are generally handled. The ateom calls them over the interior veth, just as it polls readyz. There is no exec or sleep handler for now, but we could consider adding them in the future.

    preCheckpoint

    preCheckpoint signals that a checkpoint is coming shortly. The actor should get ready for it: close open connections (including long-lived streams such as WebSockets), flush buffers to durable-dir volumes, drop state that should not be captured.

    It is not an opportunity to finish the current turn. The hook has a hardcoded timeout of roughly 5s, and a turn can take minutes. Deciding when an actor is at a good point to be suspended is the job of an outer loop, such as the idleness probe or whoever calls SuspendActor.

    preCheckpoint → deactivate networking → pause / checkpoint
    

    The hook runs before networking is deactivated, so the actor can still flush over the network. Requests still in flight when networking is deactivated are canceled.

    postRestore

    postRestore signals that the actor was restored from a snapshot, so the actor can reconcile: resync the clock, reconnect, refresh tokens.

    restore sandbox → activate networking → { postRestore ∥ readyz } → return
    

    It runs in parallel with readyz, so it costs max(hook, readyz) instead of the sum. The restore waits for both, and no traffic is routed to the actor until then. Because the hook sits on the activation path, it has a hardcoded timeout of 500ms.

    Behavior

    Hooks are fail-open. If a hook returns non-2xx, times out, or cannot be reached, the failure is logged and the checkpoint or restore proceeds. A hook is a signal, not a chance to cancel the suspend or block the restore.

    New requests are held off during preCheckpoint. Once the workflow commits SUSPENDING or PAUSING, the router parks new requests for the actor instead of routing them to it. Streams opened before that point (WebSockets, CONNECT tunnels) are not gated, so the actor must close them itself.

    A slow preCheckpoint causes 503s. The router parks a request for at most 5s. That window has to cover the hook, the checkpoint, and the resume that follows, so if preCheckpoint takes too long, requests arriving during the suspend start getting 503 errors.

    Hooks must be idempotent. They fire on every checkpoint and restore and are delivered at least once.

    Integrating

    Serve the routes you need. The status you return is logged, not acted on:

    func (a *app) preCheckpoint(w http.ResponseWriter, r *http.Request) {
        a.closeConnections()
        if err := a.flush(); err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        w.WriteHeader(http.StatusOK)
    }
    
    func (a *app) postRestore(w http.ResponseWriter, r *http.Request) {
        a.reconnect()
        a.refreshTokens()
        w.WriteHeader(http.StatusOK)
    }

    Appendix

    Why not fail-closed

    Fail-closed hooks would let an actor refuse a checkpoint or a restore. For preCheckpoint, that protects an actor whose flush failed from a DATA snapshot that is missing data. The costs:

    • The actor controls when its worker is reclaimed. A hook that keeps failing blocks every suspend, and the platform can no longer take the worker back without the actor's consent.
    • A refused suspend strands the actor. The workflow has already committed SUSPENDING, so the actor stays there, holding its worker and serving nothing, until the suspend is retried and succeeds. Requests parked in the meantime start getting 503s after 5s.
    • A refused restore does not heal on retry. A retry restores the same snapshot, and a reconcile that failed because an external dependency is down fails again, so the actor is unavailable until the dependency recovers.

    Fail-open is the right default. Fail-closed could be offered later as a per-template policy for actors that would rather not be suspended than risk losing data.

    Waiting for the current turn

    An actor may want a suspend to wait until its current turn finishes. preCheckpoint cannot provide that. While the hook runs the router parks new requests, and a parked request waits at most 5s before getting a 503. A turn can take minutes, so blocking the suspend on it would make the actor unavailable to every new caller for the rest of the turn, while it keeps holding its worker. This is out of scope for the initial lifecycle hooks.

    Updated November 19th, 2026

    Why Post, not GET

    Switched the design to use Post, instead of GET.

    A hook is an event notification, webhooks generally use POST for these types of operations. The body can also be extended to carry event data later.

  10. krisztianfekete commented on Sep 24, 2026

    @krisztianfekete
    Collaborator

    Thanks for writing this up Scott Funkenhauser (@sfunkenhauser), really excited about this one! A lot of our telemetry flushing suffering (see #503) goes away if this is designed with telemetry in mind, so it might be worth calling that out in the Problem section too?

    A few questions from the observability side:

    Does postRestore also fire when a new actor first comes up from the golden snapshot? That's the case I'm most interested in, because that's where actors would want to reset their OTel SDK. Relatedly, can we count on /run/ate/actor-* already having the new actor's identity when the hook runs? Otherwise we'd get the template's identity.

    For preCheckpoint, I'm guessing most actors will just call ForceFlush there. Could we say explicitly that the export path (egress today, the relay later) stays up until the hook returns? And since 5s is shorter than the OTLP exporter's default 10s timeout, we'll probably want to tell people to ForceFlush, and make sure ateom actually cancels the request if it times out.

    Would it be possible to send traceparent with the hook requests? Then whatever the actor does in the hook shows up in the same trace as the suspend or resume. It would make slow resumes a lot easier to debug.

    Fail open sounds right, but I'm a bit worried failures will be pretty hard to notice when logged only. What do you think about a hook duration metric and a failure event with the actor's identity? I'm happy to track these in new issues.

    Btw, I'm assuming hooks don't fire on delete, so the final flush there still relies on SIGTERM?

  11. sfunkenhauser commented on Oct 1, 2026

    @sfunkenhauser
    CollaboratorAuthor

    Does postRestore also fire when a new actor first comes up from the golden snapshot?

    Yes.

    Relatedly, can we count on /run/ate/actor-* already having the new actor's identity when the hook runs? Otherwise we'd get the template's identity.

    Good question. I haven't looked at this yet, but this sounds reasonable.

    For preCheckpoint, I'm guessing most actors will just call ForceFlush there. Could we say explicitly that the export path (egress today, the relay later) stays up until the hook returns? And since 5s is shorter than the OTLP exporter's default 10s timeout, we'll probably want to tell people to ForceFlush, and make sure ateom actually cancels the request if it times out.

    Yes, we should make sure the actor networking stays up during this hook. Good point on the additional documentation with the mismatched timeouts.

    Would it be possible to send traceparent with the hook requests? Then whatever the actor does in the hook shows up in the same trace as the suspend or resume. It would make slow resumes a lot easier to debug.

    I'd have to look into this, but there is likely other information we want to pass through to the hook (or if not through the hook directly, through another API that the actor can query). Regardless we should provide a way for actors to get the traceparent during the hook.

    Fail open sounds right, but I'm a bit worried failures will be pretty hard to notice when logged only. What do you think about a hook duration metric and a failure event with the actor's identity? I'm happy to track these in new issues.

    Sure, we can have additional metrics around this.

    Btw, I'm assuming hooks don't fire on delete, so the final flush there still relies on SIGTERM?

    Yes that's correct, at least for now. There is an idea to auto-suspend on termination instead of sending SIGTERM #1707.

  12. MushuEE commented on Nov 17, 2026

    @MushuEE
    Collaborator

    Use cases from AX (coding agents)

    Details

    Context: AX runs coding agents (Claude Code, Gemini CLI, etc.) as Substrate actors,
    with an in-guest runner as the container entrypoint. Tasks are suspended when idle
    and resumed on the next user message, often hours or days later.

    1. PreSuspend: persist session state and quiesce in-flight work

    A coding agent is suspended while it has a streaming model response open, or
    while a tool call (npm install, git rebase, a test run) is mid-flight.

    • With a full snapshot, the restored process holds a half-open TCP stream that
      never completes, so the harness hangs until its own timeout.
    • With a data-only snapshot, anything not yet written to the durable dir is
      lost: the conversation transcript, the in-progress rebase, unsaved edits.

    In PreSuspend the runner would cancel or finish the model request, let the tool
    call reach a safe point, write the transcript to the durable dir and fsync.

    Today nothing tells the guest a suspend is coming. The caller of SuspendActor
    is outside the sandbox and cannot see whether the agent is mid-write.

    2. PostResume: refresh credentials and reconnect

    The agent holds short-lived credentials (git token, model gateway token) and
    long-lived connections (MCP servers, language servers with remote backends).
    After an overnight suspend, the first git push or model call fails with a 401
    or a dead socket. The model sees a tool error, and often spends turns
    misdiagnosing it ("the remote rejected my push, let me try a different branch").

    In PostResume the runner would re-mint tokens from the actor identity, rewrite
    the git credential helper and restart MCP connections, before any request
    reaches the agent.

    wakeup_probe can approximate this, but it is a readiness poll rather than an
    action: it is called repeatedly, it cannot distinguish cold boot from restore,
    and it does not say how long the actor was asleep. The hook also has to come
    from Substrate rather than from AX, because a request through the router can
    wake an actor without AX being involved.

    3. PostResume: tell the agent that time has passed

    A user returns to a coding task after three days. The agent's context still
    believes its branch is current with main. It is not, and the agent proceeds to
    build on a stale base or opens a PR that conflicts.

    We do not want the hook to run git pull itself: that is unbounded, can
    conflict, and changes the repo underneath the model's context. Instead the
    runner would use PostResume to inject a note such as "resumed after 3 days;
    upstream may have moved" and let the agent decide whether to fetch and rebase.

    This needs the hook to carry resume metadata: suspended-at, resumed-at, and
    whether this was a full restore, a golden restore or a cold boot. The same
    metadata covers the golden-restore case, where process memory comes from the
    template but the disk is the actor's own, so the runner must reload workspace
    state rather than trust what is in memory.

    What these imply for the design

    • PreSuspend needs a deadline and a failure policy. Use case 1 would benefit
      from the handler being able to say "not safe yet" so the suspend is retried
      rather than forced. Kubernetes PreStop has no such veto; it is only bounded
      by the grace period.
    • PostResume should complete before ResumeActor returns and before the
      router forwards traffic, otherwise use case 2 races the first request.
    • PostResume should fire on every wakeup, including cold boot and golden
      restore, and tell the handler which one it was.
    • Resume metadata (resume source, suspended duration) should be passed to
      the handler or exposed in the guest.
    • Handler types: exec and HTTP, as in Kubernetes, would both work for us.
    • Delivery: at-least-once is fine; our handlers will be idempotent.
  13. thockin commented on Nov 23, 2026

    @thockin
    Collaborator

    Scott Funkenhauser (@sfunkenhauser) We have previously discussed the race between self-suspend and incoming traffic - that feels related to the period where we are SUSPENDING.

    Could you draw the parts of the actor state-machine where RUNNING->SUSPENDING->SUSPENDED for this (lifecycle hooks) proposal and then see if we can work in the self-suspend parts. I feel like there's a high risk for gaps unless we think through every transition. e.g. this proposal adds "preCheckpoint handler runs" and ""preCheckpoint handler returns success" and "preCheckpoint handler returns error" edges.

  14. thockin commented on Nov 23, 2026

    @thockin
    Collaborator

    Also, is there a reason not to use "suspend" and "resume" terms? pre_suspend and post_resume or even just suspend and resume ?

  15. thockin commented on Nov 23, 2026

    @thockin
    Collaborator

    Does postRestore also fire when a new actor first comes up from the golden snapshot? That's the case I'm most interested in, because that's where actors would want to reset their OTel SDK. Relatedly, can we count on /run/ate/actor-* already having the new actor's identity when the hook runs? Otherwise we'd get the template's identity.

    I think the identity and all projected volumes (etc) must be fully set up before we run a single instruction.

    We should consider if we need something like a "resume count" as part of the POST body. We should spec the body as JSON document, even if we have no fields yet, and then think hard about what fields we might need and how we get that info.

    and make sure ateom actually cancels the request if it times out.

    Cancels which request? The suspend?

    What do you think about a hook duration metric and a failure event with the actor's identity?

    love it

    Btw, I'm assuming hooks don't fire on delete, so the final flush there still relies on SIGTERM?

    Excellent question - that needs to be part of the state machine diagram

  16. thockin commented on Nov 23, 2026

    @thockin
    Collaborator

    Use cases from AX (coding agents)

    A coding agent is suspended while it has a streaming model response open
    ...
    In PreSuspend the runner would cancel or finish the model request, let the tool call reach a safe point, write the transcript to the durable dir and fsync.

    In the current proposal it has 5 seconds to do that. This is not being modelled as a NAK'able thing or a long-duration delay. If we need those, we need to revisit the design.

    The caller of SuspendActor is outside the sandbox and cannot see whether the agent is mid-write.

    Either external callers of SuspendActor() need to know that the actor is functionally idle (flushes aside) or they need to be OK with potentially killing an operation. Until we have network-safe suspend, anyway. I could imagine a use-case for "TrySuspendActor" or "SuspendActor(mode: WhenReady)" or even "SuspendActor(maxWaitSeconds: 3600)", but none of those are currently part of this scope. Do we need those? It's a significant change, I think.

  17. sfunkenhauser commented on Nov 23, 2026

    @sfunkenhauser
    CollaboratorAuthor

    Good callout about the terminology. I was talking with Julian Gutierrez Oschmann (@juli4n) about this and we should be consistent between the naming of the lifecycle hooks and the API (the reason they were originally checkpoint and restore is to match the atelet / worker APIs).

    So I agree the naming should be updated to pre_suspend and post_restore. I find the prefixes add a bit more clarity, but I don't have a super strong opinion if others want to push for supend and resume.

    Coupling the basic self-suspend story with lifecycle hooks adds quite a bit of complexity (if all you care about is self-suspend). I want to de-couple these concepts, and the only connection is that a suspend / resume was triggered. How it was triggered (self-supsend vs orchestrator) shouldn't matter. I have a tentative plan on how we can solve this for self-suspend without adding a dependency on lifecycle hooks #483

    For lifecycle hooks I want to break this down into a few separate milestones.

    M1 - hooks are fail open

      stateDiagram-v2
          direction LR
    
          state "POST preCheckpoint" as PC
    
          RUNNING --> SUSPENDING : SuspendActor
          SUSPENDING --> PC
          PC --> SUSPENDED : 2xx<br/>checkpoint
          PC --> SUSPENDED : non-2xx, unreachable,<br/>or no answer in 5s<br/>log + metric, checkpoint
    
    Loading
      stateDiagram-v2
          direction LR
    
          state "POST postRestore" as PR
          state "wakeupProbe" as WP
          state fork <<fork>>
          state join <<join>>
    
          SUSPENDED --> RESUMING : ResumeActor
          RESUMING --> fork : restore sandbox,<br/>activate egress
          fork --> PR
          fork --> WP
          PR --> join : 2xx
          PR --> join : unreachable after 30s,<br/>non-2xx, or no answer<br/>500ms after accept<br/>log + metric
          WP --> join : 200
          WP --> CRASHED : no 200 within<br/>timeoutSeconds
          join --> RUNNING : activate ingress
    
    Loading

    This is the easiest case, and what I think we should target first. Since the hooks are fail open, they are also best effort and you might not receive them. This means you can't use them for any consistency guarantees between self-suspend -> pre_suspend to avoid mid-suspend requests.

    To handle suspending mid-request, actors need to ensure their APIs are idempotent, update progress once the results are durable and have clients retry on failures. I imagine this will be the most common case, as there are other reasons actors need to have these properties (network failures and retires can result in the same client request landing multiple times).

    The alternative is tight coupling between the actors, clients and orchestrator so that no clients send new request if the orchestrator is triggering a suspend. If that's the case then self-suspend likely doesn't add much value for these actors.

    M2 - hooks are failed closed

      stateDiagram-v2
          direction LR
    
          state "POST preCheckpoint" as PC
    
          RUNNING --> SUSPENDING : SuspendActor
          SUSPENDING --> PC
          PC --> SUSPENDED : 2xx<br/>checkpoint
          PC --> PC : non-2xx, unreachable,<br/>or no answer in 5s<br/>retry
          PC --> CRASHED : still failing<br/>after 30s
    
    Loading
      stateDiagram-v2
          direction LR
    
          state "POST postRestore" as PR
          state "wakeupProbe" as WP
          state fork <<fork>>
          state join <<join>>
    
          SUSPENDED --> RESUMING : ResumeActor
          RESUMING --> fork : restore sandbox,<br/>activate egress
          fork --> PR
          fork --> WP
          PR --> join : 2xx
          PR --> PR : unreachable, non-2xx,<br/>or no answer 500ms<br/>after accept<br/>retry
          PR --> CRASHED : still failing<br/>after 30s
          WP --> join : 200
          WP --> CRASHED : no 200 within<br/>timeoutSeconds
          join --> RUNNING : activate ingress
    
    Loading

    Add a failurePolicy to the hooks.

    • Default to IGNORE (fail open) for backwards compatibility
    • FAIL means hooks return utill they receive 2xx. Crash if they hit a XXs timeout.

    Now the state changes are synchronous (or the actor crashes). If you have an advanced use case where you want to trade reliability for consistency you can. I'm still not sure self-suspend fits in this category, but if you really wanted to, you could use lifecycle hooks to manage self-suspend.

    It's worth pointing out this still won't avoid an orchestrator from suspending an actor in the middle of a request

      message HttpPostAction {
        ...
    
        // failure_policy says what happens when the hook fails. Unset means
        // HOOK_FAILURE_POLICY_IGNORE.
        //
        // +k8s:optional
        HookFailurePolicy failure_policy = 3;
      }
    
      // HookFailurePolicy says what happens when a lifecycle hook fails. A hook
      // fails when it can't connect, the connection breaks, it times out, or the
      // answer isn't 2xx.
      enum HookFailurePolicy {
        HOOK_FAILURE_POLICY_UNSPECIFIED = 0;
    
        // Log the failure and go ahead with the checkpoint or restore.
        HOOK_FAILURE_POLICY_IGNORE = 1;
    
        // Retry the hook until it succeeds or 30 seconds have passed. Then crash
        // the actor.
        HOOK_FAILURE_POLICY_FAIL = 2;
      }
    
  18. sfunkenhauser commented on Nov 23, 2026

    @sfunkenhauser
    CollaboratorAuthor

    We should spec the body as JSON document, even if we have no fields yet, and then think hard about what fields we might need and how we get that info.

    +1

    Btw, I'm assuming hooks don't fire on delete, so the final flush there still relies on SIGTERM?

    Excellent question - that needs to be part of the state machine diagram

    The diagram gets very complicated if we try to annotate all states. I'd prefer to keep a minimal diagram, and excluded states means they are not relevant. Let me know if you disagree, or if there are specific exceptions and I can update them.

    I could imagine a use-case for "TrySuspendActor" or "SuspendActor(mode: WhenReady)" or even "SuspendActor(maxWaitSeconds: 3600)", but none of those are currently part of this scope. Do we need those? It's a significant change, I think.

    We could add another failure policy ABORT. If the hook fails, the suspend / resume operation is aborted (actor is not crashed) and the client must retry. We need to think carefully about this as it lets an actor reject an eviction, I'm not sure that's something we want to support.

    In general I see this as a separate feature. Maybe a suspend policy? Or a separate API as you mentioned.

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

Metadata

Metadata

Labels

area/api-machinerykind/feature

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions