pmat 3.15.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
# 💾 PMAT Memory Management & Optimization - Comprehensive Guide

## Table of Contents
1. [Overview]#overview
2. [Architecture]#architecture
3. [Memory Commands]#memory-commands
4. [Pool Management]#pool-management
5. [Pressure Detection]#pressure-detection
6. [Optimization Strategies]#optimization-strategies
7. [CI/CD Integration]#cicd-integration
8. [Best Practices]#best-practices

## Overview

PMAT provides sophisticated memory management capabilities to optimize performance, prevent out-of-memory errors, and ensure efficient resource utilization across large-scale code analysis operations.

### Key Features
- **🎯 Real-time Monitoring**: Track memory usage across all PMAT components
- **🔄 Automatic Cleanup**: Smart garbage collection and cache eviction
- **📊 Pool Statistics**: Detailed memory pool analysis and optimization
- **⚠️ Pressure Detection**: Early warning system for memory constraints
- **🚀 Performance Tuning**: Adaptive memory allocation strategies
- **📈 Historical Tracking**: Memory usage patterns and trend analysis

## Architecture

```
┌────────────────────────────────────────────────────────────────┐
│                     Memory Management System                     │
├────────────────────────────────────────────────────────────────┤
│                         Core Components                          │
│                                                                  │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│  │   Monitor    │  │   Allocator  │  │   Cleanup    │         │
│  │   Service    │  │    Pools     │  │    Engine    │         │
│  └──────────────┘  └──────────────┘  └──────────────┘         │
│                                                                  │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐         │
│  │   Pressure   │  │    Cache     │  │   Metrics    │         │
│  │   Detector   │  │   Manager    │  │   Collector  │         │
│  └──────────────┘  └──────────────┘  └──────────────┘         │
└────────────────────────────────────────────────────────────────┘
```

### Memory Pools

PMAT uses specialized memory pools for different operations:

| Pool | Purpose | Default Size | Growth Strategy |
|------|---------|--------------|-----------------|
| **AST Pool** | Syntax tree parsing | 512 MB | Exponential |
| **Analysis Pool** | Code analysis operations | 256 MB | Linear |
| **Cache Pool** | Result caching | 1 GB | Adaptive |
| **Temp Pool** | Temporary allocations | 128 MB | Fixed |
| **String Pool** | String interning | 64 MB | Incremental |

## Memory Commands

### 1. Memory Statistics

```bash
# Show current memory usage
pmat memory stats

# Detailed statistics with breakdown
pmat memory stats --detailed

# Export statistics as JSON
pmat memory stats --format json > memory-stats.json

# Real-time monitoring (updates every second)
pmat memory stats --watch
```

**Example Output:**
```
Memory Statistics
═════════════════════════════════════════════
Total Allocated:     1,247 MB
Total Used:           892 MB (71.5%)
Total Available:      355 MB (28.5%)

Pool Breakdown:
├─ AST Pool:          312 MB / 512 MB (60.9%)
├─ Analysis Pool:     156 MB / 256 MB (60.9%)
├─ Cache Pool:        380 MB / 1024 MB (37.1%)
├─ Temp Pool:          28 MB / 128 MB (21.9%)
└─ String Pool:        16 MB / 64 MB (25.0%)

Pressure Level: LOW (0.28)
GC Last Run: 2 minutes ago
GC Next Run: In 8 minutes
```

### 2. Memory Cleanup

```bash
# Force immediate cleanup
pmat memory cleanup

# Cleanup with specific targets
pmat memory cleanup --target cache,temp

# Aggressive cleanup (may impact performance)
pmat memory cleanup --aggressive

# Cleanup and compact memory
pmat memory cleanup --compact
```

### 3. Memory Configuration

```bash
# Configure memory limits
pmat memory configure --max-total 4GB

# Set pool-specific limits
pmat memory configure --ast-pool 1GB --cache-pool 2GB

# Configure GC behavior
pmat memory configure --gc-interval 300 --gc-threshold 0.8

# Enable swap usage (when available)
pmat memory configure --allow-swap --swap-threshold 0.9
```

### 4. Pool Management

```bash
# Show pool statistics
pmat memory pools

# Detailed pool analysis
pmat memory pools --detailed

# Reset specific pool
pmat memory pools --reset ast

# Optimize pool sizes based on usage
pmat memory pools --optimize
```

### 5. Pressure Detection

```bash
# Check current memory pressure
pmat memory pressure

# Set pressure thresholds
pmat memory pressure --low 0.3 --medium 0.6 --high 0.8

# Enable automatic response to pressure
pmat memory pressure --auto-respond

# Test pressure response
pmat memory pressure --simulate high
```

## Pool Management

### AST Pool Optimization

```bash
# Analyze AST pool usage patterns
pmat memory pools --analyze ast

# Output:
# AST Pool Analysis
# ═════════════════════════════════
# Current Size: 512 MB
# Peak Usage: 487 MB (95.1%)
# Average Usage: 312 MB (60.9%)
# Fragmentation: 12.3%
# 
# Recommendations:
# - Increase pool size to 768 MB
# - Enable defragmentation at 15% threshold
# - Consider pre-allocation for large files

# Apply recommendations
pmat memory configure --ast-pool 768MB --ast-defrag 0.15
```

### Cache Pool Management

```bash
# View cache statistics
pmat memory pools --cache-stats

# Clear specific cache types
pmat memory cleanup --target cache:tdg,cache:ast

# Configure cache eviction
pmat memory configure --cache-policy lru --cache-ttl 3600
```

## Pressure Detection

### Pressure Levels

| Level | Threshold | System Response | User Action |
|-------|-----------|-----------------|-------------|
| **LOW** | <30% | Normal operation | None required |
| **MEDIUM** | 30-60% | Passive cleanup | Monitor situation |
| **HIGH** | 60-80% | Active cleanup | Consider manual cleanup |
| **CRITICAL** | >80% | Emergency cleanup | Immediate intervention |

### Automatic Responses

```toml
# pmat.toml configuration
[memory.pressure]
auto_respond = true

[memory.pressure.responses.medium]
actions = ["cleanup_temp", "compact_strings"]
notify = false

[memory.pressure.responses.high]
actions = ["cleanup_all", "reduce_cache", "compact_all"]
notify = true
notification_cmd = "notify-send 'PMAT Memory Warning'"

[memory.pressure.responses.critical]
actions = ["emergency_cleanup", "dump_cache", "exit_gracefully"]
notify = true
save_state = true
```

## Optimization Strategies

### 1. Large Project Analysis

```bash
# Pre-configure for large projects (>1M LOC)
pmat memory configure --profile large-project

# This sets:
# - AST Pool: 2 GB
# - Analysis Pool: 1 GB
# - Cache Pool: 4 GB
# - Aggressive GC: Every 2 minutes
# - Incremental processing: Enabled
```

### 2. CI/CD Optimization

```bash
# Optimize for CI environments (limited memory)
pmat memory configure --profile ci-pipeline

# This sets:
# - Total limit: 2 GB
# - Minimal caching
# - Aggressive cleanup
# - Swap disabled
# - Streaming results
```

### 3. Interactive Development

```bash
# Optimize for IDE/editor integration
pmat memory configure --profile interactive

# This sets:
# - Fast response priority
# - Moderate caching
# - Background cleanup
# - Incremental updates
```

## CI/CD Integration

### GitHub Actions Example

```yaml
name: Code Analysis with Memory Management
on: [push, pull_request]

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Install PMAT
        run: cargo install pmat --locked
      
      - name: Configure Memory for CI
        run: |
          pmat memory configure --profile ci-pipeline
          pmat memory configure --max-total 3GB
      
      - name: Run Analysis with Monitoring
        run: |
          # Start memory monitoring in background
          pmat memory stats --watch --format json > memory-log.json &
          MONITOR_PID=$!
          
          # Run analysis
          pmat analyze complexity . --top-files 100
          pmat tdg . --enforce-thresholds
          
          # Stop monitoring
          kill $MONITOR_PID
      
      - name: Check Memory Health
        run: |
          # Analyze memory usage patterns
          pmat memory stats --analyze-log memory-log.json
          
          # Fail if memory pressure was critical
          if grep -q '"pressure_level":"CRITICAL"' memory-log.json; then
            echo "Critical memory pressure detected during analysis"
            exit 1
          fi
      
      - name: Upload Memory Report
        uses: actions/upload-artifact@v3
        with:
          name: memory-analysis
          path: memory-log.json
```

### Docker Configuration

```dockerfile
# Dockerfile with memory optimization
FROM rust:latest

# Install PMAT
RUN cargo install pmat --locked

# Configure memory limits
ENV PMAT_MEMORY_MAX=2GB
ENV PMAT_MEMORY_PROFILE=container

# Set up memory monitoring
HEALTHCHECK --interval=30s --timeout=3s \
  CMD pmat memory pressure || exit 1

# Configure entrypoint with memory management
ENTRYPOINT ["sh", "-c", "pmat memory configure --profile container && exec $@"]
```

## Best Practices

### 1. Regular Monitoring

```bash
# Add to your development workflow
alias pmat-status='pmat memory stats --format compact'
alias pmat-clean='pmat memory cleanup --target temp,cache'
alias pmat-optimize='pmat memory pools --optimize'
```

### 2. Pre-Analysis Configuration

```bash
#!/bin/bash
# prepare-analysis.sh

# Check available memory
AVAILABLE_MEM=$(free -m | awk '/^Mem:/{print $7}')

if [ $AVAILABLE_MEM -lt 2048 ]; then
    echo "Low memory detected. Configuring conservative settings..."
    pmat memory configure --profile low-memory
elif [ $AVAILABLE_MEM -lt 4096 ]; then
    echo "Moderate memory available. Using balanced settings..."
    pmat memory configure --profile balanced
else
    echo "Ample memory available. Using performance settings..."
    pmat memory configure --profile performance
fi

# Run analysis
pmat analyze complexity . --top-files 50
```

### 3. Memory Leak Detection

```bash
# Enable memory tracking
export PMAT_MEMORY_TRACK=1

# Run analysis
pmat analyze complexity src/

# Check for leaks
pmat memory stats --check-leaks

# Generate leak report
pmat memory stats --leak-report > leaks.json
```

### 4. Cache Management

```bash
# View cache usage
pmat memory pools --cache-stats

# Clear old cache entries (>7 days)
pmat memory cleanup --cache-age 7d

# Optimize cache based on hit rates
pmat memory pools --optimize-cache
```

### 5. Emergency Recovery

```bash
#!/bin/bash
# emergency-cleanup.sh

echo "Performing emergency memory cleanup..."

# Stop all PMAT processes
pkill -TERM pmat

# Clear all caches
rm -rf ~/.pmat/cache/*
rm -rf /tmp/pmat-*

# Reset memory configuration
pmat memory configure --reset

# Restart with minimal memory
pmat memory configure --profile minimal

echo "Memory cleanup complete. System reset to minimal configuration."
```

## Integration with PMAT Ecosystem

### Quality Gate Integration

```toml
# pmat.toml
[quality.gates.memory]
enabled = true
max_memory_usage = "4GB"
max_pressure_level = "HIGH"
require_cleanup_after = true
```

### MCP Tool Integration

```javascript
// Monitor memory during analysis
const memoryBefore = await mcp.callTool('pmat', 'memory_stats');

// Run heavy analysis
await mcp.callTool('pmat', 'analyze_complexity', {
  path: '.',
  deep_analysis: true
});

// Check memory after
const memoryAfter = await mcp.callTool('pmat', 'memory_stats');

// Cleanup if needed
if (memoryAfter.pressure_level === 'HIGH') {
  await mcp.callTool('pmat', 'memory_cleanup', {
    aggressive: true
  });
}
```

### Performance Testing Integration

```bash
# Run performance test with memory monitoring
pmat test performance \
  --scenario large-codebase \
  --monitor memory \
  --memory-limit 2GB \
  --report memory-performance.json
```

## Troubleshooting

### Common Issues

1. **Out of Memory Errors**
   ```bash
   # Immediate relief
   pmat memory cleanup --aggressive
   pmat memory configure --allow-swap
   ```

2. **Slow Performance**
   ```bash
   # Check for memory pressure
   pmat memory pressure
   # Optimize pools
   pmat memory pools --optimize
   ```

3. **Cache Misses**
   ```bash
   # Analyze cache performance
   pmat memory pools --cache-stats --detailed
   # Increase cache size
   pmat memory configure --cache-pool 2GB
   ```

---

**Version**: 2.71.0 | **Last Updated**: 2025-09-09 | **Status**: Production Ready