Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Heuristic:1ay1 Agentty Lock Order Is A Type

From Leeroopedia
Knowledge Sources
Domains Concurrency, Type_Safety
Last Updated 2026-10-28 14:00 GMT

Overview

Encode lock acquisition order as a type-level ordinal, so the compiler can prove that locks are always acquired in the same order and deadlocks are structurally impossible.

Description

The Lock_Order_Is_A_Type heuristic assigns each lock a numeric level (via a type-level constant), and requires that locks are acquired in ascending level order. The level is encoded in the lock's type (using C++ templates or `constexpr`), so acquiring lock level 2 while holding lock level 1 is valid, but acquiring lock level 1 while holding lock level 2 is a compile error. This eliminates deadlock by construction: if the compiler accepts the code, the lock ordering is consistent across all call sites.

In agentty this appears in: the lock ordering types (`lock_levels.hpp`) which define type-level lock levels; and the dual-lock shared file (`shared_file.hpp`) which acquires its two locks in a defined order enforced by the type system.

Usage

Apply this heuristic when a system uses multiple locks that could deadlock. Assign each lock a level, encode the level in the type, and enforce ascending acquisition order at compile time. This is especially valuable for systems with many locks (credential store, thread log, blob store) where manual lock-order discipline is error-prone.

The Insight (Rule of Thumb)

  • Action: Encode lock acquisition order as a type-level ordinal; enforce ascending order at compile time.
  • Value: Deadlock is a compile error, not a runtime hang.
  • Trade-off: More template machinery and longer compile times; but deadlocks are eliminated, not just mitigated.
  • Compatibility: Requires C++ template metaprogramming; pairs with Heuristic:1ay1_Agentty_Compile_Time_Proofs.

Reasoning

Lock-ordering deadlocks occur when two code paths acquire the same two locks in opposite orders. Runtime discipline (code review, lock-order documentation) is fallible — a new code path that violates the order compiles fine and deadlocks intermittently. Type-level lock ordering makes the violation a compile error: the lock's type carries its level, and acquiring out of order does not compile. The compiler is an exhaustive checker that examines every call site, not just the ones a human reviewer happens to read. This trades compile-time cost for the elimination of an entire deadlock class.

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment