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
2 changes: 2 additions & 0 deletions convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down
256 changes: 2 additions & 254 deletions convex/featuredIntelligence.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,21 @@
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,
type SearchArtifactKind,
type SearchInsightArgs,
} from "./lib/searchInsights";

const ADOPTION_INSPECTION_LIMIT = 100;
const args = {
artifactKind: searchArtifactKind,
endDay: v.optional(v.number()),
Expand Down Expand Up @@ -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<FeaturedEvidence> {
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<string>;
};

// 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({
Expand Down Expand Up @@ -151,201 +97,3 @@ export const readPackageIdentitiesInternal = internalQuery({
);
},
});

async function readMonthlyAdoption(
ctx: ActionCtx,
artifactKind: SearchArtifactKind,
periodEnd: number,
weeklyDigest: boolean,
): Promise<AdoptionReport> {
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<string, MetricTotal>();
let scannedRows = 0;
let importedRows = 0;
const importDatasetVersions = new Set<string>();
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(),
};
}
Loading
Loading