Skip to main content

Packaged Electron App Can't Read .env? It Lives in userData

· 5 min read

Configuration loads fine in development. After packaging the Electron app with electron-builder and installing it, every process.env.XXX is undefined and the modules that depend on them fail one after another.

Encountered this while building a data-collection tool for a client — recording the root cause and the fix.

TL;DR​

After packaging, .env is not in process.cwd() — it belongs in app.getPath('userData').

Three steps:

  1. On startup, the main process checks whether userData/.env exists; if not, it copies the bundled .env.example over (seeding)
  2. Store the full path in process.env.ENV_PATH
  3. The config module reads it with dotenv.config({ path: process.env.ENV_PATH || '.env' })

Symptoms​

In development (electron .) everything works. After installing the packaged build (launched from the dock or the start menu), the configuration is empty:

undefined
undefined
TypeError: Cannot read properties of undefined (reading 'xxx')

Extra confusing part: launching the same packaged binary from a terminal inside its own directory sometimes works — because process.cwd() happens to be the app directory in that case. Same build, different launch method, different behavior.

Root Cause: process.cwd() Is Unreliable After Packaging​

dotenv.config() without arguments reads process.cwd()/.env. But process.cwd() is "the directory the process was started from", not "the directory the app is installed in" — they only coincide during development:

Launch methodprocess.cwd()
Dev: electron . from the project rootproject root ✓ .env is here
Windows: double-click the exethe exe's directory
macOS: double-click the .app/ (filesystem root)

After packaging, there are exactly two places .env could live, and both fail:

  • asar archives are read-only: electron-builder packs app resources into app.asar, mounted read-only at runtime. Even if you bundle .env inside, users cannot edit it — every config change would require a rebuild
  • The install directory is not writable: Program Files and /Applications require elevated permissions to write; a normally-launched app cannot write there

Electron provides a standard directory for "runtime data belonging to this user": app.getPath('userData'). It resolves per platform (macOS ~/Library/Application Support/<app>, Windows %APPDATA%\<app>, Linux ~/.config/<app>), and it is guaranteed to exist, be writable, and survive reinstalls. That is where .env should live.

The Fix: Seed + ENV_PATH​

The change touches two files, about a dozen lines total.

Step 1: seed on startup (electron/main.js, before any window or the Express server starts):

const fs = require('fs');
const path = require('path');
const { app } = require('electron');

// ── .env path setup ──
const userDataPath = app.getPath('userData');
const envPath = path.join(userDataPath, '.env');
// rootDir = the packaged app root; use app.getAppPath() or your project's convention
const envExamplePath = path.join(rootDir, '.env.example');

if (!fs.existsSync(envPath) && fs.existsSync(envExamplePath)) {
fs.copyFileSync(envExamplePath, envPath);
console.log(`[electron] .env copied to ${envPath}`);
}
process.env.ENV_PATH = envPath;

Logic: if userData has no .env, copy the bundled .env.example (read-only inside asar is fine — it is a template), then expose the final path as process.env.ENV_PATH.

Step 2: the config module follows the pointer (src/config.js):

import dotenv from 'dotenv';
dotenv.config({ path: process.env.ENV_PATH || '.env' });

The || fallback keeps non-Electron contexts working (running the same code under plain Node), so development behavior is unchanged.

Step 3: config changes without reinstalling. To change an environment, edit the .env inside the userData directory and fully quit and relaunch the app — dotenv reads the file once, at process start; edits do not apply to a running process.

This "userData holds runtime state" pattern carries more than env files: login sessions, caches, and logs all belong there. The same tool stores its cookie-based login state this way — that investigation is covered in Puppeteer Blocked by Anti-Bot? From Chrome CDP to an Electron Alternative.

Watch out

process.env.ENV_PATH must be set before the config module is imported — dotenv.config() reads the file at call time, not later. Do the seeding at the very top of the main-process entry file, not inside an app.whenReady() callback: if any module earlier in the import chain calls require('dotenv').config(), the path will not be there yet.

FAQ​

How do I use app.getPath('userdata') for config files?​

Call it in the main process before any window or server starts: app.getPath('userData') returns the per-user data directory — ~/Library/Application Support/<app> on macOS, %APPDATA%\<app> on Windows, ~/.config/<app> on Linux. Build your .env path with path.join(userDataPath, '.env') and it will be writable in every packaged build.

Why can't my packaged Electron app read .env?​

Because dotenv defaults to process.cwd(), which is the launcher's directory after installation — on macOS a double-click even sets it to / — while your app resources sit inside a read-only asar archive. The fix: seed .env into userData on startup and hand that exact path to dotenv.config({ path }).

Should .env.example be bundled into the app?​

Yes. Ship it as the first-run template inside the asar (read-only is fine for a template). On startup, if userData/.env does not exist, copy the example over. Users can then edit the copy directly to change configuration without reinstalling anything.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

process.env Not Propagating? It's the ESM Import Cache

· 5 min read

A login script successfully refreshed the credential at runtime and wrote it into process.env. Business requests still return 401 — the constant they imported is still the stale value from process startup.

Encountered this while building a data-collection tool for a client — recording the root cause and the fix.

TL;DR​

An ESM module evaluates exactly once; what you import is a read-only snapshot from load time — no later write to process.env ever reaches an already-imported constant.

// ❌ cached at load time, stale forever after
import { AUTH_TOKEN } from './config.js'

// ✅ read the current value on every use
function getToken() {
return process.env.AUTH_TOKEN || ''
}

One-sentence rule: a value that updates at runtime must be read dynamically from process.env at the call site — never imported as a module-level constant.

Symptoms​

Three files, three jobs: config.js exports config constants, login.js logs in and refreshes the credential, runtime.js sends business requests with it:

// config.js — central export
export const AUTH_TOKEN = process.env.AUTH_TOKEN || ''
// login.js — refresh after login
process.env.AUTH_TOKEN = newToken // runtime update
console.log('[login] token refreshed')
// runtime.js — business requests
import { AUTH_TOKEN } from './config.js'

fetch(url, { headers: { Authorization: `Bearer ${AUTH_TOKEN}` } })
// → 401: AUTH_TOKEN is still the startup-time value (or an empty string)

Logs say the token was refreshed; the request header carries the old credential. Print AUTH_TOKEN and process.env.AUTH_TOKEN side by side and they differ — process.env is current, the imported constant is not.

Root Cause: An ESM Module Evaluates Only Once​

Per the ESM specification, a module's code executes exactly once — from its first import until the process exits; every subsequent import receives the same cached module instance.

So import { AUTH_TOKEN } from './config.js' in runtime.js actually means: load config.js (evaluating export const AUTH_TOKEN = process.env.AUTH_TOKEN || '', which freezes the then-current process.env value into the constant) and bind that value into runtime.js's scope.

Two properties of that binding create the trap:

  1. Read-only: the imported binding in the consumer cannot be reassigned (ESM import bindings do point at the export's live binding — but config.js exports a const, which will never hold a new value)
  2. Decoupled from process.env: process.env.AUTH_TOKEN = newToken executed later by login.js merely sets a property on the process.env object — the evaluation in config.js finished long ago, and no mechanism propagates that write back into the exported constant

In one sentence: process.env is a mutable runtime object, and export const X = process.env.Y is a one-time snapshot of one of its rows. The snapshot does not track the original.

The Fix: Read Dynamically at the Call Site​

Option 1 (smallest change): read the current value on use. Replace the imported constant with a process.env read:

// runtime.js
// import { AUTH_TOKEN } from './config.js' ← remove

fetch(url, {
headers: { Authorization: `Bearer ${process.env.AUTH_TOKEN || ''}` },
})

Option 2 (many call sites): centralize in a getter. When usage is scattered, consolidate into a function that evaluates on call:

// config.js — export a function, not a constant
export const getToken = () => process.env.AUTH_TOKEN || ''
// runtime.js — evaluated at call time, always current
import { getToken } from './config.js'

fetch(url, { headers: { Authorization: `Bearer ${getToken()}` } })

Option 3 (many config keys): export an object, read by property. Property access is dynamic by nature:

// config.js
const env = {
get token() { return process.env.AUTH_TOKEN || '' },
}
export default env

// runtime.js
import env from './config.js'
env.token // reads process.env on every access

All three share one principle: defer evaluation from module load to every use.

The same tool hits a second env-file trap after packaging (userData directory, not cwd) — a sibling problem about when and where config is read, covered in Packaged Electron App Can't Read .env? It Lives in userData.

Watch out

dotenv behaves identically: dotenv.config() reads the .env file exactly once, at call time. Editing the file afterwards, or calling plain config again, does not update already-injected values (override: true does overwrite, but only for code that reads process.env afterwards — anything imported as a constant stays dead). For "I changed .env but nothing happened": first check whether the process restarted, then whether the value was imported as a constant.

FAQ​

How should Node.js environment variables be configured and read?​

Configure via a .env file with dotenv or system-level exports; read them dynamically as process.env.XXX everywhere in code. The key takeaway: process.env is the only channel that runtime updates propagate through — a constant imported at module top level is fixed at first load and never follows later changes.

Why do other modules still see the old value after process.env is updated?​

Because the consuming module says import { TOKEN } from './config.js' — that line evaluates once at first module load, copying the value of that moment into a local constant. Nothing afterwards, inside config.js or on process.env, propagates back into it. Read process.env.TOKEN at the call site instead to always get the current value.

Do I need to restart the process after updating the .env file?​

Restarting is the reliable answer: dotenv.config() reads the file exactly once, at call time. For in-process hot reloads you must call dotenv.config({ override: true }) again AND have every consumer read process.env dynamically — a single import-as-constant anywhere breaks the propagation chain.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

FastAPI 422 or useParams Undefined? 4 Contract Mismatches

· 6 min read

Three classic scenes in frontend-backend integration: a POST returns 422; a route page's parameter stays undefined forever; an SSE request sits at 200 while the UI silently shows nothing. Different symptoms, one family of root causes — the two sides disagreeing about the interface contract.

Encountered this while building an AI Agent SaaS platform for a client, frontend and backend developed in parallel — we hit all four, and here is the locating method and the prevention discipline.

TL;DR​

Contract mismatches come in four shapes, producing three kinds of symptoms:

PitfallMismatchSymptom
Field namefrontend sends name, backend wants label422
Field typefrontend sends objects, backend expects List[str]422
Route paramroute defines :id, component reads agentIdundefined, feature silently dead
Event fieldbackend pushes {"content": ...}, frontend checks token200, UI shows nothing

Prevention is a single discipline: align on the schema before writing code — field names, types, route param names, event data shapes, all sourced from the backend schema (or an interface doc both sides confirmed).

Pitfall 1: Field Name Mismatch → 422​

The most basic one. The frontend TypeScript interface declares name + key for creating an API key; the backend Pydantic schema expects label + api_key:

// what the frontend sends
interface CreateApiKeyInput {
name: string
key: string
}

# what the backend declares
class ApiKeyCreate(BaseModel):
label: str
api_key: str
POST /api/api-keys → 422 Unprocessable Entity

Locate it from the 422 response body — don't guess. FastAPI's 422 carries a detail array spelling out every missing field and why:

[
{ "loc": ["body", "label"], "msg": "Field required", "type": "missing" },
{ "loc": ["body", "api_key"], "msg": "Field required", "type": "missing" }
]

Field required = the field is not in your request body at all = a field-name mismatch. Expand the response in the Network tab and it takes ten seconds.

Pitfall 2: Field Type Mismatch → 422​

Names can line up and types can still betray you. The backend declares mcp_tools as a list of strings; the frontend sends an array of objects (each with tool_id and token_id — the business genuinely needs OAuth token binding):

// what the frontend sends
{ mcp_tools: [{ tool_id: "t1", token_id: "k1" }] }

# what the backend expects
mcp_tools: List[str]
PATCH /api/agents/{id} → 422 Unprocessable Entity

This time detail says Input should be a valid string — a type mismatch. The fix is making the backend schema accept both shapes (the frontend's structure has a real business reason to exist; don't amputate it):

from typing import List, Union

class McpToolConfig(BaseModel):
tool_id: str
token_id: str | None = None

mcp_tools: List[Union[str, McpToolConfig]]

Union lets the schema accept both a plain string (tool reference only) and an object (with binding config); Pydantic tries them in order. The pattern generalizes to any "API evolves, frontend moves first" situation: the schema accommodates the real business shape, not the other way around.

Pitfall 3: useParams Name Mismatch → undefined​

Route definition and component each written from memory, one word apart:

// route definition
<Route path="/agents/:id/memory" element={<MemoryPage />} />

// component
const { agentId } = useParams<{ agentId: string }>()
// agentId is undefined forever — the route param is named id, not agentId

No error, status codes fine, feature silently dead — agentId is undefined, so downstream API calls carry undefined or never fire.

Two fixes:

// 1. match the route definition
const { id } = useParams<{ id: string }>()

// 2. or rename while destructuring
const { id: agentId } = useParams<{ id: string }>()

What makes this one sneaky is the generic: useParams<{ agentId: string }> — TypeScript does not verify that the keys in your generic actually exist in the route definition. The type annotation hands you false confidence.

Pitfall 4: Event Field Mismatch → 200 but Silent Failure​

In an SSE stream, the backend pushes {"content": "..."} while the frontend's event check looks for token:

// the frontend's event predicate
const isTokenEvent = (d: any) => 'token' in d // always false

// what the backend actually pushes
data: {"content": "hello"}

The Network tab shows 200 and the stream flowing; the UI shows nothing — the predicate never fires and events are silently dropped. This one is harder to catch than a 422: no error, just a feature that never happens.

Fix: align the predicate with the backend's actual data shape:

const isTokenEvent = (d: any) => 'content' in d && !('type' in d)

For SSE/WebSocket interfaces carrying many event kinds over one connection, prefer an explicit type field for dispatching; inferring event kinds from "which keys happen to exist" turns every contract change into silent breakage.

Prevention: One Discipline​

All four pitfalls share an origin: each side wrote its half of the interface from imagination. Prevention needs no tooling, one discipline —

Before writing any interface code, align on the schema: field names, types, route param names, event shapes — item by item. The backend Pydantic schema (or OpenAPI doc) is the single source of truth; the frontend TypeScript interfaces mirror it. Whoever changes the contract changes the schema first, both sides confirm, then code moves.

When symptoms appear, triage in order: 422 → expand the response detail and read loc; undefined → check the route's :param names; 200 but nothing happened → capture a real response and diff it field-by-field against the frontend predicate.

The server side of streaming interfaces has a companion pitfall (exceptions and leaked resources on client disconnect), covered in FastAPI SSE CancelledError on Client Disconnect? Catch and Re-raise in the Generator.

Watch out

Frontend TypeScript interfaces (interface XxxInput) are compile-time paper constraints — as any and third-party request wrappers can bypass them entirely. Types matching does not mean fields matching. The final arbiter of contract truth is always a comparison against the backend schema, not the absence of red squiggles.

FAQ​

Why does FastAPI return 422 Unprocessable Entity?​

In 9 out of 10 cases the request body does not match the Pydantic schema: a field name the backend does not expect (sending name when the schema wants label) or a field type mismatch (an array of objects where List[str] is declared). The 422 response body lists every offending field in its detail array — read it before guessing.

How do I debug which field caused a FastAPI 422?​

Open the response body in the browser Network tab or curl: FastAPI returns a detail array where each entry has loc (the field path), msg (Field required / Input should be a valid string), and type. loc pointing at a field you did send under a different name is the classic field-name mismatch.

Why does useParams return undefined in React Router?​

The keys of useParams come from the route definition: a route of /agents/:id exposes only id. Destructuring a name that does not appear in any :param — like agentId — yields undefined silently, no error thrown. Rename during destructuring instead: const { id: agentId } = useParams().

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Hysteria Authenticates but Times Out? UDP Path QoS Diagnosis

· 6 min read

Clash shows connected, yet no page loads. The server log shows client connected, followed by timeout: no recent network activity inside the flow — each flow dying within 52 seconds to a few minutes. Every server health check passes.

Encountered this while maintaining a self-hosted overseas VPS — a cross-border path failure with a perfectly healthy host; recording the full layered diagnosis.

TL;DR​

Authentication passes, flows time out, host health checks are all green — the problem is not the host but the path: the international link applies QoS to long-lived UDP 5-tuples, leaving flows half-dead.

  • Immediate recovery: reconnect Clash — the client re-handshakes with a new source port, sidestepping the flagged 5-tuple; works in roughly 9 out of 10 cases
  • Confirm the diagnosis: journalctl -u hysteria-server should show a repeating client connected → timeout: no recent network activity cycle
  • Long-term mitigation (concept only): server-side port rotation, or lowering bandwidth declarations so the traffic profile stops triggering suppression — evaluate if recurrence gets frequent; not covered here

Symptoms​

Client and server symptoms combine into a complete picture:

Client: Clash reports connected (UDP authentication OK) but no site loads and speed tests show zero throughput.

Server (journalctl -u hysteria-server):

client connected               ← auth OK
... (52s ~ a few minutes later)
timeout: no recent network activity ← flow-level death
client disconnected
client connected ← auto-reconnect, cycle repeats

Severity data: during the worst window, reconnect storms hit 94 / 50 / 20 per day; one representative case was triggered by a 9-hour-old session going half-dead.

The Diagnosis Chain: Rule Out the Host First, Then Pin the Path​

The value of this chain is the order of elimination — blaming the carrier before clearing the host leaves the conclusion standing on nothing.

Layer 1: authentication and port. client connected in the log means UDP packets reach the server, the port is open, and auth config is correct. The first half of the path (client → server) works.

Layer 2: flow-level timeouts. timeout: no recent network activity is the server's flow liveness probe: a flow with no valid packets is declared dead. Auth passes but flows starve immediately — the return leg (server → client) is likely being dropped.

Layer 3: host health checks (clearing the host). All pass; the host is clean:

CheckResult
Outbound TCP (large-file curl)Normal, full bandwidth
NIC drop / error counters0
conntrack tableNo abnormal buildup
TLS certificate expiryNormal
Memory / diskNormal

Layer 4: pinning the cause. Three layers of evidence point to one conclusion: the host sends and receives fine, the auth direction works, and only sustained-traffic flows lose their return packets — the signature of carrier-side QoS on long-lived, high-throughput UDP 5-tuples at the international gateway: a single UDP flow (same 5-tuple) running hard gets flagged by traffic classification, after which its packets are de-prioritized or dropped, leaving the flow half-dead — not disconnected, but unable to move. Reconnecting gives the client a new source port — a fresh, unflagged 5-tuple — and service returns instantly.

The affected client side was a Guangdong Mobile egress (163.179.x). Different carriers and regions will differ in thresholds and presentation, but the pattern "long-lived UDP 5-tuple → half-dead → new port recovers" generalizes.

Handling: Reconnect to Recover + Watch Criteria​

Day-to-day (works ~90%): reconnect or restart Clash. The essence is a new source port dodging the flagged 5-tuple; recovery is instant.

When that fails: go back to the server log to re-confirm the pattern — if journalctl -u hysteria-server still cycles connected → timeout and port changes don't help, suspect something further upstream (datacenter egress, carrier policy changes) and only then dig into the server side again.

Long-term mitigation (optional, on recurrence): two directions — server-side listening port rotation (no single 5-tuple lives long enough to be flagged), or lowering bandwidth-related declarations so the traffic profile looks less "heavy". Each carries trade-offs; evaluate only if recurrence becomes frequent.

Related: if this happens inside WSL2, first clear the local proxy chain of its own traps (firewall blocking the proxy port) — see WSL2 Proxy Keeps Dropping? Windows Firewall Is Blocking the Port. Clear local factors before pinning anything on the path.

Watch out

"Server health checks all pass" does not mean "the network is fine" — health checks cover the host and its adjacent link, while QoS happens in the middle of a cross-border path, invisible to any host-side tool. When the two conclusions conflict (host fully green, user offline), suspect the path first. That is the core diagnostic lesson of this case.

FAQ​

Hysteria authenticates but there is no traffic — how do I triage by layer?​

Cut the path into three layers. First, the server log: a client connected line means authentication and the port are fine. Second, in-flow errors: timeout: no recent network activity means the flow itself is dead. Third, full server health checks (outbound TCP, NIC drops, conntrack, certs, memory, disk) — all green rules out the host and points at the path, most commonly carrier QoS on cross-border UDP.

What does 'timeout: no recent network activity' mean in Hysteria?​

It is the server's per-flow liveness probe: a flow with no valid packets for a while is declared dead and closed. When authentication succeeds but flows starve right after, the typical cause is an intermediate device (carrier QoS) having flagged that UDP 5-tuple and silently dropping its packets — the client still thinks it is connected, but the tunnel is half-dead.

How do I check if my UDP traffic is being throttled?​

Correlate three signals: server-side health is clean (ruling out the host), the flow dies after minutes of sustained transfer rather than instantly (a traffic-shaping signature, not an outage), and reconnecting — which changes the source port — immediately restores service. Together they indicate per-flow rate shaping rather than a connectivity failure.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

json.dumps fails on NaN? The error escapes your try/except

· 5 min read

A pipeline task dies halfway: the log trace stops mid-step, no error line anywhere — the process seems to vanish into thin air.

Encountered this while building AI Ops — LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operational strategy. Analysis tasks start from pandas data and end as JSON in storage; NaN is the most common landmine on that road.

Symptom: a trace that just stops, no error record​

The task is marked failed, but the business log has no exception anywhere — the trace reaches a step and ends. The exception did happen; it just exploded outside your try's coverage: the throw came from JSON serialization inside ti.xcom_push, a line sitting outside the business try block (and even wrapped, framework-internal serialization points would still be deeper than your catch radius).

The actual error:

ValueError: Out of range float values are not JSON compliant: nan

If you searched for "json.dumps NaN ValueError", "Out of range float values are not JSON compliant" or "task log stops without error" — same family.

Two rulebooks disagree here. Verified behavior matrix:

import json, math

# NaN sails through the Python world
isinstance(float('nan'), float) # True — a legal float
float('nan') == float('nan') # False — even equality can't see it

# The JSON world: permissive by default, strict mode throws
json.dumps(float('nan')) # 'NaN' (an invalid JSON literal!)
json.dumps(float('nan'), allow_nan=False) # ValueError: Out of range float values...
json.dumps(math.inf, allow_nan=False) # ValueError (±Inf equally guilty)

Three points:

  • RFC 8259's number grammar has no NaN/Infinity. Python's json defaults to allow_nan=True and emits a NaN literal — a permissive extension producing strings strict parsers downstream will reject. The trap has two layers: blow up now (strict mode), or plant it for later (permissive mode).
  • NaN defeats ordinary guard clauses. It's not None, not 0, and == against itself is False — if not value checks all pass, and the data walks all the way to the serializer before exploding.
  • The blast site is framework code. You hand a dict to xcom_push, a logging SDK, an HTTP client — serialization happens inside those frameworks, deeper than your try/catch. That's exactly why the trace stops with no error line: the exception never touched your logging hooks, it simply flattened the task.

The fix: sanitize at the boundary, backstop with a task-level hook​

Two lines of defense. First, the data — recursively clean before any JSON boundary, mapping NaN and ±Inf to None:

import math

def json_safe(value):
"""Recursively turn NaN/±Inf into None; pass everything else through."""
if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
return None
if isinstance(value, dict):
return {k: json_safe(v) for k, v in value.items()}
if isinstance(value, list):
return [json_safe(v) for v in value]
return value

import json
payload = json_safe(result_dict)
json.dumps(payload, allow_nan=False) # can no longer throw

After sanitizing, keep allow_nan=False — it changes from landmine to tripwire: anything that slipped through now raises inside your own code instead of leaking downstream.

Second, the framework — attach a failure hook to the task (an Airflow task failure callback, or a decorator wrapping the whole task callable) so catch-external exceptions also land in the log system. That turns "trace stops, no error" into "trace ends with an error". When triaging existing failures, go straight to the Airflow task logs for the traceback (logs/dag_id=.../task_id=.../attempt=N.log inside the container) rather than the business logs.

Boundary cases​

  • pandas' own to_json maps NaN to null at output time — if the whole chain uses it, no sanitizing needed; but the moment data becomes a dict and switches to json.dumps, you own the cleaning. The trap springs exactly when you swap serializers.
  • NaN == NaN is False — dedup, assertions and test comparisons all get fooled; only math.isnan detects it.
  • numpy arrays blow up json.dumps too (ndarray isn't JSON-serializable) — .tolist() first; the NaNs survive tolist, so cleaning is still required.
  • Semantically, NaN→null is lossy ("measurement failed" becomes "no value") — if downstream depends on that distinction, add an explicit marker field instead of hard-converting.

Watch out

  • Only math.isnan detects NaN — anything based on == or if not x is unreliable.
  • Sanitize once, at the serialization boundary — per-callsite cleaning guarantees one call site eventually gets skipped, and that one reproduces the bug.
  • Use strict mode as a tripwire: after sanitizing, an allow_nan=False error means leaked data — a good signal.
  • Framework failure hooks are not optional: they catch the exceptions you can't think of today but will certainly meet tomorrow.

FAQ​

Why does json.dumps raise ValueError on NaN?​

The JSON spec has no NaN/Infinity; with allow_nan=False (strict mode) they raise ValueError: Out of range float values are not JSON compliant. The default allow_nan=True emits an invalid NaN literal, handing the problem downstream.

How do I convert NaN to null before JSON serialization in pandas?​

Walk the data structure recursively and replace float NaN and ±Inf with None before dumps; in pandas itself use df.where(df.notna(), None) or to_json (NaN→null built in). Sanitize at the serialization boundary — json won't do it for you.

Why doesn't JSON support NaN and Infinity?​

RFC 8259's number grammar covers finite numbers only. Python's json module with default settings writes a NaN literal — a permissive extension producing invalid JSON that strict downstream parsers reject.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

PostgreSQL fe_sendauth in Docker? exec trust vs TCP auth

· 5 min read

On the host that runs the database container, docker exec-ing in and running psql connects with no password at all. Run the same username from another container over TCP and it dies instantly with fe_sendauth: no password supplied.

Encountered this while building AI Ops — LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operational strategy. Ops scripts inside the orchestration container reach the analytics database cross-container, and a connection string copied from the exec habit tripped on the very first hop.

Symptom: exec connects, TCP answers fe_sendauth: no password supplied​

Same host, same database, same user — two paths, two fates. Verified matrix (Airflow container → PostgreSQL container):

Connection methodResult
docker exec cclhub-db psql -U postgres (in-container socket)Connects, no password
Cross-container TCP, DSN without passwordfe_sendauth: no password supplied
Cross-container TCP, DSN with passwordConnects

If you searched for "fe_sendauth no password supplied", "psql no password error" or "docker postgres connection fails without password" — this is it.

Root cause: socket trust and TCP password auth are two different pg_hba paths​

PostgreSQL authentication is matched line by line in pg_hba.conf by connection type, and the official image ships completely different rules for the two paths:

  • docker exec uses the Unix domain socket, covered by a local all all trust-style rule — local socket is trusted, no password asked;
  • Cross-container traffic is TCP (a host-type rule), and the official image defaults to scram-sha-256 / md5 password auth.

So the no-password habit built on exec turns into "no password at all" the moment you switch to TCP — the literal meaning of fe_sendauth: no password supplied is "the server wants a password and the client supplied none".

Worth separating two often-confused errors: no password supplied means no password was provided; password authentication failed means one was, and it was wrong. The former points at the connection string; the latter at the credential itself — different fixes.

The fix: put the password in the DSN, don't copy the exec habit​

Cross-container scripts use a password-carrying connection string, always:

postgresql://postgres:<password>@<db host>:5432/<db>

The recommended source for the password is the DB container's own environment — the official image's POSTGRES_PASSWORD exists precisely for initialization — avoiding a second hardcode:

PW=$(docker exec cclhub-db printenv POSTGRES_PASSWORD)
psql "postgresql://postgres:${PW}@localhost:5432/postgres" -c "SELECT 1"

Application-side (Python here) it's the same shape, with the DSN in environment management:

import os
import psycopg

DSN = os.environ["APP_DB_DSN"] # postgresql://user:pass@host:5432/db
with psycopg.connect(DSN) as conn:
conn.execute("SELECT 1")

Note that passwords containing reserved characters like @ : / # must be percent-encoded in the URL — another place special characters bite; avoiding them in generated database passwords removes an entire class of trouble.

Boundary cases​

  • The error's shape varies by client: an interactive libpq terminal (psql without -t) first prompts Password for user postgres: and then fails with fe_sendauth; connection pools and GUI tools (pgAdmin) surface it as an auth failure in the UI — different texts, same root cause.
  • .pgpass files and the PGPASSWORD environment variable are two alternative ways to supply the password; in containerized setups, DSN/env injection is more common than mounting a .pgpass file.
  • You can set pg_hba to trust for TCP too — technically possible, and wrong for production: anything that can reach the port gets credential-free access.
  • Auth method version drift: newer official images default to scram-sha-256; very old client libraries may not support it — that's a different error class (unsupported authentication method), not "no password supplied".

Watch out

  • Diagnose the connection path first: socket or TCP, and which pg_hba rule it matches, decides whether a password is even requested — don't generalize exec behavior to everything.
  • Keep the error semantics straight: no password supplied (missing) and authentication failed (wrong) lead to completely different fixes.
  • Avoid or percent-encode special characters in DSN passwords — URL reserved characters silently change how the string parses.

FAQ​

What does fe_sendauth: no password supplied mean?​

The server's pg_hba.conf requires password auth, but the client's connection string carries no password. It is not "wrong password" (that's authentication failed) — it's "no password at all"; check whether the DSN is missing its password part.

Why does docker exec psql connect without a password?​

Inside the container psql uses the Unix domain socket, which pg_hba covers with a trust rule; cross-container traffic is TCP and hits a host rule that demands a password. Same command, different path, completely different auth requirements.

How should containerized scripts connect to PostgreSQL?​

Use a DSN with an explicit password — postgresql://user:password@host:5432/db — read from the DB container's POSTGRES_PASSWORD environment variable. Don't hardcode it and don't expect socket trust to apply over TCP.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

jsonb IS NOT NULL passes for JSON null? Use jsonb_typeof

· 5 min read

Filtering a jsonb field's "empty" values with IS NOT NULL lets rows whose value is JSON null sail right through — the data is empty, yet the predicate says otherwise.

Encountered this while building AI Ops — LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operational strategy. Analysis decision snapshots are stored as jsonb; rows where no rule fired get JSON null written in, which silently corrupted the "has rule output" predicate.

Symptom: IS NOT NULL doesn't catch the "empty" value​

field->'key' IS NOT NULL returns true for rows whose value is JSON null — the filter does nothing, and rows that should be excluded leak into the result set. If you searched for "jsonb is not null not working", "jsonb null filter" or "postgres json null check", this is the same issue.

Root cause: JSON null is a valid jsonb value, not SQL NULL​

PostgreSQL has two kinds of "empty" here: SQL NULL means no value exists; JSON null is a legitimate jsonb value. The -> operator retrieves what the key holds — for JSON null, that's a perfectly valid value, and IS NOT NULL answers "did I get something back?", not "is it meaningful?". Verified behavior matrix (tested on a PostgreSQL 16 container):

ExpressionResult
('{"a":null}'::jsonb -> 'a') IS NOT NULLtrue
('{"a":1}'::jsonb -> 'b') IS NULLtrue (missing key yields SQL NULL)
jsonb_typeof('{"a":null}'::jsonb -> 'a')'null' (a string)
jsonb_typeof('{"a":1}'::jsonb -> 'b')SQL NULL
'{"a":null}'::jsonb ? 'a'true
('{"a":null}'::jsonb ->> 'a') IS NULLtrue

Two combinations bite most often:

  • IS NOT NULL cannot tell JSON null from a real value — the first row, exactly where the misjudgment comes from.
  • Extracting text with ->> and testing IS NULL fails the same way — JSON null and a missing key both become SQL NULL (last row). Reaching for ->> to dodge the trap lands you right back in it.

The fix: ? for key existence, jsonb_typeof for value type​

Two different intents need two different tools:

-- "key exists": value irrelevant
SELECT '{"a":null}'::jsonb ? 'a'; -- true

-- "has a real value": assert the JSON type; 'null', missing keys all excluded
SELECT jsonb_typeof(config->'rule_output') = 'array'; -- arrays only
SELECT jsonb_typeof(config->'rule_output') = 'object'; -- objects only

-- find rows that hold a JSON null (data triage)
SELECT * FROM t WHERE jsonb_typeof(config->'rule_output') = 'null';

Our concrete case: the rule engine writes JSON null into decision snapshots when no rule fired, and a downstream count used ->'rule_output' IS NOT NULL as "has rule output" — the metric was simply wrong. The fix tightened the assertion to jsonb_typeof(...) = 'array', excluding JSON null, missing keys and every other type in one stroke.

Boundary cases: JSON null is not always wrong​

To be clear: JSON null is a legitimate design — "key exists but empty" and "key absent" are different business semantics; an API returning "extra": null is not the same as omitting extra. The data isn't wrong; the predicate is. Three intents, three spellings:

IntentExpression
Key exists (value irrelevant)jsonb ? 'key'
Real value of a given typejsonb_typeof(x) = 'array' / 'object' / ...
Value is JSON nulljsonb_typeof(x) = 'null'

A related trap lives on the update side: jsonb_set(config, '{rule_output}', 'null') writes a JSON null, while jsonb_set(config, '{rule_output}', NULL) deletes the key entirely — JSON vs SQL NULL as the argument flips the meaning. For other "query results don't match expectations" hunts, cross-query granularity mismatches causing dangling references are another frequent root cause worth comparing.

Watch out

  • Triage existing data before changing predicates: run jsonb_typeof(...) = 'null' across the table first to size up where JSON null rows come from, then decide whether to fix the query or the writer.
  • Standardize the spelling in your team: even if a field currently always holds a valid array and IS NOT NULL happens to work, use jsonb_typeof assertions uniformly — the moment the field's semantics shift, the loose spelling becomes a silent bug.
  • The same applies at the ORM/driver layer: when application code checks "JSON field is not empty", know what your driver maps JSON null to (most languages map it to a language-level null/None) — don't conflate the two kinds of empty.

FAQ​

What is the difference between JSON null and SQL NULL in Postgres jsonb?​

JSON null is a valid jsonb value; SQL NULL means the value does not exist. Tested: ('{"a":null}'::jsonb -> 'a') IS NOT NULL returns true; jsonb_typeof returns the string 'null' for the former and SQL NULL for a missing key.

Why doesn't IS NOT NULL filter out empty jsonb values?​

->'key' returns a valid jsonb value for JSON null, so IS NOT NULL is trivially true. Assert the type instead — jsonb_typeof(field->'key') = 'array' — or check key existence with the ? operator.

How do I tell a JSON null value from a missing key in jsonb?​

Use the ? operator for key existence — it returns true even when the value is JSON null. jsonb_typeof returns the string 'null' for a JSON null value and SQL NULL for a missing key, which tells the two apart.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Vite Env Variable Undefined? It Needs the VITE_ Prefix

· 5 min read

You set API_URL=http://localhost:3005 in a Vite project's .env, but import.meta.env.API_URL logs undefined in the browser, and every API request goes to the wrong address.

Encountered this while building an AI Agent SaaS platform for a client — recording the root cause and the fix.

TL;DR​

Vite exposes only VITE_-prefixed environment variables to client code — a security design that keeps server secrets out of the browser bundle.

# ❌ never exposed to the frontend
API_URL=http://localhost:3005

# ✅ exposed to the frontend
VITE_API_URL=http://localhost:3005

Access it as import.meta.env.VITE_API_URL. TypeScript projects should add one more step: an env.d.ts declaration for proper autocomplete.

Symptoms​

Two typical presentations:

Symptom 1: the variable is undefined

// .env: API_URL=http://localhost:3005
console.log(import.meta.env.API_URL) // undefined
console.log(import.meta.env) // BASE_URL, MODE, PROD... are all there — just not yours

The .env file clearly loaded (MODE, PROD and the other built-ins are present), so this is not a loading failure — the exposure rule filtered your variable out.

Symptom 2: prefix added, access name mistyped

// .env: VITE_API_URL=...
const url = import.meta.env.VITE_APIURL // undefined — case must match exactly

A separate note: "environment variable reads undefined" on the Node.js server side has a different common cause (dotenv load order) — see Node.js env loaded undefined: dotenv import order. Don't mix the two investigations.

Root Cause: The Prefix Rule Is a Security Boundary​

Vite's design problem: .env files typically hold two kinds of values — public config the frontend needs (an API base URL) and values that must never reach a browser (database URLs, third-party API keys). Exposing everything means one oversight puts a secret into a publicly served static bundle.

So Vite draws a hard line: only VITE_-prefixed variables appear in import.meta.env. Everything else is visible only in vite.config.ts (the Node side) via loadEnv.

The exposure mechanism matters too: static replacement at build time. Vite inlines import.meta.env.VITE_API_URL as a string literal during the build; at runtime there is no "read the environment" step. Two consequences:

  1. The value appears in plain text inside the shipped JS — a VITE_ variable is public by nature
  2. Changing environment at runtime (container env, system variables) never affects an already-built bundle — switching environments requires a rebuild, or a runtime-injected config (e.g. window.__CONFIG__)

The Fix: Prefix + Type Declaration​

Step 1: add the VITE_ prefix in .env. Keep the name semantic; the prefix is only an exposure marker:

# .env
VITE_API_URL=http://localhost:3005

Step 2: read it through one config module, not scattered import.meta.env calls in components:

// src/config.ts
export const API_URL = import.meta.env.VITE_API_URL

Step 3 (TypeScript projects): declare the types in src/env.d.ts for full autocomplete:

/// <reference types="vite/client" />

interface ImportMetaEnv {
readonly VITE_API_URL: string
}

interface ImportMeta {
readonly env: ImportMetaEnv
}

Separate dev and production values with mode files — Vite picks the right one automatically:

.env.development    # dev server
.env.production # npm run build
.env # loaded in both — shared config goes here

After editing any .env file, restart the dev server — env files load once at startup, and hot reload does not refresh them. This is the second most common "I changed it but nothing happened" cause.

Watch out

A VITE_ variable is public information: its value is inlined into the client bundle in plain text. API base URLs and feature flags are fine; database connection strings and third-party secrets are not — those stay in server-side environment variables. When the frontend needs protected config, serve it from an API endpoint instead of .env.

FAQ​

Where do Vite environment variables live?​

In the .env family at the project root: .env loads in both modes, .env.development only for the dev server, .env.production only during builds. After editing any of them you must restart the dev server — Vite loads env files once at startup, and hot reload does not refresh them.

Can I put secrets behind the VITE_ prefix?​

No. VITE_ variables are statically inlined into the client bundle at build time — anyone can read them in the page source. The prefix exists to separate publishable config (API base URLs, feature flags) from server-only secrets. Secrets belong in server-side environment variables only.

What is the difference between process.env and import.meta.env in Vite?​

import.meta.env is the browser-side API — Vite statically replaces VITE_-prefixed keys into it. process.env is a Node.js API, available only inside vite.config.ts and SSR contexts. Writing process.env.XXX in frontend code is always undefined after build.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

Vite Proxy Works in Dev but 404 in Production? Add Nginx

· 5 min read

A Vite project works perfectly in local development. After npm run build and deploying to the server, pages load fine, but every /api request returns 404 — or something sneakier: the response is index.html, and the frontend crashes parsing HTML as JSON.

Encountered this while building an AI Agent SaaS platform for a client with a separated frontend/backend deployment — recording the root cause and the fix.

TL;DR​

server.proxy in vite.config.ts belongs to the dev server only. npm run build produces plain static files with no proxy layer at all; in production, Nginx must take over /api:

location /api {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}

Placed outside the reach of the SPA fallback (try_files ... /index.html), validated with nginx -t, applied with nginx -s reload.

Symptoms​

Two presentations, one root cause:

Presentation 1: plain 404

GET https://example.com/api/agents  → 404 Not Found

Presentation 2: index.html comes back (sneakier)

GET /api/agents  → 200 OK, but the body is <!DOCTYPE html>...
Frontend fails with: Unexpected token '<' in JSON

The second one is the SPA fallback catching the request: Nginx finds no static file at /api/agents, and try_files $uri /index.html bounces it to the frontend entry page. The status code is even a green 200 — it only blows up when the frontend parses the body, which makes it look like "the request succeeded".

Root Cause: proxy Is a Dev-Server Runtime Feature​

This block in vite.config.ts:

// vite.config.ts
export default defineConfig({
server: {
proxy: {
'/api': 'http://127.0.0.1:3000',
},
},
})

works in exactly one context: the dev server started by npm run dev. That dev server is a Node process, and server.proxy is forwarding middleware inside it — the browser requests localhost:5173/api/agents, the dev server passes it to 127.0.0.1:3000, and brings the response back.

After npm run build, the output is a pile of static files in dist/, and the browser fetches them straight from Nginx — there is no Vite process anywhere in that chain, and the server.proxy config stays behind in vite.config.ts; it never ships with the build.

So in production the request path is: browser → Nginx → ?. Nginx matches locations; with no /api rule, no static file exists at /api/agents, so it either 404s or falls through to index.html via the SPA fallback — the two presentations, explained.

The Fix: Let Nginx Own the Production Proxy​

Step 1: add a proxying location to the server block.

server {
listen 80;
server_name example.com;
root /var/www/app/dist;

# API proxy: prefix match, wins over the SPA fallback
location /api {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}

# SPA fallback: everything else goes to the frontend entry
location / {
try_files $uri $uri/ /index.html;
}
}

Two points:

  • proxy_pass points at the real backend address and port (swap the example's 3000 for yours); /api-prefixed requests are forwarded as-is, so backend routes must carry the /api prefix
  • Nginx prefix locations match by longest prefix, so /api naturally beats / — no ordering tricks needed; just make sure your longest API common prefix is covered

Step 2: verify, then serve traffic.

nginx -t          # syntax check
nginx -s reload # graceful reload

# Smoke test: should return backend data, not HTML
curl -i https://example.com/api/health

JSON with Content-Type: application/json means the proxy is live; text/html means the fallback is still catching requests.

A side benefit: once both apps share a domain through the reverse proxy, the CORS problem you dodged in dev with Vite proxy disappears in production too — no CORS headers to configure.

This post and Frontend Deploy Looks Outdated? Nginx Cache and Build Output Checks are companion reads: that one covers "the deployed code is stale", this one covers "the API has no proxy layer in production". Check both and deployment-related 404s are pretty much exhausted.

Watch out

The location path must match the backend route prefix exactly. If backend routes live at /api/agents but Nginx proxies /apis, or proxy_pass ends with a stray / (which triggers path rewriting — /api/agents arrives at the backend as /agents), you get a fresh new 404. After any change, curl -i one real endpoint and check the response headers before sending traffic.

FAQ​

Does Vite proxy work in production?​

No. server.proxy is a runtime middleware of the dev server — it exists when you run npm run dev. A production build produces plain static files served by Nginx (or any web server), with no Vite process and no proxy layer. The production equivalent is an Nginx location block with proxy_pass, which typically adds 2 proxy_set_header lines and a reload.

Why is the Vite proxy not working after build?​

Because the proxy config never ships with the build. After deploying, /api requests hit Nginx directly; with no /api location rule they either 404 or get caught by the SPA fallback (try_files ... /index.html), returning HTML with a 200 status that breaks JSON parsing on the frontend. Add an /api proxy location and reload Nginx.

How do I route API requests through Nginx for a Vite app?​

Inside the server block add: location /api { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } — then nginx -t and nginx -s reload. Verify with curl -i https://example.com/api/health: a JSON content type means the proxy is live, text/html means the SPA fallback is still catching it.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me

LLM Tool Calls Fail Silently? Enum Drift and Prompt Bloat

· 12 min read

While sending a batch backfill request to our bookkeeping assistant in production, the model returned a tool call with valid JSON — and nothing happened. The user just saw a generic "didn't catch that" line.

I hit this while building Life, an AI bookkeeping assistant — you talk naturally, and the AI extracts amounts, categories, and accounts. The debugging session turned up two structural problems that both fail silently, so I'm writing them up as two scenarios.

TL;DR​

  • Scenario 1: the enum in our tool definition and the enum in our server-side validator were two hand-written copies that had drifted. The model emitted a value that was legal per the definition and the validator rejected it; because the count check lived at the array level, one invalid candidate voided the whole card. Fix: single-source the enum, then validate per item.
  • Scenario 2: to reduce dead-end candidates, we taught the model "every candidate must carry complete arguments." The teaching made outputs longer, and the small model's bad-JSON rate rose from ~6% to 12-28%. Fix: revert the teaching, relax the validation, and let a downstream deterministic guard catch missing arguments.
  • Two rules: paired enums must reference one shared constant; teach routing, not argument extraction.

Two sides: the model sees the definition, your code runs the validator​

In function calling, the tool definition and the parameter validation are two separate pieces of code, and the model only ever sees the first one — every silent failure in this post lives in the mismatch between them.

The model never executes anything. Each call, your server sends tool definitions (JSON Schema format) to the model; the model returns a tool name plus an arguments JSON; your code validates it before executing. This means any "set of legal values" exists in at least two places: in the definition sent to the model, and in your validation code.

"Silent failure" here means: no API error, a tool call comes back, the arguments look like valid JSON — but the feature doesn't run. In other words, the tool call never takes effect, or the feature fails intermittently. The user sees a generic fallback message; the details sit in server logs. Without log instrumentation, this kind of failure can live in production for a long time.

Before/after flow of two silent LLM tool-calling failures

When the enum in the tool definition and the server-side validation enum aren't the same constant, a "legal" value emitted from the definition side is guaranteed to be rejected by the validation side — and an array-level count check amplifies one invalid item into a fully voided card.

The symptom: a failure chain visible only in logs​

Our routing model has a family of disambiguation tools: when the user's input is ambiguous, the model doesn't execute directly — it calls a meta-tool that outputs 2-4 candidate intents, which we render as tappable cards. Each candidate carries a tool field whose value must be a real action tool name.

One day, production logs showed a routing failure: the user said "please backfill the missing dates in batch", the model did call the disambiguation tool, and arguments was valid JSON — but the whole candidate card was judged invalid, and the user got the fallback line. The confusing part was the contrast: by round six of rephrasing, the same request routed fine. That ruled out "the model is hallucinating" and pointed at a deterministic failure triggered by one specific value.

Root cause: two hand-written enums, plus a count check at the array level​

Digging in found two compounding causes.

Cause one: enum drift. In the tool definition, the candidates' tool enum used the full set of tool names. The server-side validation enum, however, was the full set minus one batch-split tool reserved for an image-only pipeline — that tool must never be nominated by the text path, because nominating it would bypass the image pipeline's dedicated contract. The two sets were written in two places, maintained separately:

// Definition side: JSON Schema sent to the model (before the fix)
tool: { type: 'string', enum: [...ALL_TOOLS] } // full set

// Validation side: server-side zod (before the fix, a separate hand-written copy)
const ALLOWED = ALL_TOOLS.filter((t) => t !== 'batch_split') // subset
tool: z.enum(ALLOWED)

The spec the model saw said batch_split was legal, so it dutifully used it; the validator disagreed. The model followed your schema and got rejected by your own validation — this isn't a model error, it's the two sides telling different stories.

Cause two: array-level validation voids the whole card. The candidate count constraint sat on the array:

options: z.array(OptionSchema).min(2).max(4)

Zod validates every element of the array, and any single failure fails the entire array. So one invalid candidate (that batch_split) dragged down the whole card — three perfectly valid candidates buried with it. The upper layer only had a fallback line; the truth stayed in the logs.

The fix: single-source the enum, then tolerate per item​

Step one, make both sides reference the same constant (a one-line fix):

const DISAMBIGUABLE_TOOLS = ALL_TOOLS.filter((t) => t !== 'batch_split')

// Definition side
tool: { type: 'string', enum: [...DISAMBIGUABLE_TOOLS] }
// Validation side
tool: z.enum(DISAMBIGUABLE_TOOLS)

Step two, turn "one bad element voids the array" into "a bad element only drops itself": run a per-item check inside a preprocess, drop invalid items with a log line, and apply the count floor after filtering:

import { z } from 'zod'

const OptionSchema = z.object({
tool: z.enum(DISAMBIGUABLE_TOOLS),
label: z.string().min(1).max(30),
args: z.record(z.unknown()).optional(),
})

// Per-item tolerance: invalid candidates are dropped, not propagated; every drop is logged
function filterOptions(raw: unknown): unknown {
if (!Array.isArray(raw)) return raw
return raw.filter((item) => OptionSchema.safeParse(item).success)
}

const ArgsSchema = z.object({
// min becomes a "post-filter" floor: only an emptied array rejects the whole card
options: z.preprocess(filterOptions, z.array(OptionSchema).min(1).max(4)),
})

One boundary to be explicit about: per-item tolerance silently discards invalid candidates, so every drop must emit a warn log — otherwise bad candidates vanish without a trace and your observability goes blind. Also note min now means "post-filter floor": the card is only rejected when every candidate was dropped, and at that point there's genuinely nothing to render, so falling back is correct.

This "one extra field/value sinks the whole output" problem is a sibling of Zod .strict() silently failing on LLM output: strict validation is right for fully-controlled client input; for model output, tolerance has to go down to the item level.

Scenario 2: after adding "arguments required" teaching, bad-JSON rate went from 6% to 12-28%​

For payload-length-sensitive meta-tools, teaching that forces complete arguments makes outputs longer and directly inflates the small model's bad-JSON rate — an A/B test on the same cases measured ~6% rising to 12-28%.

A reasonable-looking teaching​

After scenario one was fixed, we found a follow-up annoyance: some candidates reached the card, and only after tapping did the user discover required arguments were missing, costing another round trip. So we naturally added a teaching — "every candidate's args must carry all required arguments for that tool; never nominate a candidate you can't pre-fill completely" — injected in three places at once: a rule in the system prompt, the argument description in the tool definition, and the note on a few-shot example.

// Few-shot example (the teaching we later reverted)
{
input: 'delete it',
tool: 'suggest_options',
note: 'ambiguous reference → disambiguate; every candidate\'s args must carry all required
arguments for that tool (e.g. delete_record needs domain); never nominate a candidate
you cannot pre-fill completely',
}

The symptom: the eval gate went red three runs in a row​

We run an eval gate: a fixed set of routing cases, re-run in batch after every change; failure rate over threshold means red. After the teaching shipped, the gate failed three consecutive runs, and the failure shape was highly consistent — every failure was a JSON format error on the disambiguation tool call (truncation, extra closing brackets), not a validation rejection; frequency climbed from 2 to 5 per run.

Attribution: an old-build A/B pinned the variable down​

The first suspicion was "the teaching text itself misleads the model." But to actually conclude that, we ran a controlled experiment: old build vs new build, the same 4 cases, 16 runs each, counting the malformed-JSON rate.

BuildBad-JSON rate
Old build (no args-required teaching)~6% (1 of 16; the full gate also flaked 1 case)
New build (teaching in three places)12-28%

That single 6% case deserves a note: the old build also flaked occasionally on the full gate — that's the small model's baseline noise, not something the change introduced. The real signal is the jump from 6% to 12-28%: the teaching made every candidate carry full arguments, the disambiguation tool's outputs got significantly longer, and the small model's JSON format error rate amplifies with longer outputs. You cannot see this relationship from a single red/green run.

The fix: revert the teaching, relax validation, guard downstream​

The ruling had three parts:

  1. Strip the args-required teaching from all three places; the few-shot examples teach routing direction only (which inputs go to disambiguation, which candidates to converge on), not argument extraction.
  2. Relax validation to "only validate candidates that carry args": if a candidate includes args, pre-validate them with that tool's own schema — invalid values still get dropped; missing args are tolerated on the card.
  3. Let a downstream deterministic exit catch missing arguments: when the user taps a candidate with missing args, the server returns 422 with guiding text, the original card stays, and the user supplies the missing piece in one message.
// Same-ruler validation only for candidates that carry args: invalid values still dropped, missing tolerated
if (option.args !== undefined && !parseToolCall(option.tool, JSON.stringify(option.args))) {
dropped.push(option.tool) // drop + warn log
continue
}

Why is it safe to let missing args onto the card? Because the downstream guard is deterministic — it doesn't rely on the model's good behavior, it's a fixed branch in server code. Once code catches the problem the teaching tried to prevent, the teaching is all cost (longer outputs, higher bad-JSON rate). This is the same family as thinking-mode consuming the output budget and returning empty content: small models' structured output is sensitive to payload length. For another silent failure of that kind, see DeepSeek/Qwen structured calls returning empty.

Two rules to keep​

LLM tool-calling reliability comes down to two rules: paired enums must reference a single shared constant, and prompt teaching should cover routing direction only — never argument extraction.

Rule one: paired enums must reference a single shared constant. Anywhere a set of legal values appears both in "the definition sent to the model" and in "server-side validation", writing the two copies by hand is forbidden — expand both from one constant. The same holds for any paired constraint (field lists, count limits), not just enums.

Rule two: teach routing, not extraction; decide teaching with old-build A/Bs. Every line of teaching adds output length, and small models' format-error rate climbs with length. Routing direction (which input goes to which tool) is cheap guidance worth teaching; argument completeness, catchable by deterministic validation, belongs in code — not in the prompt. And when judging whether a teaching should stay, don't conclude from a single red/green run — run old and new builds against the same cases a dozen-plus times each and look for the jump in bad-JSON rate.

Watch out

Per-item tolerance isn't free: every drop must be logged (we emit a warn carrying the dropped tool name), otherwise invalid candidates disappear silently and observability goes blind. Likewise, document the "post-filter floor" semantics of min in a code comment — if a future maintainer restores the min value as a raw count constraint, the whole-card validation regresses and scenario one's symptom returns as-is.

FAQ​

How does LLM tool calling work?​

The model never runs anything: it returns a tool name plus a JSON payload that must match the tool's JSON Schema, and your server does the validation and execution. The definition you send and the validator you run are two separate pieces of code — both failure modes in this post (enum drift voiding a whole candidate card, bad-JSON rate jumping from ~6% to 12-28%) live in that mismatch.

Why is my function calling JSON rejected even though it looks valid?​

Because the enum in your tool definition and the enum in your server-side validator are separate hand-written copies. When they drift, the model emits a definition-legal value and your array-level check (a min(2) on the candidates array, in our case) rejects the entire call — one invalid element fails the whole array under zod-style validation. Fix it with a single shared constant plus per-item filtering.

How do I make LLM tool calling more reliable?​

Three rules from our production A/B tests: single-source every paired enum; validate arrays per item so one bad candidate doesn't void the whole card; keep prompt teaching at the routing level instead of forcing full argument payloads. Our measured bad-JSON rate jumped from ~6% to 12-28% when we forced complete arguments, and fell back to the baseline after reverting.

CCLEE

Independent developer, 24 years in e-commerce, focused on grounding AI in real business scenarios.

Work with me