iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / itx / src / context / awake.tsmain at 949894f

// awake.ts — WHICH CONTEXTS OF THE MIND ARE AWAKE NOW. A context that has work holds one WebSocket
// into the context at `AWAKE_CONTEXT_PATH`, which accepts it with the hibernation API. So the list
// of awake contexts is that context's list of open sockets: no storage, no query, no event. A
// context that dies takes its socket with it, so nothing has to say "asleep".
//
// What it costs (Cloudflare's Durable Objects pricing, read 2026-11-13):
// - An open OUTBOUND socket keeps its Durable Object in memory, billed for duration. So a context
//   holds its socket only while it has work, plus `AWAKE_QUIET_MS`, and never longer than
//   `AWAKE_MAX_HOLD_MS` after its last entry. The socket never makes a context stay awake.
// - The accepting context hibernates under its sockets and is billed only for the turns that
//   accept one or see one close. Neither turn writes a wake record, appends an event or runs a
//   timer.
// - One Durable Object accepts 32,768 sockets. A dial refused past that is logged, and that
//   context is missing from the list: nothing else depends on the socket.
//
// The same socket carries what a context says about itself (context-summary.ts). A context that
// works sends its summary at three times:
// - `AWAKE_ACTIVITY_DEBOUNCE_MS` after its activity stack changed or it said what it is. That
//   wait gathers a burst of such changes into one summary. It is no least time between two
//   summaries;
// - at a recheck, each `AWAKE_QUIET_MS` while it is busy, when such a change is not yet said or
//   the last summary is `AWAKE_SUMMARY_EVERY_MS` old;
// - before it closes.
// A summary whose text equals the last one sent is not sent, so a wake can send none. A context
// whose activity stack changes often sends about ten summaries a second; one long activity that
// only appends sends one per `AWAKE_SUMMARY_EVERY_MS`. The accepting context keeps the durable
// part of each summary that comes in one SQLite row (context-catalog.ts `store`). It writes that
// row at each summary of an equal or later offset and does not compare the two: a summary that
// differs in its activities alone writes the same row again. These rows are beside the rows
// that the wake writes in the context's own log.
//
// THE CATALOG ANSWERS EACH SUMMARY, on the same socket: it kept it, or it refused it. A context
// that goes quiet keeps its socket until its last summary is answered, at most
// `AWAKE_ANSWER_WAIT_MS`. What stays unanswered is said again:
// - while the context works, on the next socket, at once;
// - after it went quiet, by its own alarm, on the durable ladder (`AWAKE_SAY_AGAIN_AFTER_MS`,
//   doubled to at most 30 minutes, `AWAKE_SAY_AGAIN_TRIES` times, then a warning and no more);
// - after its object died with the summary unsaid, by the alarm that every entry leaves no later
//   than `AWAKE_RECOVER_AFTER_MS` ahead, and that a quiet close with every answer takes away. The
//   object that this alarm wakes has nothing in memory of the one before it, so an alarm in an
//   object that never entered says the summary (`recover`).
// So a row of the catalog is behind its context's log for a bounded time, and a row that stays
// behind is in the log of the context that gave up. The alarm is the one durable mark of a summary
// that is owed: it costs a context that has no earlier alarm two alarm writes for each time it
// works, and nothing else is written while the catalog answers.
//
// The accepting context is not `/`: every wake of `/` restarts the root's facets, and the root
// would wake twice for each wake of any other context.

import { z } from "zod";
import type { ContextActivity } from "iterate/api";

export const AWAKE_CONTEXT_PATH = "/awake";
export const AWAKE_WEBSOCKET_HEADER = "x-itx-awake";
const AWAKE_WEBSOCKET_TAG = "awake";

/** How long a context with no work in flight still counts as awake. It is billed: 1 s of an idle
 *  128 MB object is 1.6 USD per million quiet periods. A dial is 0.15 USD per million. */
export const AWAKE_QUIET_MS = 1_000;
/** The longest a socket stays open after the context's last entry, work in flight or not. A count
 *  of work in flight that never comes back to zero is then a bounded cost. */
export const AWAKE_MAX_HOLD_MS = 5 * 60_000;
/** While a context works, its summary is sent again at most this often. */
export const AWAKE_SUMMARY_EVERY_MS = 15_000;
/** Coalesces rapid activity push/pop bursts before sending an updated summary down the socket. */
export const AWAKE_ACTIVITY_DEBOUNCE_MS = 100;
/** After a dial that failed, no other dial for this long. */
export const AWAKE_REDIAL_AFTER_MS = 10_000;
/** What the accepting context answers a summary with, on the same socket. `kept`: it is the
 *  context's row. `refused`: it is no summary, and would be refused again. Both settle it.
 *  `failed`: the catalog could not keep it this time, so it is owed, and the context says it
 *  again. Any other answer is read as `kept`, so that an answer of a later release settles too. */
export const AWAKE_SUMMARY_KEPT = "kept";
export const AWAKE_SUMMARY_REFUSED = "refused";
export const AWAKE_SUMMARY_FAILED = "failed";
/** How long a context that went quiet keeps its socket for the answer to its last summary. It is
 *  billed as the quiet window is. The accepting context wakes from hibernation for a summary,
 *  which took 0.1 to 0.6 s on a deployed mind (26 November 2026). */
export const AWAKE_ANSWER_WAIT_MS = 3_000;
/** A context that entered keeps an alarm no later than this after the entry, until the catalog
 *  has answered all it said. It is past the longest hold, so a context that closes its socket
 *  with every answer takes the alarm away before it fires. */
export const AWAKE_RECOVER_AFTER_MS = AWAKE_MAX_HOLD_MS + 60_000;
/** After a quiet close with a summary unanswered: the wait before the context says it again. It
 *  doubles at each try in a row, to at most 30 minutes. */
export const AWAKE_SAY_AGAIN_AFTER_MS = 30_000;
/** How many times in a row a context says an unanswered summary again before it gives up. */
export const AWAKE_SAY_AGAIN_TRIES = 8;

export type AwakeContext = {
  path: string;
  since: number;
  updatedAt?: number;
  activities?: ContextActivity[];
};

export type AwakeContextState = {
  since: number;
  activities?: ContextActivity[];
};

/** The accepting side. Null: not a dial. Only the context at `AWAKE_CONTEXT_PATH` accepts. */
export function acceptAwakeWebSocket(
  ctx: Pick<DurableObjectState, "acceptWebSocket">,
  ownPath: string,
  request: Request,
): Response | null {
  const header = request.headers.get(AWAKE_WEBSOCKET_HEADER);
  // oxlint-disable-next-line iterate/simple-truthiness-check -- an absent header (null) means "not this request"; a present and empty one is a malformed dial, refused below
  if (header === null) return null;
  if (ownPath !== AWAKE_CONTEXT_PATH)
    return new Response(`only ${AWAKE_CONTEXT_PATH} accepts an awake socket\n`, { status: 404 });
  let path: string;
  try {
    path = decodeURIComponent(header);
  } catch {
    path = "";
  }
  if (!path.startsWith("/"))
    return new Response(`malformed ${AWAKE_WEBSOCKET_HEADER} header\n`, { status: 400 });
  const pair = new WebSocketPair();
  try {
    ctx.acceptWebSocket(pair[1], [AWAKE_WEBSOCKET_TAG]);
  } catch (error) {
    // the limit of sockets on one Durable Object
    return new Response(`${error instanceof Error ? error.message : String(error)}\n`, {
      status: 503,
    });
  }
  pair[1].serializeAttachment({ path, since: Date.now() } satisfies AwakeContext);
  return new Response(null, { status: 101, webSocket: pair[0] });
}

export function isAwakeWebSocket(ctx: Pick<DurableObjectState, "getTags">, ws: WebSocket): boolean {
  return ctx.getTags(ws).includes(AWAKE_WEBSOCKET_TAG);
}

/** What `acceptAwakeWebSocket` attached to a socket under the awake tag. */
export function awakeContextOf(ws: WebSocket): AwakeContext {
  // the one reader of the attachment that `acceptAwakeWebSocket` and `setAwakeActivities` alone write
  return ws.deserializeAttachment() as AwakeContext;
}

/** Updates the live `activities` carried on an accepted awake socket's attachment (never SQLite),
 *  so closing or crashing the socket clears its activities automatically. */
export function setAwakeActivities(
  ws: Pick<WebSocket, "deserializeAttachment" | "serializeAttachment">,
  activities: ContextActivity[] | undefined,
): void {
  // Written by `acceptAwakeWebSocket` on the same tagged socket.
  const current = ws.deserializeAttachment() as AwakeContext;
  const next: AwakeContext = {
    path: current.path,
    since: current.since,
    updatedAt: Date.now(),
    ...(activities && activities.length > 0 && { activities }),
  };
  ws.serializeAttachment(next);
}

/** Every context with an open socket here, by path, with when it woke and its latest live
 *  activities. A context that dialed twice (its first socket's close has not arrived) is there
 *  once, with its earlier wake time and the newest socket state. `except` is a socket whose close
 *  is being handled: it counts as closed, whatever its state says. */
export function awakeContexts(
  ctx: Pick<DurableObjectState, "getWebSockets">,
  except?: WebSocket,
): Map<string, AwakeContextState> {
  const byPath = new Map<string, AwakeContextState & { updatedAt: number }>();
  for (const ws of ctx.getWebSockets(AWAKE_WEBSOCKET_TAG)) {
    if (ws === except || ws.readyState !== WebSocket.OPEN) continue;
    const { path, since, updatedAt, activities } = awakeContextOf(ws);
    const rank = updatedAt ?? since;
    const prior = byPath.get(path);
    if (!prior) {
      byPath.set(path, {
        since,
        updatedAt: rank,
        ...(activities && activities.length > 0 && { activities }),
      });
      continue;
    }
    const newer = rank >= prior.updatedAt;
    const chosenActivities = newer ? activities : prior.activities;
    byPath.set(path, {
      since: Math.min(since, prior.since),
      updatedAt: Math.max(rank, prior.updatedAt),
      ...(chosenActivities && chosenActivities.length > 0 && { activities: chosenActivities }),
    });
  }
  const states = new Map<string, AwakeContextState>();
  for (const [path, { since, activities }] of byPath) {
    states.set(path, activities ? { since, activities } : { since });
  }
  return states;
}

/** What the dialing side does when its timer fires. */
export function decideAwakeSocket(input: {
  now: number;
  lastEntryAt: number;
  busy: boolean;
}): { action: "close" } | { action: "hold"; recheckInMs: number } {
  const sinceEntry = input.now - input.lastEntryAt;
  if (sinceEntry >= AWAKE_MAX_HOLD_MS) return { action: "close" };
  if (input.busy) return { action: "hold", recheckInMs: AWAKE_QUIET_MS };
  if (sinceEntry < AWAKE_QUIET_MS)
    return { action: "hold", recheckInMs: AWAKE_QUIET_MS - sinceEntry };
  return { action: "close" };
}

type AwakeDialedSocket = Pick<WebSocket, "accept" | "close" | "addEventListener" | "send">;

const UnansweredTries = z.object({ tries: z.number().int().positive(), at: z.number() });

type AwakeSocketDeps = {
  path: string;
  /** The upgrade request to the accepting context. */
  dial: () => Promise<{ status: number; webSocket?: AwakeDialedSocket | null }>;
  /** Work in flight: while true the socket stays, up to `AWAKE_MAX_HOLD_MS` after an entry. */
  busy: () => boolean;
  /** What the context says about itself now (context-summary.ts), as text. It is sent down the
   *  socket before the socket closes, and while the context works, whenever it differs from what
   *  was sent last. */
  summary?: () => string;
  /** `recoverAt()` changed: the context's alarm is set again from it. */
  recoveryChanged?: () => void;
  /** How many times in a row the context went quiet with a summary unanswered, kept where the
   *  end of the object does not lose it. Read only when that happens again, and written then and
   *  when the catalog answers at last. Absent: counted in memory. */
  unanswered?: { count(): number; set(count: number): void };
};

/** The dialing side: one per context. `entered()` at every entry that is work; the socket and the
 *  timer are this class's own, and both end when the context is quiet. Nothing awaits a dial: a
 *  context works the same with no socket. */
export class AwakeSocket {
  readonly #deps: AwakeSocketDeps;
  #socket: AwakeDialedSocket | undefined;
  #dialing = false;
  #noDialBefore = 0;
  #lastEntryAt = 0;
  #timer: ReturnType<typeof setTimeout> | undefined;
  #activityTimer: ReturnType<typeof setTimeout> | undefined;
  #activityDirty = false;
  #sentSummary: string | undefined;
  #sentSummaryAt = 0;
  /** Summaries that this socket sent and the catalog has not answered. */
  #unanswered = 0;
  /** Runs while a quiet context keeps its socket for the answer to its last summary. */
  #answerWait: ReturnType<typeof setTimeout> | undefined;
  /** A socket ended with a summary unanswered: the next one says the summary at once. */
  #sayAgain = false;
  #recoverAt: number | undefined;
  /** This object counted an unanswered summary, or was woken to say one again: the catalog's
   *  answer then takes the count away. */
  #counted = false;
  #triesInMemory = 0;

  constructor(deps: AwakeSocketDeps) {
    this.#deps = deps;
  }

  entered(): void {
    if (this.#deps.path === AWAKE_CONTEXT_PATH) return;
    const now = Date.now();
    this.#lastEntryAt = now;
    // work came back while the socket waited for its last answer: the socket stays
    this.#stopAnswerWait();
    if (this.#recoverAt === undefined || this.#recoverAt <= now)
      this.#recoverBy(now + AWAKE_RECOVER_AFTER_MS);
    this.#open();
    if (this.#timer === undefined) this.#recheckIn(AWAKE_QUIET_MS);
  }

  /** When the context's alarm must wake it, so that it says its summary again: from an entry
   *  until the catalog has answered all that the context said. Null: nothing is owed. */
  recoverAt(): number | null {
    return this.#recoverAt ?? null;
  }

  /** The context's alarm fired with nothing else due. True when the context then enters as for
   *  work, and so says its summary again: its time to say it has come, or THIS OBJECT NEVER
   *  ENTERED. The second case is the object after one that died with its summary unsaid: nothing
   *  in its memory says so, and the alarm that woke it is all that is left of the one before. It
   *  writes no wake record: the summary is of the log as it is. */
  recover(now: number): boolean {
    if (this.#deps.path === AWAKE_CONTEXT_PATH) return false;
    const neverEntered = this.#lastEntryAt === 0;
    if (!neverEntered && (this.#recoverAt === undefined || this.#recoverAt > now)) return false;
    if (this.#timer !== undefined) {
      // The context works now: it says its summary as it goes, and its quiet close settles what
      // is owed. No entry is made here, so the longest hold still counts from its last real one.
      this.#recoverBy(now + AWAKE_RECOVER_AFTER_MS);
      return false;
    }
    this.#counted = true;
    this.entered();
    return true;
  }

  /** Coalesces rapid activity stack mutations and pushes the updated summary while the context
   *  is awake, without holding an idle context open or leaving a timer after close. The commit of
   *  what the summary says of the context for good (`events.iterate.com/itx/described`) calls it
   *  too, so a watcher of the catalog sees a new title within the debounce. */
  activityChanged(): void {
    if (this.#deps.path === AWAKE_CONTEXT_PATH || this.#timer === undefined) return;
    this.#activityDirty = true;
    if (this.#activityTimer !== undefined) return;
    this.#activityTimer = setTimeout(() => {
      this.#activityTimer = undefined;
      if (this.#timer === undefined) return;
      if (this.#socket) {
        this.#activityDirty = false;
        this.#sendSummary();
      }
    }, AWAKE_ACTIVITY_DEBOUNCE_MS);
  }

  #recoverBy(at: number | undefined): void {
    if (at === this.#recoverAt) return;
    this.#recoverAt = at;
    this.#deps.recoveryChanged?.();
  }

  #recheckIn(ms: number): void {
    this.#timer = setTimeout(() => {
      this.#timer = undefined;
      const decision = decideAwakeSocket({
        now: Date.now(),
        lastEntryAt: this.#lastEntryAt,
        busy: this.#deps.busy(),
      });
      if (decision.action === "close") return this.#close();
      // again, when the far end closed it under a context that still works
      this.#open();
      if (this.#activityDirty || Date.now() - this.#sentSummaryAt >= AWAKE_SUMMARY_EVERY_MS) {
        this.#activityDirty = false;
        this.#sendSummary();
      }
      this.#recheckIn(decision.recheckInMs);
    }, ms);
  }

  // Wanted exactly while the timer runs: a dial that lands after the context went quiet is closed.
  #open(): void {
    if (this.#socket || this.#dialing || Date.now() < this.#noDialBefore) return;
    this.#dialing = true;
    this.#deps
      .dial()
      .then((response) => {
        const socket = response.webSocket;
        if (response.status !== 101 || !socket)
          throw new Error(`the dial was answered ${response.status}`);
        socket.accept();
        this.#socket = socket;
        this.#unanswered = 0;
        const gone = () => {
          if (this.#socket !== socket) return;
          this.#socket = undefined;
          if (this.#unanswered === 0) return;
          // what this socket said may not be kept: the next socket says it at once
          this.#unanswered = 0;
          this.#sentSummary = undefined;
          this.#sayAgain = true;
          if (this.#answerWait === undefined) return;
          this.#stopAnswerWait();
          this.#wentQuietUnanswered("its socket closed before the answer");
        };
        socket.addEventListener("close", gone);
        socket.addEventListener("error", gone);
        // each message of the far end answers one summary, in the order they were sent
        socket.addEventListener("message", (event: { data?: unknown }) => {
          if (this.#socket !== socket || this.#unanswered === 0) return;
          this.#unanswered -= 1;
          if (event?.data === AWAKE_SUMMARY_FAILED) {
            // the catalog could not keep it: it is owed, and the next send says it whole
            this.#sentSummary = undefined;
            this.#sayAgain = true;
          }
          if (this.#unanswered === 0 && this.#answerWait !== undefined) this.#quietSettled();
        });
        // the context went quiet while the dial was on its way: its summary still goes
        if (this.#timer === undefined) return this.#close();
        if (this.#sayAgain || (this.#activityDirty && this.#activityTimer === undefined)) {
          this.#activityDirty = false;
          this.#sendSummary();
        }
      })
      .catch((error: unknown) => {
        this.#noDialBefore = Date.now() + AWAKE_REDIAL_AFTER_MS;
        console.info({
          event: "context.awake-dial-failed",
          path: this.#deps.path,
          message: error instanceof Error ? error.message : String(error),
        });
        // quiet already, and no socket came: nothing said the context's last summary
        if (this.#timer === undefined && this.#answerWait === undefined)
          this.#wentQuietUnanswered("its dial failed");
      })
      .finally(() => {
        this.#dialing = false;
      });
  }

  // A summary that fails to be made or sent is owed, as an unanswered one is: the log it folds
  // stays, and it is said again.
  #sendSummary(): void {
    if (!this.#socket || !this.#deps.summary) return;
    try {
      const summary = this.#deps.summary();
      if (summary === this.#sentSummary) return;
      this.#socket.send(summary);
      this.#sentSummary = summary;
      this.#sentSummaryAt = Date.now();
      this.#sayAgain = false;
      this.#unanswered += 1;
    } catch (error) {
      this.#sayAgain = true;
      console.info({
        event: "context.awake-summary-failed",
        path: this.#deps.path,
        message: error instanceof Error ? error.message : String(error),
      });
    }
  }

  // The context is quiet: its last summary goes, and the socket closes when the catalog has
  // answered it, or after `AWAKE_ANSWER_WAIT_MS`.
  #close(): void {
    if (this.#activityTimer !== undefined) {
      clearTimeout(this.#activityTimer);
      this.#activityTimer = undefined;
    }
    this.#activityDirty = false;
    // a context that says nothing of itself owes the catalog nothing
    if (!this.#deps.summary) return this.#closeAnswered();
    this.#sendSummary();
    if (!this.#socket) {
      // a dial on its way closes the socket it brings (`#open`), with the summary
      if (!this.#dialing) this.#wentQuietUnanswered("it had no socket");
      return;
    }
    if (this.#unanswered === 0) return this.#quietSettled();
    this.#answerWait = setTimeout(() => {
      this.#answerWait = undefined;
      this.#closeSocket();
      this.#wentQuietUnanswered("the catalog did not answer in time");
    }, AWAKE_ANSWER_WAIT_MS);
  }

  /** Quiet, and no answer is outstanding. Nothing is owed when the catalog kept the last summary.
   *  A summary is still owed when it could not be made or sent, or when the catalog could not
   *  keep it: an answer to an EARLIER summary settles neither. */
  #quietSettled(): void {
    if (!this.#sayAgain) return this.#closeAnswered();
    this.#stopAnswerWait();
    this.#closeSocket();
    this.#wentQuietUnanswered("its last summary could not be made or sent, or was not kept");
  }

  #stopAnswerWait(): void {
    if (this.#answerWait === undefined) return;
    clearTimeout(this.#answerWait);
    this.#answerWait = undefined;
  }

  #closeSocket(): void {
    const socket = this.#socket;
    this.#socket = undefined;
    this.#unanswered = 0;
    try {
      socket?.close(1000, "quiet");
    } catch {
      // already closing
    }
  }

  /** Quiet, and the catalog answered all that the context said: nothing is owed. */
  #closeAnswered(): void {
    this.#stopAnswerWait();
    this.#closeSocket();
    if (this.#counted) {
      this.#counted = false;
      this.#triesInMemory = 0;
      this.#deps.unanswered?.set(0);
    }
    this.#recoverBy(undefined);
  }

  /** Quiet with a summary that the catalog did not answer: the context's alarm wakes it to say
   *  the summary again, a longer wait at each try in a row, and after the last try nothing does. */
  #wentQuietUnanswered(why: string): void {
    this.#sentSummary = undefined;
    const tries = (this.#deps.unanswered?.count() ?? this.#triesInMemory) + 1;
    const gaveUp = tries > AWAKE_SAY_AGAIN_TRIES;
    this.#counted = !gaveUp;
    this.#triesInMemory = gaveUp ? 0 : tries;
    this.#deps.unanswered?.set(this.#triesInMemory);
    if (gaveUp) {
      console.warn({
        event: "context.awake-summary-gave-up",
        path: this.#deps.path,
        message: `the catalog did not answer this context's summary ${AWAKE_SAY_AGAIN_TRIES} times in a row: its row stays as it is until the context next has work`,
        why,
      });
      return this.#recoverBy(undefined);
    }
    console.info({ event: "context.awake-summary-unanswered", path: this.#deps.path, why, tries });
    this.#recoverBy(
      Date.now() + Math.min(AWAKE_SAY_AGAIN_AFTER_MS * 2 ** (tries - 1), 30 * 60_000),
    );
  }
}

/** How often in a row a context went quiet with a summary unanswered, kept in the context's own
 *  storage, where the end of its object does not lose it (`AwakeSocketDeps.unanswered`). "In a
 *  row" is by time: each try comes at most 30 minutes after the one before, so a count that is
 *  older than an hour is of an earlier row of tries, and counts for nothing. */
export function unansweredSummaryTries(
  kv: Pick<SyncKvStorage, "get" | "put" | "delete">,
): NonNullable<AwakeSocketDeps["unanswered"]> {
  return {
    count: () => {
      const kept = UnansweredTries.safeParse(kv.get("awake-summary-unanswered")).data;
      return kept && Date.now() - kept.at < 60 * 60_000 ? kept.tries : 0;
    },
    set: (tries) => {
      if (tries > 0) kv.put("awake-summary-unanswered", { tries, at: Date.now() });
      else kv.delete("awake-summary-unanswered");
    },
  };
}