perf(db): fix the slowest MongoDB queries from the last 24 hours

MongoDB's slow-query log (24 h, >100 ms) showed four shapes:

- Admin repository search: a case-insensitive substring regex over four
  fields scanned all ~300k repositories, three times per page (up to 5.2 s
  each). Searches that are a repository ID or owner/name now match
  through the indexes first and only fall back to the regex otherwise.
- Admin errors page owner lookup: repoId $in without the repoId index's
  collation was a full collection scan. It now uses the collation.
- Status breakdown and home stats aggregates (~0.4 s over every
  repository, ~100 runs a day from admin polling): cached for a minute,
  and the admin overview uses the existing hourly home-stats cache.
- Folder counts for large repositories (0.7-1.5 s, 400-550k index keys)
  are cached per tree generation, which never changes; legacy trees are
  keyed by commit for 5 minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Thomas DurieuxandClaude Opus 5.5 committed 2026-11-30 13:36:17 +00:00
1 parent 8df674ef10
commit 24534823a3
5 files changed
+112 -35

No files matched your search

+24 -1
View File
@@ -6,7 +6,7 @@ const Repository = require("../src/core/Repository").default;
const Repo = require("../src/core/model/anonymizedRepositories/anonymizedRepositories.model").default;
const File = require("../src/core/model/files/files.model").default;
const Path = require("../src/core/model/anonymized-path").default;
const { folderCounts } = require("../src/core/folder-counts");
const { folderCounts, clearFolderCountCache } = require("../src/core/folder-counts");
const { FILE_LISTING_LIMIT } = require("../src/core/file-tree");
const uri = process.env.PERFORMANCE_MONGO_URI;
@@ -45,6 +45,7 @@ describe("folder count request validation", () => {
});
after(async () => { db.isConnected = false; await mongoose.connection.dropDatabase(); await mongoose.disconnect(); });
beforeEach(async () => {
clearFolderCountCache(); // Tests reuse one repository ID and generation with new files.
await Promise.all([Repo, File, Path].map(model => model.deleteMany({})));
repo = new Repository(await Repo.create({ repoId: "counts", owner: new mongoose.Types.ObjectId(), status: "ready",
statusDate: new Date(), anonymizeDate: new Date(), treeGeneration: "active", source: { type: "GitHubStream", repositoryName: "fixture/repo" }, options: { terms: [] } }));
@@ -138,6 +139,28 @@ describe("folder count request validation", () => {
expect(await folderCounts(new Repository(await Repo.findById(repo.model._id)), "")).to.deep.equal({ "": 2, new: 2 });
});
it("counts a tree generation once, then serves it from cache with the current terms", async () => {
await insert([{ path: "src", name: "a.js", size: 1 }, { path: "src", name: "b.js", size: 1 }]);
expect(await folderCounts(repo, "")).to.deep.equal({ "": 2, src: 2 });
const original = File.aggregate;
let queries = 0;
File.aggregate = function (...args) { queries++; return original.apply(this, args); };
try {
repo.model.options.terms = ["src"];
expect(await folderCounts(repo, "")).to.deep.equal({ "": 2, "XXXX-1": 2 });
expect(queries).to.equal(0);
} finally { File.aggregate = original; }
});
it("finds admin repository searches by exact ID or source name through the indexes", async () => {
const { exactRepositoryMatches } = require("../src/server/routes/admin");
const ids = matches => matches.map(String);
expect(ids(await exactRepositoryMatches("COUNTS"))).to.deep.equal([String(repo.model._id)]);
expect(ids(await exactRepositoryMatches("fixture/repo"))).to.deep.equal([String(repo.model._id)]);
expect(await exactRepositoryMatches("fixture")).to.deep.equal([]);
expect(await exactRepositoryMatches("not a repo id")).to.deep.equal([]);
});
it("keeps a hard bound for over-wide responses", async () => {
for (let offset = 0; offset <= FILE_LISTING_LIMIT; offset += 500) await insert(Array.from({
length: Math.min(500, FILE_LISTING_LIMIT + 1 - offset),