Joshua Freedman 4a7324c0c8 fix(serverless): flush IPC message before exiting local function runner (#22920)
Closes #22925

## Problem

`LocalChildProcessRunnerService.writeBootstrapRunner` generates a
child-process runner that returns the function result to the parent over
the Node IPC channel:

```js
const out = await handlerFn(msg.payload);
process.send && process.send({ ok: true, result: out });
process.exit(0);
```

`process.send()` is **asynchronous**. When the serialized payload is
larger than the OS pipe buffer (~64 KB on Linux), it can't be written in
a single synchronous step, and the `process.exit(0)` on the next line
tears the child down before the message is flushed.

On the parent side (`runChildWithEnv`), the lost message means the
`'message'` handler never fires — only `'exit'` with `code === 0` does,
which resolves:

```js
resolve({ ok: true, stdout, stderr }); // no `result`
```

`LocalDriver.execute` then returns `data: result ?? null` → **`null`**,
so the function's return value is silently discarded while the step is
reported as a *success* with an empty result.

## Symptom

Larger serverless / workflow **Code** step results intermittently come
back empty (`{}` / `null`). It is size- and load-dependent, so it
presents as flakiness. A common downstream failure is a workflow
**Iterator** fed the now-missing array:

```
Iterator input items must be an array
```

Results smaller than the pipe buffer always flush synchronously and
never reproduce it — which is why only larger payloads are affected.

## Root cause

`process.exit()` runs before the asynchronous `process.send()` (and the
stdout fallback `process.stdout.write()`) has flushed — the classic Node
footgun of exiting before pending async writes drain.

## Fix

Wait for the `send()` / `write()` flush callback before exiting, on
every exit path (success, error, stdout fallback, outer catch):

```js
if (process.send) {
  process.send({ ok: true, result: out }, () => process.exit(0));
} else {
  process.exit(0);
}
```

Behavior-preserving: it never delivers *less* than before; it only
closes the window where a large result is dropped. No change to the
small-payload happy path.

## Deterministic reproduction

Reproduces the dropped IPC message under back-pressure (parent stalls
before draining), comparing the current pattern vs the fix:

```js
const { spawn } = require('node:child_process');
const fs = require('fs');

const SIZE = 3_000_000; // beyond any pipe buffer
const child = (mode) => `
  process.on('message', () => {
    const out = 'z'.repeat(${SIZE});
    ${mode === 'fixed'
      ? 'process.send({ ok: true, result: out }, () => process.exit(0));'
      : 'process.send({ ok: true, result: out }); process.exit(0);'}
  });`;

const busy = (ms) => { const e = Date.now() + ms; while (Date.now() < e) {} };

function trial(mode) {
  return new Promise((resolve) => {
    const f = `/tmp/child_${mode}.cjs`;
    fs.writeFileSync(f, child(mode));
    const c = spawn(process.execPath, [f], { stdio: ['pipe', 'pipe', 'pipe', 'ipc'] });
    let got = false;
    c.on('message', (m) => { got = m?.result?.length === SIZE; });
    c.on('exit', () => resolve(got));
    c.send({ type: 'run' });
    busy(30); // stall parent so it doesn't drain the IPC pipe promptly
  });
}

(async () => {
  for (const mode of ['current', 'fixed']) {
    let ok = 0; const N = 25;
    for (let i = 0; i < N; i += 5) {
      ok += (await Promise.all([...Array(5)].map(() => trial(mode)))).filter(Boolean).length;
    }
    console.log(`${mode}: result delivered ${ok}/${N}`);
  }
})();
```

Output:

```
current: result delivered 0/25
fixed:   result delivered 25/25
```


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/twentyhq/twenty/pull/22920?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
2026-07-17 10:09:28 +02:00
2026-06-11 11:02:28 +02:00

Twenty logo

The #1 Open-Source CRM

Website · Documentation · Roadmap · Discord · Figma

Twenty banner


Why Twenty

Twenty gives technical teams the building blocks for a custom CRM that meets complex business needs and quickly adapts as the business evolves. Twenty is the CRM you build, ship, and version like the rest of your stack.

Learn more about why we built Twenty


Installation

Cloud

The fastest way to get started. Sign up at twenty.com and spin up a workspace in under a minute, with no infrastructure to manage and always up to date.

Build an app

Scaffold a new app with the Twenty CLI:

npx create-twenty-app my-app

Define objects, fields, and views as code:

import { defineObject, FieldType } from 'twenty-sdk/define';

export default defineObject({
  nameSingular: 'deal',
  namePlural: 'deals',
  labelSingular: 'Deal',
  labelPlural: 'Deals',
  fields: [
    { name: 'name', label: 'Name', type: FieldType.TEXT },
    { name: 'amount', label: 'Amount', type: FieldType.CURRENCY },
    { name: 'closeDate', label: 'Close Date', type: FieldType.DATE_TIME },
  ],
});

Then ship it to your workspace:

npx twenty app:publish --private

See the app development guide for objects, views, agents, and logic functions.

Self-hosting

Run Twenty on your own infrastructure with Docker Compose, or contribute locally via the local setup guide.



Everything you need

Twenty gives you the building blocks of a modern CRM (objects, views, workflows, and agents) and lets you extend them as code. Here's a tour of what's in the box.

Want to go deeper? Read the User Guide for product walkthroughs, or the Documentation for developer reference.

Create your apps

Learn more about apps in doc

Stay on top with version control

Learn more about version control in doc

All the tools you need to build anything

Learn more about primitives in doc

Customize your layouts

Learn more about layouts in doc

AI agents and chats

Learn more about AI in doc

Plus all the tools of a good CRM

Learn more about CRM features in doc


Stack

Thanks

Greptile      Sentry      Crowdin

Thanks to these amazing services that we use and recommend for code review (Greptile), catching bugs (Sentry) and translating (Crowdin).

Join the Community

Star the repo · Discord · Feature requests · Releases · X · LinkedIn · Crowdin · Contribute

S
Description
The open alternative to Salesforce, designed for AI.
Readme AGPL-3.0 1.4 GiB
Languages
TypeScript 79.6%
MDX 17.3%
JavaScript 2.7%
Python 0.2%
SCSS 0.1%