#!/usr/bin/env bash
# Aletheia — Concurrent-Worker Cascade-Heal Race Artifact Detector
#
# When N concurrent kintsugi workers process shards for the same (symbol,
# threshold), one worker heals a gap (writes Vision ZIP bars covering dates
# D1-D3), which inadvertently fills adjacent shards. Workers B-M then arrive,
# find bars already present, and log clean+0-bar entries. These entries
# trigger the 30-day dismissal window in _get_dismissed_set(), blocking
# thousands of valid historical shards from ever being re-queued.
#
# Detection heuristic: a (symbol, threshold) pair that simultaneously has
# both 'healed' entries AND 'clean+0-bar' entries within the same 2-hour
# window is exhibiting the race pattern. A genuinely sub-threshold day
# cannot logically coincide with active healing of the same pair.
#
# Also monitors the total accumulated dismissed-shard backlog.
set -euo pipefail

CH="http://localhost:8123/"

recent_artifacts=$(curl -sf "$CH" --data-binary \
  "SELECT count() FROM opendeviationbar_cache.kintsugi_log
   WHERE result = 'clean' AND bars_written = 0
   AND timestamp > now() - INTERVAL 2 HOUR
   AND (symbol, threshold_decimal_bps) IN (
     SELECT symbol, threshold_decimal_bps
     FROM opendeviationbar_cache.kintsugi_log
     WHERE result = 'healed'
     AND timestamp > now() - INTERVAL 2 HOUR
   )" | tr -d '[:space:]')

total_dismissed=$(curl -sf "$CH" --data-binary \
  "SELECT count() FROM opendeviationbar_cache.kintsugi_log
   WHERE result = 'clean' AND bars_written = 0
   AND timestamp > now() - INTERVAL 30 DAY" | tr -d '[:space:]')

unique_dismissed=$(curl -sf "$CH" --data-binary \
  "SELECT uniq(gap_start_ms) FROM opendeviationbar_cache.kintsugi_log
   WHERE result = 'clean' AND bars_written = 0
   AND timestamp > now() - INTERVAL 30 DAY" | tr -d '[:space:]')

echo "Aletheia (concurrent-worker cascade-heal race artifact detector)"
echo "  Recent artifacts (last 2h, coinciding with healing): $recent_artifacts  (safe: 0, warn: >3, fail: >10)"
echo "  Total dismissals (last 30d):                         $total_dismissed"
echo "  Unique dismissed shards (last 30d):                  $unique_dismissed  (safe: <50, warn: >200)"

if   [[ "$recent_artifacts" -gt 10 ]]; then
  echo "  Status: FAIL — $recent_artifacts race artifacts accumulating. MAX_CONCURRENT_REPAIRS should be 1 for focus-mode, or _aletheia_purge() is not running."
  exit 2
elif [[ "$recent_artifacts" -gt 3 ]]; then
  echo "  Status: WARN — $recent_artifacts possible race artifacts. Monitor next pass."
  exit 1
elif [[ "$unique_dismissed" -gt 200 ]]; then
  echo "  Status: WARN — $unique_dismissed dismissed shards is high (expected <50). Consider truncating kintsugi_log."
  exit 1
else
  echo "  Status: PASS"
  exit 0
fi
