Skip to content

Commit a9036dc

Browse files
NSHkrNSHkr
authored andcommitted
Expand tests for infra in foundation and debug
1 parent bbe678d commit a9036dc

File tree

15 files changed

+3737
-107
lines changed

15 files changed

+3737
-107
lines changed

CLAUDE.md

Lines changed: 262 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,262 @@
1+
# CLAUDE.md
2+
3+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4+
5+
## Project Overview
6+
7+
ElixirScope is a revolutionary AST-based debugging and code intelligence platform for Elixir applications built with a clean 9-layer architecture. The project provides "execution cinema" capabilities through deep static analysis, runtime correlation, and AI-powered insights.
8+
9+
**Current Status**: Foundation layer is production-ready with enterprise-grade OTP patterns. Upper 8 layers have framework structures in place but need implementation completion.
10+
11+
## Development Commands
12+
13+
### Primary Testing Commands
14+
```bash
15+
# Quick development validation
16+
mix dev.check # Format check, Credo, compile, smoke tests
17+
make dev-check # Same via Makefile
18+
19+
# Test categories
20+
mix test.unit # Fast unit tests
21+
mix test.smoke # Quick health checks
22+
mix test.integration # Cross-layer integration tests
23+
mix test.contract # API contract validation
24+
mix test.all # Complete test suite
25+
26+
# Quality assurance
27+
mix qa.format # Code formatting check
28+
mix qa.credo # Static analysis
29+
mix qa.dialyzer # Type checking
30+
mix qa.all # Complete QA pipeline
31+
32+
# CI pipeline
33+
mix ci.test # Full CI validation
34+
make ci-check # Same via Makefile
35+
```
36+
37+
### Development Workflow
38+
```bash
39+
# Setup
40+
mix setup # Install deps, compile, setup Dialyzer PLT
41+
make setup # Same via Makefile
42+
43+
# Development scripts
44+
mix dev.workflow # Interactive Foundation layer testing
45+
mix run scripts/benchmark.exs # Performance benchmarking
46+
47+
# Architecture validation
48+
mix validate_architecture # Layer dependency validation
49+
```
50+
51+
### Key Make Targets
52+
```bash
53+
make help # Show all available commands
54+
make smoke # Run smoke tests
55+
make watch # Auto-run tests on file changes
56+
make benchmark # Performance benchmarks
57+
```
58+
59+
## Architecture
60+
61+
ElixirScope implements a clean 9-layer architecture with strict dependency rules (each layer only depends on lower layers):
62+
63+
```
64+
┌─────────────────────────────────────┐
65+
│ Debugger │ ← Complete debugging interface
66+
├─────────────────────────────────────┤
67+
│ Intelligence │ ← AI/ML integration
68+
├─────────────────────────────────────┤
69+
│ Capture Query │ ← Runtime correlation & querying
70+
├─────────────────────────────────────┤
71+
│ Analysis │ ← Architectural analysis
72+
├─────────────────────────────────────┤
73+
│ CPG │ ← Code Property Graph
74+
├─────────────────────────────────────┤
75+
│ Graph │ ← Graph algorithms
76+
├─────────────────────────────────────┤
77+
│ AST │ ← AST parsing & repository
78+
├─────────────────────────────────────┤
79+
│ Foundation │ ← Core utilities (COMPLETE)
80+
└─────────────────────────────────────┘
81+
```
82+
83+
## Foundation Layer (Production Ready)
84+
85+
The Foundation layer is **complete and production-ready** with enterprise-grade OTP patterns:
86+
87+
### Core Services
88+
- **ConfigServer**: Dynamic configuration with validation and hot reloading
89+
- **EventStore**: Comprehensive event system with serialization
90+
- **TelemetryService**: Advanced metrics and monitoring
91+
- **ProcessRegistry**: Registry-based service discovery with namespace isolation
92+
93+
### Infrastructure Protection
94+
- **Circuit Breaker**: Fuse-based failure protection with telemetry
95+
- **Rate Limiter**: Hammer-based rate limiting with entity support
96+
- **Connection Manager**: Poolboy-based connection pooling
97+
- **Unified Infrastructure**: Single facade for all protection patterns
98+
99+
### Key Patterns
100+
- **Perfect Test Isolation**: Concurrent tests with namespace separation
101+
- **Graceful Degradation**: Fallback strategies for service failures
102+
- **Performance Monitoring**: Sub-millisecond operations, telemetry integration
103+
104+
## Critical File Filtering
105+
106+
The project uses `mix.exs` filtering to exclude incomplete upper layers from compilation:
107+
108+
```elixir
109+
# Currently excluded from compilation:
110+
excluded_dirs = [
111+
"analysis/", "ast/", "capture/", "cpg/",
112+
"debugger/", "graph/", "integration/",
113+
"intelligence/", "query/"
114+
]
115+
```
116+
117+
When implementing upper layers, remove directories from `excluded_dirs` in `mix.exs:get_filtered_lib_paths/0`.
118+
119+
## Testing Architecture
120+
121+
ElixirScope implements enterprise-grade testing with multiple categories:
122+
123+
### Test Organization
124+
- **unit/** - Fast, isolated layer-specific tests
125+
- **integration/** - Cross-layer integration testing
126+
- **contract/** - API contract validation
127+
- **property/** - Property-based testing
128+
- **smoke/** - Quick health checks
129+
- **support/** - Test utilities and helpers
130+
131+
### Test Isolation
132+
- **Namespace Separation**: Tests use isolated Registry namespaces
133+
- **Concurrent Safe**: All tests can run concurrently without conflicts
134+
- **Property Testing**: 30+ properties ensure algorithmic correctness
135+
136+
## Performance Characteristics
137+
138+
### Registry Performance (Validated)
139+
- **ProcessRegistry.lookup**: 2,000 ops/ms
140+
- **ServiceRegistry.lookup**: 2,000 ops/ms
141+
- **ServiceRegistry.health_check**: 2,500 ops/ms
142+
- **Memory Usage**: Sub-MB for typical workloads
143+
144+
### Development Validation
145+
Run `mix run scripts/benchmark.exs` to validate documented performance characteristics.
146+
147+
## Code Conventions
148+
149+
### Module Structure and Naming
150+
```elixir
151+
# Module naming pattern:
152+
ElixirScope.[Layer].[Component].[SubComponent]
153+
154+
# Examples:
155+
ElixirScope.Foundation.Infrastructure.CircuitBreaker
156+
ElixirScope.AST.Repository.Enhanced
157+
ElixirScope.Graph.Algorithms.Centrality
158+
```
159+
160+
### Structs and Type Specifications
161+
Following docs/CODE_QUALITY.md standards:
162+
163+
```elixir
164+
defmodule ElixirScope.Foundation.Config.StartOpts do
165+
@moduledoc """
166+
Configuration struct for service initialization.
167+
See `@type t` for complete type specification.
168+
"""
169+
170+
@enforce_keys [:name, :namespace, :options]
171+
defstruct @enforce_keys
172+
173+
@type t :: %__MODULE__{
174+
name: atom(),
175+
namespace: atom(),
176+
options: keyword()
177+
}
178+
179+
@doc """
180+
Creates a new StartOpts struct.
181+
182+
## Examples
183+
184+
iex> StartOpts.new(:service, :production, [timeout: 5000])
185+
%StartOpts{name: :service, namespace: :production, options: [timeout: 5000]}
186+
"""
187+
@spec new(atom(), atom(), keyword()) :: t()
188+
def new(name, namespace, options) do
189+
%__MODULE__{name: name, namespace: namespace, options: options}
190+
end
191+
end
192+
```
193+
194+
### Documentation Standards
195+
- Every public module has `@moduledoc`
196+
- Every public function has `@doc` with examples
197+
- Every struct has `@type t` specification
198+
- Use `@spec` for all public functions
199+
- Reference types in documentation (`See @type t`)
200+
201+
### Naming Conventions
202+
- **Modules**: CamelCase (e.g., `NodeSelectorBroadcaster`)
203+
- **Functions/Variables**: snake_case (e.g., `start_link`, `config_server`)
204+
- **Struct Fields**: snake_case (e.g., `execution_broadcaster_reference`)
205+
- **Types**: snake_case (e.g., `@type pool_config :: keyword()`)
206+
- **Atoms**: snake_case (e.g., `:rate_limit_exceeded`)
207+
208+
### Layer Dependencies
209+
Each layer can only depend on lower layers:
210+
```elixir
211+
debugger: [:intelligence, :capture, :query, :analysis, :cpg, :graph, :ast, :foundation]
212+
intelligence: [:query, :analysis, :cpg, :graph, :ast, :foundation]
213+
# ... etc (foundation depends on nothing)
214+
```
215+
216+
### Error Handling
217+
Use structured errors with ElixirScope.Foundation.Types.Error:
218+
```elixir
219+
{:error, Error.new([
220+
code: 6001,
221+
error_type: :rate_limit_exceeded,
222+
message: "Rate limit exceeded",
223+
severity: :medium,
224+
context: %{entity_id: entity_id, operation: operation}
225+
])}
226+
```
227+
228+
## Key Dependencies
229+
230+
### Production
231+
- `{:telemetry, "~> 1.2"}` - Metrics and monitoring
232+
- `{:jason, "~> 1.4"}` - JSON serialization
233+
- `{:poolboy, "~>1.5.2"}` - Connection pooling
234+
- `{:hammer, "~>7.0.1"}` - Rate limiting
235+
- `{:fuse, "~>2.5.0"}` - Circuit breakers
236+
237+
### Development/Testing
238+
- `{:mox, "~> 1.2"}` - Mocking framework
239+
- `{:stream_data, "~> 1.1"}` - Property-based testing
240+
- `{:excoveralls, "~> 0.18"}` - Test coverage
241+
- `{:credo, "~> 1.7"}` - Static analysis
242+
- `{:dialyxir, "~> 1.4"}` - Type checking
243+
244+
## Development Notes
245+
246+
### Next Implementation Priority
247+
1. **AST Layer**: Complete parser implementation and repository patterns
248+
2. **Graph Layer**: Implement mathematical graph algorithms
249+
3. **CPG Layer**: Code Property Graph construction pipeline
250+
4. **Analysis Layer**: Architectural pattern detection
251+
252+
### Important Files
253+
- `DEV.md` - Comprehensive technical development guide
254+
- `mix.exs` - Contains layer filtering configuration
255+
- `scripts/dev_workflow.exs` - Interactive Foundation testing
256+
- `docs/FOUNDATION_OTP_IMPLEMENT_NOW/` - Foundation implementation guides
257+
258+
### Testing Strategy
259+
Always run `mix dev.check` before committing. The Foundation layer has comprehensive test coverage with property-based testing ensuring algorithmic correctness.
260+
261+
### Performance Monitoring
262+
Use `scripts/benchmark.exs` to validate performance characteristics. The Foundation layer maintains sub-millisecond operation performance with telemetry integration.

lib/elixir_scope/foundation/infrastructure/circuit_breaker.ex

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,9 @@ defmodule ElixirScope.Foundation.Infrastructure.CircuitBreaker do
118118
{:error, %Error{error_type: :circuit_breaker_blown}}
119119
"""
120120
@spec execute(fuse_name(), operation(), map()) :: operation_result()
121-
def execute(name, operation, metadata \\ %{}) when is_atom(name) and is_function(operation, 0) do
121+
def execute(name, operation, metadata \\ %{})
122+
123+
def execute(name, operation, metadata) when is_atom(name) and is_function(operation, 0) do
122124
start_time = System.monotonic_time(:microsecond)
123125

124126
try do
@@ -164,6 +166,33 @@ defmodule ElixirScope.Foundation.Infrastructure.CircuitBreaker do
164166
})
165167
)
166168

169+
{:error, error}
170+
catch
171+
kind, value ->
172+
# Handle throw and exit
173+
:fuse.melt(name)
174+
duration = System.monotonic_time(:microsecond) - start_time
175+
176+
error =
177+
Error.new(
178+
code: 5012,
179+
error_type: :protected_operation_failed,
180+
message: "Protected operation failed with #{kind}: #{inspect(value)}",
181+
severity: :medium,
182+
context: %{fuse_name: name, kind: kind, value: value}
183+
)
184+
185+
emit_telemetry(
186+
:call_executed,
187+
Map.merge(metadata, %{
188+
name: name,
189+
duration: duration,
190+
status: :failed,
191+
kind: kind,
192+
value: value
193+
})
194+
)
195+
167196
{:error, error}
168197
end
169198

@@ -237,6 +266,31 @@ defmodule ElixirScope.Foundation.Infrastructure.CircuitBreaker do
237266
end
238267
end
239268

269+
def execute(name, operation, _metadata) do
270+
{:error,
271+
Error.new(
272+
code: 5009,
273+
error_type: :invalid_input,
274+
message:
275+
"Invalid circuit breaker inputs: name must be atom, operation must be 0-arity function",
276+
severity: :medium,
277+
context: %{
278+
name: name,
279+
operation_type: if(is_function(operation), do: :function, else: :not_function)
280+
}
281+
)}
282+
rescue
283+
_ ->
284+
{:error,
285+
Error.new(
286+
code: 5010,
287+
error_type: :invalid_input,
288+
message: "Invalid circuit breaker inputs",
289+
severity: :medium,
290+
context: %{name: name, operation: operation}
291+
)}
292+
end
293+
240294
@doc """
241295
Get the current status of a circuit breaker.
242296
@@ -293,6 +347,17 @@ defmodule ElixirScope.Foundation.Infrastructure.CircuitBreaker do
293347
end
294348
end
295349

350+
def get_status(name) do
351+
{:error,
352+
Error.new(
353+
code: 5011,
354+
error_type: :invalid_input,
355+
message: "Invalid circuit breaker name: must be an atom",
356+
severity: :medium,
357+
context: %{name: name}
358+
)}
359+
end
360+
296361
@doc """
297362
Reset a blown circuit breaker manually.
298363

0 commit comments

Comments
 (0)