Skip to content

v0.3.0

Choose a tag to compare

@github-actions github-actions released this 24 Nov 16:53
e3bb941

Added

  • A file output now has a size bound: PHARGUS_OUTPUT_MAX_BYTES (config key outputMaxBytes,
    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 mode 0600, 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
    --permission a file output now also needs --allow-fs-write=<file>.1 and
    --allow-fs-read=<file> (see docs/PERMISSIONS.md).
  • PHARGUS_SPAN_BUFFER (config key spanBuffer, 0 to 65536, default 1024) sets how many spans the
    agent keeps per sampling interval; the rest are counted in dropped.spans. 0 turns HTTP
    tracing off and keeps the samplers and the backpressure probe: nothing is patched or subscribed,
    no span line is written, and currentTraceId() returns undefined. The variable is read before
    anything is patched, like PHARGUS_ENABLED; an invalid value disables the agent with a message
    naming it. bench/overhead.mjs has a notrace variant (the agent with PHARGUS_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 takes ms/s for time
    metrics and MiB/GiB for 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 the counts: line of phargus serve adds agent.droppedSamples and
    agent.droppedSpans. OTLP metrics are unchanged.
  • Collector windows now keep where writes stalled: backpressure.hotspots holds 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 after max(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 shows reconnecting. docs/LIMITS.md §2 explains why the figures are
    one window behind.
  • phargus serve now 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-passthrough turns it off; a file input never echoes. Output is
    bounded at 1 MiB waiting (further lines are dropped and counted as passthrough.dropped), and
    a closed stdout stops the passthrough with one stderr line. createNdjsonDecoder gets
    agentOnly: true, which skips non-agent JSON objects as foreign (a new counter and
    onSkipped reason with the raw line); the counts: line gains decoder.foreign and
    passthrough.dropped.
  • A request that closes before its response finishes (client disconnect, res.destroy(), a
    timeout) now leaves a span with aborted: 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 traceparent now keeps its parent-id: the span line carries it
    as parentSpanId (lowercased), and OTLP export sets the span's parentSpanId, so the span is
    no longer exported as a root. Spans of requests without a valid header have no parentSpanId.

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 in collector.persistence.failed and
    reported as one PhargusPersistenceWarning per run of consecutive failures, and windows and
    alerts carry on. persist.maxBytes now 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-write for 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: each consume() run follows the first sample pid it
    sees, skips samples from other processes as the new IgnoredReason other-process (counted in
    collector.ignored, passed to onIgnored), and emits one process warning saying how many
    other processes it skipped. Samples without a pid and 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. createRingBuffer keeps its type and behaviour.
  • summarizeHeapSnapshot, diffHeapSnapshots and symbolizeStackFrames no longer re-check the
    shape of their worker's reply; the inputs are still checked before any worker runs. The pool
    option is meant for a pool from createHeapSnapshotPool() or createSymbolizationPool(): 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 in failedItems, reported once through onError. 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() (from createWindowStore) 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() and close() close the file once a pending write finishes. The
    collector now validates windowMs and the alert rules once, in createCollector, instead of on
    every consume().
  • The agent's prototype patches (write on Writable, Duplex and OutgoingMessage, emit on
    the HTTP and HTTPS Server) are installed once and never removed. When the agent disables
    itself they stay in place and are inert: they call the original with the same this and
    arguments and return its result, so a wrapper another library installed on top keeps working.
    The globalThis registries 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 only globalThis entry.
  • Tests: the integration suites share one harness, test/support.ts, and npm test builds
    dist/ once per run in a Vitest global setup when it is older than src/. The cross-process
    build lock each suite carried is gone. Test files, test names and assertions are unchanged.

Removed

  • Breaking: createSinks, SinkConfig and SinkInput are gone from
    @pharn-dev/phargus/collector, and the collector's sinks option takes ready sinks only, built
    with createStdoutSink, createFileSink or createWebhookSink. A configuration object in
    sinks now throws a TypeError from createCollector that names the factory to use. Pass
    onError to the factory for a sink's delivery failures; onSinkError still sees a send() that
    rejects or a close() 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_QUERY warning. A ?token= query is no longer a credential: GET /?token=…
    answers 401 and sets no cookie. Open /login#token=<token> in a browser, or send
    Authorization: Bearer <token>.

  • Breaking: @pharn-dev/phargus/agent no 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_MS and
    DEFAULT_ALLOCATION_SITE_LIMIT (the sampleAllocations defaults, 32768 bytes, 1000 ms and 20
    sites, are in docs/API.md). Their types go with them: SamplerController, NdjsonExporter,
    NdjsonExporterOptions, EventLoopSampler, EventLoopSamplerOptions, GcSampler,
    BackpressureProbe, BackpressureProbeOptions, LoadAgentConfigOptions, AgentConfig,
    PermissionCheck and PermissionScope. The agent keeps ten runtime exports: currentTraceId,
    runWithTrace, takeHeapSnapshot, sampleAllocations, sampleHeapSpaces, createDeoptParser,
    ANONYMOUS_FUNCTION, DEPENDENT_CODE_KIND, PhargusPermissionError and SPAN_RECORD_TYPE, and
    the output-format types. To check a permission grant, use Node's process.permission.has().

  • Breaking: the agent no longer reads phargus.config.js, and PHARGUS_CONFIG accepts a
    .json path only. Move the settings to phargus.config.json (same keys). A config file is now
    parsed, never executed: a phargus.config.js in the working directory prints one warning naming
    phargus.config.json, and PHARGUS_CONFIG=settings.js disables the agent with the
    "unsupported extension" message. The unknown-variable warning lists the valid PHARGUS_* names
    instead of guessing one ("did you mean").

  • Breaking: the deprecated OTLP exporter option queueCapacity is gone from
    OtlpExporterOptions (and so from createOtlpMetricsExporter and createOtlpTraceExporter).
    It bounded nothing; use maxQueueSize, 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, the span-export layer and toSpanRecord (folded into the agent's export wiring),
    the event loop sampler's resolution option (always 10 ms), the exporter's spanQueueBound
    option and dropped total. 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
    asynchronous fs.write (libuv's thread pool) instead of through process.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 (see docs/LIMITS.md).

  • phargus --help (and --version) now win over a bad flag: phargus --bogus --help prints the
    usage and exits 0 instead of exiting 2.

  • phargus serve <directory> fails before the dashboard binds, with
    cannot read input file "<path>": EISDIR and exit 1, instead of printing the dashboard URL and
    then failing on the first read.

  • Docs: the README's V8 row names /agent for takeHeapSnapshot, sampleAllocations and
    createDeoptParser; docs/API.md says runWithTrace always starts a fresh trace id and that
    importing /agent starts the agent unless PHARGUS_ENABLED=false; FEATURES.md marks event
    loop min/p50 and GC counts by kind as stopping at the sample line and documents how window p99
    and mean are computed; FEATURES.md, ARCHITECTURE.md and the README diagram no longer show
    the plugin runner fed by the collector; the OTLP resource notes say host.name and
    process.pid describe the exporter's process; docs/PERMISSIONS.md says sampleAllocations
    needs --allow-inspector and 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.

  • diffHeapSnapshots now 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: loadRulesDirectory reports a rule file over 1 MiB as a
    RULE_FILE_UNREADABLE failure without reading it, and a run's watchdog now starts only once the
    sandbox child has loaded isolated-vm, so a cold first run with a short timeoutMs is no longer
    timed on process start-up (a child that does not start within 10 s fails as
    PHARGUS_SANDBOX_CRASHED). docs/THREAT-MODEL.md D2 now says a rule that exhausts memory ends
    as PHARGUS_RULE_MEMORY_LIMIT, PHARGUS_RULE_TIMEOUT or PHARGUS_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 whose timestamp is not a safe integer or is
    more than 24 hours ahead of the collector's clock is now malformed and 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 as late.

  • HTTP tracing no longer pins EventEmitter.prototype.emit for 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 rewrites req.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 finish or close instead of drain (a
    res.write(big) followed by res.end(), or a client that disconnects mid-stall) now reports
    its duration in totalStall, maxStall and its hotspot instead of 0.

  • A preloaded agent (--import or --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 integer pid; forked and cluster children each still run their own agent.

  • Off means off: with PHARGUS_ENABLED=false (or 0) or PHARGUS_OUTPUT=none the agent no longer
    patches http.Server.prototype.emit for a moment or executes phargus.config.js, and an agent
    that disables itself (for example after an output error) also disables its AsyncLocalStorage,
    so currentTraceId() is undefined everywhere 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
    returned false it no longer waits for a drain that had already fired, so later alerts are
    written and close(), collector.close() and consume() resolve again.

  • The collector stores a type: "span" record as a span only when it has the agent's span shape
    (hex traceId and spanId, string name, method and path, non-negative integer
    statusCode, startTimeMs and durationNs, and a valid parentSpanId or aborted when
    present); anything else is skipped and counted in ignored as 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: N now 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 one consume() 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 at maxLineBytes, 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 ) (a proj (copy) or Dropbox (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 through NODE_OPTIONS: it is forked with its
    stdout ignored and a minimal environment (PATH, SystemRoot on Windows, and
    PHARGUS_ENABLED=false), so it no longer receives NODE_OPTIONS or 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:
    summarizeHeapSnapshot and diffHeapSnapshots reject JSON nested more than 64 levels deep
    ("nesting too deep"), and the worker no longer keeps every distinct top-level key, only
    snapshot, nodes and strings. Both now fail with a WorkerTaskError instead.

  • The dashboard returns 400 for 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 serve exits with code 2
    before binding. Previously a loopback bind plus a public allowedHosts name served that name
    with no token. Such a name now needs a token of at least 16 characters, as a non-loopback bind
    does. The 421 body 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 /events with 503 while 64 clients are connected; closing one frees a
    slot.

  • Removed the dead Secure cookie branch: the dashboard serves plain HTTP only, so its session
    cookie is never Secure (now stated in docs/LIMITS.md).

  • The webhook sink and the OTLP exporters refuse a URL with a username or password when they are
    created (send credentials with the headers option), the OTLP exporters check headers as the
    webhook sink does, and a failed delivery no longer copies fetch'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.
    symbolizeStackFrames now reports a map as malformed (MalformedSourceMapError on its frames)
    when its sources is not an array or its mappings is 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 its sourceMappingURL comment is looked for.