Skip to content

Commit c9459ca

Browse files
committed
Stop niche imports on abort and keep stdout out of errors
1 parent 815fa0c commit c9459ca

2 files changed

Lines changed: 80 additions & 4 deletions

File tree

‎scripts/ad-networks/niche-sort.mjs‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,12 +82,12 @@ export async function classifyNiches(input, rubric, options, dependencies = {})
8282
const diagnostic = `${stderr}\n${output}`;
8383
if (nicheUsageLimited(diagnostic)) return reject(Object.assign(new Error('Claude subscription usage limit reached; pause until it resets'), { code: 'NICHE_USAGE_LIMIT' }));
8484
if (/not logged in|authentication failed|invalid (?:api key|access token|refresh token)|token (?:has )?expired|login required|please log in|run \/login/i.test(diagnostic)) {
85-
return reject(Object.assign(new Error(`Claude login failed: ${nicheModelDetail(stderr || output)}`), { code: 'NICHE_MODEL_FAILED' }));
85+
return reject(Object.assign(new Error(`Claude login failed: ${nicheModelDetail(stderr) || 'no stderr diagnostic output'}`), { code: 'NICHE_MODEL_FAILED' }));
8686
}
8787
if (failure) return reject(failure);
8888
if (code !== 0) {
8989
const transient = signal || /ECONNRESET|ETIMEDOUT|EAI_AGAIN|connection (?:reset|closed)|fetch failed|network error|overloaded|temporarily unavailable|\b50[234]\b/i.test(diagnostic);
90-
return reject(Object.assign(new Error(`Model CLI exited ${code}${signal ? ` (${signal})` : ''}: ${nicheModelDetail(stderr || output) || 'no diagnostic output'}`), { code: transient ? 'NICHE_MODEL_RETRYABLE' : 'NICHE_MODEL_FAILED' }));
90+
return reject(Object.assign(new Error(`Model CLI exited ${code}${signal ? ` (${signal})` : ''}: ${nicheModelDetail(stderr) || 'no stderr diagnostic output'}`), { code: transient ? 'NICHE_MODEL_RETRYABLE' : 'NICHE_MODEL_FAILED' }));
9191
}
9292
resolveModel(output);
9393
});
@@ -127,27 +127,34 @@ export async function importNiches(client, rows, dependencies = {}) {
127127
// Queue behind other lock requests. Server-side timeouts keep each attempt
128128
// below the pool's 120-second query timeout while OVH finishes its full sync.
129129
const now = dependencies.now ?? (() => performance.now());
130+
const { signal } = dependencies;
131+
signal?.throwIfAborted();
130132
const deadline = now() + 60 * 60 * 1000;
131133
let locked = false;
132134
try {
133135
try {
134136
while (!locked) {
137+
signal?.throwIfAborted();
135138
const remaining = deadline - now();
136139
if (remaining <= 0) throw new Error('Timed out waiting 60 minutes for ad-network sync lock');
137140
await client.query(`set lock_timeout = '${Math.max(1, Math.min(100000, Math.floor(remaining)))}ms'`);
141+
signal?.throwIfAborted();
138142
try {
139143
await client.query("select pg_advisory_lock(hashtext('ad-networks-reviewed-sync'))");
140144
locked = true;
141145
} catch (error) { if (error.code !== '55P03') throw error; }
142146
}
143147
} finally { await client.query('reset lock_timeout'); }
148+
signal?.throwIfAborted();
144149
try {
145150
await client.query('begin');
151+
signal?.throwIfAborted();
146152
const result = await client.query(`update public.ad_network_publishers p set niche=i.niche
147153
from jsonb_to_recordset($1::jsonb) i(domain text,niche text)
148154
where p.normalized_domain=i.domain and p.niche is null and i.niche is not null
149155
and exists(select 1 from public.ad_network_publisher_relationships r where r.publisher_id=p.id and r.status='confirmed')`,
150156
[JSON.stringify(rows.map(row => ({ domain: row.domain, niche: publicNiche(row) })))]);
157+
signal?.throwIfAborted();
151158
await client.query('commit');
152159
return result.rowCount;
153160
} catch (error) { await client.query('rollback').catch(() => {}); throw error; }
@@ -203,7 +210,7 @@ export async function sortNiches(options, dependencies = {}) {
203210
const batch = input.slice(i, i + +options['batch-size']);
204211
for await (const rows of recoverNicheBatch(batch, rubric, options, dependencies)) {
205212
options.signal.throwIfAborted();
206-
imported += await importNiches(client, rows);
213+
imported += await importNiches(client, rows, { signal: options.signal });
207214
classified += rows.length;
208215
for (const row of rows) {
209216
if (publicNiche(row) === null) withheld++;

‎tests/pages/ad-networks/niche-sort.test.mjs‎

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,25 @@ test('login errors and usage limits stop even when the CLI returns exit code zer
131131
}
132132
});
133133

134+
test('CLI failure errors never include raw stdout, with or without stderr', async () => {
135+
for (const [stdout, exitCode, code] of [
136+
['raw-model-output-private-marker', 1, 'NICHE_MODEL_FAILED'],
137+
['Not logged in raw-model-output-private-marker', 0, 'NICHE_MODEL_FAILED'],
138+
['503 raw-model-output-private-marker', 1, 'NICHE_MODEL_RETRYABLE'],
139+
]) {
140+
for (const stderr of ['', 'safe stderr diagnostic']) {
141+
await assert.rejects(classifyNiches(input, '', {}, fakeModel(child => {
142+
child.stdout.write(stdout); child.stderr.write(stderr); child.emit('close', exitCode);
143+
})), error => {
144+
assert.equal(error.code, code);
145+
assert.doesNotMatch(error.message, /raw-model-output-private-marker|Not logged in|503/);
146+
assert.ok(error.message.endsWith(stderr || 'no stderr diagnostic output'));
147+
return true;
148+
});
149+
}
150+
}
151+
});
152+
134153
async function sortFixture(t, sites, classify, update) {
135154
const directory = await mkdtemp(join(tmpdir(), 's127-niche-recovery-'));
136155
t.after(() => rm(directory, { recursive: true, force: true }));
@@ -148,7 +167,7 @@ async function sortFixture(t, sites, classify, update) {
148167
const options = nicheSortArgs(['--apply', '--state-directory', directory, '--limit', String(sites.length)]);
149168
const run = () => sortNiches(options, { classify, delay: noDelay, revalidate: async () => {},
150169
pool: { connect: async () => client, end: async () => {} } });
151-
return { run, writes, checkpoint: async () => JSON.parse(await readFile(join(directory, 'niche-results.json'), 'utf8')) };
170+
return { run, writes, client, checkpoint: async () => JSON.parse(await readFile(join(directory, 'niche-results.json'), 'utf8')) };
152171
}
153172

154173
test('unresolved batches do not block later sites, and only completed answers get checkpoints', async t => {
@@ -205,6 +224,56 @@ test('an operator stop after classification prevents imports and releases signal
205224
assert.deepEqual(fixture.writes, []);
206225
assert.equal(process.listenerCount('SIGTERM'), priorListeners);
207226
});
227+
228+
test('SIGTERM during import lock contention prevents another lock attempt or update', async t => {
229+
let calls = 0, attempts = 0;
230+
const fixture = await sortFixture(t, [{ domain: 'example.com', title: 'Food' }], async () => {
231+
calls++; return lines([result('example.com')]);
232+
});
233+
const query = fixture.client.query;
234+
const queries = [];
235+
fixture.client.query = async (sql, args) => {
236+
queries.push(sql);
237+
if (sql.includes('pg_advisory_lock')) {
238+
if (++attempts === 1) {
239+
process.emit('SIGTERM');
240+
throw Object.assign(Error('lock unavailable'), { code: '55P03' });
241+
}
242+
}
243+
return query(sql, args);
244+
};
245+
await assert.rejects(fixture.run(), error => {
246+
assert.equal(error.jobResult.imported, 0);
247+
assert.equal(error.jobResult.unresolved, 1);
248+
return error.code === 'NICHE_STOPPED';
249+
});
250+
assert.equal(calls, 1); assert.equal(attempts, 1);
251+
assert.deepEqual(fixture.writes, []);
252+
assert.ok(queries.includes('reset lock_timeout'));
253+
assert.ok(!queries.includes('begin'));
254+
await assert.rejects(fixture.checkpoint(), { code: 'ENOENT' });
255+
});
256+
257+
test('aborted imports release acquired locks and roll back before writing or committing', async () => {
258+
for (const stage of ['before import', 'set timeout', 'lock acquired', 'begin', 'update']) {
259+
const controller = new AbortController(), queries = [];
260+
const stop = () => controller.abort(Object.assign(Error('Model interrupted'), { code: 'NICHE_STOPPED' }));
261+
if (stage === 'before import') stop();
262+
await assert.rejects(importNiches({ query: async sql => {
263+
queries.push(sql);
264+
if ((stage === 'set timeout' && sql.startsWith('set lock_timeout')) ||
265+
(stage === 'lock acquired' && sql.includes('pg_advisory_lock')) ||
266+
(stage === 'begin' && sql === 'begin') || (stage === 'update' && sql.startsWith('update'))) stop();
267+
return { rowCount: 1 };
268+
} }, [result('example.com')], { signal: controller.signal }), error => error.code === 'NICHE_STOPPED');
269+
assert.ok(!queries.includes('commit'));
270+
if (stage !== 'update') assert.ok(!queries.some(sql => sql.startsWith('update')));
271+
if (stage === 'before import') assert.deepEqual(queries, []);
272+
if (stage === 'set timeout') assert.ok(!queries.some(sql => sql.includes('pg_advisory_lock')));
273+
if (['lock acquired', 'begin', 'update'].includes(stage)) assert.match(queries.at(-1), /pg_advisory_unlock/);
274+
if (['begin', 'update'].includes(stage)) assert.ok(queries.includes('rollback'));
275+
}
276+
});
208277
test('model validation keeps only clean answers to input domains, once each', () => {
209278
const correct = [result('example.com'), result('example.org', null, 'low')];
210279
assert.deepEqual(validateNicheBatch(input, lines(correct)), correct);

0 commit comments

Comments
 (0)