Core Universal Patterns (U1-U6)
Relevant source files
The following files were used as context for generating this wiki page:
Core Universal Patterns (U1-U6) represent the foundational bug categories identified across multiple production projects. These patterns are considered "universal" because they appeared in 100% of the source projects analyzed (3/3 reference projects), indicating they are fundamental technical risks inherent to the technology stacks used, rather than project-specific logic errors.
These patterns serve as a baseline for code quality and security. They cover critical areas such as asynchronous concurrency, frontend state synchronization, external input validation, database edge cases, and architectural atomicity. Adhering to these patterns is mandatory for all new project implementations and migrations to prevent recurring production failures.
Sources: README.md:16-20, CORE-PATTERNS.md, MIGRATION-NOTES.md:47-49
U1: Async Race Conditions & Concurrency Control
This pattern addresses the most frequent class of bugs: race conditions in asynchronous environments. It specifically targets the "read-then-write" anti-pattern where an application checks a state and then performs a side effect without ensuring atomicity between the check and the action.
Reserve-then-Fill Architecture
To prevent duplicate side effects (e.g., sending two emails for one event), the system must utilize a "Reserve-then-fill" strategy. This involves committing a local record with a UNIQUE constraint or an atomic Compare-and-Swap (CAS) operation before performing any irreversible external action.
The diagram above illustrates the correct flow to prevent TOCTOU (Time-of-Check to Time-of-Use) errors. If the database insertion fails due to a conflict, the external call is never triggered.
Sources: claude-md-snippets/universal.md:3-5, MIGRATION-NOTES.md:43-49, INTEGRATION.md:120-125
U2: React State Synchronization from Props
This pattern identifies failures in keeping local React component state synchronized with incoming props, particularly when props are updated via backend refetches.
Synchronization Strategies
When a component initializes its state using a prop (e.g., useState(props.value)), that local state becomes "stale" if the parent provides a new prop value.
| Strategy | Implementation | Use Case |
|---|---|---|
| Key Prop | <Child key={id} /> | Forces complete remount when ID changes. |
| Explicit Effect | useEffect(() => setState(prop), [prop]) | Manual resync of specific state slices. |
| Derived State | No local useState; use prop directly. | Best for simple read-only or pass-through values. |
Sources: claude-md-snippets/universal.md:7-10, MIGRATION-NOTES.md:54-61, MIGRATION-NOTES.md:36-40
U3: Validation of External Input Boundaries
Validation must occur at the boundary where external data (API responses, Webhooks, LLM outputs) enters the system. Relying on type hints or implicit structures leads to runtime crashes when payloads diverge from expectations.
Validation Checklist
- Type Guards: Use
isinstance()before performing operations like.get(),.append(), or.strip(). - Numeric Safety: Check numbers with
isfinite()and range constraints. - Regex Hygiene: Use raw strings and word boundaries (
\b) to prevent catastrophic backtracking or incorrect matches on external text. - Grammar-based Validation: For complex strings (like CSP or headers), use
fullmatchagainst an allowlist grammar rather than stripping a blocklist.
Sources: claude-md-snippets/universal.md:12-18, MIGRATION-NOTES.md:65-72
U4: SQL & Postgres Edge Cases
Database interactions often fail due to subtle differences between application logic and SQL engine behavior, particularly regarding NULL handling and data types.
Key Database Patterns
- NULL Comparison: In SQL,
col = NULLevaluates toNULL(falsy in most contexts), notTRUE. Logic must useIS NULLorIS NOT NULL. - Tiebreakers in Pagination: Every
ORDER BYclause combined withLIMITorOFFSETmust include a unique tiebreaker (e.g.,ORDER BY created_at, id) to ensure deterministic results. - Data Types: External IDs (like Telegram IDs) must use
BigIntegerto avoid overflow.VARCHARlengths must be validated against the longest possible enum values during CI.
Sources: claude-md-snippets/universal.md:20-23, MIGRATION-NOTES.md:31-34
U5: Linked-Field Atomicity & State Machine Integrity
This pattern focuses on preventing "partial updates" where one field of an entity is updated (e.g., status) but related metadata (e.g., last_activity_at, audit_log) is not, leading to a drift in the system's state.
The diagram shows that a state transition is not a single field update, but a bundle of related changes that must succeed or fail together.
Sources: claude-md-snippets/universal.md:25-28, MIGRATION-NOTES.md:9-14
U6: Migration Drift & Schema Consistency
Migration drift occurs when the database schema (managed via tools like Alembic) diverges from the application's ORM models.
Integrity Requirements
- Reflective Models: Every index,
CheckConstraint, orUniqueConstraintdefined in a migration file must have a corresponding entry in the ORM's__table_args__. - Safe Deletion:
DROP COLUMNoperations must be performed in a separate migration only after the code has been updated to stop referencing the field. - Constraint Naming: Alembic revision IDs and constraint names should be kept under 30 characters for compatibility across different SQL flavors.
Sources: claude-md-snippets/universal.md:30-33, MIGRATION-NOTES.md:31-34
Summary
The Core Universal Patterns (U1-U6) provide a defensive programming framework tailored to the specific failures encountered in this project's history. By implementing atomicity (U1, U5), rigorous boundary validation (U3), and synchronization protocols (U2, U4, U6), developers can mitigate the most common and severe bugs identified across the project portfolio. These patterns should be treated as high-priority checkpoints during every code review.