nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

[Feature] Make the stats ledger flush asynchronous and avoid re-reading the ledger every time

Open addyCooks opened this issue 1 month ago • 5 comments

Summary

Every time usage stats are recorded, a debounced flush (400 ms) runs flushStatsLedgerSync(). It re-reads the whole stats.json (several existsSync calls, readFileSync, parse, normalise), merges, and writes it back (writeFileSync + rename), all synchronously on the event loop. A normal streamed turn triggers this about twice.

Steps to reproduce

  1. pnpm run build
  2. Save the script below as stats-sync.mjs and run DIST=/path/to/nanocoder/dist node stats-sync.mjs:
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {pathToFileURL} from 'node:url';
import {syncBuiltinESMExports} from 'node:module';
process.env.NANOCODER_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-stats-'));
const rec = await import(pathToFileURL(process.env.DIST + '/stats/record.js').href);
const calls = {};
for (const name of ['readFileSync', 'writeFileSync', 'existsSync', 'renameSync']) {
  const orig = fs[name];
  fs[name] = function (p, ...r) {
    if (/^stats\.json/.test(path.basename(String(p)))) calls[name] = (calls[name] || 0) + 1;
    return orig.call(this, p, ...r);
  };
}
syncBuiltinESMExports();
rec.recordUserPrompt('Ollama', 'qwen2.5-coder:7b');
await new Promise(r => setTimeout(r, 700));
console.log(JSON.stringify(calls));

Expected behaviour

No synchronous file I/O for stats on the event loop, and no re-read of a file the process already holds in memory.

Actual behaviour

{"existsSync":2,"readFileSync":1,"writeFileSync":1,"renameSync":1}

This is for one recorded prompt. In a real session of 3 streamed turns I counted 14 existsSync, 7 readFileSync, 6 writeFileSync and 6 renameSync. With 3 years of history seeded (203 KB, 1,095 days x 3 model pairs), one flush blocks for 7.8 ms on a warm SSD. That is small there; the pattern matters on slow or scanned disks (not measured).

Environment

  • OS: Windows 11 (10.0.26300)
  • Node: 22.22.3
  • Nanocoder: 1.31.0 (main at be428fc7)

Suggested fix

  • source/stats/record.ts:26,98-99,108 (FLUSH_DEBOUNCE_MS, flushStatsLedgerSync) and source/stats/storage.ts (readStatsLedger, resolveStatsReadPath with 3 existsSync).
  • Use fs.promises for the debounced flush, flush at turn end and at shutdown (the shutdown handler already exists), and collapse the three existsSync checks into one.
  • Keep merge-on-write: several nanocoder processes can share one ledger. Tests: source/stats/storage.spec.ts.

addyCooks avatar Oct 18 '26 06:10 addyCooks

hey @addyCooks i would like to work on this . can you assign it to me ?

harshillvashisht avatar Oct 18 '26 06:10 harshillvashisht

Go ahead @harshillvashisht !

addyCooks avatar Oct 18 '26 07:10 addyCooks

@addyCooks I've opened a draft PR for the first step: removing the existsSync probes and reading with ENOENT handling (PR link here). Before I start on the async flush, I have two scope questions:

  1. /stats calls flushStatsLedgerSync() inside a synchronous function. Is it OK to keep a sync flush for that and for the tests, and use the async one only for the debounced flush?
  2. Is skipping the per-flush re-read (a stat-based check) in scope for this issue, or should it be a follow-up? I'm keeping merge-on-write as it is for now.

In the meantime I'll carry on with the conservative approach (keep the sync function, keep the re-read).

Update: I'm sticking to the issue's suggested fix for the next PR: an async debounced flush using fs.promises, with flushStatsLedgerSync() kept as it is for tests and /stats, and merge-on-write unchanged. Skipping the per-flush re-read is out of scope for now. Let me know if you'd prefer otherwise.

harshillvashisht avatar Oct 18 '26 13:10 harshillvashisht

Thanks @harshillvashisht, your plan is fine.

  1. Yes, keep flushStatsLedgerSync() for /stats and the tests. Use the async path only for the debounced flush. Make sure /stats still sees the latest data, so don't let it read before a pending async flush has landed.
  2. Skipping the per-flush re-read is out of scope here. Keep merge-on-write as is, since several processes can share one ledger. We can open a follow-up for the re-read later.

Landing the existsSync cleanup (#1839) first and the async flush as a separate PR works well. Make sure the shutdown handler still flushes everything pending before exit.

addyCooks avatar Oct 19 '26 08:10 addyCooks

@addyCooks #1839 is still waiting on workflow approval (first PR here), so none of the checks have run. Can you approve it? The async flush is done on top of it and I'm holding it until this one lands.

harshillvashisht avatar Oct 28 '26 07:10 harshillvashisht