Skip to content

perf(engine): every streamed chunk event builds a NodeRunResult and an LLMUsage it never uses #397

Open

Description

@Theysua

Summary

Every streamed chunk is lifted into an engine event that builds a full NodeRunResult, and with it an LLMUsage, which a chunk event has no use for. That is 17 extra objects and about 7 µs per chunk. The time is small; the allocations are not, because they are what drives the garbage collector while an answer is streaming. In a Dify worker streaming a 400-chunk answer they cause about 60% of the young-generation collections, and giving chunk events an existing result instead lowered the worker's CPU per run from 342 ms to 312 ms.

Where

Same on main at c2e4165 and in 0.8.0.

src/graphon/engine_events/base.py — every node event defaults to a new result:

class NodeEvent(EngineEvent):
    ...
    node_run_result: NodeRunResult = Field(default_factory=NodeRunResult)

src/graphon/node_events/base.py — a new result builds four mappings and a validated LLMUsage (14 fields, seven of them Decimal("0.0")):

class NodeRunResult(BaseModel):
    inputs: Mapping[str, Any] = Field(default_factory=dict)
    process_data: Mapping[str, Any] = Field(default_factory=dict)
    outputs: Mapping[str, Any] = Field(default_factory=dict)
    metadata: Mapping[WorkflowNodeExecutionMetadataKey, Any] = Field(default_factory=_default_metadata)
    llm_usage: LLMUsage = Field(default_factory=LLMUsage.empty_usage)

src/graphon/nodes/base/node.py — the per-chunk path passes no result, so the default is built for each chunk (the same holds for StreamReasoningEvent):

@_dispatch.register
def _(self, event: StreamChunkEvent) -> NodeRunStreamChunkEvent:
    return NodeRunStreamChunkEvent(
        id=self.execution_id,
        node_id=self._node_id,
        node_type=self.node_type,
        selector=event.selector,
        chunk=event.chunk,
        is_final=event.is_final,
    )

The one thing that is read from a chunk event's result is metadata: the iteration and loop handlers write the frame labels there in prepare_frame_event (event.node_run_result.metadata = {...}), and embedders read them back from any NodeEvent (Dify does, to tag chunks with the iteration or loop they belong to). So the result on a chunk event is in practice a carrier for those labels, and it is mutated in place, which is why a shared default instance would not be a safe fix.

Measurement

One event in isolation (Python 3.13.18, graphon 0.8.0, best of 7 × 20,000; allocations are the collector's own young-generation counter with collection disabled):

Time Allocations counted by the collector
LLMUsage.empty_usage() 4.8 µs 10
NodeRunResult() 6.7 µs 17
NodeRunStreamChunkEvent(...), default result 10.7 µs 21
NodeRunStreamChunkEvent(..., node_run_result=<existing instance>) 3.7 µs 4

With the default young-generation threshold of 2,000, the 17 extra allocations per chunk are one extra collection every 118 chunks.

In an embedder. Dify 1.19.0 with graphon 0.8.0, one Celery worker process with the gevent pool. Workflow: Start → LLM → End, the model stand-in streams 400 chunks over 4 s, 10 runs in flight. CPU is the worker container's cgroup usage; collector time and counts come from gc.callbacks. Six rounds of 40 runs per variant, the variants interleaved in two passes. The second column is a sizing experiment, not a proposed fix: the two chunk handlers above pass one module-level NodeRunResult().

Per run (400 chunks) Current Chunk events given an existing result
Worker CPU 342 ms (322–366) 312 ms (294–335)
Young-generation collections 5.15 2.08
Middle-generation collections 0.46 0.19
Full collections in 240 runs 8 4
Time inside the collector 38.6 ms 17.5 ms

Of the 30 ms difference, about 21 ms is collector time and about 9 ms is outside it. Two caveats on reading it:

  • Most of the collector time is full collections, and what one of those costs is a property of the embedder's heap, not of graphon: this worker holds about 1.1 million tracked objects and a full collection takes 0.8–1.0 s. I am following that up on the Dify side. The part that is graphon's is how often collections are triggered, and those counts are stable from round to round.
  • Full collections are few and large (one or two per round), so the CPU ranges overlap; the means are over 240 runs each.

A py-spy profile of the same worker blames 9.0% of its working time on LLMUsage.empty_usage and 4.5% on _default_metadata, all of it reached from the StreamChunkEvent handler. Those shares are mostly collections that happened to start at these allocation sites, so the table above is the number to go by.

Suggestion

The cost comes from one field doing two jobs: node_run_result is the result of a finished node, and it is also where frame labels for every event are kept. Two ways to separate them, from larger to smaller:

  1. Give the frame labels their own field on NodeEvent (a small mapping, or iteration_id / loop_id style fields), and let events that have no result carry none. This removes the allocations and the in-place mutation of a default, but it changes what embedders read, so it needs a transition for code that does event.node_run_result.metadata on any event.
  2. Keep the field and make the default cheap: NodeRunResult.llm_usage could default to one shared zero usage if LLMUsage values are treated as immutable, which removes 10 of the 17 allocations and most of the time without touching the event API. The four mappings and the result object would remain.

Happy to help with a pull request once a direction is chosen. The benchmark script, the collector timer and the raw rows are available.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions