Documentation Index
Fetch the complete documentation index at: https://www.aidonow.com/llms.txt
Use this file to discover all available pages before exploring further.
Executive Summary
Procedural macro code generation offers a high-leverage response to the structural uniformity problem inherent in event-sourced domain repositories. In a SaaS platform with 20 domain entities, manual repository implementations totaled 13,600 lines; after macro refactoring, the equivalent functionality required 2,400 lines of domain-specific code plus 2,917 lines of reusable macro infrastructure—a 61% total reduction and an 80% reduction in per-entity boilerplate. Time-to-add-new-entity decreased from 4–6 hours to approximately 30 minutes. AI pattern analysis accurately identified the five macro abstractions from examination of existing implementations; human judgment was required for API boundary design and compile-time validation specification. A GSI query defect in the initial implementation was identified and resolved before production deployment through compile-time attribute validation. This analysis documents the design decisions, implementation outcomes, and actionable principles derived from this work.Key Findings
- Five derive macros eliminated 80% of per-entity boilerplate across 20 domain entities. The macro infrastructure investment of 2,917 lines reached break-even at the fourth entity migration and yields compounding savings for every subsequent entity.
- AI accurately extracts repeating patterns from a corpus of existing implementations. Given five representative entity implementations, the evaluator agent produced a macro design recommendation that identified the correct abstraction boundaries and required minimal revision.
- Compile-time attribute validation is the primary mechanism for preventing macro misconfiguration. The GSI defect in the initial implementation was caused by missing compile-time validation; adding attribute dependency checks eliminated the class of misconfiguration error.
- Test helpers generated in test-only compilation contexts provide measurably improved test authoring ergonomics. Macro-generated fixtures, event constructors, and assertion helpers reduce per-test setup overhead and enforce consistent test patterns across all entities.
- AI does not validate macro configurations against architectural intent without explicit specification. The initial DynamoDB macro generated query operations without specifying the GSI name because the functional specification did not enumerate GSI configuration as a required attribute; the macro API must be designed by a human who understands the architectural intent.
- The macro API design phase is the highest-leverage human contribution. Implementation of macro logic is a systematic task where AI performs well; the decisions about which invariants to enforce, which attributes to require, and what error messages to produce require architectural judgment that AI agents do not apply by default.
1. Introduction: The Scale of the Problem
By January 2025, a SaaS platform had accumulated 20 or more domain entities (Leads, Accounts, Opportunities, Products, and others). Each entity required five categories of surrounding infrastructure:- Event sourcing boilerplate: approximately 100 lines (version tracking, event replay, uncommitted event accumulation)
- DynamoDB repository: approximately 300 lines (CRUD operations, entity-domain conversion, GSI queries)
- In-memory test repository: approximately 80 lines (HashMap-backed CRUD for unit test isolation)
- Caching decorator: approximately 150 lines (Moka-backed read-through cache with write-invalidate)
- Event helper methods: approximately 50 lines (aggregate ID access, event type string, metadata)
2. Pattern Analysis
An AI evaluator agent was provided access to five representative entity implementations and directed to identify common patterns and recommend a macro abstraction strategy. The agent’s analysis:METADATA/LIST_ITEM as DynamoDB sort key discriminators) and which configuration attributes to make explicit versus inferred.
3. The Five Macros
3.1 DomainAggregate (Event Sourcing)
Before (100 lines of boilerplate):replay(events), uncommitted_events(), take_uncommitted_events(), version(), record_event(event).
Test helpers (generated only in #[cfg(test)] builds): test_fixture(), assert_uncommitted_events(count), assert_last_event_type(type).
3.2 DynamoDbRepository (Infrastructure)
Before (300 lines per repository):new(client), save(aggregate), find_by_id(id), list(tenant_id, capsule_id), delete(id), and find_by_name(name) when gsi_name_lookup is specified.
3.3 CachedRepository (Performance)
Before (150 lines per cached repository):find_by_id(), write-invalidate on save() and delete(), TTL-based expiration, and LRU eviction via Moka.
4. Defect: GSI Query Generation
5. Test Helper Generation
The DomainAggregate macro generates test helper methods exclusively in test compilation contexts (#[cfg(test)]), ensuring zero runtime overhead in production binaries:
test_fixture(), test_created() / test_updated() event constructors, assert_uncommitted_events(), assert_last_event_type(), and assert_roundtrip() for serialization verification.
6. Impact Quantification
Before macros:- DomainAggregate: 100 lines → 5 lines (95% reduction)
- DynamoDbRepository: 300 lines → 5 lines (98% reduction)
- CachedRepository: 150 lines → 3 lines (98% reduction)
- InMemoryRepository: 80 lines → 5 lines (94% reduction)
- DomainEvent helpers: 50 lines → 4 lines (92% reduction)
7. Comparative Analysis: Development Economics
| Metric | Before Macros | After Macros | Change |
|---|---|---|---|
| Lines per entity (total) | 680 | 120 | −82% |
| Time to add new entity | 4–6 hours | 30 minutes | −88% |
| Bug fix propagation time | 3.5 hours (7 entities manual) | 20 minutes (macro update) | −90% |
| Risk of propagation error | Present (manual multi-site edit) | Eliminated (single source) | Eliminated |
| Architectural consistency | Enforced by convention | Enforced by compiler | Structurally guaranteed |
| New entity test setup | 15–20 tests, manual fixture creation | 5–8 tests, macro-generated fixtures | −60% test authoring |
8. AI-Human Division of Labor
This engagement provides evidence for a specific division of labor between AI agents and human practitioners in macro development: AI performed well at:- Pattern extraction from a corpus of five existing implementations
- Implementation of 2,917 lines of macro logic from a specified API
- Generation of 387 lines of reference documentation from the implementation
- Diagnosis of compilation errors and root cause identification during migration
- Abstraction boundary design (which patterns to expose as macros, which to leave manual)
- Macro attribute API design (which configuration to require versus infer)
- Security invariant specification (tenant isolation check as a generated, unconditional constraint)
- Error message quality (actionable versus technically correct)
- Architecture decisions triggered by defects (DynamoDB versus search service for flexible query workloads)
9. Macro Infrastructure Structure
10. Recommendations
- Require five or more pattern instances before initiating macro development. Pattern extraction requires sufficient examples to distinguish structural uniformity from incidental similarity. Premature abstraction based on two or three examples produces macros that are poorly generalized and require frequent revision.
- Design the macro attribute API before engaging an implementation agent. Specify which attributes are required, which are optional, what their permitted values are, what compile-time dependencies exist between them, and what error messages should be produced when constraints are violated. This specification is the input to macro implementation; its quality determines the quality of the output.
-
Add compile-time attribute dependency validation for all configuration attributes. Every attribute that depends on another attribute for correctness (for example,
gsi_name_lookupdepending ongsi_index_name) must be enforced at compile time. Runtime failures from misconfigured macros impose debugging costs that negate the productivity benefit. -
Inspect generated code with
cargo expandbefore deploying any macro to production. Verify that security invariants are present in the generated output. This step is mandatory and cannot be replaced by functional testing alone. - Establish a deprecation and backward-compatibility policy for macro APIs before the first consumer is added. Macro changes propagate simultaneously to all consumers. A breaking attribute rename is a simultaneous breaking change across the entire codebase. Treating macro APIs with the same versioning discipline as public library APIs prevents cascading rework.
11. Conclusion
Procedural macro code generation is a high-leverage technique for eliminating structurally uniform boilerplate in event-sourced domain architectures. The evidence from this analysis establishes that five macros can eliminate 80% of per-entity boilerplate across 20 or more entities, reduce time-to-new-entity from hours to minutes, and convert bug fix propagation from a multi-entity manual task into a single macro change. The technique is not without risk. Generated code can omit security invariants that were not explicitly specified. Macro API changes have amplified blast radius. AI agents will not apply security or architectural awareness to generated code without explicit specification. Each of these risks has a known mitigation: explicit invariant specification, API versioning discipline, and mandatorycargo expand inspection.
The AI-human division of labor that this work demonstrates—AI for pattern extraction and systematic implementation, humans for abstraction design and invariant specification—is likely to generalize across other code generation domains. As AI-assisted development tools mature, practitioners who develop discipline around abstraction design and invariant specification will be positioned to extract maximum leverage from AI implementation capability without incurring the associated security and architectural risks.
Resources and Further Reading
- The Rust Programming Language - Macros
- syn crate documentation
- quote crate documentation
- Related article: Saga Workflow Patterns (Week 5)
Disclaimer: This content represents my personal learning journey using AI for a personal project. It does not represent my employer’s views, technologies, or approaches.All code examples are generic patterns or pseudocode for educational purposes.