← Back to Pull requests

feat(storage): add lossless compression for cold runtime history #6115

Closed
testikun closed this pull request without merging on Nov 23, 2026 03:42 UTC
View on GitHub
testikun testikun commented on Oct 15, 2026 07:59 UTC
Author

Summary

Long-lived Sessions retain large plaintext RuntimeEvent bodies even after writes stop. Compress completed text, thinking, tool calls and tool responses losslessly after seven days without an actual local content write, preserving exact JSON bytes, provider metadata, signatures, tool evidence and indexed control fields. Reads keep the stored representation compressed; continuing a Session appends ordinary records and restarts its cooling period.

  • Run bounded compression and page reclamation after Host readiness, yielding to execution, reads, writer contention and resource limits. Recheck content activity and policy before publication.

  • Convert legacy SQLite NONE databases to INCREMENTAL during controlled Host startup, using native transactional VACUUM, integrity verification, interruption recovery and failure backoff. FULL switches without a rebuild; current incremental databases skip it.

  • Show real upgrade stages and elapsed time in Desktop, with a separate upgrade readiness budget. Keep foreground pagination separate from maintenance and whole-corpus candidate searches.
  • Fixes #6109

    Verification

    Local macOS validation: root build, Desktop main/preload/renderer/Storybook typechecks, affected-file format/lint, ASF headers, protocol epoch guard and diff checks pass. Complete Storage, Host, Host assistant, Desktop and CLI regression run: 9,480 passed, 23 conditionally skipped, 0 failed. The latest Desktop wiring also passes the strict renderer architecture check, generated UI inventory check, main/renderer builds, 32 targeted tests and the real-client upgrade/quit/restart experiment. An existing two-second Host polling test timed out under the first parallel run; it passed alone and in the complete suite with bounded concurrency, without weakening its assertions or extending its deadline.

    | Experiment | Result |
    | --- | --- |
    | Complete historical SQLite copy, all source tables retained | 1,148,002,304 B after conversion → 512,114,688 B after compression/reclamation (55.39%); all 185,930 event bodies retain their exact bytes |
    | Replayed event corpus, 3,000 warm paging samples per phase | p95 21.23 ms raw → 19.11 ms compressed → 20.36 ms after reclamation |
    | Decode-cache ablation | p95 22.9 ms without cache vs 19.8 ms with a bounded immutable-string cache; identical page content |
    | SQLite auxiliary threads, one trial each | 0 / 2 / 8 threads: 8.19 / 8.30 / 8.33 seconds; no speedup observed, default remains 0 |
    | Real Electron client | Upgrade progress stays responsive; normal quit and restart preserve the full event digest and reach Host readiness |
    | Failure and packaging checks | Process death during conversion permits recovery/retry; ASAR read, codec and conversion workers preserve pages, landmarks and recall candidates |

    Source databases were read-only; benchmarks aged disposable copies explicitly. OS file caches were not purged, so first reads are not cold-disk measurements. The complete-copy run uses only 30 repeated pages for correctness; the paging p95 comparison above comes from the separate 3,000-sample replay run.

    Migration and rollout

    Runtime schema 20 → 21, operational schema 2 → 3, and Host compatibility epoch 222 → 223. Older binaries reject the newer schema/epoch; restoring payload bytes does not downgrade the whole database schema.

    Legacy NONE conversion may need approximately twice the current database file size plus 64 MiB of free space. It runs with WAL and synchronous=FULL before ordinary business writers open. Busy/low-space/failed attempts defer safely; actual corruption blocks startup. SQLite recovery protects interruption, but the implementation does not promise percentage-based resume or simulated power-loss coverage.

    Compression defaults to enabled after cooling, preserving an existing explicit disable. The issue initially suggested a disabled rollout while validation/review was pending; please review the enabled default and automatic startup conversion before merging.

    Review notes

  • Dedicated cold-history conversion and interruption experiments currently cover macOS. Windows recovery and Windows/Linux/macOS CLI package validation have passed CI; those general workflows do not replace dedicated conversion qualification on each platform.

  • Review the rollout default and startup conversion resource/wait budget.

  • Full-corpus negative searches remain a tuning target: the measured miss scan increases from roughly 2.4–3.3 seconds raw to 3.3–4.2 seconds compressed. Candidate sets are unchanged and this scan uses the maintenance worker rather than blocking the pagination queue.
  • AI use

  • No generative tool made a substantive contribution

  • Generative tooling made a substantive contribution
  • Tool(s) and scope: OpenAI Codex authored implementation, tests, benchmark scripts and this PR description at @testikun's request. The commits include Generated-by trailers.

    Checklist

  • Tests cover the change and fail without it

  • Lint, format, typecheck and the affected suites pass locally
  • Does this PR entail a change in behavior?

  • Yes — described under Summary above

  • No
  • Diff: 5228 lines (+5135 / -93) across 65 files Reviewer: Astro-Han Review duration: 55903m
    All Vouch review confidence checks passed
    Residual risk 0.17 = Change Risk (0.72) × (1 − Review Confidence (0.76)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 5228 lines diff across 65 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.56 · 5 substantive comment(s)
    0.56
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    75%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    10 items
    Astro-Han Astro-Han commented on code on Oct 15, 2026 09:16 UTC
    Code Review
    apps/desktop/src/renderer/app-shell.tsx:1
    @@ -158,7 +158,7 @@ export function AppShell() {
             <Diagnostics.DiagnosticReportToastProvider>
               <ErrorBoundary locale={uiLocale}>
                 <AppUpdateProvider>
    -              <RuntimeHostHandoffOverlay />
    +              <RuntimeHostLifecycleOverlay />

    P2: apps/desktop/src/main/__tests__/main-startup-lifetime.test.ts ("mounts the handoff overlay inside the locale providers") searches this file for <RuntimeHostHandoffOverlay. After this rename it fails, and that is the current CI test failure. Please update the assertion, including the doesNotMatch against app.tsx.

    Astro-Han Astro-Han commented on code on Oct 15, 2026 09:16 UTC
    Code Review
    packages/runtime-host/src/client/wait-for-ready.ts:1
    @@ -18,32 +18,59 @@
      */
     
     import type { RuntimeHostConnection } from './connection.js';
    +import type { HostStatusResult } from '../protocol/host-status.js';
    +
    +export const STORAGE_UPGRADE_READY_TIMEOUT_MS = 30 * 60 * 1000;

    P2: callers of waitForRuntimeHostReady get this separate upgrade budget, but verifyRuntimeHostManagedServiceReady (packages/cli/src/runtime-host-service-manager.ts) does not. It runs its own 45 s loop and treats upgrading_storage as a failure. If a managed-service update/start/configure lands on a legacy database whose conversion runs past about 45 s, the CLI retires the Host in the middle of the VACUUM. By then the schema is already v3/21, so the previous package cannot open the root either. Each retry reruns the full conversion and hits the same timeout.

    Astro-Han Astro-Han commented on code on Oct 15, 2026 09:16 UTC
    Code Review
    packages/runtime-host/src/server/execution-composition.ts:1
    @@ -323,6 +330,8 @@ export interface CreateExecutionRuntimeHostCompositionOptions {
       readonly skillHomeDirectory?: string;
       readonly projectDirectoryRoots?: readonly PublishedProjectDirectoryRoot[];
       readonly imageArchiveLimits?: import('@maka/core/image-delivery').ImageArchiveLimits;
    +  /** Reader-first rollout: absent preserves the durable policy, whose initial value is disabled. */

    P3: this comment says the initial durable value is disabled, but COLD_STORAGE_DEFAULT_WRITER_ENABLED is 1. This option is also not wired to any setting or CLI command, so users have no product-level way to opt out of compression or of the startup conversion.

    Astro-Han Astro-Han commented on code on Oct 15, 2026 09:16 UTC
    Code Review
    packages/storage/src/cold-runtime-storage.ts:1
    @@ -0,0 +1,671 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { stat, statfs } from 'node:fs/promises';
    +import { Worker } from 'node:worker_threads';
    +import {
    +  acquireOperationalStateDatabase,
    +  assertOperationalStateDatabaseClosed,
    +  resolveOperationalStateDatabasePath,
    +  type OperationalStateDatabaseLease,
    +} from './operational-state-store.js';
    +import { COLD_STORAGE_AGE_MS } from './cold-storage-schema.js';
    +import {
    +  RUNTIME_COMPRESSION_POLICY,
    +  RUNTIME_COMPRESSIBLE_KINDS,
    +  RUNTIME_PAYLOAD_MAX_BYTES,
    +  RUNTIME_PAYLOAD_PREFIX,
    +  runtimePayloadBytesSql,
    +} from './runtime-payload-codec.js';
    +import {
    +  assertStorageRootLeaseActive,
    +  assertStorageRootLease,
    +  runWithStorageRootLease,
    +  type StorageRootLease,
    +} from './root-authority.js';
    +import { createSqliteRuntimeStore } from './sqlite-runtime-store.js';
    +import type {
    +  RuntimeTranscriptQueries,
    +  RuntimeTranscriptTurnsRequest,
    +  RuntimeTranscriptTurn,
    +} from './runtime-transcript-query.js';
    +
    +const BATCH_BYTES = 1024 * 1024;
    +const MAX_RECLAIM_PAGES = 64;
    +
    +export type RuntimeAutoVacuumMode = 0 | 1 | 2;
    +
    +export interface RuntimePageReclaimResult {
    +  reclaimedPages: number;
    +  hasMore: boolean;
    +  busy: boolean;
    +  autoVacuumMode?: RuntimeAutoVacuumMode;
    +  pauseReason?: 'inactive' | 'conversion_required' | 'low_space' | 'wal_limit';
    +}
    +
    +/** Read-only worker adapter; the composing Host retains its root owner until the worker exits. */
    +export function openColdRuntimeTranscriptStore(databasePath: string): RuntimeTranscriptQueries & {
    +  close(): void;
    +  projectTranscriptTurns<T>(
    +    sessionId: string,
    +    request: RuntimeTranscriptTurnsRequest,
    +    project: (turn: RuntimeTranscriptTurn) => T,
    +  ): Promise<T[]>;
    +  listSessionsWithRuntimeEventText(
    +    sessionIds: readonly string[],
    +    terms: readonly string[],
    +  ): Promise<string[]>;
    +} {
    +  return createSqliteRuntimeStore(databasePath, { readOnly: true });
    +}
    +
    +export type RuntimeStorageCodec = (
    +  mode: 'encode' | 'decode',
    +  values: readonly string[],
    +) => Promise<readonly { json: string | null; error?: string }[]>;
    +
    +interface Candidate {
    +  event_id: string;
    +  session_id: string;
    +  bytes: number;
    +  last_content_write_at: number;
    +  activity_version: number;
    +  payload_json: string;
    +  checked_policy?: string | null;
    +}
    +
    +export interface ColdStorageBatchResult {
    +  scanned: number;
    +  changed: number;
    +  rawBytes: number;
    +  storedBytes: number;
    +  inputBytes: number;
    +  skipped: number;
    +  failures: number;
    +  busy: boolean;
    +  hasMore: boolean;
    +  pauseReason?: 'inactive' | 'writer_disabled' | 'low_space' | 'wal_limit';
    +}
    +
    +export interface ColdRuntimeStorageInput {
    +  lease: StorageRootLease<'interactive', 'write'>;
    +  codec: RuntimeStorageCodec;
    +  canRun: () => boolean;
    +  isProtected: (sessionId: string) => boolean;
    +  now?: () => number;
    +  minimumFreeBytes?: number;
    +  maximumWalBytes?: number;
    +}
    +
    +/** One lane of optional physical work; the caller retains root ownership and supplies its worker. */
    +export class ColdRuntimeStorage {
    +  readonly #lease: OperationalStateDatabaseLease;
    +  #closed = false;
    +  #draining = false;
    +  #running = false;
    +  #cursor: [number, string, string] = [-1, '', ''];
    +  #mode: 'encode' | 'decode' = 'encode';
    +
    +  static open(input: ColdRuntimeStorageInput): Promise<ColdRuntimeStorage> {
    +    return runWithStorageRootLease(
    +      input.lease,
    +      'interactive',
    +      'write',
    +      async () => new ColdRuntimeStorage(input),
    +    );
    +  }
    +
    +  private constructor(private readonly input: ColdRuntimeStorageInput) {
    +    assertStorageRootLeaseActive(input.lease, 'interactive', 'write');
    +    this.#lease = acquireOperationalStateDatabase(input.lease.canonicalPath);
    +  }
    +
    +  async setEnabled(enabled: boolean): Promise<void> {
    +    await runWithStorageRootLease(this.input.lease, 'interactive', 'write', async () => {
    +      if (this.#closed) throw new Error('Cold storage is closed');
    +      this.#lease.transaction('write', () =>
    +        this.#lease.database
    +          .prepare(`
    +        UPDATE runtime_storage_policy SET writer_enabled = ?, epoch = epoch + 1 WHERE singleton = 1
    +      `)
    +          .run(enabled ? 1 : 0),
    +      );
    +      this.#cursor = [-1, '', ''];
    +    });
    +  }
    +
    +  beginDrain(): void {
    +    this.#draining = true;
    +  }
    +
    +  close(): void {
    +    this.beginDrain();
    +    this.#closed = true;
    +    this.#lease.close();
    +  }
    +
    +  async compressBatch(
    +    options: { maxItems?: number; maxBytes?: number } = {},
    +  ): Promise<ColdStorageBatchResult> {
    +    return runWithStorageRootLease(this.input.lease, 'interactive', 'write', () =>
    +      this.#batch('encode', options),
    +    );
    +  }
    +
    +  /** Recovery is explicit maintenance, never a side effect of reading. It first stops this writer. */
    +  async restoreBatch(
    +    options: { maxItems?: number; maxBytes?: number } = {},
    +  ): Promise<ColdStorageBatchResult> {
    +    return runWithStorageRootLease(this.input.lease, 'interactive', 'write', async () => {
    +      if (this.#policy().writer_enabled === 1) await this.setEnabled(false);
    +      return this.#batch('decode', options);
    +    });
    +  }
    +
    +  /** Reclaims only already-free pages. Cooling applies to content compression, not these pages. */
    +  async reclaimFreePages(input: { readonly maxPages: number }): Promise<RuntimePageReclaimResult> {
    +    if (!Number.isSafeInteger(input.maxPages) || input.maxPages < 1)
    +      throw new Error('Invalid runtime page reclamation limit');
    +    const maxPages = Math.min(input.maxPages, MAX_RECLAIM_PAGES);
    +    return runWithStorageRootLease(this.input.lease, 'interactive', 'write', async () => {
    +      const result: RuntimePageReclaimResult = {
    +        reclaimedPages: 0,
    +        hasMore: false,
    +        busy: false,
    +      };
    +      if (!this.#allowed()) return { ...result, pauseReason: 'inactive' };
    +      if (this.#running) return { ...result, busy: true };
    +      const db = this.#lease.database;
    +      result.autoVacuumMode = readAutoVacuumMode(db);
    +      if (result.autoVacuumMode === 0) return { ...result, pauseReason: 'conversion_required' };
    +      if (result.autoVacuumMode !== 2 || readFreePages(db) === 0) return result;
    +      this.#running = true;
    +      try {
    +        const space = await statfs(this.input.lease.canonicalPath);
    +        const wal = await stat(`${this.#lease.databasePath}-wal`).catch(
    +          (error: NodeJS.ErrnoException) => {
    +            if (error.code === 'ENOENT') return null;
    +            throw error;
    +          },
    +        );
    +        if (space.bavail * space.bsize < (this.input.minimumFreeBytes ?? 64 * 1024 * 1024))
    +          return { ...result, pauseReason: 'low_space' };
    +        if ((wal?.size ?? 0) > (this.input.maximumWalBytes ?? 64 * 1024 * 1024))
    +          return { ...result, pauseReason: 'wal_limit' };
    +        if (!this.#allowed()) return { ...result, pauseReason: 'inactive' };
    +        const reclaimed = this.#lease.tryMaintenanceWrite(() => {
    +          if (!this.#allowed() || readAutoVacuumMode(db) !== 2) return result;
    +          const before = readFreePages(db);
    +          // Never pass zero: SQLite interprets it as reclaiming the entire freelist.
    +          if (before === 0) return result;
    +          db.exec(`PRAGMA incremental_vacuum(${Math.min(maxPages, before)})`);
    +          const after = readFreePages(db);
    +          return {
    +            ...result,
    +            reclaimedPages: before - after,
    +            hasMore: after > 0 && after < before,
    +          };
    +        });
    +        if (reclaimed === null) return { ...result, busy: true };
    +        // PASSIVE does not wait on readers. Actual DB/WAL files are measured separately.
    +        if (reclaimed.value.reclaimedPages > 0) db.exec('PRAGMA wal_checkpoint(PASSIVE)');
    +        return reclaimed.value;
    +      } finally {
    +        this.#running = false;
    +      }
    +    });
    +  }
    +
    +  async inspect(): Promise<{
    +    encodedRecords: number;
    +    logicalBytes: number;
    +    physicalPayloadBytes: number;
    +    pageBytes: number;
    +    freePageBytes: number;
    +    databaseBytes: number;
    +    walBytes: number;
    +    allocatedDatabaseBytes: number;
    +    allocatedWalBytes: number;
    +    writerEnabled: boolean;
    +    autoVacuumMode: RuntimeAutoVacuumMode;
    +  }> {
    +    await assertStorageRootLease(this.input.lease, 'interactive', 'write');
    +    const db = this.#lease.database;
    +    const records = db
    +      .prepare(`SELECT count(*) AS records,
    +      coalesce(sum(${runtimePayloadBytesSql('payload_json')}), 0) AS raw_bytes,
    +      coalesce(sum(length(CAST(payload_json AS BLOB))), 0) AS stored_bytes
    +      FROM runtime_events WHERE substr(payload_json, 1, ?) = ?
    +    `)
    +      .get(RUNTIME_PAYLOAD_PREFIX.length, RUNTIME_PAYLOAD_PREFIX) as {
    +      records: number;
    +      raw_bytes: number;
    +      stored_bytes: number;
    +    };
    +    const pageSize = (db.prepare('PRAGMA page_size').get() as { page_size: number }).page_size;
    +    const pageCount = (db.prepare('PRAGMA page_count').get() as { page_count: number }).page_count;
    +    const free = (db.prepare('PRAGMA freelist_count').get() as { freelist_count: number })
    +      .freelist_count;
    +    const database = await stat(this.#lease.databasePath);
    +    const wal = await stat(`${this.#lease.databasePath}-wal`).catch(
    +      (error: NodeJS.ErrnoException) => {
    +        if (error.code === 'ENOENT') return null;
    +        throw error;
    +      },
    +    );
    +    return {
    +      encodedRecords: records.records,
    +      logicalBytes: records.raw_bytes,
    +      physicalPayloadBytes: records.stored_bytes,
    +      pageBytes: pageSize * pageCount,
    +      freePageBytes: pageSize * free,
    +      databaseBytes: database.size,
    +      walBytes: wal?.size ?? 0,
    +      allocatedDatabaseBytes: database.blocks * 512,
    +      allocatedWalBytes: (wal?.blocks ?? 0) * 512,
    +      writerEnabled: this.#policy().writer_enabled === 1,
    +      autoVacuumMode: readAutoVacuumMode(db),
    +    };
    +  }
    +
    +  #policy(): { writer_enabled: number; epoch: number } {
    +    return this.#lease.database
    +      .prepare('SELECT writer_enabled, epoch FROM runtime_storage_policy WHERE singleton = 1')
    +      .get() as { writer_enabled: number; epoch: number };
    +  }
    +
    +  #allowed(): boolean {
    +    return !this.#closed && !this.#draining && this.input.canRun();
    +  }
    +
    +  async #batch(
    +    mode: 'encode' | 'decode',
    +    options: { maxItems?: number; maxBytes?: number },
    +  ): Promise<ColdStorageBatchResult> {
    +    const result: ColdStorageBatchResult = {
    +      scanned: 0,
    +      changed: 0,
    +      rawBytes: 0,
    +      storedBytes: 0,
    +      inputBytes: 0,
    +      skipped: 0,
    +      failures: 0,
    +      busy: false,
    +      hasMore: false,
    +    };
    +    if (this.#running) return { ...result, busy: true, hasMore: true };
    +    if (!this.#allowed()) return { ...result, pauseReason: 'inactive' };
    +    if (this.#mode !== mode) {
    +      this.#mode = mode;
    +      this.#cursor = [-1, '', ''];
    +    }
    +    const maxItems = Math.min(16, options.maxItems ?? 16);
    +    const maxBytes = Math.min(RUNTIME_PAYLOAD_MAX_BYTES, options.maxBytes ?? BATCH_BYTES);
    +    if (
    +      !Number.isSafeInteger(maxItems) ||
    +      maxItems < 1 ||
    +      !Number.isSafeInteger(maxBytes) ||
    +      maxBytes < 1
    +    )
    +      throw new Error('Invalid cold storage batch budget');
    +    const policy = this.#policy();
    +    if (mode === 'encode' && policy.writer_enabled !== 1)
    +      return { ...result, pauseReason: 'writer_disabled' };
    +    const cursorBefore = [...this.#cursor] as [number, string, string];
    +    this.#running = true;
    +    try {
    +      const space = await statfs(this.input.lease.canonicalPath);
    +      const wal = await stat(`${this.#lease.databasePath}-wal`).catch(
    +        (error: NodeJS.ErrnoException) => {
    +          if (error.code === 'ENOENT') return null;
    +          throw error;
    +        },
    +      );
    +      if (space.bavail * space.bsize < (this.input.minimumFreeBytes ?? 64 * 1024 * 1024))
    +        return { ...result, pauseReason: 'low_space' };
    +      if ((wal?.size ?? 0) > (this.input.maximumWalBytes ?? 64 * 1024 * 1024))
    +        return { ...result, pauseReason: 'wal_limit' };
    +      if (!this.#allowed()) return { ...result, pauseReason: 'inactive' };
    +      const now = this.input.now ?? Date.now;
    +      const candidates = this.#lease.transaction('read', () => {
    +        const prefix = `substr(e.payload_json, 1, ${RUNTIME_PAYLOAD_PREFIX.length})`;
    +        const clause =
    +          mode === 'encode'
    +            ? `e.event_kind IN (${RUNTIME_COMPRESSIBLE_KINDS.map((kind) => `'${kind}'`).join(', ')})
    +             AND ${prefix} <> '${RUNTIME_PAYLOAD_PREFIX}'
    +             AND length(CAST(e.payload_json AS BLOB)) BETWEEN 1024 AND ${RUNTIME_PAYLOAD_MAX_BYTES}`
    +            : `${prefix} = '${RUNTIME_PAYLOAD_PREFIX}'`;
    +        const index = mode === 'encode' ? 'runtime_cold_candidates' : 'runtime_encoded_candidates';
    +        const pastSession = this.#cursor[2] === '\uffff';
    +        const parameters =
    +          mode === 'encode'
    +            ? [now() - COLD_STORAGE_AGE_MS, this.#cursor[0], this.#cursor[1]]
    +            : [this.#cursor[0], this.#cursor[1]];
    +        // Seek the age index, then one Session's event index. A global join/order
    +        // would repeatedly inspect/sort the large payload corpus for each tiny batch.
    +        const session = this.#lease.database
    +          .prepare(`SELECT a.* FROM session_content_activity a
    +          WHERE ${mode === 'encode' ? 'a.last_content_write_at <= ? AND' : ''}
    +            (a.last_content_write_at, a.session_id) ${pastSession ? '>' : '>='} (?, ?)
    +            AND EXISTS (SELECT 1 FROM runtime_events e INDEXED BY ${index}
    +              WHERE e.session_id = a.session_id AND ${clause})
    +          ORDER BY a.last_content_write_at, a.session_id LIMIT 1
    +        `)
    +          .get(...parameters) as
    +          | Pick<Candidate, 'session_id' | 'last_content_write_at' | 'activity_version'>
    +          | undefined;
    +        if (!session) {
    +          this.#cursor = [-1, '', ''];
    +          return [];
    +        }
    +        const sameSession =
    +          session.session_id === this.#cursor[1] &&
    +          session.last_content_write_at === this.#cursor[0];
    +        if (this.input.isProtected(session.session_id)) {
    +          this.#cursor = [session.last_content_write_at, session.session_id, '\uffff'];
    +          result.skipped += 1;
    +          result.hasMore = true;
    +          return [];
    +        }
    +        const rows = this.#lease.database
    +          .prepare(`SELECT e.event_id, e.session_id,
    +          ${runtimePayloadBytesSql('e.payload_json')} AS bytes,
    +          c.policy AS checked_policy
    +          FROM runtime_events e INDEXED BY ${index}
    +          LEFT JOIN runtime_compression_checks c ON c.event_id = e.event_id
    +          WHERE e.session_id = ? AND e.event_id > ? AND ${clause}
    +          ORDER BY e.event_id LIMIT 64
    +        `)
    +          .iterate(session.session_id, sameSession ? this.#cursor[2] : '');
    +        const selected: Candidate[] = [];
    +        let bytes = 0;
    +        let visited = 0;
    +        result.hasMore = true;
    +        for (const stored of rows) {
    +          const row = {
    +            ...stored,
    +            ...session,
    +            event_id: String(stored.event_id),
    +            bytes: Number(stored.bytes),
    +          } as Omit<Candidate, 'payload_json'>;
    +          // One large record may exceed the soft batch budget. The scheduler charges
    +          // its actual bytes; the format/read limit remains the independent hard cap.
    +          if (selected.length === maxItems || (selected.length > 0 && bytes + row.bytes > maxBytes))
    +            break;
    +          result.scanned += 1;
    +          visited += 1;
    +          this.#cursor = [row.last_content_write_at, row.session_id, row.event_id];
    +          if (
    +            this.input.isProtected(row.session_id) ||
    +            (mode === 'encode' && row.checked_policy === RUNTIME_COMPRESSION_POLICY)

    P3: rows skipped here because they are already checked_policy stay in the runtime_cold_candidates partial index. The session-level EXISTS keeps finding them, so every pass after the 60 s idle rescans all of them at one 64-row batch per second. Records that fail to encode are not recorded anywhere, so they are retried, and reported via onError, on every pass.

    Astro-Han Astro-Han commented on code on Oct 15, 2026 09:16 UTC
    Code Review
    packages/runtime-host/src/server/transcript-storage-worker-client.ts:1
    @@ -0,0 +1,255 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +
    +import { Worker } from 'node:worker_threads';
    +import type { RuntimeTranscriptRun } from '@maka/storage/execution-stores';
    +import type { RuntimeStorageCodec } from '@maka/storage/cold-runtime-storage';
    +import { RUNTIME_PAYLOAD_MAX_BYTES } from '@maka/storage/cold-runtime-storage';
    +import type { CanonicalPermissionOutcomeRecord } from '@maka/runtime/interaction-authority';
    +import type { createTranscriptProjection } from './session-transcript-reader.js';
    +import type { SessionTurnLandmark } from '../protocol/session-turns.js';
    +import { SESSION_TURN_LANDMARK_MAX_ITEMS } from '../protocol/session-turns.js';
    +
    +export interface ProjectedTranscriptRun {
    +  run: RuntimeTranscriptRun;
    +  ordinals: [string, number][];
    +  projected: ReturnType<ReturnType<typeof createTranscriptProjection>['finishWithOutcomes']>;
    +}
    +
    +export type TranscriptStorageJob = { id: number; cancel: Int32Array } & (
    +  | {
    +      kind: 'run';
    +      sessionId: string;
    +      request: { direction: 'older' | 'newer'; throughOrdinal: number; position: number };
    +    }
    +  | { kind: 'codec'; mode: 'encode' | 'decode'; values: readonly string[] }
    +  | { kind: 'recall'; sessionIds: readonly string[]; terms: readonly string[] }
    +  | {
    +      kind: 'landmarks';
    +      sessionId: string;
    +      request: { throughOrdinal: number; maxLandmarks: number; turnId: string | null };
    +    }
    +);
    +type Pending = {
    +  job: TranscriptStorageJob;
    +  resolve(value: unknown): void;
    +  reject(error: Error): void;
    +};
    +
    +/** One bounded worker queue: foreground scans precede queued physical maintenance. */
    +export class TranscriptStorageWorker {
    +  #worker?: Worker;
    +  #active?: Pending;
    +  #queue: Pending[] = [];
    +  #nextId = 0;
    +  #closed = false;
    +  #failure?: Error;
    +  #closeTask?: Promise<void>;
    +  readonly #pins = new Map<string, number>();
    +
    +  constructor(
    +    private readonly input: {
    +      databasePath: string;
    +      permissions: (
    +        ids: readonly string[],
    +      ) => Promise<ReadonlyMap<string, CanonicalPermissionOutcomeRecord>>;
    +    },
    +  ) {}
    +
    +  get reading(): boolean {
    +    return this.#pins.size > 0;
    +  }
    +  isProtected(sessionId: string): boolean {
    +    return this.#pins.has(sessionId);
    +  }
    +
    +  /** Protect the complete frontend read, including Host-side authority I/O between scan jobs. */
    +  async withSessionRead<T>(sessionId: string, operation: () => Promise<T>): Promise<T> {
    +    if (this.#closed || this.#failure) throw this.#failure ?? new Error('Storage worker is closed');
    +    this.#pins.set(sessionId, (this.#pins.get(sessionId) ?? 0) + 1);
    +    try {
    +      return await operation();
    +    } finally {
    +      this.#releasePin(sessionId);
    +    }
    +  }
    +
    +  readRun(
    +    sessionId: string,
    +    request: Extract<TranscriptStorageJob, { kind: 'run' }>['request'],
    +  ): Promise<ProjectedTranscriptRun | undefined> {
    +    return this.#enqueue({ kind: 'run', sessionId, request });
    +  }
    +
    +  readonly codec: RuntimeStorageCodec = (mode, values) =>
    +    this.#enqueue({ kind: 'codec', mode, values });
    +
    +  readLandmarks(
    +    sessionId: string,
    +    request: Extract<TranscriptStorageJob, { kind: 'landmarks' }>['request'],
    +  ): Promise<SessionTurnLandmark[]> {
    +    return this.#enqueue({ kind: 'landmarks', sessionId, request });
    +  }
    +
    +  readRecallCandidates(sessionIds: readonly string[], terms: readonly string[]): Promise<string[]> {
    +    return this.#enqueue({ kind: 'recall', sessionIds, terms });
    +  }
    +
    +  beginDrain(): void {
    +    this.#closed = true;
    +    if (this.#active) Atomics.store(this.#active.job.cancel, 0, 1);
    +    for (const pending of this.#queue.splice(0))
    +      this.#reject(pending, new Error('Storage worker is closing'));
    +  }
    +
    +  close(): Promise<void> {
    +    this.beginDrain();
    +    return (this.#closeTask ??= (async () => {
    +      if (this.#active) {
    +        this.#reject(this.#active, new Error('Storage worker is closing'));
    +        this.#active = undefined;
    +      }
    +      await this.#worker?.terminate();
    +    })());
    +  }
    +
    +  #enqueue<T>(
    +    job:
    +      | Omit<Extract<TranscriptStorageJob, { kind: 'run' }>, 'id' | 'cancel'>
    +      | Omit<Extract<TranscriptStorageJob, { kind: 'codec' }>, 'id' | 'cancel'>
    +      | Omit<Extract<TranscriptStorageJob, { kind: 'recall' }>, 'id' | 'cancel'>
    +      | Omit<Extract<TranscriptStorageJob, { kind: 'landmarks' }>, 'id' | 'cancel'>,
    +  ): Promise<T> {
    +    if (this.#closed || this.#failure)
    +      return Promise.reject(this.#failure ?? new Error('Storage worker is closed'));
    +    if (this.#queue.length >= 32) return Promise.reject(new Error('Storage worker queue is full'));
    +    if (
    +      job.kind === 'codec' &&
    +      (job.values.length > 16 ||
    +        job.values.reduce((sum, value) => sum + Buffer.byteLength(value), 0) >
    +          RUNTIME_PAYLOAD_MAX_BYTES)
    +    )
    +      return Promise.reject(new Error('Storage codec batch exceeds its byte or record budget'));
    +    if (
    +      job.kind === 'landmarks' &&
    +      (!Number.isSafeInteger(job.request.maxLandmarks) ||
    +        job.request.maxLandmarks < 1 ||
    +        job.request.maxLandmarks > SESSION_TURN_LANDMARK_MAX_ITEMS)
    +    )
    +      return Promise.reject(new Error('Storage landmark query exceeds its record budget'));
    +    const sessions =
    +      job.kind === 'codec' ? [] : job.kind === 'recall' ? job.sessionIds : [job.sessionId];
    +    for (const sessionId of sessions)
    +      this.#pins.set(sessionId, (this.#pins.get(sessionId) ?? 0) + 1);
    +    return new Promise<T>((resolve, reject) => {
    +      this.#queue.push({
    +        job: { ...job, id: ++this.#nextId, cancel: new Int32Array(new SharedArrayBuffer(4)) },
    +        resolve: (value) => resolve(value as T),
    +        reject,
    +      });
    +      this.#pump();
    +    });
    +  }
    +
    +  #pump(): void {
    +    if (this.#closed || this.#failure || this.#active || this.#queue.length === 0) return;
    +    if (!this.#worker) {
    +      this.#worker = new Worker(new URL('./transcript-storage-worker.js', import.meta.url), {
    +        workerData: { databasePath: this.input.databasePath },
    +      });
    +      this.#worker.on('error', (error: unknown) =>
    +        this.#fail(error instanceof Error ? error : new Error('Storage worker failed')),
    +      );
    +      this.#worker.on('exit', (code) => {
    +        if (!this.#closed) this.#fail(new Error(`Storage worker exited (${code})`));
    +      });
    +      this.#worker.on(
    +        'message',
    +        (message: {
    +          id: number;
    +          kind: string;
    +          ids?: string[];
    +          value?: unknown;
    +          error?: { name: string; message: string };
    +        }) => {
    +          const active = this.#active;
    +          if (!active || message.id !== active.job.id || this.#closed) return;
    +          if (message.kind === 'permissions') {
    +            void this.input.permissions(message.ids ?? []).then(
    +              (outcomes) => {
    +                if (this.#active === active && !this.#closed)
    +                  this.#worker!.postMessage({ kind: 'permissions', id: message.id, outcomes });
    +              },
    +              (error: unknown) => {
    +                if (this.#active === active && !this.#closed)
    +                  this.#worker!.postMessage({
    +                    kind: 'permissions-error',
    +                    id: message.id,
    +                    error:
    +                      error instanceof Error ? error.message : 'Permission outcome read failed',
    +                  });
    +              },
    +            );
    +            return;
    +          }
    +          this.#active = undefined;
    +          this.#unpin(active);
    +          if (message.error)
    +            active.reject(
    +              Object.assign(new Error(message.error.message), { name: message.error.name }),
    +            );
    +          else active.resolve(message.value);
    +          this.#worker!.unref();
    +          this.#pump();
    +        },
    +      );
    +    }
    +    const priority = this.#queue.findIndex(({ job }) => job.kind !== 'codec');
    +    this.#active = this.#queue.splice(priority < 0 ? 0 : priority, 1)[0]!;
    +    this.#worker.ref();
    +    this.#worker.postMessage(this.#active.job);
    +  }
    +
    +  #unpin(pending: Pending): void {
    +    if (pending.job.kind === 'codec') return;
    +    const sessions =
    +      pending.job.kind === 'recall' ? pending.job.sessionIds : [pending.job.sessionId];
    +    for (const sessionId of sessions) this.#releasePin(sessionId);
    +  }
    +
    +  #releasePin(id: string): void {
    +    const count = this.#pins.get(id)! - 1;
    +    if (count === 0) this.#pins.delete(id);
    +    else this.#pins.set(id, count);
    +  }
    +
    +  #reject(pending: Pending, error: Error): void {
    +    this.#unpin(pending);
    +    pending.reject(error);
    +  }
    +
    +  #fail(error: Error): void {

    P3: #failure is never cleared. One worker exit, such as an OOM, makes every later transcript page read throw until the Host restarts, because withSessionRead and #enqueue reject immediately and there is no in-process fallback. Consider respawning the worker or falling back to the in-process reader.

    Astro-Han Astro-Han commented on Oct 15, 2026 09:16 UTC
    Reviewer

    Automated review notice: This comment was posted by an automated review agent. It is not an independent human review and does not replace one.

    First full review of 1751c399..0c34ac45 (3 commits; the merge base is the current tip of main). I found no prior review findings to carry forward. The diff is about 2,400 lines of product code, 1,780 lines of tests and 950 lines of scripts/perf harness across 65 files.

    Summary. The codec looks lossless as written. Each record keeps its original UTF-8 JSON text inside a zstd frame. That frame is verified on read with a length check, a sha256 and a projection check, and encode refuses to publish unless the round trip reproduces the exact input string. I ran the codec in isolation against BOMs, emoji, U+2028, escaped lone surrogates, pretty-printed and reordered keys, __proto__, duplicate keys, oversized integers and \/ escapes, and every one restored byte for byte. Values that JSON cannot round-trip (-0, 1e400) fail closed and keep their raw bytes. Publication is a compare-and-swap UPDATE ... WHERE payload_json = ? inside a write transaction. That transaction rechecks the activity version, the cooling age and the policy epoch, so a crash or a concurrent append cannot leave a half-written or stale row. Readers on WAL snapshots decode either representation to the same bytes. I found no remaining SQL json_extract on fields that compression removes; every control field that SQL reads stays in the projection. Two P2 findings block merge. A larger P3 point is that the rollout runs ahead of decisions maintainers have not made yet.

    P2: CI test fails because of this PR. apps/desktop main-startup-lifetime.test.ts ("mounts the handoff overlay inside the locale providers") searches app-shell.tsx for <RuntimeHostHandoffOverlay. This PR renames that element to <RuntimeHostLifecycleOverlay. CI on main at the merge base (1751c399) is green. Update the source-text assertion, including its doesNotMatch against app.tsx. The package job was still pending when I checked.

    P2: CLI-managed Host services cannot get through a long storage conversion. waitForRuntimeHostReady gains a separate 30-minute budget for upgrading_storage. verifyRuntimeHostManagedServiceReady (packages/cli/src/runtime-host-service-manager.ts, around line 1301) has its own 45 s loop and counts any state other than ready as a failure. maka host update, start and configure use that check. If NONE→INCREMENTAL VACUUM plus integrity_check takes longer than about 45 s, the CLI retires the replacement Host, which aborts the conversion. #6000 measured roughly 55 s for a production-shaped 1 GB database and 64 s for 3 GiB on Windows. The schema has already moved to v3/21 by that point, so an older package cannot open the root either. The marker stays running, not failed, so each later CLI start reruns the full VACUUM and hits the same timeout. I traced this from the code and did not reproduce it. A fix could treat upgrading_storage as progress in that loop and give it the upgrade budget.

    P3: the rollout runs ahead of maintainer decisions.

  • #6000 is still open. A maintainer asked for "no implementation until the placement is decided", and #5825 agreed that the full VACUUM runs only on explicit user request, persists that request and checks free disk first. This PR converts every legacy NONE database automatically at startup and requires about 2x the database size free.

  • #6109 asked for the compression writer to stay disabled at first. COLD_STORAGE_DEFAULT_WRITER_ENABLED = 1 turns it on. The PR body raises this question; the comment at execution-composition.ts:333 still says the initial value is disabled.

  • coldStorageWriterEnabled is not wired to any setting, env var or CLI command. The only off switch is a repo-checkout script, so users cannot opt out of compression or of the startup conversion.
  • P3: scope. Splitting this along its independent axes would make each part reviewable and keep a regression in one from reverting the others:
    1. Reader-only codec support, with the writer off.
    2. The compression lane.
    3. Startup NONE→INCREMENTAL conversion plus the Desktop upgrade UI and the epoch bump. This part needs the #6000 decision.
    4. Moving foreground transcript reads into a worker thread with its own read-only connection. This is a separate architectural change, and #6000 already flagged a second connection as a departure from the single-owner model.

    P3: overlap with open #6083. Both PRs add a maintenance lane named runtime page reclamation that runs incremental_vacuum on runtime.sqlite. storage-maintenance.ts and execution-composition.ts merge with no textual conflict, so merging both would run two such lanes; only the test file conflicts. Agree with #6083 on which one owns this before either lands. The conversion itself fits #6044: new databases are already INCREMENTAL, and FULL databases switch without a rebuild.

    P3: robustness and cost.

  • The checked_policy rows ("not worth compressing") stay in the runtime_cold_candidates partial index. Every pass after the 60 s idle rescans them in batches of 64 at one batch per second, so the lane rarely settles while such rows exist. Records that fail encoding are not recorded at all, so they are retried, and reported through onError, on every pass.

  • TranscriptStorageWorker.#fail is permanent. A single worker exit, such as an OOM, makes every later transcript page read fail until the Host restarts, and there is no in-process fallback. A queue of more than 32 reads is rejected outright.

  • A failing post-conversion integrity_check, or SQLITE_CORRUPT during VACUUM, now blocks Host startup with no repair path. Databases with latent damage that worked before will stop starting.

  • Each insert into runtime_events, session_messages, core_agent_run_events and the partial snapshot/segment tables now also upserts session_content_activity. That includes every streaming segment insert and update, which puts an extra write on the hot path.
  • Migration and downgrade. Runtime schema goes 20→21, operational schema 2→3, and the epoch 222→223. Once a root starts on this build, an older build refuses it; restoreBatch restores payload bytes but not the schema. Backup restore already requires the current schema. Restore also resets the writer to the default (enabled) and drops an explicit disable carried in the backup.

    Protocol epoch. host-status.ts adds the upgrading_storage state and storageUpgradePhase, and the epoch moves 222 → 223. I confirmed main is at 222. Older peers reject the unknown lifecycle state, so the bump is justified. Open #5980 also declares 223, so one of the two will need to renumber (P3).

    CI and mergeability. GitHub reports the PR as mergeable, blocked only on review. test fails (P2 above), package was still pending, and the other checks pass.

    Astro-Han Astro-Han commented on code on Oct 15, 2026 09:16 UTC
    Code Review
    packages/runtime-host/src/server/storage-maintenance.ts:1
    @@ -115,6 +118,35 @@ export class HostStorageMaintenance {
             idleDelay: RETENTION_IDLE_DELAY_MS,
             run: () => retention.sweep(),
           });
    +    if (input.coldStorage) {
    +      const cold = input.coldStorage;
    +      let inputBytes = 0;
    +      this.#lanes.push({
    +        name: 'cold runtime compression',
    +        failures: 0,
    +        activeDelay: ACTIVE_DELAY_MS,
    +        idleDelay: IDLE_DELAY_MS,
    +        run: async () => {
    +          const result = await cold.compressBatch({ maxItems: 16, maxBytes: 1024 * 1024 });
    +          inputBytes = result.inputBytes;
    +          if (result.failures > 0)
    +            this.#report(
    +              'cold runtime compression',
    +              new Error(`${result.failures} records failed verification; original bytes retained`),
    +            );
    +          return result.hasMore;
    +        },
    +        // Large records are supported, then charged against the same average input budget.
    +        activeDelayMs: () => Math.max(1000, Math.ceil((inputBytes / (1024 * 1024)) * 1000)),
    +      });
    +      this.#lanes.push({
    +        name: 'runtime page reclamation',

    P3: open #6083 adds a lane with the same name that runs incremental_vacuum on runtime.sqlite. These files merge with no textual conflict, so landing both would run two reclamation lanes. Please agree with #6083 on which one owns this.

    github-actions[bot] github-actions[bot] commented on Nov 15, 2026 03:42 UTC
    Bot

    <!-- maka-lifecycle:stale-warning -->
    This pull request has had no new commits for 30 days and has been marked stale. It will be closed in 7 days unless a new commit is pushed.

    Comments do not reset this timer: only a new commit does. If the pull request is intentionally long-lived, a maintainer can apply the pinned label.

    github-actions[bot] github-actions[bot] commented on Nov 23, 2026 03:42 UTC
    Bot

    <!-- maka-lifecycle:stale-close -->
    This pull request has been closed because it received no new commits during the 7-day grace period. This is not a judgement on the merit of the change; it only keeps the review queue aligned with work that is actively in flight.

    The branch and review history are preserved. Push a new commit and reopen the pull request whenever the work is ready to continue.

    Reviewers
    Assignees
    testikun testikun
    Labels
    risk: low confidence: 75.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 75.7% · Lower = rushed or shallow review
    75.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 17.3% · Safe to merge
    17.3%
    Repository