Skip to content
Open
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
4 changes: 4 additions & 0 deletions .jules/bolt.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@
## 2026-07-16 - [O(N*M) Nested Loop Lookups in Grading Engines]
**Learning:** In interactive scenarios (such as Bid Elevator and STR Triage), grading engines frequently iterate over user decisions and match them against scenario properties (like keywords or search terms). Performing `array.find()` inside loop bodies or filter predicates results in costly O(N*M) lookups.
**Action:** Convert arrays to `Map` lookups before entering loops/nested scans. Mapping keys once in O(M) time enables O(1) lookups during execution, transforming the time complexity of the grading logic to O(N + M).

## 2026-07-16 - [Transient Query Promise Caching in Rule Evaluators]
**Learning:** Evaluating multiple rules or criteria sequentially (such as checking badge conditions like completed lessons, tool sessions, and user metrics) can cause redundant database roundtrips for the same records or aggregates in a single request.
**Action:** Use a transient local cache class that stores and shares database query Promises during the request lifecycle. This collapses database reads from O(R) where R is the number of rules, to O(1) per query type.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,5 @@
"eslint --fix"
]
},
"packageManager": "pnpm@11.13.0+sha512.88d94724d8f2e6c186744a5584c6e59ecac869ec7ba15e9cb4cd628e8dc7066820b2481d8ee3b51ea8da323a7378068aa58c556a3720d32b7c20a051d088363a"
"packageManager": "pnpm@11.1.0"
}
75 changes: 55 additions & 20 deletions src/lib/badges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,52 @@ export interface BadgeEvaluationResult {
totalXpGained: number;
}

/**
* Transient cache for badge evaluations to prevent redundant database queries.
* This shares database query promises across all checkCriteria evaluations
* during a single evaluateBadges invocation, collapsing queries from O(R) to O(1).
*/
class EvaluationCache {
private moduleComplete: Promise<number> | null = null;
private toolSessions = new Map<string, Promise<number>>();
private userProfile: Promise<{ streakDays: number; xp: number } | null> | null = null;

getModuleComplete(userId: string): Promise<number> {
if (!this.moduleComplete) {
this.moduleComplete = db.lessonProgress.count({
where: { userId, status: 'COMPLETED' },
});
}
return this.moduleComplete;
}

getToolSessions(userId: string, toolType: string | undefined): Promise<number> {
const key = toolType || '__all__';
let p = this.toolSessions.get(key);
if (!p) {
p = db.toolSession.count({
where: {
userId,
status: 'GRADED',
...(toolType ? { toolType } : {}),
},
});
this.toolSessions.set(key, p);
}
return p;
}

getUserProfile(userId: string): Promise<{ streakDays: number; xp: number } | null> {
if (!this.userProfile) {
this.userProfile = db.user.findUnique({
where: { id: userId },
select: { streakDays: true, xp: true },
}) as Promise<{ streakDays: number; xp: number } | null>;
}
return this.userProfile;
}
}

/**
* Evaluate all badges for a user against the current database state. Award any
* newly-earned ones. Idempotent β€” re-running with no new events returns
Expand Down Expand Up @@ -95,6 +141,8 @@ export async function evaluateBadges(
xpReward: number;
}> = [];

const cache = new EvaluationCache();

for (const badge of published) {
if (alreadyAwardedSet.has(badge.id)) continue;

Expand All @@ -106,7 +154,7 @@ export async function evaluateBadges(
continue;
}

const qualifies = await checkCriteria(userId, criteria, event);
const qualifies = await checkCriteria(userId, criteria, event, cache);
if (qualifies) earnedNow.push(badge);
}

Expand Down Expand Up @@ -140,18 +188,17 @@ export async function evaluateBadges(

/**
* Returns true if the user has met the given badge criteria at this moment.
* Each branch is a narrow DB read β€” no writes.
* Each branch uses the shared evaluation cache to prevent redundant DB reads.
*/
async function checkCriteria(
userId: string,
criteria: BadgeCriteria,
event: BadgeTrigger,
cache: EvaluationCache,
): Promise<boolean> {
switch (criteria.type) {
case 'module_complete': {
const completedCount = await db.lessonProgress.count({
where: { userId, status: 'COMPLETED' },
});
const completedCount = await cache.getModuleComplete(userId);
// Treat each completed lesson as progress toward module_complete; the
// seed threshold is 1 so this triggers after the first lesson.
return completedCount >= criteria.threshold;
Expand All @@ -165,30 +212,18 @@ async function checkCriteria(

case 'tool_sessions': {
const scopeToolType = criteria.scope?.toolType;
const count = await db.toolSession.count({
where: {
userId,
status: 'GRADED',
...(scopeToolType ? { toolType: scopeToolType } : {}),
},
});
const count = await cache.getToolSessions(userId, scopeToolType);
return count >= criteria.threshold;
}

case 'streak_days': {
const user = await db.user.findUnique({
where: { id: userId },
select: { streakDays: true },
});
const user = await cache.getUserProfile(userId);
if (!user) return false;
return user.streakDays >= criteria.threshold;
}

case 'xp_threshold': {
const user = await db.user.findUnique({
where: { id: userId },
select: { xp: true },
});
const user = await cache.getUserProfile(userId);
if (!user) return false;
return user.xp >= criteria.threshold;
}
Expand Down
Loading