Skip to main content

3 posts tagged with "Bug Fixes"

View all tags

Aliyun Assistant Kills nohup Jobs? Escape with setsid

Β· 6 min read

While using Aliyun Cloud Assistant RunCommand to start an strace sampler, a watch loop and a periodic sampler on a server, the background jobs were silently reaped the moment the call returned β€” the output was an empty file, or a half file with exactly one sample, and nothing ever logged an error.

Ran into this while providing managed hosting for a WordPress site in China β€” full-site migration, image CDN offload, daily backups and automated patrols.

TL;DR​

When a Cloud Assistant invocation ends, the agent cleans up the background processes derived from it, and nohup does not save them β€” it only ignores SIGHUP and redirects output, leaving the process in the original session, right inside the cleanup's reach. A new session via setsid is what escapes: setsid nohup cmd < /dev/null &. And before reading results back, verify the output file's line count and mtime β€” do not read an empty file as "the command never ran".

Symptoms: the call returns, the background jobs vanish​

Background jobs started with nohup cmd & inside one RunCommand invocation died in three different shapes:

JobHow it died
strace samplerOutput file never created at all
Periodic sampler v1Wrote exactly one sample, then nothing
cpdavd watcher, first versionReaped; process gone

All three share two traits: the invocation itself returned Success, and the server logged no error anywhere. Searching "nohup process disappeared" mostly points at SIGHUP β€” but nohup was already in place.

Root cause: nohup never changes the session, and cleanup sweeps by session​

nohup's contract is two lines long: ignore SIGHUP, redirect output to nohup.out. What it does not do is change the session β€” the process stays inside the session the Cloud Assistant agent created for this invocation. When the invocation finishes, the agent cleans up the processes derived from it, grouped by session, and nohup jobs fall squarely inside.

setsid is the semantics that actually addresses this: it puts the new process into a brand-new session, detached from the invocation's. Detached, the end-of-invocation sweep never reaches it β€” verified across all three job types, all of which survived once setsid went in.

One honest boundary: whether the agent sweeps by process group or by session was not verified at source level. But "leave the original session and you survive" held as a sufficient condition on every job tested, and that is enough.

Fix: the setsid three-piece form, plus output verification​

Detaching from session, terminal and foreground in one line:

# Long-running job started from inside a Cloud Assistant script (sampler example)
setsid nohup /usr/local/bin/sampler --interval 60 -o /tmp/samples.csv </dev/null >/tmp/sampler.log 2>&1 &

Do not drop </dev/null β€” a background job whose stdin still hangs on the invocation's terminal semantics can survive the cleanup and still stall.

Cloud Assistant is asynchronous in three steps (CreateCommand β†’ InvokeCommand β†’ DescribeInvocationResults); fetch results about 10 seconds after invoking, and let the script exit normally after spawning the background job β€” no waiting required.

Before reading results back, verify the job actually lived:

# Line count should match the expected sample count; mtime should keep advancing
wc -l /tmp/samples.csv
stat -c %Y /tmp/samples.csv

An empty file or a single sample means the job died β€” go check the setsid form, not the business command. This "spawn remotely, read back later, verify output first" loop, combined with Cloud Assistant's ActionTrail audit trail, is a complete emergency-diagnostics workflow.

The lesson also explains the architecture behind CCLee Server Sentinel, a Linux server monitoring service: collection runs through a resident agent and local cron on each machine, and backup scripts run locally without depending on a central server β€” a long-lived job's lifecycle should never be bound to the tail end of a single remote invocation.

Note

The verified form is setsid nohup cmd < /dev/null &, and each piece does one job: setsid changes the session, nohup covers SIGHUP and output, stdin redirection cuts terminal semantics. Put output verification before the read-back β€” the invocation's Success only means the script finished, not that the background job is alive. And since a setsid job has left the invocation's session, later invocations cannot manage it directly; leave a PID file or locate it by process name.

Untrustworthy signals come in sets on Cloud Assistant: CLI errors go to stderr with exit 0, and a jq fallback default launders the failure into an empty result β€” see Aliyun CLI Exit 0 but Failed? jq Default Values Hide Errors.

FAQ​

Why did my nohup process disappear anyway?​

nohup does exactly two things: ignore SIGHUP and redirect output. The process stays in the original session, and Cloud Assistant cleans up the invocation's derived processes by session when the call ends β€” in one verified case strace, a sampler and a watcher all died while the invocation itself returned success with no error. A new session via setsid is what escapes the cleanup.

A nohup job quits after running for a while β€” what's going on?​

Three usual causes: the launcher's session being torn down, stdin still attached to a closed terminal, or a vanished redirect target. Check the timing: the sampler in this case stopped after exactly one sample, in sync with the invocation returning β€” that pinned the cause to invocation cleanup, not a crash.

How do I keep a script running in the background of a Cloud Assistant RunCommand?​

Use the three-piece form: setsid nohup cmd < /dev/null &. The new session is outside the end-of-invocation cleanup, so the job survives across calls. Before reading results, check the output file's line count and mtime β€” an empty or half-filled file means the job died, not that the command never ran.

CCLEE

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

Work with me

WPML Switcher Not Changing? do_shortcode_tag Never Fires

Β· 8 min read

While reworking the header of a WordPress site β€” replacing the WPML language switcher with a single text link β€” the do_shortcode_tag filter I hooked changed nothing on the page: no error, no log entry, no cache to clear.

Ran into this while providing managed hosting for a WordPress site in China β€” full-site migration, image CDN offload, daily backups and automated patrols.

TL;DR​

The WPML 4.9.x language switcher never touches the WordPress shortcode pipeline: its shortcode_actions slot has no add_shortcode registration, and the HTML is rendered directly by the theme's header builder, so do_shortcode_tag never fires for it. To change the rendered output, the only place that works regardless of render path is the output buffer β€” hook ob_start on template_redirect and run bounded, anchor-based replacements. Every page ends up with exactly one header link, and rolling back means deleting one mu-plugin file.

Symptoms: the filter is hooked, the page ignores it​

Once the mu-plugin lands, the page renders the switcher exactly as before β€” no error, no log entry, no cache to clear.

The code looks unimpeachable β€” hook the filter, match the tag, replace the output:

add_filter( 'do_shortcode_tag', function ( $output, $tag ) {
if ( 'wpml_language_switcher' === $tag ) {
// replace switcher markup
return my_replace_switcher( $output );
}
return $output;
}, 10, 2 );

Searching "do_shortcode_tag not working" or "filter has no effect" mostly surfaces priority and argument-count advice; none of it helps.

Two usual suspects drop out quickly: there is no page-cache layer (origin responds with no-cache, and the public HTML is byte-identical to the origin), and the filter function itself is fine β€” calling it directly under wp eval returns the expected replacement markup. The function works, no cache exists, the page ignores it β€” the problem has to be further upstream.

Root cause: the WPML switcher bypasses the shortcode pipeline​

do_shortcode_tag lives in the core shortcode parsing loop; it only fires for markup that actually goes through do_shortcode().

Reading WPML 4.9.6 source: the switcher's shortcode_actions slot (classes/language-switcher/slots/class-wpml-ls-shortcode-actions-slot.php) never registers an add_shortcode, and its render method is invoked directly by the theme's header builder. On the other side, the theme (Impreza) contains zero do_shortcode references to this slot. With both ends disconnected, the shortcode pipeline simply isn't part of this HTML's birth path β€” and a filter on that pipeline waits forever.

Not a cache issue, not a priority issue, not a callback-signature issue: the filter is never called at all. The wp eval test produced a false signal precisely because it tests the function, not the pipeline.

Four false leads​

Cache first. CDN and page-cache layers checked β€” origin no-cache, public bytes identical to origin. Not a wrong direction, but it cost a round; confirming whether shortcodes participate in the render path should have come first.

The wp eval false positive. Calling the filter function directly returned the correct replacement markup, so "the function works" steered the hunt toward caching and priorities. In hindsight, a unit test proves nothing about the request path β€” same lesson as the plugin PDF download 500: the context wp eval loads is not the context a real request walks.

Zero hits on a full-database search. The handover notes said the switcher's host element carried the class ush_html_1; a wp db search across every table found 0 hits for that literal β€” one step from declaring the notes wrong. Reality: Impreza assembles element classes at runtime as ush_ + type + index, and the literal is never written to the database. To decide whether an element exists, read the rendered HTML; don't grep the database.

The "three flags" illusion. The requirement spoke of three language flags in the header; the WPML switcher renders only two (EN/BR). Grabbing every img tag on the page revealed the third "Chinese flag" as an independent media-library image element β€” a redundant self-link back to the site's own Chinese homepage, nowhere near the switcher block. When auditing header elements, dump the full img list first and classify second; don't stay trapped inside one component's markup.

Side pit: hand-calling apply_filters takes all 4 arguments​

A test fixture calling apply_filters( 'do_shortcode_tag', $out, $tag ) with 2 arguments died with ArgumentCountError on the spot. Reason: the instagram-feed plugin hooks the same filter with a callback requiring exactly 4 arguments (a cron status check), and an under-argued invocation fatals.

Production never trips this β€” core always passes 4 arguments. Only wp eval-style fixtures do, so fixtures should use the full form:

apply_filters( 'do_shortcode_tag', $out, $tag, '', '' );

Fix: bounded anchor replacement in the output buffer​

If the render layer can't be changed, change the final HTML after rendering: hook ob_start on template_redirect and run anchor-based regex replacements in the callback. The output buffer is indifferent to render paths β€” directly-rendered HTML passes through it too, which is exactly why this works.

Four design constraints:

  1. Front-end only: admin, ajax, cron and REST all bypass
  2. HTML guard: output without <html or <!doctype (feeds, JSON) is never touched
  3. Anchors must be stable features of the rendered markup (image filenames, aria-labels); bounded regex consumes only the anchor's block
  4. Idempotence: replacement output never contains its own anchors, so repeated runs don't stack
<?php
/**
* Plugin Name: Header Link Replace
* Description: Replace header language elements with a single text link via output buffering. Rollback = delete this file.
* Version: 1.0.0
*/

defined( 'ABSPATH' ) || exit;

function hlrep_link_html() {
return '<a href="https://example.com/en/" hreflang="en" lang="en" aria-label="English site" style="text-decoration:none;color:inherit">EN</a>';
}

function hlrep_buffer_start() {
if ( is_admin() || wp_doing_ajax() || wp_doing_cron() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) {
return;
}
ob_start( 'hlrep_buffer_flush' );
}

function hlrep_buffer_flush( $html ) {
if ( ! is_string( $html ) || '' === $html ) {
return $html;
}
if ( false === stripos( $html, '<html' ) && false === stripos( $html, '<!doctype html' ) ) {
return $html; // feeds/JSON etc. stay untouched.
}
$en = hlrep_link_html();
$done = 0;
if ( false !== stripos( $html, 'flag-cn.png' ) ) {
// (1) Swap the flag element in place: replace only the <a><img></a> anchor, keep the wrapper div.
$html = (string) preg_replace(
'#<a[^>]*>\s*<img[^>]*flag-cn\.png[^>]*/?>(?:\s*</a>)#is',
$en,
$html,
1,
$done
);
}
if ( false === stripos( $html, 'aria-label="Language Switcher"' ) ) {
return $html;
}
// (2) Switcher block: with (1) present, blank it to avoid a double link; otherwise fall back to the link.
$html = (string) preg_replace(
'#<div[^>]*aria-label="Language Switcher"[^>]*>.*?</div>#is',
$done ? '' : $en,
$html,
1
);
return $html;
}
add_action( 'template_redirect', 'hlrep_buffer_start', 1 );

Division of labor between the two anchors: on pages with a flag image, the link lands in the flag's original spot (only the <a><img></a> anchor is replaced; the wrapper div stays, so the position holds) and the switcher block is blanked to prevent a duplicate; on pages without a flag, the fallback branch puts the link where the switcher was. Together, every page ends up with exactly one header link.

This went through three iterations: v1.0 was a single-anchor replacement of the switcher β€” through the very filter pipeline that got falsified, so it failed outright; v1.1 moved to the output buffer but only handled the flag image, leaving flag-less pages without the link; v1.2 added the dual-anchor fallback and closed the loop. The single-anchor version passed functional checks; its gap was page coverage β€” acceptance lists must include the flag-less pages.

Deployment and verification: pass php -l before the file lands in wp-content/mu-plugins/; the verification metric is anchor counting on rendered HTML β€” flag 0, switcher marker 0, target link 1. Rollback equals renaming the file, zero database changes. The site also runs a sibling ob mu-plugin (font-domain rewrite); the two layers stack and regress cleanly β€” output buffers nest, and each handles its own anchors.

Note

Anchors must come from measured rendered markup (grab the HTML and confirm), never guessed from theme templates or the database β€” classes may be runtime-assembled, and database greps will always return 0 hits. The .*? plus "first closing tag ends the block" pattern assumes no nested same-name structure inside; verify, or switch to a safer anchor and a bounded match. Replacement output must not contain its own anchors, or stacked runs will replace twice. And since the ob layer edits final HTML, search engines and structured data see the replaced markup too β€” confirm that is what you want.

FAQ​

How do I customize the WPML language switcher output?​

Check your version's source first: the 4.9.6 shortcode_actions slot has no add_shortcode registration and renders directly from the header builder, so every hook on the shortcode pipeline misses it. The fallback is output buffering β€” hook ob_start on template_redirect and replace anchors in the final HTML.

Why doesn't the do_shortcode_tag filter fire in WordPress?​

The filter only runs for markup produced by do_shortcode(). WPML 4.9.6 registers no shortcode for its switcher slot and the theme never calls do_shortcode on it either, so the filter is simply never invoked β€” verify against rendered HTML, not function-level unit tests.

Why does hand-calling apply_filters('do_shortcode_tag') throw ArgumentCountError?​

Other plugins hook the same filter β€” instagram-feed registers a callback requiring exactly 4 arguments, so a 2-argument test call fatals. Production never hits this because core always passes 4; fixtures should call it with the full 4-argument form.

CCLEE

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

Work with me

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

Β· 5 min read

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

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

TL;DR​

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

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

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

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

Symptoms​

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

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

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

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

Root Cause: An ESM Module Evaluates Only Once​

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

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

Two properties of that binding create the trap:

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

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

The Fix: Read Dynamically at the Call Site​

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

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

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

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

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

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

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

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

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

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

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

Watch out

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

FAQ​

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

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

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

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

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

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

CCLEE

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

Work with me