# Story 10.22: Builder API Parity Foundation

**Status:** Complete
**Priority:** High
**Depends on:** Story 10.7 (Fluent Builder API) - Complete

---

## Context / Background

Story 10.7 introduced the `LoggerBuilder` fluent API with 14 methods. However, the Settings class exposes 60+ configuration options across `CoreSettings`, `SinkConfig`, `FilterConfig`, `RedactorConfig`, and `ProcessorConfig`. This creates a significant gap where users must fall back to the verbose Settings class for advanced configuration.

The fapilog vision states: "Zero configuration - `pip install fapilog` + `get_logger()` = production-ready" and "Best-in-class DX - trivial to use for individuals AND enterprises."

**Current state:**
- `LoggerBuilder` has 14 methods covering ~25% of settings
- Users hit a wall when needing circuit breakers, backpressure, cloud sinks, etc.
- Two mental models: fluent builder for basics, nested Settings for advanced
- No automated enforcement to prevent further drift

**This story establishes the foundation for builder API completion:**
1. Formal audit of all gaps
2. Design patterns for consistency
3. Automated parity test infrastructure
4. Schema-driven approach evaluation

---

## Scope (In / Out)

### In Scope

- Complete audit of Settings vs Builder coverage gaps
- Design document for builder method patterns (naming, parameters, grouping)
- Parity test that fails CI when Settings fields lack builder methods
- Evaluation of schema-driven generation approach
- Update to 10.0 series overview with new stories

### Out of Scope

- Actual implementation of new builder methods (Stories 10.23-10.26)
- Pre-commit hooks (Story 10.27)
- Documentation updates (Story 10.28)

---

## Acceptance Criteria

### AC1: Gap Audit Complete

**Description:** A comprehensive audit document listing all Settings fields without builder methods.

**Validation:**
```markdown
# docs/architecture/builder-api-gaps.md contains:
- Table of all CoreSettings fields with builder coverage (Y/N)
- Table of all SinkConfig fields with builder coverage (Y/N)
- Table of all FilterConfig fields with builder coverage (Y/N)
- Priority ranking for implementation order
```

### AC2: Design Patterns Documented

**Description:** Consistent patterns for builder methods are documented.

**Validation:**
```python
# Design decisions documented:
# 1. Naming: with_* for settings, add_* for sinks
# 2. Parameters: use human-readable strings where applicable ("10 MB", "30s")
# 3. Grouping: flat namespace vs nested (builder.sinks.cloudwatch())
# 4. Return type: always Self for chaining
# 5. Validation: validate on build() not on method call
```

### AC3: Parity Test Infrastructure

**Description:** Automated test that detects Settings/Builder drift.

**Validation:**
```python
# tests/test_builder_parity.py
def test_all_core_settings_have_builder_coverage():
    """Ensure CoreSettings fields have builder methods."""
    core_fields = get_core_settings_fields()
    builder_coverage = get_builder_covered_fields()

    # These fields intentionally have no builder method
    excluded = {"schema_version", "benchmark_file_path"}

    missing = core_fields - builder_coverage - excluded
    assert not missing, f"CoreSettings fields without builder: {missing}"

def test_all_sink_configs_have_builder_methods():
    """Ensure each sink in SinkConfig has an add_* method."""
    sink_types = get_sink_config_types()
    builder_sinks = get_builder_sink_methods()

    missing = sink_types - builder_sinks
    assert not missing, f"Sinks without builder method: {missing}"
```

### AC4: Schema-Driven Approach Evaluated

**Description:** Decision documented on whether to generate builder methods from Settings schema.

**Validation:**
```markdown
# docs/architecture/builder-generation-decision.md contains:
- Pros/cons of generation vs manual implementation
- Recommendation with rationale
- If generation: prototype script location
- If manual: consistency checklist for implementers
```

---

## Implementation Notes

### File Changes

```
docs/architecture/builder-api-gaps.md (NEW)
docs/architecture/builder-design-patterns.md (NEW)
docs/architecture/builder-generation-decision.md (NEW)
tests/test_builder_parity.py (NEW)
docs/stories/10.0-series-overview.md (MODIFIED - add new stories)
```

### Parity Test Approach

```python
# tests/test_builder_parity.py
import inspect
from fapilog.builder import LoggerBuilder
from fapilog.core.settings import CoreSettings, Settings

def get_core_settings_fields() -> set[str]:
    """Extract all field names from CoreSettings."""
    return set(CoreSettings.model_fields.keys())

def get_builder_methods() -> set[str]:
    """Extract all public methods from LoggerBuilder."""
    return {
        name for name, _ in inspect.getmembers(LoggerBuilder, predicate=inspect.isfunction)
        if not name.startswith("_")
    }

def get_builder_covered_fields() -> set[str]:
    """Map builder methods to the Settings fields they cover."""
    # This mapping is maintained manually and verified by the test
    return {
        "log_level",  # with_level()
        "max_queue_size",  # with_queue_size()
        "batch_max_size",  # with_batch_size()
        "batch_timeout_seconds",  # with_batch_timeout()
        "default_bound_context",  # with_context()
        "enrichers",  # with_enrichers()
        "filters",  # with_filters()
        "redactors",  # with_redaction() (partial)
        "sinks",  # add_file(), add_stdout(), add_http(), add_webhook()
    }
```

---

## Tasks

### Phase 1: Audit

- [ ] Extract all fields from CoreSettings, document in gaps table
- [ ] Extract all fields from SinkConfig (each sink type), document
- [ ] Extract all fields from FilterConfig, document
- [ ] Extract all fields from RedactorConfig, document
- [ ] Extract all fields from ProcessorConfig, document
- [ ] Identify current builder method coverage for each
- [ ] Prioritize gaps by user impact (P0/P1/P2)

### Phase 2: Design Patterns

- [ ] Document naming conventions (with_* vs add_* vs configure_*)
- [ ] Document parameter style (human-readable strings, typed configs, kwargs)
- [ ] Decide on flat vs nested builder namespace
- [ ] Document validation strategy (eager vs lazy)
- [ ] Document error handling patterns

### Phase 3: Test Infrastructure

- [ ] Create tests/test_builder_parity.py
- [ ] Implement field extraction helpers
- [ ] Implement builder method mapping
- [ ] Add exclusion list for intentionally uncovered fields
- [ ] Verify test fails for current gaps (expected)
- [ ] Add test to CI workflow

### Phase 4: Generation Evaluation

- [ ] Prototype schema-driven generation script
- [ ] Evaluate generated code quality
- [ ] Document pros/cons
- [ ] Make recommendation

---

## Tests

### Unit Tests

- `tests/test_builder_parity.py`
  - test_all_core_settings_have_builder_coverage (will fail until 10.23-10.26 complete)
  - test_all_sink_configs_have_builder_methods (will fail until 10.24 complete)
  - test_builder_method_naming_conventions
  - test_builder_coverage_mapping_is_current

---

## Definition of Done

### Code Complete

- [ ] Gap audit document created with all Settings fields catalogued
- [ ] Design patterns document with naming/parameter/validation decisions
- [ ] Parity test infrastructure in place and running in CI
- [ ] Generation decision documented with clear recommendation

### Quality Assurance

- [ ] Parity test correctly identifies current gaps
- [ ] `ruff check` passes
- [ ] `mypy` passes
- [ ] No regression in existing tests

### Documentation

- [ ] Architecture docs for builder design decisions
- [ ] 10.0 series overview updated with stories 10.22-10.28

---

## Risks / Rollback

### Risks

1. **Risk:** Parity test is too strict, blocking unrelated PRs
   - **Mitigation:** Use exclusion list for intentional gaps; test initially warns, not fails

2. **Risk:** Design patterns don't account for edge cases
   - **Mitigation:** Review patterns against all 60+ settings before finalizing

### Rollback Plan

If issues occur:
1. Parity test can be marked as xfail temporarily
2. Design docs are non-blocking documentation

---

## Related Stories

- **Depends on:** Story 10.7 - Fluent Builder API (complete)
- **Enables:** Story 10.23 - Builder Core Settings Methods
- **Enables:** Story 10.24 - Builder Cloud Sink Methods
- **Enables:** Story 10.25 - Builder Filter & Processor Methods
- **Enables:** Story 10.26 - Builder Advanced Features
- **Related:** Story 10.27 - Builder API Parity Enforcement

---

## Code Review

**Date:** 2026-01-21
**Reviewer:** Claude
**Verdict:** OK to PR

### Summary

Reviewed implementation of builder API parity foundation including gap audit, design patterns, parity test infrastructure, and generation decision documentation.

### AC Verification

| Criterion | Evidence |
|-----------|----------|
| AC1: Gap Audit Complete | `docs/architecture/builder-api-gaps.md` - Tables for CoreSettings (37 fields), SinkConfig (8 types), FilterConfig (6 types), priority ranking |
| AC2: Design Patterns Documented | `docs/architecture/builder-design-patterns.md` - Naming, parameters, namespace, return type, validation strategy |
| AC3: Parity Test Infrastructure | `tests/test_builder_parity.py` - Field extraction helpers, coverage mapping, xfail parity tests |
| AC4: Schema-Driven Approach Evaluated | `docs/architecture/builder-generation-decision.md` - Pros/cons, recommends manual implementation |

### Quality Gates

- [x] ruff check passed
- [x] ruff format passed
- [x] mypy passed
- [x] Tests pass (23 passed, 3 xfailed)
- [x] No weak assertions
- [x] No dead code

---

## Change Log

| Date | Change | Author |
|------|--------|--------|
| 2026-01-21 | Implementation complete, code review passed | Claude |
| 2026-01-20 | Initial draft | Claude |
