ln-653-runtime-performance-auditor
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRuntime Performance Auditor (L3 Worker)
运行时性能审计Worker(L3 Worker)
Specialized worker auditing runtime performance anti-patterns in async and general code.
专门用于审计异步代码和通用代码中运行时性能反模式的Worker。
Purpose & Scope
目标与范围
- Worker in ln-650 coordinator pipeline - invoked by ln-650-persistence-performance-auditor
- Audit runtime performance (Priority: MEDIUM)
- Check async anti-patterns, unnecessary allocations, blocking operations
- Return structured findings with severity, location, effort, recommendations
- Calculate compliance score (X/10) for Runtime Performance category
- ln-650协调器流水线中的Worker - 由ln-650-persistence-performance-auditor调用
- 审计运行时性能(优先级:MEDIUM)
- 检查异步反模式、不必要的内存分配、阻塞操作
- 返回包含严重程度、位置、修复工作量和建议的结构化检测结果
- 计算运行时性能类别的合规分数(X/10)
Inputs (from Coordinator)
输入(来自协调器)
MANDATORY READ: Load for contextStore structure.
shared/references/task_delegation_pattern.md#audit-coordinator--worker-contractReceives with: , , .
contextStoretech_stackbest_practicescodebase_rootDomain-aware: Supports + .
domain_modecurrent_domain必读: 加载以了解contextStore结构。
shared/references/task_delegation_pattern.md#audit-coordinator--worker-contract接收包含以下内容的:、、。
contextStoretech_stackbest_practicescodebase_root领域感知: 支持 + 。
domain_modecurrent_domainWorkflow
工作流程
-
Parse context from contextStore
- Extract tech_stack, best_practices
- Determine scan_path
- Detect async framework: asyncio (Python), Node.js async, Tokio (Rust)
-
Scan codebase for violations
- Grep patterns scoped to
scan_path - For Rules 1, 3, 5: detect blocks first, then check for violations inside them
async def
- Grep patterns scoped to
-
Collect findings with severity, location, effort, recommendation
-
Calculate score using penalty algorithm
-
Return JSON result to coordinator
-
解析contextStore中的上下文
- 提取tech_stack、best_practices
- 确定扫描路径
- 检测异步框架:asyncio(Python)、Node.js async、Tokio(Rust)
-
扫描代码库以查找违规项
- 在范围内匹配模式
scan_path - 对于规则1、3、5:先检测块,再检查其中的违规情况
async def
- 在
-
收集包含严重程度、位置、修复工作量和建议的检测结果
-
使用惩罚算法计算分数
-
向协调器返回JSON结果
Audit Rules (Priority: MEDIUM)
审计规则(优先级:MEDIUM)
1. Blocking IO in Async
1. 异步代码中的阻塞IO
What: Synchronous file/network operations inside async functions, blocking event loop
Detection (Python):
- Find functions
async def - Inside them, grep for blocking calls:
- File: ,
open(,.read_bytes(),.read_text(),.write_bytes(),.write_text()Path(...).(read|write) - Network: ,
requests.get,requests.posturllib.request - Subprocess: ,
subprocess.run(subprocess.call(
- File:
- Exclude: calls wrapped in or
await asyncio.to_thread(...)await loop.run_in_executor(...)
Detection (Node.js):
- Inside or arrow async, grep for
async function,fs.readFileSync,fs.writeFileSyncchild_process.execSync
Severity:
- HIGH: Blocking IO in API request handler (blocks entire event loop)
- MEDIUM: Blocking IO in background task/worker
Recommendation: Use , , or for file operations; use instead of
aiofilesasyncio.to_thread()loop.run_in_executor()httpx.AsyncClientrequestsEffort: S (wrap in to_thread or switch to async library)
说明: 异步函数内的同步文件/网络操作,会阻塞事件循环
检测方式(Python):
- 查找函数
async def - 在函数内匹配阻塞调用:
- 文件操作:,
open(,.read_bytes(),.read_text(),.write_bytes(),.write_text()Path(...).(read|write) - 网络操作:,
requests.get,requests.posturllib.request - 子进程:,
subprocess.run(subprocess.call(
- 文件操作:
- 排除:被或
await asyncio.to_thread(...)包裹的调用await loop.run_in_executor(...)
检测方式(Node.js):
- 在或异步箭头函数内,匹配
async function,fs.readFileSync,fs.writeFileSyncchild_process.execSync
严重程度:
- HIGH: API请求处理程序中的阻塞IO(会阻塞整个事件循环)
- MEDIUM: 后台任务/Worker中的阻塞IO
建议: 文件操作使用、或;网络请求使用替代
aiofilesasyncio.to_thread()loop.run_in_executor()httpx.AsyncClientrequests修复工作量: S(包裹在to_thread中或切换到异步库)
2. Unnecessary List Allocation
2. 不必要的列表分配
What: List comprehension where generator expression suffices
Detection:
- - allocates list just to count; use
len([x for x in ...])sum(1 for ...) - - allocates list for short-circuit check; use
any([x for x in ...])any(x for ...) - - same pattern; use
all([x for x in ...])all(x for ...) - - use set comprehension
set([x for x in ...]){x for x in ...} - - use generator directly
"".join([x for x in ...])"".join(x for x in ...)
Severity:
- MEDIUM: Unnecessary allocation in hot path (API handler, loop)
- LOW: Unnecessary allocation in infrequent code
Recommendation: Replace with generator or set comprehension
[...](...){...}Effort: S (syntax change only)
说明: 使用列表推导式,但生成器表达式即可满足需求的情况
检测方式:
- - 仅为了计数而分配列表;应使用
len([x for x in ...])sum(1 for ...) - - 为短路检查分配列表;应使用
any([x for x in ...])any(x for ...) - - 相同模式;应使用
all([x for x in ...])all(x for ...) - - 应使用集合推导式
set([x for x in ...]){x for x in ...} - - 直接使用生成器
"".join([x for x in ...])"".join(x for x in ...)
严重程度:
- MEDIUM: 热点路径(API处理程序、循环)中的不必要分配
- LOW: 不频繁执行的代码中的不必要分配
建议: 将替换为生成器或集合推导式
[...](...){...}修复工作量: S(仅需修改语法)
3. Sync Sleep in Async
3. 异步代码中的同步休眠
What: inside async function blocks event loop
time.sleep()Detection:
- Grep for inside
time\.sleepblocksasync def - Pattern: ...
await some_async_call()...time.sleep(N)await another_call()
Severity:
- HIGH: in async API handler (freezes all concurrent requests)
time.sleep() - MEDIUM: in async background task
time.sleep()
Recommendation: Replace with
await asyncio.sleep(N)Effort: S (one-line change)
说明: 异步函数内的会阻塞事件循环
time.sleep()检测方式:
- 在块中匹配
async deftime\.sleep - 模式:...
await some_async_call()...time.sleep(N)await another_call()
严重程度:
- HIGH: 异步API处理程序中的(会冻结所有并发请求)
time.sleep() - MEDIUM: 异步后台任务中的
time.sleep()
建议: 替换为
await asyncio.sleep(N)修复工作量: S(仅需修改一行代码)
4. String Concatenation in Loop
4. 循环中的字符串拼接
What: Building string via inside loop (O(n^2) for large strings)
+=Detection:
- Pattern: variable ,
result,output,htmlwithtextinside+=/forloopwhile - Grep for: variable followed by containing string operand inside loop body
+=
Severity:
- MEDIUM: String concat in loop processing large data (>100 iterations)
- LOW: String concat in loop with small iterations (<100)
Recommendation: Use + , or , or f-string with
list.append()"".join()io.StringIO"".join(generator)Effort: S (refactor to list + join)
说明: 在循环内通过构建字符串(处理大字符串时时间复杂度为O(n²))
+=检测方式:
- 模式:变量,
result,output,html在text/for循环内使用while+= - 匹配:循环体中变量后跟包含字符串操作数的
+=
严重程度:
- MEDIUM: 处理大量数据(>100次迭代)的循环中的字符串拼接
- LOW: 迭代次数少(<100次)的循环中的字符串拼接
建议: 使用 + ,或,或结合生成器的f-string +
list.append()"".join()io.StringIO"".join(generator)修复工作量: S(重构为列表+join)
5. Missing to_thread
for CPU-Bound
to_thread5. CPU密集型任务缺失to_thread
to_threadWhat: CPU-intensive synchronous code in async handler without offloading to thread
Detection:
- Inside , find CPU-intensive operations:
async def- JSON parsing large files: ,
json.loads(large_data)json.load(file) - Image processing: ,
PIL.Image.opencv2.imread - Crypto: ,
hashlibbcrypt.hashpw - XML/HTML parsing: ,
lxml.etree.parseBeautifulSoup( - Large data transformation without await points
- JSON parsing large files:
- Exclude: operations already wrapped in or executor
asyncio.to_thread()
Severity:
- MEDIUM: CPU-bound operation in async handler (blocks event loop proportionally to data size)
Recommendation: Wrap in (Python 3.9+) or
await asyncio.to_thread(func, *args)loop.run_in_executor(None, func, *args)Effort: S (wrap in to_thread)
说明: 异步处理程序中的CPU密集型同步代码未卸载到线程
检测方式:
- 在内查找CPU密集型操作:
async def- 大文件JSON解析:,
json.loads(large_data)json.load(file) - 图像处理:,
PIL.Image.opencv2.imread - 加密操作:,
hashlibbcrypt.hashpw - XML/HTML解析:,
lxml.etree.parseBeautifulSoup( - 无await点的大数据转换
- 大文件JSON解析:
- 排除:已被或执行器包裹的操作
asyncio.to_thread()
严重程度:
- MEDIUM: 异步处理程序中的CPU密集型操作(会根据数据大小成比例阻塞事件循环)
建议: 使用(Python 3.9+)或包裹
await asyncio.to_thread(func, *args)loop.run_in_executor(None, func, *args)修复工作量: S(包裹在to_thread中)
6. Redundant Data Copies
6. 冗余数据拷贝
What: Unnecessary , , when data is only read, not mutated
.copy()list()dict()Detection:
- where
data = list(items)is only iterated (never modified)data - where
config = config_dict.copy()is only readconfig - where
result = dict(original)is returned without modificationresult
Severity:
- LOW: Redundant copy in most contexts (minor memory overhead)
- MEDIUM: Redundant copy of large data in hot path
Recommendation: Remove unnecessary copy; pass original if not mutated
Effort: S (remove copy call)
说明: 数据仅用于读取、不修改时,使用不必要的, ,
.copy()list()dict()检测方式:
- 其中
data = list(items)仅被迭代(从未修改)data - 其中
config = config_dict.copy()仅被读取config - 其中
result = dict(original)未修改即被返回result
严重程度:
- LOW: 大多数场景下的冗余拷贝(内存开销较小)
- MEDIUM: 热点路径中的大数据冗余拷贝
建议: 移除不必要的拷贝;若不修改则直接传递原始数据
修复工作量: S(移除拷贝调用)
Scoring Algorithm
评分算法
See for unified formula and score interpretation.
shared/references/audit_scoring.md请参阅了解统一公式和分数解读。
shared/references/audit_scoring.mdOutput Format
输出格式
Return JSON to coordinator:
json
{
"category": "Runtime Performance",
"score": 7,
"total_issues": 5,
"critical": 0,
"high": 2,
"medium": 2,
"low": 1,
"findings": [
{
"severity": "HIGH",
"location": "app/infrastructure/messaging/job_processor.py:444",
"issue": "Blocking IO: input_path.read_bytes() inside async function blocks event loop",
"principle": "Async Best Practices / Non-Blocking IO",
"recommendation": "Use aiofiles or await asyncio.to_thread(input_path.read_bytes)",
"effort": "S"
}
]
}向协调器返回JSON:
json
{
"category": "Runtime Performance",
"score": 7,
"total_issues": 5,
"critical": 0,
"high": 2,
"medium": 2,
"low": 1,
"findings": [
{
"severity": "HIGH",
"location": "app/infrastructure/messaging/job_processor.py:444",
"issue": "Blocking IO: input_path.read_bytes() inside async function blocks event loop",
"principle": "Async Best Practices / Non-Blocking IO",
"recommendation": "Use aiofiles or await asyncio.to_thread(input_path.read_bytes)",
"effort": "S"
}
]
}Critical Rules
关键规则
- Do not auto-fix: Report only
- Async context required: Rules 1, 3, 5 apply ONLY inside async functions
- Exclude wrappers: Do not flag calls already wrapped in /
to_threadrun_in_executor - Context-aware: Small files (<1KB) read synchronously may be acceptable
- Exclude tests: Do not flag test utilities or test fixtures
- 请勿自动修复: 仅报告问题
- 需异步上下文: 规则1、3、5仅适用于异步函数内部
- 排除包裹项: 请勿标记已被/
to_thread包裹的调用run_in_executor - 上下文感知: 同步读取小文件(<1KB)可能是可接受的
- 排除测试代码: 请勿标记测试工具或测试夹具
Definition of Done
完成标准
- contextStore parsed (tech_stack, async framework)
- scan_path determined
- Async framework detected (asyncio/Node.js async/Tokio)
- All 6 checks completed:
- blocking IO, unnecessary allocations, sync sleep, string concat, CPU-bound, redundant copies
- Findings collected with severity, location, effort, recommendation
- Score calculated
- JSON returned to coordinator
Version: 1.0.0
Last Updated: 2026-02-04
- 已解析contextStore(tech_stack、异步框架)
- 已确定scan_path
- 已检测异步框架(asyncio/Node.js async/Tokio)
- 已完成全部6项检查:
- 阻塞IO、不必要的分配、同步休眠、字符串拼接、CPU密集型任务、冗余拷贝
- 已收集包含严重程度、位置、修复工作量和建议的检测结果
- 已计算分数
- 已向协调器返回JSON结果
版本: 1.0.0
最后更新: 2026-02-04