coach (built-in): #160 findings 4/5/6/11 — forget keeps today's count, the instance cap is reserved at enqueue from its own counter instead of the 100-entry log, forget drops queued work, aborts the HTTP call and discards a late result, scheduled reviews advance on the server's own record and wait for an unread proposal

This commit is contained in:
Boris Kurktchiev committed 2026-09-11 10:22:24 -04:00
1 parent 67a8e68e42
commit 6d9d7a6cba
9 files changed
+485 -18

No files matched your search

+16 -1
View File
@@ -18,10 +18,12 @@ const { attemptOnce } = await import('../coach/core/pipeline.js');
const { HTTP_PROVIDERS, validateBaseUrl } = await import('../coach/core/providers.js');
const { SYSTEM_PROMPT } = await import('../coach/core/system-prompt.js');
/** A fetch that records what it was asked and answers from a script. */
/** A fetch that records what it was asked and answers from a script. Like the real one, it
* refuses an already-aborted signal without putting anything on the wire. */
function fakeFetch(answers) {
const calls = [];
const f = async (url, init) => {
if (init.signal?.aborted) throw Object.assign(new Error('aborted'), { name: 'AbortError' });
calls.push({ url, method: init.method, headers: init.headers || {}, body: init.body ? JSON.parse(init.body) : null });
const a = typeof answers === 'function' ? answers(calls.length, url, init) : answers[Math.min(calls.length, answers.length) - 1];
if (a instanceof Error) throw a;
@@ -168,6 +170,19 @@ test('a transient status (429, 5xx, 529) is retried twice with the same request,
assert.equal(f.calls.length, 1);
});
test('an abort that lands during a retry pause sends nothing more and ends as a timeout', async () => {
// A forget mid-backoff: the payload must not go out a second time, and the job must drain
// now rather than wait for the next attempt to time out.
const ac = new AbortController();
const f = fakeFetch([{ status: 429, body: { error: { message: 'slow down' } } }]);
const p = openai.invoke({ cfg: {}, prompt: 'P', env, fetch: f, signal: ac.signal, retryDelayMs: 10000 });
await new Promise(r => setTimeout(r, 20)); // the first 429 is back and the pause has begun
ac.abort();
const r = await p;
assert.equal(f.calls.length, 1, 'the payload is not sent again');
assert.equal(r.timedOut, true);
});
test('a body that is not JSON on an error still yields a readable stderr', async () => {
const f = fakeFetch([{ status: 502, body: '<html>bad gateway</html>' }]);
const r = await gemini.invoke({ cfg: {}, prompt: 'P', env, fetch: f });
+227
View File
@@ -0,0 +1,227 @@
/* What bounds the Coach's spend, pinned against the real queue and the fixture provider.
*
* Forget keeps today's per-profile count. The instance count is reserved at enqueue and is
* not read off the capped job log. A scheduled review covers a batch of workouts once, on the
* workout's own clock rather than the phone's local date, and an answer the model was paid
* for counts as that review even when it was unusable. */
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { tempData, writeState, sampleState } from './helpers.mjs';
const DIR = tempData();
const cfg = await import('../coach/config.js');
const jobs = await import('../coach/jobs.js');
const cadence = await import('../coach/cadence.js');
const { forcePrivilegeVerdict } = await import('../coach/adapters/spawn.js');
cfg.save({ enabled: true, provider: 'fixture' });
forcePrivilegeVerdict({ ok: true, dropped: false, why: 'pinned by the test suite' });
const today = new Date().toISOString().slice(0, 10);
const userFile = uid => `${DIR}/coach/${uid}.json`;
async function settle(uid, ms = 15000) {
const until = Date.now() + ms;
while (Date.now() < until) {
const s = jobs.status(uid);
if (!s.job) return s;
await new Promise(r => setTimeout(r, 25));
}
throw new Error('job never finished');
}
const lastOutcome = uid => jobs.readUser(uid).history.at(-1);
/* ---------- the per-profile cap survives forget ---------- */
test('forgetting a profile does not hand it a fresh daily cap', async () => {
const uid = 'u-forget-cap';
writeState(DIR, uid, sampleState());
cfg.save({ caps: { perProfileDaily: 1, instanceDaily: 0 } });
try {
jobs.enqueue(uid, { kind: 'review' });
await settle(uid);
assert.equal(jobs.capState(uid).used, 1);
jobs.clearUser(uid);
const s = jobs.status(uid);
assert.equal(s.pending, null, 'the proposal is gone');
assert.deepEqual(jobs.readUser(uid).history, [], 'the history is gone');
assert.equal(s.cap.used, 1, 'the day\'s count is a spending record, not the profile\'s data');
assert.throws(() => jobs.enqueue(uid, { kind: 'review' }), e => e.code === 'cap');
} finally {
cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 0 } });
}
});
test('with nothing spent today, forget leaves no file at all', () => {
const uid = 'u-forget-empty';
jobs.setShare(uid, true);
assert.ok(fs.existsSync(userFile(uid)));
jobs.clearUser(uid);
assert.equal(fs.existsSync(userFile(uid)), false);
// Yesterday's count is already worth nothing to the cap, so it does not keep the file either.
fs.writeFileSync(userFile(uid), JSON.stringify({ daily: { date: '2000-01-01', count: 5 }, history: [] }));
jobs.clearUser(uid);
assert.equal(fs.existsSync(userFile(uid)), false);
});
/* ---------- the instance cap ---------- */
test('the instance cap is reserved at enqueue, so a job still running already counts', async () => {
cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 1 }, daily: null, log: [] });
try {
writeState(DIR, 'u-inst-1', sampleState());
writeState(DIR, 'u-inst-2', sampleState());
jobs.enqueue('u-inst-1', { kind: 'review' });
assert.ok(jobs.status('u-inst-1').job, 'the first job is on its way');
assert.throws(() => jobs.enqueue('u-inst-2', { kind: 'review' }), e => e.code === 'cap',
'the second profile is refused before the first job has finished');
await settle('u-inst-1');
assert.equal(lastOutcome('u-inst-1').outcome, 'ready');
assert.deepEqual(cfg.load().daily, { date: today, count: 1 });
} finally {
cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 0 } });
}
});
test('the instance count is not bounded by the length of the job log', () => {
const uid = 'u-inst-150';
writeState(DIR, uid, sampleState());
cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 150 }, daily: { date: today, count: 150 }, log: [] });
try {
assert.throws(() => jobs.enqueue(uid, { kind: 'review' }), e => e.code === 'cap',
'a hundred and fifty jobs today trip a cap of a hundred and fifty, empty log or not');
// Yesterday's count is nobody's business today.
cfg.save({ daily: { date: '2000-01-01', count: 150 } });
assert.doesNotThrow(() => jobs.enqueue(uid, { kind: 'review' }));
assert.deepEqual(cfg.load().daily, { date: today, count: 1 });
} finally {
cfg.save({ caps: { perProfileDaily: 10, instanceDaily: 0 } });
}
return settle(uid);
});
/* ---------- scheduled reviews ---------- */
/** startCadence arms a setInterval; take the callback so the tests can tick it by hand. */
function captureTick(deps) {
const real = globalThis.setInterval;
let fn = null;
globalThis.setInterval = f => { fn = f; return { unref() {} }; };
try { cadence.startCadence(deps); } finally { globalThis.setInterval = real; }
return fn;
}
// `end` lands a second past now, so the workout is after any review that has just finished.
const newWorkout = id => ({ ...sampleState().workouts[0], id, d: today, start: Date.now() - 60000, end: Date.now() + 1000 });
test('a scheduled review reads a batch of workouts once, not once per tick', async () => {
const uid = 'u-cadence';
const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });
writeState(DIR, uid, S);
const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });
process.env.FIXTURE_MODE = 'nochange';
try {
tick();
assert.ok(jobs.status(uid).job, 'the first tick queues a review');
tick();
await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'nochange');
assert.equal(lastOutcome(uid).trigger, 'scheduled');
// The phone never opened, so lastReview in the synced state is still unset — and the same
// workout must not be reviewed again on every tick until the daily cap is gone.
tick(); tick(); tick();
assert.equal(jobs.status(uid).job, null);
assert.equal(jobs.readUser(uid).history.length, 1);
assert.equal(jobs.capState(uid).used, 1);
// A new workout is new news.
S.workouts.push(newWorkout('w2'));
writeState(DIR, uid, S);
tick();
assert.ok(jobs.status(uid).job, 'a fresh workout is due');
await settle(uid);
assert.equal(jobs.readUser(uid).history.length, 2);
} finally {
delete process.env.FIXTURE_MODE;
}
});
test('a workout the phone dated tomorrow is not re-read once the review has covered it', async () => {
const uid = 'u-cadence-tz';
// The phone stamps `d` in its own timezone: a morning session in Tokyo already carries
// tomorrow's date by the server's UTC clock. Its `end` is on the clock the review is timed on.
const tomorrow = new Date(Date.now() + 86400000).toISOString().slice(0, 10);
const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });
S.workouts.push({ ...newWorkout('w-ahead'), d: tomorrow, start: Date.now() - 45 * 60000, end: Date.now() - 60000 });
writeState(DIR, uid, S);
const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });
process.env.FIXTURE_MODE = 'nochange';
try {
tick();
await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'nochange');
tick();
assert.equal(jobs.status(uid).job, null, 'the review already read that workout, whatever date the phone gave it');
assert.equal(jobs.readUser(uid).history.length, 1);
} finally {
delete process.env.FIXTURE_MODE;
}
});
test('an answer the model was paid for counts as the review, even when it was unusable', async () => {
const uid = 'u-cadence-unusable';
const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });
writeState(DIR, uid, S);
const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });
process.env.FIXTURE_MODE = 'invalid';
try {
tick();
await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'failed');
assert.equal(lastOutcome(uid).errorClass, 'unusable');
tick();
assert.equal(jobs.status(uid).job, null, 'the model read those workouts; sending them again pays twice for the same data');
assert.equal(jobs.capState(uid).used, 1);
// A call that never reached the model read nothing, so the same workouts are asked about again.
process.env.FIXTURE_MODE = 'crash';
S.workouts.push(newWorkout('w2'));
writeState(DIR, uid, S);
tick();
await settle(uid);
assert.equal(lastOutcome(uid).errorClass, 'provider');
tick();
assert.ok(jobs.status(uid).job, 'a provider that fell over is retried on the next tick');
await settle(uid);
} finally {
delete process.env.FIXTURE_MODE;
}
});
test('a proposal nobody has answered is not replaced by the next scheduled review', async () => {
const uid = 'u-cadence-pending';
const S = sampleState({ coach: { ...sampleState().coach, cadence: { everyWorkouts: 1 } } });
writeState(DIR, uid, S);
const tick = captureTick({ users: () => [{ id: uid }], userNow: () => ({ date: today, hhmm: '18:00', weekday: 4 }) });
tick();
const first = await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'ready');
assert.ok(first.pending, 'a proposal is waiting');
S.workouts.push(newWorkout('w2'));
writeState(DIR, uid, S);
tick();
assert.equal(jobs.status(uid).job, null, 'not while the proposal is unread');
assert.equal(jobs.status(uid).pending.id, first.pending.id, 'the unread proposal is still the same one');
// Once it is answered, the workout logged since is due.
jobs.resolvePending(uid, { dismissed: true });
tick();
assert.ok(jobs.status(uid).job, 'the workout since the last review is due');
await settle(uid);
assert.equal(jobs.readUser(uid).history.filter(h => h.outcome === 'ready').length, 2);
});
+7
View File
@@ -101,3 +101,10 @@ test('the admin switch decides whether the prompt ever sees a cohort', () => {
assert.equal(cohort.cohortForPayload('a'), null);
cfg.save({ community: true });
});
test('forgetting a profile takes it out of the room at once, cache or no cache', () => {
assert.equal(cohort.computeCohort('a').people, 4);
jobs.clearUser('b');
assert.equal(jobs.isSharing('b'), false);
assert.equal(cohort.computeCohort('a').people, 3);
});
+159
View File
@@ -115,6 +115,165 @@ test('forgetting a profile leaves no server-side residue', async () => {
assert.deepEqual(jobs.readUser(uid).history, []);
});
/* ---------- forget while a job is live ----------
A provider on localhost that parks every request until the test lets it answer, so a job
can be caught mid-call or still waiting for a slot. */
async function holdingProvider() {
const http = await import('node:http');
const held = [], seen = [];
const server = http.createServer((req, res) => {
let body = '';
req.on('data', c => { body += c; });
req.on('end', () => { seen.push(JSON.parse(body || '{}')); held.push(res); });
// A caller that hangs up mid-call takes its parked response with it.
res.on('close', () => { const i = held.indexOf(res); if (i >= 0) held.splice(i, 1); });
});
await new Promise(r => server.listen(0, '127.0.0.1', r));
/** Exactly n requests parked with the provider — 0 means every caller has gone. */
const until = async n => {
const t = Date.now() + 15000;
while (held.length !== n && Date.now() < t) await new Promise(r => setTimeout(r, 25));
assert.equal(held.length, n, `${n} request(s) with the provider`);
};
const answer = content => {
for (const res of held.splice(0)) {
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ choices: [{ finish_reason: 'stop', message: { content } }] }));
}
};
const use = () => cfg.save({ enabled: true, provider: 'compatible', providerOptions: { compatible: { baseUrl: `http://127.0.0.1:${server.address().port}` } }, models: { compatible: 'local-model' } });
// Parked responses hold their sockets open; a failing test must not hold node --test with them.
const close = () => { cfg.save({ provider: 'fixture' }); server.close(); server.closeAllConnections(); };
return { seen, held, until, answer, use, close };
}
const NOCHANGE = '{"coach_contract":1,"nochange":true,"reading":"Steady."}';
/** The job's own end, as opposed to status() going quiet: the instance log gains its line. */
async function logged(n) {
const t = Date.now() + 15000;
while (cfg.load().log.length < n && Date.now() < t) await new Promise(r => setTimeout(r, 25));
assert.equal(cfg.load().log.length, n);
}
test('forgetting a profile mid-job cancels the call and frees its slot at once', async () => {
const p = await holdingProvider();
const notified = [];
jobs.setProposalHook(uid => notified.push(uid));
try {
p.use();
const uid = 'u-forget-live';
writeState(DIR, uid, sampleState());
jobs.enqueue(uid, { kind: 'review' });
await p.until(1);
assert.equal(jobs.status(uid).job.state, 'running');
const before = cfg.load().log.length;
const t0 = Date.now();
jobs.clearUser(uid);
assert.equal(jobs.status(uid).job, null);
// The provider is never answered: the call goes with the record, so the job drains now
// rather than when the provider gets round to it or the five-minute timeout does.
await logged(before + 1);
assert.ok(Date.now() - t0 < 5000, `drained in ${Date.now() - t0} ms`);
await p.until(0);
assert.equal(cfg.load().log.at(-1).outcome, 'failed', 'the job ran and is counted');
assert.equal(cfg.load().log.at(-1).errorClass, 'forgotten', 'the log names the cancellation, not a provider timeout');
assert.deepEqual(jobs.readUser(uid).pending, null, 'nothing is held for someone who asked to be forgotten');
assert.deepEqual(jobs.readUser(uid).history, [], 'the record is not recreated');
assert.deepEqual(notified, [], 'nobody is told about it');
assert.equal(jobs.capState(uid).used, 1);
// Single-flight went with the job: the profile can ask again straight away, not once the
// provider hold is over.
assert.doesNotThrow(() => jobs.enqueue(uid, { kind: 'review' }), 'the slot is free again');
await p.until(1);
p.answer(NOCHANGE);
await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'nochange');
} finally {
jobs.setProposalHook(null);
p.close();
}
});
test('a runtime that cannot be cancelled still has its late answer discarded after a forget', async () => {
// The fixture CLI is a child process, and the abort signal means nothing to one: it runs to
// its answer, which then has nobody to belong to.
const uid = 'u-forget-spawned';
writeState(DIR, uid, sampleState());
const notified = [];
jobs.setProposalHook(u => notified.push(u));
try {
jobs.enqueue(uid, { kind: 'review' });
assert.equal(jobs.status(uid).job.state, 'running');
jobs.clearUser(uid);
// The line this job writes to the instance log, not the next line anyone writes there.
const mine = () => cfg.load().log.find(e => e.uid === uid);
for (const t = Date.now() + 15000; !mine() && Date.now() < t;) await new Promise(r => setTimeout(r, 25));
assert.equal(mine()?.outcome, 'ready', 'the job ran to its answer and is counted');
assert.deepEqual(jobs.readUser(uid).pending, null, 'the proposal is not held for someone who asked to be forgotten');
assert.deepEqual(jobs.readUser(uid).history, []);
assert.deepEqual(notified, [], 'nobody is told about it');
} finally {
jobs.setProposalHook(null);
}
});
test('forgetting a profile whose job is still queued drops it before anything leaves', async () => {
const p = await holdingProvider();
try {
p.use();
// Two other profiles hold both execution slots, so the third waits.
for (const u of ['u-slot-1', 'u-slot-2']) { writeState(DIR, u, sampleState()); jobs.enqueue(u, { kind: 'review' }); }
await p.until(2);
const uid = 'u-forget-queued';
writeState(DIR, uid, sampleState());
jobs.enqueue(uid, { kind: 'review' });
assert.equal(jobs.status(uid).job.state, 'queued');
jobs.clearUser(uid);
assert.equal(jobs.status(uid).job, null);
p.answer(NOCHANGE);
await settle('u-slot-1'); await settle('u-slot-2');
await new Promise(r => setTimeout(r, 200)); // a job still queued would have started by now
assert.equal(p.seen.length, 2, 'the forgotten profile\'s payload never reached the provider');
assert.equal(jobs.status(uid).job, null);
assert.deepEqual(jobs.readUser(uid).history, []);
// Single-flight was released with the job, so the profile can ask again.
jobs.enqueue(uid, { kind: 'review' });
await p.until(1);
p.answer(NOCHANGE);
await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'nochange');
} finally { p.close(); }
});
test('consent withdrawn, or the Coach switched off, while a job waits: no payload leaves', async () => {
const p = await holdingProvider();
try {
p.use();
for (const u of ['u-slot-3', 'u-slot-4']) { writeState(DIR, u, sampleState()); jobs.enqueue(u, { kind: 'review' }); }
await p.until(2);
writeState(DIR, 'u-revoked', sampleState());
writeState(DIR, 'u-switched-off', sampleState());
jobs.enqueue('u-revoked', { kind: 'review' });
jobs.enqueue('u-switched-off', { kind: 'review' });
assert.equal(jobs.status('u-switched-off').job.state, 'queued');
// Consent gone from the synced state — no forget call, so the record itself stays and says
// what happened. Then the admin switches the Coach off before a slot frees.
writeState(DIR, 'u-revoked', sampleState({ coach: {} }));
cfg.save({ enabled: false });
p.answer(NOCHANGE);
await settle('u-revoked'); await settle('u-switched-off');
assert.equal(p.seen.length, 2, 'neither queued job reached the provider');
assert.equal(lastOutcome('u-revoked').outcome, 'failed');
assert.equal(lastOutcome('u-revoked').errorClass, 'consent');
assert.equal(lastOutcome('u-switched-off').outcome, 'failed');
assert.equal(lastOutcome('u-switched-off').errorClass, 'off');
} finally { cfg.save({ enabled: true }); p.close(); }
});
test('a job interrupted by a restart is reported as failed, not left spinning', () => {
const uid = 'u-restart';
fs.mkdirSync(`${DIR}/coach`, { recursive: true });