Zhipu Details GLM-5 Coding Agent Inference Failure Fixes
Zhipu AI disclosed the root causes of garbled output and repetition anomalies in GLM-5 during high-concurrency Coding Agent tasks, attributing them to race conditions in inference infrastructure rather than model defects. The team successfully reproduced issues by simulating Prefill/Decode separation pressure and fixed multiple independent bugs, significantly improving long-context stability. This case highlights the critical Infra engineering challenges and debugging methodologies required to scale LLM applications.
Full Report
Contents6 sections
Belief in Scaling Laws not only drives us to push the boundaries of model parameters and data scale, but also constantly tests the limits of Infrastructure engineering. This process is accompanied by inevitable growing pains, which we term "Scaling Pain." As large model applications shift from simple dialogue to more complex, long-horizon Coding Agent tasks, our inference infrastructure faces unprecedented pressure, handling hundreds of millions of Coding Agent calls daily. Over the past few weeks, some users encountered various anomalies when using the GLM-5 series models for complex Coding Agent tasks: garbled output, repetition, and occasional rare characters. These issues do not exist in standard inference environments; they are triggered only in high-concurrency, long-context Coding Agent scenarios and are difficult to reproduce consistently. After weeks of deduction, troubleshooting, and stress testing, we finally identified and fixed several independent underlying race condition bugs. We also implemented targeted optimizations for the system bottlenecks revealed by these issues, significantly improving the stability and efficiency of the inference system. In this article, we share the lessons learned from this exploration to help everyone overcome the Scaling Pain of Coding Agent inference.
From Offline Reproduction to Anomaly Identification
Since March, we have observed three types of anomalies in GLM-5's online monitoring and user feedback: garbled output, repetition, and rare characters. On the surface, these phenomena resemble the common "intelligence degradation" seen in long-context scenarios. However, since we did not deploy any optimizations that reduce model precision, a more critical question arises: Do the anomalies stem from the model itself or from the inference pipeline? If they originate from the model, the anomalies would manifest as stable, reproducible behaviors for specific inputs. Conversely, if the anomalies correlate with system load or runtime state, they likely point to issues within the inference infrastructure's pipeline or state management. During the initial investigation, we replayed user-reported bad cases locally and repeated inference on the same batch of requests hundreds of times, but failed to reproduce the anomalies. This suggested that the issue was likely not inherent to the model itself. To further simulate the pressure of the online environment, we anonymized online logs while preserving the original concurrency distribution and request timing as much as possible, then performed full-volume replays locally. Initially, the anomalies still could not be reproduced. It was only after adjusting the Prefill/Decode (PD) separation ratio and continuously increasing system load—simulating peak-hour Prefill backlog and KV Cache pressure on the Decode side—that we stably reproduced 3-5 anomalies per approximately 10,000 requests. The characteristic of being "independent of request content but correlated with system pressure" indicated that the problem likely stemmed from inference state management under high load. Meanwhile, the frequency of anomalies reproduced offline remained lower than that reported online, suggesting that existing detection methods might miss some cases or that certain trigger scenarios were not yet covered. Reliably identifying anomalous outputs became a new challenge. Among the three anomaly types, repetition is relatively easy to detect, whereas garbled output and rare characters are more tricky. We tried heuristic methods such as regular expressions and character set matching, as well as model-based discrimination approaches. The former suffered from obvious false negatives and false positives, while the latter struggled to meet the efficiency requirements for large-scale ablation experiments. These limitations made anomaly detection itself a bottleneck in the localization process.

Figure 1: Speculative decoding metrics can serve as important references for anomaly detection. After repeatedly analyzing inference logs, we discovered an unexpected entry point: speculative decoding metrics could serve as important references for anomaly detection. Speculative decoding is originally a performance optimization technique where a draft model generates candidate tokens, which are then verified by the target model to decide whether to accept them, thereby improving decode efficiency without altering the final output distribution. As shown in Figure 1, we observed that two metrics (spec_accept_length: the length of the prefix of draft tokens consecutively accepted by the target model; spec_accept_rate: the proportion of draft tokens accepted) exhibited stable patterns when anomalies occurred:
- Garbled output and rare characters: Typically accompanied by extremely low
spec_accept_length, meaning almost all candidate tokens generated by the draft model were rejected by the target model. This indicates a significant deviation between the KV Cache state seen by the target model and what the draft model expected. - Repetition: Typically accompanied by a higher
spec_accept_rate, suggesting that corrupted KV Cache may cause attention patterns to degrade, pushing the generation process into high-confidence repetitive loops.
Based on these observations, we implemented an online anomaly monitoring strategy: When spec_accept_length remains below 1.4 and the generated length exceeds 128 tokens, or when spec_accept_rate exceeds 0.96, the system actively aborts the current generation and hands the request over to the load balancer for retry. This strategy expanded speculative decoding from a mere performance optimization technique into a real-time monitoring signal for output quality, becoming a key tool in subsequent ablation experiments.
BugFix #1: KV Cache Race Condition in PD Separation Architecture
After observing a clear correlation between anomalous outputs and concurrent pressure, we further analyzed the root cause. By examining the request lifecycle and the execution timing of PD separation within the inference engine, we found that the issue stemmed from inconsistencies between the request lifecycle and the timing of KV Cache recycling and reuse, leading to KV Cache reuse conflicts.
- Root Cause Analysis: Async Abort Triggering KV Cache Reuse Race Condition
To limit tail latency, we introduced a timeout-based request termination mechanism in the inference engine: If the Prefill stage does not complete within the specified time, the Decode side executes an Abort on the request and recycles its occupied KV Cache resources. However, this Abort signal was not correctly propagated to the Prefill side, and the Decode side lacked sufficient information to determine whether the KV Cache could be safely recycled and reused. Consequently, after the Decode side aborted the request and allocated the corresponding KV Cache space to a new request, previously initiated RDMA writes and ongoing operations continued to execute, causing a race condition.
Figure 2: Illustration of KV Cache Race Condition in PD Disaggregation Scenario
Figure 2 illustrates the timing interaction between two requests across Prefill and Decode stages in a PD (Prefill-Decode) disaggregated architecture, highlighting the resulting KV Cache race condition. Initially, Req1 is dispatched to Prefill-1 (P1) and Decode (D). Due to scheduling or queuing delays, Req1 waits on the P1 side before starting its Prefill Forward pass. Meanwhile, the Decode side does not receive the corresponding KV Cache data within the expected timeframe, triggering a timeout mechanism that aborts Req1. Subsequently, the Decode side reclaims the KV Cache slots occupied by Req1 but fails to properly notify P1. Shortly after, a new request, Req2, arrives and is assigned to Prefill-2 (P2) and Decode. Due to memory reuse policies, Req2 is allocated the same KV Cache address previously used by Req1. P2 begins executing the Prefill Forward pass and initiates KV Transfer, completing quickly enough for the Decode side to enter the generation phase. However, the KV Cache write operation initiated by P1 for Req1 continues in the background. This stale data overwrites the VRAM region now reused by Req2, corrupting part of Req2’s KV Cache. Consequently, when Req2 reads this corrupted data during the Decode stage, it produces anomalous output.
2. Fix Strategy: Ensuring Temporal Consistency for KV Cache Release
To eliminate the aforementioned race condition, we introduced stricter temporal constraints in the inference engine, establishing explicit synchronization between request termination and KV Cache write completion. Specifically, upon triggering an Abort, the Decode side sends a notification to the Prefill side. The Prefill side returns a "release-ready" signal only when one of the following conditions is met: the relevant RDMA writes have not yet started, or all submitted writes have completed. The Decode side is permitted to reclaim and reuse the corresponding KV Cache slots only after receiving this confirmation. This mechanism ensures that KV writes do not cross VRAM reuse boundaries, thereby preventing cross-request KV Cache corruption.
Fix Results: After deploying this fix, the incidence rate of anomalous outputs dropped from approximately 0.15% to below 0.03%. These results demonstrate that in PD disaggregated architectures, explicit consistency constraints must be established between cross-node data transfers and VRAM reuse to avoid similar issues.
BugFix #2: Missing Load Timing in HiCache
Coding Agent scenarios significantly increase input lengths (averaging over 70K tokens) while maintaining high prefix reuse rates. Such workloads make HiCache (multi-level KV Cache) a critical optimization for online services. However, current implementations fail to guarantee that data is fully loaded before use when KV Cache swap-ins overlap with computation, leading to potential access of unready KV Cache entries.
1. Root Cause Analysis: Read-before-Ready Due to Lack of Pipeline Synchronization
Through timing analysis of HiCache execution, we identified the issue in the cache read path of DSA HiCache. The system asynchronously swaps in historical prefix caches from CPU memory, overlapping the Load Stream with the Forward Stream to improve throughput. As shown in Figure 3(a), the Load Stream handles loading KV Cache and Indexer Cache, while the Forward Stream sequentially executes Index calculation followed by Sparse Attention. Theoretically, the Indexer calculation in the Forward Stream should only start after the corresponding Indexer Cache has finished loading. However, in the original implementation, this dependency was not explicitly enforced. Specifically, the Indexer operator did not establish a synchronization constraint with the completion of the Load Indexer Cache operation (indicated by the red dashed area in Figure 3). Consequently, the Forward Stream might begin execution before the Load Stream completes data loading, resulting in a Read-before-Ready access pattern where data is read before it is fully loaded. This causes Index calculations to operate on incomplete or uninitialized data, affecting subsequent Sparse Attention results and ultimately leading to output anomalies.

Figure 3: Illustration of HiCache Read Pipeline Timing Anomaly and Fix
2. Fix Strategy: Refactoring Operator Pipeline Atomicity
To resolve this issue, we modified the HiCache read pipeline (as shown in Figure 3(b)), introducing explicit synchronization constraints between data loading and computation:
- Explicit Synchronization Constraint: A synchronization point with the Load Stream is introduced before the Indexer operator starts, ensuring that the Indexer Cache for the corresponding level has been fully loaded. The Forward Stream only initiates computation once the data is ready, thereby avoiding Read-before-Ready accesses.
After deploying this fix, under identical workload conditions, anomalies caused by execution timing inconsistencies completely disappeared, and system behavior stabilized. This fix has been submitted to the SGLang community via Pull Request #22811.
Optimization: Hierarchical Storage for KV Cache (LayerSplit)
The two race conditions described above reveal a common system bottleneck: in long-context Coding Agent Serving scenarios, the Prefill stage dominates system performance. To control Time to First Token (TTFT) caused by Prefill queuing, we introduced timeout-based Abort; to alleviate KV Cache capacity pressure on the Prefill side, we introduced HiCache. After fixing these state consistency issues, we returned to the core bottleneck itself: how to improve Prefill throughput and reduce GPU memory pressure for KV Cache on the Prefill side. To this end, we designed and implemented LayerSplit, a hierarchical storage solution for KV Cache.
Coding Agent workloads typically exhibit characteristics such as long context lengths and high Prefix Cache hit rates. In this scenario, the Prefill stage often becomes the primary performance bottleneck of the system, making Context Parallelism (CP) the main parallel strategy for online Prefill nodes. However, the existing open-source implementation in SGLang suffers from redundant KV Cache storage, causing limited KV Cache capacity to become the limiting factor for GPU compute resource utilization.

Figure 4: LayerSplit, a hierarchical storage solution for KV Cache

Figure 5: Throughput improvement with GLM-5.1 + LayerSplit across different sequence lengths. Figure 5 illustrates the performance gains achieved by this optimization when request lengths range from 40k to 120k, under a condition where the Cache hit rate reaches 90%. Experimental results show that system throughput improves by 10% to 132%, with benefits becoming more significant as context length increases. Overall, this optimization significantly enhances the system's processing capability in Coding Agent scenarios.
Summary
When intelligence truly enters high-concurrency, long-context Coding Agent scenarios, the challenges facing inference infrastructure extend beyond just throughput, latency, and availability—maintaining output quality becomes critically important. Every pursuit of Scaling Laws must be supported by equally rigorous systems engineering. We share these experiences in hopes of helping the community avoid some pitfalls and collectively refine inference infrastructure capable of supporting the future of AGI.
Acknowledgments
This blog post presents our research into a series of system-level issues in Coding Agent serving, including the reproduction and analysis of these problems, along with corresponding optimization solutions. We thank Zhongke Jiahe (Beijing) Technology Co., Ltd. and the team at the State Key Laboratory of Processor Chip Architecture, Institute of Computing Technology, Chinese Academy of Sciences, for their collaboration and support.
Technical blog link: https://z.ai/blog/scaling-pain