~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
618 lines · 28.5 KB Raw History
// A soak: the same workload, from the same seed, against one PDS or several
// side by side, for as long as it runs (bench/soak/README.md). Each server
// gets ACCOUNTS accounts, then a steady RATE operations a second: posts,
// likes, follows, profiles, deletes, batches, blobs, reads, sessions. What
// each account holds is kept here as the writes were answered, and read back
// whole now and then, nothing else done to that account meanwhile: a record
// answered is never lost, a server killed meanwhile included. A firehose
// subscriber on each server checks that every commit answered comes
// through. With DURATION_MS it ends with the settled check of Monolith's
// spec/STORE.md, "Bounds".
//
// Writes to OUT: events-<name>.jsonl (what went wrong, outages, and each
// five minutes' counts and times), summary-<name>.json (all of it so far),
// and state-<name>.json (the accounts, to carry on after a restart of this
// driver). Sends nothing while OUT/STOP exists, as a wrapper that watches
// the disk may make it.
//
// No dependencies: Node's fetch and WebSocket, and a small CBOR reader for
// the firehose's frames.

import { appendFileSync, existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'

const OUT = process.env.OUT || '/out'
const ACCOUNTS = Number(process.env.ACCOUNTS || 50)
const RATE = Number(process.env.RATE || 6)
const RUN = process.env.RUN || 'soak1'
const SEED = Number(process.env.SEED || 1)
const WINDOW_MS = 5 * 60_000
const VERIFY_EVERY_MS = 60_000
const FIREHOSE_GRACE_MS = 120_000
/// With DURATION_MS, the load stops after it and the run ends with the
/// settled check (Side.settle): the server's backfill window W_MS, and its
/// data directory DATA_DIR, read here, so the server is on this machine.
const DURATION_MS = Number(process.env.DURATION_MS || 0)
const W_MS = Number(process.env.W_MS || 86_400_000)
const DATA_DIR = process.env.DATA_DIR
/// SETTLE_ONLY: no load, no quiet: the accounts of an earlier run (state-*.json)
/// written once at once, then measured, as after a restart that followed 2 W
/// of quiet, each account's store loaded by that write.
const SETTLE_ONLY = !!process.env.SETTLE_ONLY

/// The servers: one by TARGET_URL (TARGET_NAME, TARGET_DOMAIN, the handles'
/// domain without its dot, TARGET_ADMIN_PASSWORD for invite codes), or
/// several as SIDES, a JSON list of `{name, url, domain, admin}`.
const SIDES = process.env.TARGET_URL
  ? [{ name: process.env.TARGET_NAME || 'target', url: process.env.TARGET_URL, domain: process.env.TARGET_DOMAIN || 'test', admin: process.env.TARGET_ADMIN_PASSWORD }]
  : JSON.parse(process.env.SIDES || 'null')
if (!SIDES?.length) {
  console.error('soak.mjs: give TARGET_URL, or SIDES as a JSON list of {name, url, domain, admin}')
  process.exit(2)
}

const POST = 'app.bsky.feed.post'
const PROFILE = 'app.bsky.actor.profile'
const COLLECTIONS = [POST, 'app.bsky.feed.like', 'app.bsky.graph.follow', PROFILE]
const STARTED = new Date().toISOString()

// ------------------------------------------------------------------ random

/// mulberry32: one stream per side from the same seed, so both get the same
/// operations in the same order.
function rng(seed) {
  let a = seed >>> 0
  return () => {
    a = (a + 0x6d2b79f5) >>> 0
    let t = a
    t = Math.imul(t ^ (t >>> 15), t | 1)
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296
  }
}

// --------------------------------------------------------------------- cbor

/// One CBOR item of `b` at `p`: [value, next]. A CID (tag 42) is its string.
function cbor(b, p) {
  const ib = b[p++]
  const major = ib >> 5
  const info = ib & 31
  let n = info
  if (info === 24) n = b[p++]
  else if (info === 25) { n = (b[p] << 8) | b[p + 1]; p += 2 }
  else if (info === 26) { n = (b[p] * 2 ** 24) + ((b[p + 1] << 16) | (b[p + 2] << 8) | b[p + 3]); p += 4 }
  else if (info === 27) { n = 0; for (let i = 0; i < 8; i++) n = n * 256 + b[p + i]; p += 8 }
  switch (major) {
    case 0: return [n, p]
    case 1: return [-1 - n, p]
    case 2: return [b.subarray(p, p + n), p + n]
    case 3: return [new TextDecoder().decode(b.subarray(p, p + n)), p + n]
    case 4: { const a = []; for (let i = 0; i < n; i++) { let v; [v, p] = cbor(b, p); a.push(v) } return [a, p] }
    case 5: { const o = {}; for (let i = 0; i < n; i++) { let k, v; [k, p] = cbor(b, p); [v, p] = cbor(b, p); o[k] = v } return [o, p] }
    case 6: { let v; [v, p] = cbor(b, p); return [n === 42 ? cidString(v) : v, p] }
    default:
      if (info === 20) return [false, p]
      if (info === 21) return [true, p]
      return [null, p]
  }
}

const B32 = 'abcdefghijklmnopqrstuvwxyz234567'
function cidString(bytes) {
  const raw = bytes[0] === 0 ? bytes.subarray(1) : bytes
  let out = 'b', bits = 0, val = 0
  for (const x of raw) {
    val = ((val << 8) | x) & 0xffff
    bits += 8
    while (bits >= 5) { out += B32[(val >>> (bits - 5)) & 31]; bits -= 5 }
  }
  if (bits > 0) out += B32[(val << (5 - bits)) & 31]
  return out
}

// ------------------------------------------------------------------ helpers

const now = () => Date.now()
const iso = () => new Date().toISOString()
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const stopped = () => existsSync(`${OUT}/STOP`)

function pct(xs, q) {
  if (!xs.length) return null
  const s = [...xs].sort((a, b) => a - b)
  return Math.round(s[Math.min(s.length - 1, Math.floor(q * s.length))] * 10) / 10
}

/// A PNG's signature and header, then random bytes: sniffed as image/png.
function png(r, size) {
  const head = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52, 0, 0, 0, 16, 0, 0, 0, 16, 8, 2, 0, 0, 0, 0x90, 0x91, 0x68, 0x36]
  const b = new Uint8Array(size)
  b.set(head)
  for (let i = head.length; i < size; i++) b[i] = (r() * 256) | 0
  return b
}

const hex = (n) => [...crypto.getRandomValues(new Uint8Array(n))].map((x) => x.toString(16).padStart(2, '0')).join('')

/// What a follow or like links to, as `createRecord` compares duplicates:
/// the follow's DID, the like's subject's URI, as strings.
const subjectOf = (value) => (typeof value?.subject === 'string' ? value.subject : value?.subject?.uri)

// --------------------------------------------------------------------- side

class Side {
  constructor(cfg, seed) {
    Object.assign(this, cfg)
    this.r = rng(seed)
    this.accounts = []
    /// did -> Map(uri -> {cid, collection, uncertain})
    this.model = new Map()
    this.posts = [] // {uri, cid}, to like
    this.pendingCommits = new Map() // commit cid -> when answered
    this.seenCommits = new Map() // commit cid -> when it came on the firehose, before its answer did
    this.lastFrame = now() // when the firehose last sent anything
    this.ws = null
    this.lastSeq = null
    this.down = null // since when requests fail to connect
    this.totals = { ops: 0, ok: 0, e5xx: 0, e4xx: 0, limited: 0, down: 0, mismatches: 0, lost: 0, found: 0, seqJumps: 0, missingCommits: 0, outages: 0, outageMs: 0, verifies: 0 }
    this.window = this.newWindow()
    this.statePath = `${OUT}/state-${this.name}.json`
  }

  newWindow() { return { from: iso(), ops: {}, firehose: { events: 0, lagMs: [] } } }

  event(kind, detail = {}) {
    appendFileSync(`${OUT}/events-${this.name}.jsonl`, JSON.stringify({ time: iso(), side: this.name, kind, ...detail }) + '\n')
  }

  note(op, ms, outcome) {
    const w = (this.window.ops[op] ??= { n: 0, ms: [], outcomes: {} })
    w.n++
    if (ms != null) w.ms.push(ms)
    w.outcomes[outcome] = (w.outcomes[outcome] || 0) + 1
  }

  /// An XRPC call: {status, body} or {status: 0} when it could not connect.
  /// A procedure with no input (`post`) is a POST with no body.
  async call(op, nsid, { query, body, token, bytes, mime, raw, post } = {}) {
    const url = `${this.url}/xrpc/${nsid}${query ? '?' + new URLSearchParams(query) : ''}`
    const headers = {}
    if (token) headers.authorization = token.startsWith('Basic ') ? token : `Bearer ${token}`
    let payload
    if (bytes) { headers['content-type'] = mime; payload = bytes }
    else if (body) { headers['content-type'] = 'application/json'; payload = JSON.stringify(body) }
    const t0 = performance.now()
    this.totals.ops++
    try {
      const res = await fetch(url, { method: payload || post ? 'POST' : 'GET', headers, body: payload, signal: AbortSignal.timeout(30_000) })
      const text = raw ? (await res.arrayBuffer(), null) : await res.text()
      const ms = performance.now() - t0
      if (this.down) this.up()
      let json = null
      try { json = text ? JSON.parse(text) : null } catch {}
      const s = res.status
      if (s < 300) this.totals.ok++
      else if (s === 429) this.totals.limited++
      else if (s >= 500) { this.totals.e5xx++; this.event('5xx', { op, nsid, status: s, body: (text || '').slice(0, 300) }) }
      else this.totals.e4xx++
      this.note(op, ms, s < 300 ? 'ok' : String(s))
      return { status: s, body: json, ms }
    } catch (e) {
      this.totals.down++
      if (!this.down) { this.down = now(); this.event('down', { op, error: String(e.cause?.code || e.name) }) }
      this.note(op, null, 'down')
      return { status: 0, error: String(e.cause?.code || e.message) }
    }
  }

  up() {
    const ms = now() - this.down
    this.totals.outages++
    this.totals.outageMs += ms
    this.event('up', { downMs: ms })
    this.down = null
  }

  // ------------------------------------------------------------ accounts

  save() {
    const accounts = this.accounts.map(({ did, handle, password, refresh }) => ({ did, handle, password, refresh }))
    writeFileSync(this.statePath, JSON.stringify({ accounts, lastSeq: this.lastSeq }))
  }

  async setup() {
    if (existsSync(this.statePath)) {
      const s = JSON.parse(readFileSync(this.statePath, 'utf8'))
      this.accounts = s.accounts
      this.lastSeq = s.lastSeq
      this.event('resumed', { accounts: this.accounts.length })
      for (const a of this.accounts) await this.login(a)
      // Settling only: no read before the write, which would load each
      // account's store before it and so start what the store counts from.
      if (!SETTLE_ONLY) for (const a of this.accounts) await this.resync(a)
      else for (const a of this.accounts) this.model.set(a.did, new Map())
    }
    while (!SETTLE_ONLY && this.accounts.length < ACCOUNTS) {
      const name = `${RUN}-${String(this.accounts.length + 1).padStart(3, '0')}`
      const password = hex(12)
      const input = { handle: `${name}.${this.domain}`, email: `${name}@example.com`, password }
      if (this.admin) {
        const code = await this.call('createInviteCode', 'com.atproto.server.createInviteCode', { body: { useCount: 1 }, token: 'Basic ' + btoa(`admin:${this.admin}`) })
        if (code.status !== 200) { this.event('createInviteCode refused', { status: code.status, body: code.body }); await sleep(5000); continue }
        input.inviteCode = code.body.code
      }
      const r = await this.call('createAccount', 'com.atproto.server.createAccount', { body: input })
      if (r.status !== 200) {
        this.event('createAccount refused', { handle: input.handle, status: r.status, body: r.body })
        await sleep(r.status === 429 ? 60_000 : 5000)
        continue
      }
      const a = { did: r.body.did, handle: input.handle, password, access: r.body.accessJwt, refresh: r.body.refreshJwt }
      this.accounts.push(a)
      this.model.set(a.did, new Map())
      this.save()
      await sleep(200)
    }
    this.event('ready', { accounts: this.accounts.length })
  }

  async login(a) {
    for (;;) {
      if (a.refresh) {
        const r = await this.call('refreshSession', 'com.atproto.server.refreshSession', { post: true, token: a.refresh })
        if (r.status === 200) { a.access = r.body.accessJwt; a.refresh = r.body.refreshJwt; this.save(); return }
      }
      const r = await this.call('createSession', 'com.atproto.server.createSession', { body: { identifier: a.handle, password: a.password } })
      if (r.status === 200) { a.access = r.body.accessJwt; a.refresh = r.body.refreshJwt; this.save(); return }
      await sleep(r.status === 429 ? 60_000 : 5000)
    }
  }

  /// What the server holds of `a`, taken as the model: after this driver
  /// starts again, not knowing what it wrote last.
  async resync(a) {
    const m = new Map()
    for (const c of COLLECTIONS) {
      let recs
      while (!(recs = await this.listAll(a, c))) await sleep(5000)
      for (const rec of recs) {
        m.set(rec.uri, { cid: rec.cid, collection: c, subject: subjectOf(rec.value) })
        if (c === POST) this.posts.push({ uri: rec.uri, cid: rec.cid })
      }
    }
    this.model.set(a.did, m)
  }

  async listAll(a, collection) {
    const out = []
    let cursor
    for (;;) {
      const r = await this.call('listRecords(verify)', 'com.atproto.repo.listRecords', { query: { repo: a.did, collection, limit: 100, ...(cursor ? { cursor } : {}) } })
      if (r.status !== 200) return null
      out.push(...r.body.records)
      if (!r.body.cursor || r.body.records.length === 0) return out
      cursor = r.body.cursor
    }
  }

  /// A write as `a`, signing in again once if its token is no longer taken.
  async write(a, op, nsid, body) {
    let r = await this.call(op, nsid, { body, token: a.access })
    if (r.status === 401 || (r.status === 400 && /Token/.test(r.body?.error || ''))) {
      await this.login(a)
      r = await this.call(op, nsid, { body, token: a.access })
    }
    if (r.status === 200 && r.body?.commit?.cid) {
      const cid = r.body.commit.cid
      // The firehose may send a commit before its write is answered.
      if (this.seenCommits.delete(cid)) this.window.firehose.lagMs.push(0)
      else this.pendingCommits.set(cid, now())
    }
    return r
  }

  // ---------------------------------------------------------- operations

  pick(xs) { return xs[Math.floor(this.r() * xs.length)] }
  text() { return `soak ${RUN} ${Math.floor(this.r() * 1e9).toString(36)} ` + 'lorem ipsum dolor sit amet '.repeat(1 + Math.floor(this.r() * 6)) }

  remember(a, uri, cid, collection, subject) {
    this.model.get(a.did).set(uri, { cid, collection, subject, uncertain: false })
    if (collection === POST) {
      this.posts.push({ uri, cid })
      if (this.posts.length > 5000) this.posts.splice(0, 1000)
    }
  }

  async create(a, collection, record, op) {
    const r = await this.write(a, op, 'com.atproto.repo.createRecord', { repo: a.did, collection, record })
    if (r.status === 200) {
      // A follow or like replaces the account's others of the same subject,
      // in the same commit (Monolith's spec/VALIDATION.md, "Duplicates").
      const subject = subjectOf(record)
      if (subject) {
        const model = this.model.get(a.did)
        for (const [uri, v] of model) if (v.collection === collection && v.subject === subject) model.delete(uri)
      }
      this.remember(a, r.body.uri, r.body.cid, collection, subject)
    } else if (r.status === 0) {
      // Cut short by a kill: the record is not in the model, and its
      // duplicates may be gone; a verify settles both.
      const subject = subjectOf(record)
      if (subject) for (const v of this.model.get(a.did).values()) if (v.collection === collection && v.subject === subject) v.uncertain = true
    }
    return r
  }

  async step(a) {
    const x = this.r() * 100
    const at = iso()
    const model = this.model.get(a.did)
    if (x < 25) return this.create(a, POST, { $type: POST, text: this.text(), createdAt: at }, 'post')
    if (x < 37) {
      if (!this.posts.length) return
      return this.create(a, 'app.bsky.feed.like', { $type: 'app.bsky.feed.like', subject: this.pick(this.posts), createdAt: at }, 'like')
    }
    if (x < 41) return this.create(a, 'app.bsky.graph.follow', { $type: 'app.bsky.graph.follow', subject: this.pick(this.accounts).did, createdAt: at }, 'follow')
    if (x < 44) {
      const record = { $type: PROFILE, displayName: `soak ${a.handle.split('.')[0]}`, description: this.text().slice(0, 200) }
      const r = await this.write(a, 'profile', 'com.atproto.repo.putRecord', { repo: a.did, collection: PROFILE, rkey: 'self', record })
      if (r.status === 200) this.remember(a, r.body.uri, r.body.cid, PROFILE)
      else if (r.status === 0) { const v = model.get(`at://${a.did}/${PROFILE}/self`); if (v) v.uncertain = true }
      return
    }
    if (x < 50) {
      const mine = [...model.entries()].filter(([, v]) => v.collection !== PROFILE)
      if (!mine.length) return
      const [uri, v] = this.pick(mine)
      const r = await this.write(a, 'delete', 'com.atproto.repo.deleteRecord', { repo: a.did, collection: v.collection, rkey: uri.split('/').pop() })
      if (r.status === 200) model.delete(uri)
      else if (r.status === 0) v.uncertain = true
      return
    }
    if (x < 54) {
      const writes = Array.from({ length: 5 }, () => ({ $type: 'com.atproto.repo.applyWrites#create', collection: POST, value: { $type: POST, text: this.text(), createdAt: at } }))
      const r = await this.write(a, 'applyWrites', 'com.atproto.repo.applyWrites', { repo: a.did, writes })
      if (r.status === 200) for (const w of r.body.results || []) if (w.uri) this.remember(a, w.uri, w.cid, POST)
      return
    }
    if (x < 56) {
      const up = await this.call('uploadBlob', 'com.atproto.repo.uploadBlob', { bytes: png(this.r, 2000 + Math.floor(this.r() * 120_000)), mime: 'image/png', token: a.access })
      if (up.status !== 200) return
      const embed = { $type: 'app.bsky.embed.images', images: [{ alt: 'soak', image: up.body.blob }] }
      return this.create(a, POST, { $type: POST, text: this.text(), createdAt: at, embed }, 'blobPost')
    }
    if (x < 71) {
      const mine = [...model.entries()].filter(([, v]) => !v.uncertain)
      if (!mine.length) return
      const [uri, v] = this.pick(mine)
      const [, , repo, collection, rkey] = uri.split('/')
      const r = await this.call('getRecord', 'com.atproto.repo.getRecord', { query: { repo, collection, rkey } })
      // Deleted or replaced meanwhile by another step, or no answer (down,
      // or a rate limit's 429): no claim either way.
      if (model.get(uri) !== v || r.status === 0 || r.status === 429) return
      if (r.status !== 200 || r.body?.cid !== v.cid) this.mismatch(a, 'getRecord', { uri, want: v.cid, status: r.status, got: r.body?.cid ?? r.body })
      return
    }
    if (x < 81) return this.call('listRecords', 'com.atproto.repo.listRecords', { query: { repo: a.did, collection: this.pick(COLLECTIONS), limit: 50 } })
    if (x < 86) return this.call('getLatestCommit', 'com.atproto.sync.getLatestCommit', { query: { did: a.did } })
    if (x < 88) return this.call('describeRepo', 'com.atproto.repo.describeRepo', { query: { repo: a.did } })
    if (x < 89) return this.call('getRepo', 'com.atproto.sync.getRepo', { query: { did: a.did }, raw: true })
    if (x < 90) return this.login(a)
    return this.call('describeServer', 'com.atproto.server.describeServer')
  }

  mismatch(a, what, detail) {
    if (this.down) return // a read while it was down is no answer
    this.totals.mismatches++
    this.event('mismatch', { what, did: a.did, ...detail })
  }

  /// Every record the model holds of `a`, read back whole, nothing else
  /// done to it meanwhile (run): one answered and gone is lost, one with
  /// another CID differs; one the server has that a write cut short by a
  /// kill left unknown is taken in.
  async verify(a) {
    const want = this.model.get(a.did)
    const got = new Map()
    for (const c of COLLECTIONS) {
      const recs = await this.listAll(a, c)
      if (!recs) return // down, or refused: another time
      for (const r of recs) got.set(r.uri, { cid: r.cid, collection: c, subject: subjectOf(r.value) })
    }
    let lost = 0, differ = 0, found = 0
    for (const [uri, v] of [...want.entries()]) {
      const g = got.get(uri)
      if (v.uncertain) { if (g) want.set(uri, { ...g, uncertain: false }); else want.delete(uri); continue }
      if (!g) { lost++; this.event('lost', { did: a.did, uri, cid: v.cid }); want.delete(uri); continue }
      if (g.cid !== v.cid) { differ++; this.event('differs', { did: a.did, uri, want: v.cid, got: g.cid }); want.set(uri, g) }
    }
    for (const [uri, g] of got) if (!want.has(uri)) { found++; want.set(uri, g) }
    this.totals.verifies++
    this.totals.lost += lost
    this.totals.mismatches += differ
    this.totals.found += found
    if (found) this.event('found', { did: a.did, records: found })
    this.note('verify', null, lost || differ ? 'bad' : 'ok')
  }

  // ------------------------------------------------------------ firehose

  firehose() {
    const cursor = this.lastSeq != null ? `?cursor=${this.lastSeq}` : ''
    const ws = (this.ws = new WebSocket(`${this.url.replace('http', 'ws')}/xrpc/com.atproto.sync.subscribeRepos${cursor}`))
    ws.binaryType = 'arraybuffer'
    ws.onmessage = (e) => {
      this.lastFrame = now()
      try {
        const b = new Uint8Array(e.data)
        const [header, p] = cbor(b, 0)
        const [body] = cbor(b, p)
        if (header.op === -1) { this.event('firehose error', { body }); return }
        if (typeof body.seq !== 'number') return
        // A jump in seq is no event missed: Monolith reserves seqs in blocks,
        // and numbers past the block after a start (spec/STORE.md, "Seqs are
        // never reused"). An event missed is a commit answered that never
        // comes (sweep).
        if (this.lastSeq != null && body.seq > this.lastSeq + 1) {
          this.totals.seqJumps++
          this.event('seq jump', { after: this.lastSeq, got: body.seq, t: header.t })
        }
        if (this.lastSeq == null || body.seq > this.lastSeq) this.lastSeq = body.seq
        this.window.firehose.events++
        if (header.t === '#commit' && body.commit) {
          const at = this.pendingCommits.get(body.commit)
          if (at) { this.window.firehose.lagMs.push(now() - at); this.pendingCommits.delete(body.commit) }
          else this.seenCommits.set(body.commit, now())
        }
      } catch (err) {
        this.event('firehose frame unread', { error: String(err) })
      }
    }
    ws.onclose = () => { if (this.ws === ws) setTimeout(() => this.firehose(), 2000) }
    ws.onerror = () => {}
  }

  /// A subscription that has sent nothing for 30 s while commits wait for it
  /// is taken as stalled: subscribe again from the last seq, so a commit it
  /// would have sent comes all the same, and only one never sent is missing.
  watch() {
    const waiting = [...this.pendingCommits.values()].some((at) => now() - at > 30_000)
    if (!waiting || now() - this.lastFrame < 30_000 || this.down) return
    this.event('firehose stalled', { lastSeq: this.lastSeq, silentMs: now() - this.lastFrame })
    const old = this.ws
    this.ws = null
    try { old?.close() } catch {}
    this.lastFrame = now()
    this.firehose()
  }

  /// Commits answered and not on the firehose within the grace, the side
  /// not down meanwhile.
  sweep() {
    const t = now()
    for (const [cid, at] of this.pendingCommits) {
      if (t - at < FIREHOSE_GRACE_MS || this.down) continue
      this.totals.missingCommits++
      this.event('commit not on firehose', { cid, answeredAt: new Date(at).toISOString() })
      this.pendingCommits.delete(cid)
    }
    for (const [cid, at] of this.seenCommits) if (t - at > 10 * 60_000) this.seenCommits.delete(cid)
  }

  // ----------------------------------------------------------- reporting

  flush() {
    const w = this.window
    const ops = Object.fromEntries(Object.entries(w.ops).map(([op, v]) => [op, { n: v.n, p50: pct(v.ms, 0.5), p99: pct(v.ms, 0.99), outcomes: v.outcomes }]))
    const line = { from: w.from, to: iso(), ops, firehose: { events: w.firehose.events, lagP50: pct(w.firehose.lagMs, 0.5), lagP99: pct(w.firehose.lagMs, 0.99) }, lastSeq: this.lastSeq }
    this.event('window', line)
    this.window = this.newWindow()
    const records = [...this.model.values()].reduce((n, m) => n + m.size, 0)
    writeFileSync(`${OUT}/summary-${this.name}.json`, JSON.stringify({ side: this.name, updated: iso(), started: STARTED, accounts: this.accounts.length, records, lastSeq: this.lastSeq, totals: this.totals, lastWindow: line }, null, 2))
    this.save()
  }

  async run() {
    await this.setup()
    if (SETTLE_ONLY) return this.settle()
    this.firehose()
    let next = now(), verifyAt = now() + VERIFY_EVERY_MS
    const inflight = new Set()
    const busy = new Set() // accounts being verified
    const using = new Map() // did -> operations on it under way
    const use = (a, d) => using.set(a.did, (using.get(a.did) || 0) + d)
    const timers = [setInterval(() => this.flush(), WINDOW_MS), setInterval(() => this.sweep(), 30_000), setInterval(() => this.watch(), 10_000)]
    const until = DURATION_MS ? now() + DURATION_MS : Infinity
    while (now() < until) {
      if (stopped()) { await sleep(10_000); next = now(); continue }
      next += 1000 / RATE
      const wait = next - now()
      if (wait > 0) await sleep(wait)
      else if (wait < -5000) next = now() // fell behind (down): no burst to catch up
      while (inflight.size >= 8) await Promise.race(inflight)
      const a = this.pick(this.accounts)
      if (busy.has(a.did)) continue
      let job
      if (now() >= verifyAt) {
        verifyAt = now() + VERIFY_EVERY_MS
        busy.add(a.did)
        job = (async () => {
          while (using.get(a.did)) await sleep(50)
          await this.verify(a)
        })().finally(() => busy.delete(a.did))
      } else {
        use(a, 1)
        job = this.step(a).finally(() => use(a, -1))
      }
      const p = job.catch((e) => this.event('driver error', { error: String(e?.stack || e).slice(0, 500) })).finally(() => inflight.delete(p))
      inflight.add(p)
    }
    await Promise.all(inflight)
    for (const t of timers) clearInterval(t)
    this.flush()
    if (this.ws) { const ws = this.ws; this.ws = null; ws.close() }
    if (!DATA_DIR) return { side: this.name, pass: true } // load alone: settled another time (SETTLE_ONLY)
    this.loadEnd = dirBytes(DATA_DIR)
    return this.settle()
  }

  /// spec/STORE.md, "Bounds", "Settled": no write for 2 W, then one to each
  /// account, and within 10 seconds the data directory at most three times
  /// the accounts' live states (getRepo whole, and the blobs they hold), plus
  /// 128 KiB an account and 1 MiB.
  async settle() {
    const quiet = SETTLE_ONLY ? 0 : 2 * W_MS + 2000
    this.event('settling', { quietMs: quiet })
    console.error(`${this.name}: load done; quiet for ${Math.round(quiet / 1000)} s (2 W)`)
    await sleep(quiet)
    const before = dirBytes(DATA_DIR)
    const at = iso()
    const wrote = await Promise.all(this.accounts.map((a) => this.create(a, POST, { $type: POST, text: 'settled', createdAt: at }, 'settle')))
    const t0 = now()
    let least = Infinity
    const sizes = []
    while (now() - t0 < 10_000) {
      const b = dirBytes(DATA_DIR)
      sizes.push(b)
      least = Math.min(least, b)
      await sleep(500)
    }
    let repos = 0, blobs = 0
    for (const a of this.accounts) {
      const car = await fetch(`${this.url}/xrpc/com.atproto.sync.getRepo?did=${a.did}`)
      repos += (await car.arrayBuffer()).byteLength
      for (let cursor; ; ) {
        const l = await (await fetch(`${this.url}/xrpc/com.atproto.sync.listBlobs?did=${a.did}&limit=1000${cursor ? `&cursor=${cursor}` : ''}`)).json()
        for (const cid of l.cids) blobs += (await (await fetch(`${this.url}/xrpc/com.atproto.sync.getBlob?did=${a.did}&cid=${cid}`)).arrayBuffer()).byteLength
        if (!l.cursor || !l.cids.length) break
        cursor = l.cursor
      }
    }
    const live = repos + blobs
    const bound = 3 * live + 131072 * this.accounts.length + 1048576
    const verdict = { side: this.name, wrote: wrote.filter((r) => r.status === 200).length, accounts: this.accounts.length, liveMiB: mib(live), reposMiB: mib(repos), blobsMiB: mib(blobs), boundMiB: mib(bound), loadEndMiB: this.loadEnd == null ? null : mib(this.loadEnd), beforeMiB: mib(before), leastMiB: mib(least), lastMiB: mib(sizes.at(-1)), ratio: +(least / bound).toFixed(2), pass: least <= bound }
    this.event('settled', verdict)
    console.log(JSON.stringify(verdict))
    return verdict
  }
}

const mib = (b) => +(b / 1048576).toFixed(1)

/// The sizes of the files in `dir`, at any depth (spec/STORE.md, "the data
/// directory's size"); a file gone while counted counts nothing.
function dirBytes(dir) {
  let n = 0
  for (const e of readdirSync(dir, { withFileTypes: true, recursive: true })) {
    if (!e.isFile()) continue
    try { n += statSync(join(e.parentPath, e.name)).size } catch {}
  }
  return n
}

const sides = SIDES.map((cfg) => new Side(cfg, SEED))
process.on('SIGTERM', () => { for (const s of sides) s.flush(); process.exit(0) })
const verdicts = await Promise.all(sides.map((s) => s.run()))
process.exit(verdicts.every((v) => v.pass) ? 0 : 1)