Skip to main content

Map field arrives as {}? JSON.stringify skips Maps entirely

· 6 min read

Ran into this on an estimation endpoint of a Node.js + Fastify service: the response came back 200 with a healthy body, except one field — the per-row dates the client needed were missing because estimates was always {}, whatever parameters were sent.

TL;DR​

JSON.stringify(new Map([['a', 1]])) returns '{}'. A Map's entries live in an internal slot, not in own enumerable properties — and stringify only walks own enumerable properties. Fastify and Express both default to JSON.stringify and special-case nothing. Returning a Map from the core layer is fine; the bug is passing it through the route untouched. Fix: Object.fromEntries(map) before the response leaves.

Symptoms​

The client received {} for estimates on every call — status 200, a healthy response body, no server-side error, regardless of parameters. The endpoint follows the usual shape — the server computes a schedule, the client renders rows — and the route handed the core function's return value straight to the response:

app.post('/api/projects/:id/preview', async (req, reply) => {
const r = await recalcProject({ projectId: req.params.id, /* ... */ });
return { estimatedEnd: r.estimatedEnd, estimates: r.estimates };
});

What the client received:

{
"estimatedEnd": "2026-10-29",
"estimates": {}
}

estimatedEnd was fine; estimates was permanently empty. Server-side logs showed the field present, typed Map, with the right number of entries — the same value crossed the HTTP boundary and vanished. Because the status was 200 and nothing errored, the first instinct was a client-side field-access bug, and investigation spent a while on that side — until logging JSON.stringify(r.estimates) on the server, which printed {}.

One line reproduces it:

JSON.stringify(new Map([['a', 1]]));        // '{}'
JSON.stringify(new Set([1])); // '{}'
JSON.stringify({ m: new Map([['a', 1]]) }); // '{"m":{}}'
JSON.stringify(new Date('2026-01-05')); // '"2026-01-05T00:00:00.000Z"'

Three empty results, one that works.

Root cause: stringify only walks own enumerable properties​

JSON.stringify serializes objects by enumerating their own enumerable properties and turning each into a JSON key-value pair. A Map fails the premise entirely: its entries live in the internal [[MapData]] slot defined by the ECMAScript spec, reachable only through get/forEach and friends, never as properties. An instance has 0 own enumerable properties, so the output is {}.

Set is the same story ([[SetData]]). Date is the counter-example — it implements toJSON(), which stringify calls first, hence the ISO string.

No framework will save you here. Fastify's default JSON serialization is JSON.stringify (unless you register a fast-json-stringify schema), and so is Express's res.json. This is not a framework bug but a language-level behavior — and it decides where the failure lives: not in the compute layer, at the transport boundary.

In this codebase the core function returning a Map was reasonable: consumed internally, key-value semantics, convenient get. The mistake was the route passing the return value as-is into the HTTP response, with nothing along the chain checking "a Map is not a legal JSON value" — silent all the way through.

Fix: flatten at the transport boundary​

Convert the Map into a plain object explicitly, at the edge where the response leaves the server. The fix is one call:

return {
estimatedEnd: r.estimatedEnd,
estimates: Object.fromEntries(r.estimates), // Map<string, T> → Record<string, T>
};

Object.fromEntries produces a plain object, and client-side estimates.a.plannedEnd resolves again.

More durable than the one-off fix is a boundary rule: before a route passes core return values into a response, check for non-POJO fields. The three common cases and their conversions:

Typestringify outputBoundary conversion
Map<K, V>{}Object.fromEntries(map)
Set<T>{}[...set]
DateISO string (fine)leave it; .toISOString() if you want uniformity

For a type-level cure, change the cross-boundary return type from Map<string, TaskEstimate> to Record<string, TaskEstimate> — TypeScript then forces every construction site to choose, and a missed conversion becomes a compile error instead of an empty field in production.

Watch out

  • An empty object errors nothing and alerts nothing; tests can stay green if they only assert on estimatedEnd and never on estimates entry counts. Give cross-boundary fields assertions at the "count > 0" level.
  • Maps nested deeper also become {} and hide better: in { rows: [{ est: new Map() }] } the casualty is rows[].est. When in doubt, JSON.stringify the suspect field — fastest way to see what the wire will carry.
  • Object.fromEntries flattens only the outermost layer; deeply nested Maps need recursive handling — or better, stop using Map at construction sites that feed serialized output.

Silent reshaping at serialization boundaries is not JS-only — the Python sibling bug is json.dumps with default=str turning a set into a string, where membership checks silently degrade into substring matching. Shared lesson: when the serializer meets a non-native type, convert explicitly — never let a fallback decide the shape for you.

FAQ​

Why does JSON.stringify(new Map()) return an empty object?​

JSON.stringify serializes an object's own enumerable properties, and a Map stores its entries in an internal slot instead of properties — zero own enumerable properties, so the output is {}. Nested Maps behave the same: JSON.stringify({m: new Map([['a',1]])}) gives {"m":{}}. Fix: Object.fromEntries(map) before serializing.

Why is my Map field empty in a TypeScript API response?​

TypeScript cannot catch it — a Map is a valid object and JSON.stringify throws no error; the failure is purely at the serialization boundary. Convert explicitly where the response leaves the server: estimates: Object.fromEntries(r.estimates), or type the cross-boundary field as Record<string, T> so plain objects are enforced at the source.

Do Set and Date serialize correctly with JSON.stringify?​

Set fails the same way: JSON.stringify(new Set([1])) is {} — spread it into an array with [...set]. Date works: it implements toJSON(), so JSON.stringify emits an ISO string like "2026-01-05T00:00:00.000Z". Rule of thumb: everything outside JSON's native types needs an explicit conversion at the boundary.

CCLEE

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

Work with me

pg_dump backup empty? FORCE RLS blocks the table owner too

· 7 min read

Ran into this during a disaster-recovery drill on a Node.js + PostgreSQL multi-tenant system: ran pg_dump with the business owner role, the command printed a few errors but still produced a backup file — and the database restored from that file had complete structure and zero rows of data.

TL;DR​

FORCE ROW LEVEL SECURITY puts the table owner under policy evaluation, and pg_dump's COPY is just a SELECT — an owner session without tenant context gets every row filtered out. pg_dump reports query would be affected by row-level security policy but does not stop: it hands you a plausible-looking, data-free dump. Data-touching actions (backfills, backups, full scans) run as superuser or per-tenant with context injected, and restore drills need row-count checks that can tell "structure complete" from "data complete".

Symptoms: a "successful" backup, an empty restore​

Exporting with the owner role: the command printed a few errors, the backup file was still produced, and the restored database had complete structure with zero rows of data. The raw drill output:

$ pg_dump -U app_owner -Fc appdb -f drill.dump
pg_dump: warning: query would be affected by row-level security
policy for table "attachments"
... (one line per table)
$ echo $?
1

Those lines look like warnings. The file exists and is not empty. The problem surfaced only after restoring this dump into the drill database and counting rows: every business table had complete structure — indexes, sequences, constraints — and 0 rows.

A few weeks earlier, the same root cause had shown up on the migration side. A data-action migration (nulling out a legacy column) ran through the owner channel; deployment bookkeeping stayed green. A later superuser check found 2 rows the UPDATE had missed — it had silently modified 0 rows. Stranger still, running SELECT count(*) on one of those tables from the owner session returned 0, while the superuser saw 6. The owner could not read rows from a table it owned.

Two incidents, weeks apart, in different parts of the pipeline — one root cause. The migration side has another silent failure family unrelated to RLS: UPDATE FROM laterals can't reference the target table, and drizzle-kit swallows the error — the fix is to rewrite correlated reads as a CTE.

Root cause: why FORCE RLS stops the owner and pg_dump too​

Once policies apply to the owner, owner data access goes through the same evaluation as any other role — and pg_dump's COPY is an ordinary SELECT. Three layers stack into the silence:

Layer 1: FORCE removes the owner's exemption. With only ENABLE ROW LEVEL SECURITY, the table owner bypasses policies. Multi-tenant tables usually add FORCE ROW LEVEL SECURITY, which pulls the owner into evaluation as well — a deliberate tightening, not a misconfiguration.

Layer 2: maintenance sessions carry no tenant context. The typical tenant-isolation policy:

CREATE POLICY tenant_isolation ON tasks
USING (tenant_id = current_setting('app.tenant_id', true));

The second argument of current_setting('app.tenant_id', true) is missing_ok: unset variable → NULL instead of an error. NULL in a comparison is never true — the policy rejects every row. Without missing_ok, the owner session would fail loudly with unrecognized configuration parameter and the problem would surface immediately; missing_ok turns "no context" into "silently zero rows".

Layer 3: pg_dump's failure signal is weak. A COPY blocked by RLS logs a warning, but pg_dump continues exporting whatever it can — nonzero exit code, file still on disk. Any pipeline that only checks "did the file get created" will treat an empty backup as a good one. DDL never touches policy evaluation, which is why structural changes in the same batch all succeed while data actions silently do nothing.

Fix: pick the channel by action type, then design the checks​

One-line rule: data-touching actions never run through a bare owner session.

ActionChannel
DDL migrations (create/alter/index)owner channel as usual
Data-action migrations (UPDATE / backfill / cleanup)superuser, or per-tenant SET app.tenant_id
Backups (pg_dump), full-table scanssuperuser
Application connectionsbusiness role + tenant context injected per connection (RLS works as designed)

Per-tenant injection, for tenant-by-tenant repairs:

SET app.tenant_id = 'tenant-a';
UPDATE ...; -- the policy passes rows for this tenant as intended

One-shot full backfills are simpler as superuser.

The backup fix is one character deep: pg_dump -U postgres. After switching, the re-run drill reconciled cleanly — migration records present, five key tables' row counts identical to production, RLS policy count matching, zero ownership anomalies.

Restore-drill checks must distinguish "structure complete" from "data complete". This drill nearly passed on its own criteria: the checklist said "row counts ≤ production + tenant table equal", which zero rows satisfies. Two corrections:

  1. Same-instant snapshot (export inside a write-freeze window) → row counts must be exactly equal.
  2. Hot export from a live database → tolerance allowed, but stated explicitly with its cause (normal writes during export). Zero rows is never inside any tolerance.

Add one foolproof line: row count 0 on a core table fails outright, no tolerance discussion.

Watch out

  • A nonzero pg_dump exit code is not "just a warning" under FORCE RLS — it means data did not make it into the file. A file existing is not a backup existing.
  • Do not reach for BYPASSRLS on the owner to make this go away: isolation matters precisely for roles that hold migration rights — that is why FORCE was chosen. Pick channels by action type instead of loosening roles.
  • One-command self-check across your pipeline: run SELECT count(*) on a core table as each operational role and compare against the superuser's count. Any mismatch means this trap is live.

The full backfill-side walkthrough of the same FORCE RLS chain — the layer-by-layer anatomy of a silent INSERT 0 0 — is in the companion post: Postgres RLS migration all green, backfill 0 rows? FORCE RLS stops the table owner too. Between the two: that one covers the backfill side, this one the backup and drill-check side.

FAQ​

Why does pg_dump produce only schema without data?​

With FORCE ROW LEVEL SECURITY on the tables, even the table owner's dump session must pass the RLS policies. Maintenance sessions carry no tenant context, so the policy evaluates to false for every row and COPY returns an empty set. pg_dump prints 'query would be affected by row-level security policy' warnings yet still writes a structure-only file — a healthy-looking backup with zero data.

Does row level security affect the table owner?​

Only ENABLE ROW LEVEL SECURITY leaves the owner exempt — policies constrain other roles. Adding FORCE ROW LEVEL SECURITY removes that exemption, so every row-access statement from the owner goes through policy evaluation too. Policies built on current_setting('app.tenant_id', true) return NULL in sessions without tenant context, and NULL compares false against everything: silently zero rows.

How do I verify a backup actually contains data?​

Restore it and compare per-table row counts against production. On a same-instant snapshot the counts must match exactly; for a hot export allow a tolerance you can state and explain. Zero rows in a core business table fails under any tolerance — treat it as a hard stop, not a gray zone.

CCLEE

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

Work with me

WordPress same-name upload overwrites media? Disk-only dedup

· 11 min read

On a production site whose media library is offloaded to object storage in cloud-only mode (local copies deleted), an editor re-uploaded a cover image under a name that already existed months ago. The upload succeeded with no warning. That afternoon the site's theme vendor reported that a batch of older posts was showing the new image. The media library listed two separate attachments with different IDs; only readers noticed the pictures had changed.

TL;DR​

  1. WordPress core's same-name dedup, wp_unique_filename(), only scans the local upload directory. It never queries the database — the function body contains zero $wpdb calls — and it knows nothing about your bucket. With local files deleted, the disk is always empty, so dedup always approves the name, the upload reuses the same object key, and putObject overwrites the old object.
  2. The fix: hook wp_unique_filename (priority 999) and add three checks — a disk directory family-name scan, a _wp_attached_file family-prefix query, and per-key HEAD requests against the bucket (base / -scaled / -rotated × extension set). If any face is occupied, increment WordPress-native -N names up to 20 rounds; if a dedup source errors out, fall back to a random suffix and upload unblocked.
  3. A pitfall worth copying: the object key equals the uploads-relative path, so the check set must carry the directory prefix. Our first version built keys from the bare basename, and a test fixture with a subdirectory immediately caught "bucket-face dedup misses every subdirectory upload" — 2026/11/hero.jpg and hero.jpg are unrelated strings to object storage.

grep -P fails in scripts, works in your shell? PATHs differ

· 6 min read

A release script that had run unattended on WSL for months died on its first grep call the day it was moved to a Mac: grep: invalid option -- P. What made it worse was the diagnostic itself — typing the very same grep -oP '…' into the terminal passed. Same command, same machine: works in the terminal, fails in the script.

TL;DR​

  1. The error has nothing to do with a typo: your interactive zsh and the bash script resolve two different PATHs. Interactively, grep hits a brew-installed GNU grep (which supports -P); in the script it hits /usr/bin/grep (BSD grep, no -P).
  2. The same family of failures extends beyond grep: sha256sum and other GNU coreutils tools exist only in the interactive PATH too, and fail with command not found one step later.
  3. Three portable fixes: rewrite every grep -oP as an equivalent sed -nE extraction; fall back to shasum -a 256 when sha256sum is missing; replace hardcoded paths with runtime self-detection. The script then runs on any machine, any shell.

Postgres RLS Backfill Lands 0 Rows? FORCE RLS Binds Owners

· 10 min read

While running a one-off data backfill against a multi-tenant table, the command finished normally and returned INSERT 0 0 — the baseline had 23 rows to migrate, and not one of them landed. In the same deployment, every CREATE TABLE and ADD COLUMN migration had succeeded.

TL;DR​

ENABLE ROW LEVEL SECURITY does not constrain the table owner; FORCE ROW LEVEL SECURITY removes that exemption. An owner's ops session has no app.tenant_id context, so a tenant-scoped policy evaluates to false on every row, and the SELECT source of an INSERT…SELECT is filtered to an empty set — the statement succeeds, inserts nothing, and raises no error. DDL never passes through RLS, which is why migrations stay green on the same channel. Run data backfills as a superuser (or per-tenant with SET app.tenant_id), and always verify "baseline row count vs landed row count".

The symptom​

On a FORCE-RLS multi-tenant table, an owner-session backfill silently inserts 0 rows — the statement succeeds with no error and no warning, and the command output alone reads as success. Here is how it happened for real.

The setting: a multi-tenant SaaS deployment. A batch of migrations (create table, add column) goes through the owner database channel and all succeed. Right after, an idempotent backfill moves data from legacy single-select columns into a new child table:

INSERT INTO task_assignees (tenant_id, task_id, assignee_user_id, assignee_vendor_id)
SELECT tenant_id, id, assignee_user_id, assignee_vendor_id
FROM tasks
WHERE assignee_user_id IS NOT NULL OR assignee_vendor_id IS NOT NULL
ON CONFLICT DO NOTHING;

Run as the project's owner role (app_owner for short):

INSERT 0 0

The statement exits successfully, ON_ERROR_STOP never fires, and the deployment pipeline moves on. But a superuser count shows 23 tasks with non-null legacy columns — the backfill effectively never ran. Judged by exit status alone, this step slips through silently.

The confusing part is the contrast within the same channel: in one and the same psql pipeline, CREATE TABLE and ALTER TABLE … ADD COLUMN work fine, and only this INSERT…SELECT lands 0 rows.

Root cause: FORCE RLS binds the owner too​

FORCE RLS extends policy enforcement to the owner, while the owner's ops session carries no tenant context — the policy evaluates false on every row and the SELECT is silently filtered to empty; DDL never passes through RLS, so migrations stay green on the same channel. Three layers stack into the silent chain, and each one looks reasonable on its own.

Layer 1: ENABLE and FORCE are different switches. PostgreSQL has shipped RLS since 9.5. ENABLE ROW LEVEL SECURITY turns policies on, but the table owner is exempt by default — policies only bind other roles. Multi-tenant tables usually add FORCE ROW LEVEL SECURITY to cancel that exemption:

ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;
ALTER TABLE tasks FORCE ROW LEVEL SECURITY; -- the owner is no longer exempt

Security-wise this is right: if the owner account ever leaks into an application connection, tenant isolation still holds. The cost is that the owner's ops channel is governed by policies too — a detail that deployment docs tend to omit.

Layer 2: current_setting with missing_ok silently returns NULL. The policy is the standard tenant-header filter:

CREATE POLICY tasks_tenant ON tasks
USING (tid = current_setting('app.tenant_id', true)::uuid);

The second argument, missing_ok = true, means "return NULL instead of raising an error when the setting is absent" — a lenient read designed for application connections. Nobody runs SET app.tenant_id in an ops session, so the policy expression becomes tid = NULL, which evaluates to NULL (not true, not false), and the row is filtered out. The session raises nothing; the query raises nothing; you simply see no rows.

Layer 3: DDL never passes through RLS. RLS evaluates row access only (SELECT visibility, write legality). CREATE TABLE, ALTER TABLE, and index builds never touch policy evaluation. So the same owner channel splits in two:

OperationOwner-channel result
Create table / add column / build index (DDL)Runs normally
INSERT…SELECT (DML, source governed by FORCE RLS)SELECT source filtered to empty, INSERT 0 0
Bare INSERT with VALUES into the governed tableError: "violates row-level security" (visible)

The second row is the dangerous one: INSERT…SELECT fails in the shape of an emptied source, not a rejected target. No row ever attempts to enter, so no violation is ever raised — a silent 0 is far harder to notice than an error.

The fix​

The way out is to make the backfill session bypass — or satisfy — the tenant policy: a superuser (first choice for one-off migrations), a dedicated BYPASSRLS role (regular corrections), or per-tenant SET (keeping isolation semantics). A minimal reproduction first, then each option in turn.

Minimal reproduction​

-- A FORCE-RLS multi-tenant table
CREATE TABLE tasks (
id INT GENERATED ALWAYS AS IDENTITY,
tid UUID NOT NULL,
title TEXT,
done BOOLEAN DEFAULT false
);
ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;
ALTER TABLE tasks FORCE ROW LEVEL SECURITY;
CREATE POLICY tasks_tenant ON tasks
USING (tid = current_setting('app.tenant_id', true)::uuid);

-- An unguarded archive table (the backfill target)
CREATE TABLE tasks_archived (
id INT,
tid UUID,
title TEXT,
done BOOLEAN
);

-- Seed two rows as superuser
INSERT INTO tasks (tid, title) VALUES ('11111111-1111-1111-1111-111111111111', 'a'),
('22222222-2222-2222-2222-222222222222', 'b');

-- Switch to an owner-role session (no tenant context):
SELECT count(*) FROM tasks; -- 0
INSERT INTO tasks_archived SELECT * FROM tasks; -- INSERT 0 0

count(*) returning 0 is the diagnostic pivot: the SQL is not wrong, the session simply cannot see the rows.

A superuser is not subject to RLS. Hand the backfill to the postgres role:

psql -U postgres -d mydb -v ON_ERROR_STOP=1 -f backfill.sql

The same statement flips from INSERT 0 0 to INSERT 0 23. The trade-off: maximum privilege, so reserve it for controlled one-off ops and never put it into application connection strings.

Option 2: a dedicated BYPASSRLS role​

If the ops channel runs data corrections regularly, create a dedicated role:

CREATE ROLE migrator WITH LOGIN BYPASSRLS;

A BYPASSRLS role skips every policy without acquiring the rest of the superuser privilege set — a narrower surface. It still needs explicit GRANTs per table, and the role's credentials must be treated as sensitive secrets.

Option 3: set tenant context per tenant​

To keep RLS semantics intact (the migration logic itself passes through isolation rules), run tenant by tenant inside a session:

SET app.tenant_id = '11111111-1111-1111-1111-111111111111';
-- backfill statements for that tenant

Fits backfills whose logic differs per tenant; for a straight full copy, a per-tenant loop is more ceremony than bypassing outright.

Always verify row counts afterwards​

Whichever channel you pick, the acceptance criterion for a backfill is not "command succeeded" — it is row reconciliation:

-- Baseline: affected rows (counted before the backfill)
SELECT count(*) FROM tasks
WHERE assignee_user_id IS NOT NULL OR assignee_vendor_id IS NOT NULL;

-- Landed: after the backfill
SELECT count(*) FROM task_assignees; -- total = baseline
SELECT count(DISTINCT task_id) FROM task_assignees; -- distinct tasks = baseline (single-select case)

In this incident, it was exactly the "baseline 23 = landed 23" check failing to add up that exposed the problem — the owner channel had printed INSERT 0 0, and without reconciliation the deployment would have shipped an empty child table. For belt-and-suspenders, join old and new rows on the primary key and compare migrated column values: zero diffs closes the loop.

Pitfalls on database write paths are rarely syntax errors — they are deployment-order and constraint-semantics mismatches. ON CONFLICT unique-constraint matching is the same family: the SQL is right, and a mismatched migration/deploy ordering still breaks everything.

The same FORCE RLS chain has a backup-side shape too: running pg_dump as the owner produces a structure-only backup with zero rows. Which channel each data action should take, and how to design restore-drill checks that catch it, is in the companion post pg_dump backup empty? FORCE RLS blocks the table owner too.

Gotchas​

On FORCE-RLS tables, the acceptance criterion for ops actions shifts from "command succeeded" to "row counts reconcile". All four points come straight from this incident:

Gotchas

  • A silent 0 is riskier than an error: when RLS empties the source of an INSERT…SELECT, nothing is raised. Backfill-type operations need a "baseline vs landed" row-count check, not just an exit code.
  • Never infer the data path from migration success: DDL bypasses RLS, so green DDL on the same channel proves nothing about DML. Probe the channel with a real DML statement.
  • missing_ok=true is part of the silent chain: current_setting('app.tenant_id', true) returns NULL when the setting is absent (policy always false, whole table filtered); with missing_ok=false a missing setting raises immediately, which surfaces the problem sooner. The lenient read is fine for app connections — just know what it does in ops sessions.
  • Keep superuser credentials in their own lane: the postgres role is for one-off ops only; it should never appear in connection strings, app config, or CI.

FAQ​

Why does Postgres row level security not seem to apply to the table owner?​

Because ENABLE ROW LEVEL SECURITY alone never constrains the table owner — policies only bind other roles by default. Add ALTER TABLE … FORCE ROW LEVEL SECURITY and every row-access statement from the owner session goes through policy evaluation too.

What does INSERT 0 0 mean in PostgreSQL?​

The two numbers are OID and row count: the statement succeeded but inserted 0 rows. Under FORCE RLS, a policy can filter the SELECT source of an INSERT…SELECT down to an empty set — nothing violates any policy, so nothing is raised. To pinpoint it, run SELECT count(*) in the same session first; a 0 confirms visibility filtering rather than a broken statement.

How do I bypass row level security in PostgreSQL for a data migration?​

Three options: run as a superuser such as the postgres role (bypasses RLS by definition — best for one-off backfills); create a dedicated role with BYPASSRLS; or SET app.tenant_id per tenant to keep RLS semantics. Whichever you choose, follow up with a row-count check against the baseline.

Does FORCE ROW LEVEL SECURITY affect DDL statements?​

No. RLS evaluates row access only — SELECT visibility and write legality. CREATE TABLE, ALTER TABLE, and index builds never touch policy evaluation, which is why the same migration run shows all-green DDL next to a silently empty DML backfill.

CCLEE

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

Work with me

coscli has no upload? v1 uses cp, sync, rm; LHCOS quirks

· 6 min read

While wiring up off-site uploads for a PostgreSQL backup, the first line of the script was the intuitive coscli upload backup.sql.gz cos://… — which failed immediately: no such subcommand.

Ran into this in a PostgreSQL off-site backup pipeline (shell scripts + Tencent Cloud coscli, v1.0.9).

TL;DR​

v1 has no upload/delete verbs: use cp for uploads/downloads, sync for folder sync, rm for deletes, always adding -r for recursion; pass the region via -e if you skip the config file. LHCOS buckets (the object storage bundled with Lighthouse instances) add a quirk: they never appear in the account's global COS bucket list — GET Service returns 0 buckets, and a HEAD against the exact bucket name is the existence test. Bucket creation and deletion are console-only; file APIs work normally.

Symptoms: no such command, wrong arg count, empty bucket list​

Three symptoms that look unrelated — a missing command (if you searched "coscli command not found" or "COS CLI upload fails"), -r reporting accepts 2 args, and GET Service returning an empty list — are two rule sets stacked: v1's verb table, and LHCOS bucket visibility.

First trap: the intuitive verb doesn't exist. upload and delete both fail as unknown subcommands — they simply aren't in v1's help.

Second trap: the recursion flag treated as a command. With -r misplaced or arguments missing, the tool reports accepts 2 args — -r is not a standalone command, just cp/sync's recursion flag, and the positional arguments follow cp's signature.

Third trap, the most misleading: running the list-buckets call (GET Service) to confirm the bucket exists returns 0 buckets. Meanwhile the backup job has been writing and reading that bucket all along — the bucket is fine, just absent from that list.

Root cause: coscli v1's verb table, plus LHCOS staying out of the global list​

v1's semantics are object operations, not resource management. The v1 verb set is three words: cp (upload/download), sync (folder sync), rm (delete). The upload/delete verbs in many tutorials belong to other tools or newer CLI versions; recursion is the -r flag rather than a command, so "command + -r + source + target" with one positional argument missing reports accepts 2 args. Tencent also ships an older Python tool, coscmd, with yet another verb table — check which tool a tutorial is about before copying.

LHCOS buckets are a separate namespace, not merged into the account's COS list. GET Service only returns buckets from the COS product line; LHCOS buckets never appear in it, so an empty list does not mean the bucket is missing. The existence test is a HEAD against the exact bucket name. File-level APIs (upload/download/delete) address the bucket directly and work normally; only bucket creation and deletion are console-only operations.

Fix: a fixed invocation shape for scripts, HEAD for existence​

  1. The non-interactive shape. --init-skip=true skips the first-run setup wizard, -i/-k pass the keys, -e names the region endpoint — together they make the command usable from cron and scripts:
# upload a single file; add -r for directories
coscli --init-skip=true cp backup.sql.gz cos://examplebucket-1250000000/backup/ \
-e cos.ap-guangzhou.myqcloud.com -i "$SECRET_ID" -k "$SECRET_KEY"

# folder sync
coscli --init-skip=true sync ./dump/ cos://examplebucket-1250000000/backup/ \
-e cos.ap-guangzhou.myqcloud.com -i "$SECRET_ID" -k "$SECRET_KEY"

# delete (add -r for recursion)
coscli --init-skip=true rm -r cos://examplebucket-1250000000/backup/old/ \
-e cos.ap-guangzhou.myqcloud.com -i "$SECRET_ID" -k "$SECRET_KEY"

Bucket names carry the APPID suffix (1250000000 in the example); the Guangzhou region endpoint looks like cos.ap-guangzhou.myqcloud.com.

  1. Existence checks bypass the bucket list. When debugging "does this bucket exist", HEAD the exact bucket name or check the console — an empty GET Service result proves nothing.

  2. One-off operations go to the console. Bucket creation, deletion, and permission changes are console actions; scripts don't touch them.

Intentv1 invocation
Upload one filecp <local> cos://bucket/path/
Upload a directorycp -r <dir> cos://bucket/path/
Sync a foldersync <dir> cos://bucket/path/
Deleterm [-r] cos://bucket/path/

Watch out

  • Inline -i/-k values linger in shell history and process lists. For cron jobs, source credentials from a 0600-permission file instead; scope the sub-account to read-write on the target bucket only.
  • LHCOS and COS are separate product lines with separate billing and capacity — don't audit LHCOS through the COS bucket list.
  • Check the verb table first on errors: coscli v1, v2, and coscmd share no verb table — run --version to see which one you installed before matching tutorials.

FAQ​

coscmd supports upload — why doesn't coscli?​

They are two different tools: coscmd is the older Python CLI, while coscli v1 (e.g. 1.0.9) uses object verbs — cp for uploads (add -r for directories), sync for folder sync, rm for deletes. Same transfer, different verb table; check which CLI a tutorial targets before copying its commands.

How do I check whether an LHCOS bucket exists?​

Don't trust the bucket list: GET Service returns 0 buckets for the LHCOS namespace. Send a HEAD request for the exact bucket name (or check the console) — that's the existence test. File APIs work normally; only bucket creation and deletion are console-only.

How do I run coscli non-interactively in scripts?​

Combine --init-skip=true (skips the setup wizard), -i/-k for the keys, and -e cos.<region>.myqcloud.com for the endpoint. In cron jobs, source credentials from a 0600-permission file instead of inline values, and scope the sub-account to read-write on the target bucket only.

CCLEE

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

Work with me

drizzle-kit migrate: exit 0 but no tables? Audit the journal

· 9 min read

While shipping a batch of new tables for a multi-tenant system, drizzle-kit migrate on the deploy host printed "applying migrations" and exited quietly with code 0 — the application then started and its very first query failed on a missing table.

Ran into this in the deploy pipeline of a Node.js + PostgreSQL multi-tenant system (Drizzle ORM for migrations, row-level security isolating tenants, drizzle-orm 0.45.4 / drizzle-kit 0.31.11).

TL;DR​

Exit code 0 does not mean the migration applied. drizzle-kit's journal (the drizzle.__drizzle_migrations ledger) and the actual tables in the database are two different books: when the journal says "applied" but the table is missing, every later migration is skipped silently. Three steps: reconcile (journal count = migration file count, key tables present in information_schema) → re-apply missing files with psql -v ON_ERROR_STOP=1 and insert the journal row by hand → fix table ownership with OWNER TO. On the deploy path we retired drizzle-kit migrate entirely in favor of an owner pipeline: per-file apply + server-side journaling + verify-or-stop.

Symptoms: three errors, all exit code 0​

There are three layers to this, the first two in the migration command and the third right after it — none of them produce a failure signal on the command level. If you searched "drizzle migrate not working", "migrations applied but no tables", or "must be owner of table", read on.

Symptom one: the migration prints "applying", exits 0, tables missing.

$ drizzle-kit migrate
...
applying migrations...
$ echo $?
0

The local dev database hit the "journaled but not created" shape first — an interrupted migration left a half state behind, and every later migrate run treated that batch as applied and skipped it. Production hit the same problem in the opposite shape: migration 0019 exited 0 with neither the SQL applied nor the journal row written.

Symptom two: adding a foreign key fails with an unrelated error.

ERROR:  unrecognized configuration parameter "app.tenant_id"

Symptom three: with the key in place, the policy script stalls.

ERROR:  must be owner of table conflict_events

All three errors are segments of the same deploy pipeline.

Root cause: the journal and the schema are two different books​

The journal records "booked", not "the table exists". drizzle-kit migrate reads the SQL files in the migrations folder and decides what to skip by comparing hashes in drizzle.__drizzle_migrations — the journal is its only input. Once a "journaled row, missing table" intermediate state exists (most often left by an interrupted migration), every later migrate run believes that batch is done and skips it: no error, exit code 0. Production's 0019 was the inverse — neither applied nor journaled — but it surfaced the same way: caught by the ledger reconciliation, with no signal from the command itself.

Plainly put: this is a design where status is judged from the ledger alone, and when the ledger is polluted or never written, drizzle-kit offers no clue about it. Why it skips silently on the normal path, the command does not explain — our response was to stop trusting its judgment on the deploy path (the trade-off is explained in the fix).

Foreign keys meet RLS: the RI check runs without tenant context​

The referential-integrity trigger reading the referenced table does not carry your application's tenant injection. Multi-tenant tables usually have row-level security (RLS) policies that read a session variable via current_setting('app.tenant_id'). But the referential integrity (RI) check is an internal trigger scan: it runs on a bare connection that never SET app.tenant_id, so current_setting throws unrecognized configuration parameter — the foreign key isn't wrong, the policy blows up on that bare connection first.

The fix is one parameter:

current_setting('app.tenant_id', true)  -- returns NULL when unset

NULL matches no rows inside the policy (equivalent to deny), so the isolation semantics are unchanged while the RI check's bare connection stops erroring. For an RLS database the order becomes fixed: fix the policies first, then add the foreign keys.

Ownership drift: superuser-owned tables block policy application​

Policies can only be changed by the owner, and historical tables may be owned by someone else. The three tables apply-policies choked on (conflict_events, equipments, vendors) had been created manually by a superuser much earlier — owned by postgres, not by the owner role migrations run as. CREATE POLICY requires the table owner; with the wrong owner, applying all 15 policy files stalls.

Reclaim ownership:

ALTER TABLE conflict_events OWNER TO app_owner;

And audit the whole database — this query must return 0 rows:

SELECT tablename FROM pg_tables WHERE tableowner <> 'app_owner';

Fix: reconcile → re-apply → reclaim → harden the deploy path​

For 0019 the order of events was: fix the policy, add the foreign key, get blocked again by table ownership — after reclaiming the three tables, all 15 policy files applied, and only then did the journal check reveal that 0019 had never been applied or recorded. Later, 0020 skipped silently on the same pipeline, and this time the deploy entry's ledger check stopped it before the half-applied state went live. After those two recurrences, the deploy-path migration became a fixed shape:

  1. Reconcile (a fixed step after every migration):
SELECT count(*) FROM drizzle.__drizzle_migrations;
-- must equal the number of files in the migrations folder

SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
-- key tables must actually exist
  1. Re-apply: for missing journal rows, pipe the SQL in as the owner role, then add the journal row:
psql -v ON_ERROR_STOP=1 -U app_owner -d appdb < drizzle/0019_missing.sql
# journal row: hash = sha256 of the full SQL file; created_at = epoch seconds (bigint), matching existing rows
  1. Reclaim: check owners, ALTER TABLE … OWNER TO app_owner (previous section), re-run policy application.

  2. Harden the deploy: replace "run drizzle-kit migrate once" with a per-file loop — apply each file with ON_ERROR_STOP and stop on the first failure, compute the journal hash server-side, and reconcile the count at the end:

for tag in $pending; do
psql -v ON_ERROR_STOP=1 -U app_owner -d appdb < "drizzle/$tag.sql"
hash=$(sha256sum "drizzle/$tag.sql" | cut -d' ' -f1)
psql -d appdb -c "INSERT INTO drizzle.__drizzle_migrations (hash, created_at)
VALUES ('$hash', extract(epoch from now())::bigint)"
done
# final check: journal count = local migration file count, otherwise abort the deploy

Deploy-time migration: the owner pipeline

The trade-off: why not keep drizzle-kit migrate? What a deploy needs is not "let the tool decide" but "the applied result is verifiable, and any failure stops the run". Per-file application turns every action into an assertable atomic step, and the ledger reconciliation turns "silently skipped" into an explicit failure. Local development keeps using the package.json db:migrate script (drizzle-kit migrate plus policy application) — what retired is the deploy usage, not the tool.

That owner pipeline guards against the journal and the schema diverging — but the ledger itself can be corrupted: hand-edited future timestamps in _journal.json inflate the watermark max(created_at) and pin every later migration below it, and a raw SQL file without journal registration never enters the pending list. Both shapes and their fixes are in the companion post drizzle migration skipped silently? Check the journal first.

The same family of "the migration looked done" exists on the SQLAlchemy side: three Alembic migration pitfalls (async engine misuse, broken revision chains, model changes without migrations). To systematize existence and ownership checks, see auditing orphan tables with information_schema.

Watch out

  • Run both checks after every migration: journal count = migration file count, and the key tables exist in information_schema. Both passing is what "migration complete" means; the exit code alone is not evidence.
  • Manual journal rows must match the existing format: hash is the sha256 of the full SQL file, created_at is epoch seconds as bigint — keep the same types drizzle-kit writes, or later reconciliations drift.
  • Run migrations as the owner role, always: tables created by a superuser are owned by the superuser, and the next policy application stalls for sure. The owner check belongs in the post-migration checklist.

FAQ​

Why does drizzle-kit migrate exit 0 without creating tables?​

The journal and the schema have diverged. Reconcile two counts: SELECT count(*) FROM drizzle.__drizzle_migrations; must equal the number of migration files, and information_schema.tables must contain the tables. Re-apply the missing SQL with psql -v ON_ERROR_STOP=1 and insert the journal row manually (hash = sha256 of the SQL file).

drizzle-kit migrate vs push — which one for production?​

migrate applies versioned SQL files tracked in a journal — one journal row per file; push diffs the schema directly with no history. Versioned files plus a verification step fit production better — but don't trust the exit code alone: reconcile the journal against the actual tables after every run.

How do I verify drizzle migrations were actually applied?​

Two counts plus one ownership check: the journal count equals the migration file count, the new tables exist in information_schema.tables, and SELECT tablename FROM pg_tables WHERE tableowner <> 'owner_role'; returns 0 rows — otherwise policy application fails with "must be owner of table".

CCLEE

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

Work with me

Postgres 42501 on new tables? Default grants per database

· 6 min read

While creating new tables with a dedicated owner role in a multi-tenant system, every query from the application role failed with permission denied for table — old tables were fine, every freshly migrated table was unreachable.

Ran into this in a Node.js + PostgreSQL multi-tenant system (row-level security isolating tenant data).

TL;DR​

ALTER DEFAULT PRIVILEGES is not a global switch: its scope is "which role grants × which database it runs in". Running it once in the postgres database gives future tables in your app database nothing — queries fail with 42501 anyway. Fix in two moves: run it in every application database; and when DROP ROLE complains about dependencies, clear the stale entries with DROP OWNED BY in that same database.

Symptoms: old tables work, new tables fail with 42501​

A freshly created table is immediately unreadable for the application role while the same role queries every existing table without trouble — grants missing only on "tables created after migration" is the signature of missing default privileges. If you searched "postgres permission denied for table", "42501 insufficient privilege", or "granted privileges but still permission denied", it's the same problem.

-- a table the owner role just created via migration
ERROR: permission denied for table vendors
SQLSTATE: 42501

The second symptom shows up later, when cleaning up a role:

ERROR:  role "app_role" cannot be dropped because some objects depend on it
DETAIL: privileges for default privileges in database appdb

The DETAIL line is the tell: the dependency is not a table or a function, it's a stale default-privileges entry.

Root cause: ALTER DEFAULT PRIVILEGES is scoped to a role × a database​

The default-privilege rule lives in the database where you ran it, and never crosses databases. What ALTER DEFAULT PRIVILEGES records is a rule — "objects created in this database, from now on, by the role named in FOR ROLE (default: the current role), are granted to the TO role automatically". The rule is stored in the database-local pg_default_acl catalog, which means:

  • run it in the postgres database → only future objects in the postgres database are covered
  • never ran it in the app database → new tables there carry no default grants at all
  • tables get created by a different role (no FOR ROLE) → the rule doesn't match

The order of events that produced this: a tutorial-style "global" default-privilege statement ran in the postgres database first, then the app database was created. The first few tables happened to be granted manually, so everything looked fine — until migrations started creating tables automatically and 42501 errors appeared in bulk. First hypothesis: a missing GRANT statement; adding grants changed nothing. The stale entry surfaced only when dropping an unused role failed with privileges for default privileges in the DETAIL — the grants did exist, just in the wrong database.

PostgreSQL treating "where you run it" as a behavior boundary shows up elsewhere too: fe_sendauth across containers is the same logic — identical command, different execution path, completely different rules.

ALTER DEFAULT PRIVILEGES scope: one role × one database

Fix: grants go into the app database, cleanup goes into the same database​

Three steps, all organized around the database unit:

  1. Inventory which databases have default privileges. Run in each database; 0 in an application database means it was missed:
SELECT count(*) FROM pg_default_acl;
  1. Run the default grants per database. One statement for TABLES, one for SEQUENCES, FOR ROLE naming the role that actually creates tables:
-- run with psql -d <appdb>, not while connected to the postgres database
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO app_role;

ALTER DEFAULT PRIVILEGES FOR ROLE app_owner IN SCHEMA public
GRANT USAGE, SELECT ON SEQUENCES TO app_role;
  1. Clear stale entries. When DROP ROLE reports dependencies, connect to each database named in the DETAIL (every database holding default-privileges entries) and run:
DROP OWNED BY app_role;
DROP ROLE app_role;

For new databases, bake step 2 into the provisioning script — every grant statement in our init script is forced through -d <database>, which rules out the "ran it while connected to postgres" failure mode for good.

Default privileges only cover future objects, so tables that already exist need a one-time grant:

GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO app_role;

Watch out

  • No FOR ROLE means the current role: run it as the superuser without FOR ROLE and the rule is attached to the superuser — it only fires when the superuser creates objects, and migrations running as the owner role still produce ungranted tables.
  • DROP OWNED drops objects too: it revokes the role's privileges in that database and drops objects it owns. Use it for dedicated roles being removed, not casually on shared roles.
  • A new database is a new grants gap: default privileges are not inherited on CREATE DATABASE. "Create database → immediately set default privileges" should be one fixed step in the provisioning script.

FAQ​

Why is ALTER DEFAULT PRIVILEGES not working for new tables?​

Its scope is one role in one database: running it in the postgres database only affects future objects created there. Run it in each application database, with FOR ROLE set to the role that actually creates tables.

What does PostgreSQL error 42501 (permission denied for table) mean?​

SQLSTATE 42501 is insufficient_privilege. When old tables query fine and only migrated tables fail, the app role is missing default grants — verify with SELECT count(*) FROM pg_default_acl; in that database (0 means none configured), then add the per-database ALTER DEFAULT PRIVILEGES.

Do I need ALTER DEFAULT PRIVILEGES FOR ROLE in every database?​

Yes — once per database per table-creating role, and it only covers future objects, so existing tables need a one-time GRANT ... ON ALL TABLES IN SCHEMA public. To drop a role blocked by "privileges for default privileges", run DROP OWNED BY in each database holding stale entries, and retry DROP ROLE once SELECT count(*) FROM pg_default_acl; returns 0 there.

CCLEE

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

Work with me

URL Rewrites Miss JSON Images? Escape Forms Are the Reason

· 8 min read

During the final verification pass of a CDN migration for a client site, the homepage slider's large images and a 47MB background video were still serving from the origin domain, hogging a 5Mbps shared uplink — while the noscript fallback inside the very same element already pointed at the CDN domain. Half the element migrated, half didn't.

TL;DR​

  1. URLs don't only live in src="...". Slider plugins store image paths inside inline JSON ("src":"..." — colon form), often further escaped into https:\/\/ byte streams. An attribute-grammar rewrite surface (src=/srcset=/href= with a whitespace-required prefix) misses all of these, and a plain str_replace misses the escaped forms too.
  2. Close it with a storage-side three-form replace: inspect the stored form first, then replace plain, single-escaped, and double-escaped variants separately. We closed 204 occurrences across the three slides/slides7 tables of Slider Revolution. PHP serialized fields must go through the serialization engine; JSON fields can be replaced byte-for-byte.
  3. Then run a two-hop save fixpoint: two consecutive editor saves that leave the stored byte stream unchanged prove the save path writes back no old domain.

wp eval Works but REST 500s? Three WordPress Context Traps

· 9 min read

Three quiet WordPress plugin behaviors surfaced while building CCLEE B2B — a WooCommerce B2B plugin covering user management, differential pricing, quoting, and bulk ordering. The entry point was its PDF catalog download: on production the button returned the generic fatal-error page while the very same logic ran via wp eval; fixing the first layer exposed the second, and the second the third. The three root causes live on three different layers — deploy, context, filesystem — and they fit in one post.

TL;DR​

  1. Deploy layer: CI/rsync deploys never run composer install. If the plugin's vendor/ is hidden by stacked .gitignore rules (plugin-level /vendor/ plus repo-level vendor/ and plugins/), it never enters git, and the first new after require autoload is a Fatal. Fix: remove the ignore chain, commit vendor, smoke-test with class_exists after deploy.
  2. Context layer: REST requests never load wp-admin/includes/, so admin-only functions like wp_tempnam() throw Call to undefined function. wp eval works because CLI loads full WordPress — "it works in CLI" proves nothing about the REST context. Fix: function_exists guard plus a tempnam(sys_get_temp_dir(), ...) fallback.
  3. Filesystem layer: mPDF's default temp directory sits at vendor/mpdf/mpdf/tmp/. In the container, rsync preserved owner UID 1001 while PHP-FPM runs as www-data (UID 82), is_writable returns false, and chown fails on the volume-mounted filesystem. Fix: pass an explicit tempDir under the system temp directory at construction.