ln-628-concurrency-auditor

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Concurrency Auditor (L3 Worker)

并发审计器(L3工作器)

Specialized worker auditing concurrency and async patterns.
专注于审计并发与异步模式的工作器。

Purpose & Scope

用途与范围

  • Worker in ln-620 coordinator pipeline
  • Audit concurrency (Category 11: High Priority)
  • Check race conditions, async/await, thread safety
  • Calculate compliance score (X/10)
  • ln-620协调器流水线中的工作器
  • 审计并发(类别11:高优先级)
  • 检查竞态条件、async/await使用情况、线程安全
  • 计算合规分数(X/10)

Inputs (from Coordinator)

输入(来自协调器)

Receives
contextStore
with tech stack, language, codebase root.
接收包含技术栈、编程语言、代码库根目录的
contextStore

Workflow

工作流程

  1. Parse context
  2. Check concurrency patterns
  3. Collect findings
  4. Calculate score
  5. Return JSON
  1. 解析上下文
  2. 检查并发模式
  3. 收集检测结果
  4. 计算分数
  5. 返回JSON格式结果

Audit Rules

审计规则

1. Race Conditions

1. 竞态条件

What: Shared state modified without synchronization
Detection Patterns:
LanguagePatternGrep
PythonGlobal modified in async
global\s+\w+
inside
async def
TypeScriptModule-level let in async
^let\s+\w+
at file scope + async function modifies it
GoMap access without mutex
map\[.*\].*=
without
sync.Mutex
in same file
AllShared cache
cache\[.*\]\s*=
or
cache\.set
without lock
Severity:
  • CRITICAL: Race in payment/auth (
    payment
    ,
    balance
    ,
    auth
    ,
    token
    in variable name)
  • HIGH: Race in user-facing feature
  • MEDIUM: Race in background job
Recommendation: Use locks, atomic operations, message queues
Effort: M-L
定义: 共享状态在未同步的情况下被修改
检测模式:
编程语言模式正则匹配
Python异步函数内修改全局变量
global\s+\w+
位于
async def
内部
TypeScript异步函数修改模块级let变量文件作用域的
^let\s+\w+
+ 异步函数对其进行修改
Go无互斥锁的Map访问同一文件中
map\[.*\].*=
未搭配
sync.Mutex
所有语言共享缓存操作
cache\[.*\]\s*=
cache\.set
未加锁
严重程度:
  • CRITICAL(致命): 支付/认证流程中的竞态(变量名包含
    payment
    balance
    auth
    token
  • HIGH(高): 用户可见功能中的竞态
  • MEDIUM(中): 后台任务中的竞态
建议: 使用锁、原子操作、消息队列
修复工作量: 中-大

2. Missing Async/Await

2. 缺失Async/Await

What: Callback hell or unhandled promises
Detection Patterns:
IssueGrepExample
Callback hell
\.then\(.*\.then\(.*\.then\(
.then().then().then()
Fire-and-forget
async.*\(\)
not preceded by
await
saveToDb()
without await
Missing await
return\s+new\s+Promise
in async function
Should just
return await
or
return
value
Dangling promise
\.catch\(\s*\)
Empty catch swallows errors
Severity:
  • HIGH: Fire-and-forget async (can cause data loss)
  • MEDIUM: Callback hell (hard to maintain)
  • LOW: Mixed Promise styles
Recommendation: Convert to async/await, always await or handle promises
Effort: M
定义: 回调地狱或未处理的Promise
检测模式:
问题正则匹配示例
回调地狱
\.then\(.*\.then\(.*\.then\(
.then().then().then()
即发即弃(Fire-and-forget)
async.*\(\)
前未加
await
saveToDb()
未加await
缺失await异步函数中返回
return\s+new\s+Promise
应改为
return await
或直接返回值
悬垂Promise
\.catch\(\s*\)
空catch块吞掉错误
严重程度:
  • HIGH(高): 即发即弃的异步操作(可能导致数据丢失)
  • MEDIUM(中): 回调地狱(难以维护)
  • LOW(低): Promise风格混用
建议: 转换为async/await写法,始终await或正确处理Promise
修复工作量:

3. Resource Contention

3. 资源竞争

What: Multiple processes competing for same resource
Detection Patterns:
IssueGrepExample
File lock missing
open\(.*["']w["']\)
without
flock
or
lockfile
Concurrent file writes
Connection exhaustion
create_engine\(.*pool_size
check if pool_size < 5
DB pool too small
Concurrent writes
writeFile
or
fs\.write
without lock check
File corruption risk
Severity:
  • HIGH: File corruption risk, DB exhaustion
  • MEDIUM: Performance degradation
Recommendation: Use connection pooling, file locking,
asyncio.Lock
Effort: M
定义: 多个进程争夺同一资源
检测模式:
问题正则匹配示例
缺失文件锁
open\(.*["']w["']\)
未搭配
flock
lockfile
并发文件写入
连接耗尽
create_engine\(.*pool_size
检查pool_size是否小于5
数据库连接池过小
并发写入
writeFile
fs\.write
未检查锁
存在文件损坏风险
严重程度:
  • HIGH(高): 文件损坏风险、数据库连接耗尽
  • MEDIUM(中): 性能下降
建议: 使用连接池、文件锁、
asyncio.Lock
修复工作量:

4. Thread Safety Violations

4. 线程安全违规

What: Shared mutable state without synchronization
Detection Patterns:
LanguageSafe PatternUnsafe Pattern
Go
sync.Mutex
with map
map[...]
without Mutex in same struct
Rust
Arc<Mutex<T>>
Rc<RefCell<T>>
in multi-threaded context
Java
synchronized
or
ConcurrentHashMap
HashMap
shared between threads
Python
threading.Lock
Global dict modified in threads
Grep patterns:
  • Go unsafe:
    type.*struct\s*{[^}]*map\[
    without
    sync.Mutex
    in same struct
  • Python unsafe:
    global\s+\w+
    in function +
    threading.Thread
    in same file
Severity: HIGH (data corruption possible)
Recommendation: Use thread-safe primitives
Effort: M
定义: 共享可变状态未同步
检测模式:
编程语言安全模式不安全模式
Go
sync.Mutex
搭配map
同一结构体中
map[...]
未使用Mutex
Rust
Arc<Mutex<T>>
多线程环境中使用
Rc<RefCell<T>>
Java
synchronized
ConcurrentHashMap
线程间共享
HashMap
Python
threading.Lock
线程中修改全局字典
正则匹配模式:
  • Go不安全写法:结构体定义
    type.*struct\s*{[^}]*map\[
    且同一结构体中无
    sync.Mutex
  • Python不安全写法:函数中存在
    global\s+\w+
    且同一文件中使用
    threading.Thread
严重程度: HIGH(高)(可能导致数据损坏)
建议: 使用线程安全原语
修复工作量:

5. Deadlock Potential

5. 死锁可能性

What: Lock acquisition in inconsistent order
Detection Patterns:
IssueGrepExample
Nested locks
with\s+\w+_lock:.*with\s+\w+_lock:
(multiline)
Lock A then Lock B
Lock in loop
for.*:.*\.acquire\(\)
Lock acquired repeatedly without release
Lock + external call
.acquire\(\)
followed by
await
or
requests.
Holding lock during I/O
Severity: HIGH (deadlock freezes application)
Recommendation: Consistent lock ordering, timeout locks (
asyncio.wait_for
)
Effort: L
定义: 锁获取顺序不一致
检测模式:
问题正则匹配示例
嵌套锁
with\s+\w+_lock:.*with\s+\w+_lock:
(多行)
先锁A再锁B
循环中加锁
for.*:.*\.acquire\(\)
重复获取锁未释放
锁+外部调用
.acquire\(\)
后跟随
await
requests.
I/O操作期间持有锁
严重程度: HIGH(高)(死锁会导致应用冻结)
建议: 保持一致的锁顺序、使用带超时的锁(
asyncio.wait_for
修复工作量:

6. Blocking I/O in Event Loop (Python asyncio)

6. 事件循环中的阻塞I/O(Python asyncio)

What: Synchronous blocking calls inside async functions
Detection Patterns:
Blocking CallGrep in
async def
Replacement
time.sleep
time\.sleep
inside async def
await asyncio.sleep
requests.
requests\.(get|post)
inside async def
httpx
or
aiohttp
open()
file
open\(
inside async def
aiofiles.open
Severity:
  • HIGH: Blocks entire event loop
  • MEDIUM: Minor blocking (<100ms)
Recommendation: Use async alternatives
Effort: S-M
定义: 异步函数内的同步阻塞调用
检测模式:
阻塞调用async def中的正则匹配替代方案
time.sleep
time\.sleep
位于async def内
await asyncio.sleep
requests.
requests\.(get|post)
位于async def内
httpx
aiohttp
open()
文件操作
open\(
位于async def内
aiofiles.open
严重程度:
  • HIGH(高): 阻塞整个事件循环
  • MEDIUM(中): 轻微阻塞(<100ms)
建议: 使用异步替代方案
修复工作量: 小-中

Scoring Algorithm

评分算法

See
shared/references/audit_scoring.md
for unified formula and score interpretation.
统一公式与分数解读请参考
shared/references/audit_scoring.md

Output Format

输出格式

json
{
  "category": "Concurrency",
  "score": 7,
  "total_issues": 4,
  "critical": 0,
  "high": 2,
  "medium": 2,
  "low": 0,
  "checks": [
    {"id": "race_conditions", "name": "Race Conditions", "status": "passed", "details": "No shared state modified without synchronization"},
    {"id": "missing_await", "name": "Missing Await", "status": "failed", "details": "2 fire-and-forget async calls found"},
    {"id": "resource_contention", "name": "Resource Contention", "status": "warning", "details": "DB pool_size=3 may be insufficient"},
    {"id": "thread_safety", "name": "Thread Safety", "status": "passed", "details": "All shared state properly synchronized"},
    {"id": "deadlock_potential", "name": "Deadlock Potential", "status": "passed", "details": "No nested locks or inconsistent ordering"},
    {"id": "blocking_io", "name": "Blocking I/O", "status": "failed", "details": "time.sleep in async context"}
  ],
  "findings": [
    {
      "severity": "HIGH",
      "location": "src/services/payment.ts:45",
      "issue": "Shared state 'balanceCache' modified without synchronization",
      "principle": "Thread Safety / Concurrency Control",
      "recommendation": "Use mutex or atomic operations for balanceCache updates",
      "effort": "M"
    }
  ]
}
json
{
  "category": "Concurrency",
  "score": 7,
  "total_issues": 4,
  "critical": 0,
  "high": 2,
  "medium": 2,
  "low": 0,
  "checks": [
    {"id": "race_conditions", "name": "Race Conditions", "status": "passed", "details": "No shared state modified without synchronization"},
    {"id": "missing_await", "name": "Missing Await", "status": "failed", "details": "2 fire-and-forget async calls found"},
    {"id": "resource_contention", "name": "Resource Contention", "status": "warning", "details": "DB pool_size=3 may be insufficient"},
    {"id": "thread_safety", "name": "Thread Safety", "status": "passed", "details": "All shared state properly synchronized"},
    {"id": "deadlock_potential", "name": "Deadlock Potential", "status": "passed", "details": "No nested locks or inconsistent ordering"},
    {"id": "blocking_io", "name": "Blocking I/O", "status": "failed", "details": "time.sleep in async context"}
  ],
  "findings": [
    {
      "severity": "HIGH",
      "location": "src/services/payment.ts:45",
      "issue": "Shared state 'balanceCache' modified without synchronization",
      "principle": "Thread Safety / Concurrency Control",
      "recommendation": "Use mutex or atomic operations for balanceCache updates",
      "effort": "M"
    }
  ]
}

Reference Files

参考文件

  • Audit scoring formula:
    shared/references/audit_scoring.md
  • Audit output schema:
    shared/references/audit_output_schema.md

Version: 3.0.0 Last Updated: 2025-12-23
  • 审计评分公式:
    shared/references/audit_scoring.md
  • 审计输出 Schema:
    shared/references/audit_output_schema.md

版本: 3.0.0 最后更新: 2025-12-23