Fix NAS phantom delivery on resume/top-up: a stopped NAS ad restarts from its true served count

stopNas zeroes `remaining` after recording the true served count. Resume (setStatus) and topUpCampaign then
used a plain nas.topUp, so assigned - remaining read the zeroed remainder as served and the next reconcileNas
charged it (up to the whole budget). New nas.restart(id, trueServed, add) re-bases assigned on the recorded
count; ads.nasExtend uses it for any stopped ad (remaining 0) and keeps the plain top-up for a running one;
resume tops up only to the budget left. QA: qa/nas-restart.mjs (9 checks; fails on the old code), nas-served 8,
run.sh member all passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-27 07:54:08 -05:00
parent 59607d0c94
commit 8b03dd2311
3 changed files with 66 additions and 1 deletions
BIN
View File
Binary file not shown.
+12 -1
View File
@@ -133,4 +133,15 @@ async function topUp(nasAdId, addImpressions, days) {
return { ok: true };
}
module.exports = { setClickUrl, enabled, pushCampaign, readServed, deactivate, topUp, impressionsPerCredit, nasKind };
// restart a STOPPED ad (deactivate zeroed `remaining`) with `addImpressions` more, re-basing `assigned` on the TRUE served
// count we recorded at the stop. A plain topUp would leave assigned - remaining = the whole old allocation, so the
// undelivered part would read back as served (the same trap as deactivate, one step later).
async function restart(nasAdId, trueServed, addImpressions, days) {
if (!enabled()) return { skipped: 'flag-off' };
const add = Math.max(0, Math.floor(Number(addImpressions) || 0)), base = Math.max(0, Math.floor(Number(trueServed) || 0));
await q(`UPDATE sponsorads SET assigned=?, remaining=?, approved=1, EDate=DATE_ADD(NOW(), INTERVAL ? DAY) WHERE ID=?`,
[base + add, add, Number(days || 30), Number(nasAdId)]);
return { ok: true };
}
module.exports = { setClickUrl, enabled, pushCampaign, readServed, deactivate, topUp, restart, impressionsPerCredit, nasKind };
+54
View File
@@ -0,0 +1,54 @@
// NAS phantom delivery on resume / top-up (found 2026-10-27). stopNas zeroes `remaining` after recording the true served
// count. Resuming (or topping up) used a plain topUp, so assigned - remaining then read the zeroed remainder as served
// and the next reconcileNas CHARGED it. Fix: a stopped ad restarts from the true count (nas.restart).
// JSON store, NAS layer stubbed, throwaway data dir. node qa/nas-restart.mjs
import { createRequire } from 'node:module';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
const require = createRequire(import.meta.url);
delete process.env.DATABASE_URL;
const ok = [], bad = [];
const t = (n, c, extra) => { (c ? ok : bad).push(n + (c || extra === undefined ? '' : ' -> ' + extra)); };
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-nas-restart-'));
const nas = require('../nas.js');
const rows = {}; const calls = { restart: 0, topUp: 0 };
nas.enabled = () => true;
nas.impressionsPerCredit = type => type === 'banner' ? 5 : 10;
nas.readServed = async id => { const r = rows[id]; return r ? { assigned: r.assigned, remaining: r.remaining, served: Math.max(0, Math.min(r.assigned, r.assigned - r.remaining)), clicks: 0 } : null; };
nas.deactivate = async id => { const r = rows[id]; const served = Math.max(0, r.assigned - r.remaining); r.remaining = 0; return { ok: true, served }; };
nas.topUp = async (id, add) => { rows[id].assigned += add; rows[id].remaining += add; calls.topUp++; return { ok: true }; };
nas.restart = async (id, base, add) => { rows[id].assigned = base + add; rows[id].remaining = add; calls.restart++; return { ok: true }; };
const ads = require('../ads.js');
const OWNER = 'restart@qa.test', FILE = path.join(DATA, 'campaigns.json');
const banner = (id, x) => Object.assign({ id, owner: OWNER, memberId: 0, type: 'banner', name: 'QA ' + id, targetUrl: 'https://example.com/', imageUrl: 'https://example.com/b.png', width: 728, height: 90,
budget: 1000, spent: 0, accrued: 0, imps: 0, batchImps: 0, clicks: 0, status: 'active', nasAdId: id, nasServed: 0, created: Date.now() }, x || {});
fs.writeFileSync(FILE, JSON.stringify({ v: 1, nextId: 9100, campaigns: [banner(9001)], burnsPending: [] }));
ads.init({ dataDir: DATA, chain: { creditBalance: async () => 0 } });
const C = id => JSON.parse(fs.readFileSync(FILE, 'utf8')).campaigns.find(c => c.id === id);
const used = c => (c.spent || 0) + (c.accrued || 0);
await ads.addEarned(OWNER, 10000);
rows[9001] = { assigned: 5000, remaining: 5000 };
rows[9001].remaining -= 1000; await ads.reconcileNas();
t('1,000 real NAS views charge 200 credits', used(C(9001)) === 200, String(used(C(9001))));
await ads.setStatus(OWNER, 9001, 'paused');
t('pause records the true 1,000 served', C(9001).nasServed === 1000, String(C(9001).nasServed));
const r0 = calls.restart; await ads.setStatus(OWNER, 9001, 'active');
t('resume restarts the stopped ad (not a plain top-up)', calls.restart === r0 + 1, String(calls.restart - r0));
t('resume books the budget left (800 credits x 5 = 4,000)', rows[9001].remaining === 4000 && rows[9001].assigned === 5000, JSON.stringify(rows[9001]));
await ads.reconcileNas();
t('no phantom charge after the resume', used(C(9001)) === 200, String(used(C(9001))));
rows[9001].remaining -= 500; await ads.reconcileNas();
t('real views after the resume still charge (500 views = 100)', used(C(9001)) === 300, String(used(C(9001))));
// a running ad that is topped up keeps a plain top-up
const tu = calls.topUp; await ads.topUpCampaign(OWNER, 0, 9001, 100);
t('top-up of a running ad is a plain top-up (+500)', calls.topUp === tu + 1 && rows[9001].remaining === 4000, JSON.stringify(rows[9001]));
// a stopped ad that is topped up restarts from the true count
await ads.setStatus(OWNER, 9001, 'paused'); const before = used(C(9001));
const r1 = calls.restart; await ads.topUpCampaign(OWNER, 0, 9001, 100); await ads.reconcileNas();
t('top-up of a stopped ad restarts it', calls.restart === r1 + 1, String(calls.restart - r1));
t('and charges nothing that was not served', used(C(9001)) === before, used(C(9001)) + ' vs ' + before);
console.log('PASS ' + ok.length);
for (const b of bad) console.log('FAIL ' + b);
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
process.exit(bad.length ? 1 : 0);