Repository navigation
v0.3.0
Added
- A file output now has a size bound:
PHARGUS_OUTPUT_MAX_BYTES(config keyoutputMaxBytes,
default 64 MiB,0= no bound). Before a line would take the file past it, the agent renames it
to<file>.1, replacing an older one, and continues in a new file created with mode0600, so
at most twice the bound is on disk and no line is split. Rotation uses asynchronous file calls
only; a failed rename disables the agent with one[phargus] agent disabled: ...line. Under
--permissiona file output now also needs--allow-fs-write=<file>.1and
--allow-fs-read=<file>(seedocs/PERMISSIONS.md). PHARGUS_SPAN_BUFFER(config keyspanBuffer, 0 to 65536, default 1024) sets how many spans the
agent keeps per sampling interval; the rest are counted indropped.spans.0turns HTTP
tracing off and keeps the samplers and the backpressure probe: nothing is patched or subscribed,
no span line is written, andcurrentTraceId()returnsundefined. The variable is read before
anything is patched, likePHARGUS_ENABLED; an invalid value disables the agent with a message
naming it.bench/overhead.mjshas anotracevariant (the agent withPHARGUS_SPAN_BUFFER=0).phargus serve --alert '<metric><op><threshold>[:<windows>]'raises collector alerts from the
command line, for example--alert 'eventLoop.p99>50ms:3'or--alert 'memory.rssLast>=512MiB'.
The flag is repeatable, the rule id is its text, and the threshold takesms/sfor time
metrics andMiB/GiBfor memory metrics. Each rule prints one stderr line when it fires and
one when it resolves, and the dashboard's Alerts panel shows them. A bad rule is a usage error
(exit 2) that quotes it; an unknown metric lists the valid names.- Each dashboard card now shows the recent trend, not only the last value: the page keeps the last
300 windows it received and draws an inline SVG sparkline of event loop p99, heap used and RSS,
GC total pause, and backpressure total stall, labelled with the line's maximum. Sparkline redraws
are coalesced to one per animation frame, and a reconnect refills the lines from the new replay. - The agent's drop counters now reach the user: each collector window carries
dropped: { samples, spans }from its last sample (missing or malformed counts as 0; persisted
windows without the field restore with zeros), the dashboard header shows "agent dropped N
samples, M spans" when either is above 0 and the waterfall notes that older requests may be
missing, and thecounts:line ofphargus serveaddsagent.droppedSamplesand
agent.droppedSpans. OTLP metrics are unchanged. - Collector windows now keep where writes stalled:
backpressure.hotspotsholds the top 5 call
sites by total stall, merged by site across the window's samples (at most 64 distinct sites
tracked per window, sites cut to 256 characters). A sample with missing or malformed hotspots
still counts. Persisted windows carry the field (older lines restore with an empty list), and
the dashboard has a Backpressure section with the latest window's stalls and call sites. OTLP
metrics are unchanged. - The dashboard says when its data is stale: each card shows the end time of the window on
display, and aftermax(3 × window length, 5 s)without a new window the status reads
stale: no data for N s(counting up, in the error style) until the next window arrives. A
disconnected stream still showsreconnecting.docs/LIMITS.md§2 explains why the figures are
one window behind. phargus servenow passes the app's own output through: when reading stdin, every line that
is not agent data (plain text and JSON log lines) is written to its stdout in input order,
instead of disappearing.--no-passthroughturns it off; a file input never echoes. Output is
bounded at 1 MiB waiting (further lines are dropped and counted aspassthrough.dropped), and
a closed stdout stops the passthrough with one stderr line.createNdjsonDecodergets
agentOnly: true, which skips non-agent JSON objects asforeign(a new counter and
onSkippedreason with the raw line); thecounts:line gainsdecoder.foreignand
passthrough.dropped.- A request that closes before its response finishes (client disconnect,
res.destroy(), a
timeout) now leaves a span withaborted: true; the dashboard waterfall shows it as an error
marked "aborted", and OTLP export sets its status to error. - A request that continues a W3C
traceparentnow keeps its parent-id: the span line carries it
asparentSpanId(lowercased), and OTLP export sets the span'sparentSpanId, so the span is
no longer exported as a root. Spans of requests without a valid header have noparentSpanId.
Changed
- The agent's sample line no longer carries
heapSpaces(V8 heap space statistics): nothing in
the collector, dashboard, OTLP export or CLI reads it, and it was about 1.6 KB of a 2 KB line. A
line with no backpressure hotspots is now about 450 bytes.sampleHeapSpaces()is still
exported with the same shape, and the collector still accepts lines from older agents that
carry the field. - A window persistence failure (restore, append or compaction) no longer rejects
collector.consume()or stops the pipeline: it is counted incollector.persistence.failedand
reported as onePhargusPersistenceWarningper run of consecutive failures, and windows and
alerts carry on.persist.maxBytesnow caps the file: compaction keeps the newest windows that
fit in half of it, so the file is rewritten rarely. Compaction writes<file>.compact.tmp, so
grant--allow-fs-writefor that path too (docs/PERMISSIONS.md). - The collector no longer adds samples from several processes on one stream (a
node:cluster
app, forked children) into one window: eachconsume()run follows the first samplepidit
sees, skips samples from other processes as the newIgnoredReasonother-process(counted in
collector.ignored, passed toonIgnored), and emits one process warning saying how many
other processes it skipped. Samples without apidand all spans are kept as before. - One bounded drop-oldest queue (
src/agent/bounded-queue.ts) now serves the agent exporter, the
collector's ring buffers and persistence queue, the dashboard's SSE client and the OTLP batch
queue, replacing four separate implementations. It grows to its capacity on demand, so a large
bound costs nothing until used.createRingBufferkeeps its type and behaviour. summarizeHeapSnapshot,diffHeapSnapshotsandsymbolizeStackFramesno longer re-check the
shape of their worker's reply; the inputs are still checked before any worker runs. Thepool
option is meant for a pool fromcreateHeapSnapshotPool()orcreateSymbolizationPool(): a pool
running some other worker now gets that worker's reply back as is.- An OTLP batch that cannot be encoded now fails as a whole: it counts as one failed batch and all
its items infailedItems, reported once throughonError. The exporters no longer re-encode
item by item to send the rest, since the collector already rejects malformed spans. The metrics
and trace exporters now share one implementation; their options, counters and types are
unchanged. WindowStore.append()(fromcreateWindowStore) no longer queues overlapping calls: call it
again only once the previous call settled. The collector's persistence queue already appends one
window at a time.release()andclose()close the file once a pending write finishes. The
collector now validateswindowMsand the alert rules once, increateCollector, instead of on
everyconsume().- The agent's prototype patches (
writeonWritable,DuplexandOutgoingMessage,emiton
the HTTP and HTTPSServer) are installed once and never removed. When the agent disables
itself they stay in place and are inert: they call the original with the samethisand
arguments and return its result, so a wrapper another library installed on top keeps working.
TheglobalThisregistries that let an ESM and a CJS copy share one set of wrappers, the
identity-guarded restore and the peeling of dead wrapper layers are gone: only the copy that
starts the agent patches, and the start-once flag is the agent's onlyglobalThisentry. - Tests: the integration suites share one harness,
test/support.ts, andnpm testbuilds
dist/once per run in a Vitest global setup when it is older thansrc/. The cross-process
build lock each suite carried is gone. Test files, test names and assertions are unchanged.
Removed
-
Breaking:
createSinks,SinkConfigandSinkInputare gone from
@pharn-dev/phargus/collector, and the collector'ssinksoption takes ready sinks only, built
withcreateStdoutSink,createFileSinkorcreateWebhookSink. A configuration object in
sinksnow throws aTypeErrorfromcreateCollectorthat names the factory to use. Pass
onErrorto the factory for a sink's delivery failures;onSinkErrorstill sees asend()that
rejects or aclose()that fails. Before and after:// before createCollector({ windowMs, capacity, sinks: [{ type: 'webhook', url }] }); // after createCollector({ windowMs, capacity, sinks: [createWebhookSink({ url })] });
-
Breaking: the deprecated dashboard login link
/?token=<token>is gone, along with its
PHARGUS_DEP_TOKEN_QUERYwarning. A?token=query is no longer a credential:GET /?token=…
answers401and sets no cookie. Open/login#token=<token>in a browser, or send
Authorization: Bearer <token>. -
Breaking:
@pharn-dev/phargus/agentno longer exports the agent's own wiring, configuration
and permission internals. Importing the subpath starts the agent, so these were never safe to use
next to it (a second controller doubles the observers;createNdjsonExporter(process.stdout).stop()
ends the app's stdout). Removed runtime exports:createSamplerController,
createNdjsonExporter,createEventLoopSampler,createGcSampler,createBackpressureProbe,
loadAgentConfig,defaultAgentConfig,PhargusConfigError,assertPermission,
checkPermission,isPermissionModelEnabled,sampleMemory,
DEFAULT_ALLOCATION_SAMPLING_INTERVAL,DEFAULT_ALLOCATION_SAMPLING_DURATION_MSand
DEFAULT_ALLOCATION_SITE_LIMIT(thesampleAllocationsdefaults, 32768 bytes, 1000 ms and 20
sites, are indocs/API.md). Their types go with them:SamplerController,NdjsonExporter,
NdjsonExporterOptions,EventLoopSampler,EventLoopSamplerOptions,GcSampler,
BackpressureProbe,BackpressureProbeOptions,LoadAgentConfigOptions,AgentConfig,
PermissionCheckandPermissionScope. The agent keeps ten runtime exports:currentTraceId,
runWithTrace,takeHeapSnapshot,sampleAllocations,sampleHeapSpaces,createDeoptParser,
ANONYMOUS_FUNCTION,DEPENDENT_CODE_KIND,PhargusPermissionErrorandSPAN_RECORD_TYPE, and
the output-format types. To check a permission grant, use Node'sprocess.permission.has(). -
Breaking: the agent no longer reads
phargus.config.js, andPHARGUS_CONFIGaccepts a
.jsonpath only. Move the settings tophargus.config.json(same keys). A config file is now
parsed, never executed: aphargus.config.jsin the working directory prints one warning naming
phargus.config.json, andPHARGUS_CONFIG=settings.jsdisables the agent with the
"unsupported extension" message. The unknown-variable warning lists the validPHARGUS_*names
instead of guessing one ("did you mean"). -
Breaking: the deprecated OTLP exporter option
queueCapacityis gone from
OtlpExporterOptions(and so fromcreateOtlpMetricsExporterandcreateOtlpTraceExporter).
It bounded nothing; usemaxQueueSize, counted in items. An untyped caller that still passes it
is not refused: the value is ignored. -
Internal agent code that nothing in production called: the span buffer's
push()and its
string fallbacks for ids and paths the tracer never produces (the buffer is now fixed-size),
newSpanId, thespan-exportlayer andtoSpanRecord(folded into the agent's export wiring),
the event loop sampler'sresolutionoption (always 10 ms), the exporter'sspanQueueBound
option anddroppedtotal. Six one-importer files are folded into their importer. No public
export or output line changes.
Fixed
-
On Windows, with output on stdout and stdout a pipe, a stalled reader no longer stops the app. Node
writes a stdout pipe synchronously there, so the agent now writes that pipe itself with
asynchronousfs.write(libuv's thread pool) instead of throughprocess.stdout; its bounded
lanes drop and count lines as on Linux and macOS. While the reader is stalled, one thread-pool
thread waits on the pipe (seedocs/LIMITS.md). -
phargus --help(and--version) now win over a bad flag:phargus --bogus --helpprints the
usage and exits 0 instead of exiting 2. -
phargus serve <directory>fails before the dashboard binds, with
cannot read input file "<path>": EISDIRand exit 1, instead of printing the dashboard URL and
then failing on the first read. -
Docs: the README's V8 row names
/agentfortakeHeapSnapshot,sampleAllocationsand
createDeoptParser;docs/API.mdsaysrunWithTracealways starts a fresh trace id and that
importing/agentstarts the agent unlessPHARGUS_ENABLED=false;FEATURES.mdmarks event
loop min/p50 and GC counts by kind as stopping at the sample line and documents how windowp99
andmeanare computed;FEATURES.md,ARCHITECTURE.mdand the README diagram no longer show
the plugin runner fed by the collector; the OTLP resource notes sayhost.nameand
process.piddescribe the exporter's process;docs/PERMISSIONS.mdsayssampleAllocations
needs--allow-inspectorand is refused on Node 22. -
The backpressure probe names each stall by its own call site instead of caching the first
stall's site per stream, so stalls from different code on one keep-alive socket, shared log
stream or database connection are separate hotspots. A sampling window makes at most 32 stack
captures; later stalls in the window are named by the stream's constructor (for example
ServerResponse), so a server whose responses stall no longer pays a stack capture per request. -
The dashboard waterfall rebuilds at most once per animation frame instead of once per span event,
so a page load that replays 1,024 spans builds it once; an aborted span keeps its "aborted" marker
when later spans arrive; the stream reader no longer builds a promise chain that grows for as long
as the tab stays open; and the embedded layout function survives a minifier renaming it. -
diffHeapSnapshotsnow shows what shrank as well as what grew: it leaves out types whose count
and self size did not change and ranks the rest by absolute self-size change, so a type that
lost objects is no longer cut off below the unchanged rows. -
Rule sandbox edges:
loadRulesDirectoryreports a rule file over 1 MiB as a
RULE_FILE_UNREADABLEfailure without reading it, and a run's watchdog now starts only once the
sandbox child has loadedisolated-vm, so a cold first run with a shorttimeoutMsis no longer
timed on process start-up (a child that does not start within 10 s fails as
PHARGUS_SANDBOX_CRASHED).docs/THREAT-MODEL.mdD2 now says a rule that exhausts memory ends
asPHARGUS_RULE_MEMORY_LIMIT,PHARGUS_RULE_TIMEOUTorPHARGUS_SANDBOX_CRASHED. -
One sample line dated in the future, or a host clock stepping back, no longer stops all windows
and alerts until the collector restarts. A sample whosetimestampis not a safe integer or is
more than 24 hours ahead of the collector's clock is nowmalformedand counted in
collector.ignored, and a sample more than 60 windows older than the open window restarts
aggregation at its time instead of being counted aslate. -
HTTP tracing no longer pins
EventEmitter.prototype.emitfor HTTP and HTTPS servers: a later replacement (node:domain, other instrumentation) is now reached, so a domain catches a server's'error'again. -
A span's path is now the path the client requested, read when the request starts, so a framework
that rewritesreq.url(an Express mounted router) no longer changes it. It is cut to its first
256 characters, so a long URL cannot grow a span line past a few hundred bytes. -
A backpressure stall that ends with
finishorcloseinstead ofdrain(a
res.write(big)followed byres.end(), or a client that disconnects mid-stall) now reports
its duration intotalStall,maxStalland its hotspot instead of 0. -
A preloaded agent (
--importor--require) now starts in the main thread only, so worker
threads no longer each start their own agent and write extra sample lines. Every sample line now
carries the writer's integerpid; forked and cluster children each still run their own agent. -
Off means off: with
PHARGUS_ENABLED=false(or0) orPHARGUS_OUTPUT=nonethe agent no longer
patcheshttp.Server.prototype.emitfor a moment or executesphargus.config.js, and an agent
that disables itself (for example after an output error) also disables itsAsyncLocalStorage,
socurrentTraceId()isundefinedeverywhere and Node 22 stops paying for its async hooks. -
The stdout alert sink keeps delivering when its stream is backed up: after a
write()that
returnedfalseit no longer waits for adrainthat had already fired, so later alerts are
written andclose(),collector.close()andconsume()resolve again. -
The collector stores a
type: "span"record as a span only when it has the agent's span shape
(hextraceIdandspanId, stringname,methodandpath, non-negative integer
statusCode,startTimeMsanddurationNs, and a validparentSpanIdorabortedwhen
present); anything else is skipped and counted inignoredas malformed. A stored span keeps
only those fields, with strings cut to 1,024 characters, so large span-shaped lines no longer
fill the span ring and every dashboard client with up to 1 GiB. -
An alert rule with
forWindows: Nnow fires only on N adjacent breaching windows: a gap between
windows (dropped agent lines, an agent restart, a clock step back) restarts the count. A rule's
state is kept by its collector, so a rule firing when oneconsume()run ends no longer fires
again in the next, and resolves there when it stops breaching. -
A partial line that reaches the collector's NDJSON decoder in tiny pieces (progress dots, a
spinner) is now held in one buffer that doubles as it fills, capped atmaxLineBytes, instead
of one Buffer per piece: 1,000,000 one-byte chunks held 109 MiB of heap before, about 1 MiB now. -
The plugin runner's ESM build now finds its sandbox child script when the package is installed
under a path containing)(aproj (copy)orDropbox (Company)folder). It used to look
for the child at a path relative to the filesystem root, so every rule failed with
PHARGUS_SANDBOX_CRASHED. The plugin runner and the analyzer now find their own directory the
same way. -
The plugin runner's sandbox child no longer starts a second agent or writes sample lines to the
host's stdout when the host preloads the agent throughNODE_OPTIONS: it is forked with its
stdout ignored and a minimal environment (PATH,SystemRooton Windows, and
PHARGUS_ENABLED=false), so it no longer receivesNODE_OPTIONSor any of the host's secrets. -
The dashboard login link (
/login#token=<token>) now keeps+,/and=in a token
instead of turning+into a space, so base64 tokens work; other characters can be
percent-encoded.
Security
-
A heap snapshot file under the 256 MiB cap can no longer abort the host process:
summarizeHeapSnapshotanddiffHeapSnapshotsreject JSON nested more than 64 levels deep
("nesting too deep"), and the worker no longer keeps every distinct top-level key, only
snapshot,nodesandstrings. Both now fail with aWorkerTaskErrorinstead. -
The dashboard returns
400for malformed request targets and catches request-handler errors, so one request cannot crash the process hosting it. -
Dashboard binds outside loopback now require a token of at least 16 characters; short tokens are refused before the server binds.
-
A dashboard without a token now refuses to start when
allowedHosts(phargus serve --allowed-host)
names a host that is not loopback, even on a loopback bind;phargus serveexits with code 2
before binding. Previously a loopback bind plus a publicallowedHostsname served that name
with no token. Such a name now needs a token of at least 16 characters, as a non-loopback bind
does. The421body now says such a name needs a token. -
Breaking change: The dashboard session cookie is now named
phargus_session_<port>after
the port the dashboard is bound to (the actual port on a port 0 bind), instead of
phargus_token, so two dashboards on one host no longer overwrite each other's session. The
rename signs every browser out once; open the/login#token=<token>link again. -
The dashboard refuses
/eventswith503while 64 clients are connected; closing one frees a
slot. -
Removed the dead
Securecookie branch: the dashboard serves plain HTTP only, so its session
cookie is neverSecure(now stated indocs/LIMITS.md). -
The webhook sink and the OTLP exporters refuse a URL with a username or password when they are
created (send credentials with theheadersoption), the OTLP exporters checkheadersas the
webhook sink does, and a failed delivery no longer copiesfetch's message, which could quote
the full URL or a header value: it reports a fixed text or the network error code (for example
fetch failed (ECONNREFUSED)). -
A hostile source map no longer aborts the process or crashes the symbolization worker.
symbolizeStackFramesnow reports a map as malformed (MalformedSourceMapErroron its frames)
when itssourcesis not an array or itsmappingsis not a string, in the map or any section
(a 70-byte map with"sources":{"length":4294967295}made V8 end the host with exit code 134),
or when its mappings are longer than 1/32 of the free worker heap (a mapping-dense map of about
24 MiB or more killed the worker and rejected the whole call). A built file of up to 64 MiB of
newlines no longer kills the worker while itssourceMappingURLcomment is looked for.