Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(hogql): build the parser WASM without dynamic execution (#100642)

Tom Piccirello334006bddad6
diff --git a/common/hogql_parser/CMakeLists.txt b/common/hogql_parser/CMakeLists.txt
index 152a58c282c7..1ffdf5c13960 100644
--- a/common/hogql_parser/CMakeLists.txt
+++ b/common/hogql_parser/CMakeLists.txt
@@ -53,10 +53,24 @@ if(EMSCRIPTEN)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fwasm-exceptions")
# Shared link flags for all WASM targets
+ #
+ # DYNAMIC_EXECUTION=0 removes the `new Function` that embind emits. By default embind builds
+ # an invoker per bound signature by concatenating a function body and compiling it, and the
+ # app's `script-src` reports that as an eval violation. With the flag, embind closes over the
+ # argument converters and calls `.apply` instead. That costs a little per call and nothing
+ # per parse.
+ #
+ # The flag does not fail the build when the glue needs dynamic execution. Emscripten replaces
+ # each eval site with `abort('DYNAMIC_EXECUTION=0 was set, cannot eval')`, so a binding that
+ # needs one links clean and aborts at runtime. The check is on the output:
+ # frontend/src/lib/monaco/__tests__/hogqlParserCjs.test.ts asserts that the published glue
+ # contains neither `new Function(` nor that abort string. Do not switch to `=2`, which keeps
+ # the eval and only logs a warning.
set(WASM_COMMON_LINK_FLAGS "\
-lembind \
-s WASM=1 \
-s MODULARIZE=1 \
+ -s DYNAMIC_EXECUTION=0 \
-s EXPORT_NAME='createHogQLParser' \
-s ALLOW_MEMORY_GROWTH=1 \
-s SINGLE_FILE=1 \
diff --git a/common/hogql_parser/CONTRIBUTING.md b/common/hogql_parser/CONTRIBUTING.md
index 47319ac7ed08..03ea18f63f0a 100644
--- a/common/hogql_parser/CONTRIBUTING.md
+++ b/common/hogql_parser/CONTRIBUTING.md
@@ -77,51 +77,37 @@ In that case run commands from [this step](https://github.com/PostHog/posthog/bl
## WebAssembly (JavaScript/TypeScript) build
-The HogQL parser can also be compiled to WebAssembly for use in JavaScript/TypeScript environments via the `@posthog/hogql-parser` workspace package.
+The HogQL parser also compiles to WebAssembly. The `@posthog/hogql-parser` npm package wraps it for JavaScript and TypeScript.
### Prerequisites
-1. Install [Emscripten](https://emscripten.org/docs/getting_started/downloads.html):
-
- ```bash
- # macOS
- brew install emscripten
-
- # Ubuntu/Debian
- sudo apt-get install emscripten
- ```
-
-2. Install Ninja (recommended for faster builds):
-
- ```bash
- # macOS
- brew install ninja
-
- # Ubuntu/Debian
- sudo apt-get install ninja-build
- ```
+The repo's flox environment provides Emscripten, CMake and Ninja at the versions CI uses (`.github/actions/setup-emsdk` pins the Emscripten version). Run the build inside `flox activate`.
### Building
-From the repository root:
-
```bash
-# Using Ninja (recommended, faster)
-pnpm --filter=@posthog/hogql-parser build
-
-# Or using Make
-pnpm --filter=@posthog/hogql-parser build:make
+cd common/hogql_parser
+npm run build # Ninja
+npm run build:make # or Make
```
-This will generate the following files in `common/hogql_parser/dist/`:
+This generates the following files in `common/hogql_parser/dist/`:
-- `hogql_parser_wasm.js` - ES module with embedded WASM
+- `hogql_parser_wasm.js` - ES module for Node.js, with embedded WASM
+- `hogql_parser_wasm_browser.js` - ES module for browsers and web workers
+- `hogql_parser_wasm.cjs` - CommonJS module for Jest
- `index.cjs` - CommonJS wrapper
- `index.d.ts` - TypeScript type definitions
+The glue must load under the app's content security policy, so `CMakeLists.txt` links it with `DYNAMIC_EXECUTION=0`. Check a fresh build with:
+
+```bash
+grep -a -c 'new Function(' dist/hogql_parser_wasm_browser.js # must print 0
+```
+
### Using in the frontend
-The frontend uses this as a workspace dependency. After building, the parser can be used:
+The frontend pins the published npm package in `frontend/package.json`. To release a new version, bump `version` in `common/hogql_parser/package.json` in your PR. The `Release hogql-parser npm` workflow then builds the package, publishes it to npm, and commits the new pin to your branch.
```typescript
import createHogQLParser from '@posthog/hogql-parser'
diff --git a/common/hogql_parser/package.json b/common/hogql_parser/package.json
index 86dbb32ec0f8..f63f724bc3b6 100644
--- a/common/hogql_parser/package.json
+++ b/common/hogql_parser/package.json
@@ -1,6 +1,6 @@
{
"name": "@posthog/hogql-parser",
- "version": "1.3.84",
+ "version": "1.3.88",
"description": "WebAssembly HogQL Parser - Parse HogQL queries in JavaScript/TypeScript",
"keywords": [
"antlr4",
@@ -41,7 +41,7 @@
},
"scripts": {
"build:compile": "emmake cmake --build build_wasm --config Release && cmake --install build_wasm",
- "build:make": "emcmake cmake -S . -B build_wasm -DCMAKE_BUILD_TYPE=Release && npm run build:compile || echo 'Warning: hogql-parser build failed, skipping'",
- "build": "emcmake cmake -S . -B build_wasm -G Ninja -DCMAKE_BUILD_TYPE=Release && npm run build:compile || echo 'Warning: hogql-parser build failed, skipping'"
+ "build:make": "emcmake cmake -S . -B build_wasm -DCMAKE_BUILD_TYPE=Release && npm run build:compile",
+ "build": "emcmake cmake -S . -B build_wasm -G Ninja -DCMAKE_BUILD_TYPE=Release && npm run build:compile"
}
}
diff --git a/frontend/package.json b/frontend/package.json
index fe3eff6045f9..d5829e3547db 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -78,7 +78,7 @@
"@posthog/docs-onboarding": "workspace:*",
"@posthog/esbuilder": "workspace:*",
"@posthog/hedgehog-mode": "^0.0.57",
- "@posthog/hogql-parser": "1.3.84",
+ "@posthog/hogql-parser": "1.3.88",
"@posthog/hogvm": "workspace:*",
"@posthog/icons": "catalog:",
"@posthog/llm-normalizer": "workspace:*",
diff --git a/frontend/src/lib/monaco/__tests__/hogqlParserCjs.test.ts b/frontend/src/lib/monaco/__tests__/hogqlParserCjs.test.ts
index 1306c77b77fc..003c7706913d 100644
--- a/frontend/src/lib/monaco/__tests__/hogqlParserCjs.test.ts
+++ b/frontend/src/lib/monaco/__tests__/hogqlParserCjs.test.ts
@@ -1,6 +1,15 @@
// Regression test: the @posthog/hogql-parser package works in Jest without mocks
+import fs from 'fs'
+import path from 'path'
+
import createHogQLParser from '@posthog/hogql-parser'
+// The app's CSP has no 'unsafe-eval', so the published glue must be linked with
+// DYNAMIC_EXECUTION=0. Emscripten does not fail the build without it: the default embind emits a
+// `new Function` invoker, and with the flag a binding that still needs eval becomes a runtime
+// abort. Both leave a fixed string in the output, so the check runs on the pinned package.
+const GLUE_FILES = ['hogql_parser_wasm_browser.js', 'hogql_parser_wasm.js', 'hogql_parser_wasm.cjs']
+
describe('@posthog/hogql-parser', () => {
it('exports a factory function', () => {
expect(typeof createHogQLParser).toBe('function')
@@ -16,4 +25,11 @@ describe('@posthog/hogql-parser', () => {
const result = JSON.parse(parser.parseSelect('SELECT 1'))
expect(result.node).toBe('SelectQuery')
})
+
+ it.each(GLUE_FILES)('%s is built without dynamic execution', (file) => {
+ const distDir = path.dirname(require.resolve('@posthog/hogql-parser'))
+ const glue = fs.readFileSync(path.join(distDir, file), 'utf8')
+ expect(glue).not.toContain('new Function(')
+ expect(glue).not.toContain('DYNAMIC_EXECUTION=0 was set')
+ })
})
diff --git a/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.test.ts b/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.test.ts
index 50083db9e893..0279f1c4eef5 100644
--- a/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.test.ts
@@ -16,12 +16,16 @@ jest.mock('@posthog/hogql-parser', () => ({
describe('hogqlParserSingleton', () => {
let parseSelect: (input: string, isInternal?: boolean) => Promise<string>
+ let captureException: jest.SpyInstance
beforeEach(async () => {
jest.resetModules()
parseSelectMock.mockReset()
initMock.mockReset()
parseSelectMock.mockImplementation((input: string) => `{"node":"SelectQuery","len":${input.length}}`)
+ // Imported after the reset, so the spy sits on the posthog-js instance the singleton loads.
+ const { default: posthog } = await import('posthog-js')
+ captureException = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)
;({ parseSelect } = await import('./hogqlParserSingleton'))
})
@@ -70,6 +74,24 @@ describe('hogqlParserSingleton', () => {
await expect(parseSelect('SELECT 1 FROM events')).rejects.toThrow('boom')
await expect(parseSelect('SELECT 1 FROM events')).resolves.toContain('SelectQuery')
expect(parseSelectMock).toHaveBeenCalledTimes(2)
+ // Only init failures are reported. A failure of one parse is per query and would flood error tracking.
+ expect(captureException).not.toHaveBeenCalled()
+ })
+
+ it('reports a failed parser init once, however many parses retry it', async () => {
+ // A CSP that blocks the glue's eval fails init on every retry, and the editor's fallback
+ // swallows the rejection, so this report is the only trace of a broken parser.
+ const blocked = new EvalError('Refused to evaluate a string as JavaScript')
+ initMock.mockImplementation(() => {
+ throw blocked
+ })
+
+ await expect(parseSelect('SELECT 1 FROM events')).rejects.toBe(blocked)
+ await expect(parseSelect('SELECT 2 FROM events')).rejects.toBe(blocked)
+
+ expect(initMock).toHaveBeenCalledTimes(2)
+ expect(captureException).toHaveBeenCalledTimes(1)
+ expect(captureException).toHaveBeenCalledWith(blocked, { feature: 'hogql-parser-init' })
})
it('does not grow without bound as the query is edited', async () => {
diff --git a/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.ts b/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.ts
index 9cb25ebfaff3..e3bf4cdb9a93 100644
--- a/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.ts
+++ b/frontend/src/scenes/data-warehouse/editor/hogqlParserSingleton.ts
@@ -1,6 +1,9 @@
+import posthog from 'posthog-js'
+
import type { HogQLParser } from '@posthog/hogql-parser'
let parserPromise: Promise<HogQLParser> | null = null
+let initFailureReported = false
function getParser(): Promise<HogQLParser> {
if (!parserPromise) {
@@ -9,6 +12,13 @@ function getParser(): Promise<HogQLParser> {
.catch((error) => {
// Reset so next call retries initialization
parserPromise = null
+ // The editor's main-thread fallback swallows this rejection, so without a report a
+ // broken parser only shows up as missing highlighting. A CSP that blocks the glue's
+ // eval fails every retry the same way, so report it once per page load.
+ if (!initFailureReported) {
+ initFailureReported = true
+ posthog.captureException(error, { feature: 'hogql-parser-init' })
+ }
throw error
})
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index cbb599887590..882bfd40ecdc 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -633,8 +633,8 @@ importers:
specifier: ^0.0.57
'@posthog/hogql-parser':
- specifier: 1.3.84
- version: 1.3.84
+ specifier: 1.3.88
+ version: 1.3.88
'@posthog/hogvm':
specifier: workspace:*
version: link:../common/hogvm/typescript
@@ -10691,8 +10691,8 @@ packages:
react: 18.3.1
react-dom: 18.3.1
- '@posthog/[email protected]':
- resolution: {integrity: sha512-dDBrHb5TcyM+APFAb+1VhdIVg1LHHF+f2SlogX7ZcWwCvBg2shPwUsdFQyNBr/vfxZzzR9Tvet57JOhgn0eTnA==}
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-zygPFNMJVxeiOdO1zW2mPK4A2fBS2qCaNvGK9B7Fan1mrW5C6cK2ESc22qf/+aiGS+8IMe6xvkmGwCjzoU2GQw==}
'@posthog/[email protected]':
resolution: {integrity: sha512-Y458v7A9ipKvHCo77rAc2/ELUDvfNjFpn9AwV8aVYUl5/wvLH9CwEfq1IxgQDj33OaML4IE2w5LQ0TbKbo63XA==}
@@ -30347,7 +30347,7 @@ snapshots:
transitivePeerDependencies:
- prop-types
- '@posthog/[email protected]': {}
+ '@posthog/[email protected]': {}
dependencies: