Your keyword alert fired. The analyst opens the stored row, and the matching source isn't there. Now you're explaining an alert with a title and a link.
A bodyText search selects exploit candidates; retrieving their raw code requires byIds with includeCode: true.
The Actor searches public JSON tables, then enriches exact records from detail pages. Those are different retrieval paths. Your database needs to preserve the handoff between them.
Why doesn't a body search include the body?
Selection answers which entries deserve inspection. Evidence retrieval gives the analyst something to inspect.
Don't let the notification outrun that distinction. Until the source arrives, you've a candidate alert with unfinished evidence work.
Choose socket as the Example keyword and bound discovery with an explicit record cap.
import { createHash } from 'node:crypto'; import { ApifyClient } from 'apify-client'; import { z } from 'zod'; import pg from 'pg'; const client = new ApifyClient({ token: process.env.APIFY_TOKEN }); const pool = new pg.Pool(); const run_input = { mode: 'search', collection: 'exploits', bodyText: 'socket', maxItems: 20, } as const; const observation = process.env.OBSERVATION_KEY ?? 'initial'; const attempt = process.env.RETRY_KEY ?? 'initial'; const rule = 'literal-case-sensitive-v1'; const queryKey = createHash('sha256') .update(JSON.stringify({ input: run_input, observation })) .digest('hex'); The observation identifies an intentional evidence collection window. Keep it unchanged during recovery; change it when you want a fresh snapshot.
The retry key has a narrower purpose: authorize another retrieval attempt within that observation. An ordinary process restart should resume existing work without quietly starting another paid run.
Your workflow now has a visible evidence boundary:
body search → candidate metadata → pending enrichment ↓ byIds + includeCode ↓ stored body + hash + local check ↓ analyst inspection containsKeyword can't replace the discovery filter here. It checks titles and GHDB descriptions, rather than the full exploit body.
That distinction matters operationally. A title can explain what an entry concerns while saying nothing about the particular code fragment your analyst needs.
Keep entry identity separate from evidence versions
Use an exploit-qualified edbId as the entry key. Keep the identifier as text.
The prefix belongs to your ingestion model. It prevents another collection's identifier from sharing the same database identity, and leaves room for an origin namespace if you ingest other archives later.
That key is stable enough for candidate upserts. It isn't a source version.
An entry can retain its identifier while its body changes. Evidence therefore gets a separate content hash, plus timestamps that describe when each observation happened.
Create typed columns for queue selection and provenance, while retaining the complete returned records.
async function prepare() { await pool.query(` CREATE TABLE IF NOT EXISTS candidate ( query_key text NOT NULL, entity_key text NOT NULL, title text, source_url text NOT NULL, scraped_at timestamptz NOT NULL, raw jsonb NOT NULL, PRIMARY KEY (query_key, entity_key) ); CREATE TABLE IF NOT EXISTS evidence ( query_key text NOT NULL, entity_key text NOT NULL, rule text NOT NULL, content_hash text NOT NULL, literal_match boolean NOT NULL, source_scraped_at timestamptz NOT NULL, retrieved_at timestamptz NOT NULL, run_id text NOT NULL, raw jsonb NOT NULL, PRIMARY KEY (query_key, entity_key, rule, content_hash) ); CREATE TABLE IF NOT EXISTS ingestion_run ( query_key text NOT NULL, phase text NOT NULL, run_id text NOT NULL UNIQUE, input jsonb NOT NULL, expected_keys text[] NOT NULL, status text, dataset_id text, at_cap boolean NOT NULL DEFAULT false, started_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY (query_key, phase) ); CREATE TABLE IF NOT EXISTS quarantine ( run_id text NOT NULL, item_index integer NOT NULL, phase text NOT NULL, raw jsonb NOT NULL, issues jsonb NOT NULL, PRIMARY KEY (run_id, item_index) ); `); } const conflicts = { candidate: `ON CONFLICT (query_key, entity_key) DO UPDATE SET title = EXCLUDED.title, source_url = EXCLUDED.source_url, scraped_at = EXCLUDED.scraped_at, raw = EXCLUDED.raw WHERE EXCLUDED.scraped_at >= candidate.scraped_at`, evidence: 'ON CONFLICT DO NOTHING', quarantine: 'ON CONFLICT DO NOTHING', } as const; async function save( table: keyof typeof conflicts, rows: unknown[], ) { if (!rows.length) return; await pool.query(` INSERT INTO ${table} SELECT * FROM jsonb_populate_recordset(NULL::${table}, $1::jsonb) ${conflicts[table]} `, [JSON.stringify(rows)]); } The table names come from a closed internal set. Returned source content only enters parameterized values.
JSONB preserves fields you haven't promoted into your model. Typed columns make the queue and analyst-facing joins predictable.
Neither approach deserves the whole job. JSONB alone pushes contract checking into downstream queries; typed columns alone discard context that may become useful during review.
The body stays inside evidence JSONB, avoiding another copy in a dedicated text column. Promote it later if your actual query workload justifies that storage trade-off.
The candidate key also includes query_key. Membership in a particular search observation is distinct from archive identity, so separate searches shouldn't overwrite each other's discovery history.
Accept additions, quarantine broken handoffs
Empty source fields are omitted. Optional metadata therefore stays optional.
Identity and provenance have a different responsibility. Without them, you can't safely attach a body to its candidate or explain when it was observed.
Validate the fields this workflow consumes, and retain everything else.
const candidateSchema = z.object({ recordType: z.string().min(1), edbId: z.string().min(1), sourceUrl: z.string().url(), scrapedAt: z.string().datetime({ offset: true }), title: z.string().optional(), }).passthrough(); const evidenceSchema = candidateSchema.extend({ code: z.string().min(1), }); async function validateBatch<T>( schema: z.ZodType<T>, items: unknown[], runId: string, phase: string, ) { const valid: Array<{ data: T; raw: unknown }> = []; const rejected: unknown[] = []; items.forEach((raw, itemIndex) => { const parsed = schema.safeParse(raw); if (parsed.success) { valid.push({ data: parsed.data, raw }); } else { rejected.push({ run_id: runId, item_index: itemIndex, phase, raw, issues: parsed.error.issues, }); } }); await save('quarantine', rejected); return valid; } A strict schema around this selected subset would reject legitimate metadata outside it. Passthrough accepts additions while enforcing your operational contract.
That choice has a deliberate blind spot: new fields won't trigger a drift alert. Missing optional metadata won't either.
Changes that break identity, provenance, or the required body do produce quarantine records. Their issue paths let you distinguish missing evidence from incompatible metadata.
Quarantine isn't a disposal bin. Keep the original value and validation issues so you can repair the mapping and replay the existing dataset, rather than paying to rediscover the same problem.
A rejected record never enters either trusted table. Other valid records can still move forward.
Checkpoint before waiting
A database upsert prevents duplicate logical rows. It doesn't prevent duplicate upstream charges.
Save the remote run identifier before waiting. On recovery, resume that identifier and reuse its original expected identities, even if the current queue has changed.
This helper records terminal status before reading records and flags a dataset that reaches its requested cap.
type Checkpoint = { run_id: string; input: Record<string, unknown>; expected_keys: string[]; }; async function fetchBatch( input: Record<string, unknown>, phase: string, expectedKeys: string[] = [], ) { const phaseKey = `${phase}:${attempt}`; let saved = (await pool.query<Checkpoint>(` SELECT run_id, input, expected_keys FROM ingestion_run WHERE query_key = $1 AND phase = $2 `, [queryKey, phaseKey])).rows[0]; if (!saved) { const started = await client .actor('nimbryxo-studio/exploit-db-and-google-hacking-database-extractor') .start(input); await pool.query(` INSERT INTO ingestion_run (query_key, phase, run_id, input, expected_keys) VALUES ($1, $2, $3, $4::jsonb, $5::text[]) `, [queryKey, phaseKey, started.id, JSON.stringify(input), expectedKeys]); saved = { run_id: started.id, input, expected_keys: expectedKeys, }; } const run = await client.run(saved.run_id).waitForFinish(); if (!run || ![ 'SUCCEEDED', 'FAILED', 'TIMED-OUT', 'ABORTED', ].includes(run.status)) { throw new Error(`Unresolved run: ${saved.run_id}`); } await pool.query(` UPDATE ingestion_run SET status = $2, dataset_id = $3 WHERE run_id = $1 `, [run.id, run.status, run.defaultDatasetId]); const { items } = await client.dataset(run.defaultDatasetId).listItems(); const retrievedAt = new Date().toISOString(); const atCap = typeof saved.input.maxItems === 'number' && items.length >= saved.input.maxItems; await pool.query(` UPDATE ingestion_run SET at_cap = $2 WHERE run_id = $1 `, [run.id, atCap]); return { run, items, retrievedAt, expectedKeys: saved.expected_keys }; } Run a single worker per query key for this recipe. Concurrent workers need a queue claim or lock around checkpoint creation.
There's also a gap between starting the remote run and saving its identifier. A crash inside that gap requires reconciliation before replacement work starts. A local transaction can't make a remote start atomic.
Once the checkpoint exists, recovery is simpler. Re-read its dataset and repeat idempotent writes.
A terminal failure doesn't establish search completeness. If its dataset exposes usable rows, preserve them as partial observations while keeping the failed status visible.
Likewise, success at the record cap doesn't establish exhaustive coverage. The cap bounds ingestion, not the archive.
Build the queue from missing evidence
Persist candidate metadata before starting enrichment. That makes the database itself the durable queue.
If the process stops after the candidate write, those entries remain eligible next time. There's no separate message that can disappear between insertion and publication.
This discovery function deduplicates the batch before issuing its upsert.
async function discover() { const batch = await fetchBatch(run_input, 'discovery'); const valid = await validateBatch( candidateSchema, batch.items, batch.run.id, 'discovery', ); valid.sort((a, b) => Date.parse(a.data.scrapedAt) - Date.parse(b.data.scrapedAt)); const rows = [...new Map(valid.map(({ data, raw }) => [ `exploit:${data.edbId}`, { query_key: queryKey, entity_key: `exploit:${data.edbId}`, title: data.title ?? null, source_url: data.sourceUrl, scraped_at: data.scrapedAt, raw, }, ])).values()]; await save('candidate', rows); } Sorting before deduplication retains the newest validated observation within the batch. The database condition also prevents an older replay from overwriting newer stored metadata.
Deduplication matters before the statement, too. Conflicting entries in the same upsert batch shouldn't compete to update the same target row.
Use the returned sourceUrl for enrichment. Bare numeric identifiers pass through unified resolution; a collection-qualified URL keeps the intended retrieval path explicit.
The queue will exclude candidates with evidence already stored for this observation and local rule. Repeated discovery doesn't automatically refresh an existing body.
That's intentional. Recovery and fresh observation are different operations, with different spending consequences.
Store the body before interpreting the match
Hash the returned body without trimming, reformatting, or changing line endings. Your hash should describe the text retained for inspection.
The local rule here's a case-sensitive literal substring check. It documents your own inspection rule, without claiming to reconstruct the server's matching algorithm.
Enrichment checks requested membership, preserves the body, and writes the local verdict beside its hash.
async function enrich() { const pending = await pool.query<{ entity_key: string; source_url: string; }>(` SELECT c.entity_key, c.source_url FROM candidate c WHERE c.query_key = $1 AND NOT EXISTS ( SELECT 1 FROM evidence e WHERE e.query_key = c.query_key AND e.entity_key = c.entity_key AND e.rule = $2 ) ORDER BY c.entity_key LIMIT $3 `, [queryKey, rule, run_input.maxItems]); if (!pending.rows.length) return; const batch = await fetchBatch({ mode: 'byIds', exploitIds: [...new Set(pending.rows.map(row => row.source_url))], includeCode: true, maxItems: run_input.maxItems, }, 'evidence', pending.rows.map(row => row.entity_key)); const wanted = new Set(batch.expectedKeys); const schema = evidenceSchema.refine( row => wanted.has(`exploit:${row.edbId}`), { message: 'Returned identity was not requested' }, ); const valid = await validateBatch( schema, batch.items, batch.run.id, 'evidence', ); const rows = valid.map(({ data, raw }) => ({ query_key: queryKey, entity_key: `exploit:${data.edbId}`, rule, content_hash: createHash('sha256').update(data.code, 'utf8').digest('hex'), literal_match: data.code.includes(run_input.bodyText), source_scraped_at: data.scrapedAt, retrieved_at: batch.retrievedAt, run_id: batch.run.id, raw, })); await save('evidence', rows); } A disagreement remains stored evidence with literal_match = false. It doesn't disappear because it makes the alert inconvenient.
The source may have changed between discovery and enrichment. The search may apply different matching semantics. Without further evidence, don't choose an explanation on the analyst's behalf.
Discovery's scraped_at, enrichment's source_scraped_at, and your dataset read's retrieved_at describe different events. Keeping them separate makes that uncertainty visible.
The hash identifies the returned text representation. It isn't a signature, and it doesn't prove the body was unchanged since discovery.
Even a positive local match needs interpretation. A keyword in a comment or usage example warrants different treatment from a keyword in executable logic. Store enough context for the analyst to make that distinction.
This entry point closes the shared pool once, after both phases.
try { await prepare(); await discover(); await enrich(); } finally { await pool.end(); } With unchanged keys, restarting replays the saved runs. Successful evidence writes remain idempotent, including recovery after a database write whose acknowledgement was lost.
Changing RETRY_KEY starts another discovery attempt and fetches candidates still missing evidence. It leaves successful evidence snapshots alone.
That deliberately conservative retry also repeats discovery, so it has an upstream cost. At higher volume, split discovery and enrichment into independently scheduled workers.
There's no automatic loop around missing bodies. An empty evidence response shouldn't become an enthusiastic billing loop.
What can leave the handoff incomplete?
The worked example uses Exploit-DB & Google Hacking Database Extractor. Its useful lesson is the boundary between selecting an entry and preserving the material behind that selection.
The tempting shortcuts fail for specific reasons:
| Shortcut | Behavior that breaks the assumption | Engineering consequence |
|---|---|---|
Add includeCode to discovery | Raw code attachment belongs to byIds | Keep a separate enrichment phase |
Substitute containsKeyword | It checks a different text surface | Preserve the original discovery intent |
| Require every metadata field | Empty fields are omitted | Require identity and provenance; allow absent metadata |
| Pass an unqualified mixed-collection ID | Numeric IDs use unified resolution | Queue collection-qualified source URLs |
Those are contract boundaries. They aren't evidence that every incomplete handoff has the same cause.
Alert on terminal failures, unresolved checkpoints, incompatible identity or provenance fields, and pending evidence that remains unresolved across scheduled attempts. Include the query key, run identifier, phase, and validation issue paths.
Route missing bodies and local disagreements to review separately. A broken contract needs an ingestion fix; an inspectable disagreement needs an analyst.
Treat at_cap as a coverage warning. Missing entries in a later bounded search are also insufficient evidence of deletion.
Spending needs its own boundary. maxItems caps emitted records, while starts, emitted results, and platform usage contribute to cost. Stable checkpoints prevent routine recovery from starting replacements, but an intentional retry still incurs new work.
Keep the source inert throughout this process. Public proof-of-concept text is untrusted content: store it as text, render it escaped, and never execute it to validate the alert.
Before the analyst opens the alert
- Keep the discovery input and run identifier attached to the observation.
- Require a preserved body, content hash, and independent evidence timestamps.
- Show the local rule beside its verdict.
- Leave missing evidence pending and disagreements visible.
- Reconcile unresolved runs before authorizing replacement attempts.
The awkward question isn't whether a search matched. It's whether you can show exactly what your alert checked.
Drafted with AI assistance and reviewed for accuracy.