Skip to main content

Slot lifecycle

This page covers when an identity is created, what keeps it, and when it goes. When a write is delivered (frames and batches) is the channel's business and is covered in The channel.

Setup shared by the examples on this page
import { OIMDB, isOIMSlotReleased, createOIMEntityContentService, createOIMSlotCollectionService, OIMSlotEarliestReleasePolicy, OIMSlotAfterWriteReleasePolicy, OIMSlotAfterIdleReleasePolicy, OIMSlotAfterUnholdReleasePolicy, mintOIMAfterIdleSlotReleaseWheel, OIMSlotReleaseManualDueFramePolicy, OIMSlotRefetchWheel, type TOIMSlot, OIMDefaults } from '@oimdb/core';

type Card = { id: string; title: string };

const db = new OIMDB();
const cardService = createOIMSlotCollectionService({ slotContentService: createOIMEntityContentService<Card>() });
const cards = cardService.createStoreSlot(db);
const cardContentService = cardService.slotContentService;

The life of a slot​

A slot is the identity of one key in one collection, a store slot. Everything that reads, writes or subscribes works through it, so its life is the part of the engine a consumer deals with every day.

Four doors mint a slot:a writea subscriptiona holdgetSlotByKey, held by the collector for the turn
Mintedthe collection creates the slot and files it under its key
Kepta hold, an effect, a column slot or a bucket counts on it
Asked to gothe last reference is given back, or its value leaves while nothing keeps it
Releasedthe release policy agrees: the slot leaves the store and isReleased is set

Filling and emptying happen while the slot is kept, and never change its identity. After a release, the next door for that key mints a new slot.

StageWhat happensWho causes it
Mintedthe slot owner creates the slot and files it under its key in the store slot's storethe first getSlotByKey, holdSlotByKey, writeSlotContentByKey for that key
Keptsomething counts on it: a hold (holdCount), an effect filed on it, a column slot on it, a bucket it is a member ofyou, an effect, an index
Filled / emptieda value lands on it or leaves it; the identity stays the same either waywrites: writeSlotContentByKey, updateEntity, clearSlotContent
Asked to gothe last thing keeping it gives it back, or its value leaves while nothing keeps itunholdSlot, effectService.disposeEffect(effect), the unused-slot collector at flush, a delete
Releasedthe release policy agrees; the value (if any) is cleared, the slot leaves the store, its RELEASED flag is set (isOIMSlotReleased(slot))the owner, never the caller

Try the stages on a real collection: mint with a getter and flush, hold and give back, write a value and delete it. Watch the identity number change when a released key is minted again.

Minted — four doors, and each one says who keeps the result​

A slot is created only by a door that also decides what keeps it, so nothing can mint an identity and leave it with no owner of its lifetime:

  • getSlotByKey(storeSlot, key) mints and hands the slot to the unused-slot collector, which holds it until the next flush. A read you do not keep is given back for you.
  • holdSlotByKey(storeSlot, key) mints and holds; the hold is yours to give back.
  • A write (writeSlotContentByKey) mints and fills; the value keeps it under the default policy. Two writes leave nothing that keeps the slot, and the unused-slot collector holds it until the collector flushes instead, the same as for getSlotByKey — see below.
  • An effect holds every slot it subscribes to until effectService.disposeEffect(effect).
const peek = cardService.getSlotByKey(cards, 'c1');
db.flush();
const released = isOIMSlotReleased(peek);
const again = cardService.getSlotByKey(cards, 'c1');
const isNewIdentity = again !== peek;

peek was minted empty and kept only by the collector. The flush gave that hold back, nothing else counted on the slot and it had no value, so it was released: released is true. The next read of 'c1' mints a new identity, so isNewIdentity is true.

Two writes that the collector keeps until it flushes​

A slot nothing holds is normally released at once. Two writes are the exception, because the slot they return would otherwise be dead on the very next line:

  1. The value lands empty. The collection's emptiness policy calls what was written empty — a soft-deleted record under slotEmptinessPolicy: { isEmpty: slot => slot.entity?.deleted === true }, say.
  2. The policy's window is already over at the write. OIMSlotAfterWriteReleasePolicy or OIMSlotAfterIdleReleasePolicy with a window of 0, on a slot no effect subscribes to.

In both, the slot goes to the unused-slot collector and is released when the collector flushes: at the end of db.flush(), or when a collector scope (OIMUnusedSlotCollectorService.INSTANCE.run) closes. Until then the caller can keep using what the write returned:

const briefService = createOIMSlotCollectionService({
slotContentService: createOIMEntityContentService<Card>(),
slotReleasePolicy: new OIMSlotAfterWriteReleasePolicy({ keepAfterWriteMs: 0 }),
});
const briefs = briefService.createStoreSlot(db);
const brief = briefService.writeSlotContentByKey(briefs, 'b1', { id: 'b1', title: 'one' });
brief.updateEntity({ title: 'two' });
db.flush();
const isGone = isOIMSlotReleased(brief);

The second write lands on the same slot, and the collector's flush at the end of db.flush() releases it: isGone is true. The case that needs this is a load that writes and then hands the result on, for example to a bucket: writeInBatch returning the slots of the writes, as persist's restore does. Without the collector, a record that lands empty would reach the bucket already released, and the bucket would refuse it.

Kept — references are counted​

Every reason to keep a slot is a count the owner keeps, and the owner is the only writer of it: holdCount, the effects list, the column slots on the carrier, bucket membership. There is no release command. A command would let one caller drop an identity another caller is still subscribed to; counting references lets the owner decide "nothing refers to it" in one place.

const ace = cardService.holdSlotByKey(cards, 'c2');
const filled = cardService.writeSlotContentByKey(cards, 'c2', { id: 'c2', title: 'Ace' });
const isSameIdentity = filled === ace;
db.flush();
ace.unholdSlot();
const keptByValue = !isOIMSlotReleased(ace);
ace.clearSlotContent();
const goneWithValue = isOIMSlotReleased(ace);

The hold minted 'c2' empty; the upsert filled the same slot. After the hold was given back the slot stayed, because under the default policy a value keeps it. The delete took the value away while nothing held it, and the slot went.

Asked to go — the release policy answers​

When the last reference goes, or the value leaves an unheld slot, the owner asks releaseSlotIfUnheld(slot). It re-checks everything (not held, not referenced, still owned by this owner) and then asks the release policy. How long data is worth keeping is a property of the collection type, not of each caller: a store of entities keeps what was written, a computed can be derived again and is dropped, and a cache of a remote list may be kept for a while after the screen closes. The policy is chosen once, at construction, so no write path branches on it. The policies are listed in the table in releasing an identity on a clock.

Released — the slot is dead and its key can be minted again​

Releasing a slot clears its content (an entity's value, a bucket's members, a computed's sources) and removes it from the store. After that, the object you still hold is a dead identity: every door that works with it (holdSlot, unholdSlot, a write, a subscription) throws "This identity was released". The key is not dead: the next door for it mints a new slot. So the long-lived things to keep in your code are the services and their store slots (entity, bucket, index or computed), and you keep a slot only for as long as you hold it.

const late = cardService.getSlotByKey(cards, 'c3');
db.flush();
try {
late.holdSlot();
} catch {
const fresh = cardService.holdSlotByKey(cards, 'c3');
fresh.unholdSlot();
}

clearSlotContent is not a release: they take the value away and leave the identity standing for as long as something keeps it. A subscriber of a deleted entity is still subscribed, and a later writeSlotContentByKey under the same key lands on the same slot.

Hearing a release​

slot.data is the consumer's own array (unknown[] | undefined) — rendered nodes, a cached view model — and the core never touches it. Claim a cell of it with db.claimSlotDataCell(), so two consumers on one database never share one. To tear that cache down when the engine lets the slot go, add a release listener:

const releasedNodes: unknown[] = [];
const listenedDb = new OIMDB();
const removeReleaseListener = listenedDb.addSlotReleaseListener({ onSlotReleased: releasedSlot => { releasedNodes.push(releasedSlot.data); } });
const listenedCards = cardService.createStoreSlot(listenedDb);
cardService.writeSlotContentByKey(listenedCards, 'c1', { id: 'c1', title: 'Ace' });
const listenedCard = cardService.holdSlotByKey(listenedCards, 'c1');
listenedCard.data = ['rendered ace'];
listenedCard.clearSlotContent();
listenedCard.unholdSlot();
listenedDb.flush();
// releasedNodes: [['rendered ace']]

onSlotReleased(slot) is called once for every slot and every column slot the engine releases, of every collection on that database, after the slot is marked released and with slot.data still on it. It is told, not asked: it cannot keep the slot. removeReleaseListener() stops it; with no listener a release costs one length check.

Releasing an identity on a clock — opt-in, and off it costs nothing​

A slot is memory: the identity, its value, and whatever it files. A screen that only ever shows what it holds can let the rest go, and a cache of server responses can let data go once it is stale. Both are a slot release policy, handed in at construction. A policy decides whether and when a slot goes. It does no work itself, and the slot still goes only when nothing holds it and nothing refers to it.

There is no release(slot) door: a slot you could release by hand could be released under a subscriber somebody else took. The policy is asked at the moments a slot could go (a write, the last subscriber leaving, the last hold given back), and a hold always outranks its answer.

PolicyA slot goesTake it for
OIMSlotAtEmptyReleasePolicy.INSTANCEonce it has no value and nothing holds it; a slot with a value stays. A computed, never empty, stays while its store slot livesthe default for entity, bucket and index collections
OIMSlotNeverReleasePolicy.INSTANCEnever, empty or not; a deleted key's slot stays fileda small, fixed key space whose identities you want stable
OIMSlotAtUnholdReleasePolicy.INSTANCEthe moment nothing holds it, even with a value — at its last unhold, and right after a write into a slot nobody holdskeeping only what something is subscribed to or holds; the default for every computed, single or collection
OIMSlotAfterWriteReleasePolicy({ keepAfterWriteMs })once its last write is older than the windowdata that goes stale on a known schedule
OIMSlotAfterIdleReleasePolicy({ keepAfterIdleMs })once nothing has watched it for the windowa cache that keeps what was recently on screen
OIMSlotAfterUnholdReleasePolicy({ keepAfterUnholdMs })once the window after its last unhold has passed; a hold taken again inside it keeps the slot. A slot that was never held is never on this clocknavigating back to a screen within the window
OIMSlotEarliestReleasePolicy([...])as soon as any of several policies says socombining windows

Under OIMSlotAtUnholdReleasePolicy, a write into an entity nothing holds releases it at once: the slot comes back released (isOIMSlotReleased(slot)) and hasSlotContentByKey for its key is false. An entity filed into a held bucket is kept, because the bucket holds it.

Where the policy comes from. The slotReleasePolicy of an OIMDefaults reaches every factory it is passed to as defaults (createOIMSlotCollectionService, createOIMSingleSlotService and the index factories). Each of them takes a slotReleasePolicy of its own to override it for one collection type, and so for every store slot of it. If neither names one, the collection is built with OIMSlotAtEmptyReleasePolicy.INSTANCE. The computed factories ignore a defaults release policy and default to OIMSlotAtUnholdReleasePolicy.INSTANCE instead; pass one in their options to change it.


const releasingDefaults = new OIMDefaults({
slotReleasePolicy: new OIMSlotEarliestReleasePolicy([
new OIMSlotAfterWriteReleasePolicy({ keepAfterWriteMs: 60_000 }),
new OIMSlotAfterIdleReleasePolicy({ keepAfterIdleMs: 30_000 }),
]),
});

const unholdingDefaults = new OIMDefaults({
slotReleasePolicy: new OIMSlotAfterUnholdReleasePolicy({ keepAfterUnholdMs: 5_000 }),
});

The question a policy answers​

interface IOIMSlotReleasePolicy {
readonly releasesWrittenSlots: boolean;
readonly schedulesReleaseOnWrite: boolean;
onSlotWritten(slot: TOIMSlot): void;
onSlotIdle(slot: TOIMSlot): boolean;
onSlotUnheld(slot: TOIMSlot): void;
isSlotReleasable(slot: TOIMSlot): boolean;
isEmptySlotReleasable(slot: TOIMSlot): boolean;
cancelSlotRelease(slot: TOIMSlot): void;
}

Implement it to write a policy of your own. The engine calls:

MethodCalled whenWhat the answer does
onSlotWrittena write leaves the slot with a valuea write window restarts here
onSlotIdlethe slot first gets a value with no subscriber, or its last subscriber leavestrue means already due: a freshly filled slot goes to the unused-slot collector and leaves at the end of the frame; an idle one is released at once if nothing holds it
onSlotUnheldits last hold is given backan unhold window restarts here
isSlotReleasablenothing holds it, nothing refers to it, and it has a valuetrue releases it; false keeps it, and a timed policy files it into its own queue
isEmptySlotReleasablethe same, for a slot with no valueonly OIMSlotNeverReleasePolicy answers false
cancelSlotReleasethe slot is being releasedtakes it off the policy's queue

releasesWrittenSlots: whether the policy can ever release a slot that holds data. false lets writes skip the release check. schedulesReleaseOnWrite: whether a write can schedule a release. false lets writes skip onSlotWritten. Both are read once, at construction.

Controlling the clock​

Each timed policy files into its own release wheel on the db's collectorSlot (afterWriteSlotReleaseWheel, afterIdleSlotReleaseWheel or afterUnholdSlotReleaseWheel, each an OIMSlotReleaseWheel). The clock and the timer are the db's: new OIMDB({ getNowMs, releaseTimer }), getNowMs defaulting to Date.now and the timer to a setTimeout that is unrefed, so it does not keep a Node process alive. Pass both to control time:


let nowMs = 0;
const testDb = new OIMDB({
getNowMs: () => nowMs,
releaseTimer: () => () => undefined,
});
const testDefaults = new OIMDefaults({
slotReleasePolicy: new OIMSlotAfterIdleReleasePolicy({ keepAfterIdleMs: 30_000 }),
});

nowMs += 31_000;
mintOIMAfterIdleSlotReleaseWheel(testDb.collectorSlot).flush();

flush() releases every slot whose deadline has passed, up to now; cancelAllSlots() empties the wheel and disarms the timer. Deadlines are filed in slices of OIM_SLICE_LENGTH_MS (1024 ms) and the timer arms for the end of a slice, so on the timer alone a slot goes never before its deadline and at most one slice after it. Many slots on one clock cost one timer. The default timer caps a delay at 2^31 − 1 ms (about 24.8 days), so a longer window still fires.

What restarts each window​

Each timed policy keeps its own deadline on the slot. Under OIMSlotEarliestReleasePolicy a slot goes on the soonest one, and a hold outranks all of them.

PolicyWindow restarts onNot on
OIMSlotAfterWriteReleasePolicyevery write that leaves a value, updateEntity includeda subscriber arriving or leaving
OIMSlotAfterIdleReleasePolicythe first value of a slot nobody subscribes to, and the last subscriber leavinga later write, or an unhold
OIMSlotAfterUnholdReleasePolicyevery last unholda write

A refetch that lands before the sweep restarts the write window of the entities it rewrote.

Which writes move the deadline​

By default every write restarts the write window, a local edit included. When only server responses should keep data fresh, give OIMSlotAfterWriteReleasePolicy a manual frame strategy and write the responses inside its frame. Writes outside it leave the deadline where it was.


type Deck = { id: string; title: string };

const serverDb = new OIMDB();
const serverFrame = new OIMSlotReleaseManualDueFramePolicy();
const serverDeckService = createOIMSlotCollectionService({ slotContentService: createOIMEntityContentService<Deck>(), slotReleasePolicy: new OIMSlotAfterWriteReleasePolicy({ keepAfterWriteMs: 30_000, slotReleaseDueFramePolicy: serverFrame }) });
const serverCardService = createOIMSlotCollectionService({ slotContentService: createOIMEntityContentService<Card>(), slotReleasePolicy: new OIMSlotAfterWriteReleasePolicy({ keepAfterWriteMs: 60_000, slotReleaseDueFramePolicy: serverFrame }) });
const serverDecks = serverDeckService.createStoreSlot(serverDb);
const serverCards = serverCardService.createStoreSlot(serverDb);

const onDeckResponse = (response: { deck: Deck; cards: Card[] }): void => {
serverFrame.writeInSlotReleaseDueFrame(() => {
serverDeckService.writeSlotContentByKey(serverDecks, response.deck.id, response.deck);
for (const card of response.cards) serverCardService.writeSlotContentByKey(serverCards, card.id, card);
});
};

const onLocalRename = (deck: Deck, title: string): void => {
serverDeckService.writeSlotContentByKey(serverDecks, ({ ...deck, title }).id, { ...deck, title });
};

openSlotReleaseDueFrame() and closeSlotReleaseDueFrame() do the same as a pair; closing a frame that is not open throws. One frame strategy shared by several policies moves each slot by its own collection's window. The function you pass must be synchronous: the frame closes when it returns.

Invalidating​

mintOIMAfterWriteSlotReleaseWheel(db.collectorSlot).markSlotReleaseDueNow(slot) makes the slot's write deadline now. A slot nothing holds or watches goes at once, with its data. A held or watched one keeps its data and goes when its last hold or subscriber leaves, unless a write inside the release-due frame moves its deadline a window ahead first. Nothing is written, so no effect wakes.

Refetching on a clock​

A release wheel decides when a slot may go. To refresh data while somebody is looking at it, create an OIMSlotRefetchWheel on the db (it takes the db's clock, timer and error policy) with a listener and file the slots at the moment they should be refetched:


const refetchDue: TOIMSlot[] = [];
const refetchWheel = new OIMSlotRefetchWheel(db, {
slotRefetchListener: { onSlotsRefetchDue: slots => { refetchDue.push(...slots); } },
});

const onCardResponse = (cardSlot: TOIMSlot, staleTimeMs: number): void => {
refetchWheel.scheduleSlotRefetchAt(cardSlot, Date.now() + staleTimeMs);
};

The wheel keeps nothing on the slot. Every scheduleSlotRefetchAt files one entry, so moving a refetch earlier is one more call; the listener decides from its own data whether an entry it is handed is still current. A sweep takes only slices that have fully passed, skips released slots, and calls the listener once with every slot that came due, watched or not. The array it passes is reused, so copy what you keep.

An idle window opens twice, and a held slot is off the clock​

An idle window opens in exactly two places: when the slot first gets content and nobody subscribes to it, and when its last subscriber leaves. An empty slot gets no window; it goes as soon as nothing holds it. An unhold opens no idle window.

A held slot is off the clock. Two consequences follow:

  • A hold defers the verdict; it does not restart the clock. An entity whose window ran out while it was held goes at the give-back itself.

    const heldSlot = cardService.holdSlotByKey(cards, 'c1');
    // …the window passes, sweeps run, nothing happens to this slot…
    heldSlot.unholdSlot();
    isOIMSlotReleased(heldSlot); // true — the give-back settles what the sweep could not

    The last subscriber leaving is the other case: the last disposeEffect(effect) grants a full fresh idle window.

  • A cascade takes one sweep: a stale bucket that goes gives back its entities, and those whose own windows ran out go in the same sweep.

A subscriber is a hold, so a watched slot is off the clock and never loses data mid-read. No read is reported to the clock. After the last dispose, OIMSlotAfterIdleReleasePolicy grants a whole fresh window, while OIMSlotAfterWriteReleasePolicy grants only what is left of the write window, so an already-stale entity goes on that call.

A bucket runs its own window, given to its own collection. A bucket something holds keeps every entity in it whatever the entities' own age.

Where to next​