From 75a71d242e461761cb0cf47a5624deacb70dae88 Mon Sep 17 00:00:00 2001 From: Vincent Koc Date: Mon, 30 Nov 2026 14:58:21 +0800 Subject: [PATCH] refactor: isolate Featured evidence reads --- convex/_generated/api.d.ts | 2 + convex/featuredIntelligence.ts | 256 +------------------------ convex/lib/featuredIntelligenceRead.ts | 254 ++++++++++++++++++++++++ convex/lib/searchReportEvidence.ts | 2 +- 4 files changed, 259 insertions(+), 255 deletions(-) create mode 100644 convex/lib/featuredIntelligenceRead.ts diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts index a776b4337c..bfa4f73d0f 100644 --- a/convex/_generated/api.d.ts +++ b/convex/_generated/api.d.ts @@ -110,6 +110,7 @@ import type * as lib_embeddings from "../lib/embeddings.js"; import type * as lib_endorAnalysis from "../lib/endorAnalysis.js"; import type * as lib_experimentalTemplates from "../lib/experimentalTemplates.js"; import type * as lib_featuredIntelligence from "../lib/featuredIntelligence.js"; +import type * as lib_featuredIntelligenceRead from "../lib/featuredIntelligenceRead.js"; import type * as lib_featuredPolicy from "../lib/featuredPolicy.js"; import type * as lib_featuredSelections from "../lib/featuredSelections.js"; import type * as lib_fileValidators from "../lib/fileValidators.js"; @@ -498,6 +499,7 @@ declare const fullApi: ApiFromModules<{ "lib/endorAnalysis": typeof lib_endorAnalysis; "lib/experimentalTemplates": typeof lib_experimentalTemplates; "lib/featuredIntelligence": typeof lib_featuredIntelligence; + "lib/featuredIntelligenceRead": typeof lib_featuredIntelligenceRead; "lib/featuredPolicy": typeof lib_featuredPolicy; "lib/featuredSelections": typeof lib_featuredSelections; "lib/fileValidators": typeof lib_fileValidators; diff --git a/convex/featuredIntelligence.ts b/convex/featuredIntelligence.ts index 168e452bd6..9ad67964ae 100644 --- a/convex/featuredIntelligence.ts +++ b/convex/featuredIntelligence.ts @@ -1,19 +1,14 @@ -import { paginationOptsValidator, type PaginationOptions } from "convex/server"; +import { paginationOptsValidator } from "convex/server"; import { v } from "convex/values"; -import { internal } from "./_generated/api"; import type { ActionCtx } from "./_generated/server"; import { action, internalAction, internalQuery } from "./functions"; import { assertModerator, requireUserFromAction } from "./lib/access"; import { renderFeaturedEvidence, type FeaturedIntelligenceReport, - type FeaturedEvidence, - type AdoptionReport, - type AdoptionArtifact, } from "./lib/featuredIntelligence"; -import { readReport as readSearchReport } from "./lib/searchInsightRead"; +import { collectFeaturedEvidence } from "./lib/featuredIntelligenceRead"; import { - SEARCH_DAY_MS, searchArtifactKind, searchInsightSource, searchScope, @@ -21,7 +16,6 @@ import { type SearchInsightArgs, } from "./lib/searchInsights"; -const ADOPTION_INSPECTION_LIMIT = 100; const args = { artifactKind: searchArtifactKind, endDay: v.optional(v.number()), @@ -56,54 +50,6 @@ async function readReport( return renderFeaturedEvidence(await collectFeaturedEvidence(ctx, input), input.limit ?? 20); } -export async function collectFeaturedEvidence( - ctx: ActionCtx, - input: SearchInsightArgs & { artifactKind: SearchArtifactKind }, - weeklyDigest = false, -): Promise { - const limit = input.limit ?? 20; - if (!Number.isInteger(limit) || limit < 1 || limit > 100) - throw new Error("limit must be between 1 and 100"); - const startedAt = Date.now(); - const endDay = input.endDay ?? Math.floor(startedAt / SEARCH_DAY_MS) * SEARCH_DAY_MS; - const [searchReport, currentFeatured, adoption, editorial] = await Promise.all([ - readSearchReport(ctx, { ...input, includeCurrentResults: true, limit: 100 }), - ctx.runQuery(internal.featuredArtifacts.readCurrentFeaturedInternal, { - artifactKind: input.artifactKind, - }), - readMonthlyAdoption(ctx, input.artifactKind, endDay, weeklyDigest), - input.artifactKind === "plugin" - ? ctx.runQuery(internal.featuredSelections.readEditorialInternal, { artifactKind: "plugin" }) - : Promise.resolve({ revision: 0, items: [] }), - ]); - return { - searchReport, - currentFeatured, - adoption, - editorial, - currentEditorialRevision: editorial.revision, - editorialArtifacts: await ctx.runQuery(internal.featuredArtifacts.readInternal, { - identities: editorial.items.map((item) => item.id), - editorial: true, - }), - metadataCheckedAt: Math.max( - startedAt, - adoption.metadataCheckedAt ?? 0, - searchReport.metadataCheckedAt ?? 0, - ), - }; -} - -const INSTALL_RANKING_VERSION = "featured-installs-30d-v1"; -const PLUGIN_RANKING_VERSION = "featured-downloads-30d-v1"; -type MetricTotal = { - id: string; - count30d: number; - count7d: number; - importedRows: number; - importDatasetVersions: Set; -}; - // Read raw index pages before selecting nonzero rows. A database filter can // exhaust its scan budget before finding a page, silently losing ranking facts. export const readDailyRankingStatsInternal = internalQuery({ @@ -151,201 +97,3 @@ export const readPackageIdentitiesInternal = internalQuery({ ); }, }); - -async function readMonthlyAdoption( - ctx: ActionCtx, - artifactKind: SearchArtifactKind, - periodEnd: number, - weeklyDigest: boolean, -): Promise { - const collectionStartedAt = Date.now(); - if ( - !Number.isSafeInteger(periodEnd) || - periodEnd % SEARCH_DAY_MS || - periodEnd > Math.floor(collectionStartedAt / SEARCH_DAY_MS) * SEARCH_DAY_MS - ) - throw new Error("Monthly adoption requires completed UTC days"); - const endDay = periodEnd / SEARCH_DAY_MS; - const pluginDownloads = artifactKind === "plugin" && !weeklyDigest; - const rankingVersion = pluginDownloads ? PLUGIN_RANKING_VERSION : INSTALL_RANKING_VERSION; - const periodStart = periodEnd - 30 * SEARCH_DAY_MS; - const periodStart7d = periodEnd - 7 * SEARCH_DAY_MS; - const totals = new Map(); - let scannedRows = 0; - let importedRows = 0; - const importDatasetVersions = new Set(); - const readPage = async ( - day: number, - paginationOpts: PaginationOptions, - ): Promise<{ isDone: boolean; continueCursor: string }> => { - const result = await ctx.runQuery(internal.featuredIntelligence.readDailyRankingStatsInternal, { - artifactKind, - day, - pluginDownloads, - paginationOpts, - }); - if (result.pageStatus === "SplitRequired") { - // Native cursor ranges replace the incomplete parent; never count both. - if ( - !result.splitCursor || - result.splitCursor === paginationOpts.cursor || - result.splitCursor === result.continueCursor - ) - throw new Error("Monthly adoption page cannot be completed"); - await readPage(day, { ...paginationOpts, endCursor: result.splitCursor }); - await readPage(day, { - ...paginationOpts, - cursor: result.splitCursor, - endCursor: result.continueCursor, - }); - } else { - scannedRows += result.scannedRows; - for (const row of result.page) { - let total = totals.get(row.id); - if (!total) { - total = { - id: row.id, - count30d: 0, - count7d: 0, - importedRows: 0, - importDatasetVersions: new Set(), - }; - totals.set(row.id, total); - } - total.count30d += row.count; - if (day >= endDay - 7) total.count7d += row.count; - if (row.imported) { - total.importedRows++; - importedRows++; - } - if (row.dataset) { - total.importDatasetVersions.add(row.dataset); - importDatasetVersions.add(row.dataset); - } - } - } - return { isDone: result.isDone, continueCursor: result.continueCursor }; - }; - // Four independent day scans bound active transactions. Ranking starts only - // after every day completes; no Trending or download-sorted admission cap. - let nextDay = endDay - 30; - let failed = false; - const scans = await Promise.allSettled( - Array.from({ length: 4 }, async () => { - try { - while (nextDay < endDay) { - if (failed) break; - const day = nextDay++; - let cursor: string | null = null; - for (;;) { - if (failed) break; - const page = await readPage(day, { - cursor, - numItems: 5000, - maximumBytesRead: 8_000_000, - }); - if (page.isDone) break; - cursor = page.continueCursor; - } - } - } catch (error) { - failed = true; - throw error; - } - }), - ); - for (const result of scans) if (result.status === "rejected") throw result.reason; - let ranked = [...totals.values()].filter((entry) => entry.count30d > 0); - if (artifactKind === "plugin") { - const resolved: MetricTotal[] = []; - for (let offset = 0; offset < ranked.length; offset += 100) { - const batch = ranked.slice(offset, offset + 100); - const identities = await ctx.runQuery( - internal.featuredIntelligence.readPackageIdentitiesInternal, - { ids: batch.map((entry) => entry.id as import("./_generated/dataModel").Id<"packages">) }, - ); - identities.forEach((entry, index) => { - if (entry.identity) resolved.push({ ...batch[index], id: entry.identity }); - }); - } - ranked = resolved; - } - ranked.sort( - (a, b) => - b.count30d - a.count30d || b.count7d - a.count7d || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0), - ); - const generatedAt = Date.now(); - const snapshotId = `${artifactKind}:${periodEnd}:${collectionStartedAt}`; - const artifacts: AdoptionArtifact[] = []; - let inspectedItems = 0; - let eligibleItems = 0; - let retainedExclusions = 0; - // Limit rich report metadata after ranking the complete metric population. - // Ineligible leading rows cannot starve lower-ranked eligible candidates. - for ( - let offset = 0; - offset < ranked.length && eligibleItems < ADOPTION_INSPECTION_LIMIT; - offset += 100 - ) { - const batch = ranked.slice(offset, offset + 100); - const metadata = await ctx.runQuery(internal.featuredArtifacts.readInternal, { - identities: batch.map((entry) => entry.id), - }); - const byId = new Map(metadata.map((entry) => [entry.id, entry])); - inspectedItems += batch.length; - for (const [index, entry] of batch.entries()) { - const artifact = byId.get(entry.id); - if (!artifact) continue; - if (artifact.eligibleForFeatured) eligibleItems++; - else if (retainedExclusions++ >= ADOPTION_INSPECTION_LIMIT) continue; - artifacts.push({ - artifact, - evidence: { - ...(pluginDownloads - ? { - source: "package-daily-downloads" as const, - downloads30d: entry.count30d, - downloads7d: entry.count7d, - } - : { - source: - artifactKind === "plugin" - ? ("package-daily-installs" as const) - : ("skill-daily-installs" as const), - installs30d: entry.count30d, - installs7d: entry.count7d, - }), - rank: offset + index + 1, - snapshotId, - rankingVersion, - periodStart, - periodStart7d, - periodEnd, - generatedAt, - importedRows: entry.importedRows, - importDatasetVersions: [...entry.importDatasetVersions].sort(), - }, - }); - } - } - return { - summary: { - status: "available", - generatedAt, - collectionStartedAt, - periodStart, - periodStart7d, - periodEnd, - snapshotId, - rankingVersion, - totalItems: ranked.length, - inspectedItems, - truncated: inspectedItems < ranked.length || artifacts.length < inspectedItems, - scannedRows, - importedRows, - importDatasetVersions: [...importDatasetVersions].sort(), - }, - artifacts, - metadataCheckedAt: Date.now(), - }; -} diff --git a/convex/lib/featuredIntelligenceRead.ts b/convex/lib/featuredIntelligenceRead.ts new file mode 100644 index 0000000000..fb641f3285 --- /dev/null +++ b/convex/lib/featuredIntelligenceRead.ts @@ -0,0 +1,254 @@ +import type { PaginationOptions } from "convex/server"; +import { internal } from "../_generated/api"; +import type { ActionCtx } from "../_generated/server"; +import type { AdoptionArtifact, AdoptionReport, FeaturedEvidence } from "./featuredIntelligence"; +import { readReport as readSearchReport } from "./searchInsightRead"; +import { SEARCH_DAY_MS, type SearchArtifactKind, type SearchInsightArgs } from "./searchInsights"; + +const ADOPTION_INSPECTION_LIMIT = 100; + +export async function collectFeaturedEvidence( + ctx: Pick, + input: SearchInsightArgs & { artifactKind: SearchArtifactKind }, + weeklyDigest = false, +): Promise { + const limit = input.limit ?? 20; + if (!Number.isInteger(limit) || limit < 1 || limit > 100) + throw new Error("limit must be between 1 and 100"); + const startedAt = Date.now(); + const endDay = input.endDay ?? Math.floor(startedAt / SEARCH_DAY_MS) * SEARCH_DAY_MS; + const [searchReport, currentFeatured, adoption, editorial] = await Promise.all([ + readSearchReport(ctx, { ...input, includeCurrentResults: true, limit: 100 }), + ctx.runQuery(internal.featuredArtifacts.readCurrentFeaturedInternal, { + artifactKind: input.artifactKind, + }), + readMonthlyAdoption(ctx, input.artifactKind, endDay, weeklyDigest), + input.artifactKind === "plugin" + ? ctx.runQuery(internal.featuredSelections.readEditorialInternal, { artifactKind: "plugin" }) + : Promise.resolve({ revision: 0, items: [] }), + ]); + return { + searchReport, + currentFeatured, + adoption, + editorial, + currentEditorialRevision: editorial.revision, + editorialArtifacts: await ctx.runQuery(internal.featuredArtifacts.readInternal, { + identities: editorial.items.map((item) => item.id), + editorial: true, + }), + metadataCheckedAt: Math.max( + startedAt, + adoption.metadataCheckedAt ?? 0, + searchReport.metadataCheckedAt ?? 0, + ), + }; +} + +const INSTALL_RANKING_VERSION = "featured-installs-30d-v1"; +const PLUGIN_RANKING_VERSION = "featured-downloads-30d-v1"; +type MetricTotal = { + id: string; + count30d: number; + count7d: number; + importedRows: number; + importDatasetVersions: Set; +}; + +async function readMonthlyAdoption( + ctx: Pick, + artifactKind: SearchArtifactKind, + periodEnd: number, + weeklyDigest: boolean, +): Promise { + const collectionStartedAt = Date.now(); + if ( + !Number.isSafeInteger(periodEnd) || + periodEnd % SEARCH_DAY_MS || + periodEnd > Math.floor(collectionStartedAt / SEARCH_DAY_MS) * SEARCH_DAY_MS + ) + throw new Error("Monthly adoption requires completed UTC days"); + const endDay = periodEnd / SEARCH_DAY_MS; + const pluginDownloads = artifactKind === "plugin" && !weeklyDigest; + const rankingVersion = pluginDownloads ? PLUGIN_RANKING_VERSION : INSTALL_RANKING_VERSION; + const periodStart = periodEnd - 30 * SEARCH_DAY_MS; + const periodStart7d = periodEnd - 7 * SEARCH_DAY_MS; + const totals = new Map(); + let scannedRows = 0; + let importedRows = 0; + const importDatasetVersions = new Set(); + const readPage = async ( + day: number, + paginationOpts: PaginationOptions, + ): Promise<{ isDone: boolean; continueCursor: string }> => { + const result = await ctx.runQuery(internal.featuredIntelligence.readDailyRankingStatsInternal, { + artifactKind, + day, + pluginDownloads, + paginationOpts, + }); + if (result.pageStatus === "SplitRequired") { + // Native cursor ranges replace the incomplete parent; never count both. + if ( + !result.splitCursor || + result.splitCursor === paginationOpts.cursor || + result.splitCursor === result.continueCursor + ) + throw new Error("Monthly adoption page cannot be completed"); + await readPage(day, { ...paginationOpts, endCursor: result.splitCursor }); + await readPage(day, { + ...paginationOpts, + cursor: result.splitCursor, + endCursor: result.continueCursor, + }); + } else { + scannedRows += result.scannedRows; + for (const row of result.page) { + let total = totals.get(row.id); + if (!total) { + total = { + id: row.id, + count30d: 0, + count7d: 0, + importedRows: 0, + importDatasetVersions: new Set(), + }; + totals.set(row.id, total); + } + total.count30d += row.count; + if (day >= endDay - 7) total.count7d += row.count; + if (row.imported) { + total.importedRows++; + importedRows++; + } + if (row.dataset) { + total.importDatasetVersions.add(row.dataset); + importDatasetVersions.add(row.dataset); + } + } + } + return { isDone: result.isDone, continueCursor: result.continueCursor }; + }; + // Four independent day scans bound active transactions. Ranking starts only + // after every day completes; no Trending or download-sorted admission cap. + let nextDay = endDay - 30; + let failed = false; + const scans = await Promise.allSettled( + Array.from({ length: 4 }, async () => { + try { + while (nextDay < endDay) { + if (failed) break; + const day = nextDay++; + let cursor: string | null = null; + for (;;) { + if (failed) break; + const page = await readPage(day, { + cursor, + numItems: 5000, + maximumBytesRead: 8_000_000, + }); + if (page.isDone) break; + cursor = page.continueCursor; + } + } + } catch (error) { + failed = true; + throw error; + } + }), + ); + for (const result of scans) if (result.status === "rejected") throw result.reason; + let ranked = [...totals.values()].filter((entry) => entry.count30d > 0); + if (artifactKind === "plugin") { + const resolved: MetricTotal[] = []; + for (let offset = 0; offset < ranked.length; offset += 100) { + const batch = ranked.slice(offset, offset + 100); + const identities = await ctx.runQuery( + internal.featuredIntelligence.readPackageIdentitiesInternal, + { ids: batch.map((entry) => entry.id as import("../_generated/dataModel").Id<"packages">) }, + ); + identities.forEach((entry, index) => { + if (entry.identity) resolved.push({ ...batch[index], id: entry.identity }); + }); + } + ranked = resolved; + } + ranked.sort( + (a, b) => + b.count30d - a.count30d || b.count7d - a.count7d || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0), + ); + const generatedAt = Date.now(); + const snapshotId = `${artifactKind}:${periodEnd}:${collectionStartedAt}`; + const artifacts: AdoptionArtifact[] = []; + let inspectedItems = 0; + let eligibleItems = 0; + let retainedExclusions = 0; + // Limit rich report metadata after ranking the complete metric population. + // Ineligible leading rows cannot starve lower-ranked eligible candidates. + for ( + let offset = 0; + offset < ranked.length && eligibleItems < ADOPTION_INSPECTION_LIMIT; + offset += 100 + ) { + const batch = ranked.slice(offset, offset + 100); + const metadata = await ctx.runQuery(internal.featuredArtifacts.readInternal, { + identities: batch.map((entry) => entry.id), + }); + const byId = new Map(metadata.map((entry) => [entry.id, entry])); + inspectedItems += batch.length; + for (const [index, entry] of batch.entries()) { + const artifact = byId.get(entry.id); + if (!artifact) continue; + if (artifact.eligibleForFeatured) eligibleItems++; + else if (retainedExclusions++ >= ADOPTION_INSPECTION_LIMIT) continue; + artifacts.push({ + artifact, + evidence: { + ...(pluginDownloads + ? { + source: "package-daily-downloads" as const, + downloads30d: entry.count30d, + downloads7d: entry.count7d, + } + : { + source: + artifactKind === "plugin" + ? ("package-daily-installs" as const) + : ("skill-daily-installs" as const), + installs30d: entry.count30d, + installs7d: entry.count7d, + }), + rank: offset + index + 1, + snapshotId, + rankingVersion, + periodStart, + periodStart7d, + periodEnd, + generatedAt, + importedRows: entry.importedRows, + importDatasetVersions: [...entry.importDatasetVersions].sort(), + }, + }); + } + } + return { + summary: { + status: "available", + generatedAt, + collectionStartedAt, + periodStart, + periodStart7d, + periodEnd, + snapshotId, + rankingVersion, + totalItems: ranked.length, + inspectedItems, + truncated: inspectedItems < ranked.length || artifacts.length < inspectedItems, + scannedRows, + importedRows, + importDatasetVersions: [...importDatasetVersions].sort(), + }, + artifacts, + metadataCheckedAt: Date.now(), + }; +} diff --git a/convex/lib/searchReportEvidence.ts b/convex/lib/searchReportEvidence.ts index 3d7ddb57e4..8fe837eb5e 100644 --- a/convex/lib/searchReportEvidence.ts +++ b/convex/lib/searchReportEvidence.ts @@ -1,8 +1,8 @@ import { ConvexError } from "convex/values"; import { internal } from "../_generated/api"; import type { ActionCtx } from "../_generated/server"; -import { collectFeaturedEvidence } from "../featuredIntelligence"; import { renderFeaturedEvidence, type FeaturedEvidence } from "./featuredIntelligence"; +import { collectFeaturedEvidence } from "./featuredIntelligenceRead"; import { readReport } from "./searchInsightRead"; import type { SearchCurrentResult, SearchInsightReport } from "./searchInsights"; import type { ReportRequest } from "./searchReportContract";