fraiseql-wire 0.1.1

Streaming JSON query engine for Postgres 17
Documentation
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
# fraiseql-wire Testing Guide

## Overview

This guide explains how to run the fraiseql-wire test suite, including unit tests, integration tests, load tests, and stress tests.

---

## Test Structure

### Test Types

1. **Unit Tests** (`.rs` files in `src/`)
   - Protocol encoding/decoding
   - JSON validation
   - SQL generation
   - Error handling
   - **Run**: `cargo test --lib`

2. **Integration Tests** (`tests/` directory)
   - End-to-end client functionality
   - Connection lifecycle
   - Query execution
   - **Run**: `cargo test --test integration -- --ignored`

3. **Load Tests** (`tests/load_tests.rs`)
   - Throughput benchmarks
   - Memory stability
   - Concurrent connections
   - Chunk size optimization
   - **Run**: `cargo test --test load_tests -- --ignored --nocapture`

4. **Stress Tests** (`tests/stress_tests.rs`)
   - Failure scenarios
   - Error handling
   - Recovery mechanisms
   - Edge cases
   - **Run**: `cargo test --test stress_tests -- --ignored --nocapture`

---

## Setting Up the Test Environment

### Prerequisites

1. **Postgres 17** (or compatible)
   ```bash
   # Check if Postgres is running
   pg_isready

   # Start Postgres if needed
   sudo systemctl start postgresql
   ```

2. **Test Database**
   ```bash
   # Create test database
   sudo -u postgres createdb fraiseql_test

   # Or with psql
   psql -U postgres -c "CREATE DATABASE fraiseql_test;"
   ```

3. **Load Test Schema** (required for load/stress tests)
   ```bash
   # Initialize staging schema and tables
   psql -U postgres -d fraiseql_test -f tests/fixtures/schema.sql

   # Seed with test data
   psql -U postgres -d fraiseql_test -f tests/fixtures/seed_data.sql
   ```

### Using Docker (Recommended)

For isolated testing, use Docker Compose:

```bash
# Start Postgres in Docker
docker-compose up -d postgres

# The database is ready when:
docker-compose exec postgres pg_isready

# Initialize schema and seed data
docker-compose exec postgres psql -U postgres -d fraiseql_test -f tests/fixtures/schema.sql
docker-compose exec postgres psql -U postgres -d fraiseql_test -f tests/fixtures/seed_data.sql
```

---

## Running Tests

### All Unit Tests
```bash
cargo test --lib
```

**Expected Output**:
```
running 47 tests

test result: ok. 47 passed; 0 failed; 0 ignored
```

### All Integration Tests (Requires Postgres)
```bash
# Set environment variables
export POSTGRES_HOST=localhost
export POSTGRES_USER=postgres
export POSTGRES_PASSWORD=postgres
export POSTGRES_DB=fraiseql_test

# Run tests
cargo test --test integration -- --ignored --nocapture
```

### Load Tests (Requires Postgres + Schema)
```bash
# Ensure schema is loaded first
psql -U postgres -d fraiseql_test -f tests/fixtures/schema.sql
psql -U postgres -d fraiseql_test -f tests/fixtures/seed_data.sql

# Run load tests
export POSTGRES_HOST=localhost
export POSTGRES_USER=postgres
export POSTGRES_PASSWORD=postgres
export POSTGRES_DB=fraiseql_test

cargo test --test load_tests -- --ignored --nocapture
```

**Load Tests Include**:
- Moderate volume streaming
- Large volume with custom chunk size
- SQL predicate filtering
- Rust predicate filtering
- Large JSON object handling
- ORDER BY verification
- Concurrent connections
- Sustained streaming
- Chunk size comparison
- Partial stream consumption

### Stress Tests (Requires Postgres + Schema)
```bash
export POSTGRES_HOST=localhost
export POSTGRES_USER=postgres
export POSTGRES_PASSWORD=postgres
export POSTGRES_DB=fraiseql_test

cargo test --test stress_tests -- --ignored --nocapture
```

**Stress Tests Include**:
- Early stream drop (client disconnect)
- Invalid connection strings
- Connection refused (unreachable host)
- Missing tables
- Invalid WHERE clauses
- Empty result sets
- Large WHERE clauses
- Rapid connection cycling
- Single connection, multiple queries
- Tiny chunk size
- Huge chunk size
- Wrong credentials
- Partial consumption
- Zero chunk size
- Invalid ORDER BY
- Combined predicates
- JSON validity verification
- Complex ORDER BY expressions

### Run All Tests
```bash
# Unit tests (always runs)
cargo test --lib

# Integration, load, and stress tests (requires Postgres)
cargo test -- --ignored --nocapture
```

---

## Test Database Verification

### Check Schema
```bash
# List all tables in test_staging schema
psql -U postgres -d fraiseql_test -c "\dt test_staging.*"

# Expected output:
#                   List of relations
#  Schema        | Name      | Type  | Owner
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
#  test_staging  | documents | table | postgres
#  test_staging  | projects  | table | postgres
#  test_staging  | tasks     | table | postgres
#  test_staging  | users     | table | postgres
```

### Check Views
```bash
psql -U postgres -d fraiseql_test -c "\dv test_staging.*"
```

### Check Data
```bash
# Count rows in each table
psql -U postgres -d fraiseql_test -c "SELECT * FROM test_staging.row_counts();"

# Sample data
psql -U postgres -d fraiseql_test -c "SELECT jsonb_pretty(data) FROM test_staging.v_projects LIMIT 1;"
```

### Truncate Test Data (Reset)
```bash
psql -U postgres -d fraiseql_test -c "SELECT test_staging.truncate_all();"
```

---

## Interpreting Test Results

### Load Test Output

```
Test: Moderate data volume streaming
  Rows: 5
  Time: 15ms
  Throughput: 333 rows/sec
```

**What This Means**:
- 5 rows were streamed from the projects table
- Took 15 milliseconds
- Throughput is 333 rows/sec

### Stress Test Output

```
Test: Early stream drop (client disconnect)
  Received first row, dropping stream...
  Stream dropped: โœ“
  Reconnection successful: โœ“
```

**What This Means**:
- Stream was successfully dropped after receiving one row
- Client can reconnect and use the connection again
- Error handling and resource cleanup work correctly

---

## Performance Expectations

### Baseline Metrics

After running load tests, you should see:

| Metric | Expected | Notes |
|--------|----------|-------|
| Throughput | > 100 rows/sec | Depends on JSON size |
| Latency (first row) | < 10ms | For local Postgres |
| Memory stability | < 100MB | With default chunk size |
| Connection setup | < 50ms | TCP to localhost |

### Factors Affecting Performance

1. **JSON Size**: Larger objects = lower throughput
2. **Chunk Size**: Affects memory usage and latency
3. **Predicates**: SQL predicates reduce data volume
4. **Network**: TCP slower than Unix socket
5. **Postgres Load**: Other queries affect performance

---

## Debugging Failed Tests

### Connection Issues

```bash
# Verify Postgres is running
pg_isready -h localhost -p 5432

# Check database exists
psql -U postgres -l | grep fraiseql_test

# Check schema is loaded
psql -U postgres -d fraiseql_test -c "SELECT * FROM information_schema.tables WHERE table_schema = 'test_staging';"
```

### Schema Issues

```bash
# Reload schema
psql -U postgres -d fraiseql_test -f tests/fixtures/schema.sql

# Clear and reseed data
psql -U postgres -d fraiseql_test -c "SELECT test_staging.truncate_all();"
psql -U postgres -d fraiseql_test -f tests/fixtures/seed_data.sql
```

### Test Output

Run with `--nocapture` to see print statements:

```bash
cargo test --test load_tests -- --ignored --nocapture
```

### Verbose Output

```bash
# Show test names as they run
cargo test --test stress_tests -- --ignored --nocapture --test-threads=1
```

### Single Test

Run a specific test:

```bash
cargo test --test load_tests test_load_moderate_volume -- --ignored --nocapture
```

---

## CI/CD Testing

### GitHub Actions

The project includes automated testing in `.github/workflows/ci.yml`:

1. **Unit Tests**: Run on every push
2. **Integration Tests**: Run with Postgres service
3. **Load Tests**: Optional, can be run manually or nightly

### Local CI Simulation

To test locally before pushing:

```bash
# Run everything the CI does
cargo fmt -- --check
cargo clippy -- -D warnings
cargo test --lib
cargo test --test integration -- --ignored
```

---

## Best Practices

### When Writing Tests

1. **Use `#[ignore]` for tests requiring Postgres**
   ```rust
   #[tokio::test]
   #[ignore] // Requires Postgres running
   async fn test_database_operation() { }
   ```

2. **Provide clear test names**
   - `test_load_moderate_volume` not `test_load_1`
   - Describes what is being tested

3. **Include println! for diagnostics**
   ```rust
   println!("  Rows: {}", count);
   println!("  Time: {:?}", elapsed);
   println!("  Throughput: {:.0} rows/sec", throughput);
   ```

4. **Test both success and failure paths**
   - Happy path: correct input
   - Error path: invalid input, missing resources

5. **Clean up resources**
   - Drop streams explicitly
   - Close connections
   - Test reconnection

### When Running Tests

1. **Run unit tests frequently** (no dependencies)
2. **Run integration tests before committing** (with Postgres)
3. **Run load tests periodically** (time-consuming)
4. **Run stress tests when adding error handling** (validates robustness)

---

## Troubleshooting

### "connection refused" Error

```
Error: connection error: failed to connect to localhost:5432: connection refused
```

**Solution**:
1. Verify Postgres is running: `pg_isready`
2. Check hostname/port environment variables
3. Start Postgres: `sudo systemctl start postgresql`

### "database does not exist" Error

```
Error: connection error: database "fraiseql_test" does not exist
```

**Solution**:
1. Create database: `createdb fraiseql_test`
2. Load schema: `psql -U postgres -d fraiseql_test -f tests/fixtures/schema.sql`

### "relation does not exist" Error

```
Error: sql error: relation "test_staging.projects" does not exist
```

**Solution**:
1. Schema not loaded: `psql -U postgres -d fraiseql_test -f tests/fixtures/schema.sql`
2. Wrong schema: Verify connection string uses correct database

### Authentication Failed

```
Error: authentication failed: role "test" does not exist
```

**Solution**:
1. Check `POSTGRES_USER` environment variable
2. Verify user exists: `psql -U postgres -c "\du"`
3. Use correct credentials

### Tests Hang/Timeout

```bash
# Run with timeout and single thread
timeout 30 cargo test --test load_tests -- --ignored --nocapture --test-threads=1
```

---

## Next Steps

1. **Read the implementation plan**: `.claude/phases/phase-7-3-7-6-stabilization.md`
2. **Review acceptance criteria**: Success metrics for each phase
3. **Run baseline tests**: Establish performance baseline
4. **Monitor over time**: Track throughput and memory

---

## Related Documentation

- **Load Testing**: Throughput, memory, concurrency
- **Stress Testing**: Failure scenarios, recovery
- **Performance Tuning**: `PERFORMANCE_TUNING.md`
- **Architecture**: `.claude/CLAUDE.md`

---

**Ready to test fraiseql-wire!** ๐Ÿงช