Repository navigation
v0.1.0-rc.2 🚀
Pre-releaseUnified Exception Envelope, End-to-End Soft-Delete Lifecycle, Lightweight LOOKUP Projections, Inverted Search Operators, Re-entrant Unit of Work & Polymorphic Identifiers
Welcome to v0.1.0-rc.2 (Release Candidate 2) of the ZCore Framework! 🚀
As we approach the final validation phase before tagging our official v1.0.0 Stable GA, v0.1.0-rc.2 focuses on framework-wide standardization, operational robustness, and developer ergonomic refinements.
This release introduces an automated, normalized exception handling system conforming all HTTP errors to the ResponseWrapper envelope; implements an end-to-end soft-delete, restoration, and forced hard-delete lifecycle; scaffolds a high-performance, schema-projected /lookup endpoint; expands the dynamic AST search engine with negated operators and logical NOT grouping; establishes re-entrant, depth-aware Unit of Work coordination; generalizes user identifiers (int, str, UUID) across all subsystems; and introduces schema-level private field shielding for unauthenticated guests.
🚀 Core Features & Architectural Advancements
1. 🛡️ Unified Exception Handling & Error Normalization (ResponseWrapper)
Previously, standard FastAPI validation failures (422) and Starlette HTTP exceptions bypassed ZCore's standardized response structure. In v0.1.0-rc.2, all exceptions are normalized into a unified, consistent JSON envelope:
- Pydantic Error Sanitization (
_sanitize_error_item,_format_error_location): Converts raw Pydantic error loc tuples into clean, dot-separated field paths (e.g.,body.email,query.limit) and safely serializes context payloads. - Unified Handlers:
request_validation_exception_handler: Formats 422 errors with clean field-level error lists and a human-readable summary.http_exception_handler: Preserves original response headers while wrapping Starlette/FastAPIHTTPExceptioninstances.response_validation_exception_handler: Intercepts internal schema mismatch errors (500) and displays field diagnostics only whensettings.DEBUGis enabled.unhandled_exception_handler: Catch-all fallback for uncaught runtime crashes with debug-gated stack traces.
- Centralized Registration (
register_exception_handlers): A single callregister_exception_handlers(app)binds all handlers to FastAPI with granular feature toggles. - Lazy Module Packaging: Handlers are exported at the root package level via dynamic
__getattr__resolution to avoid circular import issues.
2. 🗑️ End-to-End Soft-Delete Lifecycle & Restoration (restore, force)
Soft deletion is now fully integrated through the Repository, Service, and Web layers:
- Atomic Batch Soft-Delete:
delete_multi()executes atomicUPDATE ... SET deleted_at=now()with SQL dialect-awareRETURNINGsupport and pre-fetch fallbacks. - Single & Batch Restoration: Added
restore(target)andrestore_multi(ids)toWriteRepositoryMixinandWriteServiceMixinto recover soft-deleted records (deleted_at=None). - Forced Physical Hard Deletes: Added
force: bool = Falseacross repository, service execution orchestrators, and lifecycle hooks (pre_delete,post_delete,pre_delete_multi,post_delete_multi). - Web Router Query Flag: Auto-scaffolded DELETE endpoints accept
?force=true(e.g.,DELETE /tasks/{id}?force=true) to permanently purge records when requested.
3. 🔍 Lightweight LOOKUP Endpoint & Schema-Driven Projections (POST /lookup)
For autocomplete selectors, dropdown lists, and relational references where fetching full database entities is wasteful:
- Automatic Schema Projection (
_resolve_lookup_projections): Introspectslookup_schemaagainst SQLAlchemy model metadata to selectively generateload_only(*columns)statements, always including primary keys. - Automatic Eager-Loader Configuration: Detects relationships declared in
lookup_schemaand attaches optimal loader strategies (selectinloadfor collections,joinedloadfor scalar relations). - Strict Whitelist Protection (
allowed_lookup_fields): Client queries attempting to filter or sort on unauthorized fields are immediately rejected with a 400ValidationError. - RBAC Integration: Mapped to
Actions.LOOKUP(model.actions().LOOKUP) for granular permission checks.
4. ⚡ Search Engine Negation & Logical NOT Grouping (SearchEngine)
The dynamic JSON search engine now supports inverted filter operations:
- Inverted Operators: Added
not_like,not_ilike,not_contains,not_startswith,not_endswith,not_in,not_between, andis_not_null. - SQL Expression Wrapping:
_compare_columndetectsnot_prefixes and wraps clauses in SQLAlchemy'snot_()expression. - Logical
NOTBlocks: Evaluates nested filter groups underop="not"asnot_(and_(*sub_exprs))or single-field inversions. - Null Semantics:
is_nullandis_not_nullnow accept boolean flags (True/False) orNonevalues consistently.
5. 🔗 Re-entrant Unit of Work & Deferred Domain Events (UnitOfWork)
To coordinate multi-service business transactions across complex modular monolith architectures:
- Depth-Aware Re-entrancy (
uow_depth): Tracks execution nesting depth insession.info['uow_depth']. NestedUnitOfWorkblocks execute safe intermediatesession.flush()calls, delegating the physicalsession.commit()solely to the outermost root boundary. - Buffered Post-Commit Events: Domain events registered via
uow.register_event()across nested scopes accumulate insession.info['uow_events']and dispatch atomically only after the root transaction commits. - Global Rollback Safeguard: Any unhandled exception resets depth to
0, clears pending events, and executes an immediate session rollback.
6. 🆔 Polymorphic User Identifiers (int, str, UUID)
Removed strict uuid.UUID type enforcement from core identity layers:
- Polymorphic
ZContext&UserProtocol:ZContext.user_idandUserProtocol.idnow acceptAny | None(supporting integer IDs, UUIDs, Auth0/Firebase string IDs, or custom tenant keys). - Real-time Streaming (
StreamManager): Subscriber mapping queues (users_queues) now accept arbitrary user ID types with mixed-type string comparison routing. - Cursor Pagination PK Inspection: Keyset cursor pagination dynamically inspects column types (
mapper.primary_key[0].type.python_type), coercing cursor payload keys tointorUUIDautomatically.
7. 🔒 Optional Authentication & Schema-Level Private Fields (Zchema.__private__)
Enables clean guest-friendly routes and sensitive field filtering:
- Optional Authentication (
BaseAuth(auto_error=False)): Allows endpoints to accept optional authentication without raising401 Unauthorizedon missing or invalid tokens. - Dependency Anchor (
get_optional_user_stub): Exported acrosszcoreandzcore.securityfor optional route parameters. - Private Field Pruning (
__private__): Schemas can declare sensitive fields via__private__: ClassVar[set[str]] = {"cost_price", "notes"}. ZCore automatically prunes these fields from response payloads, input validations, and generated JSON schemas (?schema=true) when no authenticated user is present.
8. ⚙️ Tunable Framework Settings & Request Boundary Clamping
Replaced magic numbers across subsystems with environment-driven settings in Settings:
- Subsystem Tuning: Added
PAGINATION_DEFAULT_SIZE(20),PAGINATION_MAX_SIZE(100),SEARCH_MAX_DEPTH(3),CACHE_LOCAL_MAXSIZE(1000),CACHE_DEFAULT_TTL(3600),CACHE_EVICTION_INTERVAL(60),STREAM_QUEUE_MAXSIZE(100), andAUTH_CACHE_TTL(300). - Dynamic Parameter Validation: Added Pydantic
@model_validatoracrossPageNumberParams,CursorParams, andSearchRequestto clamp requested page sizes within configured minimum and maximum boundaries.
9. 🧪 Advanced Testing Harness & Sandboxing Engine (zcore.testing)
Comprehensive upgrades to make automated testing deterministic and isolated:
- Database Table Lifecycle (
setup_test_database): Drop and recreate test database tables across sync fixtures or running event loops viaThreadPoolExecutorsafely. - Event Sandboxing (
EventDispatcherSandbox): Snapshots and restores registered event subscribers across test runs, eliminating listener pollution. - Multi-Dependency Overrides:
DatabaseRollbackandZTestClientsupport custom engine injections, multiple authentication stub overrides, and strict Pydantic user model validation (user_model).
10. 🪵 Non-Intrusive Logging & Context Isolation
Refined logging signal-to-noise ratio across development and production modes:
- Status-Code-Aware Exception Logging: Application and HTTP exceptions log at
DEBUGfor client errors (< 500) andERRORfor server failures (>= 500). - Independent Slow-Query Interceptor: Slow queries exceeding
slow_query_threshold_msare logged even if generallog_sql_queriesis disabled. - Developer Console Mode: Development mode preserves native Uvicorn console formatting via
passthrough_loggers, switching cleanly toProcessorFormatterJSON rendering in production. - Background Scope Context:
background_scopeisolates Structlog contextvars, bindstask_id=scope_id, and restores parent context on exit.
11. 🖥️ Cascading CLI Server Configuration & Dynamic Scaffolding
Upgraded the zc command-line tool:
- Cascading Precedence (
zc run): Server parameters resolve with the precedence:CLI Arguments > .env File > Defaults. - Transparent Uvicorn Passthrough: Uses
parse_known_args()to forward arbitrary flags (e.g.,--root-path,--proxy-headers) directly to Uvicorn. - Multi-Worker Safety: Automatically disables
--reloadwhen--workers > 1. - Dynamic Test Filename Pattern:
zc startapp <app_name>generates Pytest files following standard naming conventions (test_<app_name>.py).
⚠️ Breaking Changes & Migration Guide
1. Exception Handler Registration in main.py
Replace manual exception handler bindings with the unified register_exception_handlers utility.
Old:
from zcore.exceptions import AppException, app_exception_handler
app.add_exception_handler(AppException, app_exception_handler)New:
from zcore import register_exception_handlers
register_exception_handlers(app)2. Service & Repository Deletion Hook Signatures
Custom service classes overriding delete hooks must now accept the optional force: bool = False keyword argument.
Old:
class TaskService(BaseService[Task]):
async def pre_delete(self, id: Any) -> None:
...
async def post_delete(self, model: Task) -> None:
...New:
class TaskService(BaseService[Task]):
async def pre_delete(self, id: Any, force: bool = False) -> None:
...
async def post_delete(self, model: Task, force: bool = False) -> None:
...3. User Identifier Typing (user_id / UserProtocol)
If your custom code strictly expected uuid.UUID for ctx.user_id or UserProtocol.id, update type annotations to accept Any.
Old:
user_id: uuid.UUID | None = ctx.user_idNew:
user_id: Any | None = ctx.user_id # Supports int, str, and uuid.UUID4. SQL Query Logging Default
LoggingSettings.log_sql_queries now defaults to False to reduce log noise. To enable SQL query dumping in development, update your settings or .env:
LOG_SQL_QUERIES=true🛠 How to Install / Upgrade
To install or upgrade to v0.1.0-rc.2:
pip install --upgrade "fastapi-zcore-framework[all]==0.1.0rc2"📢 We Need Your Feedback!
As we prepare for the official v1.0.0 release, please test this release candidate against your real-world services. If you encounter edge cases or have architectural feedback, please open an issue on GitHub.
- 📖 Documentation Portal: https://zcore.baseryn.com
- 🛍️ Modular Monolith Showcase: ZShop Reference App