Eliminate O(N×L) live-metadata JSON.stringify and sequential full-archive scans in cosAgentStorage

Aperta
#19,064 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
35/100
Tipo di issue
Refactoring
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
javascript, nodejs

Direzione di ricerca

Start in server/services/cos/cosAgentStorage.js: read inspect(), previewAgentStorage(), runAutomaticAgentStorage() and revalidate(), then trace the callers in server/services/cos/cos.js (around line 413) and server/routes/dataManager.js (line 29). Run server/services/cos/cosAgentStorage.test.js before and after. Done when live metadata is serialized once per scan, metadata.json is statted once per run, and the automatic path stops at the limit with exact interactive totals.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

area:cos-agents effort:medium model:medium performance performance-efficiency plan planner:gemini-4-neon source:performance-efficiency

Audit slice: server/services/cos (re-verification of 2026-11-24 performance-efficiency slice) — Date: 2026-11-26
Scope: medium

Problem

The hourly cos-recording-maintenance job (server/services/cos/cos.js:413-420) calls runAutomaticAgentStorage(), and POST /api/data-manager/agent-storage/preview (server/routes/dataManager.js:29) calls previewAgentStorage(). In server/services/cos/cosAgentStorage.js:

  1. O(N × L) repeated JSON.stringify of live agent metadata (cosAgentStorage.js:147): Inside inspect(), every archived agent evaluates:
    Object.values(state.agents).some(agent => JSON.stringify(agent.metadata || {}).includes(id))
    Across N archived runs and L live agents, a single scan performs N × L full JSON.stringify serializations of every live agent's metadata object.
  2. Sequential full-archive filesystem traversal with redundant syscalls (cosAgentStorage.js:122-169, :204-224): previewAgentStorage() awaits inspect(date, id, ...) serially for every archived run on disk. Each inspect() call performs 10–11 sequential syscalls:
    • safeDirectory() (:122-128) re-runs lstat(AGENTS_DIR) and lstat(join(AGENTS_DIR, date)) for every single run even though locators() just enumerated those directories with withFileTypes: true.
    • json(metadata.json) (:131) calls lstat + readFile on metadata.json, and line :137 calls lstat(join(dir, 'metadata.json')) a second time.
    • The independent lstat calls for raw.txt, raw.txt.gz, output.txt, prompt.txt, and raw-storage.json (:132-137) run sequentially instead of in parallel.
  3. Unbounded full-disk scans during hourly automatic maintenance (cosAgentStorage.js:351-362): runAutomaticAgentStorage() only requests limit: 25 candidates and ignores totals, reasons, rows, and models, yet previewAgentStorage() still scans every archived run on disk — including date buckets newer than olderThanDays and all runs after 25 eligible candidates are already found. When both autoPurge and autoCompress are enabled and no purge candidates exist, runAutomaticAgentStorage() runs the full sequential scan twice back-to-back (:356 and :359).
  4. Repeated state.json reads during batch execution (cosAgentStorage.js:301-315): revalidate() calls inspect() without liveState twice per candidate (once before calling compress/purge, and again inside withStateLock), re-reading state.json and re-stringifying all live agents' metadata up to 50 times per 25-item batch.

Impact

On installs with thousands of archived CoS runs, every hourly cos-recording-maintenance tick (and every Data Manager storage preview request) executes tens of thousands of sequential filesystem syscalls and hundreds of thousands of redundant JSON.stringify() calls on the main Node event loop, causing recurring CPU and disk I/O spikes.

Fix

Update server/services/cos/cosAgentStorage.js (and cover in server/services/cos/cosAgentStorage.test.js):

  1. Precompute live-agent reference haystack once per scan: Build a helper (e.g. buildLiveReferenceContext(liveState)) that computes liveMetadataStrings = Object.values(state.agents).map(agent => JSON.stringify(agent.metadata || {})) once per previewAgentStorage() call (and once per revalidate() call), passing it into inspect() so line :147 checks liveMetadataStrings.some(text => text.includes(id)) in O(1) serialization cost.
  2. Parallelize and deduplicate filesystem reads in inspect() and previewAgentStorage():
    • Reuse the lstat result from reading metadata.json instead of statting it a second time on :137.
    • Parallelize the independent lstat / readManifest calls inside inspect() via Promise.all.
    • When called from previewAgentStorage(), skip re-statting AGENTS_DIR and AGENTS_DIR/<date> on every agent (validate the parent directories once per bucket).
    • Process locator batches in previewAgentStorage() with bounded concurrency (e.g. mapWithConcurrency with concurrency 16, preserving deterministic date/id ordering for candidates and rows).
  3. Add an early-stop + date-cutoff fast path for runAutomaticAgentStorage():
    • Pass an internal option (e.g. { stopAtLimit: true }) from runAutomaticAgentStorage() to previewAgentStorage() so automatic runs skip date buckets strictly newer than now - (olderThanDays - 1) * DAY (leaving a 1-day UTC/local buffer so timezone/completion-time edge cases are never missed) and stop scanning once candidates.length >= limit.
    • Interactive POST /api/data-manager/agent-storage/preview keeps stopAtLimit: false so totals, reasons, rows, and models remain exact.

Acceptance Criteria

  • inspect() does not call JSON.stringify(agent.metadata || {}) per archived run when scanning in previewAgentStorage(); live agent metadata is serialized at most once per scan.
  • inspect() stats metadata.json at most once per run and runs independent artifact lstat/manifest reads in parallel via Promise.all.
  • previewAgentStorage() processes archived runs with bounded concurrency while preserving deterministic ordering and exact totals, reasons, rows, and models for interactive previews.
  • runAutomaticAgentStorage() skips date buckets newer than the retention threshold (with a safe day buffer) and stops scanning once limit eligible candidates are collected.
  • Existing and new unit tests in server/services/cos/cosAgentStorage.test.js pass, verifying eligibility, safety gates, live-reference detection, and early-stop behavior.
Lingua principale
JavaScript
Stelle
38
Fork
32
Merge medio
14m
PR unite (30g)
995

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di atomantic/PortOS

Tutte le issue di atomantic/PortOS

Issue simili

Altre issue su JavaScript

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.