File size: 10,836 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { describe, it, expect, vi, beforeEach } from "vitest";

// Mock prisma
const mockFindMany = vi.fn();
const mockUpdate = vi.fn();
const mockDelete = vi.fn();
const mockDeleteMany = vi.fn();
const mockCount = vi.fn();
const mockGroupBy = vi.fn();

vi.mock("@/lib/db", () => ({
  prisma: {
    topicSource: {
      findMany: (...args: unknown[]) => mockFindMany(...args),
      update: (...args: unknown[]) => mockUpdate(...args),
      delete: (...args: unknown[]) => mockDelete(...args),
      count: (...args: unknown[]) => mockCount(...args),
      groupBy: (...args: unknown[]) => mockGroupBy(...args),
    },
    teachingCache: {
      deleteMany: (...args: unknown[]) => mockDeleteMany(...args),
      count: (...args: unknown[]) => mockCount(...args),
    },
  },
}));

// Mock verifyWikipediaUrl (the underlying HEAD check)
const mockVerify = vi.fn();
vi.mock("../wikipedia", () => ({
  verifyWikipediaUrl: (...args: unknown[]) => mockVerify(...args),
}));

// Mock curate module for MIN_SOURCES
vi.mock("../curate", () => ({
  MIN_SOURCES: 2,
}));

import {
  getStaleSources,
  verifySourceUrl,
  runVerification,
  getSourceHealthSummary,
  STALE_THRESHOLD_MS,
  MAX_VERIFY_BATCH,
} from "../verify";

beforeEach(() => {
  vi.clearAllMocks();
});

describe("constants", () => {
  it("STALE_THRESHOLD_MS is 7 days", () => {
    expect(STALE_THRESHOLD_MS).toBe(7 * 24 * 60 * 60 * 1000);
  });

  it("MAX_VERIFY_BATCH defaults to 50", () => {
    expect(MAX_VERIFY_BATCH).toBe(50);
  });
});

describe("getStaleSources", () => {
  it("queries sources with null or stale verifiedAt", async () => {
    mockFindMany.mockResolvedValueOnce([]);

    const result = await getStaleSources();

    expect(mockFindMany).toHaveBeenCalledOnce();
    const args = mockFindMany.mock.calls[0][0];
    expect(args.where.OR).toHaveLength(2);
    expect(args.where.OR[0]).toEqual({ verifiedAt: null });
    expect(args.where.OR[1].verifiedAt.lt).toBeInstanceOf(Date);
    expect(args.take).toBe(MAX_VERIFY_BATCH);
    expect(result).toEqual([]);
  });

  it("respects custom limit", async () => {
    mockFindMany.mockResolvedValueOnce([]);

    await getStaleSources(10);

    const args = mockFindMany.mock.calls[0][0];
    expect(args.take).toBe(10);
  });

  it("orders by verifiedAt ascending (nulls first)", async () => {
    mockFindMany.mockResolvedValueOnce([]);

    await getStaleSources();

    const args = mockFindMany.mock.calls[0][0];
    expect(args.orderBy).toEqual([{ verifiedAt: "asc" }]);
  });

  it("uses stale date threshold correctly", async () => {
    const before = Date.now() - STALE_THRESHOLD_MS;
    mockFindMany.mockResolvedValueOnce([]);

    await getStaleSources();

    const staleDate = mockFindMany.mock.calls[0][0].where.OR[1].verifiedAt.lt;
    const after = Date.now() - STALE_THRESHOLD_MS;
    expect(staleDate.getTime()).toBeGreaterThanOrEqual(before);
    expect(staleDate.getTime()).toBeLessThanOrEqual(after);
  });
});

describe("verifySourceUrl", () => {
  it("delegates to verifyWikipediaUrl", async () => {
    mockVerify.mockResolvedValueOnce(true);

    const result = await verifySourceUrl("https://en.wikipedia.org/wiki/Test");

    expect(mockVerify).toHaveBeenCalledWith("https://en.wikipedia.org/wiki/Test");
    expect(result).toBe(true);
  });

  it("returns false for dead URLs", async () => {
    mockVerify.mockResolvedValueOnce(false);

    const result = await verifySourceUrl("https://example.com/dead");

    expect(result).toBe(false);
  });
});

describe("runVerification", () => {
  const makeStaleSources = (ids: number[], topicIds: string[]) =>
    ids.map((id, i) => ({
      id,
      topicId: topicIds[i],
      url: `https://example.com/${id}`,
      title: `Source ${id}`,
      excerpt: "excerpt",
      domain: "wikipedia",
      license: "CC BY-SA 4.0",
      confidence: "high",
      verifiedAt: null,
      createdAt: new Date(),
    }));

  it("returns zero counts when no stale sources", async () => {
    mockFindMany.mockResolvedValueOnce([]);

    const result = await runVerification();

    expect(result.checked).toBe(0);
    expect(result.live).toBe(0);
    expect(result.removed).toBe(0);
    expect(result.cachesInvalidated).toBe(0);
    expect(result.invalidatedTopics).toEqual([]);
    expect(result.durationMs).toBeGreaterThanOrEqual(0);
  });

  it("updates verifiedAt for live sources", async () => {
    const sources = makeStaleSources([1, 2], ["topic-a", "topic-b"]);
    mockFindMany.mockResolvedValueOnce(sources);
    mockVerify.mockResolvedValue(true);
    mockUpdate.mockResolvedValue({});

    const result = await runVerification();

    expect(result.checked).toBe(2);
    expect(result.live).toBe(2);
    expect(result.removed).toBe(0);
    expect(mockUpdate).toHaveBeenCalledTimes(2);

    // Check that verifiedAt is updated to a recent date
    const updateCall = mockUpdate.mock.calls[0][0];
    expect(updateCall.where.id).toBe(1);
    expect(updateCall.data.verifiedAt).toBeInstanceOf(Date);
  });

  it("deletes dead sources and tracks affected topics", async () => {
    const sources = makeStaleSources([1, 2], ["topic-a", "topic-a"]);
    mockFindMany.mockResolvedValueOnce(sources);
    mockVerify.mockResolvedValue(false);
    mockDelete.mockResolvedValue({});
    // After deletion, remaining count for topic-a
    mockCount.mockResolvedValueOnce(0);
    // deleteMany for teaching cache
    mockDeleteMany.mockResolvedValueOnce({ count: 1 });

    const result = await runVerification();

    expect(result.checked).toBe(2);
    expect(result.live).toBe(0);
    expect(result.removed).toBe(2);
    expect(mockDelete).toHaveBeenCalledTimes(2);
  });

  it("invalidates teaching cache when topic drops below threshold", async () => {
    const sources = makeStaleSources([1], ["topic-x"]);
    mockFindMany.mockResolvedValueOnce(sources);
    mockVerify.mockResolvedValueOnce(false);
    mockDelete.mockResolvedValue({});
    // remaining sources for topic-x: 1 (below MIN_SOURCES = 2)
    mockCount.mockResolvedValueOnce(1);
    mockDeleteMany.mockResolvedValueOnce({ count: 1 });

    const result = await runVerification();

    expect(result.cachesInvalidated).toBe(1);
    expect(result.invalidatedTopics).toEqual(["topic-x"]);
    expect(mockDeleteMany).toHaveBeenCalledWith({
      where: { topicId: "topic-x" },
    });
  });

  it("does not invalidate cache when topic stays above threshold", async () => {
    const sources = makeStaleSources([1], ["topic-y"]);
    mockFindMany.mockResolvedValueOnce(sources);
    mockVerify.mockResolvedValueOnce(false);
    mockDelete.mockResolvedValue({});
    // remaining sources for topic-y: 3 (still above MIN_SOURCES)
    mockCount.mockResolvedValueOnce(3);

    const result = await runVerification();

    expect(result.cachesInvalidated).toBe(0);
    expect(result.invalidatedTopics).toEqual([]);
    expect(mockDeleteMany).not.toHaveBeenCalled();
  });

  it("handles mixed live and dead sources", async () => {
    const sources = makeStaleSources([1, 2, 3], ["topic-a", "topic-a", "topic-b"]);
    mockFindMany.mockResolvedValueOnce(sources);
    // Source 1: live, Source 2: dead, Source 3: live
    mockVerify
      .mockResolvedValueOnce(true)
      .mockResolvedValueOnce(false)
      .mockResolvedValueOnce(true);
    mockUpdate.mockResolvedValue({});
    mockDelete.mockResolvedValue({});
    // topic-a remaining count after deletion: 2 (still above threshold)
    mockCount.mockResolvedValueOnce(2);

    const result = await runVerification();

    expect(result.checked).toBe(3);
    expect(result.live).toBe(2);
    expect(result.removed).toBe(1);
    expect(result.cachesInvalidated).toBe(0);
    expect(mockUpdate).toHaveBeenCalledTimes(2);
    expect(mockDelete).toHaveBeenCalledTimes(1);
  });

  it("respects limit parameter", async () => {
    mockFindMany.mockResolvedValueOnce([]);

    await runVerification(5);

    const args = mockFindMany.mock.calls[0][0];
    expect(args.take).toBe(5);
  });

  it("deduplicates affected topics when multiple sources die for same topic", async () => {
    const sources = makeStaleSources([1, 2, 3], ["topic-z", "topic-z", "topic-z"]);
    mockFindMany.mockResolvedValueOnce(sources);
    mockVerify.mockResolvedValue(false);
    mockDelete.mockResolvedValue({});
    // remaining count = 0
    mockCount.mockResolvedValueOnce(0);
    mockDeleteMany.mockResolvedValueOnce({ count: 1 });

    const result = await runVerification();

    expect(result.removed).toBe(3);
    // Should only check/invalidate once despite 3 deleted sources
    expect(mockCount).toHaveBeenCalledTimes(1);
    expect(result.cachesInvalidated).toBe(1);
  });

  it("tracks durationMs", async () => {
    mockFindMany.mockResolvedValueOnce([]);

    const result = await runVerification();

    expect(typeof result.durationMs).toBe("number");
    expect(result.durationMs).toBeGreaterThanOrEqual(0);
  });
});

describe("getSourceHealthSummary", () => {
  it("returns comprehensive health metrics", async () => {
    // total sources, stale sources, never verified, total caches
    mockCount
      .mockResolvedValueOnce(100) // totalSources
      .mockResolvedValueOnce(10) // stale (older than threshold)
      .mockResolvedValueOnce(5) // never verified
      .mockResolvedValueOnce(20); // total caches

    // groupBy for topics with sources
    mockGroupBy
      .mockResolvedValueOnce([
        { topicId: "a" },
        { topicId: "b" },
        { topicId: "c" },
      ])
      // groupBy for topic source counts
      .mockResolvedValueOnce([
        { topicId: "a", _count: { id: 3 } },
        { topicId: "b", _count: { id: 1 } }, // below threshold
        { topicId: "c", _count: { id: 2 } },
      ]);

    const summary = await getSourceHealthSummary();

    expect(summary.totalSources).toBe(100);
    expect(summary.staleSources).toBe(15); // 10 stale + 5 never verified
    expect(summary.neverVerified).toBe(5);
    expect(summary.freshSources).toBe(85); // 100 - 10 - 5
    expect(summary.totalCaches).toBe(20);
    expect(summary.topicsWithSources).toBe(3);
    expect(summary.topicsAboveThreshold).toBe(2); // a (3) and c (2), not b (1)
    expect(summary.minSourcesRequired).toBe(2);
    expect(summary.staleThresholdDays).toBe(7);
  });

  it("handles empty database", async () => {
    mockCount
      .mockResolvedValueOnce(0)
      .mockResolvedValueOnce(0)
      .mockResolvedValueOnce(0)
      .mockResolvedValueOnce(0);
    mockGroupBy
      .mockResolvedValueOnce([])
      .mockResolvedValueOnce([]);

    const summary = await getSourceHealthSummary();

    expect(summary.totalSources).toBe(0);
    expect(summary.staleSources).toBe(0);
    expect(summary.freshSources).toBe(0);
    expect(summary.topicsWithSources).toBe(0);
    expect(summary.topicsAboveThreshold).toBe(0);
  });
});