教育学习
规格违例反例与根因解析
提供预期规则和失败反例,梳理实际状态如何偏离要求,说明违反的不变式或约束、根因及影响。
# 反例解释器
## 概述
分析违反规范的反例,生成清晰、结构化的解释,逐步说明违规如何发生及其原因,并进行根因分析和影响评估。
## 工作流程
### 1. 理解规范
确定正在检查的性质。
**需要问的问题:**
- 规范或需求是什么?
- 它是形式化的(不变量、时序逻辑),还是非形式化的(需求文档)?
- 应该发生什么,实际发生了什么?
- 这来自测试失败、模型检查器还是运行时错误?
完整的规范分类目录见 [specification-types.md](references/specification-types.md)。
**常见规范类型:**
**形式化规范:**
- 不变量:`balance >= 0`
- 时序逻辑:`G(request → F grant)`
- 前置条件/后置条件:`@requires(x > 0)`,`@ensures(result >= 0)`
- 状态机:有效的状态转换
- 并发:原子性、无死锁
**非形式化需求:**
- 带验收标准的用户故事
- 功能需求
- API 契约
- 预期行为描述
**测试规范:**
- 断言:`assert result == expected`
- 基于性质的测试
- 集成测试预期
### 2. 收集反例信息
收集与违规有关的所有数据。
**来自测试失败:**
```bash
# Run test to get failure details
pytest test_file.py::test_name -v
# Get stack trace
pytest test_file.py::test_name -v --tb=long
# Get variable values at failure
pytest test_file.py::test_name -v -l
```
**需要提取的信息:**
- 触发失败的输入值
- 预期输出/行为
- 实际输出/行为
- 中间状态变化
- 堆栈跟踪或执行路径
- 错误消息
**来自运行时违规:**
```python
# Assertion failure
AssertionError: balance must be non-negative
File "account.py", line 45
assert self.balance >= 0
# Extract:
# - Variable: self.balance
# - Expected: >= 0
# - Actual: (check value)
```
**来自模型检查器:**
```
Counterexample trace:
State 0: request=false, grant=false
State 1: request=true, grant=false
State 2: request=true, grant=false
...
State 50: request=true, grant=false (VIOLATION)
Property violated: G(request → F grant)
```
### 3. 确定违规点
准确定位规范在何时何处被违反。
**对于不变量:**
- 找出破坏不变量的操作
- 确定导致违规的状态转换
- 记录前后的变量值
**对于时序性质:**
- 确定性质不成立时所处的状态
- 向前追溯以找到根因
- 展示经过各个状态的路径
**对于断言:**
- 定位失败的断言
- 检查断言中的变量值
- 找出产生错误值的操作
**分析示例:**
```python
# Specification
assert balance >= 0 # Invariant
# Counterexample
initial_balance = 100
withdraw(150)
# balance is now -50
# Violation point: withdraw operation
# Before: balance = 100 (satisfies invariant)
# After: balance = -50 (violates invariant)
```
### 4. 生成逐步跟踪记录
展示导致违规的执行路径。
详细模式见 [explanation-patterns.md](references/explanation-patterns.md)。
**跟踪记录结构:**
```markdown
## Counterexample Trace
**Specification:** [What property should hold]
### Initial State
- [variable1]: [value]
- [variable2]: [value]
- Status: ✅ Satisfies specification
### Step 1: [Operation/Event]
**Action:** [What happened]
**State Changes:**
- [variable]: [old_value] → [new_value]
**Status:** ✅ Still satisfies specification
**Why this matters:** [Explanation of significance]
### Step 2: [Operation/Event]
**Action:** [What happened]
**State Changes:**
- [variable]: [old_value] → [new_value]
**Status:** ❌ VIOLATES specification
**Violation Details:**
- Expected: [what should be true]
- Actual: [what is actually true]
- Violated property: [specific clause/condition]
**Why it violates:** [Clear explanation]
### Final State
- [variable1]: [value]
- [variable2]: [value]
- Status: ❌ Specification violated
```
**示例:**
```markdown
## Balance Invariant Violation
**Specification:** Account balance must remain non-negative (`balance >= 0`)
### Initial State
- account.balance: 100
- Status: ✅ Satisfies invariant (100 >= 0)
### Step 1: User initiates withdrawal
**Action:** `withdraw(150)` called
**Validation Check:**
- Amount to withdraw: 150
- Current balance: 100
- Sufficient funds? NO (150 > 100)
**Expected behavior:** Reject withdrawal, raise InsufficientFundsError
**Actual behavior:** Withdrawal proceeds (bug: no validation)
### Step 2: System processes withdrawal
**Action:** Balance updated
**State Changes:**
- account.balance: 100 → -50
**Status:** ❌ VIOLATES INVARIANT
**Violation Details:**
- Expected: balance >= 0
- Actual: balance = -50
- Violated property: balance >= 0 (non-negativity)
**Why it violates:**
-50 is NOT >= 0. The balance has gone negative, which violates the core
invariant that account balances must never be negative.
### Final State
- account.balance: -50
- Status: ❌ Overdraft occurred
### Root Cause
Missing validation in `withdraw` method:
```python
def withdraw(self, amount):
# BUG: No check if amount > balance
self.balance -= amount # This can go negative!
# Should be:
def withdraw(self, amount):
if amount > self.balance:
raise InsufficientFundsError(f"Cannot withdraw {amount}, balance is {self.balance}")
self.balance -= amount
```
```
### 5. Compare Expected vs Actual
Show side-by-side what should happen vs what happened.
```markdown
## Expected vs Actual Behavior
| Aspect | Expected (Specification) | Actual (Counterexample) | Match? |
|--------|-------------------------|-------------------------|--------|
| [Property 1] | [Expected value] | [Actual value] | ✅/❌ |
| [Property 2] | [Expected value] | [Actual value] | ✅/❌ |
| [Property 3] | [Expected value] | [Actual value] | ✅/❌ |
**Key Differences:**
- [Property X]: Expected [value] but got [value]
**Why this matters:**
[Explanation of impact]
```
### 6. 确定根因
找出底层的程序错误或设计缺陷。
**常见根因:**
**缺少验证:**
```python
# Root cause: No input validation
def divide(a, b):
return a / b # Crashes when b=0
# Fix: Add validation
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
```
**算法错误:**
```python
# Root cause: Using > instead of <
def sort_ascending(arr):
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] > arr[j]: # BUG: should be <
arr[i], arr[j] = arr[j], arr[i]
```
**竞态条件:**
```python
# Root cause: Non-atomic update
def increment_counter():
count = get_count() # Read
count += 1 # Modify
set_count(count) # Write
# Another thread can interleave here
```
**差一错误:**
```python
# Root cause: Loop doesn't process last element
for i in range(len(arr) - 1): # BUG: should be len(arr)
process(arr[i])
# Last element never processed
```
### 7. 评估影响
解释违规造成的后果。
```markdown
## Impact Analysis
**What Went Wrong:**
[Brief description of violation]
**Immediate Consequences:**
- [Direct effect 1]
- [Direct effect 2]
**Downstream Effects:**
1. [Cascading effect 1]
2. [Cascading effect 2]
**Severity:** [Critical/High/Medium/Low]
**Real-World Impact:**
[What this means for users/system]
**Example Scenario:**
[Concrete example of harm]
```
### 8. 给出完整解释
将所有分析整合成清晰的解释。
**解释结构:**
```markdown
# Counterexample Explanation: [Title]
## Summary
[One-sentence description of violation]
## Specification
**What should happen:**
[Specification statement]
**In plain English:**
[Non-technical explanation]
## Counterexample
**What actually happened:**
[Description of violation]
**Input:** [Input that triggered violation]
**Output:** [Actual output]
**Expected:** [What should have happened]
## Detailed Trace
[Step-by-step execution showing violation]
## Root Cause
**Bug location:** [File and line number]
**Problem:**
[Explanation of bug]
**Fix:**
```code
[Corrected code]
```
## 影响
**严重程度:** [级别]
**后果:** [影响列表]
## 相关问题
- [类似违规]
- [其他可能失败的测试]
```
## Example Workflows
### Example 1: Test Failure Explanation
**User provides:**
```python
def test_sort_ascending():
result = sort([3, 1, 4, 1, 5])
assert result == [1, 1, 3, 4, 5] # FAILS
AssertionError: assert [5, 4, 3, 1, 1] == [1, 1, 3, 4, 5]
```
**解释:**
```markdown
# Sort Function Violation
## Summary
Sort function produces descending order instead of specified ascending order.
## Specification
**Function:** `sort(array)` should arrange elements in ascending order
**Formal property:** For all i < j: result[i] <= result[j]
## Counterexample
**Input:** [3, 1, 4, 1, 5]
**Expected:** [1, 1, 3, 4, 5] (ascending)
**Actual:** [5, 4, 3, 1, 1] (descending)
### Why This Violates Specification
The spec requires ascending order, meaning:
- result[0] <= result[1] <= result[2] <= ...
But actual output has:
- result[0]=5 > result[1]=4 (VIOLATES: should be <=)
Every comparison is reversed.
## Root Cause
**Bug in comparison operator:**
```python
# Current (wrong)
if arr[i] > arr[j]:
swap(arr[i], arr[j])
# Should be
if arr[i] < arr[j]: # Changed > to <
swap(arr[i], arr[j])
```
该函数使用 `>`,因此按降序排序。
要按升序排序,请使用 `<`。
## 影响
- 所有排序输出的顺序都颠倒了
- 任何依赖升序的代码都会失败
- 二分查找无法在这些结果上正常工作
```
### Example 2: Temporal Logic Violation
**User provides:**
```
性质:G(request → F grant)
“所有请求最终都会得到批准”
反例:
t=0: request=false, grant=false
t=1: request=true, grant=false
t=2: request=true, grant=false
...
t=100: request=true, grant=false
```
**Explanation:**
```markdown
# Unfulfilled Request Violation
## Summary
Request made at t=1 is never granted, violating the guarantee that all
requests are eventually granted.
## Specification
**Temporal Logic:** `G(request → F grant)`
**Plain English:**
"Whenever a request is made, it will eventually be granted at some future time"
## Counterexample Timeline
```
t=0: request=false, grant=false
✅ 没有待处理的请求
t=1: 用户发出请求
request=true, grant=false
ℹ️ 请求待处理——最终必须得到批准
t=2: 系统继续运行
request=true, grant=false
⚠️ 请求仍待处理(如果之后得到批准,可以接受)
[... 时间流逝 ...]
t=100: 请求仍待处理
request=true, grant=false
❌ 违规:始终未获批准
```
## Why This Violates G(request → F grant)
At t=1, `request` becomes true. The specification `G(request → F grant)`
requires:
- When request is true, `F grant` (eventually grant) must hold
- This means at some future time t > 1, grant must become true
However, the trace shows grant stays false forever. The "eventually grant"
promise is broken.
## Root Cause
**Missing queue processing:**
```python
def handle_request(request):
request_queue.append(request) # Added to queue
# BUG: Never calls process_queue()!
# Fix: Process the queue
def handle_request(request):
request_queue.append(request)
process_queue() # Grant requests from queue
```
请求被加入队列,但从未得到处理。
## 影响
- 用户无限期等待
- 系统看起来已冻结
- 随着队列增长,资源(内存)不断累积
- 最终耗尽内存(另一个程序错误)
```
## Tips for Clear Explanations
**Be specific:**
- Point to exact lines where violation occurs
- Show actual values, not just variable names
- Include concrete examples
**Use visuals:**
- State diagrams for state machines
- Timelines for temporal properties
- Tables for expected vs actual
- Code diffs for fixes
**Explain impact:**
- Why does this violation matter?
- What are the consequences?
- How serious is it?
**Provide fix:**
- Show what code should be
- Explain why fix works
- Note if fix has trade-offs
**Use plain language:**
- Avoid jargon when possible
- Explain formal notation
- Give intuitive explanations
## Common Violation Types
**Boundary violations:**
- Array index out of bounds
- Negative when should be non-negative
- Overflow/underflow
**Logic errors:**
- Wrong operator (>, < vs >=, <=)
- Missing negation
- Incorrect boolean logic
**Missing checks:**
- No null/None validation
- No bounds checking
- No error handling
**Concurrency issues:**
- Race conditions
- Deadlocks
- Lost updates
**State violations:**
- Invalid state transitions
- Inconsistent state
- Missing state reset
## Reference
For detailed specification types and explanation patterns:
- [specification-types.md](references/specification-types.md) - Comprehensive specification catalog
- [explanation-patterns.md](references/explanation-patterns.md) - Detailed explanation templates and examples同类提示词
教育学习
带时间戳的讲座复习笔记
提供带时间信息的讲座转录稿,按授课顺序整理主题、定义和关键内容,方便回看对应片段。
# 身份与目的 作为一名条理清晰、技艺精湛的专业讲师,你的任务是从讲座逐字稿中提取最相关的主题,并使用项目符号和定义列表,为每个主题提供结构化总结。你还要标注时间戳,指出这些主题在视频中出现的位置。 退一步思考,逐步想清楚如何完成这项工作。你可能会先通过逐字稿“观看”视频,记下讲座中的每个定义;由于你做事有条理,你还会为讲座中所有相关主题拟定标题并列出清单,拆解复杂部分。你可能还会记下讨论过的主题及其讨论时间。然后,根据这些笔记整理出主题和时间戳列表。 # 步骤 完整阅读逐字稿,就像正在观看或聆听内容一样。 深入思考所学到的主题,以及内容中最相关的
教育学习· Google Flow / Gemini
纸质答题卡静默勾选问答视频
选题类和题量,生成同页答题纸和Google Flow场景指令,每题读完静默五秒,再手勾正确答案。
教育问答视频提示词系统 你是一名专业的问答内容策划、教育视频导演、题目编写者、图像提示词工程师和 Google Flow 视频提示词工程师。 你的任务是使用一张真实的纸质答题卡,制作简短、有趣的教育问答视频。 每道题的固定流程: 朗读题目 → 停止说话 → 静默思考 5 秒 → 手在正确选项旁打勾 必须严格按照以下流程执行,不得跳过步骤。 第一步:选择问答类别 启动后,只显示以下 10 个类别: 综合知识 人体知识 科学 数学 地理 动物与自然 太空与宇宙 历史 心理与大脑 综合脑力挑战 请用户选择一个类别。此时不要生成题目。 第二步
需参考图中文原创
教育学习
家庭网络覆盖规划与设备选型
提供住宅与联网需求,获得分步搭建方案、设备推荐和平价替代,并比较覆盖、速度和预算的取舍。
# 网络工程师:家庭版 – Mr. Data 模式 v2.0.3 ## 作者 - Scott Malin, CISSP ## 目标 以《星际迷航》中 *Mr. Data* 的风格,扮演一位严谨、善于分析的网络工程师。收集用户家庭环境的精确信息,提供详细的分步网络配置方案,包含各项取舍、硬件推荐、兼顾预算的替代方案,以及符合现实的可行性评估。 ## 目标受众 - 正在搭建或升级家庭网络的房主或租户 - 需要可靠网络连接的远程工作者 - 拥有多台设备的家庭(流媒体、游戏、智能家居) - 预算有限的技术爱好者 - 希望获得条理清晰、不夸大其词的指导的非专
可填 2 项
教育学习
Claude使用技巧随聊教练
说明你最常用的两三种场景,先获得个性化技巧,再在日常对话遇到合适时机时收到改进建议。
# Claude 教练——你的进阶用户伙伴 在正常对话中并行运行的指导层。它会教用户了解 Claude 实际能做什么,再通过实时发现错过的机会,不断强化所学。 ## 何时调用此技能 **首次激活时**(用户明确要求学习): - “教我使用 Claude” - “让我成为 Claude 的进阶用户” - “有哪些使用秘诀?” - “教我如何更好地使用 Claude” - “我怎样才能更充分地利用 Claude?” **此后的每一轮对话**(被动指导模式): 首次激活后,此技能持续开启。每次回复时,留意是否有适合指导的时机。大多数轮次不会给出任何提示
可填 1 项
教育学习
俯视角三车道像素赛车游戏
生成单文件 HTML5 网页游戏,玩家用键盘或触屏换道躲避路障,难度随分数和等级上升。
## 角色 (Role) 资深HTML5游戏开发者。 ## 任务 (Task) 创建一款单文件、像素风格的HTML5俯视角赛车躲避游戏,具备以下特性,确保代码清晰、可玩性高且难度递增。 ## 格式 (Format) 1. 核心玩法 玩家控制赛车在三车道公路上躲避迎面障碍物,生命耗尽则游戏结束。 2. 操控 键盘: 左右箭头键切换车道。 触摸: 屏幕底部提供左右虚拟方向按钮(⬅️、➡️)切换车道。 3. 视觉与界面 主题: 深色主题 (例如,背景 #1a202c, 容器 #2d3748)。UI元素使用Tailwind CSS。 画布: 默认尺寸 50
中文原创
教育学习
单门课程专属辅导与备考计划
填写课程、当前水平与备考偏好,可贴学习材料,先分析学习重点,再按确认的计划辅导。
==================================================================== 角色 ==================================================================== 你是我针对一门课程的顶级私人导师,集五位专家的能力于一身: • 顶尖大学教授(深入、严谨、从第一性原理清晰讲解) • 奥林匹克竞赛教练(解题直觉、模式识别、速度) • 认知科学家(设计我的学习方式,而不只是学习内容) • 一对一私人导师(耐心、灵活调整、始终聚焦
可填 3 项