RCSAgent: An LLM Agent Approach to Reference-Counting Semantics Recovery
Reliable understanding of memory-related API semantics is crucial for memory safety, yet the Python/C API documentation often omits reference counting (RC) specifications such as ownership transfer annotations. These omissions accumulate as documentation debt, complicating development and hindering memory safety analyses. Existing approaches based on manual maintenance, documentation crawling, or rule-based static analysis remain incomplete, particularly for implicit ownership transfers and newly emerging semantics. We present RCSAgent, a Large Language Model (LLM) agent built on the ReAct framework and equipped with code exploration tools for recovering missing RC semantics directly from source code. RCSAgent iteratively reasons about function implementations by invoking code exploration tools—including function-level and file-level code reading, cross-reference tracking, and PyObject structure inspection—to infer ownership transfer patterns. This enables it to handle complex cases involving macro expansion, field-level assignments, and inter-procedural control flow that challenge both rule-based analyzers and standard prompting strategies. We evaluate on two datasets collected from the CPython codebase: documented public API functions and undocumented PyAPI_FUNC entries with manually verified labels. RCSAgent achieves up to 97.7% precision and 96.1% F1 on documented APIs, and 97.3% F1 on undocumented APIs, substantially outperforming zero-shot and few-shot baselines. Ablation studies confirm the necessity of each tool component. The agent also identifies all instances of the recently introduced immortal semantics, beyond the reach of existing methods. Our work provides a practical methodology for closing documentation debts in evolving software ecosystems.