Skip to main content

Aliyun CLI Exit 0 but Failed? jq Default Values Hide Errors

· 6 min read

An automation script probed whether a Cloud Assistant command still existed using DescribeCommands with a jq -r '.TotalCount // 0' fallback — the API returned an error, the script read TotalCount=0, concluded "command doesn't exist," and dutifully created a duplicate.

Encountered this while running managed hosting for a leading manufacturer's China site — Cloud Assistant automation is the dispatch channel for patrols and maintenance on that server.

TL;DR​

Two layers stack into one illusion. Layer one: the aliyun CLI prints API error JSON to stderr with exit code 0, so set -e gets no signal. Layer two: the jq -r '.TotalCount // 0' fallback turns an error response — which has no TotalCount field — into 0, disguising "query failed" as "query succeeded, zero hits." The house rule: capture with 2>&1, read the raw response first, and never use a jq default as a failure probe. Two more landmines nearby: DescribeCommands takes the singular --CommandId (the array-style --CommandId.1 belongs to InvokeCommand habits and is an error here), and DescribeInvocationResults only accepts a CommandId with object-in-object nesting.

Symptoms: the command exists, the script says it doesn't​

The flow is the classic three-step Cloud Assistant pattern: CreateCommand for a CommandId, InvokeCommand to dispatch, DescribeInvocationResults to read back. Before invoking, the script checks the command object:

# existence probe (buggy)
resp=$(aliyun ecs DescribeCommands --CommandId.1 "c-xxx" 2>&1)
count=$(echo "$resp" | jq -r '.TotalCount // 0')
[ "$count" -eq 0 ] && aliyun ecs CreateCommand ... # judged missing → recreate

In practice this walked into the recreate branch on every run: the command was created in the previous round, yet judged missing in this one. Worse, invoking the freshly recreated CommandId could still hit InvalidCmdId.NotFound — the new object isn't ready yet, so both the probe and the recreate were wasted work. Left unfixed, the loop kept burning quota.

Root cause: errors exit 0, and jq washes them into defaults​

Two independent facts compose the trap. On the CLI side, API-level errors are printed to stderr while the process exit code stays 0 — exit-code-based defenses like set -e never fire. On the jq side, 2>&1 does carry the error JSON into the pipe, but the object has no TotalCount field, so the // 0 fallback helpfully outputs 0. "API call failed" has been laundered into "call succeeded, zero commands found."

--CommandId.1 is a third, smaller fact: the array-style suffix is the parameter habit of InvokeCommand --InstanceId.1, while DescribeCommands wants the singular --CommandId. The wrong form produces yet another error response, silently swallowed by the same fallback.

Fix: raw response first, jq without fallback probes​

The principle in one line: establish what the response is before asking what a field equals. In code, treat a missing TotalCount as failure instead of as zero:

resp=$(aliyun ecs DescribeCommands --CommandId "c-xxx" 2>&1)  # singular flag, capture stderr

# no TotalCount field = API-level failure: print raw and abort, no defaults
echo "$resp" | jq -e '.TotalCount' >/dev/null 2>&1 \
|| { echo "API call failed: $resp"; exit 1; }

count=$(echo "$resp" | jq -r '.TotalCount')
[ "$count" -eq 0 ] && aliyun ecs CreateCommand ... # only now is "missing" trustworthy

jq -e '.TotalCount' exits non-zero when the field is absent — it replaces // 0 by escalating "field not found" into an explicit failure. The raw response $resp prints alongside the error, so a human can tell a parameter mistake from a server-side error at a glance.

One boundary worth adding: a CommandId returned by CreateCommand doesn't guarantee the object is usable — invoke may still report InvalidCmdId.NotFound while DescribeCommands already counts TotalCount=1. So after recreating, verify existence before invoking; on NotFound, recreate — with the raw-response reading above, never with another fallback.

Reading results: nesting and the two IDs​

The read-back side has its own silent failures. DescribeInvocationResults nests objects inside objects; the correct path is:

jq -r '.Invocation.InvocationResults.InvocationResult[0].Output' \
<<< "$resp" | base64 -d

Writing it with array intuition as .InvocationResults[0] throws Cannot index object with number — the failure is in the accessor, and the data is already in the response. The other confusion source is the ID system: InvokeCommand returns an InvokeId (t- prefix), while DescribeInvocationResults only accepts a CommandId (c- prefix); if only the InvokeId is at hand, exchange it via DescribeInvocations --InvokeId first. When polling, terminal states are exactly Success and Failed, and results deserve a ~10-second wait after dispatch.

Cloud Assistant pitfalls travel in sets: dispatched content can get corrupted (heredoc assembly) and background jobs get killed (nohup) — see Aliyun RunCommand Corrupts Files? Ship base64, Not heredoc and Aliyun Assistant Kills nohup Jobs? Escape with setsid.

Notes

  • Always capture aliyun CLI calls with 2>&1 and judge the response text; the exit code is untrustworthy (errors also exit 0).
  • Never use jq // default as a failure probe — a missing field should fail loudly, not default to zero.
  • DescribeCommands takes singular --CommandId; the array-style .1 suffix belongs to InvokeCommand.
  • DescribeInvocationResults only accepts a CommandId; the path is .Invocation.InvocationResults.InvocationResult[0].

FAQ​

What should I watch out for when parsing aliyun CLI output with jq?​

The biggest trap is fallback defaults: jq -r '.TotalCount // 0' prints 0 on an error response instead of failing — error JSON goes to stderr with exit code 0, and when TotalCount is missing, the default washes the failure into a legitimate-looking empty result. Capture the raw response with 2>&1 and read it before applying jq, and never use a // default as a failure probe.

Why does the aliyun CLI return success even when the API call failed?​

The CLI prints API-level error JSON to stderr while the process exit code stays 0 — set -e and || exit never see it. Failure detection must be based on response content (error code / message fields), never on the exit code.

Why can't DescribeInvocationResults read my results?​

Two common causes. Wrong nesting: the result is an object inside an object, and the correct path is .Invocation.InvocationResults.InvocationResult[0] — the array-style .InvocationResults[0] throws Cannot index object with number even though the data is right there. Mixed IDs: DescribeInvocationResults only accepts a CommandId (c- prefix); if all you have is an InvokeId (t- prefix), exchange it first via DescribeInvocations --InvokeId.

CCLEE

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

Work with me

Aliyun RunCommand Corrupts Files? Ship base64, Not heredoc

· 5 min read

Inside an Aliyun Cloud Assistant RunCommand script, PHP files assembled with a quoted heredoc plus sed kept failing to parse on the instance — and every parse error landed on the line where the file says exit 1.

Encountered this while running managed hosting for a leading manufacturer's China site — RunCommand is the main channel for patrols and automated maintenance on that server.

TL;DR​

Two rules came out of this. First, never assemble complex code files inside the RunCommand script: generate locally, embed as base64, decode once on the instance — after the switch, two consecutive dispatches passed clean. Second, encode exactly once: --CommandContent is already base64-transported, and double-encoding the script fails with command not found (rc=127). The corruption trigger itself stays unidentified — exit 1 was the common marker of every failed file, but neither ! nor brace interpolation reproduces it alone.

Symptoms: RunCommand-dispatched files fail to parse at the exit 1 line​

The script's shape was assemble-on-instance, execute immediately:

cat > /tmp/check.php <<'EOF'
<?php
// …bail out when a condition fails
exit 1;
EOF
sed -i 's|placeholder|actual|' /tmp/check.php
wp eval-file /tmp/check.php

The result was a parse error, not the script's own business check:

PHP Parse error: unexpected integer "1"
# error position = the exit 1 line of each failing file

Three observations narrowed things fast: the parse position was exactly the exit 1 line every time; eval files without exit 1 in the same script parsed and ran fine; and running the identical heredoc+sed pipeline locally produced byte-perfect files. The damage lived only on the "dispatched via RunCommand, assembled on the instance" path — heredoc syntax itself was not the problem.

Detour: the trigger narrows, the mechanism never lands​

The first suspect was ! — history expansion and PHP's !function_exists both seemed plausible. Re-reading the execution record killed it: the very first failing script contained a heredoc with !function_exists that parsed and ran fine, so ! alone doesn't trigger anything. Interpolation braces went next; rewording {} didn't reproduce the corruption either.

After the eliminations, one common trait remained across every failing file: the exit 1 marker. But a shared trait is not a proven trigger, and going further would mean gambling on a mechanism. The operational call was to stop chasing it and change the path instead: move assembly back to the local machine and route around the unexplained corruption.

Fix: generate locally, embed base64, decode once​

All content generation moves local; the script keeps only decode-and-run:

# Local: generate the full file, encode it, paste into the script text
base64 -w0 check.php
# → one base64 line, goes into the B64 variable below
# RunCommand script: decode to disk, no on-instance assembly
B64='PGhwCi8v…'
echo "$B64" | base64 -d > /tmp/check.php
wp eval-file /tmp/check.php

Verification: after the switch, two follow-up dispatches (test-attachment cleanup and a probe script) both passed clean — no more parse errors.

The second pitfall is about encoding layers. CreateCommand receives --CommandContent as base64 — the caller encodes the script text once, the service decodes once and runs it. Encoding twice makes the server decode into another base64 string, which then gets executed as a script:

# Wrong: encoding the script body twice
base64 -w0 script.sh | base64 -w0 > doubled.txt
# CreateCommand --CommandContent "$(cat doubled.txt)"
# → server decodes once, executes base64 text → command not found, rc=127

Encode once. The base64 around embedded files is a separate layer (encoding of the file content) and has nothing to do with the script's own transport encoding.

Silent Cloud Assistant behavior doesn't stop here — once the invocation returns, background jobs started with nohup inside the script get cleaned up with the session; the fix is covered in Aliyun Assistant Kills nohup Jobs? Escape with setsid.

Notes

  • Complex code files: always generate locally and ship base64-embedded; keep on-instance heredoc+sed for simple config snippets only.
  • --CommandContent is encoded exactly once; double encoding fails with command not found (rc=127).
  • An unidentified mechanism means no safe boundary: don't treat "my content has no exit 1" as an exemption — avoiding the assembly path is the stable policy.
  • A Success result only means the script finished, not that background jobs it started are still alive.

FAQ​

Why is the same content fine locally but corrupted through Cloud Assistant?​

The only difference between the two paths is the on-instance assembly step: the same heredoc+sed pipeline produces byte-perfect files locally, while files assembled inside the RunCommand script get corrupted at the line carrying an exit 1 marker. The trigger is unidentified (! and brace interpolation alone don't reproduce it), but the avoidance rule is settled — don't assemble complex code files inside RunCommand scripts.

How should files be delivered through Cloud Assistant?​

Generate the full file content locally, base64-encode it, embed it in the RunCommand script, and decode once on the instance with base64 -d. After switching, two consecutive dispatches passed clean. Mind the encoding layers: --CommandContent is itself base64-transported, so the script body is encoded exactly once — double encoding fails with command not found (rc=127).

Can heredoc still be used inside RunCommand scripts?​

At the time, simple eval files without exit 1 in the same script parsed and ran fine; the corruption clustered around assembled PHP code files. But with the mechanism unidentified, the safe boundary can't be drawn — production scripts should avoid assembling code on the instance entirely and ship complex files as locally generated, base64-embedded payloads.

CCLEE

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

Work with me

Cert Alert Every Day? cPanel Keeps Stale Cert Generations

· 6 min read

A certificate expiry monitor reported the same service certificate at "20 days left" every single day, while a live port probe showed the certificate actually in service was valid until 2027-02-08 — the alert and reality were more than two years apart.

Tracked this down while running managed hosting for a leading manufacturer's China site — certificate expiry monitoring is a standing patrol item on that cPanel server.

TL;DR​

The root of the false alarm is "shortest days ≠ live certificate": cPanel's service certificate directory (/var/cpanel/ssl/system/certs/) accumulates past generations — multiple generations coexist, nothing prunes them. A monitor that scans PEM files one by one counts the expired-but-unreferenced old generation too, whose negative remaining days stay under the 21-day threshold forever, so the alert repeats daily. The path out: check the *-NOT_AFTER markers in the directory plus a live s_client probe to identify the live cert, delete the unreferenced stale generation (crt and .cache), and the alert heals on the next scan with services untouched.

Symptoms: the cert alert fires daily, the live certificate has two years left​

The alert reported the minimum remaining days across certificates: some service certificate expiring in 20 days, repeating daily — as if a certificate were simultaneously expired and about to expire, forever.

Checking the alert against reality didn't add up. Live probes across the four service ports (s_client, reading the presented certificate) all pointed to the same current-generation certificate: NOT_AFTER marker 1802123049, which converts to 2027-02-08. The "20 days left" certificate — a Let's Encrypt past generation issued September 11, expiring December 10 — was referenced by no service at all. Long expired, it had disturbed no online service, only the monitor.

Root cause: generations coexist, file scans don't follow references​

cPanel installs service certificates by accumulating them into system/certs/: each renewal or reissue adds a new generation, and older generations stay where they are. The directory therefore holds several generations at any time.

The monitor scans by PEM file sniffing: it reads each file and computes remaining days per file, without checking which service actually references which certificate. The hostname filter is substring-based — every generation of the same hostname shares the same CN, so the filter cannot separate live from expired. The oldest expired generation thus sits permanently below the 21-day alert threshold and gets reported every scan. The monitor wasn't lying — it faithfully reported the oldest file in the directory. What lied was the default assumption "shortest-days file = live certificate."

Fix: NOT_AFTER plus a live probe identify the live cert; delete unreferenced generations​

Four steps, evidence first:

# 1. Each certificate has a NOT_AFTER marker file beside it (epoch); check markers first
ls /var/cpanel/ssl/system/certs/
cat /var/cpanel/ssl/system/certs/*-NOT_AFTER
# live generation marker 1802123049 → date -r 1802123049 → 2027-02-08

# 2. Live port probe: what certificate does the service actually present?
openssl s_client -connect <hostname>:2083 </dev/null 2>/dev/null \
| openssl x509 -noout -enddate
# output must match the live NOT_AFTER marker
# 3. With markers and probe both saying "not in service" and no references: delete stale generation
rm /var/cpanel/ssl/system/certs/<stale-generation>.crt
rm /var/cpanel/ssl/system/certs/<stale-generation>.cache

# 4. Verify: services intact + alert cleared
openssl s_client -connect <hostname>:2083 </dev/null 2>/dev/null | head -1
openssl s_client -connect <hostname>:993 </dev/null 2>/dev/null | head -1

Result of the actual run (2026-11-22): services on 2083 and 993 unaffected after deletion, and the alert stopped repeating from the next scan — the shortest remaining days in the directory became the live certificate's true count, and the monitor's view re-aligned with reality. This "file-scan, conclusion-style alerting" patrol is part of CCLee Server Sentinel's certificate monitoring — alerts are merged into conclusions with handling guidance; for the issuance side of certificates (AutoSSL not issuing), see cPanel AutoSSL Not Issuing? Self-Signed Certificate Fix.

Notes

  • Order of judgment for certificate alerts: check NOT_AFTER markers and live port probes before any action — the shortest remaining days is not necessarily the live certificate.
  • Delete only confirmed-unreferenced files; the live certificate and its .cache stay.
  • After deletion, verify both ways: port probes intact, alert gone on the next scan — both required.
  • Multiple generations of the same hostname share the same CN; substring filters cannot separate them — don't rely on filters, check the markers.

FAQ​

A certificate expiry alert keeps firing every day — what should I do?​

Identify the live certificate before acting: check the *-NOT_AFTER marker files under /var/cpanel/ssl/ and probe the actual port certificate with s_client. In this incident the alert's '20 days left' came from a stale generation file, while the live certificate was valid until 2027-02-08. Once the alert target is confirmed as an unreferenced stale file, delete it (crt plus .cache) and the alert clears on the next scan — no certificate replacement needed.

How do I tell which certificate is the live one?​

Cross-check two sources: the *-NOT_AFTER marker files beside each certificate in the directory (epoch timestamps), and a live port probe (s_client reading the actual expiry). For the live certificate the two values agree. Filenames, issue dates, or the shortest remaining-days figure in a monitor are all unreliable — in this case the shortest 20 days belonged precisely to an unreferenced stale generation.

Will deleting old certificate generations disrupt live services?​

Delete only files confirmed to be unreferenced (the crt and its .cache); leave the live certificate untouched. After the deletion, services on ports 2083 and 993 were unaffected and the alert cleared on the next scan. The precondition is evidence first: both the NOT_AFTER marker and the live probe must point to 'not in service' before deleting.

CCLEE

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

Work with me

cPanel Crash Loop? mycpanel.pem Needs Cert + Key in One File

· 6 min read

After a deploy script replaced the cPanel service certificate, cpanel.service fell into a crash loop: nothing listening on 2083/2087, and both WHM and cPanel were unreachable.

Encountered this while running managed hosting for a leading manufacturer's China site — an ongoing engagement covering monitoring, backups, and certificate deployment on a production cPanel/WHM server.

TL;DR​

One cause: /var/cpanel/ssl/cpanel/mycpanel.pem must be a single PEM combining the leaf certificate and the private key (the same shape as the pure-ftpd bundle), with the chain in mycpanel.cabundle; the split crt/key formats used by dovecot/exim are not interchangeable, and writing a fullchain into the pem is exactly the crashing form. A second trap sits in verification: restartsrv_cpsrvd exit 0 and an active unit mean nothing — SSL setup fails 1-6 seconds after start, so recovery is proven on port 2083.

Symptoms: panel down, service crash loop​

Right after writing the new certificate and restarting, the panel hostname stopped responding and both 2083/2087 had no listener. The journal and error_log show two faces of the same failure:

cpanel.service: Main process exited, status=25
cpsrvd: Failed to load SSL libraries or certificate from
/var/cpanel/ssl/cpanel/ at cpsrvd.pl line 724

The standard recovery path came first: restartsrv_cpsrvd returned 0 and systemctl is-active cpanel reported active — it looked recovered. Seconds later 2083 was still silent and the panel still unreachable, crash loop intact. Those two green lights that aren't green are the second topic of this post.

Root cause: mycpanel.pem is cert + key combined, not the chain​

cPanel's format requirement for cpsrvd (the panel service) differs from most services: mycpanel.pem holds the leaf certificate and private key combined, while the chain lives separately in mycpanel.cabundle. That matches the pure-ftpd bundle shape; dovecot/exim use split crt/key files — the three formats are not interchangeable:

ServiceCertificate file shape
cpsrvd (cPanel/WHM panel)mycpanel.pem combined (leaf+key) + mycpanel.cabundle (chain)
pure-ftpdcombined bundle (same shape as cpsrvd)
dovecot / eximsplit crt/key

The failing script wrote a fullchain — chain only, no private key — into mycpanel.pem. At startup cpsrvd loads SSL, finds no private key, and fails at cpsrvd.pl line 724; systemd starts the unit, the process exits immediately, status 25, and the cycle repeats. The certificate itself was fine; only the file shape was wrong.

One distinction worth making: this is the cPanel service certificate (hostname-level, serving the panel ports). Site domain certificates go through AutoSSL — a separate track; when issuance stalls there, check the exclusion list first, see cPanel AutoSSL Not Issuing? Self-Signed Certificate Fix.

The false-success detour: restartsrv exit 0 ≠ cpsrvd alive​

Timing is what makes this misleading. SSL setup fails 1-6 seconds after systemd starts the unit, while restartsrv_cpsrvd returned its 0 at start-up time and is-active sampled the pre-crash window — both signals landed before the crash, so both were green.

That pair of green lights is exactly what the triage trusted first: recovery declared on restartsrv 0 + active, then the panel still down, and only a direct curl against 2083 exposed the SSL load failure. Since then, liveness for cpsrvd on this server is judged only by port probes: curl -sv https://hostname:2083 or openssl s_client -connect hostname:2083, requiring a completed handshake with certificate details.

"State signal disconnected from actual usability" is not an one-off — the reverse variant, systemctl showing inactive while the process runs, is covered in systemctl Shows inactive But the Process Is Running? Bare-Process Health Check False Negative. The shared conclusion: probe the service through its own port/protocol, not through the process manager's word.

Fix: write per-service formats, verify on the port​

The repair is three steps: combined PEM in place, chain separated, acceptance on the port.

# leaf.pem = server certificate (leaf), privkey.pem = private key, cabundle.pem = chain
cat leaf.pem privkey.pem > /var/cpanel/ssl/cpanel/mycpanel.pem
cp cabundle.pem /var/cpanel/ssl/cpanel/mycpanel.cabundle
chown cpanel:cpanel /var/cpanel/ssl/cpanel/mycpanel*
chmod 660 /var/cpanel/ssl/cpanel/mycpanel*
systemctl restart cpanel

Acceptance ignores status signals and reads the port only:

curl -sv https://<hostname>:2083 -o /dev/null 2>&1 | grep -E 'subject|expire'
curl -sv https://<hostname>:2087 -o /dev/null 2>&1 | grep -E 'subject|expire'

Both commands must print the certificate subject and expiry before the panel ports count as recovered. After this incident the deploy script fixed the combined format in place and gained an end-to-end check: the hook prints DEPLOY-OK with all four service ports green.

For the other services, match the table above: dovecot/exim get split crt/key, pure-ftpd and cpsrvd get combined bundles. One certificate, three file shapes, none interchangeable.

Notes

  • Content order in mycpanel.pem: leaf certificate first, private key after; the chain goes into mycpanel.cabundle, never into the pem.
  • Permissions cpanel:cpanel 660 — too wide or too narrow, cpsrvd may refuse to load.
  • Acceptance is port probes only; restartsrv's exit code and is-active are not liveness evidence.
  • More AlmaLinux 10 + cPanel close-out pitfalls (TFA, missing resources, domain mounting): AlmaLinux 10 + cPanel: New-Server Pitfalls from TFA to DNS.

FAQ​

What goes in mycpanel.pem vs mycpanel.cabundle?​

mycpanel.pem is one PEM holding the leaf certificate followed by the private key, owned cpanel:cpanel with 660 permissions; the intermediate chain goes separately into mycpanel.cabundle. Writing a fullchain into mycpanel.pem produces exactly this crash — no private key in the file, cpsrvd fails SSL loading, and systemd reports status=25 in a loop.

Can the dovecot/exim certificate files be reused for cpsrvd?​

Not directly. cpsrvd expects a combined PEM (the same shape as the pure-ftpd bundle), while dovecot/exim use separate crt/key files — the formats are not interchangeable across the services. The same certificate must be written out in each service's own format.

restartsrv returned 0 and systemctl says active — is cpsrvd really alive?​

Neither signal is a liveness proof: SSL setup failed 1-6 seconds after systemd started the unit, long after restartsrv printed its exit 0, and is-active still showed active in that window. Probe port 2083 instead (curl -sv or openssl s_client); a completed TLS handshake is the only evidence that counts.

CCLEE

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

Work with me

Postgres Lateral Can't See the UPDATE Target? Use a CTE

· 7 min read

In a migration pipeline for a Node.js + PostgreSQL service, a data-migration SQL using UPDATE ... FROM lateral was rejected by psql with a clear error; the same file handed to drizzle-kit migrate failed silently — exit 1, with nothing but two unrelated NOTICEs in the output.

TL;DR​

The UPDATE/DELETE target table has zero visibility inside a lateral: top-level references fail, nested ones fail too — the SELECT intuition that "a lateral sees earlier FROM items" simply does not apply here. psql states the error plainly, while drizzle-kit (postgres-js driver) swallows it into a silent exit, which left a dev database's migration ledger three versions behind. Fix: rewrite every correlated reference to the target table as a CTE with correlated subqueries, and verify complex migrations with psql -v ON_ERROR_STOP=1 before they reach the toolchain.

Symptoms: psql speaks up, drizzle-kit says nothing​

The same migration file, two execution paths, opposite behavior: psql shows the error, drizzle-kit fails quietly.

The psql-side error, verbatim:

ERROR:  invalid reference to FROM-clause entry for table "t"
LINE 1: ... UPDATE tenants AS t SET settings = t.settings FROM lateral (SELECT t.settings ...
^
HINT: There is an entry for table "t", but it cannot be referenced from this part of the query.

The first instinct was "the reference is written wrong": move the target-table reference into the lateral's select list — still rejected; wrap it one level deeper in a scalar subquery — the same error again. Two edits died on the same sentence, which is what forced a change of direction: this is not about where you place the reference. Search phrasing for the same problem varies — "postgres update from lateral", "lateral reference to the outer update table" — all pointing at the same semantic gap.

The drizzle-kit side was worse: pnpm db:migrate exited 1 on the same file, stderr holding only two unrelated NOTICEs, no error message at all. The dev database's migration ledger stayed at 0027, three later migrations never applied, and tenant settings were missing the new keys — no alert anywhere in the process.

For why migration ledgers fall behind silently and how to reconcile them at deploy time, see drizzle-kit migrate: table missing? Journal silently skipped — same lesson: never trust a green tool alone.

Root cause: the lateral has zero visibility into the UPDATE target​

The conclusion, stated hard: the UPDATE/DELETE target table cannot be referenced from a lateral at any position — not "only at the top level", but nowhere.

In SELECT, a lateral sees the FROM items before it; carried over to UPDATE ... FROM, that intuition breaks: Postgres removes the target table from the lateral's visible set entirely in UPDATE/DELETE context. The HINT says it all — the entry exists, but it cannot be referenced from this part of the query, and both the top level and nested levels count as "this part". That is exactly why moving the reference into the select list still failed: no legal position exists.

A minimal reproduction on PG 16 (temp tables suffice; both variants fail with the identical message):

BEGIN;
CREATE TEMP TABLE t0 (id int PRIMARY KEY, settings jsonb);
INSERT INTO t0 VALUES (1, '{"a":"1","b":"2"}');

-- Variant A: lateral top level references target t → rejected
UPDATE t0 AS t
SET settings = t.settings
FROM lateral (SELECT t.settings->>'a' AS va) x
WHERE t.id = 1;
-- ERROR: invalid reference to FROM-clause entry for table "t"

-- Variant B: one nested scalar subquery to "relay" the value → same error
UPDATE t0 AS t
SET settings = t.settings
FROM lateral (SELECT (SELECT t.settings->>'b') AS vb) x
WHERE t.id = 1;
ROLLBACK;

Of the two failure sources, the drizzle-kit half is the more dangerous: swallowed error → no logs → dev state lags indefinitely with no alert. The psql half at least says something every time.

Fix: move correlated reads into a CTE​

Put the reads of the target table into a plain CTE and let UPDATE ... FROM do a key join only — semantically equivalent to the original lateral intent, with no reference-position restrictions. This is the final shape of that 0029 migration:

WITH src AS (
SELECT id,
settings->>'daily_remind' AS v1,
settings->>'daily_remind_at' AS v2
FROM tenants
WHERE settings ? 'daily_remind'
)
UPDATE tenants AS t
SET settings = t.settings || jsonb_build_object('remind_time', src.v2)
FROM src
WHERE t.id = src.id;

The CTE is an ordinary SELECT — no restrictions on referencing the target table; UPDATE ... FROM src does an equality join only.

The matching minimal check (PG 16, fully self-contained — the previous block's temp table was rolled back, this one rebuilds it):

BEGIN;
CREATE TEMP TABLE t0 (id int PRIMARY KEY, settings jsonb);
INSERT INTO t0 VALUES (1, '{"a":"1","b":"2"}');

WITH src AS (
SELECT id, settings->>'a' AS va
FROM t0
WHERE settings->>'a' IS NOT NULL
)
UPDATE t0 AS t
SET settings = t.settings || jsonb_build_object('a_cte', src.va)
FROM src
WHERE t.id = src.id;
-- UPDATE 1
ROLLBACK;

Three verification passes after the rewrite: the same file verified through both the pg 8.16 node driver and psql; applied twice to the dev database — UPDATE 3 the first run, UPDATE 0 the second — idempotent; ledger reconciled after backfilling, __drizzle_migrations count equal to the migration file count.

Before you ship

  • The SELECT lateral intuition does not carry to UPDATE/DELETE FROM: rewrite correlated references to the target as CTE + correlated subqueries, never lateral.
  • Verify complex data migrations with dev psql -v ON_ERROR_STOP=1 before they reach the drizzle-kit toolchain — never trust a green tool alone.
  • After drizzle-kit migrations, reconcile the ledger count against the file count routinely; a "done" with no output counts as a failure.

FAQs​

What does 'invalid reference to FROM-clause entry for table' mean in Postgres?​

A FROM entry exists but can't be referenced from where you used it. The classic trigger: a lateral subquery in UPDATE/DELETE FROM referencing the target table — Postgres rejects every position, top level included (verified on PG 16); the HINT says cannot be referenced from this part of the query. Other common causes are join order or alias scope mistakes.

Can a lateral subquery reference the UPDATE target table in Postgres?​

No — not at any position. Unlike SELECT, where a lateral sees earlier FROM items, UPDATE and DELETE give the lateral zero visibility into the target table at any nesting depth (PG 16 verified, top level included). Move the correlated reads into a CTE and join by key.

Why does drizzle-kit migrate fail with no error output?​

The postgres-js driver swallows the error: exit 1 with nothing but two unrelated NOTICEs on stderr. It once left a dev database stuck three migrations behind with no alert. Run complex SQL through psql -v ON_ERROR_STOP=1 first.

What is the correct rewrite for UPDATE FROM lateral?​

A CTE joined by key: WITH src AS (SELECT id, settings->>'k' AS v FROM target) UPDATE target t SET ... FROM src WHERE t.id = src.id. The CTE is a plain SELECT with no reference restrictions; verified on PG 16 with UPDATE 1, and idempotent as UPDATE 3 then UPDATE 0 on a real migration.

CCLEE

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

Work with me

Does rsync -a Preserve Timestamps? Why Fresh Backups Vanish

· 8 min read

In a cron-driven rsync-plus-find backup pipeline that keeps 7 days of upload snapshots by directory name, the pull script ran fine by hand but, once scheduled, three consecutive snapshot directories showed files = 0 — the files landed, then vanished.

TL;DR​

The a in rsync -a (archive) propagates the source's mtimes to the target, directories included — the target directory's mtime means "when the source last changed", never "when this pull finished". If the source's top-level directory is frozen (new files only land in deep subdirectories), that value stays in the past, and a trailing find -mtime +7 cleanup judges the just-pulled snapshot "7 days old" and deletes the whole directory. "Manual runs always work, cron always fails" is a false correlation: manual testing only ever runs the rsync line, never the cleanup. Fix: judge retention by directory-name dates, and record pull completion in a marker file's mtime.

Symptoms: fresh snapshots vanish​

The scheduled pipeline's signature is "pulled, then deleted": the snapshot directory exists with no transport errors in the logs, yet files = 0; run the same script by hand and every file is there. Three runs in a row.

The usual suspects were eliminated one by one: CRLF line endings, fd handling around flock, disk space, cron-vs-terminal environment differences, execution shape (an inline heredoc one-liner vs the script file) — all negative. Along the way a strong false correlation formed: "the script always fails, the inline version always works", and the investigation chased execution shapes for two loops.

The turn came from strace: in the failing runs the transfer was complete — the directory tree's mkdir calls and the jpg bytes landing were all on record. In other words rsync finished its job and the files disappeared afterwards. Moving attention from "the transfer" to "which line runs after the transfer" surfaced the cleanup line at the bottom of the script.

The database side of this same pipeline has a sibling pitfall: pg_dump backups with no data? FORCE RLS binds owners too — the same "command exits normally, content is empty" shape.

Root cause: rsync -a resets the target's mtimes​

The cleanup didn't delete "files that never arrived" — it deleted "directories judged old", because the retention check read the wrong clock. Three links chained; remove any one and nothing happens:

Link 1: -a preserves the source's timestamps, directories included. -a equals -rlptgoD; -t preserves mtimes and -r recurses. After the sync, the target tree's mtime = the source's directory mtime, and the moment "this pull finished" is recorded nowhere in the synced paths.

Link 2: the source's top-level directory mtime is frozen. New attachments all land in deep subdirectories, so uploads/ itself hasn't changed since Oct 30. Every snapshot inherits that same stale value at its top level.

Link 3: the retention check find -mtime +7. Today is Nov 23; the snapshot's top-level mtime is Oct 30 — 24 days apart, beyond the 7-day retention. -mtime +7 matches, and the directory is deleted. Every run: pulled, then deleted.

Root-cause chain: rsync -a carries the source&#39;s frozen mtime to the target, and find -mtime +7 judges the fresh snapshot stale

"Inline always works" falls out of the same chain: inline testing only ever runs the transfer lines and never the cleanup, so it cannot fail — the real difference from the script is not execution shape but whether the find line runs.

A minimal reproduction shows who decides the mtime:

mkdir -p /tmp/demo/src/uploads/2026-11-23
echo x > /tmp/demo/src/uploads/2026-11-23/a.jpg
touch -d '2026-10-30' /tmp/demo/src/uploads # freeze the top level

mkdir -p /tmp/demo/dst
rsync -a /tmp/demo/src/uploads /tmp/demo/dst/snap

stat -c '%y %n' /tmp/demo/dst/snap # 2026-10-30 ← inherited
find /tmp/demo/dst -maxdepth 1 -type d -mtime +7 -print
# → /tmp/demo/dst/snap ← exactly what the cleanup deletes

Fix: judge retention by directory names, mark completion with a file​

The fix replaces the clock the retention check reads — not mtime but the date in the directory name; and "when this pull finished" gets its own record in a marker file the sync never touches.

# Retention: compare directory-name dates (ISO order == lexicographic order)
cutoff=$(date -d '7 days ago' +%Y-%m-%d)
for d in /data/snapshots/20*-*-*; do
name=$(basename "$d")
[[ "$name" < "$cutoff" ]] && rm -rf "$d"
done

# Completion time: touch a marker after the pull; later checks read its mtime
rsync -a "$SRC_HOST:uploads/" "$SNAP_DIR/"
touch "$SNAP_DIR/.pull-complete"
# How long since completion: stat -c %Y "$SNAP_DIR/.pull-complete"

The two clocks have separate jobs: directory-name dates answer "should this snapshot be kept", the marker's mtime answers "how long has this pull been running, is it stuck". Both avoid the mtime that rsync writes, because that field means "when the source changed", not "when I pulled".

After the fix landed in those two places, the cron runs stopped showing files = 0.

Scenario 2: root gets Permission denied on /tmp lock files? fs.protected_regular​

Even root gets rejected: on the same box, root opening an existing lock file with open(O_CREAT) in /tmp — a file owned by someone else — fails with EACCES. Ubuntu's fs.protected_regular applies to sticky directories and root has no exemption. Put lock and swap files in /run, not /tmp.

Scenario 3: can't find the rsync read-only restriction? It's on the dedicated transfer user​

Nothing shows up on the usual login account because the restriction lives in the command= option of authorized_keys for a dedicated transfer user (rrsync). When auditing ssh restrictions, first work out which user a key belongs to, then read that user's authorized_keys.

On rsync 3.2.7, a --link-dest pointing at a nonexistent path only prints a warning and still exits 0 — not fatal, but the hard-link space saving silently disappears for that run. Check the link-dest target exists before running, or alert on the warning.

Scenario 5: grep $'\r' always matches over ssh? A false positive from nested quoting​

Detecting CRLF remotely with grep -c $'\r' fails under nested quoting: by the time it reaches the remote shell, $'\r' is treated as a plain pattern and matches everything. Detect CR with awk '/\r/' instead.

Before you ship

  • For any retention / cleanup / cooldown check, avoid fields the transfer tool rewrites: -a resets directory mtimes — judge by directory-name dates or a completion marker.
  • Dry-run handwritten cleanups with -print for a few rounds before switching to -delete.
  • The --link-dest target must exist; 3.2.7 only warns and exits 0 on a dangling path.
  • Put lock and swap files in /run to stay clear of /tmp's fs.protected_regular.

FAQs​

Does rsync -a preserve timestamps?​

Yes. -a equals -rlptgoD: -t preserves mtimes and -r recurses, so directory mtimes are carried over from the source as well. The target's mtime means "when the source last changed", not "when this pull happened" — record the pull time in a marker file instead.

How do I delete files older than 7 days with find safely?​

find /dir -mtime +7 is the usual one-liner, but never key a retention policy on mtimes that rsync controls — a pull with -a rewrites them. Compare zero-padded directory-name dates or a completion marker's timestamp, and verify the hit set with -print before switching to -delete.

Why does my cron rsync job produce empty backup directories?​

In this failure the transfer itself completed every run (strace showed the full tree and jpgs landing), but a trailing find -mtime +7 cleanup deleted the just-pulled snapshot — three consecutive runs showed files = 0. Separate the transfer from the cleanup and log the cleanup decision.

What should I use instead of mtime for backup retention?​

Directory-name dates (ISO format compares lexicographically) or a .pull-complete marker touched after each pull, read back with stat. Neither is rewritten by rsync -a; the same rule applies to row-count style checks — don't rely on fields the transfer tool overwrites.

CCLEE

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

Work with me

Bash 3.2 + set -u: Which Empty Array Expansions Crash?

· 6 min read

The same backup restore-drill script runs on schedule on the production server every day; run it under local regression testing and it dies on one arithmetic line with nothing but unbound variable — no status file, no log entry.

Ran into this while building CCLee Server Sentinel — monitoring and alerting for Linux servers: performance, availability, security and backup. Alerts arrive as conclusions with next steps, and backups are proven restorable by monthly real-restore drills.

TL;DR​

Under set -u, bash 3.2 (macOS's /bin/bash) and bash 5.x disagree about which expansions of an empty array or an undefined name count as "unset" — and only one crash site spans every version. Tested live on bash 3.2.57 and 5.3.20, six combinations:

Expressionbash 3.2 (macOS system)bash 5.x (brew / modern Linux)
Empty-array word expansion ${arr[@]} (quoted or not)crashes with unboundfine
Empty-array arithmetic $(( ${#arr[@]} ))fine (yields 0)fine
Undefined name in arithmetic $(( ${#undef[@]} ))crashescrashes

Two guards, one per site: write word expansions as ${arr[@]+"${arr[@]}"} (covers 3.2's empty-array crash), and wrap arithmetic in $( set +u; echo $(( … )) ) (covers the everywhere-fatal undefined-name crash).

Symptom: dead on the arithmetic line, no status file, no log​

The script runs set -u, and its first real statement counts the drill targets:

# pre-fix shape (same structure as the crash site)
EXPECTED=$(( ${#DRILL_DUMPS[@]} + ${#TAR_FILES[@]} ))

DRILL_DUMPS / TAR_FILES come from a config renderer: a list section that exists renders an array assignment; one that doesn't, renders nothing. The conf used for local regression happened to miss a section, so one of the two variables never existed — the script exited right there with unbound variable. No drill status JSON, nothing in the log, and 22 regression assertions failing with zero output — which looks exactly like the script-under-test being broken.

The confusing part: the same script produced results on production TencentOS daily. "Fine in production, dead locally" — the difference was not the script but the local bash version.

Root cause: bash 3.2 and 5.x distribute the crash sites differently​

macOS ships /bin/bash frozen at 3.2.57 (the 2007 GPLv2 release), while Homebrew and modern Linux distributions carry 5.x. Under set -u (nounset), which expansions count as "unset" differs between generations. All of the following is live terminal output:

$ /bin/bash --version | head -1
GNU bash, version 3.2.57(1)-release (arm64-apple-darwin26)

$ /bin/bash -uc 'arr=(); for x in ${arr[@]}; do echo $x; done'
bash: arr[@]: unbound variable

$ /bin/bash -uc 'arr=(); for x in "${arr[@]}"; do echo $x; done' # quoted crashes too
bash: arr[@]: unbound variable

$ /bin/bash -uc 'arr=(); echo $(( ${#arr[@]} ))' # arithmetic length is fine
0

$ /bin/bash -uc 'echo $(( ${#undef[@]} ))' # undefined: arithmetic crashes
bash: undef: unbound variable

$ /opt/homebrew/bin/bash -uc 'arr=(); for x in ${arr[@]}; do echo $x; done; echo done'
done # 5.3: empty-array expansion is fine

$ /opt/homebrew/bin/bash -uc 'echo $(( ${#undef[@]} ))'
bash: undef: unbound variable # undefined: 5.3 crashes the same way

Note the second case: quoting does not exempt it. The common belief that "${arr[@]}" is the safe form does not hold on 3.2 under set -u. Meanwhile the empty-array arithmetic length never crashes on either generation; the only everywhere-fatal site is an undefined name in arithmetic (bash: undef: unbound variable — notice the error names undef, not undef[@]).

One wrong turn worth recording: the first suspect was the script's own logic, and changing it fixed nothing. The contrast with "works in production" is what redirected the investigation toward the version difference — the same variable reference is "unset" to 3.2 and "empty" to 5.x.

The guards: one convention per crash site​

Word expansions — ${arr[@]+"${arr[@]}"} means "expand to the element list only if the array is defined; otherwise expand to nothing". This is the +-test form of parameter expansion: it tests before expanding, so 3.2 never reports unbound. Every array loop in the drill script uses this shape:

for pair in ${DRILL_DUMPS[@]+"${DRILL_DUMPS[@]}"}; do

Arithmetic — the ${#arr[@]} length form cannot take the +-test, and the undefined-name crash affects every bash version, so wrap the expression in a subshell that locally drops -u:

EXPECTED=$( set +u; echo $(( ${#DRILL_DUMPS[@]} + ${#TAR_FILES[@]} )) )   # set +u:bash3.2 空数组保护

The set +u applies inside the subshell only — the rest of the script keeps strict mode. An undefined name becomes 0 in the arithmetic, which is the correct semantics for counting drill targets; if your expression must distinguish "undefined" from "zero", this guard does not apply and you need an explicit emptiness check.

The same "fine in the terminal, dead in a script" family has another member: grep -P works in the terminal but dies in the script? zsh and bash don't share PATH — different root cause (two PATHs for interactive vs. script shells), same symptom family.

Watch out

  • Two stub-environment traps in the same family: on macOS, date lives at /bin/date — /usr/bin/date does not exist, so tooling that hardcodes the latter fails to find the command.
  • printf '%d' silently emits 0 for an empty value: tested on bash 3.2.57, printf '%d\n' "" prints 0 and exits 0 with no error at all. When asserting numeric fields like last_ok_epoch or epoch, a 0 may be an empty value swallowed by printf, not a real value — check the true source.
  • When regression and production run different bash versions, "the test passed" is not "production behaves this way"; either apply both guards everywhere or align versions first with bash --version.

FAQ​

Why does bash report 'unbound variable' for an empty array?​

Under set -u, bash 3.2 (the /bin/bash shipped with macOS) treats any expansion of an empty array — ${arr[@]} or "${arr[@]}" — as referencing an unset variable. Bash 4.4 and newer allow it. The ${#arr[@]} length form does not crash; an undefined name in arithmetic does, on every version.

How do I protect a bash script against empty arrays under set -u?​

Two guards, one per crash site. For word expansions use ${arr[@]+"${arr[@]}"} — expand only when the array is defined. For arithmetic wrap the expression in $( set +u; echo $(( … )) ), which also covers the undefined-name crash that affects every bash version.

Why does the same script behave differently on macOS and Linux?​

macOS ships /bin/bash 3.2.57 from 2007; Linux distributions ship 4.4+ (commonly 5.x). Bash 4.4 relaxed the empty-array behavior under set -u. Install bash 5.x via Homebrew to get Linux-identical behavior for local testing.

CCLEE

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

Work with me

Postgres Table Count 0=0? Schema Is Not the Database Name

· 7 min read

While adding a table-count comparison to our restore-drill script, the source and temp databases both reported 0 tables — 0=0, verdict "pass" — while a manual count of the same database showed 25 tables.

Ran into this while building CCLee Server Sentinel — monitoring and alerting for Linux servers: performance, availability, security and backup. Alerts arrive as conclusions with next steps, and backups are proven restorable by monthly real-restore drills.

TL;DR​

In PostgreSQL, information_schema.tables' table_schema column holds the namespace inside the current database — tables live in public by default — not the database name. Counting a database's tables requires connecting to that database first (psql -d dbname) and counting public. Our drill script got both wrong at once: it queried the database name as the schema and hardcoded -d postgres (the maintenance database), so every count was 0 and two equal zeros always "passed". After the fix, a real drill ran 25=25.

Symptom: the table-count check is a permanent 0=0 pass​

The drill's status file recorded per_db as "app_db:0:0" — source database 0 tables, temp database 0 tables, counts equal, status reported ok. That was the script's first real run on 2026-11-22.

The contradiction was already two days old: the manual drill on 2026-11-20 had counted 25 tables in the same imported copy. In other words, the script-side table-count comparison had never touched a real value — even if half the tables had gone missing during import, 0=0 still holds and the check still passes. A count of 0 on both sides is a check with a permanently green light.

Root cause: table_schema is not the database name, and psql connected to the wrong database​

Two bugs stacked — either alone breaks the count; together they make source and temp databases wrong in the same direction, which removes the comparison's ability to detect any difference.

First: the database name was used as the schema. PostgreSQL's hierarchy is database → schema (namespace) → table, and application tables land in the public namespace by default. The table_schema column of information_schema.tables stores the namespace name. Matching a database name against table_schema asks "is there a namespace named app_db" — always an empty set, so COUNT returns 0.

Second: the connection was hardcoded to the maintenance database. Every PostgreSQL instance ships with a default maintenance database named postgres. The old code pinned -d postgres, so the query ran against the maintenance database — and information_schema only shows the contents of the currently connected database.

The pre-fix db_count:

db_count(){  # $1=engine $2=container $3=user $4=schema → 表数(对正式库只读 COUNT,不改数据)
local sql="SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$4'"
if [ -n "$2" ]; then
case "$1" in
postgres) docker exec "$2" psql -U "$3" -d postgres -t -A -c "$sql" ;;
mysql) docker exec "$2" mysql -u "$3" -N -B -e "$sql" ;;
esac
else
mysql -N -B -e "$sql"
fi
}

The call site runs it once per database:

src=$(db_count "$engine" "$container" "$u" "$db")    # source tables
dst=$(db_count "$engine" "$container" "$u" "$tmp") # temp drill tables

Both calls go through the same function and make the same mistake, so src=0 and dst=0, and 0=0 passes.

Why MySQL never hits this​

In MySQL, schema and database are synonyms: CREATE DATABASE and CREATE SCHEMA are equivalent, and information_schema.tables is visible across the whole instance, so WHERE table_schema='dbname' is simply correct. This script supports both engines, and the MySQL semantics were carried into the PostgreSQL branch without a second look — inside one function, $4 meant two different things.

The fixed version branches by engine:

db_count(){  # $4 在 postgres 语义是目标库名,在 mysql 语义是 schema(=库名)
if [ -n "$2" ]; then
case "$1" in
postgres) docker exec "$2" psql -U "$3" -d "$4" -t -A -c \
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public'" ;;
mysql) docker exec "$2" mysql -u "$3" -N -B -e \
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$4'" ;;
esac
else
mysql -N -B -e "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='$4'"
fi
}

The postgres branch changes two things: -d "$4" connects to the target database itself, and table_schema='public' counts the default namespace. The MySQL branch is untouched.

Why the regression tests stayed green: the stub mirrored the bug​

The script ships with a 22-assertion regression suite, and it was green the whole time — because the test stub was written to match the implementation's wrong semantics. The old stub parsed the table_schema='...' value out of the SQL and used it as a lookup key: however the implementation queried, the stub answered. Implementation and stub shared the same wrong assumption, so the test had nothing to catch.

# before: the stub answered by the caller's query semantics — argument used as schema
sch=$(printf '%s' "$sql" | sed -E "s/.*table_schema='([^']*)'.*/\1/")
cat "$ST/count.$sch" 2>/dev/null || echo 0

# after: the stub answers by the -d target database (matching real psql behavior)
cat "$ST/count.$tgt" 2>/dev/null || echo 0

The lesson: a stub should simulate the real contract of the external system (what information_schema returns after psql -d somedb), not copy the caller's query code. The moment a stub copies the implementation, the test only proves the implementation agrees with its own shadow.

Fix: connect to the target database and count public​

The fix was two moves: correct db_count's postgres branch (shown above), and correct the stub's lookup in the same commit. All 22 assertions stayed green, then a real drill re-ran on the client machine — this time per_db recorded app_db:25:25 (drill_date=2026-11-21), the first time the comparison touched real values.

Silent failure modes on a backup chain rarely come alone: the backup file itself can come out empty — PostgreSQL's FORCE RLS stops even the owner session's COPY, producing an archive that "looks fine". That pitfall and its fix are in Postgres pg_dump backs up no data? FORCE RLS blocks the owner too. For the cleanup side of information_schema.tables, see PostgreSQL left orphan tables after migration? Audit schema residue with information_schema.

Watch out

  • ON_ERROR_STOP=1 only catches import-time errors; "no errors on import" does not mean the content is intact. Table counts are the floor — row counts and sample queries against business tables cover actual data damage.
  • The same mistake recurs in disguise: filtering pg_tables by database name as schemaname, or pg_class by database name as namespace, also yields an empty set. The rule is simple — in PostgreSQL these columns mean namespace, and the database name only belongs in -d (which database to connect to).

FAQ​

How do I count tables in a PostgreSQL database?​

Connect to that database itself (psql -d dbname), then run SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='public'. table_schema holds the namespace name (public by default), not the database name. Running the query from another database cannot see the target database's tables.

What does table_schema mean in information_schema.tables?​

In PostgreSQL it is the namespace inside the currently connected database — tables land in public by default. It is never the database name. In MySQL the two coincide, which is why the same SQL means different things across engines.

How often should you test your database backups?​

Run a real restore drill at least monthly: import the dump into a scratch database and verify the result. Comparing table counts is the floor; row counts and sample queries go further. A backup file that merely exists is not a verified backup.

CCLEE

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

Work with me

sqlite3 Writes Vanish After close()? Python Never Committed

· 5 min read

During a shadow-mode observation window, metric samples from two freshly installed machines kept landing in the database every cycle — yet the state table's updated_at stayed frozen at the installation moment. None of the state-machine transitions ever reached disk, for two straight days.

Ran into this while building CCLee Server Sentinel — monitoring and alerting for Linux servers: performance, availability, security and backup. Alerts arrive as conclusions with next steps, and backups are proven restorable by monthly real-restore drills.

TL;DR​

Python's sqlite3 with the default isolation_level="" (deferred mode) opens a transaction implicitly on the first write statement — and close() only closes the connection, it does not commit. The uncommitted transaction rolls back when the connection closes. The treacherous shape is "some tables live, some die": within a single run, write paths that end with conn.commit() persist, paths that miss it roll back. The fix is one line: conn.commit() before close().

Symptom: samples keep landing, state table frozen at install time​

Shadow mode (dry_run) is the 48-hour baseline window after a new install: collection, writes and state-machine evaluation all run normally; only outbound push is suppressed. Watching two new machines produced a contradictory pair:

  • the samples table gained a row every 5 minutes — the collection path was alive;
  • the state table's updated_at stuck at 10:53 / 10:55 on installation day, even though the state machine was evaluating transitions (the alerting count should have moved).

"data was written" and "data was not written" held at the same time in the same run. That is not a classic write failure (an error, a lost batch) — it is a per-path rollback.

Root cause: close() does not commit for you​

With the default isolation_level="", Python's sqlite3 runs deferred transactions: the first write statement opens a BEGIN implicitly, and every subsequent write hangs on that one uncommitted transaction. close() means "close the connection" — committing is not its job; at close, the pending transaction rolls back.

In the code, two paths diverged:

def insert_samples(conn, samples, ts_iso, epoch):
conn.executemany("INSERT INTO samples (…) VALUES (…)", rows)
...
conn.commit() # ← commits at the end: samples survive every cycle
# the dry_run branch of do_check (pre-fix)
for rule_name, st in new_state.items():
state_save(conn, rule_name, st, now_iso) # writes state, no commit

if cfg.get("dry_run"):
LOG.info("[dry_run] %d samples, %d events", ...)
...
conn.close() # ← closes directly: this cycle's state writes roll back
return 0

The non-dry_run branch commits before closing — which is why only the shadow-mode state writes rolled back, and why the freeze started exactly when the machines entered shadow mode.

Fix: one commit line before close​

if cfg.get("dry_run"):
LOG.info("[dry_run] %d samples, %d events", len(samples), len(events))
...
conn.commit() # 状态机/安全基线照常落库——此前漏 commit,影子期每轮回滚(state 表冻结、基线永不生效)
conn.close()
return 0

The fix landed with the 2026-11-22 commit; the full regression suite of 271 cases passed, and the client ships with the next rollout. Nothing in the language enforces "every write path commits" — each path owns its own commit discipline, and one missed path silently loses its writes.

When chasing similar vanishing-write reports (data not saved, freshly written rows not found), check two things first: the connection's lifecycle (who creates it, who closes it) and each write path's commit timing — not the SQL itself. A statement executing successfully and a transaction reaching disk are two different events. A close relative on the Python side is swallowed exceptions that let the flow continue as if nothing happened, see Python try/except swallows exceptions and fails silently? Recovery triggers and fallbacks are both required.

Watch out

  • Do not switch everything to autocommit to save a commit: isolation_level=None lands every statement immediately, but insert_samples runs executemany plus two ring-cleanup DELETEs that must stay in one transaction for atomicity — committing between them can persist a half-cleaned state. For statement groups, use a with conn: block (commits on exit, rolls back on exception).
  • with conn: (using the connection as a context manager) does not close the connection — commit discipline and close timing are two independent decisions.
  • Sharing one connection across threads turns messy commit timing into intermittent data loss: sqlite3 is single-thread by default; with check_same_thread=False and your own lock, "whoever owns the path commits" becomes a hard rule.

FAQ​

Does sqlite3 close() commit the transaction?​

No. Under the default isolation_level (deferred mode), INSERT/UPDATE/DELETE open a transaction implicitly; close() only closes the connection and does not commit — the uncommitted transaction rolls back with the connection. Call conn.commit() explicitly before close().

Why did my sqlite3 data disappear after closing the connection?​

Most likely a write path executed DML but never committed before close(). The statement succeeds and reads inside the same connection see the data, but nothing is durable until commit. Trace who owns the connection and where each write path commits.

How do I make sqlite3 autocommit in Python?​

Either pass isolation_level=None at connect time, or wrap writes in a with conn: block. Autocommit lands every statement immediately; the context manager commits one transaction per block — prefer the block when several statements must stay atomic.

CCLEE

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

Work with me

drizzle migration skipped silently? Check the journal first

· 7 min read

On a Node.js + PostgreSQL multi-tenant system, a deploy printed "no pending migrations", everything stayed green — and about 18 minutes later production hit "relation does not exist". The batch shipped a create-table migration that had never executed, and the application container logs held not a single error.

TL;DR​

drizzle decides "which migrations are applied" from two ledgers: drizzle.__drizzle_migrations in the database (execution ledger) and drizzle/meta/_journal.json (registration manifest). Either can break silently. Hand-edited future timestamps inflate the execution ledger's max(created_at) — the watermark migrate uses — pinning every later migration below it; a raw SQL file dropped into drizzle/ without journal registration never enters the pending list. Fix: register hand-written migrations via generate --custom, never hand-edit the ledgers, and put a "journal count = file count" gate in the deploy pipeline.

Symptoms: two incidents, two broken ledgers​

Incident one: migrate reports success, the next step fails on a missing table. pnpm db:migrate (drizzle-kit migrate) finished with normal output; the following step, applying RLS policies, failed with relation "task_assignees" does not exist — the create-table migration it depends on (0032) had not run, yet migrate's output and exit code showed nothing wrong.

Hand-fixing the ledger and re-running migrate produced a second problem: the tool re-applied 0028 and 0029, two migrations long since applied. __drizzle_migrations accumulated duplicate and orphan rows — 34 rows for 32 migration files.

Incident two: the deploy says "no pending migrations", production lacks the table. Another release carried a hand-written create-table SQL (0037). The deploy's migration check reported no pending work; nobody noticed, and the application container started normally. The missing table surfaced only when the WeCom-side department sync failed. Roughly 18 minutes ran with production missing the table and zero errors in the logs.

Post-incident reconciliation: journal 36 entries, production ledger 36 rows — both sides "consistent", each one entry short. The 0037 SQL file sat in drizzle/ with no journal registration.

Root cause: how drizzle decides "which migrations are applied"​

The decision reads only the ledgers, and each pit corrupts one of them.

The watermark: the ledger's max(created_at) is the only waterline. drizzle-orm's migrate uses the largest created_at in the ledger as the watermark and applies only journal entries whose when is greater. The setup for incident one came earlier: to force a re-apply, someone had hand-edited when values in _journal.json to future timestamps (like 1794716400000). After the journal was normalized back to real chronology, the future created_at rows were still in the ledger — the watermark stayed high, and 0032, whose when sat below it, could never satisfy "when > watermark". Skipped forever, no output.

Hashes are computed at execution time, so re-runs insert new rows. The hash migrate uses for bookkeeping is computed from the SQL file's content when it executes, not read from the ledger. That explains the second half of incident one: the old migrations re-running were not considered "already applied", and each inserted a fresh ledger row — hence the duplicates and orphans (34 > 32).

A raw file outside the journal is invisible to the pending list. The pending list is effectively the journal entries minus the ledger rows. 0037 had no journal entry: journal 36 = ledger 36, the difference was empty, so "no pending migrations". Tests did not catch it either: the catalog/integration tests run against a test database cloned from dev, and dev had already received 0037 by direct psql, with a bookkeeping row to match — structure complete, everything green. Of the three ledgers (journal, dev, test), exactly one was wrong and the other two agreed.

Fix: register through the proper channel, gate the deploy​

Hand-written migrations must go through generate --custom:

# Back up first! The command overwrites an existing file of the same name
cp drizzle/0037_departments.sql /tmp/0037_backup.sql
pnpm exec drizzle-kit generate --custom --name=departments
# Put the SQL into the generated stub; journal and snapshot register automatically

Never hand-edit journal when or ledger created_at — normalize what was edited: restore when to real chronology; delete duplicate/orphan ledger rows and align created_at with the journal; then verify three things — ledger rows = file count, max(created_at) matches the last migration, and a re-run of migrate is a no-op. Incident one cleared up in that order, and later migrations resumed applying.

Two hard rules for the deploy pipeline:

  1. Journal count ≠ drizzle/*.sql file count → halt the deploy and print the mismatched filenames. This is the only reliable signal of an unregistered raw file — the database-side ledger can look "normal" because dev was hand-applied.
  2. The output says "no pending migrations" while the batch ships migration files → contradiction. Stop and inspect the journal.

The ledger decision behind migrate, and where the two pits sit

The gate has caught a real case: after registering 0037, the journal held 37 entries, the deploy re-identified 1 pending migration, and the owner channel — per-file psql ON_ERROR_STOP, server-side sha256 bookkeeping, ownership and policy checks — completed with the ledger reconciled at 37/37. Why that owner channel replaced drizzle-kit migrate on the deploy path in the first place (a different pit: the ledger diverging from the actual tables) is in the companion post drizzle-kit migrate: exit 0 but no tables? Audit the journal — together the two posts map the whole ledger: that one covers ledger-vs-database, this one covers the ledger corrupting itself.

Watch out

  • drizzle-kit generate --custom overwrites an existing file of the same name — back up the hand-written SQL before generating, then fill the stub. Do not let the tool silently eat your file.
  • Run the count check twice over: journal vs file count (registration completeness), ledger vs journal (execution completeness). Incident two's 36 = 36 shows why one comparison is not enough.
  • When hand-inserting ledger rows, match the existing row shape (hash = sha256 of the full SQL file, created_at as a bigint epoch in seconds); mixed formats break later reconciliation — details in the companion post.

FAQ​

Why is drizzle-kit migrate not applying my migrations?​

Two ledgers, two failure modes. Count drizzle.__drizzle_migrations against the number of SQL files in drizzle/ — a mismatch means an unregistered file that will never apply. If the counts match, check drizzle/meta/_journal.json: any entry whose when is below the ledger's max(created_at) is pinned below the watermark and silently skipped forever.

Can I edit drizzle's journal manually?​

Leave the when fields in _journal.json and the created_at values in the ledger alone. migrate uses the ledger's max(created_at) as the watermark and only applies entries with when greater than it — a future timestamp inflates the watermark permanently, and later migrations stay skipped even after you normalize the journal.

How do I add a hand-written migration to drizzle properly?​

Never drop a SQL file straight into drizzle/ — without a journal entry it is invisible to the pending list and will never execute. Generate the file with drizzle-kit generate --custom --name=xxx (which registers the journal and snapshot) and put the SQL into the generated file.

CCLEE

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

Work with me