Fix NAS stop trap on LinkSpin: snapshot true delivery before every stop, reconcile active ads only, restart stopped ads from the true count

The InstantAdPay 2026-09-17 fix was never ported. nas.deactivate zeroed `remaining` with no snapshot, so served =
assigned - remaining read the undelivered rest as delivered, and reconcileNas read EVERY status: a paused ad was
charged for its zeroed remainder (up to its budget) and stopped ads showed their whole allocation as network views.
Now: nas.deactivate returns the served count read before the stop; ads.stopNas persists it on pause, end and
exhaustion; reconcileNas only looks at active campaigns; resume/top-up of a stopped ad uses the new nas.restart
(re-bases assigned on the true count) instead of a plain top-up. QA: qa/nas-stop.test.cjs (9), loginqueue 13,
refill 12, run.sh member passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-27 07:56:56 -05:00
parent 2d0413037d
commit fd6f88cab7
3 changed files with 69 additions and 1 deletions
BIN
View File
Binary file not shown.
+14 -1
View File
@@ -102,9 +102,22 @@ async function readServed(nasAdId) {
}
// stop a syndicated ad (budget spent, paused, or expired) — remaining:0 halts serving.
// THE TRAP (InstantAdPay, found 2026-09-17, ported here 2026-10-27): NAS has no stop flag, so a stop zeroes `remaining`, and
// served = assigned - remaining then reads the undelivered rest as DELIVERED. The true figure is captured BEFORE the stop
// and returned; callers persist it (ads.stopNas) and never reconcile a stopped ad again.
async function deactivate(nasAdId) {
if (!enabled()) return { skipped: 'flag-off' };
let served = null;
try { const s = await readServed(nasAdId); if (s) served = s.served; } catch (e) {}
await q('UPDATE sponsorads SET remaining=0, EDate=NOW() WHERE ID=?', [Number(nasAdId)]);
return { ok: true, served };
}
// restart a STOPPED ad with `addImpressions` more, re-basing `assigned` on the TRUE served count recorded at the stop
// (a plain topUp would leave the zeroed remainder counted as served)
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 };
}
@@ -131,4 +144,4 @@ async function topUp(nasAdId, addImpressions, days) {
return { ok: true };
}
module.exports = { setClickUrl, updateCreative, enabled, pushCampaign, readServed, deactivate, topUp, impressionsPerCredit, nasKind };
module.exports = { setClickUrl, updateCreative, enabled, pushCampaign, readServed, deactivate, restart, topUp, impressionsPerCredit, nasKind };
+55
View File
@@ -0,0 +1,55 @@
// NAS stop trap on LinkSpin (fixed 2026-10-27; the InstantAdPay 2026-09-17 fix was never ported). NAS has no stop flag,
// a stop zeroes `remaining`, and served = assigned - remaining then reads the undelivered rest as DELIVERED. Before the fix:
// pause/end/exhaustion called nas.deactivate with no snapshot, reconcileNas read EVERY status, so a paused ad was charged
// for its zeroed remainder, and a resume/top-up of a stopped ad counted it again. JSON store, NAS stubbed, throwaway data.
// node qa/nas-stop.test.cjs
'use strict';
delete process.env.DATABASE_URL;
const fs = require('fs'); const os = require('os'); const path = require('path');
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(), 'ls-nas-stop-'));
const nas = require('../nas.js');
const rows = {}; const calls = { restart: 0, deactivate: 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; calls.deactivate++; return { ok: true, served }; };
nas.topUp = async (id, add) => { rows[id].assigned += add; rows[id].remaining += add; return { ok: true }; };
nas.restart = async (id, base, add) => { rows[id].assigned = base + add; rows[id].remaining = add; calls.restart++; return { ok: true }; };
nas.updateCreative = async () => ({ ok: true });
const ads = require('../ads.js');
const ADV = 'stop@qa.test', FILE = path.join(DATA, 'campaigns.json');
const banner = (id, x) => Object.assign({ id, owner: ADV, 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 || {});
const seed = camps => { fs.writeFileSync(FILE, JSON.stringify({ v: 1, nextId: 9100, campaigns: camps, 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);
(async () => {
seed([banner(9001), banner(9002, { budget: 100 })]);
await ads.addEarned(ADV, 10000);
rows[9001] = { assigned: 5000, remaining: 5000 }; rows[9002] = { assigned: 500, remaining: 500 };
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(ADV, 9001, 'paused');
t('pause records the TRUE 1,000 served, not the 5,000 allocation', C(9001).nasServed === 1000, String(C(9001).nasServed));
await ads.reconcileNas();
t('a paused ad is not charged for its zeroed remainder', used(C(9001)) === 200, String(used(C(9001))));
const r0 = calls.restart; await ads.setStatus(ADV, 9001, 'active'); await ads.reconcileNas();
t('resume restarts the stopped ad from the true count', calls.restart === r0 + 1 && rows[9001].assigned === 5000 && rows[9001].remaining === 4000, JSON.stringify(rows[9001]));
t('no phantom delivery or charge after the resume', C(9001).nasServed === 1000 && used(C(9001)) === 200, C(9001).nasServed + ' / ' + used(C(9001)));
rows[9001].remaining -= 500; await ads.reconcileNas();
t('real views after the resume still charge (500 = 100 credits)', used(C(9001)) === 300, String(used(C(9001))));
// exhaustion: budget 100 = 500 views; NAS serves 300, a budget top-up of on-site spend exhausts it on the next reconcile
const c2 = C(9002); c2.spent = 60; const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.campaigns[s.campaigns.findIndex(x => x.id === 9002)] = c2; fs.writeFileSync(FILE, JSON.stringify(s)); ads.init({ dataDir: DATA, chain: { creditBalance: async () => 0 } });
rows[9002].remaining -= 300; const d0 = calls.deactivate; await ads.reconcileNas();
const x = C(9002);
t('exhausted: charge capped at the budget and the NAS ad stopped', used(x) === 100 && x.status === 'out' && calls.deactivate === d0 + 1, JSON.stringify({ used: used(x), st: x.status }));
t('exhausted: served kept at the TRUE 300', x.nasServed === 300, String(x.nasServed));
await ads.reconcileNas();
t('an exhausted (out) ad is never reconciled again', C(9002).nasServed === 300 && used(C(9002)) === 100, String(C(9002).nasServed));
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);
})().catch(e => { console.error(e); process.exit(1); });