diff --git a/src/lib/postgres.mjs b/src/lib/postgres.mjs index 3e4b368..eb52e92 100644 --- a/src/lib/postgres.mjs +++ b/src/lib/postgres.mjs @@ -4475,18 +4475,26 @@ export async function refreshQuoteOutcomes(pool, { submissionLimit = 1000, inventoryLimit = 50000, } = {}) { - const safeSubmissionLimit = Math.max(1, Number(submissionLimit) || 50000); + const safeSubmissionLimit = Math.max(1, Number(submissionLimit) || 1000); const safeInventoryLimit = Math.max(1, Number(inventoryLimit) || 50000); const submissionsResult = await pool.query( ` - SELECT event_id, observed_at, ingested_at, quote_id, payload - FROM ( - SELECT event_id, observed_at, ingested_at, quote_id, payload - FROM trade_execution_results - WHERE payload->>'status' = 'submitted' - ORDER BY COALESCE(observed_at, ingested_at) DESC + WITH recent_submissions AS ( + SELECT s.event_id, s.observed_at, s.ingested_at, s.quote_id, s.payload + FROM trade_execution_results s + LEFT JOIN ${QUOTE_OUTCOMES_TABLE} o + ON o.quote_id = s.quote_id + WHERE s.payload->>'status' = 'submitted' + AND ( + o.quote_id IS NULL + OR o.outcome_status IN ('not_filled', 'submitted', 'awaiting_outcome') + OR COALESCE(s.observed_at, s.ingested_at) > o.computed_at + ) + ORDER BY COALESCE(s.observed_at, s.ingested_at) DESC LIMIT $1 - ) recent_submissions + ) + SELECT event_id, observed_at, ingested_at, quote_id, payload + FROM recent_submissions ORDER BY COALESCE(observed_at, ingested_at) ASC `, [safeSubmissionLimit],