Repository navigation
feat(custom_audience): execute requestBody templates inside isolated-vm - #5193
Conversation
|
Note
|
| Layer / File(s) | Summary |
|---|---|
Batching interface and chunking utility src/services/destination/nativeBatching/types.ts, src/services/destination/nativeBatching/chunkPayloads.ts |
BatchStrategy.batch now returns Promise<BatchGroup[]>. Added PayloadChunk type and chunkPayloads to split payloads by optional maxItems and maxPayloadSize (size estimated using wrapped body bytes). |
ChunkBatchStrategy & CustomBatchStrategy src/services/destination/nativeBatching/chunkBatchStrategy.ts, src/services/destination/nativeBatching/customBatchStrategy.ts |
ChunkBatchStrategy delegates chunking to chunkPayloads and is async; CustomBatchStrategy accepts async batchFn and exposes async batch. |
Batching execution and tests src/services/destination/nativeBatching/processBatchedDestination.ts, src/services/destination/nativeBatching/__tests__/batchDestination.test.ts, src/v0/destinations/posthog/routerTransform.test.ts |
processBatchedDestination now awaits strategy.batch(...) per group. Added test verifying async CustomBatchStrategy support and updated PostHog test to await async batch. |
Ivm runner and bundle path src/v0/destinations/custom_audience/template/ivmScriptRunner.ts, (deleted) src/v0/destinations/custom_audience/template/sandboxedParse.entry.ts |
Ivm runner now accepts args for execute and uses evalClosure; adds stable BUNDLE_PATH and exports templateSandboxRunner singleton configured from env vars. Removed old single-parse entry. |
Sandbox entry with parse & evaluate globals src/v0/destinations/custom_audience/template/sandboxedTemplate.entry.ts |
New esbuild entry defines globalThis.parseTemplateInSandbox and globalThis.evaluateTemplateInSandbox; evaluate compiles template synchronously and evaluates chunks with provided connection, returning { ok: true, bodies } or { ok: false, error }. |
Template sandbox wrapper and tests src/v0/destinations/custom_audience/template/templateSandbox.ts, src/v0/destinations/custom_audience/template/templateSandbox.test.ts |
Added sandboxedParseTemplate and sandboxedEvaluateTemplate that call templateSandboxRunner.execute with args and map errors to PlatformError/InstrumentationError as appropriate. Added comprehensive tests and assertBundleFreshness. |
Router integration, utils, controller & tests src/v0/destinations/custom_audience/routerTransform.ts, src/v0/destinations/custom_audience/routerTransform.test.ts, src/controllers/eventTest.ts, src/controllers/__tests__/eventTest.test.ts, src/v0/destinations/custom_audience/utils.ts, related tests |
getBatchStrategy now uses async CustomBatchStrategy, chunks payloads with chunkPayloads, and calls sandboxedEvaluateTemplate per chunk; removed exported evaluateTemplate from utils and inlined endpoint evaluation with try/catch; tests updated to verify bundle freshness and import paths. ivm tests updated to use new execute args. |
Sequence Diagram(s)
sequenceDiagram
participant Router as CustomAudienceRouter
participant Strategy as CustomBatchStrategy
participant Chunker as chunkPayloads
participant SandboxAPI as sandboxedEvaluateTemplate
participant Runner as templateSandboxRunner
Router->>Strategy: batch(payloads)
Strategy->>Chunker: chunkPayloads(payloads, {maxItems, maxPayloadSize, wrapBody})
Chunker-->>Strategy: PayloadChunk[] (bodies, jobIds)
loop per PayloadChunk
Strategy->>SandboxAPI: evaluate(requestBody, chunk.bodies, connection, workspaceId)
SandboxAPI->>Runner: execute(evaluateTemplateInSandbox, expression, args=[template, chunks, connection])
Runner-->>SandboxAPI: { ok: true, bodies } | { ok: false, error }
SandboxAPI-->>Strategy: bodies[] or throws
end
Strategy-->>Router: Promise~BatchGroup[]~
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
- rudderlabs/rudder-transformer#5187: Follow-up refactor of custom_audience router-transform and batching integration.
- rudderlabs/rudder-transformer#5185: Overlapping sandboxed template parsing/refactor and import-path consolidation.
Suggested reviewers
- krishna2020
- maheshkutty
- saikumarrs
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title accurately describes the main change: moving requestBody template evaluation into isolated-vm for the custom_audience destination. |
| Description check | ✅ Passed | The description comprehensively explains the changes, design decisions, affected files, error handling, and testing approach—clearly related to the changeset. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
📝 Generate docstrings
- Create stacked PR
- Commit on current branch
🧪 Generate unit tests (beta)
- Create PR with unit tests
- Commit unit tests in branch
feat/int-6302-router-transform-isolate-vm
Warning
Review ran into problems
🔥 Problems
Stopped waiting for pipeline failures after 30000ms. One of your pipelines takes longer than our 30000ms fetch window to run, so review may not consider pipeline-failure results for inline comments if any failures occurred after the fetch window. Increase the timeout if you want to wait longer or run a @coderabbit review after the pipeline has finished.
Tip
💬 Introducing Slack Agent: The best way for teams to turn conversations into code.
Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
- Generate code and open pull requests
- Plan features and break down work
- Investigate incidents and troubleshoot customer tickets together
- Automate recurring tasks and respond to alerts with triggers
- Summarize progress and report instantly
Built for teams:
- Shared memory across your entire org—no repeating context
- Per-thread sandboxes to safely plan and execute work
- Governance built-in—scoped access, auditability, and budget controls
One agent for your entire SDLC. Right inside Slack.
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 @coderabbitai help to get the list of available commands and usage tips.
7a527f7 to
8b5ada2
Compare
8b5ada2 to
a1eb3ca
Compare
08ff4e6 to
35ebf01
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (13)
src/services/destination/nativeBatching/chunkPayloads.ts (3)
38-48: ⚡ Quick winSingle oversized payload will violate maxPayloadSize constraint.
If a single
payload.body, when wrapped, exceedsmaxPayloadSize, it will still be added to an empty chunk after flushing (line 47), resulting in a chunk that violates the size limit. This might be acceptable (you cannot split an individual event), but the behavior should be documented or explicitly handled.Consider one of these approaches:
- Document this behavior in a comment above the function
- Add validation to detect and warn/error on oversized single payloads
- Add a comment explaining that single events exceeding the limit are allowed by design
📝 Proposed documentation addition
export function chunkPayloadsBySize<TBody extends Record<string, unknown>>( payloads: (TransformedEvent<TBody> & { jobId: number })[], opts: { maxItems?: number; maxPayloadSize?: string; wrapBody?: (bodies: TBody[]) => Record<string, unknown>; } = {}, ): PayloadChunk<TBody>[] { + // Note: Individual payloads that exceed maxPayloadSize when wrapped will still + // be included in their own chunk, as events cannot be split. Callers should + // validate payload sizes upstream if strict enforcement is required. const maxItems = opts.maxItems ?? Infinity;🤖 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 `@src/services/destination/nativeBatching/chunkPayloads.ts` around lines 38 - 48, The current chunking logic in chunkPayloads.ts can add a single oversized payload (when JSON.stringify(wrapBody([payload.body])) > maxPayloadSize) into an empty chunk after flush(), violating the size constraint; update the function to either (a) explicitly detect this case and log/warn or throw (e.g., validate when prospectiveBytes > maxPayloadSize and currentBodies.length === 0), or (b) add a clear comment above the chunking logic stating that single payloads exceeding maxPayloadSize are allowed by design; reference the wrapBody call, maxPayloadSize check, flush(), currentBodies.push(payload.body) and payload.body when implementing the validation or adding the documentation note.
38-45: ⚖️ Poor tradeoffPerformance consideration: Repeated serialization on every iteration.
The size check serializes the prospective batch
[...currentBodies, payload.body]on each iteration. For N payloads with average batch size B, this performs O(N×B) JSON serialization operations. For large batches or payloads with deep object structures, this could become a performance bottleneck.This is likely acceptable given the typical use case, but if performance becomes a concern, consider tracking approximate sizes incrementally (though this would be more complex and error-prone).
🤖 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 `@src/services/destination/nativeBatching/chunkPayloads.ts` around lines 38 - 45, The current size-check in chunkPayloads.ts repeatedly serializes the prospective batch by calling JSON.stringify on wrapBody([...currentBodies, payload.body]) every iteration, causing O(N×B) serialization work; to fix, change the logic in the chunking loop that uses maxPayloadSize, Buffer.byteLength and wrapBody/currentBodies/payload.body so you incrementally track the serialized size (or an approximate byte count) as you append payloads instead of re-serializing the whole prospective array each time—maintain a runningSize variable updated with Buffer.byteLength(JSON.stringify(payload.body)) (or a cheaper heuristic) and combine with the known wrapper overhead from wrapBody once when starting a batch, calling flush() only when the runningSize plus next payload would exceed maxPayloadSize.
38-38: 💤 Low valueSize checking requires both maxPayloadSize and wrapBody.
The condition
if (maxPayloadSize < Infinity && wrapBody)means size checking is silently skipped ifwrapBodyis not provided, even ifmaxPayloadSizeis set. While this makes logical sense (we cannot measure the wrapped size withoutwrapBody), it could lead to unexpected behavior if a caller setsmaxPayloadSizewithout realizingwrapBodyis also required.Consider adding a validation check or JSDoc comment to document this requirement.
🤖 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 `@src/services/destination/nativeBatching/chunkPayloads.ts` at line 38, Add an explicit validation and/or documentation that enforces the dependency between maxPayloadSize and wrapBody: detect when maxPayloadSize is finite but wrapBody is falsy (inside the chunkPayloads logic where maxPayloadSize and wrapBody are used) and either throw a clear error or log a warning, and add a JSDoc note on the chunking function (referencing maxPayloadSize and wrapBody) that explains wrapBody is required for payload size checking; this prevents silent skipping of size checks and makes the requirement explicit for callers.src/v0/destinations/custom_audience/utils.ts (1)
44-48: ⚡ Quick winConsider validating that the endpoint template evaluates to a string.
The evaluation result is coerced to a string with a fallback to empty string (
?? ''). If the template evaluates to an unexpected type (e.g., an object or array due to a configuration error), the coercion will produce'[object Object]'or similar, which could result in malformed URLs that fail in non-obvious ways.✅ Add explicit type check
let resolved: string; try { - resolved = String( - JsonTemplateEngine.createAsSync(wrapped, { defaultPathType: PathType.JSON }).evaluate({ - connection, - }) ?? '', - ); + const result = JsonTemplateEngine.createAsSync(wrapped, { + defaultPathType: PathType.JSON + }).evaluate({ connection }); + + if (typeof result !== 'string' && result !== null && result !== undefined) { + throw new Error(`Endpoint template must evaluate to a string, got ${typeof result}`); + } + resolved = result ? String(result) : ''; } catch (err: unknown) {🤖 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 `@src/v0/destinations/custom_audience/utils.ts` around lines 44 - 48, The endpoint template evaluation currently coerces any result into a string (assigned to resolved) using JsonTemplateEngine.createAsSync(...).evaluate(...) ?? '' which can yield '[object Object]' for non-string results; update the code around JsonTemplateEngine.createAsSync and the evaluate call to explicitly verify the evaluation result is a string (e.g., check typeof result === 'string' and non-empty/trimmed), and if it is not, throw or return a clear validation error before assigning resolved so malformed objects/arrays cannot produce invalid endpoint URLs.src/v0/destinations/custom_audience/template/sandboxedTemplate.entry.ts (1)
38-40: ⚡ Quick winAdd runtime type validation for template evaluation results.
The evaluation result is cast to
Record<string, unknown>without validation. If the template evaluates to a non-object value (e.g., a primitive, array, or null), this will cause type safety issues for downstream code expecting an object.🛡️ Proposed type guard
+ function isRecord(value: unknown): value is Record<string, unknown> { + return typeof value === 'object' && value !== null && !Array.isArray(value); + } + const bodies = chunks.map( - (records) => compiled.evaluate({ records, connection }) as Record<string, unknown>, + (records) => { + const result = compiled.evaluate({ records, connection }); + if (!isRecord(result)) { + throw new Error(`Template must evaluate to an object, got ${typeof result}`); + } + return result; + }, );🤖 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 `@src/v0/destinations/custom_audience/template/sandboxedTemplate.entry.ts` around lines 38 - 40, The mapped evaluation in compiled.evaluate that assigns to bodies is casting results to Record<string, unknown> without runtime checks, so add a runtime type guard after calling compiled.evaluate inside the map used to build bodies to ensure each result is a non-null plain object (not an array or primitive); if a result fails validation, either throw a descriptive error (including identifying context like the chunk index or connection) or skip/log and continue — implement a helper type guard (e.g., isPlainObject(value): value is Record<string, unknown>) and use it when building bodies to guarantee downstream code receives only valid objects.src/v0/destinations/custom_audience/template/templateSandbox.ts (2)
49-51: Note: Large chunk arrays may cause memory pressure during serialization.The expression is built by serializing the entire
chunksarray (potentially containing thousands of records across multiple chunks) usingJSON.stringify. For large batch operations, this could create a substantial string that must be transmitted to the isolate and parsed there.This is likely acceptable given the design constraints, but it's worth noting for future optimization if memory usage becomes a concern.
🤖 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 `@src/v0/destinations/custom_audience/template/templateSandbox.ts` around lines 49 - 51, The current construction of the expression string serializes the entire chunks array into expression via JSON.stringify (see the expression variable and evaluateTemplateInSandbox call), which can cause memory pressure for very large batches; change the approach so you do NOT stringify the full chunks outside the sandbox — instead pass only a lightweight reference (e.g., metadata, chunk IDs or start/end indices) or a smaller payload and perform JSON parsing/serialization inside the sandboxed context (or stream/iterate chunks in smaller batches) before calling evaluateTemplateInSandbox, updating the code that builds expression and the caller of evaluateTemplateInSandbox to accept the new smaller payload shape.
28-31: 💤 Low valueConsider preserving more error context for debugging.
The fallback error message
'Template parsing is temporarily unavailable.'completely hides the actual error from the user, which could make debugging difficult when template parsing fails. While logging captures the details, users/operators have no visibility into whether the issue is transient infrastructure failure or a problem requiring intervention.Consider including a sanitized error hint:
} catch (err: unknown) { const message = err instanceof Error ? err.message : String(err); logger.error('Template sandbox parse error', { workspaceId, error: message }); - return { valid: false, errors: ['Template parsing is temporarily unavailable.'] }; + return { + valid: false, + errors: [`Template parsing unavailable: ${message.substring(0, 100)}`] + }; }🤖 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 `@src/v0/destinations/custom_audience/template/templateSandbox.ts` around lines 28 - 31, The catch block in templateSandbox.ts currently logs the full error via logger.error but returns only a generic fallback (the return in the catch that yields { valid: false, errors: ['Template parsing is temporarily unavailable.'] }); update this to include a sanitized, truncated error hint in the returned errors so operators and users get actionable context without leaking sensitive data: create or call a small sanitizer (e.g., sanitizeError or maskStack) to remove PII/paths and limit length, then return something like { valid: false, errors: ['Template parsing is temporarily unavailable.', `Error hint: ${sanitizedHint}`] }; keep logger.error as-is to preserve full logs.src/v0/destinations/custom_audience/template/ivmScriptRunner.ts (2)
151-153: ⚡ Quick winAdd validation for environment variable values.
The environment variables are parsed but not validated. Invalid values (negative numbers, zero, or parsing failures resulting in
NaN) could cause subtle runtime issues such as isolates with no memory limit or operations that never timeout.✅ Proposed validation logic
+function parsePositiveInt(envVar: string, defaultValue: string, name: string): number { + const value = Number.parseInt(process.env[envVar] || defaultValue, 10); + if (Number.isNaN(value) || value <= 0) { + throw new Error(`Invalid ${name}: ${process.env[envVar]}. Must be a positive integer.`); + } + return value; +} + export const templateSandboxRunner = new IvmScriptRunner({ bundlePath: BUNDLE_PATH, - memoryLimitMb: Number.parseInt(process.env.CUSTOM_AUDIENCE_IVM_MEMORY_MB || '32', 10), - initTimeoutMs: Number.parseInt(process.env.CUSTOM_AUDIENCE_IVM_INIT_TIMEOUT_MS || '5000', 10), - execTimeoutMs: Number.parseInt(process.env.CUSTOM_AUDIENCE_IVM_EXEC_TIMEOUT_MS || '500', 10), + memoryLimitMb: parsePositiveInt('CUSTOM_AUDIENCE_IVM_MEMORY_MB', '32', 'memory limit'), + initTimeoutMs: parsePositiveInt('CUSTOM_AUDIENCE_IVM_INIT_TIMEOUT_MS', '5000', 'init timeout'), + execTimeoutMs: parsePositiveInt('CUSTOM_AUDIENCE_IVM_EXEC_TIMEOUT_MS', '500', 'exec timeout'), });🤖 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 `@src/v0/destinations/custom_audience/template/ivmScriptRunner.ts` around lines 151 - 153, The parsed env values for memoryLimitMb, initTimeoutMs, and execTimeoutMs in ivmScriptRunner.ts must be validated: parse each with Number.parseInt (as currently done), then check for NaN or non-positive values (<= 0) and either replace with the safe default (32, 5000, 500 respectively) or throw a clear error; update the place where these values are used (the ivm/Isolate/options or the config object that contains memoryLimitMb, initTimeoutMs, execTimeoutMs) to use the validated numbers and add a short processLogger.warn or throw with details when an invalid env value was encountered so misconfiguration is visible at startup.
147-147: ⚡ Quick winConsider validating that the bundle file exists at startup.
The
BUNDLE_PATHresolution uses a five-level relative traversal that assumes a specific directory structure. Whilepath.resolve(__dirname, ...)is stable relative to the compiled file location, there's no verification that the bundle actually exists at this path. If the bundle build step is skipped or fails, this will only be discovered when the first sandbox operation is attempted.🛡️ Proposed validation check
Add a startup validation after the path resolution:
const BUNDLE_PATH = path.resolve(__dirname, '../../../../../dist/sandboxedTemplate.bundle.js'); + +if (!fs.existsSync(BUNDLE_PATH)) { + throw new Error(`Template sandbox bundle not found at ${BUNDLE_PATH}. Run 'npm run build:custom-audience-sandbox' to generate it.`); +}🤖 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 `@src/v0/destinations/custom_audience/template/ivmScriptRunner.ts` at line 147, Validate that the resolved BUNDLE_PATH points to an existing file at startup: after the const BUNDLE_PATH = path.resolve(...) check for file existence (using fs.existsSync or fs.promises.access) and if missing log a clear error and throw or process.exit(1) to fail fast; add this validation near the module top (in ivmScriptRunner where BUNDLE_PATH is defined) so any consumers of the sandboxed template fail early when the bundle build is absent.src/v0/destinations/custom_audience/routerTransform.ts (1)
110-120: ⚡ Quick winConsider validating that
bodies.lengthmatcheschunks.length.The code assumes
sandboxedEvaluateTemplatereturns exactly one body per chunk, but there's no explicit validation. If the sandbox returns a different-length array,bodies[i]will be undefined, leading to invalid batch jobs downstream.🛡️ Suggested defensive check
const bodies = await sandboxedEvaluateTemplate( actionConfig.requestBody, chunks.map((chunk) => chunk.bodies), connectionConfig, workspaceId, ); + if (bodies.length !== chunks.length) { + throw new InstrumentationError( + `Template evaluation returned ${bodies.length} results but expected ${chunks.length}`, + ); + } return chunks.map((chunk, i) => ({🤖 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 `@src/v0/destinations/custom_audience/routerTransform.ts` around lines 110 - 120, The code assumes sandboxedEvaluateTemplate(...) returns an array with the same length as chunks before mapping bodies into each returned job; add a defensive validation after calling sandboxedEvaluateTemplate to assert bodies.length === chunks.length and throw or log a clear error if not. Specifically, in routerTransform.ts after the call to sandboxedEvaluateTemplate, check the bodies array (variable bodies) against chunks.length and handle the mismatch (throw an Error or return a failed result) so that downstream mapping of bodies[i] cannot produce undefined for job payloads in the returned array from the function that constructs the { body, jobIds } objects.src/v0/destinations/custom_audience/template/templateSandbox.test.ts (3)
86-91: ⚡ Quick winSimplify the type-guard assertion for clarity.
Similar to the valid cases, line 90's short-circuit pattern could return
falseinstead of a string iferrorsis missing, making test failures less clear.♻️ Clearer assertion pattern
it.each(invalidCases)('returns valid=false: $name', async ({ template, errorMatch }) => { const result = await sandboxedParseTemplate(template, 'ws-invalid'); expect(result.valid).toBe(false); - expect('errors' in result && result.errors[0]).toMatch(errorMatch); + if (result.valid) throw new Error('Expected invalid result'); // Type guard + expect(result.errors[0]).toMatch(errorMatch); });🤖 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 `@src/v0/destinations/custom_audience/template/templateSandbox.test.ts` around lines 86 - 91, The test's assertion uses a short-circuit `'errors' in result && result.errors[0]` which can produce a false boolean and hide failures; update the invalid-case test that calls sandboxedParseTemplate (using invalidCases) to first assert that result.errors exists/non-empty (e.g., expect(result.errors).toBeDefined()/toHaveLength > 0) and then assert the first error string matches errorMatch (expect(result.errors[0]).toMatch(errorMatch)), so failures clearly show a missing errors array versus a mismatched message.
144-148: 💤 Low valueConsider asserting the error type explicitly.
The test expects
InstrumentationErrorfor runtime failures (line 141), but this test only checks the error message. For consistency and to ensure the correct error type is thrown, consider using.toThrow(InstrumentationError)as in the previous test.🔍 Suggested consistency improvement
it('throws InstrumentationError for unparseable templates', async () => { - await expect(sandboxedEvaluateTemplate('{{{{', [[]], {}, 'ws-eval')).rejects.toThrow( - /Failed to evaluate requestBody template/, - ); + await expect( + sandboxedEvaluateTemplate('{{{{', [[]], {}, 'ws-eval') + ).rejects.toThrow(InstrumentationError); });Alternatively, keep the message check and add type:
- await expect(sandboxedEvaluateTemplate('{{{{', [[]], {}, 'ws-eval')).rejects.toThrow( - /Failed to evaluate requestBody template/, - ); + const promise = sandboxedEvaluateTemplate('{{{{', [[]], {}, 'ws-eval'); + await expect(promise).rejects.toThrow(InstrumentationError); + await expect(promise).rejects.toThrow(/Failed to evaluate requestBody template/);Note: The second approach requires adjusting because the same promise can't be awaited twice. The first approach is simpler if message checking isn't critical.
🤖 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 `@src/v0/destinations/custom_audience/template/templateSandbox.test.ts` around lines 144 - 148, Update the test so it asserts the specific InstrumentationError type instead of only matching the message: replace the current expect(...).rejects.toThrow(/Failed to evaluate requestBody template/) with expect(sandboxedEvaluateTemplate('{{{{', [[]], {}, 'ws-eval')).rejects.toThrow(InstrumentationError). If you need to keep the message assertion too, await the promise inside a try/catch (call sandboxedEvaluateTemplate('{{{{', [[]], {}, 'ws-eval') inside the try, catch the thrown error and assert both error instanceof InstrumentationError and the message matches /Failed to evaluate requestBody template/); reference the sandboxedEvaluateTemplate helper and the test case in templateSandbox.test.ts when applying the change.
79-84: ⚡ Quick winSimplify the type-guard assertion for clarity.
Line 83 uses a short-circuit expression that could return
falseinstead of an array ifrecordFieldsis missing. While the test would fail in that case, the assertion is harder to read and could produce confusing error messages.♻️ Clearer assertion pattern
it.each(validCases)('returns valid=true: $name', async ({ template, expectedFields }) => { const result = await sandboxedParseTemplate(template, 'ws-valid'); expect(result.valid).toBe(true); - expect('recordFields' in result && result.recordFields.sort()).toEqual(expectedFields); + if (!result.valid) throw new Error('Expected valid result'); // Type guard for TS + expect(result.recordFields.sort()).toEqual(expectedFields); });Alternatively, if the type is already narrowed properly:
- expect('recordFields' in result && result.recordFields.sort()).toEqual(expectedFields); + expect(result).toHaveProperty('recordFields'); + expect((result as any).recordFields.sort()).toEqual(expectedFields);🤖 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 `@src/v0/destinations/custom_audience/template/templateSandbox.test.ts` around lines 79 - 84, The assertion uses a short-circuit that can yield false instead of an array; change the test around sandboxedParseTemplate's returned result so you first assert presence/type of result.recordFields (e.g., expect(result).toHaveProperty('recordFields') or expect(Array.isArray(result.recordFields))). After narrowing, compare the sorted recordFields to expectedFields (call result.recordFields.sort() only after confirming it exists) to make the failure message clearer; update the test in templateSandbox.test.ts where validCases and sandboxedParseTemplate are used.
🤖 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 `@src/services/destination/nativeBatching/chunkPayloads.ts`:
- Around line 38-48: The current chunking logic in chunkPayloads.ts can add a
single oversized payload (when JSON.stringify(wrapBody([payload.body])) >
maxPayloadSize) into an empty chunk after flush(), violating the size
constraint; update the function to either (a) explicitly detect this case and
log/warn or throw (e.g., validate when prospectiveBytes > maxPayloadSize and
currentBodies.length === 0), or (b) add a clear comment above the chunking logic
stating that single payloads exceeding maxPayloadSize are allowed by design;
reference the wrapBody call, maxPayloadSize check, flush(),
currentBodies.push(payload.body) and payload.body when implementing the
validation or adding the documentation note.
- Around line 38-45: The current size-check in chunkPayloads.ts repeatedly
serializes the prospective batch by calling JSON.stringify on
wrapBody([...currentBodies, payload.body]) every iteration, causing O(N×B)
serialization work; to fix, change the logic in the chunking loop that uses
maxPayloadSize, Buffer.byteLength and wrapBody/currentBodies/payload.body so you
incrementally track the serialized size (or an approximate byte count) as you
append payloads instead of re-serializing the whole prospective array each
time—maintain a runningSize variable updated with
Buffer.byteLength(JSON.stringify(payload.body)) (or a cheaper heuristic) and
combine with the known wrapper overhead from wrapBody once when starting a
batch, calling flush() only when the runningSize plus next payload would exceed
maxPayloadSize.
- Line 38: Add an explicit validation and/or documentation that enforces the
dependency between maxPayloadSize and wrapBody: detect when maxPayloadSize is
finite but wrapBody is falsy (inside the chunkPayloads logic where
maxPayloadSize and wrapBody are used) and either throw a clear error or log a
warning, and add a JSDoc note on the chunking function (referencing
maxPayloadSize and wrapBody) that explains wrapBody is required for payload size
checking; this prevents silent skipping of size checks and makes the requirement
explicit for callers.
In `@src/v0/destinations/custom_audience/routerTransform.ts`:
- Around line 110-120: The code assumes sandboxedEvaluateTemplate(...) returns
an array with the same length as chunks before mapping bodies into each returned
job; add a defensive validation after calling sandboxedEvaluateTemplate to
assert bodies.length === chunks.length and throw or log a clear error if not.
Specifically, in routerTransform.ts after the call to sandboxedEvaluateTemplate,
check the bodies array (variable bodies) against chunks.length and handle the
mismatch (throw an Error or return a failed result) so that downstream mapping
of bodies[i] cannot produce undefined for job payloads in the returned array
from the function that constructs the { body, jobIds } objects.
In `@src/v0/destinations/custom_audience/template/ivmScriptRunner.ts`:
- Around line 151-153: The parsed env values for memoryLimitMb, initTimeoutMs,
and execTimeoutMs in ivmScriptRunner.ts must be validated: parse each with
Number.parseInt (as currently done), then check for NaN or non-positive values
(<= 0) and either replace with the safe default (32, 5000, 500 respectively) or
throw a clear error; update the place where these values are used (the
ivm/Isolate/options or the config object that contains memoryLimitMb,
initTimeoutMs, execTimeoutMs) to use the validated numbers and add a short
processLogger.warn or throw with details when an invalid env value was
encountered so misconfiguration is visible at startup.
- Line 147: Validate that the resolved BUNDLE_PATH points to an existing file at
startup: after the const BUNDLE_PATH = path.resolve(...) check for file
existence (using fs.existsSync or fs.promises.access) and if missing log a clear
error and throw or process.exit(1) to fail fast; add this validation near the
module top (in ivmScriptRunner where BUNDLE_PATH is defined) so any consumers of
the sandboxed template fail early when the bundle build is absent.
In `@src/v0/destinations/custom_audience/template/sandboxedTemplate.entry.ts`:
- Around line 38-40: The mapped evaluation in compiled.evaluate that assigns to
bodies is casting results to Record<string, unknown> without runtime checks, so
add a runtime type guard after calling compiled.evaluate inside the map used to
build bodies to ensure each result is a non-null plain object (not an array or
primitive); if a result fails validation, either throw a descriptive error
(including identifying context like the chunk index or connection) or skip/log
and continue — implement a helper type guard (e.g., isPlainObject(value): value
is Record<string, unknown>) and use it when building bodies to guarantee
downstream code receives only valid objects.
In `@src/v0/destinations/custom_audience/template/templateSandbox.test.ts`:
- Around line 86-91: The test's assertion uses a short-circuit `'errors' in
result && result.errors[0]` which can produce a false boolean and hide failures;
update the invalid-case test that calls sandboxedParseTemplate (using
invalidCases) to first assert that result.errors exists/non-empty (e.g.,
expect(result.errors).toBeDefined()/toHaveLength > 0) and then assert the first
error string matches errorMatch (expect(result.errors[0]).toMatch(errorMatch)),
so failures clearly show a missing errors array versus a mismatched message.
- Around line 144-148: Update the test so it asserts the specific
InstrumentationError type instead of only matching the message: replace the
current expect(...).rejects.toThrow(/Failed to evaluate requestBody template/)
with expect(sandboxedEvaluateTemplate('{{{{', [[]], {},
'ws-eval')).rejects.toThrow(InstrumentationError). If you need to keep the
message assertion too, await the promise inside a try/catch (call
sandboxedEvaluateTemplate('{{{{', [[]], {}, 'ws-eval') inside the try, catch the
thrown error and assert both error instanceof InstrumentationError and the
message matches /Failed to evaluate requestBody template/); reference the
sandboxedEvaluateTemplate helper and the test case in templateSandbox.test.ts
when applying the change.
- Around line 79-84: The assertion uses a short-circuit that can yield false
instead of an array; change the test around sandboxedParseTemplate's returned
result so you first assert presence/type of result.recordFields (e.g.,
expect(result).toHaveProperty('recordFields') or
expect(Array.isArray(result.recordFields))). After narrowing, compare the sorted
recordFields to expectedFields (call result.recordFields.sort() only after
confirming it exists) to make the failure message clearer; update the test in
templateSandbox.test.ts where validCases and sandboxedParseTemplate are used.
In `@src/v0/destinations/custom_audience/template/templateSandbox.ts`:
- Around line 49-51: The current construction of the expression string
serializes the entire chunks array into expression via JSON.stringify (see the
expression variable and evaluateTemplateInSandbox call), which can cause memory
pressure for very large batches; change the approach so you do NOT stringify the
full chunks outside the sandbox — instead pass only a lightweight reference
(e.g., metadata, chunk IDs or start/end indices) or a smaller payload and
perform JSON parsing/serialization inside the sandboxed context (or
stream/iterate chunks in smaller batches) before calling
evaluateTemplateInSandbox, updating the code that builds expression and the
caller of evaluateTemplateInSandbox to accept the new smaller payload shape.
- Around line 28-31: The catch block in templateSandbox.ts currently logs the
full error via logger.error but returns only a generic fallback (the return in
the catch that yields { valid: false, errors: ['Template parsing is temporarily
unavailable.'] }); update this to include a sanitized, truncated error hint in
the returned errors so operators and users get actionable context without
leaking sensitive data: create or call a small sanitizer (e.g., sanitizeError or
maskStack) to remove PII/paths and limit length, then return something like {
valid: false, errors: ['Template parsing is temporarily unavailable.', `Error
hint: ${sanitizedHint}`] }; keep logger.error as-is to preserve full logs.
In `@src/v0/destinations/custom_audience/utils.ts`:
- Around line 44-48: The endpoint template evaluation currently coerces any
result into a string (assigned to resolved) using
JsonTemplateEngine.createAsSync(...).evaluate(...) ?? '' which can yield
'[object Object]' for non-string results; update the code around
JsonTemplateEngine.createAsSync and the evaluate call to explicitly verify the
evaluation result is a string (e.g., check typeof result === 'string' and
non-empty/trimmed), and if it is not, throw or return a clear validation error
before assigning resolved so malformed objects/arrays cannot produce invalid
endpoint URLs.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 64b91768-17ad-493c-8b1c-6a1348730470
⛔ Files ignored due to path filters (3)
.claude/skills/code-structure/SKILL.mdis excluded by!**/*.md.claude/skills/typescript-guidelines/SKILL.mdis excluded by!**/*.mdpackage.jsonis excluded by!**/*.json
📒 Files selected for processing (19)
src/controllers/__tests__/eventTest.test.tssrc/controllers/eventTest.tssrc/services/destination/nativeBatching/chunkBatchStrategy.tssrc/services/destination/nativeBatching/chunkPayloads.tssrc/services/destination/nativeBatching/customBatchStrategy.tssrc/services/destination/nativeBatching/processBatchedDestination.tssrc/services/destination/nativeBatching/types.tssrc/v0/destinations/custom_audience/routerTransform.test.tssrc/v0/destinations/custom_audience/routerTransform.tssrc/v0/destinations/custom_audience/template/ivmScriptRunner.tssrc/v0/destinations/custom_audience/template/sandboxedParse.entry.tssrc/v0/destinations/custom_audience/template/sandboxedTemplate.entry.tssrc/v0/destinations/custom_audience/template/templateParserSandbox.test.tssrc/v0/destinations/custom_audience/template/templateParserSandbox.tssrc/v0/destinations/custom_audience/template/templateSandbox.test.tssrc/v0/destinations/custom_audience/template/templateSandbox.tssrc/v0/destinations/custom_audience/utils.test.tssrc/v0/destinations/custom_audience/utils.tssrc/v0/destinations/posthog/routerTransform.test.ts
💤 Files with no reviewable changes (4)
- src/v0/destinations/custom_audience/template/templateParserSandbox.ts
- src/v0/destinations/custom_audience/utils.test.ts
- src/v0/destinations/custom_audience/template/templateParserSandbox.test.ts
- src/v0/destinations/custom_audience/template/sandboxedParse.entry.ts
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## develop #5193 +/- ##
===========================================
- Coverage 92.32% 92.32% -0.01%
===========================================
Files 678 679 +1
Lines 37133 37175 +42
Branches 8689 8701 +12
===========================================
+ Hits 34282 34320 +38
- Misses 2613 2617 +4
Partials 238 238 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
35ebf01 to
19d85c7
Compare
19d85c7 to
9d05d28
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/v0/destinations/custom_audience/routerTransform.test.ts (1)
8-8: ⚡ Quick winMove
assertBundleFreshnessfrom a test file to a shared helper module.Importing
assertBundleFreshnessfromtemplateSandbox.test.ts(line 8) causes that test module to execute on import, registering its describe and it blocks prematurely. Extract the function into a non-test helper module (e.g.,template/templateHelpers.tsor similar) and import it from both test files to avoid test registration side effects.🤖 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 `@src/v0/destinations/custom_audience/routerTransform.test.ts` at line 8, The test helper assertBundleFreshness is defined in templateSandbox.test.ts which causes that test file to execute when imported; extract assertBundleFreshness into a non-test helper module (e.g., create template/templateHelpers.ts or template/assertBundleFreshness.ts) and move its implementation there, then update imports in routerTransform.test.ts (and any other tests) to import { assertBundleFreshness } from the new helper module instead of from templateSandbox.test.ts; ensure the new file exports only the helper (no describe/it) so importing it does not register tests.src/v0/destinations/custom_audience/template/ivmScriptRunner.ts (1)
146-146: ⚡ Quick winConsider extracting BUNDLE_PATH to avoid duplication.
BUNDLE_PATHis defined identically in bothivmScriptRunner.ts(line 146) andtemplateSandbox.test.ts(line 17). To maintain DRY principles and ensure consistency, consider exportingBUNDLE_PATHfromivmScriptRunner.tsand importing it in the test file.♻️ Proposed refactor
Export from
ivmScriptRunner.ts:// Resolve relative to __dirname so the path is stable regardless of process.cwd(). // Works under both ts-jest (src/) and compiled runtime (dist/). -const BUNDLE_PATH = path.resolve(__dirname, '../../../../../dist/sandboxedTemplate.bundle.js'); +export const BUNDLE_PATH = path.resolve(__dirname, '../../../../../dist/sandboxedTemplate.bundle.js');Then in
templateSandbox.test.ts, import instead of redefining:import fs from 'fs'; import path from 'path'; import { InstrumentationError, PlatformError } from '@rudderstack/integrations-lib'; import { sandboxedEvaluateTemplate, sandboxedParseTemplate } from './templateSandbox'; -import { templateSandboxRunner } from './ivmScriptRunner'; +import { templateSandboxRunner, BUNDLE_PATH } from './ivmScriptRunner'; -const BUNDLE_PATH = path.resolve(__dirname, '../../../../../dist/sandboxedTemplate.bundle.js'); const ENTRY_SOURCE = path.resolve(__dirname, 'sandboxedTemplate.entry.ts');🤖 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 `@src/v0/destinations/custom_audience/template/ivmScriptRunner.ts` at line 146, Extract the duplicated BUNDLE_PATH constant so the test imports the single source of truth: change the local const BUNDLE_PATH in ivmScriptRunner.ts to an exported symbol (e.g., export const BUNDLE_PATH) and remove the duplicate definition in templateSandbox.test.ts, then import { BUNDLE_PATH } from the ivmScriptRunner module in the test; ensure the exported value uses the same path.resolve(...) logic so both runtime and tests reference the identical bundle path.
🤖 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.
Inline comments:
In `@src/v0/destinations/custom_audience/template/ivmScriptRunner.ts`:
- Around line 150-152: The env parsing for memoryLimitMb, initTimeoutMs, and
execTimeoutMs uses Number.parseInt which can yield NaN for non-numeric env
values; update the logic that reads CUSTOM_AUDIENCE_IVM_MEMORY_MB,
CUSTOM_AUDIENCE_IVM_INIT_TIMEOUT_MS, and CUSTOM_AUDIENCE_IVM_EXEC_TIMEOUT_MS to
validate the parsed number (e.g., Number.parseInt(..., 10) followed by
Number.isFinite or Number.isNaN checks) and fallback to the current defaults
(32, 5000, 500) when parsing fails or results in NaN so the isolate creation
always receives a valid numeric value.
---
Nitpick comments:
In `@src/v0/destinations/custom_audience/routerTransform.test.ts`:
- Line 8: The test helper assertBundleFreshness is defined in
templateSandbox.test.ts which causes that test file to execute when imported;
extract assertBundleFreshness into a non-test helper module (e.g., create
template/templateHelpers.ts or template/assertBundleFreshness.ts) and move its
implementation there, then update imports in routerTransform.test.ts (and any
other tests) to import { assertBundleFreshness } from the new helper module
instead of from templateSandbox.test.ts; ensure the new file exports only the
helper (no describe/it) so importing it does not register tests.
In `@src/v0/destinations/custom_audience/template/ivmScriptRunner.ts`:
- Line 146: Extract the duplicated BUNDLE_PATH constant so the test imports the
single source of truth: change the local const BUNDLE_PATH in ivmScriptRunner.ts
to an exported symbol (e.g., export const BUNDLE_PATH) and remove the duplicate
definition in templateSandbox.test.ts, then import { BUNDLE_PATH } from the
ivmScriptRunner module in the test; ensure the exported value uses the same
path.resolve(...) logic so both runtime and tests reference the identical bundle
path.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: acc15c23-42bf-4f27-b7c2-85852b623be9
⛔ Files ignored due to path filters (3)
.claude/skills/code-structure/SKILL.mdis excluded by!**/*.md.claude/skills/typescript-guidelines/SKILL.mdis excluded by!**/*.mdpackage.jsonis excluded by!**/*.json
📒 Files selected for processing (21)
src/controllers/__tests__/eventTest.test.tssrc/controllers/eventTest.tssrc/services/destination/nativeBatching/__tests__/batchDestination.test.tssrc/services/destination/nativeBatching/chunkBatchStrategy.tssrc/services/destination/nativeBatching/chunkPayloads.tssrc/services/destination/nativeBatching/customBatchStrategy.tssrc/services/destination/nativeBatching/processBatchedDestination.tssrc/services/destination/nativeBatching/types.tssrc/v0/destinations/custom_audience/routerTransform.test.tssrc/v0/destinations/custom_audience/routerTransform.tssrc/v0/destinations/custom_audience/template/ivmScriptRunner.test.tssrc/v0/destinations/custom_audience/template/ivmScriptRunner.tssrc/v0/destinations/custom_audience/template/sandboxedParse.entry.tssrc/v0/destinations/custom_audience/template/sandboxedTemplate.entry.tssrc/v0/destinations/custom_audience/template/templateParserSandbox.test.tssrc/v0/destinations/custom_audience/template/templateParserSandbox.tssrc/v0/destinations/custom_audience/template/templateSandbox.test.tssrc/v0/destinations/custom_audience/template/templateSandbox.tssrc/v0/destinations/custom_audience/utils.test.tssrc/v0/destinations/custom_audience/utils.tssrc/v0/destinations/posthog/routerTransform.test.ts
💤 Files with no reviewable changes (4)
- src/v0/destinations/custom_audience/template/templateParserSandbox.ts
- src/v0/destinations/custom_audience/template/templateParserSandbox.test.ts
- src/v0/destinations/custom_audience/utils.test.ts
- src/v0/destinations/custom_audience/template/sandboxedParse.entry.ts
🚧 Files skipped from review as they are similar to previous changes (11)
- src/v0/destinations/posthog/routerTransform.test.ts
- src/services/destination/nativeBatching/types.ts
- src/controllers/tests/eventTest.test.ts
- src/controllers/eventTest.ts
- src/services/destination/nativeBatching/chunkPayloads.ts
- src/services/destination/nativeBatching/customBatchStrategy.ts
- src/v0/destinations/custom_audience/utils.ts
- src/v0/destinations/custom_audience/template/templateSandbox.ts
- src/services/destination/nativeBatching/chunkBatchStrategy.ts
- src/v0/destinations/custom_audience/template/sandboxedTemplate.entry.ts
- src/services/destination/nativeBatching/processBatchedDestination.ts
- Rename chunkPayloadsBySize → chunkPayloads - Use PlatformError for body count mismatch (internal issue, not user error) - Deduplicate EvaluateResult type (export from templateSandbox, import type in entry) - Update error message wording Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/v0/destinations/custom_audience/routerTransform.ts (1)
97-134: 💤 Low valueAsync batch strategy and sandboxed evaluation wiring look correct.
A few small observations on the new
getBatchStrategybody:
- Lines 102–103 assume
payloadsis non-empty (it dereferencespayloads[0].internalGroupKey). This matches the framework's per-group invocation contract, so it's fine — but if you'd like a belt-and-braces guard, a short-circuitif (payloads.length === 0) return [];at the top of the strategy callback would make this resilient to future changes in caller behavior.- Lines 112–114: the throwing
wrapBodystub is a nice defensive contract sincemaxPayloadSizeisn't passed — clear intent that this code path is unreachable today.- Lines 122–127: the 1:1 post-condition between
bodiesandchunksplus thePlatformError(500)classification reads well as a sandbox-boundary assertion.Nothing blocking here.
🤖 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 `@src/v0/destinations/custom_audience/routerTransform.ts` around lines 97 - 134, The batch strategy assumes payloads is non-empty; update the async callback passed to new CustomBatchStrategy in getBatchStrategy to short-circuit and return an empty array when payloads.length === 0 to guard getBatchStrategy/CustomBatchStrategy from future caller changes, keeping all existing logic (chunkPayloads, wrapBody stub, sandboxedEvaluateTemplate and the 1:1 bodies/chunks check) unchanged.src/services/destination/nativeBatching/chunkPayloads.ts (1)
38-45: ⚖️ Poor tradeoffO(n²) size estimation on large chunks — consider tracking a running byte count.
For every incoming payload, this re-serializes the entire prospective chunk via
JSON.stringify(wrapBody([...currentBodies, payload.body])). WhenmaxItemsis large (or unset) and many payloads fit undermaxPayloadSize, this grows quadratically with chunk size and is a noticeable hot-path cost during batching.A common alternative is to measure the incremental cost (body byte length + a small per-item overhead estimate) and only call
wrapBodyto refine when close to the limit, or to maintain a running byte counter and reset it on flush. Not blocking — current behavior is correct — but worth considering if chunks routinely contain hundreds of records.🤖 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 `@src/services/destination/nativeBatching/chunkPayloads.ts` around lines 38 - 45, The size check re-serializes the entire prospective chunk on every add (JSON.stringify(wrapBody([...currentBodies, payload.body]))) causing O(n²) behavior; change to maintain a running byte counter (e.g., bytesInCurrentChunk) updated when adding/removing items using Buffer.byteLength(JSON.stringify(payload.body)) plus any per-item overhead introduced by wrapBody, only recomputing full wrapBody serialization when the running count is close to maxPayloadSize; update bytesInCurrentChunk on flush() to reset to zero and use it in the conditional instead of re-serializing currentBodies each time (references: maxPayloadSize, currentBodies, payload.body, wrapBody, flush).
🤖 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.
Inline comments:
In `@src/services/destination/nativeBatching/chunkPayloads.ts`:
- Around line 38-45: The current logic may push a single oversize payload into a
chunk after calling flush; update the code in chunkPayloads.ts around the
maxPayloadSize check to detect the "single-body too large" case: after computing
prospectiveBytes for wrapBody([...currentBodies, payload.body]) and calling
flush(), compute singleBodyBytes =
Buffer.byteLength(JSON.stringify(wrapBody([payload.body]))); if singleBodyBytes
> maxPayloadSize then surface a clear error (throw or return an error result)
instead of blindly pushing the body (or alternatively add an explicit comment
and documented acceptance if you prefer fallback behavior); reference symbols:
maxPayloadSize, wrapBody, currentBodies, payload.body, flush to locate and
implement the check and error handling.
---
Nitpick comments:
In `@src/services/destination/nativeBatching/chunkPayloads.ts`:
- Around line 38-45: The size check re-serializes the entire prospective chunk
on every add (JSON.stringify(wrapBody([...currentBodies, payload.body])))
causing O(n²) behavior; change to maintain a running byte counter (e.g.,
bytesInCurrentChunk) updated when adding/removing items using
Buffer.byteLength(JSON.stringify(payload.body)) plus any per-item overhead
introduced by wrapBody, only recomputing full wrapBody serialization when the
running count is close to maxPayloadSize; update bytesInCurrentChunk on flush()
to reset to zero and use it in the conditional instead of re-serializing
currentBodies each time (references: maxPayloadSize, currentBodies,
payload.body, wrapBody, flush).
In `@src/v0/destinations/custom_audience/routerTransform.ts`:
- Around line 97-134: The batch strategy assumes payloads is non-empty; update
the async callback passed to new CustomBatchStrategy in getBatchStrategy to
short-circuit and return an empty array when payloads.length === 0 to guard
getBatchStrategy/CustomBatchStrategy from future caller changes, keeping all
existing logic (chunkPayloads, wrapBody stub, sandboxedEvaluateTemplate and the
1:1 bodies/chunks check) unchanged.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1e702801-e3ac-4a87-86b4-ba5ea6bdfcb5
📒 Files selected for processing (5)
src/services/destination/nativeBatching/chunkBatchStrategy.tssrc/services/destination/nativeBatching/chunkPayloads.tssrc/v0/destinations/custom_audience/routerTransform.tssrc/v0/destinations/custom_audience/template/sandboxedTemplate.entry.tssrc/v0/destinations/custom_audience/template/templateSandbox.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/v0/destinations/custom_audience/template/templateSandbox.ts
- src/services/destination/nativeBatching/chunkBatchStrategy.ts
- src/v0/destinations/custom_audience/template/sandboxedTemplate.entry.ts
|



Summary
Moves user-supplied
requestBodytemplate evaluation into isolated-vm, completing the sandbox work started in #5185 (which sandboxed only the parse step). After this change, untrusted templates supplied via destination config never run in the Node process — both validation and execution happen inside a memory- and time-limited isolate.Why isolated-vm for evaluation?
The
requestBodytemplate is authored by customers via the dashboard and executed per-batch during router transforms. Running it in-process means a malicious or buggy template could access Node globals, block the event loop, or exhaust memory. The parse step was already sandboxed (#5185), but the evaluate step was still running in-process with a TODO comment. This PR closes that gap.Key design decisions
One bundle, one isolate per workspace — Parse and evaluate share a single esbuild bundle (
dist/sandboxedTemplate.bundle.js) and a singleIvmScriptRunnerinstance. The runner is sized for the heavier evaluate operation (32 MB heap, 500 ms exec timeout, configurable viaCUSTOM_AUDIENCE_IVM_*env vars). This avoids maintaining two separate bundles/runners for operations that always coexist.Structured clone via
evalClosure— Data (template, chunks, connection config) is passed into the isolate usingcontext.evalClosure()with{ copy: true }, which uses V8's structured clone. This avoidsJSON.stringifyembedding in script text, which silently dropsundefined, convertsNaN/Infinitytonull, and requires V8 to re-parse serialized text as JS source. Args are scoped to the closure (referenced as$0,$1,$2), avoiding global mutation and race conditions between concurrent calls for the same workspace. This is consistent with how user transformers pass data into isolates viaExternalCopy.Chunking stays in Node, evaluation goes to the isolate — The batch strategy chunks payloads by
batchSizeusing the existing native-batching infrastructure, then passes all chunks to the isolate in a single call. The isolate evaluates the template once per chunk and returns an array of response bodies. This keeps the chunking logic reusable and limits isolate round-trips (≤ 3 per transform, one per action group).Async
BatchStrategy.batch()— The isolate call is inherently async, soBatchStrategy.batch()now returnsPromise<BatchGroup[]>. This is a framework-level change that touchesChunkBatchStrategy,CustomBatchStrategy, andprocessBatchedDestination. Existing sync strategies (e.g. PostHog) are unaffected since returning a value from an async function wraps it in a resolved promise.Error categorization — Template runtime errors (bad syntax, missing field) throw
InstrumentationError(4xx, user's template is wrong). Isolate infrastructure failures (timeout, OOM, disposed isolate) throwPlatformError(5xx, retryable).What changed
ivmScriptRunner.ts—execute()now usescontext.evalClosure()with{ copy: true }(structured clone) instead ofisolate.compileScript()withJSON.stringify-embedded data. Args are passed as$0, $1, $2scoped to the closure — no global mutation, no race conditions. Adds a shared singletontemplateSandboxRunnerat module level.sandboxedTemplate.entry.ts(new) — ReplacessandboxedParse.entry.ts. Exports two globals onglobalThis:parseTemplateInSandbox(unchanged) andevaluateTemplateInSandbox(new). The evaluate function compiles the template viaJsonTemplateEngine, maps it over all chunks, and returns{ ok, bodies }or{ ok: false, error }.templateSandbox.ts(new) — ReplacestemplateParserSandbox.ts. ExportssandboxedParseTemplate(unchanged behaviour) andsandboxedEvaluateTemplate(new). Both useexecuteClosurewith positional args.routerTransform.ts—getBatchStrategy()switches fromChunkBatchStrategywrapping an in-processevaluateTemplatetoCustomBatchStrategythat chunks payloads viachunkPayloadsBySize, then callssandboxedEvaluateTemplatein the isolate.chunkPayloads.ts(new) — Extracts the chunking loop fromChunkBatchStrategyinto a standalonechunkPayloadsBySize()function.wrapBodyis mandatory — callers that don't use size-based splitting pass a no-op that throws if invoked unexpectedly.ChunkBatchStrategynow delegates to it.utils.ts— Removes the in-processevaluateTemplatefunction.resolveEndpoint(its only remaining caller) inlines the template engine call directly, with a comment explaining why endpoint resolution intentionally stays in-process (no record data, no user-controlled template path — only${$.connection.fieldName}interpolation).types.ts/chunkBatchStrategy.ts/customBatchStrategy.ts/processBatchedDestination.ts—BatchStrategy.batch()signature becomesasync → Promise<BatchGroup[]>.processBatchedDestinationawaits the call.Tests —
templateSandbox.test.tscovers parse (same cases as before) plus evaluate: multi-chunk evaluation, object-iteration templates,InstrumentationErroron bad templates,PlatformErroron isolate failure, and structured clone type preservation (undefined, NaN, Infinity).assertBundleFreshnessis defined once and imported inrouterTransform.test.ts. PostHog router tests updated toawaitthe now-asyncbatch().batchDestination.test.tsadds an asyncCustomBatchStrategytest case.Test plan
npm run build:custom-audience-sandboxproduces up-to-datedist/sandboxedTemplate.bundle.jsnpm run lintcleannpm test -- --testPathPattern="custom_audience|nativeBatching|posthog|eventTest" --no-coverage— all tests passnpm run test:ts -- component --destination=custom_audience— 5/5 router integration scenarios passChunkBatchStrategy) still works through the now-asyncbatch()interfacebeforeAllguard inrouterTransform.test.tsandtemplateSandbox.test.tscatches stale bundles in CIundefined,NaN,Infinitysurvive the isolate boundary🤖 Generated with Claude Code