Skip to main content

WordPress PDF Download 500? Vendor, REST Context, tempDir

· 5 min read

Clicking the PDF catalog download on a product page first produces WordPress's "There has been a critical error on this website"; after the missing-library problem is fixed, the same endpoint switches to HTTP 500 — three independent pits, stacked into one failure chain.

Ran into this while building CCLEE B2B, a WooCommerce B2B enhancement plugin covering customer group management, tiered pricing, and bulk ordering — the PDF catalog feature walked through all three.

TL;DR​

PitRoot CauseFix
Critical errorvendor never entered git, rsync deployed without libraries.gitignore exception + force-commit vendor
REST endpoint 500admin-only functions absent in REST contextfunction_exists guard + tempnam() fallback
Still 500 after fixesmPDF's default temp dir unwritable in containerpoint tempDir at sys_get_temp_dir()

All three share one backdrop: a CI + rsync containerized deployment pipeline. None of them reproduces on a standard LAMP host — they are almost pure products of the container-plus-REST combination.

Pit 1: "There has been a critical error" — vendor never reached the server​

Symptom: everything works locally; after deployment, clicking download yields WordPress's generic fatal error page.

Root cause: vendor/ (the mPDF library) never reached the server. The chain is doubled: the plugin's own .gitignore excludes /vendor/, and the repo root .gitignore carries both vendor/ and plugins/ rules, masking tracked files at the top level. CI checkout skips untracked files, rsync faithfully mirrors a library-less directory, and on the server require_once vendor/autoload.php fatals immediately.

Fix: remove /vendor/ from the plugin .gitignore, add an exception at the repo root, then force-commit:

git add -f wp/plugins/cclee-b2b/vendor/

When a WordPress plugin ships via CI + rsync, the server never runs composer install — vendor must go into git as part of the source.

Pit 2: wp eval Works, REST Endpoint 500 — Admin Functions Missing​

Symptom: with vendor in place, calling the PDF generation method through wp eval works; the REST endpoint /wp-json/cclee-b2b/v1/pdf-catalog returns 500.

Root cause: two calls incompatible with the REST context. wp_tempnam() is defined in wp-admin/includes/file.php — REST requests never load that directory, so the call fatals. WC()->shop_management is not a public WooCommerce property either, and the fallback path fatals the same way. wp eval avoids all of this precisely because the CLI loads full WordPress including admin files.

Fix: guard admin functions with an existence check and fall back to PHP native:

$tmp = function_exists( 'wp_tempnam' )
? wp_tempnam( $filename )
: tempnam( sys_get_temp_dir(), 'pdf' );

The shop name moves to the public API: get_bloginfo( 'name' ). Inside REST, treat everything under wp-admin/includes/ as nonexistent.

Pit 3: Dependencies in Place, Still 500 — mPDF Temp Dir Unwritable​

Symptom: the class loads, no more fatals, yet REST still returns 500. The server access log keeps a single 858-byte response.

Root cause: mPDF defaults to vendor/mpdf/mpdf/tmp/ as its temp directory; rsync preserves the source owner UID 1001 while PHP-FPM inside the container runs as www-data (UID 82). The directory is unwritable and the mPDF constructor throws. Attempting chown inside the container fails too — the volume-mounted filesystem doesn't allow it.

Fix: point the temp directory at the system /tmp explicitly:

$mpdf_tmp = sys_get_temp_dir() . '/mpdf';
if ( ! is_dir( $mpdf_tmp ) ) {
wp_mkdir_p( $mpdf_tmp );
}

$mpdf = new \Mpdf\Mpdf( array(
'mode' => 'utf-8',
'format' => 'A4',
'tempDir' => $mpdf_tmp,
) );

There is a shortcut for diagnosing this class of 500: wp eval-file calls the internal method directly, bypassing the REST route and permission checks, and the exception stack arrives in one step. Silent skips of this kind are not unique to PDF generation — PPCP buttons silently skipping render is another example.

Caution

Verify the three fixes in order: vendor lands first, then test the REST context, and only then the temp directory — skipping steps misattributes which fix killed the 500. Also, the function_exists guard is not a long-term shape; if the plugin claims to run outside admin contexts, its temp-file logic should never touch wp-admin/includes/ at all.

FAQ​

Why does wp eval work while the REST endpoint returns 500?​

The CLI environment loads full WordPress including wp-admin/includes/, while REST requests never load that directory. Code depending on admin-only functions like wp_tempnam runs fine under wp eval and Fatal Errors inside REST — the two contexts load different file sets.

How do I find the actual exception behind a REST 500?​

Call the plugin's internal method directly with wp eval-file, bypassing the REST route and permission checks — the exception stack arrives in one step, far more useful than an 858-byte 500 page.

Should a containerized WordPress plugin deployment run composer install on the server?​

Don't count on it — in a CI plus rsync pipeline the server never runs composer install. The vendor directory must be committed to git and land on the server through rsync; a plugin .gitignore that excludes /vendor/ ships a broken plugin.

Why is a library's built-in temp dir unwritable inside a container?​

rsync preserves the source machine's owner UID (say 1001) while PHP-FPM inside the container runs as another identity (www-data, UID 82), so the default temp dir under vendor/ becomes unwritable — and volume-mounted filesystems often refuse chown. Point tempDir at sys_get_temp_dir() explicitly.

CCLEE

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

Work with me

Playwright networkidle timeout? The 401 silent refresh loop

· 9 min read

While writing a Playwright E2E check script for a signed-in app, we opened a page with waitUntil: 'networkidle' — and 30 seconds later got a TimeoutError, even though the page opens instantly in a browser. The same day, another check script that filters records by date returned nothing for "today", with no error at all.

The app under check: a React + Node.js + Prisma full-stack web app — both pitfalls surfaced in its automated E2E check scripts.

TL;DR

  • networkidle timing out ≠ slow page: once the token expires, the frontend's 401 single-flight refresh fetches a new token and replays the request, so the network never gets a 500ms gap with zero requests. Fix: sign a fresh token right before the run, and chain signing and running into one command.
  • Date comparison always false ≠ no data: the date field Prisma returns is a UTC representation; slicing it can never equal a local calendar date. Fix: convert the comparison key to the UTC representation before slicing.

Scenario 1: networkidle keeps timing out? Root cause: the 401 silent refresh loop​

If page.goto with waitUntil: 'networkidle' keeps timing out, in most cases the page is not slow — some request is looping silently. In signed-in apps, 401 auto-refresh is the classic culprit.

The symptom​

await page.goto(url, { waitUntil: 'networkidle' });
// TimeoutError: page.goto: Timeout 30000ms exceeded.

The page itself returns HTTP 200 and opens instantly in a browser; switching networks or bypassing the proxy changes nothing — a textbook "looks like an environment problem". It only shows up when the check run is interrupted by a long manual step in the middle, and disappears as soon as the token is re-signed.

Root cause: expired token, refresh loop keeps the network busy​

Three layers of cause stacking into one symptom:

  1. The access token is short-lived (15 minutes in our case). When the check run interleaves manual steps — tweaking config, editing data — anything over 15 minutes leaves the script holding an expired token.
  2. The frontend handles login state with a 401 single-flight refresh: any request that gets a 401 is intercepted, the token is refreshed, and the original request is replayed. Invisible to users — expired sessions get silently extended, never logged out.
  3. That mechanism is the natural enemy of networkidle: every failed request immediately produces a replayed request, so the network never gets the "at least 500 ms with no connections" window. The waiter holds out for 30 seconds, then times out.
The 401 single-flight refresh loop keeps the network busy; networkidle never fires and times out after 30s

The diagnostic: one curl call makes it show its hand​

Our first guess was also the environment: page 200, everything fine in a local browser — for a while it looked like a proxy or DNS issue. The check that settled it was to take the token the script currently holds and call any authenticated endpoint:

curl -s -o /dev/null -w "%{http_code}" \
-H "Authorization: Bearer $TOKEN" \
https://your-app.example.com/api/whoami
# prints 401 → token expired, confirmed

Once the 401 shows up, the whole chain clicks into place: token expired → frontend refreshes and replays → network never idle → networkidle timeout.

The fix: sign a fresh token, chain it with the run in one command​

TOKEN=$(curl -s -X POST https://your-app.example.com/api/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"ci","password":"***"}' | jq -r .accessToken) \
&& node e2e-check.mjs

The only thing that matters: no manual step between signing and running. Our second bite of this bug came exactly from splitting signing and running into two commands — we edited some code in between, and by the next run the token was already 15 minutes old. Same symptom, same root. After embedding the signing helper into the check script entry point, this class of timeout has not come back.

Watch out

  • Without auto-refresh on your frontend, the same symptom can come from polling, heartbeats, or auto-retry — anything that "sends again after a failure" feeds this loop. The diagnostic approach is identical: first prove that requests are looping.
  • Playwright's docs officially mark networkidle as discouraged and recommend web assertions to assess readiness. If you truly need a quiet network, pair the wait with token keep-alive or a timeout circuit breaker — don't let it wait bare.

Scenario 2: date filter always empty? Root cause: toISOString outputs UTC dates​

A check script filters records by "today" and gets an always-empty result with zero errors — because the records' date field is a UTC representation, which can never equal a local calendar date.

The symptom​

const todayKey = new Date().toLocaleDateString('en-CA', {
timeZone: 'Asia/Shanghai',
});
// '2026-09-29'

const todays = records.filter((r) => r.date.slice(0, 10) === todayKey);
// todays is always empty — no error at all

r.date comes from Prisma and looks like this: 2026-09-28T16:00:00.000Z.

Root cause: the "date" in the DTO is Shanghai midnight written in UTC​

  1. Prisma reads and writes PostgreSQL naive timestamps in UTC. A record for "September 29, Shanghai" is stored as 2026-09-28T16:00:00.000Z — 16:00 on Sep 28 in UTC, which is midnight of Sep 29 in Shanghai.
  2. slice(0, 10) takes the UTC calendar day '2026-09-28', while todayKey is the Shanghai day '2026-09-29'. Different frames of reference, never equal.
  3. The nastiest part is the silence: the filter "runs normally", it just returns nothing. The surface symptom is misleading — what we noticed first was leftover state accumulating across runs (a "clear today's records" pre-check spinning emptily, clearing nothing). Only by tracing it did we find the data was never lost — the comparison key was in the wrong frame. A second, independently written script reproduced it with the same slice comparison, confirming the cause was in the key, not the data.

The fix: convert the comparison key to the UTC representation​

// Convert Shanghai midnight to its UTC representation, take the UTC calendar day
const todayKeyUtc = new Date(todayKey + 'T00:00:00+08:00')
.toISOString()
.slice(0, 10);
// '2026-09-28' — same frame as the DTO's stored representation

const todays = records.filter((r) => r.date.slice(0, 10) === todayKeyUtc);

Both sides are now "UTC calendar day" and the comparison works. Note the offset is written explicitly as +08:00 (the business timezone) — do not rely on the machine's local timezone, since the script may run in any TZ environment; an explicit offset is the only deterministic choice.

Boundaries and variants​

  • The same root cause has another face on the SQL side: wrapping a UTC time column in a single AT TIME ZONE conversion before filtering re-interprets a UTC value as wall-clock time, shifting the retrieval window by 8 hours and making time-window reconciliation silently miss. The fix is isomorphic on both sides: normalize to a UTC baseline first, then convert.
  • The reverse has the same trap: new Date().toISOString().slice(0, 10) for "today" still yields yesterday's UTC date between 0:00 and 8:00 Shanghai time. For any date-string comparison, ask what timezone frame each of the three values is in — stored value, comparison key, display value.

Watch out

The signature of this class of bug: zero errors, reproducible, and it looks like lost data. When a filter comes back empty, print both comparison keys before querying the data — in most cases the data was always there; the keys were in different frames.

The common thread: zero-error silent failures​

Neither pitfall raised an error — one "just timed out", one "just found nothing", and both got blamed on the environment first. Both fixes are now permanent parts of the automated checks at Life, an AI bookkeeping and health assistant — capture expenses by natural language, track mood and medication, end-to-end encrypted. This class of silent failure had shown up before: Zod .strict() silently dropping entire LLM outputs, and a WeChat mini-program image check failing silently — a Promise wrapper String()-ing the whole result object into [object Object], again zero errors, just an empty result. The general-purpose move for this class of failure is to give the emptiness a witness: a 401 probe, a printed comparison key — make the fault show its hand at the scene instead of guessing.

Frequently asked questions​

Why does page.goto with networkidle keep timing out in Playwright?​

A silent request loop keeps the network busy. When the access token expires, a 401 single-flight refresh interceptor fetches a new token and replays the failed request, so the network never sees the 500ms idle gap networkidle requires, and goto times out at 30 seconds. Verify with one curl call carrying the current token — a 401 confirms it. Fix: sign a fresh token and run it in the same command as the check.

Why is networkidle not working in Playwright?​

networkidle needs zero network connections for at least 500 ms, so polling, heartbeats, or auto-retry layers keep resetting the window. Playwright also officially marks networkidle as discouraged — prefer web assertions to assess readiness; if you truly need a quiet network, keep the token fresh and add a timeout circuit breaker.

CCLEE

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

Work with me

Airflow trigger no dag_run_id? duplicate logical_date 409

· 5 min read

Calling the Airflow trigger API, the request goes out cleanly and your logs say "triggered" — and later you discover the DAG never ran; the task list is empty.

Encountered this while building AI Ops — LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operational strategy. The platform's backfill script triggers an analysis DAG day by day; one repeated date parameter and the downstream silently misses an entire batch.

Symptom: the API "succeeded", the DAG never ran​

The trigger request completes without raising, the caller's log line says triggered — but Airflow shows no corresponding run and nothing executes. What makes this nasty: it never surfaces in the triggerer's errors, only in the downstream question "why is this day missing?". If you searched for "Airflow API trigger no effect", "dagRun not created" or "trigger dag silently fails", same problem.

Root cause: Airflow enforces (dag_id, logical_date) uniqueness on triggers​

Within one DAG, logical_date cannot repeat (dag_run_id is a unique primary key too). Triggering again with an existing logical_date is rejected outright — verified on Airflow 3:

POST /api/v2/dags/{dag_id}/dagRuns
HTTP 409
{"detail": {"reason": "Unique constraint violation", ...}}

The response is a 4xx — the status code and body both say "not triggered". The failure lives in how the caller consumes that response. The three most common misses:

  • No status-code check: no network exception means "success", and the 4xx body gets discarded;
  • "Got a response" treated as success: resp.json() parsed fine, therefore triggered — nobody looks for dag_run_id;
  • Error text lost in log noise: the 409 detail is a constraint-violation blob that no grep keyword matches, so nobody reads it twice.

The fix: a fresh logical_date per trigger, assert dag_run_id in the response​

Two things, both mandatory. On the trigger side, backfills use a distinct logical_date per day (naturally increasing):

from datetime import date, timedelta

for i in range(days):
ld = (date(2026, 1, 1) + timedelta(days=i)).isoformat()
trigger(dag_id, logical_date=ld)

On the caller side, make "response body contains dag_run_id" the only success criterion, with status codes as a secondary signal:

import requests

def trigger(dag_id: str, logical_date: str) -> str:
resp = requests.post(
f"{BASE}/api/v2/dags/{dag_id}/dagRuns",
headers=auth_headers(),
json={"logical_date": logical_date},
)
body = resp.json()
run_id = body.get("dag_run_id")
if not run_id:
# 409 = a run already exists for this logical_date; other 4xx/5xx are failures too
raise TriggerFailed(f"{resp.status_code}: {body}")
return run_id

The beauty of this criterion is that it's status-code agnostic: whatever the server answers, a body without dag_run_id means the trigger did not happen — one check covers every failure shape.

Boundary cases: the rejection is sometimes exactly what you want​

Worth stating the other side: if your logical_date is the business date, the unique constraint is your idempotency guard. Backfilling the same day twice — the second trigger gets a 409 and no duplicate run is created. In that scenario the move is not "make the trigger succeed" but "clear and rerun the existing run". Don't mix the two:

ScenarioCorrect move
Backfill: one run per dayFresh logical_date per trigger
Rerun the same business dayDon't re-trigger; clear + rerun the existing run
Deciding whether a trigger happenedOnly trust dag_run_id in the body; status code secondary

Also: manual triggers without a logical_date get a manual__<timestamp> run_id and corresponding logical_date from Airflow — inherently collision-free. The ones who hit this are callers constructing their own logical_date values.

Watch out

  • Put the dag_run_id check inside your trigger wrapper — scattered call sites guarantee one of them skips it, and that one silently drops a batch.
  • Alert on status-code classes, not message keywords — the 409 detail is constraint-error text that no grep pattern reliably matches.
  • Business-date logical_dates are good practice: clear semantics plus a free idempotency guard.

FAQ​

What happens if I trigger the same Airflow DAG run twice via the API?​

It gets rejected by a unique constraint: re-triggering with an existing logical_date returned HTTP 409 (Unique constraint violation) with no dag_run_id in the body, and the DAG never ran. Callers that only log the request miss the failure entirely.

Why was my Airflow dagRun triggered but nothing ran?​

The most common cause is a duplicate logical_date — Airflow enforces (dag_id, logical_date) uniqueness and answers 409, which an unchecked caller never notices. Rule: a trigger only succeeded if the response body contains a dag_run_id.

Can logical_date repeat in Airflow?​

Not within the same DAG — (dag_id, logical_date) carries a unique constraint and dag_run_id is a primary key. The rejection is by design and doubles as an idempotency guard for business-date-based triggers.

CCLEE

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

Work with me

Airflow DAG gone but metadata stays? Delete order matters

· 5 min read

The .py file is gone from the codebase and deployed — yet the DAG still sits in Airflow's list. You clean the metadata tables by hand, and minutes later the rows are back.

Encountered this while building AI Ops — LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operational strategy. Retiring old analysis types in the DAG pipeline left zombie entries piling up in the list page.

Symptom: the file is gone, the metadata refuses to leave​

Two symptoms, depending on the order you did things:

  • File deleted first, tables checked after: rows for the dag_id remain in dag, serialized_dag, dag_code and dag_version, and the UI list still shows the DAG;
  • Tables cleaned first, file deleted after: stranger still — freshly DELETEd rows reappear within minutes. The DAG "resurrects".

If you searched for "Airflow delete DAG still shows in UI" or "dag metadata comes back", same story.

Root cause: dag-processor registers whatever it finds; reserialize never cleans​

The resurrection is designed behavior, not a haunting:

  • dag-processor periodically scans the DAG directory. As long as the .py file exists, the scan parses it and re-registers metadata rows — which is exactly why cleaning tables before deleting the file resurrects the DAG: at clean time the file was still there, and the next scan rebuilt everything.
  • airflow dags reserialize only registers upward. It serializes "files currently in the directory" into the tables, but never removes rows whose files have disappeared — run reserialize after deleting a file and the leftovers don't budge.

So the order of "delete file" vs "clean metadata" is inherently one-directional: while the file exists, cleaning is futile; once it's gone, one clean is final.

The fix: delete file → clean tables in FK order → reserialize to verify​

Three steps, order not negotiable:

  1. Delete the .py file first. In production the DAG directory is a volume mount — sync via git pull on the host rather than deleting inside the container:
ssh <host> "cd /root/workspace/ai_dag && git pull"
# the DAG directory (mounted as /opt/airflow/dags) no longer has the .py
  1. Clean the metadata in foreign-key order (task_instance goes with dag_run via cascade):
DELETE FROM dag_run        WHERE dag_id = 'old_dag';      -- cascades task_instance
DELETE FROM serialized_dag WHERE dag_id = 'old_dag';
DELETE FROM dag_code WHERE dag_id = 'old_dag';
DELETE FROM dag_version WHERE dag_id = 'old_dag';
DELETE FROM dag WHERE dag_id = 'old_dag';
  1. Run reserialize as the verification: after airflow dags reserialize, query the dag table — if the dag_id doesn't reappear, the cleanup is final.

The whole thing takes under a minute; with the file gone from the directory, dag-processor's scans have nothing to re-register.

Boundary cases​

  • Make sure no scheduler/processor is mid-parse of that DAG before cleaning — avoid racing the registrar; off-peak windows keep it simple.
  • If run history matters as evidence, export it with SELECT first — run history is the only record of "what actually happened"; once deleted it's gone.
  • Same dag_id moving directories/platform folders follows the same logic: make the old file disappear from the directory first, then do the metadata surgery.
  • Metadata schemas differ across Airflow versions (dag_code/dag_version are relatively recent) — \d your own tables and foreign keys before running DELETEs; don't copy table names blind.

Watch out

  • The order is an iron rule: cleaning tables before deleting the file = guaranteed resurrection. Put "delete the file" at step one and everything after is downhill.
  • Direct SQL against a production metadata database is high-risk: WHERE must pin the exact dag_id — check affected row counts inside a transaction before committing.
  • The UI's "delete" button (newer versions) goes through an API path with different behavior from manual table cleaning; this flow targets scenarios needing precise control of what gets removed.

FAQ​

Why does a deleted DAG still show in the Airflow UI?​

Its metadata rows remain in dag, serialized_dag, dag_code and dag_version, and the UI renders from tables. reserialize only upserts files that exist — it never removes rows for vanished files, so the tables need a manual DELETE in foreign-key order.

Why did the metadata I cleaned come back?​

The DAG file was still on disk when the tables were cleaned: dag-processor periodically scans the DAG directory and re-registers any file it finds. Delete the file first (git pull into the mounted directory), then clean tables, then reserialize to confirm.

What is the right order to fully remove an Airflow DAG?​

  1. delete the .py file and sync the DAG directory; 2) DELETE in foreign-key order: dag_run (cascades task_instance) → serialized_dag → dag_code → dag_version → dag; 3) run airflow dags reserialize and confirm the dag table stays clean.

CCLEE

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

Work with me

Airflow 3 password reset not working? It reads a JSON file

· 5 min read

After updating a user password on Airflow 3, requests to /auth/token with the new password still return 401 — while the password hash in the database verifiably holds the new value.

Encountered this while building AI Ops — LLM-powered analytics that surfaces market trends, user behavior, and sales data for precise operational strategy. The platform's DAG trigger chain rides on this Airflow JWT auth, so a stuck password rotation left the pipeline authorization dangling.

Symptom: password changed, /auth/token still answers with the old one​

The new password gets 401 from /auth/token while the old one still gets 201 — every modification step "succeeded", yet the password in effect never changed. This particular rotation was incident response: the old credential had leaked, so every minute of "changed but not effective" was exposure.

The first reflex is the official CLI:

$ airflow users reset-password -u apiuser -p <new>
AttributeError: 'AirflowSecurityManagerV2' object has no attribute 'find_user'

The error points into the FAB (Flask-AppBuilder) auth stack, which smells like a 3.x version bug. CLI broken? Fine — bypass it and update the database directly. That detour set up an even deeper trap.

Root cause: SimpleAuthManager never reads the database — the password lives in passwords.json​

This deployment's auth manager is not the FAB the error implies, but SimpleAuthManager — one command reveals it:

airflow config get-value core auth_manager
# airflow.api_fastapi.auth.managers.simple.simple_auth_manager.SimpleAuthManager

Three layers, and the symptom explains itself:

  • The CLI error is a red herring. The airflow users CLI family belongs to the FAB auth stack; on a SimpleAuthManager deployment its code path crashes with AttributeError. The AirflowSecurityManagerV2 class in the message does exist (as a leftover component), but it has nothing to do with the manager actually handling auth.
  • ab_user is a leftover table. Deployments upgraded from Airflow 2.x carry FAB's user tables. Writing directly — UPDATE ab_user SET password=... with a werkzeug generate_password_hash scrypt hash — returned rowcount=1, and check_password_hash confirmed the stored hash matched the new password. Yet /auth/token kept answering 401: the table genuinely changed; the auth flow simply never reads it.
  • The real source is a JSON file. SimpleAuthManager takes user passwords from the file pointed to by AIRFLOW__CORE__SIMPLE_AUTH_MANAGER_PASSWORDS_FILE — a flat mapping:
{
"apiuser": "<password>",
"admin": "<password>"
}

The username-to-role mapping is declared separately via AIRFLOW__CORE__SIMPLE_AUTH_MANAGER_USERS (e.g. apiuser:admin,admin:admin). The first move in incidents like this should be asking "which manager owns auth?", not patching the symptom "auth is broken".

The fix: edit passwords.json, then force-recreate the container​

Three steps:

  1. Edit the host-side passwords.json (the source file mounted into the container):
python3 - <<'EOF'
import json
d = json.load(open('/root/workspace/ai_dag/deploy/passwords.json'))
d['apiuser'] = '<new password>'
json.dump(d, open('/root/workspace/ai_dag/deploy/passwords.json', 'w'), indent=2)
EOF
  1. Recreate the api-server container. This step is not optional — the password file is read only at startup, so editing it does nothing to the running process:
cd /root/workspace/ai_dag/deploy
docker compose up -d --force-recreate airflow-api-server
  1. Once the service is up, verify in both directions — the new password must pass AND the old one must fail; both assertions matter:
# health: back to 200 within ~30s of the recreate
curl -s -o /dev/null -w '%{http_code}' http://localhost:8080/api/v2/monitor/health

# new password → expect 201
curl -s -o /dev/null -w '%{http_code}' -X POST http://localhost:8080/auth/token \
-H 'Content-Type: application/json' \
-d '{"username":"apiuser","password":"<new>"}'

# old password → expect 401
curl -s -o /dev/null -w '%{http_code}' -X POST http://localhost:8080/auth/token \
-H 'Content-Type: application/json' \
-d '{"username":"apiuser","password":"<old>"}'

On this incident the results were 201 for the new password, 401 for the old — rotation closed. Verifying only "the new password works" without "the old one fails" is the most common loose end in credential rotation.

Watch out

  • Identify the auth manager before touching anything: the output of airflow config get-value core auth_manager decides where the password lives — FAB keeps it in the database, SimpleAuthManager in a file. Completely different paths.
  • Editing the password file demands a container recreate: the file is read only at startup, and docker compose restart won't reload it.
  • Services depending on that auth must pick up the new password too and restart — otherwise the pipeline sits in a window where the old password 401s and the new one isn't wired in.
  • Recreating the api-server costs seconds to half a minute of downtime — do it off-peak, and poll health until it returns 200 before verifying.

FAQ​

Why does the reset-password command fail after upgrading to Airflow 3?​

On 3.x deployments running SimpleAuthManager, the FAB airflow users CLI is gone for good — it crashes with AttributeError: 'AirflowSecurityManagerV2' object has no attribute 'find_user' (verified). Run airflow config get-value core auth_manager first to see which manager actually handles auth.

Where does SimpleAuthManager store user passwords?​

In a passwords.json file (flat JSON like {"username": "password"}) pointed to by AIRFLOW__CORE__SIMPLE_AUTH_MANAGER_PASSWORDS_FILE. The file is read only at container startup — after editing it you must run docker compose up -d --force-recreate airflow-api-server.

Why doesn't updating the ab_user table change the password?​

ab_user belongs to the FAB auth manager. On deployments migrated to SimpleAuthManager it is leftover data the auth flow never reads — we wrote a scrypt hash with rowcount=1 and /auth/token still returned 401.

CCLEE

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

Work with me

Model Changed but Column Missing? 3 Alembic Pitfalls

· 7 min read

You add a field to a SQLAlchemy model in a FastAPI project using async SQLAlchemy. Everything works locally. After deploying, the first API call throws sqlalchemy.exc.ProgrammingError: column "xxx" does not exist — the model changed, the table did not.

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

TL;DR​

When the model changed but the table didn't (or alembic won't even run), it is one of three pitfalls:

  1. Alembic still using the async engine — Alembic does not run inside an event loop. env.py must switch to a sync URL (postgresql+asyncpg:// → postgresql://, psycopg2 driver)
  2. down_revision pointing at a revision ID that doesn't exist — alembic upgrade fails with Can't locate revision
  3. Model edited, migration never generated — the code looks right, the table is untouched, and production blows up on first use of the new column

The three pitfalls map to "migration won't run", "chain is broken", "migration was never created" — in that triage order.

Symptoms​

Three symptoms, one per pitfall:

Symptom 1: production error after adding a model field

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedColumn) column "risk_threshold" does not exist

Works locally, fails on the first production query.

Symptom 2: the migration command itself fails

Can't locate revision identified by '001_initial'

alembic upgrade head never reaches your new migration.

Symptom 3: autogenerate reports no changes

Generating migration ...  (no changes in schema detected)

You definitely edited a model, yet alembic sees nothing — usually env.py never imports your models, or it connects to the wrong database.

Root Cause 1: Alembic Running on an Async Engine​

Alembic migration scripts do not run inside an asyncio event loop. Your application can use async SQLAlchemy with the asyncpg driver, but the alembic command executes synchronously. If env.py reuses the app's async URL, the driver fails or behaves unpredictably.

The fix: give env.py its own sync engine. Swap postgresql+asyncpg:// for postgresql:// and install the psycopg2 driver.

pip install psycopg2-binary

Key part of alembic/env.py (after the config object is ready, before engine_from_config):

from sqlalchemy import pool, engine_from_config
from alembic import context

from app.config import settings
from app.database import Base
from app.models import * # noqa: F401,F403 - import all models

# Override sqlalchemy.url with sync URL for migrations
# Replace postgresql+asyncpg:// with postgresql:// for psycopg2
sync_url = settings.database_url.replace("postgresql+asyncpg://", "postgresql://")
config.set_main_option("sqlalchemy.url", sync_url)

Two details:

  • Replacing the async URL with the sync one via config.set_main_option() overrides the ini setting, so alembic.ini never needs a second connection string
  • The from app.models import * line is what registers every model into Base.metadata for autogenerate — drop it and you get symptom 3, "no changes in schema detected"

On dependencies: psycopg2-binary must be installed in whatever environment runs alembic. It is easy to miss in CI or a container that only runs migrations.

Root Cause 2: A Broken down_revision Chain​

Alembic maintains a one-way linked list through revision / down_revision. upgrade head walks that chain from the current version to the tail. down_revision must reference a revision identifier that actually exists in the chain, character for character. A "close enough" name from memory breaks the link.

A real repository's chain, three files under alembic/versions/:

# 001_initial.py
revision = '001_initial'
down_revision = None

# 002_rename_model_config_to_llm_config.py
revision = '002_rename_model_config'
down_revision = '001_initial'

# 003_add_cascade_delete.py
revision = '003'
down_revision = '002_rename_model_config'

Can't locate revision identified by 'xxx' means some down_revision string does not resolve — a wrong migration filename, half-copied ID, anything.

The fix is always the same two commands:

# 1. See the real chain (left column = revision ID)
alembic history

# 2. See where the database currently sits
alembic current

Point the new migration's down_revision at the real chain tail from alembic history, then alembic upgrade head. Alembic resumes from the position recorded in the alembic_version table; already-applied migrations do not re-run.

Use alembic history --verbose once the chain grows — guessing the topology from filenames does not scale.

Watch out

Two developers branch in parallel and both write a migration whose down_revision points at the same parent — upgrade head now reports multiple heads. Resolve it with alembic merge, which generates a merge migration. Our repository carries one such merge file, created to stitch two parallel branches. Multiple heads are not an anomaly; leaving them unmerged is.

Root Cause 3: Model Edited, Migration Never Created​

The most common misconception: an ORM model is a code-level declaration and never modifies the database by itself. Adding a field to a model class:

class Agent(Base):
__tablename__ = "agent_agents"
# ...
risk_threshold = Column(String, default="medium") # new

This changes a Python object definition. The agent_agents table is untouched, and the first query referencing the column raises column does not exist. Locally it often "just works" because your dev environment built tables with create_all(), or a SQLite in-memory database is recreated each run — both paths bypass migrations and mask the problem. Another model-layer trap is the Pydantic v2 ORM mode change; see Pydantic v2 ORM mode migration.

After any ORM model change, three fixed steps:

# 1. Generate a migration (autogenerate diffs model vs. database)
alembic revision --autogenerate -m "add risk_threshold to agent_agents"

# 2. Review the generated file by hand (autogenerate misses server defaults and
# constraint names; never upgrade blind)
# alembic/versions/xxxx_add_risk_threshold_to_agent_agents.py

# 3. Apply it
alembic upgrade head

Step 2 is not optional. Autogenerate is a diff tool with blind spots; upgrading its output unchecked is a gamble.

Verify the migration landed:

psql -c "\d agent_agents"   # confirm the new column exists
alembic current # confirm the version sits at the chain tail

Triage: Three Questions​

For any "changed the model, table didn't move" problem (also searched as "column does not exist" or "field missing in table"), three questions locate it in a minute:

  1. Does the migration command run at all? No → pitfall 2, check the down_revision chain
  2. It runs, but the column is still missing? → pitfall 3, confirm autogenerate produced a file, upgrade head ran, and alembic current sits at the tail
  3. Connection or driver errors from alembic upgrade? → pitfall 1, the sync URL setup in env.py

One team rule on top: model changes and their migration files ship in the same commit. A model without its migration hands every collaborator the exact production error on pull.

FAQ​

What are the basic alembic migration commands?​

Generate a migration with alembic revision --autogenerate -m "message", apply it with alembic upgrade head, roll back one step with alembic downgrade -1, and inspect the chain with alembic history. The standard workflow after any model change is exactly two steps: autogenerate, then upgrade head. Skip either one and the table stays unchanged.

I created my tables with SQLAlchemy — why doesn't a model change take effect?​

A SQLAlchemy model is a code-level declaration only; it never touches the database. Alembic migrations own schema changes. Even if you built tables with create_all() locally, the new column lives in in-memory metadata — production PostgreSQL raises ProgrammingError: column does not exist the first time a query touches it. Always generate a migration and run upgrade.

Why does alembic upgrade fail with Can't locate revision?​

Your down_revision references a revision identifier that does not exist in the chain — usually a short name typed from memory. Run alembic history to get the real IDs, point the new migration's down_revision at the actual chain tail, then run alembic upgrade head. revision and down_revision must match character for character; one wrong character breaks the whole chain.

CCLEE

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

Work with me

Claude Code Hooks Overblocking? Gate on Real SQL Writes

· 10 min read

While configuring a Claude Code Bash hook to stop the AI from writing to a production database, pm2 restart, grep, and Python debug commands got blocked one after another — every dangerous SQL was caught, but half of the legitimate ops commands were caught too. This is commonly discussed as hook overblocking or false positives. This post walks through the full narrowing from "keyword matching" to "execution semantics".

Encountered this while operating the production servers behind CCLee Server Sentinel — managed Linux server monitoring across performance, availability, security and backups, with alerts merged into conclusions plus remediation guidance.

TL;DR​

Using "command text contains a write keyword" as the hook criteria is guaranteed to overblock: sys.path.insert, pm2 --update-env, and grep 'UPDATE …' all contain whole-word keywords, and \b boundaries save none of them. Narrow the criteria to three conditions — ssh prefix to the prod host + psql in the command + word-boundary keyword — and 8 classes of false positives drop to zero. Meanwhile, define the legit write path as file piping (keywords never enter the command line), which by construction never triggers the guard. Finally, turn the criteria table into 22 regression cases: change criteria by changing tests first.

Symptom: pm2 restart blocked, ops commands caught in the net​

On day one, the v1 blocking hook caught pm2 restart, remote grep, and Python debug commands — none of the blocked commands actually wrote a database.

Some context: our workflow lets Claude Code connect to the production database for read-only troubleshooting — locate the trace in the logs table first, form a hypothesis, then read code. That path depends on one premise: INSERT / UPDATE / DROP writes must never be issued directly by the AI. The rule went into CLAUDE.md first, but rules are advisory; models forget under long-session pressure. So we added a mechanical layer: a PreToolUse hook that blocks (exit code 2) any ssh-to-production command whose text contains a write keyword.

The false positives piled up fast. All of these were blocked; none of them writes a database:

# Python path tweak inside a container (sys.path.insert contains "insert")
ssh prod "docker exec app python3 -c 'import sys; sys.path.insert(0, \"/app/lib\")'"

# pm2 rolling env reload (--update-env contains "update")
ssh prod "pm2 restart api --update-env"

# Service restart (pm2 delete contains "delete")
ssh prod "cd /app && pm2 delete api 2>/dev/null; pm2 start ecosystem.config.js && pm2 save"

# Searching code remotely (grep's argument contains "UPDATE")
ssh prod "grep -rn 'UPDATE api_keys' /app/server/"

# Counting errors in logs
ssh prod "tail -5 error.log | grep -c UPDATE"

# pandas inside a container (df.update contains "update")
ssh prod "docker exec airflow python3 -c 'df.update(other)'"

Every blocked command meant Claude had to stop and reroute, breaking the troubleshooting chain. The false-positive list grew to 8 classes (the regression suite keeps 6 representative samples) — v1 criteria declared failed.

Root cause: keyword matching hits text, not execution semantics​

Word boundaries cannot fix shell-command false positives — v1's regex already had \b, and the false positives happened anyway:

grep -qiE '\b(INSERT|UPDATE|DELETE|DROP|TRUNCATE|ALTER|GRANT|REVOKE)\b'

Word boundaries cannot fix shell-command false positives, and the reason is counter-intuitive: punctuation in code syntax is itself a word boundary. The . in sys.path.insert, the - in --update-env, the . and () in df.update() are all non-word characters to the regex engine, so insert and update count as "whole words" in every one of them. v1's boundaries prevented zero false positives.

One level deeper, the criteria was anchored on the wrong thing: a keyword appearing in the command text does not mean the command executes that keyword's semantics. grep 'UPDATE api_keys' means "search", not "update"; pm2 --update-env means "restart", not "modify data". No text-level trick (boundaries, casing, context windows) can tell them apart, because the discriminating information is not in the text — it is in the executor. What is actually dangerous is "psql receives a write statement", not "the word UPDATE appears somewhere".

So the fix is not finer matching but a different anchor: execution semantics. A command poses a database-write risk only if three things hold at once: it is an ssh to the production host, it actually invokes psql, and the text psql will execute contains a write keyword.

The Claude Code hook decision flow: three conditions, all required​

The flow below shows the gate: three conditions in series, every "no" branch allows, only three "yes" results block.

bash-guard decision flow: ssh prod prefix, psql presence, and word-boundary write keyword must all hold before blocking; SQL via file piping passes by construction

The entire v1-to-v2 diff is one line — a psql condition added before the keyword check:

# v1: keyword only (deprecated)
if echo "$CMD" | grep -qiE '\b(INSERT|UPDATE|DELETE|DROP|TRUNCATE|ALTER|GRANT|REVOKE)\b'; then

# v2: psql presence + keyword, checked together
if echo "$CMD" | grep -qi 'psql' && echo "$CMD" | grep -qiE '\b(INSERT|UPDATE|DELETE|DROP|TRUNCATE|ALTER|GRANT|REVOKE)\b'; then

The full hook (17 lines; replace prod with your production host's ssh alias):

#!/bin/bash
INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.tool_name // empty')
[ "$TOOL" != "Bash" ] && exit 0

CMD=$(echo "$INPUT" | jq -r '.tool_input.command // empty')

if echo "$CMD" | grep -qi '^ssh prod'; then
if echo "$CMD" | grep -qi 'psql' && echo "$CMD" | grep -qiE '\b(INSERT|UPDATE|DELETE|DROP|TRUNCATE|ALTER|GRANT|REVOKE)\b'; then
echo "Blocked: psql inline write keyword detected: $CMD" >&2
exit 2
fi
echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"allow","permissionDecisionReason":"read-only ssh command"}}'
exit 0
fi

exit 0

Register it in settings.json, matcher limited to the Bash tool, timeout 5 seconds so a hung script cannot stall the session:

{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{ "type": "command", "command": "/path/to/bash-guard.sh", "timeout": 5 }
]
}
]
}
}

Precise blocking is half the job — writes still need a path. Schema changes and data fixes are real work, and they should not die because a hook exists. Our legit path is file piping: SQL goes to disk, stdin feeds psql, and write keywords never enter the command line:

cat x.sql | ssh prod "docker exec -i db psql -U app -d appdb"
# or
ssh prod "docker exec -i db psql -U app -d appdb" < x.sql

A pleasant side effect: the legit path never triggers the hook, no whitelist or exemptions needed. Neither side of the pipe (cat, or ssh … psql without -c) contains a keyword — criteria and legit path are structurally disjoint rather than exception-enumerated. The rule worth writing down is: what is forbidden is not "writing the database" but "inlining keywords into the command line" — team convention and hook criteria now say the same sentence.

The criteria table is the test: 22 regression cases lock the contract​

A hook encodes criteria; criteria need regression tests. We wrote the criteria table directly as a test table — one case per row: command, expected outcome (2 = block, 0 = allow). Running it only verifies; it does not negotiate:

run_case 2 'inline INSERT'   $'ssh prod "docker exec -i db psql -c \'INSERT INTO customers ...\'"'
run_case 0 'pm2 restart --update-env' $'ssh prod "pm2 restart api --update-env"'
run_case 0 'remote grep keyword' $'ssh prod "grep -rn \'UPDATE api_keys\' /app/server/"'
run_case 0 'file pipe cat|' $'cat /tmp/x.sql | ssh prod "docker exec -i db psql"'
run_case 0 'cd && prefix bypass (permission layer backstop)' $'cd /x && ssh prod "psql -c \'DROP TABLE t\'"'
run_case 2 'read-only query with literal keyword (residual)' $'ssh prod "psql -c \'SELECT body FROM logs WHERE body LIKE \\'%UPDATE%\\'\'"'

The 22 cases split into four groups: 7 true blocks, 6 v1 false-positive fixes, 6 read-only and legit-path, 3 known residuals. A comment at the top of the test file reads: "the expectation column is the confirmed contract — execution only verifies, never negotiates". Criteria changes must edit the expectation column first, then pass the suite.

The suite repaid itself quickly. The heredoc policy was once recorded as "blocked as well", then reverted the same day — and the revert rationale is now unrecoverable. Documentation-based memory forgets; the criteria now has an arbiter: a local heredoc to disk (cat > x.sql <<'EOF', starts with cat, never enters the ssh prefix gate) is allowed; a remote heredoc (ssh prod "… psql …" <<'EOF', full SQL in the command line) is blocked. Both cases sit in the test table — run it and the answer is there.

Residual risks: what this line of defense does not catch​

Note

Hook blocking is one layer of defense in depth, not absolute safety. These residuals are known and accepted; evaluate them against your own scenario:

  • cd x && ssh prod "…" prefix bypass: the criteria anchors on the ^ssh prefix, so a command starting with cd slips through. The backstop for this is not the hook — Claude Code still asks for permission confirmation on commands outside the allowlist, keeping a human in the loop.
  • Read-only queries with literal keywords still blocked: SELECT body FROM logs WHERE body LIKE '%UPDATE%' gets blocked. The rate is negligible and the failure direction is safe (prefer blocking), so we accept it.
  • psql substring false positives: a path containing "psql" plus a keyword trips the guard, e.g. grep UPDATE /tmp/psql-dump.log.
  • pg_restore not in the enumeration: restores go through a tool, not SQL keywords, so ssh prod "pg_restore -d appdb snap.sql" passes. The enumeration covers SQL write keywords; tool-level dangerous commands need separate coverage.

Why a hook instead of just a CLAUDE.md rule? They are not substitutes: rules are the advisory layer — models forget; hooks are the mechanical layer — they block even when the model forgets; permission prompts are the human layer — they backstop what the hook misses. Each layer covers a different failure mode; no single layer is enough. If you remember one sentence about the criteria: block execution semantics, not text presence.

This is our second Claude Code engineering post; the first was VS Code panel 500s and GLM multi-session rejection — both looked like random failures, and in both the root cause lived in the mechanics, not the model.

FAQ​

How do I add a Claude Code hook to block Bash commands?​

Register a PreToolUse command hook with matcher Bash in settings.json, pointing to your script with timeout: 5. The script reads tool_name and tool_input.command from stdin; exit 2 blocks the call and feeds stderr back to the model, exit 0 allows it.

What are best practices for writing Claude Code hooks?​

Anchor the guard on execution semantics, not text presence: this guard fires only when three conditions hold together — an ssh prefix to the prod host, psql in the command, and word-boundary write keywords. Keep a regression table (22 cases here) so every criteria change is verified, and document the residual risks you accept.

How do Claude Code PreToolUse hooks work?​

Before a Bash call executes, the hook receives the full command as JSON and answers with an exit code: exit 2 blocks the call and sends stderr back to the model as the reason; exit 0 allows it. A bare exit 0 with no output passes silently.

Why is my Claude Code hook blocking harmless commands?​

Because keyword matching hits text, not semantics: sys.path.insert, --update-env and grep 'UPDATE' all contain whole-word keywords, and word boundaries cannot help since punctuation in code is itself a boundary. v1 blocked 8 classes of legitimate commands this way; adding the psql condition cleared all of them.

CCLEE

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

Work with me

cPanel Domain Log 0 Bytes After Rotation? Reload Apache

· 6 min read

Every day around 20:08 the cPanel server rotates its domain logs (domlogs) — and the freshly created log file stays at 0 bytes for hours: the access-log evidence surface goes blind, and every fail2ban / traffic-analysis rule starves — while the panel shows everything as normal.

Encountered this while running a fully-managed cPanel/WHM hosting environment for a manufacturing-industry client on Alibaba Cloud China — recording the two-layer root cause and the permanent fix. Read the full engagement story in the managed-hosting case study.

TL;DR​

Two root causes stacked: cPanel's domlog rotation never reloads Apache, and the anti-blackout cron itself was written wrong — failing silently every night.

  • Immediate recovery: apachectl graceful — domlog writing resumes within seconds
  • Permanent fix: a two-line post-rotation cron — apachectl graceful (restore writing) + fail2ban-client -q reload (rebind jails to the new log file)
  • Detection: ls -la /etc/apache2/logs/domlogs/<domain>-ssl_log — still 0 bytes one hour after rotation means you are hit

Symptoms​

After each daily rotation (~20:08 on this host), the site log (domlogs/<domain>-ssl_log) stays at 0 bytes for hours:

  • First confirmed 09-27: new file at 0 bytes after rotation, until manual intervention
  • Recurred 09-28: rotation at 20:07, still 0 bytes at 21:08 — the safety-net cron deployed for exactly this had no effect

The danger is the silence: no errors, no panel alerts — but fail2ban, traffic analysis, and intrusion detection all lose their data source. For a managed environment, that is a quiet collapse of the evidence surface.

Diagnosis: The Rotation-Window journalctl Is the Watershed​

Step 1: check what Apache did during the rotation window.

journalctl -u httpd --since "20:00" --until "21:30"

Zero activity — no reload, no restart around the rotation. That pins the mechanism: the rotation moved the old file and created a new one, but Apache was never told to reopen its log files.

Step 2: find out why the safety-net cron did not catch it. The anti-blackout cron fires nightly at 21:00. Running its command by hand exposed everything on the spot:

$ fail2ban-client reload -q
ERROR No section: '-q'

Two mistakes surfaced at once:

  1. Syntax: -q is a global option of fail2ban-client and must come before the subcommand (fail2ban-client -q reload); placed after reload, it is parsed as a jail name and the command errors out
  2. Wrong target: even with correct syntax, fail2ban-client reload reloads fail2ban itself — it does not restore Apache's log writing. The breakage lives in Apache; what it needs is apachectl graceful

In other words: since the day it was deployed, this cron ran a command that was guaranteed to fail, never worked once, and raised no alert — the 09-28 blackout recurring as usual was its direct consequence.

Root Cause: Rotation Doesn't Reload, and the Net Was Tied Wrong​

The two layers, separated:

Root cause 1: cPanel domlog rotation does not reload Apache. The rotation = move the old file + create a new one, nothing more. Apache opens each log file once and keeps writing through its held file descriptor — which points at the old file's inode. After rotation, writes follow the old inode into the archive, and the new file sits unwritten from birth. This is not a malfunction; it is descriptor semantics — which is why something external must tell Apache to reopen its files (a reload) after every rotation.

Root cause 2: the safety-net cron got the command wrong twice over. The intent was right (reload after rotation), but the command was fail2ban-client reload -q: the misplacement of -q broke the syntax, and even fixed syntax would have reloaded the wrong daemon (fail2ban manages jails, not Apache's log handles). The combined effect: a safety net that silently did nothing — cron failures notify no one, the second silent point in this story.

The Fix: A Two-Line Cron, One Job Each​

Rewrite the safety-net cron (a custom file under /etc/cron.d/), split into two lines with separate responsibilities:

# Nightly 21:00 — restore domlog writing (after the ~20:08 rotation)
0 21 * * * root /usr/sbin/apachectl graceful
# Nightly 21:05 — rebind fail2ban jails to the new log files (-q is a global option; it precedes the subcommand)
5 21 * * * root /usr/bin/fail2ban-client -q reload

Design notes:

  • 21:00 graceful: after the rotation (~20:08) and before the log-consumption peak, restores Apache's writes to the new file
  • 21:05 fail2ban reload: deliberately 5 minutes apart — fail2ban's watched paths point at the rotated file, and a reload rebinds the jails; the offset avoids colliding with the Apache reload
  • Manual verification (same night): after graceful, domlog resumed writing (922 bytes and climbing); fail2ban-client -q reload returned clean

The other failure classes from this machine's provisioning phase (TFA, resource 404s, domain mounting) are covered in AlmaLinux 10 cPanel: TFA Ineffective, Resource 404s, Domain Mount Refused — together the two posts form a full provisioning-troubleshooting picture.

Watch out

Cron failures are silent: a broken command errors out and nobody hears about it. Any "anti-blackout" or "auto-recovery" cron must be verified by running the command manually once right after deployment — in this case a single manual run would have caught the syntax error on day one instead of three days later. Also note that global options like fail2ban-client's -q, when misplaced, get parsed as a jail name — the error (No section: '-q') does not hint that position is the problem.

FAQ​

Why is my cPanel domlog 0 bytes after daily rotation?​

Because cPanel's domlog rotation never reloads Apache. The server keeps its file descriptor on the old inode — new writes follow the rotated file into the archive — and nobody opens the freshly created log. Run apachectl graceful to restore writing immediately, then add a nightly post-rotation graceful cron as the permanent fix.

Where does the log content go after Apache log rotation?​

Old content lands in the rotation archive. The "empty new file" effect comes from the descriptor semantics: Apache holds one open file handle and keeps writing to the old inode no matter what happens to the filename. A graceful reload makes Apache reopen its log files — switching to the new inode — which is exactly why rotation must be followed by a reload.

How do I troubleshoot a crontab job that never runs?​

Three steps: crontab -l to confirm the entry exists; run the command by hand to see the real error (in this case fail2ban-client reload -q instantly failed with ERROR No section: '-q' — -q is a global option that must precede the subcommand); then check cron logs for trigger records. A syntactically broken command fails silently under cron — manual execution is the only reliable verification.

CCLEE

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

Work with me

.env Edits Do Nothing? DB Config Overrides Env Variables

· 6 min read

An AI model config in .env was changed — provider, key, and model name all swapped. Service restarted. The application's behavior did not move by an inch: still the old provider, the old model. The new config sits right there in the file, looking ready to apply at any moment. It never does.

Encountered this while maintaining a client-delivered AI content-processing application — recording the detour and the final diagnosis.

TL;DR​

When an app supports editing config through an admin UI, the database fully overrides .env — same-named entries in .env are a fallback at best, dead config at worst.

One sentence for the triage order: check the app's runtime config store (the DB config table) before checking .env. This investigation wasted two steps on .env and the process environment snapshot before the DB config table revealed the truth: it held a complete set of values from a different provider, shadowing .env in full.

Symptoms​

The server's .env:

# /path/to/backend/.env — looks "in use"
AI_API_KEY=sk-xxxx...xxxx
AI_BASE_URL=https://old-provider-compatible-endpoint
AI_MODEL=old-model-name

Actual behavior: model calls go to a different provider entirely (a real OpenAI-protocol endpoint, different key, different model). Edit .env, restart, no effect. Edit again, restart again, still no effect.

The Detour: Two Checks That Paid Nothing​

The investigation itself is worth recording — two checks that looked professional and accomplished nothing.

Detour 1: staring at the .env file. The config was complete, well-formatted, in the right directory (the systemd unit genuinely points there). Everything about it says "in use". But a config being in a file and a config being in effect are different things — the app's loader has a precedence chain, and .env is only one candidate source.

Detour 2: checking /proc/<pid>/environ. The standard move to see what environment a process actually received:

cat /proc/<pid>/environ | tr '\0' '\n' | grep AI_

Empty. And the check itself was flawed: dotenv injects into os.environ at runtime, after the process started — /proc/<pid>/environ is a snapshot from launch time and can never show dotenv-injected values. Absence here proves nothing about the process, and presence here proves nothing about effectiveness. For a dotenv app, this snapshot supports no conclusion in either direction.

The third step finally landed: querying the DB config table. The app supports editing AI config through an admin UI, and its loader is "DB first, env as fallback" — the DB config table held a full set of the other provider's values, outranking .env. Case closed.

Root Cause: A Config UI Requires DB > env​

Why must this class of app rank DB above env? Reverse-engineer from the feature requirement:

The app promises "admin edits AI config in the backend; it applies on save". If .env outranked the DB, every UI edit would be crushed by .env and the feature would be dead on arrival. So any app with this feature has a loader shaped like:

def _ensure_client():
cfg = load_db_config() # 1. DB config table first
if cfg is None: # 2. fall back to env only when DB is empty
cfg = from_env()
return build_client(cfg)

DB wins whenever it has values — and the moment anyone saves a config in the backend once, the DB has values forever. From that day on, .env is dead config: nothing written there gets read, unless the DB config is cleared.

The trap is its invisibility: .env sits right there on the server, complete and tidy, and the natural operator reflex is "edit this". Nothing ever warns "your edit was overridden by the DB" — the config system silently follows its precedence chain, and only someone who knows the chain can predict the outcome.

The Fix: Check the DB First, Then Clean Up​

Step 1: confirm the real source of effective config. Query the app's config table (an app_config-style key-value table in this case):

SELECT key, value FROM app_config;

Match the DB values against observed behavior (e.g., which endpoint requests actually hit). Once they line up, the conclusion is nailed: DB fully overrides; the same-named .env block is leftover dead config.

Step 2: before deleting dead config, verify the DB really covers everything. Compare DB entries against .env item by item: if DB covers all critical fields, removing the .env leftovers should be harmless in theory — but restart and verify before deleting, in case some field in the loader still falls back to env. Verify, then delete: that is the safe order for dead-config cleanup.

Step 3: write the precedence chain into the ops doc. The two wasted steps trace back to one gap: nobody knew this app had config precedence at all. One line in the handover doc saves the next person two hours: "config lives in the admin UI (DB); .env is fallback only — check the DB before touching .env."

Watch out

"A config file exists and looks correct" never equals "this config is in effect" — effectiveness depends on the loading logic and its precedence chain. Likewise, /proc/<pid>/environ proves neither presence nor effectiveness for a dotenv app. The right starting point for any config investigation is the app's config-loading code — read the precedence chain out of the code, then walk it.

FAQ​

What is the config precedence between database and environment variables?​

In apps with an admin config UI, from lowest to highest: system-level env vars → process startup env → dotenv-injected values → the app's runtime config store (a DB or config file). The DB layer wins — UI edits must take effect immediately, which is impossible if .env outranks it. When troubleshooting, check the app's config store before the env files and you skip most of the detour.

Do environment variable changes require a restart?​

By layer: system-level variables need a shell or service restart; dotenv reads .env once at process start, so file edits need a process restart too; apps with a DB config layer pick up backend edits instantly — the loader reads the DB on every client build. Mixing the three timing models is how you end up concluding "changes do nothing".

Why can't I see dotenv variables in /proc/pid/environ?​

Because /proc/pid/environ is a snapshot from the instant the process started, while dotenv injects into os.environ after the process is already running. To verify dotenv's values, print them inside the process or read the .env file directly — and remember that a value being in the file still doesn't mean it's in effect; a higher-precedence layer may be overriding it.

CCLEE

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

Work with me

Duplicate hreflang in Docusaurus? Built-in i18n emits them

· 4 min read

Running an SEO audit on a multilingual site, you read the page source and find every <link rel="alternate" hreflang="..."> appearing twice — two full hreflang sets coexisting, with overlapping language codes.

Encountered this while building CCLEE Docusaurus Theme — a documentation theme built on Docusaurus 3.x with multilingual and SEO infrastructure baked in; hreflang is exactly the kind of thing it must get right natively.

Symptom: two hreflang sets in the head​

In the page head, the same locale's alternate link appears twice — one set from Docusaurus's built-in i18n, one from a custom injector. Each set is individually correct; together they conflict. One-line self-check:

curl -s https://your-site.com/ | grep -o 'hreflang="[^"]*"' | sort | uniq -c

Any locale code (including x-default) appearing more than once means duplication. If you searched for "duplicate hreflang", "hreflang emitted twice" or "Docusaurus two sets of hreflang" — same issue.

Root cause: built-in i18n already generates them; the plugin adds a second set​

Once i18n.locales is configured, Docusaurus's built-in i18n automatically emits complete hreflang alternates (including x-default) for every page — out of the box, no plugin involved. This site's custom SEO plugin, however, also had hreflang injection logic, so every page received two sets:

  • Built-in i18n: generated from the locales config, rendered with the page;
  • Custom plugin: another set injected into the head, with language codes heavily overlapping the generated ones.

hreflang semantics are declaration, not accumulation: two sets that disagree on even one entry (say, a different URL for a locale) are conflicting annotations as far as search engines are concerned.

The fix: remove the custom injection, rely on built-in i18n​

The fix is subtraction — delete the custom plugin's hreflang injection entirely and keep only what Docusaurus generates:

// custom SEO plugin
- const links = locales.map((locale) => ({
- rel: 'alternate',
- hreflang: locale,
- href: urlFor(locale),
- }));
- // inject into head ...

Post-fix live measurement (homepages of both sites): en-US, zh-CN and x-default each appear exactly once — one clean set. Re-run the grep above after the change; ship only when every locale code counts exactly one.

Boundary cases​

  • When manual injection is actually needed: only for pages Docusaurus doesn't generate, or variant URLs that don't follow i18n routing rules. Even then, grep the current state first — the built-in generator may already cover the pair you're about to declare.
  • Duplicates don't only come from your own plugin: multiple SEO plugins stacking, or theme plus plugin each contributing a set, are common sources; debug by disabling one injector at a time — every head tag should have exactly one owner.
  • hreflang vs canonical: canonical handles "duplicate content in the same language", hreflang handles "cross-language variants"; neither replaces the other, and custom logic shouldn't entangle the two.

Watch out

  • Built-in capability before custom code: Docusaurus ships i18n, sitemap and meta-description infrastructure out of the box — confirm what's already covered before writing injectors, or you're manufacturing duplicates.
  • Make the grep self-check part of the release flow: one line of cost that catches an entire class of head-tag conflicts.
  • Search engines ignore conflicting hreflang silently — no error, no warning. It's the same "silent, no alarm" family as dotenv truncating values.

FAQ​

What are hreflang tags in SEO?​

They tell search engines which language/region variants a page has and which URL each maps to, powering regional targeting for multilingual sites. Format: <link rel="alternate" hreflang="zh-CN" href="...">.

How do I check hreflang tags on a page?​

Fetch the page source and count: curl -s https://your-site.com/ | grep -o 'hreflang="[^"]*"' | sort | uniq -c. Each locale code (including x-default) should appear exactly once; more means a duplicate injection somewhere.

Does Docusaurus generate hreflang automatically?​

Yes — with i18n.locales configured, Docusaurus emits the full alternate set plus x-default for every page out of the box. No plugin needed; adding one is how duplicates happen.

CCLEE

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

Work with me