Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions components/reports/publish-flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ import { getErrorMessage, useAppToast } from "@/lib/toast/use-app-toast";
import { stepBack, withoutKeys } from "@/lib/url-state/step-back";
import { useWorkspaceSlug, workspaceHref } from "@/lib/workspaces/href";
import { inWorkspace, useWorkspace, useWorkspaceScope } from "@/lib/workspaces/url";
import { MAX_PDF_BYTES, MAX_PDF_MB } from "@/lib/files/limits";
import { REPORT_PDF_BYTES, REPORT_PDF_MB } from "@/lib/files/limits";
import { useUpload } from "@/lib/files/upload";
import { cn, finePointer } from "@/lib/utils";

Expand Down Expand Up @@ -1952,7 +1952,7 @@ function UploadStep({ report, workspaceId, onAttached, onBack, onNext }: { repor
const format = useFormatter();
/**
* A file's size, in megabytes or kilobytes as the reader's language writes them. Counted in 1,024s, as the limit
* (`MAX_PDF_MB`) is: a PDF just under it never reads as over it.
* (`REPORT_PDF_MB`) is: a PDF just under it never reads as over it.
*/
const bytes = (n: number) => (n > 1024 * 1024 ? format.number(n / 1024 / 1024, { style: "unit", unit: "megabyte", minimumFractionDigits: 1, maximumFractionDigits: 1 }) : format.number(Math.round(n / 1024), { style: "unit", unit: "kilobyte" }));
const startUpload = useMutation(api.reports.flow.startUpload);
Expand Down Expand Up @@ -1996,7 +1996,7 @@ function UploadStep({ report, workspaceId, onAttached, onBack, onNext }: { repor
say(null);
if (!/\.pdf$/i.test(picked.name)) return say(t("notPdf", { name: picked.name }));
if (picked.size === 0) return say(t("emptyFile"));
if (picked.size > MAX_PDF_BYTES) return say(t("tooBig", { max: MAX_PDF_MB }));
if (picked.size > REPORT_PDF_BYTES) return say(t("tooBig", { max: REPORT_PDF_MB }));
setSending(picked);
// Whether the file got as far as Openscholar: a failure says which half went wrong.
let arrived = false;
Expand Down Expand Up @@ -2068,7 +2068,7 @@ function UploadStep({ report, workspaceId, onAttached, onBack, onNext }: { repor
<>
<FileUp className="size-6 text-primary" />
<span className="text-sm font-medium">{t(by ? "drop" : "bylineBy.chooseFirst")}</span>
<span className="text-xs text-muted-foreground">{t("dropHint", { max: MAX_PDF_MB })}</span>
<span className="text-xs text-muted-foreground">{t("dropHint", { max: REPORT_PDF_MB })}</span>
</>
)}
</button>
Expand Down
15 changes: 15 additions & 0 deletions convex/files/read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,21 @@ export async function fileBlob(ctx: Pick<ActionCtx, "runQuery" | "storage">, fil
return response ? new Blob([await response.arrayBuffer()], { type: kept.contentType }) : null;
}

/**
* A file's whole bytes, for an action that works on them; null when it is gone. From R2 they are the answer's own
* buffer, held once: a 500 MB PDF isn't copied into a Blob on the way.
*/
export async function fileBytes(ctx: Pick<ActionCtx, "runQuery" | "storage">, file: FileRef): Promise<Uint8Array | null> {
const kept = await ctx.runQuery(internal.files.uploads.keyOf, { id: file });
if (!kept) {
const blob = await ctx.storage.get(file as Id<"_storage">);
return blob ? new Uint8Array(await blob.arrayBuffer()) : null;
}
const response = await read(kept.key);
if (!response) console.error(JSON.stringify({ event: "upload-missing-in-r2", file, key: kept.key }));
return response ? new Uint8Array(await response.arrayBuffer()) : null;
}

/** A file's text, for an action; empty when it is gone. */
export async function fileText(ctx: Pick<ActionCtx, "runQuery" | "storage">, file: FileRef) {
return (await (await fileBlob(ctx, file))?.text()) ?? "";
Expand Down
4 changes: 2 additions & 2 deletions convex/files/uploads.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { api, internal } from "../_generated/api";
import type { Id } from "../_generated/dataModel";
import { UPLOAD_PART_BYTES } from "../../lib/files/limits";
import { REPORT_PDF_BYTES, UPLOAD_PART_BYTES } from "../../lib/files/limits";
import { R2_TEST, setup, stubUploads } from "../reports/reports.test-support";
import { freshUpload } from "./uploads";

Expand Down Expand Up @@ -49,7 +49,7 @@ describe("uploads to R2", () => {
const large = await world.author.action(api.files.uploads.start, { purpose: "report-supplement", name: "data.zip", contentType: "application/zip", bytes: UPLOAD_PART_BYTES * 2 + 1 });
expect(large.parts).toHaveLength(3);
expect(large.partBytes).toBe(UPLOAD_PART_BYTES);
await expect(world.author.action(api.files.uploads.start, { purpose: "report-pdf", name: "huge.pdf", contentType: "application/pdf", bytes: 101 * 1024 * 1024 })).rejects.toThrow(/too large/);
await expect(world.author.action(api.files.uploads.start, { purpose: "report-pdf", name: "huge.pdf", contentType: "application/pdf", bytes: REPORT_PDF_BYTES + 1 })).rejects.toThrow(/too large/);
await expect(world.author.action(api.files.uploads.start, { purpose: "report-pdf", name: "empty.pdf", contentType: "application/pdf", bytes: 0 })).rejects.toThrow(/empty/);
});

Expand Down
4 changes: 2 additions & 2 deletions convex/reports/flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { withFoundDois, costOf, DETAILS_MAX_BYTES, DETAIL_CAPS, REPORT_TYPES, RE
import { isCoverShape } from "../../lib/papers/cover";
import { countStart, startsLeft } from "./limits";
import { refuseClosed } from "./intake";
import { MAX_PDF_BYTES, MAX_PDF_MB } from "../../lib/files/limits";
import { REPORT_PDF_BYTES, REPORT_PDF_MB } from "../../lib/files/limits";
import { formVersion } from "./corrections";
import { notify } from "./mail";
import { register } from "./registering";
Expand Down Expand Up @@ -626,7 +626,7 @@ export const attachPdf = workspaceMutation({
: report.doiUnder ? DOI_WAITS
: !/\.pdf$/i.test(name.trim()) ? "Choose a PDF."
: stored.bytes === 0 ? "That file is empty. Choose the PDF again."
: stored.bytes > MAX_PDF_BYTES ? `A report's PDF is at most ${MAX_PDF_MB} MB.`
: stored.bytes > REPORT_PDF_BYTES ? `A report's PDF is at most ${REPORT_PDF_MB} MB.`
: null;
if (refused || !report) {
await forget(ctx, file, picture ? cover : undefined);
Expand Down
8 changes: 4 additions & 4 deletions convex/reports/pdfBytes.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
// A report's PDF as the actions that work on it hold it (./reading.ts, ./checks.ts).
import type { ActionCtx } from "../_generated/server";
import { fileBlob } from "../files/read";
import { fileBytes } from "../files/read";
import type { FileRef } from "../files/validators";

/**
* A stored PDF's bytes, read on their own. The Blob they arrive in is let go as soon as they are out of it, so a PDF
* near the upload limit is held once while it is worked on, not twice. Throws when the file is gone.
*/
export async function storedBytes(ctx: Pick<ActionCtx, "runQuery" | "storage">, file: FileRef) {
const blob = await fileBlob(ctx, file);
if (!blob) throw new Error("The report's PDF is gone.");
return new Uint8Array(await blob.arrayBuffer());
const bytes = await fileBytes(ctx, file);
if (!bytes) throw new Error("The report's PDF is gone.");
return bytes;
}
21 changes: 21 additions & 0 deletions convex/reports/reader.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// A scan too large to be given to the reader whole is refused before anything is sent: its bytes as base64 would pass
// what a string can hold, and the author types the details in instead.
import { describe, expect, it } from "vitest";
import { MockLanguageModelV3 } from "ai/test";
import { catalogue, SCAN_LIMIT } from "./reader";

describe("a report's PDF read whole", () => {
it("is never sent when it is a scan past what the reader is given", async () => {
let asked = 0;
const model = new MockLanguageModelV3({
doGenerate: async () => {
asked++;
throw new Error("not to be asked");
},
});
await expect(catalogue(new Uint8Array(SCAN_LIMIT + 1), "", "scan.pdf", { model, slug: "test/model" })).rejects.toThrow(/no text/);
// As the reading asks for it: without the file's bytes, which it never reads past the limit, and with no text.
await expect(catalogue(null, "", "scan.pdf", { model, slug: "test/model" })).rejects.toThrow(/no text/);
expect(asked).toBe(0);
});
});
9 changes: 9 additions & 0 deletions convex/reports/reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,12 @@ const TEXT_LIMIT = 400_000;
* request of a third more bytes again, which providers refuse and a Convex action has no memory to build.
*/
export const FILE_LIMIT = 20 * 1024 * 1024;
/**
* The most a PDF the reader is given whole may be, when it has no text to read instead (a scan): what reports could
* be before they could be 500 MB. Past it, its bytes as base64 pass what a string can hold, and the author types the
* details in.
*/
export const SCAN_LIMIT = 100 * 1024 * 1024;
/** How long one reading may take. Two of them, as a file and then as text, end before the page gives up on the PDF (STUCK_MS). */
const READ_MS = 100_000;

Expand Down Expand Up @@ -185,8 +191,11 @@ export async function catalogue(pdf: Uint8Array | null, text: string, fileName:
if (!ended) console.warn(JSON.stringify({ event: "report-reference-list-cut", model: slug, parts: part, references: references.length }));
return { ...first.output, references };
};
// Nothing to read: no file (a scan too large to give whole) and no text. Asked about nothing, a model invents.
if (!pdf && !text.trim()) throw new Error("The PDF has no text, and it is too large to be given whole.");
// No file is given when it is too large to send and its text is there to read.
if (!pdf || (pdf.length > FILE_LIMIT && text.trim())) return ask("text");
if (pdf.length > SCAN_LIMIT) throw new Error(`The PDF is ${Math.round(pdf.length / 1048576)} MB and has no text, more than the reader is given whole.`);
try {
return await ask("file");
} catch (error) {
Expand Down
7 changes: 4 additions & 3 deletions convex/reports/reading.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { buildPageTextFromItems } from "../../lib/extraction/pdfjs-text";
import type { BylineTrouble } from "../../lib/reports/byline-page";
import { blankDetails, carries, DETAILS_MAX_BYTES, DETAIL_CAPS, DETAIL_TEXT, type Metadata } from "../../lib/reports/report";
import { storedBytes } from "./pdfBytes";
import { FILE_LIMIT, readDetails, type Read } from "./reader";
import { FILE_LIMIT, SCAN_LIMIT, readDetails, type Read } from "./reader";

/** What the model read, held to what a report keeps: a PDF with more references than that keeps the first of them,
* a title, keyword or grant number longer than a report holds is cut to fit, and a date still to come is today,
Expand Down Expand Up @@ -79,8 +79,9 @@ export const read = internalAction({
if (!job.modelId) throw new Error("The model that reads PDFs is no longer offered.");
const { model, modelSlug } = await resolveOpenRouterModel(ctx, job.modelId);
// The page Openscholar added says details read before: the reader is given the report's own pages, the PDF as
// its author uploaded it. A PDF too large to send is read from its text, so its bytes are never asked for.
const own = job.stamped ? (job.original ? await storedBytes(ctx, job.original) : await (await import("../../lib/reports/byline-page")).withoutLastPage(await bytes())) : size > FILE_LIMIT && !scanned ? null : await bytes();
// its author uploaded it. A PDF too large to send is read from its text, so its bytes are never asked for; a
// scan too large to be given whole has nothing to be read from (`SCAN_LIMIT`).
const own = (size > FILE_LIMIT && !scanned) || size > SCAN_LIMIT ? null : job.stamped ? (job.original ? await storedBytes(ctx, job.original) : await (await import("../../lib/reports/byline-page")).withoutLastPage(await bytes())) : await bytes();
const done = await readDetails({ pdf: own, text: read, fileName: job.name, ownDoi: job.doi, reader: { model, slug: modelSlug, effort: job.effort } });
Comment thread
sickerine marked this conversation as resolved.
Resolved
const found = capped(done.metadata);
// A reading that found neither a title nor an abstract read nothing: the author fills the details in, as for one that failed.
Expand Down
10 changes: 9 additions & 1 deletion lib/files/limits.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,20 @@
export const MAX_PDF_MB = 100;
export const MAX_PDF_BYTES = MAX_PDF_MB * 1024 * 1024;

/**
* A report's PDF, sent straight to R2. Its reading holds it whole: measured 2026-12-01 on 500 MB PDFs of 100, 1,000
* and 4,000 pages under the backend's 4 GB heap, at most 516 MB of heap and 2.65 GB of memory in all (the byline page
* on 4,000 pages of text), a few seconds each.
*/
export const REPORT_PDF_MB = 500;
export const REPORT_PDF_BYTES = REPORT_PDF_MB * 1024 * 1024;

/** What Zenodo keeps in one record: 50 GB (help.zenodo.org/docs/deposit/manage-files), its supplements' limit together. */
export const ZENODO_RECORD_BYTES = 50_000_000_000;

/** The most a file uploaded as each of these may be. */
export const UPLOAD_MAX_BYTES = {
"report-pdf": MAX_PDF_BYTES,
"report-pdf": REPORT_PDF_BYTES,
"report-cover": 10 * 1024 * 1024,
"report-supplement": ZENODO_RECORD_BYTES,
} as const;
Expand Down
Loading