-- file: validation_sql/SQL_VALIDATION_RAYDIUM_CPMM_AUDIT_CLEANUP_0_7_50_FINAL.sql

-- Raydium CPMM residual audit cleanup validation for 0.7.50 final.
-- These queries must be empty after applying the final cleanup patch and replaying with
-- skipDexDecode=no, forceDexDecode=yes, deferInstructionObservations=yes.

SELECT
    json_extract(payload_json, '$.discriminatorHex') AS discriminator_hex,
    COUNT(*) AS audit_count,
    COUNT(DISTINCT transaction_id) AS tx_count
FROM k_sol_dex_decoded_events
WHERE protocol_name = 'raydium_cpmm'
  AND event_kind = 'raydium_cpmm.instruction_audit'
GROUP BY discriminator_hex
ORDER BY audit_count DESC, discriminator_hex;

SELECT
    de.event_kind,
    COUNT(*) AS decoded_count
FROM k_sol_dex_decoded_events de
LEFT JOIN k_sol_dex_event_coverage_entries ce
    ON ce.decoder_code = 'raydium_cpmm'
   AND ce.local_event_kind = de.event_kind
WHERE de.protocol_name = 'raydium_cpmm'
  AND ce.id IS NULL
GROUP BY de.event_kind
ORDER BY decoded_count DESC, de.event_kind;

-- Manual emergency cleanup only if the application replay still leaves the legacy audit rows.
-- It intentionally unlinks k_sol_instruction_observations first, because existing DBs created
-- before ON DELETE SET NULL may otherwise retain decoded_event_id references.

UPDATE k_sol_instruction_observations
SET decoded_event_id = NULL
WHERE decoded_event_id IN (
    SELECT id
    FROM k_sol_dex_decoded_events
    WHERE protocol_name = 'raydium_cpmm'
      AND event_kind = 'raydium_cpmm.instruction_audit'
      AND instr(lower(COALESCE(payload_json, '')), '40f4bc78a7e9690a') > 0
);

DELETE FROM k_sol_dex_decoded_events
WHERE protocol_name = 'raydium_cpmm'
  AND event_kind = 'raydium_cpmm.instruction_audit'
  AND instr(lower(COALESCE(payload_json, '')), '40f4bc78a7e9690a') > 0;
