Upgrade running actors in place

An order waiting a week for delivery can move to its chart's next version and keep the state it reached. Two million actors, most of them hibernated, moved while events kept coming.

Add the new version to the host

host.addImage(image) adds a compiled image to a running host. A chart in it with a name the host already has becomes that chart's new version.

host.spawn(name) spawns the newest version, which host.chart(name) returns, and running actors stay on theirs.

Each image becomes a segment of the host: those new Host was given, and each one added after.

Time the first actor on a new version

Compile both versions of the order chart up front. In version 2, change the retry delay from one second to two.

For each trial, start and settle one version 1 actor on a fresh host with a simulated clock. Time host.addImage(), spawning the first version 2 actor and waiting for host.idle().

After 20 warm-up trials, the next 100 took 0.18 ms at the median and 0.95 ms at the 95th percentile. Measured 2026-12-02 with @tinyactors/node 0.4.0, Node.js 24.22.3 and Linux on an AMD EPYC 9V74.

This measures activation inside one process with the chart bytes already in memory. Compilation, transferring the chart and moving existing actors are separate steps.

Decide which actors must move

Adding the image is a deploy on its own: an actor that may finish on its version needs no migration.

An order that waits a week for its delivery is still running when the next version ships. Stopping it would lose its state.

A migration moves it instead, while the host goes on working, as part of operating a host.

An actor found by name is replaced when its owner spawns the new version under the name (updating through names). Migrate the actors that must not wait for their end.

Move the actors and carry their variables

host.migrate() moves the running actors to the newest version of their chart, during the next turns.

A moved actor keeps its session, its active states, its queue and its delayed sends with their data. Its states are matched by id (below).

Its variables do not carry over by themselves, since the new version may name them differently. The actor first gets error.platform.upgrade, whose data holds the old version's variables.

Version 2 of this counter renames n to count and takes the old value from the upgrade event:

migrate.mjsjavascript
import { compileCharts, Host } from '@tinyactors/node';

const image = (name, text) => {
  const compiled = compileCharts([{ name, text }]);
  const bytes = compiled.image;
  compiled.close();
  return bytes;
};

const v1 = image('counter-v1.scxml', `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="counter" initial="counting">
  <datamodel><data id="n" expr="0"/></datamodel>
  <state id="counting">
    <transition event="add"><assign location="n" expr="n + 1"/><log expr="'v1 counts ' + n"/></transition>
  </state>
</scxml>`);

// Version 2 renames n to count and counts by ten.
const v2 = image('counter-v2.scxml', `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="counter" initial="counting">
  <datamodel><data id="count" expr="0"/></datamodel>
  <state id="counting">
    <transition event="error.platform.upgrade">
      <assign location="count" expr="_event.data.n"/>
      <log expr="'upgraded, the old variables were ' + JSON.stringify(_event.data)"/>
    </transition>
    <transition event="add"><assign location="count" expr="count + 10"/><log expr="'v2 counts ' + count"/></transition>
  </state>
</scxml>`);

const host = new Host(v1, {
  system: 'demo',
  log: (entry) => console.log(entry.text),
  migrated: (moved) => console.log(`session ${moved.session} moved to segment ${moved.segment}`),
  migrationDone: (result) => console.log(`migration ${result.migration}: ${result.migrated} moved, ${result.failed.length} failed`),
});

const counter = host.spawn('counter');
counter.send('add');
counter.send('add');
await host.idle();

host.addImage(v2);                 // the deploy
const id = host.migrate({ chart: 'counter' });
console.log(`started migration ${id}`);
await host.idle();

counter.send('add');
await host.idle();
host.close();
output
v1 counts 1
v1 counts 2
started migration 1
session 1 moved to segment 1
migration 1: 1 moved, 0 failed
upgraded, the old variables were {"n":2}
v2 counts 12

Once no actor runs on an old segment, the host retires it and frees its memory. host.hostStats counts the retired segments (Inspecting a host).

On the native datamodel, the upgrade event's data holds exactly the old version's variables. An old name the new version does not declare is gone after it.

The actor gets the new version's helper functions. The new version's vars are declared and undefined, since a migration runs no script.

Choose what moves, and read the result

host.migrate picks the actors, and the migrationDone and migrated handlers in the host's options report on them:

  • host.migrate({ chart, session, wake, timeout })starts a migration and returns its id, a number. With no options it moves the actors of every chart; chart names one chart, session one actor. wake: true asks for the hibernated actors. timeout is in milliseconds of the host's clock, rounded up to its next tick; 0 or none means none. A chart the host does not have throws TA_ERROR_INVALID, and a session that ended TA_ERROR_STALE: a migration that could move nothing is refused rather than reported done.
  • migrationDone: (result) => ...in the host's options, gets the end of each migration: { migration, migrated, failed, pending }. failed lists the actors it could not move, each { session, reason } with reason core's status; pending lists the sessions (bigints) its timeout left behind. It is a handler of the host, so a migration started by a host that was later restored reports to the restored host's handler.
  • migrated: (moved) => ...gets each actor moved, a view of session, segment, chart (its name) and migration, valid while the handler runs.

Do <onentry> work in the upgrade transition

A migration enters the new version's states without running their <onentry>, and leaves the old ones without their <onexit>.

It matches states by id, then completes the active states to a set the new version allows:

  • a state that is compound in the new version, and had no children in the old, is entered at its initial child, or its first;
  • a state the new version does not have at all is replaced by its parent's initial state, the chart's initial at the top;
  • a <parallel> gets all its regions, and an <invoke> of a state the migration enters is started.

So what an <onentry> would have done, such as arming a timer or telling your program, is the upgrade transition's job. In() tells it where the actor landed.

Version 2 of this subscription gives pastDue a grace period and drops paused:

upgrade-states.mjsjavascript
import { compileCharts, Host, SimulatedClock } from '@tinyactors/node';

const image = (name, text) => {
  const compiled = compileCharts([{ name, text }]);
  const bytes = compiled.image;
  compiled.close();
  return bytes;
};

const v1 = image('sub-v1.scxml', `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="subscription" initial="active">
  <state id="active"><transition event="miss" target="pastDue"/><transition event="pause" target="paused"/></state>
  <state id="pastDue"/>
  <state id="paused"/>
</scxml>`);

// Version 2: pastDue starts a grace period, and paused is gone.
const v2 = image('sub-v2.scxml', `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="subscription" initial="active">
  <state id="active">
    <transition event="error.platform.upgrade"><log expr="_sessionid + ' upgraded into active'"/></transition>
  </state>
  <state id="pastDue" initial="grace">
    <transition event="error.platform.upgrade" cond="In('grace')">
      <log expr="_sessionid + ' upgraded into grace: arming its timer'"/>
      <send event="graceOver" delay="7s"/>
    </transition>
    <state id="grace">
      <onentry><log expr="'grace onentry'"/><send event="graceOver" delay="7s"/></onentry>
    </state>
  </state>
</scxml>`);

const host = new Host(v1, { system: 'demo', clock: new SimulatedClock(), log: (entry) => console.log(entry.text) });
const late = host.spawn('subscription');
const paused = host.spawn('subscription');
late.send('miss');
paused.send('pause');
await host.idle();

host.addImage(v2);
host.migrate();
await host.idle();
for (const actor of [late, paused]) console.log(actor.id, JSON.stringify((await actor.state()).value));
console.log('next deadline', host.nextDeadline);
host.close();
output
1 upgraded into grace: arming its timer
2 upgraded into active
1n {"pastDue":"grace"}
2n "active"
next deadline 7000

grace onentry is never logged. Without the upgrade transition's <send>, actor 1 would wait in grace forever.

Give a migration a timeout

A migration ends when every actor it looks at has moved, or at its timeout.

An actor running an invocation, an invoked chart or a service, moves once the invocation ends. With a timeout, the migration waits for the invocation to end, up to the timeout.

Without a timeout it fails such an actor at once with 'TA_ERROR_STATE', since an invocation may never end.

A migration still running when the host is closed never reaches migrationDone.

Wake hibernated actors so they move

A hibernated actor moves once it is woken. With wake: true the migration asks the host for it, and the host loads it from its store.

The migration asks again if it finds the actor hibernated after a wake.

Without wake, a hibernated actor that nothing wakes holds the migration until its timeout. Without a timeout it holds it forever, and migrationDone is never called.

Bound memory during a large migration

A migration with wake: true asks for every hibernated actor early. Woken all at once, they would all be in memory at once.

A host with a resident bound loads a migration's requests only while it holds fewer actors than the bound. It hibernates actors again after each turn, so the migration moves the population a few at a time.

An event for a hibernated actor still loads it at once.

A hundred counters with resident: 10 migrate with at most 10 in memory between turns:

paced.mjsjavascript
import { compileCharts, Host, MemoryStore } from '@tinyactors/node';

const image = (version) => {
  const compiled = compileCharts([{ name: `v${version}.scxml`, text: `
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="counter" initial="s">
  <datamodel><data id="version" expr="${version}"/></datamodel>
  <state id="s"><transition event="error.platform.upgrade"/></state>
</scxml>` }]);
  const bytes = compiled.image;
  compiled.close();
  return bytes;
};

const store = new MemoryStore();
/** @type {import('@tinyactors/node').MigrationResult | undefined} */
let done;

const host = new Host(image(1), {
  system: 'demo',
  store,
  resident: 10,
  migrationDone: (result) => (done = result),
});

for (let i = 0; i < 100; i++) host.spawn('counter');
await host.idle();
console.log(`${store.blobs.size} hibernated`);

host.addImage(image(2));
host.migrate({ wake: true });
let mostResident = 0;
while (done === undefined) {
  await host.idle();
  const stats = await host.hostStats();
  mostResident = Math.max(mostResident, stats.host.actors - stats.host.hibernated);
}
console.log(`${done.migrated} moved, ${done.failed.length} failed, at most ${mostResident} in memory between turns`);
host.close();
output
90 hibernated
100 moved, 0 failed, at most 10 in memory between turns

Find the actors that could not move

An actor whose variables cannot be stored stays on its version, in the result's failed with reason 'TA_ERROR_UNSUPPORTED'.

On the native datamodel, such a variable holds a value outside the value table, such as a function or a Map.

Hibernation refuses the same actors: call host.hibernate on one, and its error names the variable.

Migrate two million actors with 1000 in memory

tools/migration.mjs (mise run migration) runs this pattern at scale, with the actors past the bound in SQLite.

200,000 events came before the migration and 200,000 more during it. Every actor moved to version 2 with wake: true, in 3,688,635 loads from the store per run.

Every actor migrated, none failed and none was left. All 25,000 sampled actors had their count and version 2, and version 1's segment was retired.

After every eviction at most 1000 actors were resident.

Runtime, datamodelPopulate (2,000,000 and 200,000 events)Migrate (2,000,000 moved, 200,000 events)Peak residentCore's region, both versions / afterSQLite file
node, native58.4 s217.8 s (9,180 a second)756 MB (378 B per actor)329 MB / 164 MB (82 B per actor)590 MB
node, quickjs52.0 s181.8 s (11,000 a second)935 MB (467 B per actor)329 MB / 164 MB (82 B per actor)777 MB
bun, native52.4 s195.4 s (10,240 a second)967 MB (483 B per actor)329 MB / 164 MB (82 B per actor)590 MB
bun, quickjs49.4 s173.3 s (11,540 a second)925 MB (462 B per actor)329 MB / 164 MB (82 B per actor)777 MB
Two million actors of version 1 of a counter, at most 1000 resident, the rest in SQLite, all moved to version 2. One run of tools/migration.mjs, alone on the machine, 2026-11-20: Intel Xeon at 2.10 GHz, 4 CPUs, 16 GiB, Linux; Node.js 22.23.5, Bun 1.4.1.