paperlint 18.2.2 → 18.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,316 @@
1
+ /**
2
+ * The walk: for each field, the venue editions of `queries.json` in round-robin rounds; in each
3
+ * edition the candidates in their fixed order; each candidate through rules 1 to 4, the first
4
+ * failing rule logged as its reason; the first passing ones kept. Nothing is picked by hand.
5
+ *
6
+ * Quotas, caps and the 5 per edition are TOTALS over every entry of `venue-manifest.json`, earlier
7
+ * batches included: a field's quota counts the entries with that `field`, an edition's cap the
8
+ * entries of that series and year. So growing the set is raising a quota in `queries.json` and
9
+ * rerunning; a quota already met adds nothing.
10
+ */
11
+ import { stagingPlan, sha256, unpack } from "./archive.ts";
12
+ import { keptPaper, type Candidate, type KeptPaper } from "./paper.ts";
13
+ import {
14
+ judgeClass,
15
+ judgeComment,
16
+ judgeLicence,
17
+ judgeListedVenue,
18
+ judgeSize,
19
+ PER_EDITION,
20
+ preambleOf,
21
+ type Preamble,
22
+ SlotSchema,
23
+ type Slot,
24
+ } from "./rules.ts";
25
+ import {
26
+ arxivCandidates,
27
+ baseId,
28
+ eprint,
29
+ licenceUrl,
30
+ s2Candidates,
31
+ type Found,
32
+ type Get,
33
+ } from "./sources.ts";
34
+ import * as R from "remeda";
35
+ import { z } from "zod";
36
+
37
+ export const QueriesSchema = z.object({
38
+ hardCap: z.number(),
39
+ maxPages: z.number(),
40
+ quotas: z.record(z.string(), z.number()),
41
+ slots: z.array(SlotSchema),
42
+ });
43
+ export type Queries = Readonly<z.infer<typeof QueriesSchema>>;
44
+
45
+ /** The part of a manifest entry the counts read. */
46
+ export const CountedSchema = z.looseObject({
47
+ arxiv_id: z.string(),
48
+ field: z.string().optional(),
49
+ series: z.string().optional(),
50
+ year: z.number().optional(),
51
+ });
52
+ export type Counted = Readonly<z.infer<typeof CountedSchema>>;
53
+
54
+ /** One line of `probe-log.jsonl`: every candidate that reached a rule, kept or with its reason. */
55
+ export const ProbeLineSchema = z.looseObject({
56
+ id: z.string(),
57
+ field: z.string(),
58
+ series: z.string(),
59
+ year: z.number(),
60
+ rank: z.number(),
61
+ query: z.string(),
62
+ source: z.enum(["arxiv-comment", "semantic-scholar"]),
63
+ acceptance: z.enum(["arxiv-comment", "s2-venue-listing"]),
64
+ outcome: z.enum(["kept", "rejected"]),
65
+ reason: z.string(),
66
+ });
67
+ export type ProbeLine = Readonly<z.infer<typeof ProbeLineSchema>>;
68
+
69
+ /** How a venue edition's walk ended. */
70
+ export type SlotEnd = Readonly<{
71
+ slot: string;
72
+ ended: "full" | "exhausted" | "time" | "search error";
73
+ walkedTo: number;
74
+ error?: string;
75
+ }>;
76
+
77
+ /** What the walk is given: the world through `get`, and everything already decided. */
78
+ export type Walk = Readonly<{
79
+ queries: Queries;
80
+ /** Only these fields; all when null. */
81
+ only: readonly string[] | null;
82
+ /** Every entry of the venue manifest (the counts) — with the preprints', the ids to skip. */
83
+ entries: readonly Counted[];
84
+ otherIds: ReadonlySet<string>;
85
+ /** Earlier log lines: a candidate already judged for this edition is not judged again. */
86
+ logged: readonly ProbeLine[];
87
+ shipped: ReadonlySet<string>;
88
+ get: Get;
89
+ outOfTime: () => boolean;
90
+ /** Called on each new log line, with the paper when it is kept, as soon as it is decided. */
91
+ emit: (line: ProbeLine, paper?: KeptPaper) => void | Promise<void>;
92
+ }>;
93
+
94
+ const edition = (
95
+ s: Readonly<{ series?: string | undefined; year?: number | undefined }>,
96
+ ): string => `${String(s.series)} ${String(s.year)}`;
97
+ export const slotKey = (s: Slot): string =>
98
+ `${s.field}/${s.series} ${String(s.year)}`;
99
+
100
+ /** The rounds of one field: each slot's target per round, `cap + round`, at most `hardCap` and 5. */
101
+ export const targets = (
102
+ slots: readonly Slot[],
103
+ hardCap: number,
104
+ ): readonly (readonly [Slot, number])[] => {
105
+ const cap = Math.min(hardCap, PER_EDITION);
106
+ return Array.from({ length: cap + 1 }, (_, round) => round).flatMap((round) =>
107
+ slots
108
+ .map((s) => [s, Math.min(cap, s.cap + round)] as const)
109
+ .filter(
110
+ ([s, t]) => round === 0 || t !== Math.min(cap, s.cap + round - 1),
111
+ ),
112
+ );
113
+ };
114
+
115
+ type Judged = Readonly<{ reason: string; detail?: object; paper?: KeptPaper }>;
116
+ type Sources = Readonly<{
117
+ licence: Extract<ReturnType<typeof judgeLicence>, { ok: true }>;
118
+ plan: Extract<ReturnType<typeof stagingPlan>, { ok: true }>;
119
+ sourceSha: string;
120
+ }>;
121
+
122
+ /** Rule 2 and the download: the licence, then the e-print and what it stages. */
123
+ async function fetchSources(
124
+ get: Get,
125
+ id: string,
126
+ ): Promise<Sources | Readonly<{ reason: string }>> {
127
+ const oai = await licenceUrl(get, id);
128
+ if (!oai.ok) return { reason: `download failed: OAI ${oai.status}` };
129
+ const licence = judgeLicence(oai.url);
130
+ if (!licence.ok) return licence;
131
+ const src = await eprint(get, id);
132
+ if (!src.ok) return { reason: `download failed: src ${src.status}` };
133
+ const files = unpack(src.bytes);
134
+ if (!files.ok) return files;
135
+ const plan = stagingPlan(files.files);
136
+ return plan.ok ? { licence, plan, sourceSha: sha256(src.bytes) } : plan;
137
+ }
138
+
139
+ /** Rules 3 and 4 on what the e-print staged: the class and style, then the size. */
140
+ function judgeStaged(
141
+ slot: Slot,
142
+ plan: Sources["plan"],
143
+ ):
144
+ | Readonly<{ preamble: Preamble; style?: string; styleOpts?: string }>
145
+ | Judged {
146
+ const preamble = preambleOf(plan.mainText);
147
+ const cls = judgeClass(slot.classSpec, preamble);
148
+ if (!cls.ok)
149
+ return {
150
+ reason: cls.reason,
151
+ detail: { cls: preamble.cls, clsOpts: preamble.clsOpts },
152
+ };
153
+ const size = judgeSize(plan.size);
154
+ if (!size.ok) return { reason: size.reason };
155
+ return { preamble, ...R.omit(cls, ["ok"]) };
156
+ }
157
+
158
+ /** Rules 2 to 4, and the staging, for a candidate that passed rule 1. */
159
+ async function judgeSources(
160
+ w: Walk,
161
+ c: Candidate,
162
+ slot: Slot,
163
+ track: string | null,
164
+ ): Promise<Judged> {
165
+ const got = await fetchSources(w.get, c.id);
166
+ if ("reason" in got) return { reason: got.reason };
167
+ const staged = judgeStaged(slot, got.plan);
168
+ if ("reason" in staged) return staged;
169
+ return {
170
+ reason: "passes rules 1-4",
171
+ detail: { licence: got.licence.name, comment: c.comment.slice(0, 200) },
172
+ paper: keptPaper({ ...got, ...staged, c, slot, track, shipped: w.shipped }),
173
+ };
174
+ }
175
+
176
+ /** What a walk remembers across editions: the counted entries, the ids taken, the pairs judged. */
177
+ type State = Readonly<{
178
+ counted: Counted[];
179
+ ids: Set<string>;
180
+ judged: Set<string>;
181
+ }>;
182
+
183
+ const judgedKey = (id: string, s: Readonly<{ series: string; year: number }>) =>
184
+ `${id} ${s.series} ${String(s.year)}`;
185
+
186
+ /** A failed download is judged again on the next run; every other verdict stands. */
187
+ const stateOf = (w: Walk): State => ({
188
+ counted: [...w.entries],
189
+ ids: new Set([...w.otherIds, ...w.entries.map((e) => baseId(e.arxiv_id))]),
190
+ judged: new Set(
191
+ w.logged
192
+ .filter(
193
+ (l) => l.outcome === "kept" || !l.reason.startsWith("download failed"),
194
+ )
195
+ .map((l) => judgedKey(l.id, l)),
196
+ ),
197
+ });
198
+
199
+ /** Rule 1, then the rest, for one candidate. */
200
+ async function judge(w: Walk, st: State, c: Candidate, slot: Slot) {
201
+ if (st.ids.has(baseId(c.id))) return { reason: "already in the corpora" };
202
+ if (c.s2 !== undefined && c.updated === "")
203
+ return { reason: "arXiv metadata missing for the listed id" };
204
+ const rule1 =
205
+ c.s2 === undefined ? judgeComment(c, slot) : judgeListedVenue(c.s2.venue);
206
+ if (rule1.ok) return judgeSources(w, c, slot, rule1.track);
207
+ return {
208
+ reason: rule1.reason,
209
+ detail: c.s2 === undefined ? { comment: c.comment.slice(0, 160) } : {},
210
+ };
211
+ }
212
+
213
+ const lineOf = (slot: Slot, c: Candidate, v: Judged): ProbeLine => {
214
+ const s2 = slot.source === "semantic-scholar";
215
+ return {
216
+ id: c.id,
217
+ field: slot.field,
218
+ series: slot.series,
219
+ year: slot.year,
220
+ rank: c.rank,
221
+ query: c.query,
222
+ source: s2 ? "semantic-scholar" : "arxiv-comment",
223
+ acceptance: s2 ? "s2-venue-listing" : "arxiv-comment",
224
+ outcome: v.paper === undefined ? "rejected" : "kept",
225
+ reason: v.reason,
226
+ ...v.detail,
227
+ };
228
+ };
229
+
230
+ /** Judges one candidate not judged before for this edition, counts it when kept, emits its line. */
231
+ async function probe(
232
+ w: Walk,
233
+ st: State,
234
+ slot: Slot,
235
+ c: Candidate,
236
+ ): Promise<void> {
237
+ const key = judgedKey(c.id, slot);
238
+ if (st.judged.has(key)) return;
239
+ st.judged.add(key);
240
+ const verdict: Judged = await judge(w, st, c, slot);
241
+ if (verdict.paper !== undefined) {
242
+ const { field, series, year } = slot;
243
+ st.counted.push({ arxiv_id: c.id, field, series, year });
244
+ st.ids.add(baseId(c.id));
245
+ }
246
+ await w.emit(lineOf(slot, c, verdict), verdict.paper);
247
+ }
248
+
249
+ type Stop = Omit<SlotEnd, "slot" | "walkedTo">;
250
+
251
+ /** The candidate to judge next, or why the walk stops before it. */
252
+ const next = (
253
+ f: Found,
254
+ w: Walk,
255
+ full: () => boolean,
256
+ ): Readonly<{ stop: Stop }> | Readonly<{ candidate: Candidate }> => {
257
+ if ("searchError" in f)
258
+ return { stop: { ended: "search error", error: f.searchError } };
259
+ if (w.outOfTime()) return { stop: { ended: "time" } };
260
+ return full() ? { stop: { ended: "full" } } : { candidate: f };
261
+ };
262
+
263
+ async function walkSlot(
264
+ w: Walk,
265
+ st: State,
266
+ slot: Slot,
267
+ full: () => boolean,
268
+ ): Promise<Omit<SlotEnd, "slot">> {
269
+ const found =
270
+ slot.source === "semantic-scholar"
271
+ ? s2Candidates(w.get, slot)
272
+ : arxivCandidates(w.get, slot, w.queries.maxPages);
273
+ let walkedTo = 0;
274
+ for await (const f of found) {
275
+ const n = next(f, w, full);
276
+ if ("stop" in n) return { ...n.stop, walkedTo };
277
+ walkedTo = n.candidate.rank;
278
+ await probe(w, st, slot, n.candidate);
279
+ }
280
+ return { ended: full() ? "full" : "exhausted", walkedTo };
281
+ }
282
+
283
+ /**
284
+ * Walks every field of `w.queries`, and returns how each edition's walk ended. An edition is full
285
+ * when the manifest holds its round's target for it, or its field's quota: both TOTALS.
286
+ */
287
+ export async function collect(w: Walk): Promise<readonly SlotEnd[]> {
288
+ const st = stateOf(w);
289
+ const count = (keep: (e: Counted) => boolean) =>
290
+ st.counted.filter(keep).length;
291
+ const slots = w.queries.slots.filter(
292
+ (s) => w.only === null || w.only.includes(s.field),
293
+ );
294
+ const order = [...new Set(slots.map((s) => s.field))].flatMap((field) =>
295
+ targets(
296
+ slots.filter((s) => s.field === field),
297
+ w.queries.hardCap,
298
+ ),
299
+ );
300
+ const ends: SlotEnd[] = [];
301
+ // An edition that ran out of candidates or failed its search is not walked again in a later round.
302
+ const done = new Set<string>();
303
+ for (const [slot, target] of order) {
304
+ if (done.has(slotKey(slot))) continue;
305
+ const full = () =>
306
+ count((e) => edition(e) === edition(slot)) >= target ||
307
+ count((e) => e.field === slot.field) >=
308
+ (w.queries.quotas[slot.field] ?? 0);
309
+ if (full()) continue;
310
+ const end = await walkSlot(w, st, slot, full);
311
+ ends.push({ slot: slotKey(slot), ...end });
312
+ if (end.ended === "time") break;
313
+ if (end.ended !== "full") done.add(slotKey(slot));
314
+ }
315
+ return ends;
316
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * The transport over a fake `fetch` and a fake clock: arXiv's 3-second gap shared by all its hosts,
3
+ * Semantic Scholar's own gap, and the retries. No real request, no real wait.
4
+ */
5
+ import { describe, expect, test } from "vitest";
6
+ import { realClock, serviceOf, throttledGet, USER_AGENT } from "./http.ts";
7
+
8
+ type Answer = number | "drop";
9
+
10
+ /** A clock whose sleeps only move its time, and a `fetch` that answers from a script. */
11
+ function world(answers: readonly Answer[]) {
12
+ const t = { now: 0 };
13
+ const sleeps: number[] = [];
14
+ const calls: (readonly [string, number])[] = [];
15
+ const queue = [...answers];
16
+ const fetchFn: typeof fetch = (input, init) => {
17
+ const url = typeof input === "string" ? input : "not a string URL";
18
+ calls.push([url, t.now]);
19
+ // Guards: every request names this package.
20
+ expect(init?.headers).toEqual({ "user-agent": USER_AGENT });
21
+ const a = queue.shift() ?? 200;
22
+ return a === "drop"
23
+ ? Promise.reject(new Error("socket hang up"))
24
+ : Promise.resolve(new Response(a === 200 ? "body" : "", { status: a }));
25
+ };
26
+ const clock = {
27
+ now: () => t.now,
28
+ sleep: (ms: number) => {
29
+ sleeps.push(ms);
30
+ t.now += ms;
31
+ return Promise.resolve();
32
+ },
33
+ };
34
+ return { get: throttledGet(fetchFn, clock), sleeps, calls };
35
+ }
36
+
37
+ describe("the gap between requests", () => {
38
+ test("arXiv's hosts share one gap; another service has its own", async () => {
39
+ const w = world([]);
40
+ await w.get("https://export.arxiv.org/api/query?a");
41
+ await w.get("https://api.semanticscholar.org/x");
42
+ await w.get("https://arxiv.org/src/1");
43
+ // Guards: the e-print waits 3.1 s after the export API, while S2 did not wait for arXiv.
44
+ expect(w.calls).toEqual([
45
+ ["https://export.arxiv.org/api/query?a", 0],
46
+ ["https://api.semanticscholar.org/x", 0],
47
+ ["https://arxiv.org/src/1", 3100],
48
+ ]);
49
+ // Guards: which hosts are arXiv.
50
+ expect(
51
+ [
52
+ "https://arxiv.org/",
53
+ "https://export.arxiv.org/",
54
+ "https://notarxiv.org/",
55
+ ].map((u) => serviceOf(u)),
56
+ ).toEqual([
57
+ { key: "arxiv", gapMs: 3100 },
58
+ { key: "arxiv", gapMs: 3100 },
59
+ { key: "notarxiv.org", gapMs: 1100 },
60
+ ]);
61
+ });
62
+ });
63
+
64
+ describe("retries", () => {
65
+ test("a 429, a 5xx and a dropped connection are retried with a growing pause", async () => {
66
+ const w = world([429, 503, "drop", 200]);
67
+ const r = await w.get("https://api.semanticscholar.org/x");
68
+ // Guards: the fourth attempt's answer comes back.
69
+ expect(r).toEqual({ ok: true, bytes: new Uint8Array(Buffer.from("body")) });
70
+ // Guards: 10, 20, 30 s between attempts (the 1.1 s gap already passed).
71
+ expect(w.sleeps).toEqual([10_000, 20_000, 30_000]);
72
+ });
73
+
74
+ test("a 404 is final, and four failures give up", async () => {
75
+ const w = world([404, 500, 500, 500, 500]);
76
+ // Guards: a client error is not retried.
77
+ expect(await w.get("https://api.semanticscholar.org/a")).toEqual({
78
+ ok: false,
79
+ status: "404",
80
+ });
81
+ // Guards: the last status, with the number of attempts.
82
+ expect(await w.get("https://api.semanticscholar.org/b")).toEqual({
83
+ ok: false,
84
+ status: "500 after 4 attempts",
85
+ });
86
+ expect(w.calls.length).toBe(5);
87
+ });
88
+ });
89
+
90
+ test("the real clock sleeps and tells the time", async () => {
91
+ const before = realClock.now();
92
+ await realClock.sleep(1);
93
+ // Guards: time moves forward across a sleep.
94
+ expect(realClock.now()).toBeGreaterThanOrEqual(before);
95
+ });
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The transport behind `Get`: one request at a time per service, a fixed gap between two requests
3
+ * to the same service (arXiv asks for 3 s between ANY two of its requests, export API and e-prints
4
+ * alike), and a retry after a 429, a 5xx or a dropped connection. `fetch` and the clock are passed
5
+ * in, so a test runs it on fakes without waiting.
6
+ */
7
+ import type { Fetched, Get } from "./sources.ts";
8
+
9
+ export type Clock = Readonly<{
10
+ now: () => number;
11
+ sleep: (ms: number) => Promise<void>;
12
+ }>;
13
+
14
+ /** The real clock. */
15
+ export const realClock: Clock = {
16
+ now: Date.now,
17
+ sleep: (ms) => new Promise<void>((done) => setTimeout(done, ms)),
18
+ };
19
+
20
+ export const USER_AGENT =
21
+ "paperlint-fixtures/1.0 (+https://github.com/zernie/paperlint)";
22
+
23
+ /** arXiv's hosts share one gap (3.1 s); any other host, Semantic Scholar's, has its own (1.1 s). */
24
+ export const serviceOf = (
25
+ url: string,
26
+ ): Readonly<{ key: string; gapMs: number }> => {
27
+ const host = new URL(url).hostname;
28
+ return host === "arxiv.org" || host.endsWith(".arxiv.org")
29
+ ? { key: "arxiv", gapMs: 3100 }
30
+ : { key: host, gapMs: 1100 };
31
+ };
32
+
33
+ /** One request: its answer, or the status worth a retry (429, 5xx, a dropped connection). */
34
+ const once = async (
35
+ fetchFn: typeof fetch,
36
+ url: string,
37
+ ): Promise<Fetched | Readonly<{ retry: string }>> => {
38
+ try {
39
+ const res = await fetchFn(url, { headers: { "user-agent": USER_AGENT } });
40
+ if (res.ok)
41
+ return { ok: true, bytes: new Uint8Array(await res.arrayBuffer()) };
42
+ const status = String(res.status);
43
+ return res.status === 429 || res.status >= 500
44
+ ? { retry: status }
45
+ : { ok: false, status };
46
+ } catch (e) {
47
+ return { retry: String(e) };
48
+ }
49
+ };
50
+
51
+ export function throttledGet(
52
+ fetchFn: typeof fetch,
53
+ clock: Clock,
54
+ attempts = 4,
55
+ ): Get {
56
+ const last = new Map<string, number>();
57
+ const wait = async (key: string, gapMs: number): Promise<void> => {
58
+ const due = (last.get(key) ?? -Infinity) + gapMs - clock.now();
59
+ if (due > 0) await clock.sleep(due);
60
+ last.set(key, clock.now());
61
+ };
62
+ const tryFrom = async (url: string, attempt: number): Promise<Fetched> => {
63
+ const { key, gapMs } = serviceOf(url);
64
+ await wait(key, gapMs);
65
+ const r = await once(fetchFn, url);
66
+ if (!("retry" in r)) return r;
67
+ if (attempt >= attempts)
68
+ return {
69
+ ok: false,
70
+ status: `${r.retry} after ${String(attempts)} attempts`,
71
+ };
72
+ await clock.sleep(10_000 * attempt);
73
+ return tryFrom(url, attempt + 1);
74
+ };
75
+ return (url) => tryFrom(url, 1);
76
+ }