File size: 30,079 Bytes
8a29801
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
/**

 * The Fleet reporter's durable queue.

 *

 * The collectors record observations here and the uploader drains them to the phone's own Core. A partition is

 * one account on one Core: records queued as account A on Core X are only ever delivered as A to X, so a

 * partition's records are never returned for, or mixed with, another's. Every call takes the partition it works

 * on.

 *

 * Storage layout, in the `mentra-fleet` MMKV instance (which logout's `storage.clearAll()` does not touch):

 * - `q:<partition>:<seq>:<recordId>` holds one record, as `{enqueuedAt, record}` JSON. `<seq>` is the partition's

 *   enqueue counter, zero-padded to 16 digits so that key order is queue order.

 * - `i:<partition>` is the partition's index: `{count, nextSeq, oldest, newest}`, the record count, the next

 *   sequence and the oldest and newest record keys.

 * - `l:<partition>` holds the losses not yet reported: `{dropped, expired, from, to, updatedAt}`.

 * - `n:<partition>` holds the collector-session sequence counters, as `[collectorSessionId, next][]`.

 * - `t:<partition>` holds the miniapp telemetry lost and not yet reported, per package (`FleetTelemetryLosses`).

 *

 * Telemetry (Phase 12) has a share of the queue: a `telemetry_event`'s record ID starts with `tel.`, so its key says

 * what it is. Telemetry takes at most 2,000 of the 10,000 places. When that share or the queue is full, the oldest

 * telemetry record gives way, and a record of any other kind never does to telemetry: an arriving record that finds

 * the queue full evicts the oldest telemetry before anything else. Telemetry that is evicted, expires, or that MFM

 * rejects is counted per package under `t:`, never as a coverage gap, and the reporter sends it as `telemetry_loss`.

 *

 * MMKV can list keys only by listing all of them, so the first call for a partition in a process scans the store

 * once, repairs the index if a crash left it behind, and keeps the partition's ordered record keys in memory.

 * After that every call costs in proportion to its own work: an enqueue is two writes (three at capacity), and

 * no call touches another partition's records. Because that list is the queue's view of the store, one queue

 * owns a store: `createFleetQueue()` returns the app's shared queue, and tests build theirs over a store of

 * their own.

 *

 * Writes are ordered so that a crash errs toward reporting a loss twice rather than never: a loss is recorded

 * before the record it describes is removed, and the index is written last and rebuilt from the records if it is

 * missing or stale.

 *

 * Logout spares this store, so an account that signs out and never returns leaves its partition behind.

 * `sweepExpired` is how the 7-day bound still holds for it: one scan finds every partition, expires its old

 * records and removes what an empty partition no longer needs.

 */
import {FLEET_LIMITS, FLEET_TELEMETRY_LIMITS, type FleetRecord} from "@mentra/cloud-protocol"
import {normalizeCoreUrl} from "./coreUrl"
import {getFleetStore} from "./fleetStorage"
import {sha256HexOfText, utf8ByteLength} from "./utf8"

/** The subset of an MMKV instance the queue uses; tests pass an in-memory Map-backed implementation. */
export interface FleetKeyValueStore {
  getString(key: string): string | undefined
  set(key: string, value: string): void
  remove(key: string): void
  getAllKeys(): string[]
}

/** What the queue lost since the last `takeLosses`, and the span of observation time it covers. */
export interface FleetLosses {
  /** Records discarded because the queue was full (or could not be read or written). */
  dropped: number
  /** Records discarded because they were older than the queue's maximum age. */
  expired: number
  /** The earliest `observedAt` among the lost records, or null if none had a readable one. */
  from: string | null
  /** The latest `observedAt` among the lost records, or null if none had a readable one. */
  to: string | null
}

/** The telemetry the queue (or the Mentra App's limits) lost, per package, since the last `takeTelemetryLosses`. */
export interface FleetTelemetryLosses {
  packages: Record<string, {overLimit: number; evicted: number; expired: number; rejected: number}>
  from: string | null
  to: string | null
}
export type FleetTelemetryLossKind = "overLimit" | "evicted" | "expired" | "rejected"

/** A telemetry record's ID starts with this, so the queue tells telemetry from the rest by its key. */
export const TELEMETRY_RECORD_PREFIX = "tel."
export const isTelemetryRecordId = (recordId: string) => recordId.startsWith(TELEMETRY_RECORD_PREFIX)

/** A partition is one account on one Core. */
export interface FleetQueue {
  /** Adds a record. Drops the oldest beyond 10,000 and counts the drop. Never throws: a record that cannot be stored is counted as dropped. */
  enqueue(partition: string, record: FleetRecord): void
  /**

   * Up to `maxRecords` records, oldest first, whose own JSON (UTF-8 bytes, as serialized in the batch) adds up to

   * at most `maxBytes`. `maxBytes` is the caller's budget for the records themselves; the caller leaves headroom

   * for the envelope and the commas. The oldest record is always offered even if it alone exceeds `maxBytes`, so

   * one oversize record cannot block the queue; the server rejects it and the caller removes it. Records stay

   * queued until `remove`.

   */
  nextBatch(partition: string, maxRecords: number, maxBytes: number): FleetRecord[]
  /** Removes the records with these IDs. IDs that are not queued are ignored. */
  remove(partition: string, recordIds: string[]): void
  /**

   * Drops records older than 7 days, then returns the drops and expiries since the last call, with the span of

   * `observedAt` they cover, and resets the counters. The caller turns a non-zero result into a coverage gap and

   * should enqueue it straight away: the counters are cleared by this call.

   */
  takeLosses(partition: string, now: number): FleetLosses
  /**

   * Enforces the 7-day bound on every partition in the store, including those of accounts that signed out and

   * never came back (nothing else visits them, and logout spares this store). One scan finds the partitions; for

   * each, records older than 7 days are dropped and counted exactly as `takeLosses` counts expiries, so an

   * account that does return still gets its coverage gap. A partition left with no records loses its index and

   * sequence counters, and its loss counters too once they are themselves older than 7 days: a gap report that

   * old, for an account that never returned, can never be delivered. Never throws.

   *

   * The reporter calls this at start, and then at most hourly from its upload loop (only when an upload is due, so

   * an idle reporter does not wake to sweep). `now` defaults to the queue's clock.

   */
  sweepExpired(now?: number): void
  /** Counts `count` of `packageName`'s telemetry as lost, as of `at` (epoch ms). Never throws. */
  noteTelemetryLoss(partition: string, packageName: string, kind: FleetTelemetryLossKind, count: number, at?: number): void
  /** The telemetry lost since the last call, per package, and resets the counters; `null` when nothing was lost. */
  takeTelemetryLosses(partition: string, now: number): FleetTelemetryLosses | null
  /** Forgets everything held for the partition: records, losses and sequence counters. */
  clearPartition(partition: string): void
  size(partition: string): number
  /** The next sequence number for a collector session, counting up from 0 and persisted. */
  nextSequence(partition: string, collectorSessionId: string): number
}

export interface FleetQueueOptions {
  /** The clock that stamps `enqueuedAt`. Defaults to `Date.now`. */
  now?: () => number
}

const SEQUENCE_WIDTH = 16
const MAX_TRACKED_COLLECTOR_SESSIONS = 16

/** The losses as stored: the counters plus when they last changed, which tells a sweep when they are too old to matter. */
interface LossRecord extends FleetLosses {
  updatedAt: number
}
const EMPTY_LOSSES: LossRecord = {dropped: 0, expired: 0, from: null, to: null, updatedAt: 0}

/** The partition for an account on a Core: sha256 hex of `${normalizedCoreUrl}|${mentraUserId}`. */
export function partitionKey(coreUrl: string, mentraUserId: string): string {
  const core = normalizeCoreUrl(coreUrl)
  if (core === "" || mentraUserId.trim() === "") throw new Error("A Fleet partition needs a Core URL and an account")
  return sha256HexOfText(`${core}|${mentraUserId}`)
}

interface StoredEntry {
  enqueuedAt: number
  record: FleetRecord
}

interface PartitionIndex {
  count: number
  nextSeq: number
  oldest: string | null
  newest: string | null
}

interface PartitionState {
  /** The partition's record keys in queue order. */
  keys: string[]
  nextSeq: number
}

type LossKind = "dropped" | "expired"

const recordPrefix = (partition: string) => `q:${partition}:`
const indexKey = (partition: string) => `i:${partition}`
const lossKey = (partition: string) => `l:${partition}`
const sequenceKey = (partition: string) => `n:${partition}`
const telemetryLossKey = (partition: string) => `t:${partition}`

function recordKey(partition: string, sequence: number, recordId: string): string {
  return `${recordPrefix(partition)}${String(sequence).padStart(SEQUENCE_WIDTH, "0")}:${recordId}`
}

function isRecordKey(key: string, prefix: string): boolean {
  if (!key.startsWith(prefix)) return false
  for (let offset = 0; offset < SEQUENCE_WIDTH; offset += 1) {
    const code = key.charCodeAt(prefix.length + offset)
    if (!(code >= 48 && code <= 57)) return false
  }
  return key.charCodeAt(prefix.length + SEQUENCE_WIDTH) === 58
}

function isCount(value: unknown): value is number {
  return typeof value === "number" && Number.isInteger(value) && value >= 0
}

function describe(error: unknown): string {
  return error instanceof Error ? error.message : String(error)
}

function warn(message: string, error: unknown): void {
  // Never log record content: only what failed.
  console.warn(`[FleetQueue] ${message}: ${describe(error)}`)
}

function parseTime(value: string | null): number {
  return value === null ? Number.NaN : Date.parse(value)
}

function earlier(a: string | null, b: string | null): string | null {
  if (Number.isNaN(parseTime(a))) return Number.isNaN(parseTime(b)) ? null : b
  if (Number.isNaN(parseTime(b))) return a
  return parseTime(b) < parseTime(a) ? b : a
}

function later(a: string | null, b: string | null): string | null {
  if (Number.isNaN(parseTime(a))) return Number.isNaN(parseTime(b)) ? null : b
  if (Number.isNaN(parseTime(b))) return a
  return parseTime(b) > parseTime(a) ? b : a
}

function mergeLosses(a: LossRecord, b: LossRecord): LossRecord {
  return {
    dropped: a.dropped + b.dropped,
    expired: a.expired + b.expired,
    from: earlier(a.from, b.from),
    to: later(a.to, b.to),
    updatedAt: Math.max(a.updatedAt, b.updatedAt),
  }
}

function lossesOf(kind: LossKind, observedAts: Array<string | undefined>, updatedAt: number): LossRecord {
  let from: string | null = null
  let to: string | null = null
  for (const observedAt of observedAts) {
    if (observedAt === undefined) continue
    from = earlier(from, observedAt)
    to = later(to, observedAt)
  }
  return {
    dropped: kind === "dropped" ? observedAts.length : 0,
    expired: kind === "expired" ? observedAts.length : 0,
    from,
    to,
    updatedAt,
  }
}

/** What a scan of the store found for one partition. */
interface FoundPartition {
  records: string[]
  hasIndex: boolean
  hasLosses: boolean
  hasTelemetryLosses: boolean
  hasSequences: boolean
}

const RECORD_KEY_PARTITION = /^q:(.+?):\d{16}:/

/** Groups every Fleet queue key in the store by the partition it belongs to. */
function groupByPartition(keys: string[]): Map<string, FoundPartition> {
  const found = new Map<string, FoundPartition>()
  const entry = (partition: string): FoundPartition => {
    let existing = found.get(partition)
    if (!existing) {
      existing = {records: [], hasIndex: false, hasLosses: false, hasTelemetryLosses: false, hasSequences: false}
      found.set(partition, existing)
    }
    return existing
  }
  for (const key of keys) {
    if (key.startsWith("q:")) {
      const partition = RECORD_KEY_PARTITION.exec(key)?.[1]
      if (partition !== undefined) entry(partition).records.push(key)
    } else if (key.startsWith("i:")) entry(key.slice(2)).hasIndex = true
    else if (key.startsWith("l:")) entry(key.slice(2)).hasLosses = true
    else if (key.startsWith("n:")) entry(key.slice(2)).hasSequences = true
    else if (key.startsWith("t:")) entry(key.slice(2)).hasTelemetryLosses = true
  }
  return found
}

function buildQueue(store: FleetKeyValueStore, options: FleetQueueOptions): FleetQueue {
  const now = options.now ?? Date.now
  const states = new Map<string, PartitionState>()
  /** Losses that could not be written to the store; reported by the next `takeLosses` in this process. */
  const unpersistedLosses = new Map<string, LossRecord>()
  const sequences = new Map<string, Array<[string, number]>>()

  function readJson(key: string): unknown {
    try {
      const raw = store.getString(key)
      return raw === undefined ? null : JSON.parse(raw)
    } catch {
      return null
    }
  }

  function readIndex(partition: string): PartitionIndex | null {
    const value = readJson(indexKey(partition)) as Partial<PartitionIndex> | null
    if (!value || !isCount(value.count) || !isCount(value.nextSeq)) return null
    const oldest = typeof value.oldest === "string" ? value.oldest : null
    const newest = typeof value.newest === "string" ? value.newest : null
    return {count: value.count, nextSeq: value.nextSeq, oldest, newest}
  }

  function writeIndex(partition: string, state: PartitionState): void {
    const index: PartitionIndex = {
      count: state.keys.length,
      nextSeq: state.nextSeq,
      oldest: state.keys[0] ?? null,
      newest: state.keys[state.keys.length - 1] ?? null,
    }
    store.set(indexKey(partition), JSON.stringify(index))
  }

  function readEntry(key: string): StoredEntry | null {
    const value = readJson(key) as Partial<StoredEntry> | null
    const record = value?.record as Partial<FleetRecord> | undefined
    if (!value || typeof value.enqueuedAt !== "number" || !record || typeof record.recordId !== "string") return null
    return value as StoredEntry
  }

  function readLosses(partition: string): LossRecord | null {
    const value = readJson(lossKey(partition)) as Partial<LossRecord> | null
    if (!value || !isCount(value.dropped) || !isCount(value.expired)) return null
    return {
      dropped: value.dropped,
      expired: value.expired,
      from: typeof value.from === "string" ? value.from : null,
      to: typeof value.to === "string" ? value.to : null,
      updatedAt: isCount(value.updatedAt) ? value.updatedAt : 0,
    }
  }

  /** Removes a key. A key that will not go is logged, not thrown: the queue has already moved on in memory. */
  function removeKey(key: string): void {
    try {
      store.remove(key)
    } catch (error) {
      warn("could not remove a key", error)
    }
  }

  /** Writes the index. A failed write is logged, not thrown: the next load rebuilds the index from the records. */
  function persistIndex(partition: string, state: PartitionState): void {
    try {
      writeIndex(partition, state)
    } catch (error) {
      warn("could not update the index", error)
    }
  }

  /** Counts losses, in the store if it will take them, otherwise in memory. */
  function noteLosses(

    partition: string,

    kind: LossKind,

    observedAts: Array<string | undefined>,

    at: number = now(),

  ): void {
    if (observedAts.length === 0) return
    const delta = lossesOf(kind, observedAts, at)
    try {
      store.set(lossKey(partition), JSON.stringify(mergeLosses(readLosses(partition) ?? EMPTY_LOSSES, delta)))
    } catch (error) {
      warn("could not persist a loss count", error)
      unpersistedLosses.set(partition, mergeLosses(unpersistedLosses.get(partition) ?? EMPTY_LOSSES, delta))
    }
  }

  /** The partition's state from its record keys, repairing the index if a crash left it behind. */
  function stateFrom(partition: string, recordKeys: string[]): PartitionState {
    const prefix = recordPrefix(partition)
    const keys = [...recordKeys].sort()
    const index = readIndex(partition)
    const lastKey = keys[keys.length - 1]
    const lastSequence =
      lastKey === undefined ? -1 : Number(lastKey.slice(prefix.length, prefix.length + SEQUENCE_WIDTH))
    const state: PartitionState = {keys, nextSeq: Math.max(index?.nextSeq ?? 0, lastSequence + 1)}
    const inStep =
      index !== null &&
      index.count === keys.length &&
      index.nextSeq === state.nextSeq &&
      index.oldest === (keys[0] ?? null) &&
      index.newest === (lastKey ?? null)
    if (!inStep && (keys.length > 0 || index !== null)) persistIndex(partition, state)
    return state
  }

  /** The partition's records, read from the store the first time the process asks. */
  function load(partition: string): PartitionState {
    const loaded = states.get(partition)
    if (loaded) return loaded
    const prefix = recordPrefix(partition)
    const state = stateFrom(
      partition,
      store.getAllKeys().filter((key) => isRecordKey(key, prefix)),
    )
    states.set(partition, state)
    return state
  }

  /** Removes the first `count` records of the partition (they are already counted as lost). */
  function removeOldest(state: PartitionState, count: number): void {
    for (const key of state.keys.splice(0, count)) removeKey(key)
  }

  /** Discards records that cannot be read, counting them as dropped. */
  function discardUnreadable(partition: string, state: PartitionState, unreadable: string[]): void {
    // An unreadable telemetry record names no miniapp to count it for, and is never a coverage gap.
    noteLosses(
      partition,
      "dropped",
      unreadable.filter((key) => !isTelemetryKey(partition, key)).map(() => undefined),
    )
    const gone = new Set(unreadable)
    for (const key of unreadable) removeKey(key)
    state.keys = state.keys.filter((key) => !gone.has(key))
    persistIndex(partition, state)
  }

  const idOffsetOf = (partition: string) => recordPrefix(partition).length + SEQUENCE_WIDTH + 1
  const isTelemetryKey = (partition: string, key: string) => isTelemetryRecordId(key.slice(idOffsetOf(partition)))

  /** Removes the telemetry record at `key`, counting it as `kind` for its package. */
  function evictTelemetry(partition: string, state: PartitionState, key: string, kind: "evicted" | "expired", at: number = now()): void {
    const record = readEntry(key)?.record
    const packageName = record?.kind === "telemetry_event" ? record.payload.packageName : null
    if (packageName !== null) noteTelemetryLoss(partition, packageName, kind, 1, at, record!.observedAt)
    state.keys.splice(state.keys.indexOf(key), 1)
    removeKey(key)
  }

  /**

   * Keeps the partition inside its places: telemetry inside its share, and the whole inside 10,000, the oldest

   * telemetry going first. Only a queue full of other records drops the oldest record of all, as a coverage gap.

   */
  function trimToCapacity(partition: string, state: PartitionState): void {
    const telemetry = state.keys.filter((key) => isTelemetryKey(partition, key))
    while (telemetry.length > FLEET_TELEMETRY_LIMITS.queueShare) evictTelemetry(partition, state, telemetry.shift()!, "evicted")
    while (state.keys.length > FLEET_LIMITS.phoneQueueMaxRecords && telemetry.length > 0) evictTelemetry(partition, state, telemetry.shift()!, "evicted")
    const excess = state.keys.length - FLEET_LIMITS.phoneQueueMaxRecords
    if (excess <= 0) return
    const observedAts = state.keys.slice(0, excess).map((key) => readEntry(key)?.record.observedAt)
    noteLosses(partition, "dropped", observedAts)
    removeOldest(state, excess)
  }

  function readTelemetryLosses(partition: string): (FleetTelemetryLosses & {updatedAt: number}) | null {
    const value = readJson(telemetryLossKey(partition)) as (FleetTelemetryLosses & {updatedAt: number}) | null
    return value && typeof value === "object" && value.packages && typeof value.packages === "object" ? value : null
  }

  function noteTelemetryLoss(partition: string, packageName: string, kind: FleetTelemetryLossKind, count: number, at: number = now(), observedAt?: string): void {
    if (!(count > 0)) return
    try {
      const stored = readTelemetryLosses(partition) ?? {packages: {}, from: null, to: null, updatedAt: at}
      const entry = stored.packages[packageName] ?? {overLimit: 0, evicted: 0, expired: 0, rejected: 0}
      entry[kind] += count
      stored.packages[packageName] = entry
      const when = observedAt ?? new Date(at).toISOString()
      stored.from = earlier(stored.from, when)
      stored.to = later(stored.to, when)
      stored.updatedAt = at
      store.set(telemetryLossKey(partition), JSON.stringify(stored))
    } catch (error) {
      // Telemetry losses are best effort: a count that cannot be stored is lost with the events it counted.
      warn("could not persist a telemetry loss count", error)
    }
  }

  function expire(partition: string, state: PartitionState, at: number): void {
    const cutoff = at - FLEET_LIMITS.phoneQueueMaxAgeMs
    const expired: Array<string | undefined> = []
    const unreadable: Array<undefined> = []
    let head = 0
    // Records are in enqueue order, so the expired ones are a prefix of the queue. If the wall clock was stepped back,
    // a young record can sit ahead of older ones; those wait until it ages out, which only delays their expiry.
    for (; head < state.keys.length; head += 1) {
      const entry = readEntry(state.keys[head])
      if (entry === null) {
        if (!isTelemetryKey(partition, state.keys[head]!)) unreadable.push(undefined)
      } else if (entry.enqueuedAt < cutoff) {
        // Expired telemetry is counted per package, never as a coverage gap.
        if (entry.record.kind === "telemetry_event") {
          noteTelemetryLoss(partition, entry.record.payload.packageName, "expired", 1, at, entry.record.observedAt)
        } else expired.push(entry.record.observedAt)
      } else break
    }
    if (head === 0) return
    noteLosses(partition, "expired", expired, at)
    noteLosses(partition, "dropped", unreadable, at)
    removeOldest(state, head)
    persistIndex(partition, state)
  }

  /** Expires a partition's old records, then clears out what an empty partition no longer needs. */
  function sweepPartition(partition: string, found: FoundPartition, at: number): void {
    const state = states.get(partition) ?? stateFrom(partition, found.records)
    expire(partition, state, at)
    if (state.keys.length > 0) return
    if (found.hasIndex) removeKey(indexKey(partition))
    if (found.hasSequences) removeKey(sequenceKey(partition))
    if (found.hasLosses) {
      const losses = readLosses(partition)
      if (losses === null || at - losses.updatedAt > FLEET_LIMITS.phoneQueueMaxAgeMs) removeKey(lossKey(partition))
    }
    if (found.hasTelemetryLosses) {
      const losses = readTelemetryLosses(partition)
      if (losses === null || at - losses.updatedAt > FLEET_LIMITS.phoneQueueMaxAgeMs) removeKey(telemetryLossKey(partition))
    }
  }

  function loadSequences(partition: string): Array<[string, number]> {
    const cached = sequences.get(partition)
    if (cached) return cached
    const stored = readJson(sequenceKey(partition))
    const counters = (Array.isArray(stored) ? stored : []).filter(
      (item): item is [string, number] => Array.isArray(item) && typeof item[0] === "string" && isCount(item[1]),
    )
    sequences.set(partition, counters)
    return counters
  }

  return {
    enqueue(partition, record) {
      let state: PartitionState
      try {
        state = load(partition)
        const key = recordKey(partition, state.nextSeq, record.recordId)
        store.set(key, JSON.stringify({enqueuedAt: now(), record}))
        state.keys.push(key)
        state.nextSeq += 1
      } catch (error) {
        warn("could not store a record", error)
        // Telemetry that cannot be stored is its miniapp's loss, never a coverage gap.
        if (record?.kind === "telemetry_event") noteTelemetryLoss(partition, record.payload.packageName, "evicted", 1, now(), record.observedAt)
        else noteLosses(partition, "dropped", [record?.observedAt])
        return
      }
      trimToCapacity(partition, state)
      persistIndex(partition, state)
    },

    nextBatch(partition, maxRecords, maxBytes) {
      if (!(maxRecords >= 1)) return []
      const state = load(partition)
      const batch: FleetRecord[] = []
      const unreadable: string[] = []
      let bytes = 0
      for (const key of state.keys) {
        if (batch.length >= maxRecords) break
        const entry = readEntry(key)
        if (entry === null) {
          unreadable.push(key)
          continue
        }
        const size = utf8ByteLength(JSON.stringify(entry.record))
        if (batch.length > 0 && !(bytes + size <= maxBytes)) break
        batch.push(entry.record)
        bytes += size
      }
      if (unreadable.length > 0) discardUnreadable(partition, state, unreadable)
      return batch
    },

    remove(partition, recordIds) {
      if (recordIds.length === 0) return
      const state = load(partition)
      const wanted = new Set(recordIds)
      const idOffset = recordPrefix(partition).length + SEQUENCE_WIDTH + 1
      const kept: string[] = []
      for (const key of state.keys) {
        if (wanted.has(key.slice(idOffset))) removeKey(key)
        else kept.push(key)
      }
      if (kept.length === state.keys.length) return
      state.keys = kept
      persistIndex(partition, state)
    },

    takeLosses(partition, at) {
      expire(partition, load(partition), at)
      const losses = mergeLosses(
        readLosses(partition) ?? EMPTY_LOSSES,
        unpersistedLosses.get(partition) ?? EMPTY_LOSSES,
      )
      if (losses.dropped === 0 && losses.expired === 0) return {dropped: 0, expired: 0, from: null, to: null}
      // If the counters will not go they are reported again next time, which is better than never.
      removeKey(lossKey(partition))
      unpersistedLosses.delete(partition)
      return {dropped: losses.dropped, expired: losses.expired, from: losses.from, to: losses.to}
    },

    sweepExpired(at = now()) {
      try {
        for (const [partition, found] of groupByPartition(store.getAllKeys())) {
          try {
            sweepPartition(partition, found, at)
          } catch (error) {
            warn("could not sweep a partition", error)
          }
        }
        // Counts that never reached the store go with the process; forget the ones too old to report.
        for (const [partition, losses] of unpersistedLosses) {
          if (at - losses.updatedAt > FLEET_LIMITS.phoneQueueMaxAgeMs) unpersistedLosses.delete(partition)
        }
      } catch (error) {
        warn("could not sweep expired records", error)
      }
    },

    noteTelemetryLoss(partition, packageName, kind, count, at) {
      noteTelemetryLoss(partition, packageName, kind, count, at)
    },

    takeTelemetryLosses(partition, at) {
      expire(partition, load(partition), at)
      const losses = readTelemetryLosses(partition)
      if (losses === null || Object.keys(losses.packages).length === 0) return null
      removeKey(telemetryLossKey(partition))
      return {packages: losses.packages, from: losses.from, to: losses.to}
    },

    clearPartition(partition) {
      const state = load(partition)
      for (const key of state.keys) removeKey(key)
      removeKey(indexKey(partition))
      removeKey(lossKey(partition))
      removeKey(telemetryLossKey(partition))
      removeKey(sequenceKey(partition))
      state.keys = []
      state.nextSeq = 0
      unpersistedLosses.delete(partition)
      sequences.delete(partition)
    },

    size(partition) {
      return load(partition).keys.length
    },

    nextSequence(partition, collectorSessionId) {
      const counters = loadSequences(partition)
      const position = counters.findIndex(([id]) => id === collectorSessionId)
      const next = position >= 0 ? counters[position][1] : 0
      if (position >= 0) counters.splice(position, 1)
      counters.push([collectorSessionId, next + 1])
      while (counters.length > MAX_TRACKED_COLLECTOR_SESSIONS) counters.shift()
      try {
        store.set(sequenceKey(partition), JSON.stringify(counters))
      } catch (error) {
        // The counter still increases for the life of this process.
        warn("could not persist a sequence counter", error)
      }
      return next
    },
  }
}

let sharedQueue: FleetQueue | undefined

/**

 * Without a store, the app's one shared queue over the `mentra-fleet` MMKV instance. A queue keeps its view of a

 * store in memory, so two queues over one store would not see each other's writes; share this one.

 *

 * With a store (tests), a new queue over it. `options` apply only then.

 */
export function createFleetQueue(store?: FleetKeyValueStore, options: FleetQueueOptions = {}): FleetQueue {
  if (store === undefined) return (sharedQueue ??= buildQueue(getFleetStore(), {}))
  return buildQueue(store, options)
}