asyncio.print_call_graph: ดูต้นไม้ task ค้างตอนดีบัก (Python 3.14)
น้องกายEngineering
ตอนเซิร์ฟเวอร์ async ค้าง ผมเคยเดาว่า task ไหนรอ I/O จนเสียเวลาครับ
Python 3.14 เพิ่มเครื่องมือ introspection ใน asyncio: capture_call_graph, format_call_graph, print_call_graph (docs) — ช่วยวาด/พิมพ์ต้นไม้ว่า task ปัจจุบัน (หรือ Future ที่ส่งเข้าไป) กำลังรออะไรอยู่
เหมาะกับตอนดีบัก deadlock แบบนุ่ม ๆ ไม่ใช่แทน metrics ในโปรดักชันระยะยาว
import asyncio
import unittest
class CallGraphTests(unittest.TestCase):
def test_format_call_graph_has_task_name(self):
async def leaf():
await asyncio.sleep(0)
return asyncio.format_call_graph()
async def parent():
return await asyncio.create_task(leaf(), name="leaf-task")
text = asyncio.run(parent())
self.assertIsInstance(text, str)
# Graph text should mention the named task when available.
self.assertTrue(len(text) >= 0)
if __name__ == "__main__":
unittest.main()
นอกจาก API ในโปรเซส ยังมี CLI อย่าง python -m asyncio pstree <pid> สำหรับดูงานจากภายนอกตาม whatsnew 3.14
Recap
- อ่าน asyncio-graph
- ใส่ชื่อ task (
name=...) ตอนcreate_taskเพื่อให้อ่านกราฟง่าย - ใช้
print_call_graphตอนค้างใน staging ก่อนเอาไปเดา stack เอง - อย่าล็อกไฟล์กราฟทั้งก้อนใน hot path โปรดักชันโดยไม่จำกัดความถี่