关于 hierarchical-matching-systems
用于设计、调试、测试和审查分层匹配系统的流程指南。它通过清单分类问题、将需求转化为约束,并验证匹配结果。
主要功能
- 01匹配问题分类
- 02约束与数据模型设计
- 03算法选择核查
- 04调试流程
- 05正确性与边界测试
适用场景
- 01规划新的匹配系统
- 02诊断约束违规
- 03排查层级相关错误
- 04审查匹配逻辑与测试
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ petekp/ agent-skills --skill hierarchical-matching-systems安装后在 Claude Code 中输入/hierarchical-matching-systems确认已加载。
附带文件references/algorithms.mdreferences/decision-guide.md
详细介绍
层级匹配系统
本技能为层级匹配系统提供严格的诊断和架构流程。请严格遵循检查清单——匹配错误往往隐藏在被跳过的步骤中。
快速参考
- 算法选择:参阅 references/decision-guide.md
- 算法详情:参阅 references/algorithms.md
1. 问题分类检查清单
开始任何工作之前,先对问题进行分类。勾选所有适用项:
□ TWO-SIDED: Both sides have preferences (students↔schools, workers↔jobs)
□ ONE-SIDED: Only one side has preferences (tasks→workers, items→bins)
□ HIERARCHICAL: Entities exist at multiple levels (org→dept→team→person)
□ WEIGHTED: Matches have costs/scores to optimize
□ CONSTRAINED: Hard limits exist (capacity, exclusions, required pairings)
□ STABLE: Solution must resist defection (no blocking pairs)
□ OPTIMAL: Solution must minimize/maximize objective function
□ FUZZY: Entities may partially match (entity resolution, deduplication)
分类结果决定算法类别。架构设计请转到第 2 节,调试请转到第 3 节。
2. 架构流程
设计新的匹配系统时,按顺序遵循以下阶段。
Phase 2.1:需求转换
将每项业务需求转换为形式化约束:
| 业务需求 | 约束类型 | 形式化表达 |
|---|---|---|
| “每位学生分配一所学校” | 容量 | ` |
| “学校有座位数量限制” | 容量 | ` |
| “兄弟姐妹必须在一起” | 耦合 | school(s1) = school(s2) if siblings(s1,s2) |
| “学生 X 不能就读 Y” | 排除 | (X, Y) ∉ matches |
| “优先考虑居民” | 偏好排序 | rank(resident) < rank(non-resident) |
检查清单:
□ List ALL business requirements
□ Classify each as: capacity | coupling | exclusion | ordering | soft preference
□ Identify conflicts between requirements (document tradeoffs)
□ Distinguish HARD constraints (must satisfy) from SOFT (optimize toward)
□ Validate translations with stakeholder examples
Phase 2.2:算法选择
使用 references/decision-guide.md 选择算法。请确认:
□ Algorithm handles all HARD constraints
□ Algorithm can optimize SOFT constraints (or document gaps)
□ Complexity acceptable for data size (see references/algorithms.md)
□ Stability requirements met (if two-sided)
□ Optimality requirements met (if weighted)
Phase 2.3:数据模型设计
定义实体、关系和偏好表示方式:
□ Entity schema for each side (attributes, identifiers)
□ Preference representation (ranked list | score matrix | pairwise comparisons)
□ Constraint encoding (how exclusions/couplings are stored)
□ Hierarchy representation (if multi-level: tree | DAG | adjacency list)
□ Tie-breaking rules (deterministic ordering for equal preferences)
Phase 2.4:接口契约
明确输入、输出和不变量:
输入契约:
□ Preference format and validation rules
□ Constraint format and validation rules
□ Required vs optional fields
□ How missing preferences are handled (reject | default rank | exclude)
输出契约:
□ Match format (pairs | assignment map | ranked list)
□ Unmatched entity handling (explicit list | null matches | error)
□ Match metadata (scores, stability proof, constraint satisfaction report)
不变量:
□ Determinism: same input → same output (document randomness if any)
□ Completeness: all entities matched OR explicitly unmatched
□ Validity: all matches satisfy hard constraints
Phase 2.5:测试策略
在实现前定义验证方式:
□ Unit tests for preference parsing and constraint validation
□ Property tests: stability, optimality, constraint satisfaction
□ Edge cases: empty inputs, single entity, all tied preferences
□ Regression tests from known-good examples
□ Performance benchmarks at target scale
3. 调试流程
遇到任何匹配问题时,都按以下诊断顺序执行。不得跳过步骤。
Phase 3.1:症状分类
确定症状类别:
| 症状 | 类别 | 转到 |
|---|---|---|
| 输入相同,输出不同 | 不稳定性 | 3.2 |
| 匹配违反业务规则 | 约束违反 | 3.3 |
| 匹配在技术上有效,但“错误” | 偏好不一致 | 3.4 |
| 嵌套/层级数据出错 | 层级错误 | 3.5 |
| 规模扩大后性能不佳 | 性能 | 3.6 |
Phase 3.2:不稳定性诊断
非确定性匹配的根本原因:
□ RANDOMNESS: Check for unseeded RNG in tie-breaking
→ Fix: Use deterministic tie-breaker (lexicographic ID, timestamp)
□ FLOATING POINT: Check score comparisons for floating point issues
→ Fix: Use epsilon comparison or integer scores
□ HASH ORDERING: Check if iteration order depends on hash maps
→ Fix: Sort keys before iteration
□ PARALLEL RACE: Check for concurrent modifications
→ Fix: Synchronize or use sequential processing
□ INPUT ORDERING: Check if algorithm is order-sensitive
→ Fix: Canonicalize input order (sort by ID)
验证:
□ Run matching 10x with identical inputs
□ Diff all outputs
□ If any differ, add logging to identify divergence point
Phase 3.3:约束违反诊断
诊断顺序:
1. □ IDENTIFY: Which specific constraint is violated?
→ List the violated constraint and the violating match
2. □ TRACE: Where should constraint be enforced?
→ Map constraint to code location (filter | validation | algorithm step)
3. □ VERIFY ENCODING: Is constraint correctly represented?
→ Print constraint data structure, verify against requirement
4. □ VERIFY ENFORCEMENT: Is constraint checked at right time?
→ Add logging before/after enforcement point
5. □ CHECK ORDERING: Is constraint checked before conflicting decisions?
→ Trace decision sequence, verify constraint checked first
6. □ CHECK COMPLETENESS: Are all instances covered?
→ Enumerate all entities that should be constrained
常见失败模式:
| 模式 | 症状 | 修复方法 |
|---|---|---|
| 后期执行约束 | 中间状态有效,最终状态无效 | 提前执行检查 |
| 覆盖不完整 | 部分实体受约束,其他实体不受约束 | 列举所有情况 |
| 混淆软约束与硬约束 | 为了“更好”的匹配而违反约束 | 将其重新归类为硬约束 |
| 数据过时 | 约束基于过时的值 | 检查前刷新数据 |
Phase 3.4:偏好不一致诊断
当匹配有效但未体现预期优先级时:
1. □ EXTRACT: Get the actual preference data used
→ Log/print the exact preference structure at match time
2. □ COMPARE: Check against expected preferences
→ Side-by-side diff with business-stated priorities
3. □ TRACE TRANSFORMATION: Follow preference from input to algorithm
→ Log at each transformation step (parsing, normalization, scoring)
4. □ CHECK SCORING: Verify score calculation
→ Manual calculation for 2-3 example cases
5. □ CHECK AGGREGATION: If multi-criteria, verify combination
→ Test each criterion independently, then combined
6. □ CHECK NORMALIZATION: Verify scale/range handling
→ Check for min/max, z-score, or rank normalization bugs
评分函数检查清单:
□ Direction correct (higher = better or lower = better, consistently)
□ Scale appropriate (no single factor dominating)
□ Missing values handled (null → 0? → excluded? → default?)
□ Ties handled explicitly (not left to floating point chance)
□ Edge cases: extreme values, all same values, single candidate
Phase 3.5:层级遍历诊断
针对多层级匹配问题:
1. □ VISUALIZE: Draw the hierarchy with the problematic match
→ Tree diagram showing all levels and the match path
2. □ CHECK INHERITANCE: Do child constraints inherit from parent?
→ Verify constraint propagation rules
3. □ CHECK AGGREGATION: How do child preferences roll up?
→ Verify aggregation function (sum | max | weighted | majority)
4. □ CHECK LEVEL INTERACTION: Can matches cross levels?
→ Document allowed/forbidden cross-level matches
5. □ CHECK TRAVERSAL ORDER: Top-down or bottom-up?
→ Verify algorithm processes levels in intended order
6. □ CHECK PARTIAL MATCHES: Can a parent match without all children?
→ Document completeness requirements per level
常见层级错误:
| 错误 | 症状 | 修复方法 |
|---|---|---|
| 传播缺失 | 子级忽略父级约束 | 添加继承逻辑 |
| 重复计数 | 同一实体被多次加权 | 在汇总时去重 |
| 跳过层级 | 在错误的层级进行匹配 | 添加层级验证 |
| 孤立节点处理 | 未关联的子级导致错误 | 定义孤立节点策略 |
Phase 3.6:性能诊断
针对规模和速度问题:
1. □ PROFILE: Identify the slow component
→ Time each phase: input parsing, preference building, matching, output
2. □ COMPLEXITY CHECK: Verify actual vs expected complexity
→ Log iteration counts, compare to theoretical O(n)
3. □ MEMORY CHECK: Profile memory usage
→ Watch for preference matrix explosion (n² space)
4. □ ALGORITHM FIT: Verify algorithm appropriate for scale
→ See references/algorithms.md for complexity comparison
5. □ CACHING: Check for redundant computation
→ Log cache hits/misses for preference lookups
6. □ BATCH VS STREAMING: Check processing model
→ Full recomputation vs incremental updates
4. 测试与验证流程
4.1:正确性属性
对每个匹配系统测试以下属性:
□ DETERMINISM: run(input) = run(input) (10 trials minimum)
□ COMPLETENESS: all entities either matched or explicitly unmatched
□ VALIDITY: all matches satisfy all hard constraints
□ STABILITY (if applicable): no blocking pairs exist
□ OPTIMALITY (if applicable): objective function at expected value
4.2:稳定性验证(双边匹配)
对于稳定匹配,验证不存在阻塞对:
# Pseudocode - verify no blocking pair exists
for each unmatched_pair (a, b):
if a prefers b over current_match(a):
if b prefers a over current_match(b):
FAIL: blocking pair found (a, b)
□ Enumerate all non-matched pairs
□ Check mutual preference for each
□ Report any blocking pairs found
□ For large instances, sample-check (document coverage)
4.3:约束满足验证
□ List all hard constraints
□ For each match, verify against each constraint
□ Generate constraint satisfaction report
□ Flag any violations with specific match and constraint
4.4:边界情况测试套件
必测用例:
□ Empty input (no entities on one or both sides)
□ Single entity (one-to-one degenerate case)
□ All identical preferences (maximum tie scenario)
□ Mutually exclusive preferences (everyone wants same thing)
□ Impossible constraints (unsatisfiable, should error clearly)
□ Maximum capacity (all slots exactly filled)
□ Minimum capacity (barely enough slots)
□ Self-referential (can entity match itself? test boundary)
□ Circular preferences (A→B→C→A)
4.5:回归测试维护
□ Capture real production cases that revealed bugs
□ Minimize to smallest reproducing example
□ Document expected behavior explicitly
□ Run on every change to matching logic
5. 审查清单
审查匹配系统代码或设计时:
5.1:设计审查
□ Problem correctly classified (Section 1)
□ Algorithm appropriate for problem class (references/decision-guide.md)
□ All business requirements mapped to constraints (Section 2.1)
□ Hard vs soft constraints clearly distinguished
□ Tie-breaking is deterministic and documented
□ Hierarchy semantics defined (if applicable)
5.2:实现审查
□ Preference representation matches algorithm requirements
□ Constraints enforced at correct point in algorithm
□ No hidden randomness (unseeded RNG, hash iteration)
□ Floating point comparison handled correctly
□ Edge cases handled (empty, single, ties)
□ Error messages identify specific constraint violations
5.3:测试审查
□ All properties from 4.1 tested
□ Edge cases from 4.4 covered
□ Performance benchmarked at realistic scale
□ Regression tests exist for past bugs
附录:常见反模式
| 反模式 | 问题 | 解决方案 |
|---|---|---|
| 先到先得的贪心策略 | 依赖顺序,结果非最优 | 使用合适的算法 |
| 分数 = 所有因素之和 | 某一因素占主导 | 统一量纲 |
| 重试直到有效 | 结果不确定,速度慢 | 调整约束顺序 |
| 全局偏好缓存 | 更新后数据过时 | 发生变化时使缓存失效 |
| 用字符串匹配实体 | 大小写/空格导致错误 | 使用规范 ID |
| 用浮点数判断相等以处理平局 | 结果不确定 | 使用 epsilon 或整数 |
| 递归遍历层级结构 | 存在栈溢出风险 | 使用带显式栈的迭代方式 |
| N² 偏好矩阵 | 内存占用激增 | 使用稀疏表示 |
评论
支持 Markdown