feat(redis-worker,webapp): mollifier buffer extensions + snapshot type#3752
feat(redis-worker,webapp): mollifier buffer extensions + snapshot type#3752d-cs wants to merge 3 commits into
Conversation
Adds the buffer-side data layer used by phase-3 work: - buffer.ts gains entry inspection (getEntry), idempotency lookup (lookupIdempotency), in-place snapshot mutation (mutateSnapshot), and dwell tracking — all atomic via Lua. - snapshot.server.ts: shared MollifierSnapshot type + (de)serialise. - Drops the entry-TTL config — the drainer is the recovery mechanism. Adds methods to the buffer interface; nothing consumes them yet. Subsequent PRs in the stack wire trigger-time mollify, read-fallback, and mutation paths against this surface. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
🦋 Changeset detectedLatest commit: 02cfe1a The changes in this PR will be included in the next version bump. This PR includes changesets to release 32 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
WalkthroughThis PR extends the MollifierBuffer with idempotency support via Redis-backed lookup keys, migrates queue storage from lists to per-env ZSETs scored by createdAtMicros, redesigns accept to return typed AcceptResult variants and support optional idempotency/task identifiers, adds mutateSnapshot and casSetMetadata APIs (with Lua atomic implementations), implements an idempotency claim lifecycle and self-healing lookup/reset helpers, changes ack to mark entries materialised with a 30s grace TTL instead of deleting them, removes accept-time entry TTL in favor of drainer-only management, adds drain concurrency configuration, expands public types/exports and Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/redis-worker/src/mollifier/buffer.ts (1)
291-304: 💤 Low valueConsider parallel fetching for consistency with
listForEnvWithWatermark.This method fetches entries sequentially with
awaitinside a loop, whilelistForEnvWithWatermarkusesPromise.allfor parallel fetches. For smallmaxCountvalues this is fine, but parallel fetching would be more consistent and faster for larger page sizes.♻️ Optional: parallel fetch
async listEntriesForEnv(envId: string, maxCount: number): Promise<BufferEntry[]> { if (maxCount <= 0) return []; const runIds = await this.redis.zrevrange( `mollifier:queue:${envId}`, 0, maxCount - 1, ); - const entries: BufferEntry[] = []; - for (const runId of runIds) { - const entry = await this.getEntry(runId); - if (entry) entries.push(entry); - } - return entries; + const fetched = await Promise.all(runIds.map((runId) => this.getEntry(runId))); + return fetched.filter((entry): entry is BufferEntry => entry !== null); }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/redis-worker/src/mollifier/buffer.ts` around lines 291 - 304, The loop in listEntriesForEnv performs sequential awaits for getEntry causing slower fetches for larger maxCount; change it to fetch entries in parallel similar to listForEnvWithWatermark by mapping runIds to promises (e.g., runIds.map(id => this.getEntry(id))) and awaiting Promise.all, then filter out null/undefined results before returning the BufferEntry[] so behavior and performance match listForEnvWithWatermark.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@packages/redis-worker/src/mollifier/buffer.ts`:
- Around line 291-304: The loop in listEntriesForEnv performs sequential awaits
for getEntry causing slower fetches for larger maxCount; change it to fetch
entries in parallel similar to listForEnvWithWatermark by mapping runIds to
promises (e.g., runIds.map(id => this.getEntry(id))) and awaiting Promise.all,
then filter out null/undefined results before returning the BufferEntry[] so
behavior and performance match listForEnvWithWatermark.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: f5fa1ec2-cb73-4a04-9d09-65c1a8b8137c
📒 Files selected for processing (8)
.changeset/mollifier-buffer-extensions.mdapps/webapp/app/env.server.tsapps/webapp/app/v3/mollifier/mollifierBuffer.server.tsapps/webapp/app/v3/mollifier/mollifierSnapshot.server.tspackages/redis-worker/src/mollifier/buffer.test.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/schemas.ts
💤 Files with no reviewable changes (2)
- apps/webapp/app/env.server.ts
- apps/webapp/app/v3/mollifier/mollifierBuffer.server.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (19)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (8, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (5, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (2, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (1, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (3, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (7, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (4, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (6, 8)
- GitHub Check: typecheck / typecheck
- GitHub Check: packages / 🧪 Unit Tests: Packages (1, 1)
- GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead
Files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.tspackages/redis-worker/src/mollifier/schemas.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.test.ts
{packages/core,apps/webapp}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use zod for validation in packages/core and apps/webapp
Files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use function declarations instead of default exports
**/*.{ts,tsx,js,jsx}: Prefer static imports over dynamic imports. Only use dynamicimport()when circular dependencies cannot be resolved otherwise, code splitting is needed for performance, or the module must be loaded conditionally at runtime.
Import from@trigger.dev/coreusing subpaths only - never import from the root.
When writing Trigger.dev tasks, always import from@trigger.dev/sdk. Never use@trigger.dev/sdk/v3or deprecatedclient.defineJob.
Add agentcrumbs markers (//@Crumbsor `#region `@crumbs) as you write code, not just when debugging. They stay on the branch throughout development and are stripped byagentcrumbs stripbefore merge.
Files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.tspackages/redis-worker/src/mollifier/schemas.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.test.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)
**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries
Files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.tspackages/redis-worker/src/mollifier/schemas.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.test.ts
apps/webapp/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/webapp.mdc)
apps/webapp/**/*.{ts,tsx}: Access environment variables through theenvexport ofenv.server.tsinstead of directly accessingprocess.env
Use subpath exports from@trigger.dev/corepackage instead of importing from the root@trigger.dev/corepathUse named constants for sentinel/placeholder values (e.g.
const UNSET_VALUE = '__unset__') instead of raw string literals scattered across comparisons
Files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.ts
apps/webapp/**/*.server.ts
📄 CodeRabbit inference engine (apps/webapp/CLAUDE.md)
apps/webapp/**/*.server.ts: Never userequest.signalfor detecting client disconnects. UsegetRequestAbortSignal()fromapp/services/httpAsyncStorage.server.tsinstead, which is wired directly to Expressres.on('close')and fires reliably
Access environment variables viaenvexport fromapp/env.server.ts. Never useprocess.envdirectly
Always usefindFirstinstead offindUniquein Prisma queries.findUniquehas an implicit DataLoader that batches concurrent calls and has active bugs even in Prisma 6.x (uppercase UUIDs returning null, composite key SQL correctness issues, 5-10x worse performance).findFirstis never batched and avoids this entire class of issues
Files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}
📄 CodeRabbit inference engine (AGENTS.md)
Code formatting must be enforced using Prettier before committing
Files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.tspackages/redis-worker/src/mollifier/schemas.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.test.ts
packages/**/*
📄 CodeRabbit inference engine (CLAUDE.md)
When modifying any public package (
packages/*orintegrations/*), add a changeset usingpnpm run changeset:add. Default to patch for bug fixes and minor changes.
Files:
packages/redis-worker/src/mollifier/schemas.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.test.ts
**/*.{test,spec}.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use vitest for all tests in the Trigger.dev repository
Files:
packages/redis-worker/src/mollifier/buffer.test.ts
**/*.test.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
**/*.test.{ts,tsx,js,jsx}: Test files should live beside the files under test and use descriptive describe and it blocks
Unit tests should use vitest framework
Tests should avoid mocks or stubs and use helpers from@internal/testcontainerswhen Redis or Postgres are needed
**/*.test.{ts,tsx,js,jsx}: Never mock anything in tests - use testcontainers instead.
Test files should be placed next to source files (e.g.,MyService.ts->MyService.test.ts).
Files:
packages/redis-worker/src/mollifier/buffer.test.ts
🧠 Learnings (10)
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).
Applied to files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.tspackages/redis-worker/src/mollifier/schemas.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.test.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.
Applied to files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.tspackages/redis-worker/src/mollifier/schemas.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.test.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.
Applied to files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.tspackages/redis-worker/src/mollifier/schemas.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.test.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.
Applied to files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.tspackages/redis-worker/src/mollifier/schemas.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.test.ts
📚 Learning: 2026-03-29T19:16:28.864Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3291
File: apps/webapp/app/v3/featureFlags.ts:53-65
Timestamp: 2026-03-29T19:16:28.864Z
Learning: When reviewing TypeScript code that uses Zod v3, treat `z.coerce.*()` schemas as their direct Zod type (e.g., `z.coerce.boolean()` returns a `ZodBoolean` with `_def.typeName === "ZodBoolean"`) rather than a `ZodEffects`. Only `.preprocess()`, `.refine()`/`.superRefine()`, and `.transform()` are expected to wrap schemas in `ZodEffects`. Therefore, in reviewers’ logic like `getFlagControlType`, do not flag/unblock failures that require unwrapping `ZodEffects` when the input schema is a `z.coerce.*` schema.
Applied to files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.ts
📚 Learning: 2026-05-05T09:38:02.512Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3523
File: apps/webapp/app/routes/api.v3.batches.ts:178-181
Timestamp: 2026-05-05T09:38:02.512Z
Learning: When reviewing code that catches `ServiceValidationError` in `*.server.ts` files, do not blindly forward `error.status` to HTTP responses, because SVEs may be thrown with non-default statuses (e.g., 400/500) and forwarding them can cause client-visible behavioral regressions (e.g., surfacing 500s to clients). Prefer a safe default response status of `error.status ?? 422`, but only after confirming via the reachable call graph that the caught `ServiceValidationError` instances are expected to carry those non-default statuses; otherwise, normalize to `422` to avoid unexpected client-visible 5xx behavior.
Applied to files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.ts
📚 Learning: 2026-05-12T21:04:05.815Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/components/sessions/v1/SessionStatus.tsx:1-3
Timestamp: 2026-05-12T21:04:05.815Z
Learning: In this Remix + TypeScript codebase, do not flag a server/client boundary violation when a file imports only types from a module matching `*.server`.
Specifically, it’s safe to import types using `import type { Foo } from "*.server"` or `import { type Foo } from "*.server"` because TypeScript erases type-only imports at compile time and they emit no JavaScript, so they won’t cross the Remix server/client bundle boundary.
Only raise the boundary concern for value imports (e.g., `import { Foo }` without `type`, or `import Foo`), since those produce JavaScript output.
Applied to files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.ts
📚 Learning: 2026-05-14T08:21:07.614Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3614
File: apps/webapp/app/v3/mollifier/mollifierGate.server.ts:48-52
Timestamp: 2026-05-14T08:21:07.614Z
Learning: When using Trigger.dev v3 feature flags in the webapp, prefer the existing per-org gating mechanism supported by `flag()` via the `overrides` argument. Pass `Organization.featureFlags` (from `environment.organization.featureFlags`) as the `overrides` value; overrides must take precedence over the global `featureFlag` row. Do not require schema changes or add an `orgId` field to `FlagsOptions` for per-org gating—use the overrides pattern consistently (e.g., in gate flows like `resolveOrgFlag` and any server code that threads `environment.organization.featureFlags` into the gate call).
Applied to files:
apps/webapp/app/v3/mollifier/mollifierSnapshot.server.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In this repo’s trigger.dev codebase, the “never mock — use testcontainers” guideline should only be applied to integration tests that talk to real external services (e.g., Redis, Postgres, S2). For unit tests that validate in-memory logic (e.g., deduplication/cache behavior in StandardRealtimeStreamsManager and similar module-boundary call counting), it is allowed to use Vitest mocks like `vi.fn()` and to stub/mock `ApiClient` objects to count calls or simulate in-process collaborators. Do not flag `vi.fn()`-based mocks as policy violations in these unit-test scenarios; reserve the rule for true external-service integration tests.
Applied to files:
packages/redis-worker/src/mollifier/buffer.test.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In the triggerdotdev/trigger.dev repo, the policy “Never mock anything — use testcontainers instead” should only be enforced for integration tests that interact with real external services (e.g., Redis, Postgres) via actual infrastructure. For unit tests that exercise pure in-memory logic (e.g., cache semantics) it is OK to stub collaborators such as `ApiClient` using Vitest (`vi.fn()`) to assert call counts or control behavior. Do not flag `vi.fn()`-based `ApiClient` stubs in unit tests as violations of the testcontainers policy.
Applied to files:
packages/redis-worker/src/mollifier/buffer.test.ts
🔇 Additional comments (22)
.changeset/mollifier-buffer-extensions.md (1)
1-7: LGTM!apps/webapp/app/v3/mollifier/mollifierSnapshot.server.ts (1)
1-16: LGTM!packages/redis-worker/src/mollifier/index.ts (1)
1-24: LGTM!packages/redis-worker/src/mollifier/buffer.test.ts (1)
23-2030: LGTM!packages/redis-worker/src/mollifier/schemas.ts (1)
30-33: LGTM!Also applies to: 51-68
packages/redis-worker/src/mollifier/buffer.ts (17)
16-67: LGTM!
93-154: LGTM!
215-283: LGTM!
306-357: LGTM!
359-414: LGTM!
416-444: LGTM!
446-456: LGTM!
510-578: LGTM!
580-614: LGTM!
616-674: LGTM!
676-717: LGTM!
719-738: LGTM!
740-776: LGTM!
778-835: LGTM!
837-861: LGTM!
863-892: LGTM!
919-993: LGTM!
After the buffer extensions in this PR: - ack() keeps the entry alive with a grace TTL as a read-fallback safety net. Test asserts the entry persists with materialised=true. - fail() deletes the entry once the drainer-handler has written the canonical SYSTEM_FAILURE PG row. Tests assert the entry is null and use runOnce()'s `failed` counter as the surviving signal. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…m ownership token Addresses code-review feedback on the buffer's idempotency keying: - Encode `envId` / `taskIdentifier` / `idempotencyKey` with base64url before concatenation so customer-supplied segments containing `:` cannot alias each other onto the same Redis key. Exports `idempotencyLookupKeyFor` so tests assert against the same encoding the buffer writes. - Replace the shared `"pending"` claim marker with a caller-supplied ownership token (`"pending:<token>"`). `publishClaim` and `releaseClaim` become compare-and-set / compare-and-delete via Lua, so a late release from a previous claimant whose TTL expired cannot erase a new owner's claim. New buffer tests cover the alias-collision case, the encoded-key-shape contract, and the token-ownership safety properties (stale release is a no-op, wrong-token publish is a no-op, fresh claim survives the post-TTL-expiry stale-release race). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/redis-worker/src/mollifier/buffer.ts (1)
480-486:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift
resetIdempotency()leaves the authoritative claim key behind.
claimIdempotency()now serializes the hot path onmollifier:claim:*, but this reset path only clearsmollifier:idempotency:*and the buffered payload. After a manual reset, the same key can still come back as{ kind: "resolved", runId }until the claim TTL expires, so the reset does not actually reopen the idempotency key. Please clear the claim namespace in the same reset operation, or explicitly handle the pending/resolved-claim semantics here.Also applies to: 825-859
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/redis-worker/src/mollifier/buffer.ts` around lines 480 - 486, resetIdempotency currently only clears the idempotency and buffered payload keys, leaving the authoritative claim key (mollifier:claim:*) in place so a manual reset can be immediately re-covered by a pending/resolved claim; update resetIdempotency to also remove the corresponding claim key (mollifier:claim:<lookupKey>) in the same Redis operation (or invoke the existing redis-level claim reset helper if present) so the idempotency entry is fully reopened, and apply the same fix to the other reset code path referenced around the 825-859 block to ensure claim and idempotency namespaces are cleared together.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@packages/redis-worker/src/mollifier/buffer.ts`:
- Around line 480-486: resetIdempotency currently only clears the idempotency
and buffered payload keys, leaving the authoritative claim key
(mollifier:claim:*) in place so a manual reset can be immediately re-covered by
a pending/resolved claim; update resetIdempotency to also remove the
corresponding claim key (mollifier:claim:<lookupKey>) in the same Redis
operation (or invoke the existing redis-level claim reset helper if present) so
the idempotency entry is fully reopened, and apply the same fix to the other
reset code path referenced around the 825-859 block to ensure claim and
idempotency namespaces are cleared together.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 77fb6ff3-ca3e-446e-b493-88e071291045
📒 Files selected for processing (3)
packages/redis-worker/src/mollifier/buffer.test.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/index.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (20)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (4, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (7, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (8, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (3, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (6, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (1, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 8)
- GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (5, 8)
- GitHub Check: internal / 🧪 Unit Tests: Internal (2, 8)
- GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
- GitHub Check: packages / 🧪 Unit Tests: Packages (1, 1)
- GitHub Check: typecheck / typecheck
- GitHub Check: Analyze (javascript-typescript)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead
Files:
packages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/buffer.test.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use function declarations instead of default exports
**/*.{ts,tsx,js,jsx}: Prefer static imports over dynamic imports. Only use dynamicimport()when circular dependencies cannot be resolved otherwise, code splitting is needed for performance, or the module must be loaded conditionally at runtime.
Import from@trigger.dev/coreusing subpaths only - never import from the root.
When writing Trigger.dev tasks, always import from@trigger.dev/sdk. Never use@trigger.dev/sdk/v3or deprecatedclient.defineJob.
Add agentcrumbs markers (//@Crumbsor `#region `@crumbs) as you write code, not just when debugging. They stay on the branch throughout development and are stripped byagentcrumbs stripbefore merge.
Files:
packages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/buffer.test.ts
**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)
**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries
Files:
packages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/buffer.test.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}
📄 CodeRabbit inference engine (AGENTS.md)
Code formatting must be enforced using Prettier before committing
Files:
packages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/buffer.test.ts
packages/**/*
📄 CodeRabbit inference engine (CLAUDE.md)
When modifying any public package (
packages/*orintegrations/*), add a changeset usingpnpm run changeset:add. Default to patch for bug fixes and minor changes.
Files:
packages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/buffer.test.ts
**/*.{test,spec}.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Use vitest for all tests in the Trigger.dev repository
Files:
packages/redis-worker/src/mollifier/buffer.test.ts
**/*.test.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
**/*.test.{ts,tsx,js,jsx}: Test files should live beside the files under test and use descriptive describe and it blocks
Unit tests should use vitest framework
Tests should avoid mocks or stubs and use helpers from@internal/testcontainerswhen Redis or Postgres are needed
**/*.test.{ts,tsx,js,jsx}: Never mock anything in tests - use testcontainers instead.
Test files should be placed next to source files (e.g.,MyService.ts->MyService.test.ts).
Files:
packages/redis-worker/src/mollifier/buffer.test.ts
🧠 Learnings (6)
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).
Applied to files:
packages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/buffer.test.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.
Applied to files:
packages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/buffer.test.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.
Applied to files:
packages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/buffer.test.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.
Applied to files:
packages/redis-worker/src/mollifier/index.tspackages/redis-worker/src/mollifier/buffer.tspackages/redis-worker/src/mollifier/buffer.test.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In this repo’s trigger.dev codebase, the “never mock — use testcontainers” guideline should only be applied to integration tests that talk to real external services (e.g., Redis, Postgres, S2). For unit tests that validate in-memory logic (e.g., deduplication/cache behavior in StandardRealtimeStreamsManager and similar module-boundary call counting), it is allowed to use Vitest mocks like `vi.fn()` and to stub/mock `ApiClient` objects to count calls or simulate in-process collaborators. Do not flag `vi.fn()`-based mocks as policy violations in these unit-test scenarios; reserve the rule for true external-service integration tests.
Applied to files:
packages/redis-worker/src/mollifier/buffer.test.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In the triggerdotdev/trigger.dev repo, the policy “Never mock anything — use testcontainers instead” should only be enforced for integration tests that interact with real external services (e.g., Redis, Postgres) via actual infrastructure. For unit tests that exercise pure in-memory logic (e.g., cache semantics) it is OK to stub collaborators such as `ApiClient` using Vitest (`vi.fn()`) to assert call counts or control behavior. Do not flag `vi.fn()`-based `ApiClient` stubs in unit tests as violations of the testcontainers policy.
Applied to files:
packages/redis-worker/src/mollifier/buffer.test.ts
🔇 Additional comments (3)
packages/redis-worker/src/mollifier/index.ts (1)
1-10: LGTM!packages/redis-worker/src/mollifier/buffer.ts (1)
46-61: LGTM!Also applies to: 76-77, 145-149, 379-446, 455-466, 762-823, 1056-1071
packages/redis-worker/src/mollifier/buffer.test.ts (1)
5-5: LGTM!Also applies to: 1113-1117, 1248-1252, 1294-1298, 1342-1346, 2048-2321
Summary
Buffer-side data layer used by the rest of the mollifier phase-3 stack.
buffer.tsgains entry inspection (getEntry), idempotency lookup (lookupIdempotency), in-place snapshot mutation (mutateSnapshot), and dwell tracking. All atomic via Lua.mollifierSnapshot.server.ts: sharedMollifierSnapshottype plus (de)serialise helpers.Adds methods to the buffer interface; nothing consumes them yet. Subsequent PRs in the stack wire trigger-time mollify, read-fallback, and mutation paths against this surface.
Test plan