Repository navigation
Releases
v0.3.1
Added
-
The pharn.dev link says how much traffic each commit served, so "no errors since the deploy" can
be told from "no requests since the deploy" (CORE-527). Each interval's request now carries an
optionaltrafficlist: per commit,requests(spans the collector received, one per incoming
HTTP request) anddropped(spans the agent dropped), withlowerBound: truewhendroppedis
above 0. Counts only: no path, method or status. A commit that served requests and raised no
error is still sent, once per interval, with an emptygroupslist; a process with no request
data (no HTTP, or none in the interval) sends notrafficentry rather than 0. Counted in
phargus servefrom the spans and drop counters the agent already writes: no new work in the
agent.docs/schema/production-errors.v1.jsonstays version 1:trafficis optional and
groupsmay now be empty. New typesPharnPayloadTrafficandPharnTrafficInput;
buildPharnPayloadtakes the counts as an optional third argument. -
A Next.js server error's frames can be mapped inside the function that threw (CORE-550). Next
writes a.mapnext to every server chunk, butoutput: 'standalone'and a Vercel function leave
them out;addNextServerSourceMapsToTraces(distDir), run fromnext.config's
compiler.runAfterProductionCompile, adds each traced chunk's map to Next's file traces and strips
itssourcesContent.mapErrorFramesInProcess(frames)then maps frames in the calling process
(no worker pool, nophargus serve) to the repository path and line, and leaves a frame it cannot
map at its built position withunmapped: true;reportNextErrornow maps its frames with it, so
an error sent from a function nameslib/thrower.tsand its line. Both are new exports of
@pharn-dev/phargus/analyzer, withDEFAULT_MAX_IN_PROCESS_MAP_BYTES(8 MiB). Checked on Next.js
16.4.6 underoutput: 'standalone'and on a Vercel preview deployment (docs/LIMITS.mdsection 8). -
A Next.js error on a serverless function reaches pharn.dev.
reportNextError(error, request, context)from@pharn-dev/phargus/pharn, called inonRequestErrorininstrumentation.ts,
builds the allow-listed payload for that one error and starts one request without making the
hook wait: the promise goes to the platform'swaitUntil(@vercel/request-context, no
dependency), else it runs on its own with a 5 s timeout, so a route handler's 500 is not delayed.
It readsPHARGUS_PHARN_KEY(no key: nothing sent, nofetch), takes the commit from
VERCEL_GIT_COMMIT_SHA(orPHARGUS_COMMIT), sends frames mapped in-process where the chunk's
map was shipped and otherwise at their built position flaggedunmapped, sends nothing from a
non-productionVERCEL_ENVunlessPHARGUS_PHARN_PREVIEW_KEYis set, keeps at most 10 requests in flight, and never throws. It does not need
@pharn-dev/phargus/agent, so no sampler or request tracing starts.examples/nextjs-app/serverless
is a real Next.js 16 app showing it, installed on its own. -
An optional link sends error groups to pharn.dev. It is off until a key is set:
phargus serve
readsPHARGUS_PHARN_KEY(andPHARGUS_PHARN_URLfor a test intake) from the environment, and
the agent ignores both. Every 10 seconds it sends one request with the errors seen since the last,
grouped by signature: per group the class, code, origin, frames (repository-relative path, line,
column, function, andunmapped; a frame that is not in-app is sent with its function name
only), commit, count, first and last seen, and once the Node.js version. Never the message, stack
text, request paths or absolute paths: the payload is built from an allow-list and matches
docs/schema/production-errors.v1.json, the schema pharn.dev validates. HTTPS only (http:to
loopback for tests), no redirects, the key only in anAuthorizationheader, a bounded queue with
retries and backoff, a 5-minute pause after a 401 or 403 (reported once), andpharn.droppedon
thecounts:line. New entry point@pharn-dev/phargus/pharn:createPharnExporter(the
collector listener),createPharnSenderandbuildPharnPayload(for an in-process reporter),
DEFAULT_PHARN_URL. A collector listener can now take anerrorcallback, called for every error
the collector keeps, not only the 10 a window lists. A test reads the built agent and fails if it
holds code that opens a connection. -
An error has a signature that survives a deploy. Every error a collector window lists carries
signature:v1:and the SHA-256 of its class and the repository path and function name of its
3 innermost in-app frames, with no line, column, message orcode, so an edit above a frame keeps
it and a renamed function gets a new one. Without in-app frames (a collector with no repository
root) it falls back to file basenames. A weak signature carriessignatureFlags(anonymous,
unmapped,no-in-app-frames); windows read back from disk get it recomputed. The algorithm is
specified indocs/API.mdso a receiver can recompute it, anddocs/LIMITS.mdsays when two
bugs merge and one splits. New collector exports:errorSignature,groupErrors(count, first
and last seen per signature) and typesErrorSignature,ErrorSignatureFlag,ErrorGroup,
SignableError. -
Error frames name the source file and line, not the built file. The collector maps each error's
frames through source maps, off its stream pipeline:createCollector({ symbolizeErrorFrames })
takes a function, andcreateErrorFrameSymbolizer({ repoRoot })from
@pharn-dev/phargus/analyzerbuilds one that runs on the symbolization worker, with its caps
(32 MiB per built file or map by default,DEFAULT_MAX_ERROR_MAP_BYTES) and reads confined to the
repository root.phargus serve --repo-root <dir>(orPHARGUS_REPO_ROOT) turns it on. Each
frame then carriesinApp, a repository-relativepath(in-app frames only: never a full path)
and, when it could not be mapped,unmapped: truewith its built position kept. A map whose
source lies outside the root is refused, a malformed map costs only its own file's frames, and a
dependency, a file outside the root or a Node internal frame isinApp: false. A symbolizer
failure keeps the error with the agent's frames and counts it (collector.symbolization,
collector.symbolizeFailedon thecounts:line). New exports:createErrorFrameSymbolizer,
DEFAULT_MAX_ERROR_MAP_BYTES,ErrorFrameSymbolizer,ErrorFrameSymbolizerOptions(analyzer),
and typesErrorFrame,SymbolizeErrorFrames,ErrorSymbolization(collector). -
captureError(error)(agent) reports an error your application handled: it writes the same
errorline as an uncaught exception, with originhandledand thetraceIdof the request in
progress, so a framework's 500 is tied to the error behind it. It accepts any value (a non-Error
is recorded by its type), never throws, does nothing while the agent is not running, and queues
the line in the agent's non-blocking output instead of writing it synchronously. At most 10
handled error lines are written per second; the rest are counted in the sample line's
dropped.errors(present once above 0), which collector windows keep and the dashboard shows.
The collector accepts originhandled.docs/API.mdand the README give recipes for an Express
error middleware, a FastifyonErrorhook and a Next.jsonRequestErrorininstrumentation.ts;
examples/express-appnow reports itsGET /errorthrough an Express-shaped error middleware,
and newexamples/fastify-appandexamples/nextjs-appcover the other two, without installing
any framework. -
Every window and span names the commit its process runs. The agent reads
PHARGUS_COMMITonce at
start, or else the first ofVERCEL_GIT_COMMIT_SHA,RENDER_GIT_COMMIT,
RAILWAY_GIT_COMMIT_SHA,HEROKU_BUILD_COMMITandHEROKU_SLUG_COMMITthat is set, and writes it
in one header line ({"type":"header","pid":…,"commit":"…"}) before any other line. A value that
is not 7 to 40 hexadecimal characters is ignored, counted (commitIgnored) and warned about on
stderr; the agent never runsgitor reads.git, and with no variable set no header line is
written. The collector attaches the commit to windows and spans (commit), the dashboard header
shows the short sha or "commit unknown", and OTLP resources carry it asvcs.ref.head.revision. -
The agent records uncaught exceptions and unhandled rejections. Each one becomes one NDJSON line
withtype: "error":class,code(only when it is letters, digits and_),origin
(uncaughtorrejection), up to 32frames(file,line,column,function) parsed from
the stack string, thetraceIdof the request in progress,pidandtimestamp. It is written
synchronously, so it reaches the output before the process exits. The agent listens on
uncaughtExceptionMonitoronly: whether the process dies, its exit code and its stderr do not
change. The message is left out unlessPHARGUS_ERROR_MESSAGES=1(config keyerrorMessages).
Collector windows carry anerrorsfield (countand the first 10 errors) when they received
any (each error with the run'scommit), persisted windows keep it, and the dashboard lists them. New types:ErrorRecord,
ErrorFrame,ErrorOrigin(agent),WindowError,WindowErrors(collector).
Fixed
- A process that was stopped and resumed (
SIGSTOP, a paused container, a suspended serverless
instance) no longer reports the stop as event-loop delay, and an event-loop alert no longer fires
on every resume. When the time since the agent's previous sample is longer than
max(5 × PHARGUS_INTERVAL_MS, 1 s), the event loop spent more than half of it idle and the
process used less CPU time than half of it, the sample carries `...
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; `createNdjsonExport...
v0.2.1
Fixed
- The backpressure probe no longer double-counts a stall on
http.ServerResponseand
http.ClientRequest. On newer Node releases the message flushes to its underlying socket after
write()returns, outside the synchronous window the probe's wrapper suppresses, so the probe
started a second, separate stall for that socket even though it was the same write already
tracked as a stall on the message.createBackpressureProbenow recognizes a socket covered by
an open stall on its_httpMessageand skips observing it, so one slow write is reported once.
v0.2.0
Security
- Behavior change:
symbolizeStackFramesnow confines reads to the working directory whenroots
is left out. Frames whose built file or source map lies outside the working directory are no
longer read; they come back unchanged unless you passrootsnaming the directories to read
from, orroots: nullfor the old unconfined behavior. - Dashboard login no longer puts the token in a request line. Open
/login#token=<token>: the
token is in the URL fragment, which the browser never sends; the public login page removes it
from the address bar and history, then posts it as JSON to the newPOST /session(4096-byte
cap, JSON only, constant-time compare), which answers204with the sameHttpOnly,
SameSite=Strictsession cookie, or401with none.phargus serveand the dashboard script
now point at this link./?token=<token>still works but is deprecated and will be removed in a
later release; the first use emits aPHARGUS_DEP_TOKEN_QUERYdeprecation warning.
Added
-
PHARGUS_CONFIGpins the agent's config file. When set, the agent loads exactly that.json
or.jsfile (a relative path resolves against the working directory) and does not look for
phargus.config.jsonorphargus.config.jsthere. An empty value, a missing or unreadable
file, something that is not a regular file, or any other extension rejects with a
PhargusConfigErrornamingPHARGUS_CONFIG, and never falls back to the working-directory
lookup.docs/THREAT-MODEL.mdgains row I1 for the config file as code-execution surface. -
phargus serve, a command-line way to get the dashboard without writing a collector. The
package now has abin, sonode --import @pharn-dev/phargus/agent app.mjs | npx phargus serve
reads the agent's NDJSON from stdin (or-), replays a capture file given as an argument,
aggregates it into windows and serves the dashboard. Flags:--port(default 7070),--host
(default127.0.0.1),--token,--window-ms(default 1000) and--max-line-bytes, plus
--helpand--version.PHARGUS_TOKENsupplies the token, and a non-loopback--host
without one is refused with exit code 2 before anything binds. Diagnostics go to stderr only:
the dashboard URL, an input-ended line and acounts:line (decoder.invalid,
decoder.oversized,collector.ignored,dashboard.droppedEvents). The server keeps running
after the input ends. SIGINT and SIGTERM close the server and the collector and exit 0; a stuck
shutdown is forced out with exit code 1 after 5 seconds. Exit codes: 0 success, 1 runtime error
(unreadable file, port in use), 2 usage error. Errors print without a stack unless
PHARGUS_DEBUGis set. The CLI is ESM-only and is not anexportssubpath.
@pharn-dev/phargus/dashboardnow also exportsisLoopbackHost.npm run check:exports,
check:packageandcheck:installverify thebin. -
phargus serve --allowed-host <host>, repeatable, passed to the dashboard'sallowedHosts.
It lets a browser reach a server bound with--host 0.0.0.0(for example in a container) by
IP or hostname instead of getting421. A bare name matches on any port;host:portmatches
exactly. An empty value, or one with whitespace or/, is a usage error (exit code 2). It does
not lift the token requirement for a non-loopback--host. -
Webhook alert sinks take an optional
headersoption, for example
{ authorization: 'Bearer …' }, sent with every request (review finding F23). It works on
createWebhookSinkand on a{ type: 'webhook' }sink config. Headers are copied and checked
when the sink is created: a name must be an HTTP token, a value must be a string with no control
characters (tab aside) and nothing above U+00FF, and the same name twice in different case is
rejected.content-typeis reserved for the sink's ownapplication/json, so supplying it is a
TypeErrorrather than a silent override.__proto__is rejected too, because Node'sfetch
drops it. Errors name the header, never its value. -
OTLP metrics export (
@pharn-dev/phargus/otel) now carries every window field (review finding
F22). New gaugesphargus.gc.pause.maxandphargus.backpressure.stall.max(ns); new delta
monotonic sumsphargus.gc.pause.totalandphargus.backpressure.stall.total(ns),
phargus.backpressure.events({event}),phargus.window.samplesand
phargus.window.late_samples({sample}, from the window'scountandlate). The metrics
resource now carriesservice.instance.id,host.nameandprocess.pidbeside
service.name, so several instances no longer merge into one series.service.instance.id
defaults to a random UUID generated once per process; the newserviceInstanceIdoption on
createOtlpMetricsExporterandtoOtlpMetricsoverrides it, and an empty or non-string value
throws aTypeError. The trace exporter is unchanged. -
docs/API.md, a reference of every supported export per subpath.npm run check:exportsnow
also compares each subpath's runtime export names with an exact expected list, throughimport
andrequire, and fails on a name added or missing.
Fixed
- Lower memory cost of HTTP tracing under load. The tracer's span buffer kept each of its 1024
most recent spans as an object plus four strings, and under load each lived long enough to be
promoted by V8 and die in the old generation (about 3× the agent-off promotion rate on a
promise-heavy server, and about 25 MiB more RSS after a minute). Spans are now stored as bytes
in preallocated slots, which take about 280 KiB for the default 1024 spans. Promotion and
steady-state RSS now match the agent-off run. What is buffered, dropped and exported is
unchanged. - Lower per-request CPU cost of HTTP tracing. Trace and span ids are now cut from a 4 KiB buffer
of CSPRNG bytes refilled as it runs out, instead of onerandomBytes()call (and Buffer) per
id; a CPU profile of the overhead benchmark put those calls at about 16% of the busy time of a
traced server. Ids keep their format (lowercase hex, never all zeros) and no byte is used twice. - The dashboard no longer reports a normal SSE client disconnect as a server error. A write to a
connection the client had already closed (EPIPE) is now treated likeECONNRESET: the client
is cleaned up andonError(or the process warning) is not called. Other errors on an SSE
response or socket are still reported, and cleanup stays idempotent. summarizeHeapSnapshotanddiffHeapSnapshots(@pharn-dev/phargus/analyzer) no longer time
out on large snapshots within a raisedmaxSnapshotBytes(review finding F27). The task timeout
is nowmax(30 s, size / 20 MB/s), summed over both files for a diff, computed by the new
heapSnapshotTimeoutMs(bytes)export. It applies when notimeoutMsis passed and the pool is
the one the call makes or one fromcreateHeapSnapshotPool()withouttaskTimeoutMs. An
explicittimeoutMsalways wins, and a pool made withtaskTimeoutMs,createWorkerPoolor
anything else keeps its own timeout. At the default 256 MiB cap the timeout stays 30 s.- Collector persistence no longer backpressures
consume()(review finding F25). A slow disk used
to hold every window up behind the append, all the way back to the source. Windows now go
through a bounded queue and are appended one at a time, in emission order, off the pipeline.
persist.maxQueueSizesets how many wait (default 1024); it must be a positive safe integer,
orcreateCollectorthrows aRangeError. When the queue is full the oldest window is dropped.
collector.persistence.droppedcounts those drops andcollector.persistence.failedcounts
windows whose append failed (both integers). A failed append still rejectsconsume()with the
append error, now without waiting for the source to end.close()and the end ofconsume()
wait for the queue to drain, with no time limit, so a disk that never completes an append
stallsclose().close()stops accepting windows before it drains, so aconsume()still
running cannot hold it open; a window that arrives after it is counted infailed. - OTLP exporters (
@pharn-dev/phargus/otel) no longer lose spans and windows under load (review
finding F2). They used to send one request per exported span or window, with one request in
flight, and silently dropped the newest batch once 64 were queued. They now batch: pending
items go out in one request whenmaxBatchSize(default 512) items are pending or after
flushIntervalMs(default 1000 ms), one request at a time. At mostmaxQueueSize(default 2048) items are held; when full, the OLDEST pending items are dropped, counted and reported
throughonErroras aggregated "dropped" reports. New countersdroppedItems,exportedItems
andfailedItemssit besidedroppedBatchesandfailedBatches. The flush timer is
unref()ed and armed only while items are pending. A record that cannot be encoded fails only
itself. Behaviour change: one export call is no longer one request, and the first send waits up
toflushIntervalMsunless a full batch is pending; callclose()orflush()before exit.
queueCapacityis deprecated: still accepted and validated, but it no longer bounds anything
(the queue holds items, not batches); usemaxQueueSize. - Dashboard: a client that connects to
/eventsnow receives the collector's whole history
(every buffered alert, window and span) instead of losing part of it to the live-event drop
queue; with full buffers it previously got no alerts and a truncated window history. The replay
is written in one call outside that queue, alerts first, then windows, then spans.
maxBufferedEventsanddroppedEventsnow cover live events only. - Dashboard: a request whose
Hostis not allowed still gets421, but now with a short
text/plainbody...
v0.1.0
First release of Phargus (@pharn-dev/phargus).
Added
- Release preparation workflow that validates a tarball without publishing, with explicit opt-in for later GitHub Release publishing.
- Installed-package checks for ESM/CJS imports and types, analyzer workers, plugin sandbox, and the agent → collector → dashboard SSE flow.
- Single npm package with subpath exports, built as both ESM and CommonJS.
- Open-source baseline:
README.md,SECURITY.md,CODE_OF_CONDUCT.md,docs/THREAT-MODEL.md,docs/LIMITS.md, issue and pull request templates. - CI: format, lint, typecheck, test, build, action-pin checks, CodeQL and gitleaks.
- Manual release process with npm Trusted Publishing and provenance.
- Agent: event loop delay and memory samplers driven by a sampler controller.
- Agent: NDJSON export stream with bounded, drop-oldest backpressure, to stdout or a file.
- Agent: configuration from
PHARGUS_*environment variables andphargus.config.{js,json}. - Agent: GC sampler (count and pause times by kind) from
PerformanceObserver. - Agent: stream backpressure probe that reports stalled writes by call site.
- Agent:
require('@pharn-dev/phargus/agent')/import '@pharn-dev/phargus/agent'(or--require/--import) starts the agent once per process. - Agent: automatic trace id per incoming
node:http/node:httpsrequest throughAsyncLocalStorage, honouring an incoming W3Ctraceparent;currentTraceId(). - Agent: V8 heap space statistics in every sample and on-demand heap snapshots (
takeHeapSnapshot). - Agent: on-demand allocation sampling through the inspector (
sampleAllocations). - Agent: a parser for
node --trace-deoptoutput (createDeoptParser). It does not capture the output itself. - Agent: runs under the Node permission model; a denied grant disables only that feature with a typed
PhargusPermissionError;isPermissionModelEnabled()andcheckPermission(). - Agent: HTTP spans exported as NDJSON lines next to samples.
- Collector (
@pharn-dev/phargus/collector): fixed time windows with integer math and ring buffers of recent windows, alerts and spans. - Collector: window-based alerts with per-metric thresholds.
- Collector: alert sinks for stdout, a file and a webhook (Node core
fetch). - Collector: opt-in persistence of recent windows to an append-only file, restored on start.
- Dashboard (
@pharn-dev/phargus/dashboard): SSE server with token gating for non-loopback binds. - Dashboard: vanilla-JS live page with event loop, memory, GC, alerts and a trace waterfall of recent requests.
- Analyzer (
@pharn-dev/phargus/analyzer): Worker Thread pool with heap-snapshot summaries and diffs. - Analyzer: source-map stack-trace symbolization on the worker pool.
- Plugin runner (
@pharn-dev/phargus/plugin-runner): user rules in anisolated-vmsandbox in a child process, with a memory limit and a timeout. - Plugin runner: built-in rules (event loop lag, GC pause share, heap growth) and
loadRulesDirectory. - OpenTelemetry (
@pharn-dev/phargus/otel): opt-in OTLP/HTTP JSON export of windows as metrics and spans as traces. - Examples:
examples/express-app(agent in the app, collector and dashboard in a second process) andexamples/worker-pool. - Agent: every sample line carries cumulative
dropped: { samples, spans }loss counters. - Agent:
createDeoptParser({ maxEvents, maxLineLength })anddroppedEvents(). - Agent:
createSamplerController(onSample, { onError }); newPhargusSamplerWarningandPhargusBackpressureWarningprocess warnings. - Dashboard:
allowedHostsoption for names the dashboard is reached by (reverse proxy, container port mapping). - Collector and OpenTelemetry:
closeTimeoutMsoption on the webhook sink and the OTLP exporters;WindowStore.close(). - Analyzer:
maxSnapshotBytesoption (default 256 MiB) andHeapSnapshotTooLargeError(ERR_HEAP_SNAPSHOT_TOO_LARGE);DEFAULT_RESOURCE_LIMITS,DEFAULT_MAX_SNAPSHOT_BYTES. - Analyzer: symbolizer
rootsoption (reads confined byrealpath) andmaxFileBytes(default 64 MiB);DEFAULT_MAX_SOURCE_FILE_BYTES. - Plugin runner:
maxFindings(default 10 000) andmaxResultBytes(default 1 MiB) options. bench/overhead.mjs(agent-on versus agent-off benchmark),bench/soak.mjs(leak checks under load) and a nightly workflow that runs both.- CI:
npm run check:packagein the Build job checks the tarball contents and thatengines.nodematches.nvmrc.
Changed
- Renamed the project and npm package to Phargus (
@pharn-dev/phargus). Imports and preloads now use@pharn-dev/phargus/<subpath>; configuration usesPHARGUS_*environment variables andphargus.config.{js,json}. Existing integrations must update those names. - Renamed public errors and warnings to
Phargus*, error codes toPHARGUS_*, built-in rule IDs and OpenTelemetry metric names tophargus/...andphargus.*, and the dashboard session cookie tophargus_token(existing dashboard sessions must sign in again). engines.nodeis now>=22.18.0, and.nvmrcpins22.18.0; required CI jobs run on that floor.- The package no longer ships declaration maps or the analyzer test fixture;
.js.mapfiles embed their sources. - Agent: an unknown
PHARGUS_*variable prints one warning on stderr and is ignored, instead of disabling the agent. - Agent: samples and spans are queued in separate lanes, each bounded by
queueBound; sample lines are written first. - Agent: the backpressure probe also covers
Duplex,Transform,PassThrough,net.Socket,tls.TLSSocket,http.ServerResponseandhttp.ClientRequest. - Agent: an ESM and a CJS copy of the agent share one set of prototype wrappers.
- Agent:
traceparentwith an all-zero parent id starts a new trace; versions other than00are parsed with the00layout. - Dashboard: requests whose
Hostis not allowed get421; a cross-originOriginon/eventsor a non-GET request gets403. - Dashboard:
?token=is accepted only onGET /and exchanged for anHttpOnly,SameSite=Strictcookie; assets and/eventstake the cookie orAuthorization: Bearer. - Dashboard: malformed-request warnings are rate-limited to one report plus one summary per 10 s; client resets are not reported.
- Collector and OpenTelemetry:
close()waits at mostcloseTimeoutMs, then drops queued batches and aborts in-flight requests, counting both. - Collector:
collector.close()closes the sinks first and latches the window store. - Analyzer: every pool worker runs with
resourceLimits(default 512 MiB old, 64 MiB young generation). - Analyzer: the heap-snapshot worker streams the file; snapshots must list
snapshot,nodesandstringsin V8's order and have at most 262 144 distinct object names. - Analyzer: workers no longer inherit entry-point flags such as
--input-type,-eor--inspect. - Plugin runner: the sandbox child receives the host's
--permission,--experimental-permissionand--allow-*flags.
Fixed
- Agent: requests that arrive while the agent configuration loads are traced.
- Agent: spans no longer evict metric samples from the output queue under load.
- Agent: disabling the backpressure probe or tracing never leaves a throwing
writeoremitbehind and never removes a wrapper another library installed later. - Agent: the stream
writewrappers keep the original arity (write.length === 3). - Agent: a throwing
onSamplecallback no longer becomes an uncaught exception. - Agent: the deopt parser no longer keeps every event forever.
- Analyzer: an oversized heap snapshot can no longer abort the host process with a fatal out-of-memory error.
- Analyzer: a host started with
--input-type=module -ecan start analyzer workers. - Collector:
append()aftercollector.close()no longer reopens the persistence file. - Dashboard: a stalled SSE client no longer retains dropped events.
Security
- Dashboard:
Host/Originallowlist against DNS rebinding. - Dashboard: the token no longer appears in page, asset or SSE URLs; the session cookie holds an HMAC of the token, not the token.
/eventsand error responses sendnosniff, adefault-src 'none'CSP andReferrer-Policy: no-referrer. - Collector and OpenTelemetry: webhook and OTLP requests never follow redirects (a 3xx is a failed delivery) and read at most 64 KiB of a response body.
- Files the agent, the window store and the file alert sink create are mode
0600. - Analyzer: symbolizer parse errors no longer quote file content.
- Plugin runner: rule results are capped in the child and validated on the host; rule error messages are cut to 4 096 characters.