agenticraft_foundation.complexity.annotations¶
Complexity annotations — decorator-based tracking for algorithmic complexity classification.
Complexity annotations for algorithm documentation and analysis.
This module provides decorators and utilities for documenting and analyzing algorithm complexity, following formal verification principles from distributed systems research.
Example
@complexity( time="O(D * log n)", space="O(n)", messages="Theta(n^2)", rounds="O(D)", assumptions=["partial synchrony", "f < n/3 Byzantine"], theorem_ref="Castro & Liskov 1999" ) async def propose(self, value, context): ...
ComplexityClass
¶
Bases: str, Enum
Standard complexity classes.
SynchronyModel
¶
Bases: str, Enum
Synchrony assumptions for distributed algorithms.
FaultModel
¶
Bases: str, Enum
Fault tolerance models.
Classical distributed systems fault models: - CRASH_STOP: Process halts, never recovers (f < n/2) - CRASH_RECOVERY: Process halts, may recover with stable storage (f < n/2) - BYZANTINE: Arbitrary behavior including malicious (f < n/3) - OMISSION: Process fails to send or receive messages (f < n/2) - AUTHENTICATED_BYZANTINE: Byzantine with digital signatures (f < n/3)
LLM-specific fault models (map to classical analogs): - HALLUCINATION: Generates plausible but incorrect output (analog: Byzantine — arbitrary incorrect responses) - PROMPT_INJECTION: Adversarial input manipulates behavior (analog: Byzantine — attacker-controlled behavior) - NON_DETERMINISM: Same input yields different outputs across calls (analog: Omission — unreliable message content) - CONTEXT_OVERFLOW: Input exceeds context window, truncating information (analog: Crash-Recovery — partial state loss, recoverable with chunking)
ComplexityBound
dataclass
¶
Represents a complexity bound with optional proof reference.
| ATTRIBUTE | DESCRIPTION |
|---|---|
expression |
The complexity expression (e.g., "O(n log n)")
TYPE:
|
tight |
Whether this is a tight bound (Theta vs O)
TYPE:
|
amortized |
Whether this is amortized complexity
TYPE:
|
expected |
Whether this is expected (average) complexity
TYPE:
|
worst_case |
Whether this is worst-case complexity
TYPE:
|
proof_ref |
Reference to proof (paper, theorem number)
TYPE:
|
notes |
Additional notes about the bound
TYPE:
|
__str__()
¶
Format the complexity bound as a string.
parse(expr)
classmethod
¶
Parse a complexity expression string.
| PARAMETER | DESCRIPTION |
|---|---|
expr
|
Complexity expression like "O(n log n)" or "Theta(n^2)"
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ComplexityBound
|
ComplexityBound instance |
DistributedComplexity
dataclass
¶
Complexity metrics specific to distributed algorithms.
| ATTRIBUTE | DESCRIPTION |
|---|---|
time |
Time complexity (sequential operations)
TYPE:
|
space |
Space complexity per node
TYPE:
|
messages |
Total message complexity
TYPE:
|
message_size |
Size of individual messages
TYPE:
|
rounds |
Round/communication complexity
TYPE:
|
bits |
Total bit complexity
TYPE:
|
synchrony |
Required synchrony model
TYPE:
|
fault_model |
Assumed fault model
TYPE:
|
fault_tolerance |
Maximum faults tolerated (e.g., "f < n/3")
TYPE:
|
assumptions |
List of additional assumptions
TYPE:
|
theorem_ref |
Reference to theorem/paper
TYPE:
|
lower_bound |
Known lower bound for the problem
TYPE:
|
optimal |
Whether this achieves the lower bound
TYPE:
|
ComplexityAnalysis
dataclass
¶
Results of complexity analysis on a codebase.
summary()
¶
Generate summary report.
get_complexity(func)
¶
Get complexity annotation for a function.
| PARAMETER | DESCRIPTION |
|---|---|
func
|
The annotated function
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DistributedComplexity | None
|
DistributedComplexity if annotated, None otherwise |
get_all_complexities()
¶
Get all registered complexity annotations.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, DistributedComplexity]
|
Dictionary mapping function keys to complexity info |
complexity(time=None, space=None, messages=None, message_size=None, rounds=None, bits=None, synchrony=None, fault_model=None, fault_tolerance=None, assumptions=None, theorem_ref=None, lower_bound=None, optimal=False)
¶
Decorator to annotate function with complexity information.
This decorator documents algorithm complexity for formal analysis and documentation purposes. It stores the complexity information in a registry for later retrieval.
| PARAMETER | DESCRIPTION |
|---|---|
time
|
Time complexity (e.g., "O(n log n)")
TYPE:
|
space
|
Space complexity per node
TYPE:
|
messages
|
Total message complexity
TYPE:
|
message_size
|
Size of individual messages
TYPE:
|
rounds
|
Round/communication complexity
TYPE:
|
bits
|
Total bit complexity
TYPE:
|
synchrony
|
Required synchrony model
TYPE:
|
fault_model
|
Assumed fault model
TYPE:
|
fault_tolerance
|
Maximum faults tolerated
TYPE:
|
assumptions
|
Additional assumptions
TYPE:
|
theorem_ref
|
Reference to theorem/paper
TYPE:
|
lower_bound
|
Known lower bound
TYPE:
|
optimal
|
Whether this achieves lower bound
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Callable[P, R]], Callable[P, R]]
|
Decorated function with complexity metadata |
Example
@complexity( time="O(n^2)", messages="O(n^2)", rounds="O(1)", fault_model=FaultModel.BYZANTINE, fault_tolerance="f < n/3", theorem_ref="Castro & Liskov 1999, PBFT" ) async def pbft_prepare(self, request): ...
consensus_complexity(algorithm, fault_tolerance='f < n/3', synchrony=SynchronyModel.PARTIAL_SYNCHRONY)
¶
Specialized complexity decorator for consensus algorithms.
Provides preset complexity bounds for common consensus algorithms.
| PARAMETER | DESCRIPTION |
|---|---|
algorithm
|
Name of consensus algorithm (raft, pbft, paxos, etc.)
TYPE:
|
fault_tolerance
|
Fault tolerance bound
TYPE:
|
synchrony
|
Synchrony model
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Callable[P, R]], Callable[P, R]]
|
Complexity decorator with preset values |
gossip_complexity(fanout=3, rounds='O(log n)')
¶
Specialized complexity decorator for gossip protocols.
| PARAMETER | DESCRIPTION |
|---|---|
fanout
|
Number of nodes to contact per round
TYPE:
|
rounds
|
Expected rounds to convergence
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable[[Callable[P, R]], Callable[P, R]]
|
Complexity decorator with gossip-specific values |
analyze_complexity(module)
¶
Analyze complexity annotations in a module.
| PARAMETER | DESCRIPTION |
|---|---|
module
|
Python module to analyze
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ComplexityAnalysis
|
ComplexityAnalysis with results |
parse_big_o(expression)
¶
Parse a Big-O expression into components.
| PARAMETER | DESCRIPTION |
|---|---|
expression
|
Big-O expression like "O(n^2 log n)"
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
tuple[str, dict[str, Any]]
|
Tuple of (base_class, parameters) |
Example
parse_big_o("O(n^2 log n)") ('polynomial_log', {'exponent': 2, 'log_factor': True})
compare_complexity(a, b)
¶
Compare two complexity expressions.
| PARAMETER | DESCRIPTION |
|---|---|
a
|
First complexity expression
TYPE:
|
b
|
Second complexity expression
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
-1 if a < b, 0 if equal, 1 if a > b |