Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

14.1 KB
Raw Blame
/**
 * Hot SwarmGroup reads that name their index (prod slow log, 2026-10-28: ~200 ms of each read was query planning). Prisma
 * sends its filters as $expr, and a filter several indexes could serve is planned again whenever the plan cache misses: a
 * race of every candidate index over the Swarm's rows, which a bigger Swarm repeats by evicting the cached plan, and which
 * can pick an index that reads every quiet conversation to return none. A named index is never planned.
 * integration/superTabGroupPlans.test.ts holds each read to it under Mongo's profiler.
 */
import { AsyncLocalStorage } from 'node:async_hooks'
import type { Prisma, PrismaClient } from '@prisma/client'
import { logger } from '../../utils/logger.js'

type Transaction = Prisma.TransactionClient

/** The SwarmGroup indexes hot reads name, as prisma/schema.prisma declares them. */
export const GROUP_INDEX = {
  proposalDue: { deleted: 1, proposalDueAt: 1, tabId: 1, key: 1 },
  key: { tabId: 1, key: 1 },
  running: { tabId: 1, executionMachineId: 1 },
  agents: { tabId: 1, agentIds: 1 },
  /** A person's Tasks feed pages, newest activity first (read/personalTasks.ts, task #4203). */
  feed: { tabId: 1, feedIds: 1, lastActivityAt: 1, key: 1 },
  project: { tabId: 1, projectId: 1, dormant: 1, lastActivityAt: 1, key: 1 },
  dormancy: { tabId: 1, dormant: 1, changedAt: 1 },
  /** Groups active since a time, in every Swarm: the scorecard's projects with a day to count (scorecard/job.ts). */
  activity: { dormant: 1, lastActivityAt: 1 },
  /** A command's awake conversations by the columns a held part is compared by (parts/held.ts): the listing reads no document. */
  held: { tabId: 1, dormant: 1, deleted: 1, key: 1, version: 1, changedAt: 1 },
  changes: { tabId: 1, changedAt: 1 },
  /** A host's changed conversations: led by the host, so the wake check reads no other host's. */
  wake: { hostMachineIds: 1, tabId: 1, changedAt: 1 },
  /** Every live group: the host signature's index. */
  live: { tabId: 1, deleted: 1, key: 1, hostDigest: 1, dormant: 1 },
  /** Rows by id: a delta's whole rows of the versions it has not read (parts/load.ts loadDelta). */
  id: { _id: 1 },
} as const
export type GroupIndex = keyof typeof GROUP_INDEX

/** Every index a hot read names, by collection, as prisma/schema.prisma declares them (roadmap Phase 3). */
export const NAMED_INDEX = {
  SwarmGroup: GROUP_INDEX,
  SuperTab: {
    /** An owner's Swarms in id order: the grid poll. */
    owner: { autonomousEnv: 1, ownerId: 1, _id: 1 },
    /** The Swarms inviting each address (invitedSwarms.ts), and every Swarm with an invitation (the hourly sweep). */
    invited: { autonomousEnv: 1, invitedEmails: 1, _id: 1 },
    /** A member's Swarms in id order: Swarm lists and Workspace removals. */
    members: { autonomousEnv: 1, memberIds: 1, _id: 1 },
    /** A machine's Swarms, newest first, and those that still list it for cleanup: the host poll. */
    machines: { autonomousEnv: 1, machineIds: 1, updatedAt: 1 },
    cleanup: { autonomousEnv: 1, cleanupMachineIds: 1, updatedAt: 1 },
    /** Swarms by id. */
    id: { _id: 1 },
    /** A Workspace's Swarms: a Workspace removal reads its deleted ones (workspaceStore.ts). */
    workspace: { autonomousEnv: 1, workspaceId: 1 },
    /** Deleted Swarms by purge time (deletion.ts): the purge sweep. */
    purge: { purgeAt: 1 },
    /** The Swarms people at a domain join by themselves (autoJoin.ts): one read per person at most every 2 minutes. */
    autoJoin: { autonomousEnv: 1, autoJoinDomain: 1 },
  },
  /** Each part kind's changes since a cursor; machines also by when they were last read. `id`: rows by id, a delta's whole
   *  rows of the versions it has not read (parts/load.ts loadDelta). `held`: a command's live parts by the columns a held part
   *  is compared by (parts/held.ts), so the listing reads no document (task #4368). */
  SwarmHead: { changes: { tabId: 1, changedAt: 1 }, id: { _id: 1 } },
  /** `purge`: tombstones past their purge time (the hourly sweep). */
  SwarmMember: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 }, held: { tabId: 1, deleted: 1, key: 1, version: 1, changedAt: 1 } },
  SwarmAgent: { changes: { tabId: 1, changedAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 }, held: { tabId: 1, deleted: 1, key: 1, version: 1, changedAt: 1 } },
  SwarmMachine: { changes: { tabId: 1, changedAt: 1 }, read: { tabId: 1, readAt: 1 }, purge: { purgeAt: 1 }, id: { _id: 1 },
    held: { tabId: 1, deleted: 1, key: 1, version: 1, changedAt: 1, readAt: 1 } },
  /** `expiry`: live starts by finish time (the hourly sweep). `agents`: a Swarm's starts of some agents (agentTombstones.ts):
   *  unnamed, Mongo planned that read on `expiry` and read every live start of every Swarm. */
  SwarmStart: { changes: { tabId: 1, changedAt: 1 }, expiry: { deleted: 1, finishedAt: 1 }, agents: { tabId: 1, agentId: 1 }, id: { _id: 1 } },
  SwarmProgress: { changes: { tabId: 1, changedAt: 1 }, id: { _id: 1 }, held: { tabId: 1, deleted: 1, key: 1, version: 1, changedAt: 1 } },
  SuperTabMessage: {
    /** A conversation's page in (sequence, id) order. */
    sequence: { tabId: 1, conversationId: 1, sequence: 1, _id: 1 },
    /** One thread's page. */
    thread: { tabId: 1, conversationId: 1, thread: 1, sequence: 1 },
    /** One message. */
    id: { _id: 1 },
  },
  /** A project chat's open proposal roots, newest first (proposals.ts). */
  SuperTabOpenProposal: { open: { tabId: 1, conversationId: 1, sequence: 1 }, id: { _id: 1 } },
  /** A Swarm's newest route decisions: the route-decision list. */
  SuperTabRouteDecision: { recent: { tabId: 1, createdAt: 1 } },
  /** A project's scorecard days (scorecard/rows.ts). */
  SuperTabScorecard: { day: { tabId: 1, projectId: 1, on: 1 } },
  SuperTabDelivery: {
    /** An agent's deliveries by status and age: its open ones, oldest first. */
    agentOpen: { tabId: 1, agentId: 1, status: 1, createdAt: 1 },
    agentProposal: { tabId: 1, agentId: 1, status: 1, inputPriority: 1, createdAt: 1 },
    /** Finished deliveries by their last change: those old enough to compact (deliveryCompaction.ts). */
    compaction: { status: 1, updatedAt: 1 },
    /** Unfinished deliveries in id order, a page at a time (deliverySettle.ts). Named: with a fourth status Mongo planned the pass on
     *  `compaction` and sorted, reading far more than a page. */
    settle: { status: 1, _id: 1 },
    /** A message's deliveries in its Swarm. */
    byMessage: { tabId: 1, messageId: 1 },
  },
  /** Compacted receipts (pageReads.ts): a page's by message id, and a host's by the compacted delivery's id. */
  SuperTabReceipt: {
    id: { _id: 1 },
    delivery: { tabId: 1, deliveryIds: 1 },
  },
  /** A person's thread marks (readMarks.ts): `person`, every one or those moved since a cursor, the cap's count and oldest,
   *  and the sweep's people per Swarm; `age`, the sweep's marks untouched for 180 days. */
  SuperTabThreadMark: {
    person: { tabId: 1, personId: 1, updatedAt: 1 },
    age: { updatedAt: 1 },
  },
  /** A page's thread summaries, by root id (pageReads.ts pageThreads). */
  SuperTabThread: { id: { _id: 1 } },
  /** `age`: Activity rows past their expiry (activity.ts sweepActivity). */
  /** `unread`: a person's unread rows, newest first: the digest each of their reads asks for (activity.ts activityDigest). */
  SuperTabActivity: { age: { createdAt: 1 }, unread: { tabId: 1, personId: 1, readAt: 1, createdAt: 1 } },
  /** `age`: chat settings back at the default, untouched for a week (chatSettings.ts sweepChatSettings). */
  SuperTabChatSetting: { age: { updatedAt: 1 } },
  /** A person's reminders (reminders.ts): `person`, the due list, the next one, the digest and the cap's count; `due`, the
   *  sweep's reminders due more than 30 days ago. */
  SuperTabReminder: {
    person: { tabId: 1, personId: 1, dueAt: 1 },
    due: { dueAt: 1 },
  },
} as const
export type NamedCollection = keyof typeof NAMED_INDEX
export type NamedIndex<C extends NamedCollection> = keyof typeof NAMED_INDEX[C] & string

/** The named indexes each collection had when last listed; none until then. A read names only these: naming one the
 *  database lacks fails the read, and in a transaction aborts it. */
let present = new Map<NamedCollection, Set<string>>()

const COLLECTIONS = Object.keys(NAMED_INDEX) as NamedCollection[]
const indexOf = (collection: NamedCollection, name: string) => (NAMED_INDEX[collection] as Record<string, Record<string, number>>)[name]!

/** Lists the named collections' indexes, outside any transaction, and says which hot reads go without theirs. The worker's
 *  `prisma db push` builds a new index at startup (Dockerfile.k8s), possibly after a server first lists them. */
export async function listNamedIndexes(db: PrismaClient): Promise<void> {
  const generation = drops
  const listed = await Promise.all(COLLECTIONS.map(async collection => {
    const reply = await db.$runCommandRaw({ listIndexes: collection }).catch(error => {
      // A collection nothing has written yet has no indexes either.
      if (/NamespaceNotFound|ns does not exist/i.test(error instanceof Error ? error.message : String(error))) return null
      throw error
    }) as unknown as { cursor: { firstBatch: Array<{ key: Record<string, unknown> }> } } | null
    return [collection, new Set((reply?.cursor.firstBatch ?? []).map(index => Object.keys(index.key).join(',')))] as const
  }))
  // A read dropped the listing while this one was on its way: its reply may predate the removal (review of #1994).
  if (drops !== generation) return
  present = new Map(listed.map(([collection, fields]) => {
    const names = Object.keys(NAMED_INDEX[collection])
    const found = new Set(names.filter(name => fields.has(Object.keys(indexOf(collection, name)).join(','))))
    const missing = names.filter(name => !found.has(name))
    if (missing.length) logger.error(`[swarm-reads] ${collection} lacks indexes hot reads name; they read without them`, { missing: missing.map(name => indexOf(collection, name)) })
    return [collection, found] as const
  }))
}
/** The SwarmGroup listing's older name: it lists every named collection now. */
export const listGroupIndexes = listNamedIndexes

/** Lists the indexes now and every five minutes, until the process ends. */
export function watchGroupIndexes(db: PrismaClient): void {
  const list = () => listNamedIndexes(db).catch(error => logger.warn('[swarm-reads] listing Swarm indexes failed', { error: error instanceof Error ? error.message : String(error) }))
  void list()
  setInterval(list, 5 * 60_000).unref()
}

/** How many times a read dropped the listing. A transaction a dropped index aborted fails in whichever of its reads Mongo
 *  answers first, often not the one that named it: its runner reruns it when this moved during the attempt. */
let drops = 0
export const listingDrops = (): number => drops

/** Set while a transaction a dropped index aborted runs again: its reads name no index, whatever a listing since says. */
const rerun = new AsyncLocalStorage<true>()
export const withoutHints = <T>(run: () => Promise<T>): Promise<T> => rerun.run(true, run)

/** Runs a transaction opened directly (outside store.ts `transaction`) once more when a read in it dropped the listing:
 *  the second attempt names no index (`withoutHints`). */
export async function retryStaleIndex<T>(run: () => Promise<T>): Promise<T> {
  const before = drops
  try {
    return await run()
  } catch (error) {
    if (drops === before) throw error
    return withoutHints(run)
  }
}

/** The rows a named read asks for in its first reply: all of them, in one round trip, within Mongo's 16 MB reply. Its default
 *  first batch is 101 documents, and each further batch a getMore: an agent's quiet conversations or a Swarm's week of
 *  finished starts took more of them as the Swarm grew (#2839: Atlas ops per request up 38% at flat traffic). */
export const READ_BATCH = 100_000

/**
 * The rows of an `aggregateRaw` pipeline on `collection`, through its index `name` once the database is known to have it.
 * An index removed since the last listing (a rollback, an index replaced) fails the read: the listing is dropped, said, and
 * the read runs without it at once outside a transaction. In one, the failed command aborted it, and Prisma may report only
 * that: its runner runs it again (`listingDrops`).
 */
export async function readBy<C extends NamedCollection>(tx: Transaction, collection: C, name: NamedIndex<C>,
  pipeline: Prisma.InputJsonValue[]): Promise<Array<Record<string, unknown>>> {
  const model = (tx as unknown as Record<string, { aggregateRaw(args: unknown): Promise<unknown> }>)[collection[0]!.toLowerCase() + collection.slice(1)]!
  const run = async (hint?: Record<string, number>) => await model.aggregateRaw({ pipeline, options: { batchSize: READ_BATCH, ...hint ? { hint } : {} } }) as
    Array<Record<string, unknown>>
  if (rerun.getStore() || !present.get(collection)?.has(name)) return run()
  try {
    return await run(indexOf(collection, name))
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error)
    if (!/hint provided does not correspond to an existing index|has been aborted/.test(message)) throw error
    present = new Map()
    drops++
    logger.error('[swarm-reads] A Swarm collection lacks an index a hot read names; reads name none until the next listing',
      { collection, index: indexOf(collection, name) })
    if (typeof (tx as { $transaction?: unknown }).$transaction === 'function') return run()
    throw error
  }
}

/** The rows of an `aggregateRaw` pipeline on SwarmGroup through `index` (readBy). */
export const groupsBy = (tx: Transaction, index: GroupIndex, pipeline: Prisma.InputJsonValue[]): Promise<Array<Record<string, unknown>>> =>
  readBy(tx, 'SwarmGroup', index, pipeline)

/** A project's quiet conversations last active since `since`, as the project index serves them. A conversation stored with no
 *  project belongs to the first one (projects.ts groupProject); a null match is a missing field too. */
export function quietSince(tabId: string, projectId: string | string[], since: number): Record<string, Prisma.InputJsonValue> {
  return { tabId, deleted: false, dormant: true, lastActivityAt: { $gte: { $date: new Date(since).toISOString() } },
    projectId: { $in: [projectId].flat().flatMap(id => id === 'lead' ? ['lead', null] : [id]) } }
}