File size: 4,820 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/**
 * Source verification for the grounded teaching pipeline.
 *
 * Periodically verifies that cached source URLs are still live,
 * removes dead sources, and invalidates teaching caches that
 * fall below the minimum source threshold.
 */

import { prisma } from "@/lib/db";
import { verifyWikipediaUrl } from "./wikipedia";
import { MIN_SOURCES } from "./curate";

/** Sources older than this are considered stale and need re-verification. */
export const STALE_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1000; // 7 days

/** Maximum number of sources to verify in a single run (rate limiting). */
export const MAX_VERIFY_BATCH = 50;

export interface VerificationResult {
  /** Total sources checked in this run. */
  checked: number;
  /** Sources confirmed live. */
  live: number;
  /** Sources removed (dead URLs). */
  removed: number;
  /** Teaching caches invalidated due to insufficient sources. */
  cachesInvalidated: number;
  /** Topic IDs whose caches were invalidated. */
  invalidatedTopics: string[];
  /** Duration of the verification run in milliseconds. */
  durationMs: number;
}

/**
 * Get sources that need verification — either never verified or stale.
 */
export async function getStaleSources(limit: number = MAX_VERIFY_BATCH) {
  const staleDate = new Date(Date.now() - STALE_THRESHOLD_MS);

  return prisma.topicSource.findMany({
    where: {
      OR: [
        { verifiedAt: null },
        { verifiedAt: { lt: staleDate } },
      ],
    },
    orderBy: [
      { verifiedAt: "asc" }, // nulls first, then oldest
    ],
    take: limit,
  });
}

/**
 * Verify a single source URL.
 * Returns true if the URL is live, false otherwise.
 */
export async function verifySourceUrl(url: string): Promise<boolean> {
  return verifyWikipediaUrl(url); // Generic HEAD check
}

/**
 * Run a full verification pass on stale sources.
 *
 * 1. Finds sources with null or stale verifiedAt timestamps
 * 2. HEAD-checks each URL
 * 3. Updates verifiedAt for live URLs
 * 4. Deletes dead sources
 * 5. Invalidates teaching caches for topics that dropped below MIN_SOURCES
 */
export async function runVerification(
  limit: number = MAX_VERIFY_BATCH,
): Promise<VerificationResult> {
  const start = Date.now();
  const staleSources = await getStaleSources(limit);

  let live = 0;
  let removed = 0;
  const affectedTopicIds = new Set<string>();

  for (const source of staleSources) {
    const isLive = await verifySourceUrl(source.url);

    if (isLive) {
      await prisma.topicSource.update({
        where: { id: source.id },
        data: { verifiedAt: new Date() },
      });
      live++;
    } else {
      await prisma.topicSource.delete({
        where: { id: source.id },
      });
      removed++;
      affectedTopicIds.add(source.topicId);
    }
  }

  // Check if any affected topics dropped below the source threshold
  const invalidatedTopics: string[] = [];

  for (const topicId of affectedTopicIds) {
    const remainingCount = await prisma.topicSource.count({
      where: { topicId },
    });

    if (remainingCount < MIN_SOURCES) {
      // Invalidate the teaching cache — it's no longer sufficiently grounded
      const deleted = await prisma.teachingCache.deleteMany({
        where: { topicId },
      });
      if (deleted.count > 0) {
        invalidatedTopics.push(topicId);
      }
    }
  }

  return {
    checked: staleSources.length,
    live,
    removed,
    cachesInvalidated: invalidatedTopics.length,
    invalidatedTopics,
    durationMs: Date.now() - start,
  };
}

/**
 * Get a summary of source health across all topics.
 */
export async function getSourceHealthSummary() {
  const staleDate = new Date(Date.now() - STALE_THRESHOLD_MS);

  const [totalSources, staleSources, neverVerified, totalCaches] =
    await Promise.all([
      prisma.topicSource.count(),
      prisma.topicSource.count({
        where: { verifiedAt: { lt: staleDate } },
      }),
      prisma.topicSource.count({
        where: { verifiedAt: null },
      }),
      prisma.teachingCache.count(),
    ]);

  // Count unique topics with sources
  const topicsWithSources = await prisma.topicSource.groupBy({
    by: ["topicId"],
  });

  // Count topics with sufficient sources (>= MIN_SOURCES)
  const topicSourceCounts = await prisma.topicSource.groupBy({
    by: ["topicId"],
    _count: { id: true },
  });

  const topicsAboveThreshold = topicSourceCounts.filter(
    (t) => t._count.id >= MIN_SOURCES,
  ).length;

  return {
    totalSources,
    staleSources: staleSources + neverVerified,
    neverVerified,
    freshSources: totalSources - staleSources - neverVerified,
    totalCaches,
    topicsWithSources: topicsWithSources.length,
    topicsAboveThreshold,
    minSourcesRequired: MIN_SOURCES,
    staleThresholdDays: STALE_THRESHOLD_MS / (24 * 60 * 60 * 1000),
  };
}