Dynamic Composition and Rollback for Long-Running Agent Hosts
Long-running agents must keep memory, connections, task progress, and tool state alive across hours of work while adding and replacing capabilities in place. This article explains why coarse process restarts lose that state, and how spatial dependency topology, temporal replacement order, plugin contracts, snapshots, version vectors, short critical-section switches, and graded isolation make dynamic extension, in-place updates, and atomic rollback testable runtime behavior.
Long-running agents are no longer a single model call wrapped around a user question. Over hours or longer, they must keep conversation memory, external connections, task progress, and tool state, and add capabilities as execution demands them. The host framework is therefore not a thin wrapper around the model. It is a runtime responsible for lifecycle, dependencies, isolation, and recovery.
Where the Problem Comes From
A failed single-turn call is cheap: resend a bad prompt, and a process exit does not affect the next call. Long-running work is different. An agent may hold a retrieval session, message subscriptions, file handles, and intermediate plans at the same time. Restarting the whole process whenever a tool is added or removed drops accumulated context, forces connections to be rebuilt, and interrupts the step in progress. Users see the task jump back to the start. On the system side, the cost is startup latency and inconsistent state.
These systems usually face three requirements at once.
First, capabilities must be assembled for the task. Load the component when the current step needs computation, retrieval, or an external service, and unload it when the task ends so every dependency does not stay in the process forever.
Second, updates must take effect in place. If a tool is defective at runtime, or a piece of adapter logic must be added, replace the implementation instead of discarding the session. Before and after replacement, confirmed in-memory state, connection caches, and the task cursor need a clear owner.
Third, failures must be retractable. If an extension written by a model or a person has a syntax error, a missing dependency, or a runtime exception, the blast radius should be that one change, not the host. This is similar to the atomicity a database transaction seeks: either the new version is fully usable, or the system returns to a consistent snapshot from before the change.
Why Coarse-Grained Restarts Are Not Enough
A common industry approach is editor-style plugins, service orchestration, or process isolation for extensibility. These solve “we can add a module,” but the grain is often too coarse.
Uninstall or upgrade often means restarting the process or even rebuilding the runtime unit. In-memory sessions, caches, and partial results are not migrated by default. The startup path must reload configuration, recheck dependencies, and reestablish connections, and latency grows with the number of dependencies. More importantly, dependencies stop at “this service depends on that service.” They do not express a finer topology inside one address space: which plugin is valid only for one task, which state belongs to the session and which to the process, and which layer should roll back on failure.
Coarse isolation still has value, especially for untrusted code and resource quotas. It does not replace fine-grained composition. A long-running agent needs clear extension boundaries and state boundaries that can be declared, migrated, and rolled back.
Two Orthogonal Dimensions of Composition
Dynamic composition can be split into space and time. The two are orthogonal and cannot substitute for each other.
The spatial dimension answers what parts exist now and how they connect. That includes plugin identity, interface contracts, dependency direction, ownership of shared state, and the blast radius of failure. Poor spatial design shows up as cyclic dependencies, implicit globals, and dangling references that are still invoked after unload.
The temporal dimension answers how the system moves from one moment to the next. That includes the order of load, initialization, replacement, unload, and rollback, and whether those actions overlap work that is already running. Poor temporal design shows up as a hot update tearing down an object that is in use, or old and new implementations writing the same state at once.
Composition can be checked only when both dimensions are describable, not merely “run it and see.” Checkable does not require a full formal proof. It does require being able to say which plugins a change touches, which state it touches, and what success and failure each leave behind.
Plugins as the Basic Unit
One workable principle is to keep the host small and bring business capabilities, tool adapters, memory stores, policy control, and observability probes into the runtime as plugins. A plugin is not another name for an arbitrary script. It should meet a few minimum contracts.
- It has a stable identity and version, so it is clear which implementation is running.
- It declares dependencies and the capabilities it provides. The host builds a topology from that declaration instead of relying on startup order.
- It separates three kinds of state: immutable configuration, rebuildable cache, and session facts that must be kept. Only the third kind must be migrated or frozen across an update.
- Initialization, ready, replacement, and stop are an explicit lifecycle, not side effects of importing a module.
A schematic lifecycle can be written as the pseudocode below. The point is order and failure branches, not the API of any particular framework:
begin_change(change_id):snapshot = capture(session_facts, dependency_graph)stage = load_candidate(plugin, version)if not stage.check_contract():abort(change_id) # do not touch the running instancereturn snapshotstage.prepare(snapshot) # prepare only; do not switch trafficif not stage.ready():discard(stage)restore(snapshot)return snapshotswitch(active, stage) # short critical sectiondrain(old)commit(change_id)
The switch should be as short as possible. Checks, dependency resolution, and state preparation happen before it. If the switch fails, discard the candidate and restore the snapshot so the system is not half new and half old.
Spatial Composition Needs an Explicit Topology
Sharing one address space reduces serialization cost and makes it easier to share read-only context, but dependencies must be data, not implicit imports.
At a minimum, record the plugin identifier, version, imported capabilities, exported capabilities, whether task-level dynamic loading is allowed, and whether the plugin holds external connections. Before load, the host checks for cycles and rejects undeclared cross-plugin calls. Dynamically generated tools follow the same path. “Written for this task” is not a reason to bypass the contract.
State ownership comes before performance tuning. Session facts live in a versioned state store. Rebuildable objects such as connection pools and index caches live in plugin-private caches and may be dropped and rebuilt on update. If two plugins must share a mutable structure, they hand it off through a narrow interface provided by the host and do not hold each other’s internal objects. Otherwise unload cannot tell whether a reference is still live.
Isolation can be graded rather than only “whole process” or “fully trusted.” Syntax and dependency checks finish before load. Runtime exceptions are caught at the boundary and attributed to the change or the tool call, not to the entire host. Only untrusted or resource-unbounded code is promoted to a separate process. Graded isolation keeps most tools low-latency while keeping high-risk code outside.
Temporal Composition Must Preserve the Session
The goal of a hot update is not “the process never restarts.” It is “confirmed progress is not destroyed by one replacement.” A few rules help in practice.
- Calls already in progress keep the old implementation until they return. Only new calls enter the new implementation, so code does not change mid-execution.
- Freeze writes to session facts before replacement, or record them in a pending commit log, and open writes again only after the switch succeeds. That avoids old and new implementations interleaving writes to the same key.
- Reuse external connections when they can be reused. If they cannot, establish the new connection during preparation and close the old one after the switch. Do not perform a network handshake inside the critical section.
- Keep in memory only derivatives that can be replayed from session facts. If a cache cannot be recomputed, it is already a fact and belongs in the snapshot.
Long-running tasks also need checkpoints, but not a full copy on every step. A checkpoint should cover the task cursor, references to results of completed steps, inputs of unfinished steps, and the plugin version vector. The version vector answers which plugin combination produced a result. On replay or migration, an incompatible version should go through an explicit migration function rather than silently reusing the old object.
Fold Failure into One Transaction
When a model helps generate extensions, errors are normal: invalid syntax, incomplete dependency declarations, exceptions at runtime, or logic that runs but corrupts state. The host should assume a change may fail and define the rollback point in advance.
At the start of a change, record the dependency graph and the snapshot identity of session facts. The candidate plugin enters a staging area only and is not registered in the callable table. A failed static check discards the staging area immediately. A failed prepare also does not switch. The change is committed only after the switch succeeds and the old instance has drained. If a health check fails after the switch, switch back and restore the version vector pointed to by the snapshot identity.
Two kinds of rollback should be distinguished. Install rollback undoes code and dependencies while session facts stay as they are. Business rollback undoes session facts that this change has already written, which requires those writes to be compensatable or replayable. If an extension changes the outside world before commit and that change cannot be compensated, the transaction boundary does not hold. Such side effects must be deferred until after commit, or turned into idempotent external operations.
A process can still crash. Snapshots therefore cannot live only in memory. At least the version vector, checkpoints, and change log belong in durable state storage. After a restart, the host recovers first and only then accepts new tasks. The goal of recovery is consistency, not bravely continuing a half-finished change.
Observation, Testing, and Release
A dynamic system that cannot answer “what is loaded now” cannot be debugged. Each change should leave an identifier, the actor (a person or an agent), the old version, the new version, check results, and duration. Runtime metrics should at least include active plugin count, switch latency, rollback count, checkpoint interval, and session-fact size. Alerts should target rollback rate and switch failure rate, not only whether the process is alive.
Tests must cover overlap in time, not only single-plugin unit tests. Typical cases include replacement while a call is in progress, failed preparation, a failed health check after switch, unload while an in-flight call still references the plugin, and two changes acting on the same dependency concurrently. Concurrent changes are best serialized inside the host for the same session so two snapshots do not overwrite each other.
Release in small steps: replace one plugin, or one tightly related group, at a time, and keep the previous version until the observation window ends. Extensions written by the agent itself should pass contract checks and a sandbox rehearsal before they enter the change transaction of a real session. The rehearsal uses a copy of session facts, not production connections.
Tradeoffs in Practice
Not every component deserves a hot update. Tool adapters that change often and are tightly bound to the session fit plugins plus transactional switching. Stateless computation that changes rarely and starts cheaply is simpler to restart. Components that hold large, non-compensatable external side effects should narrow the transaction and move those side effects out of the critical section.
There is also no need for everything to live in one process. A fine-grained spatial topology can coexist with a small amount of process isolation: keep trusted, low-latency paths in-process, and place untrusted extensions outside the isolation boundary, called through an explicit message contract. Choose by failure radius and whether state must be shared, not by an architectural slogan.
Summary
The host problem for long-running agents is not another wrapper around the call interface. It is designing spatial dependency topology and temporal replacement order together. Plugins provide the assembly unit, snapshots and version vectors provide recovery coordinates, and a short critical-section switch plus graded isolation provide an operable failure boundary. With those in place, dynamic extension, in-place update, and atomic rollback become testable runtime capabilities rather than tribal technique. Without them, no amount of finer task prompting restores a session lost to a blunt restart.
