설계: docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md
계획/진행 기록: docs/superpowers/plans/2026-09-25-capability-module-packaging.md
- Wave 0: 규칙 고정(AGENTS.md capability 완료 기준·테스트 규칙) + 차단 결함 7건
(compose overlay 검사, redis-sdk CI job, 적용된 V9/V13 원복 + V16, @EnableScheduling,
messaging bridge 순서, prod 에러 상세 validator, sample loggers read-only)
- Wave 1: 데이터·보안 Critical 10건 (durable operation 25P02, operation 유스케이스 이동,
outbox 재인코딩, Kafka TLS/SASL, 알림 트랜잭션, SNS 서명, tus checksum, GraphQL fragment,
Redis lane, gRPC FAILED_TERMINAL)
- Wave 2: 리팩터링 잔재·실험용 자리 삭제, outbox v1 fencing(V17), 멱등성 V2 정본화
- Wave 3: 라이브러리형 코드 정리(동작하지 않는 설정·인터페이스·gate 제거, web-advanced 분리)
- Wave 4: capability 11개를 "있으면 켜짐" 모듈로 포장, 끄는 장치 제거, 기본 조립 web-only,
qualificationBootJar 분리
- Wave 5: 빌드 로직 축소(17.2k -> 10.8k줄), sample 테스트 컨벤션 적용
삭제한 코드는 docs/capability-status.md "제거된 코드" 표에 복구 커밋(208077fd)과 함께 기록.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
5.2 KiB
Advanced — Multi-tenancy
Capabilities: MongoCapability.SHARED_COLLECTION_TENANCY (Advanced),
MongoCapability.DATABASE_PER_TENANT (Experimental)
Enablement: library API, no configuration property. The service's own adapter constructs the
entry point with a MongoAdvancedCapabilityGuard built from MongoAdvancedCapabilityFlags that
enables the capability; construction is refused otherwise.
Shared-collection tenancy has no entry point (its types are policies), so only
DATABASE_PER_TENANT is ever checked.
1. Shared collection
Every tenant's documents live in one collection, discriminated by a tenant field.
MongoTenantContext carries the tenant. MongoTenantPredicateInjector adds the tenant predicate to
every query, every atomic filter and the first aggregation stage. The adopter's repository calls
the injector on every tenant-scoped path; there is no tenant-scoped operations facade in this leaf.
Three details are load-bearing:
- Injection, not convention. A tenant predicate that each query is expected to add itself is a
cross-tenant leak waiting for one missed
where(...). The injector adds it structurally. - First aggregation stage.
firstStageMatch(...)places the tenant$matchbefore anything else. A$lookupor$groupthat runs before the tenant filter has already crossed the boundary, even if a later stage filters the output. - An absent tenant is not "all tenants". The injector takes an
Optional<MongoTenantContext>so the missing case is a decision the policy makes explicitly, not a predicate that quietly disappears.
MongoTenantManifestValidator.validate(manifest, tenantScopedUniqueIndexes) checks that every unique
index that should be per-tenant actually includes the tenant field. A unique index on email alone in
a shared collection makes an email globally unique across tenants — tenant B cannot register an
address tenant A already used, which is both a bug and an information leak.
requireShardKeyAnalysed(...) requires a shard-key readiness report before a shared-collection tenant
model is sharded: tenant id as a shard key prefix concentrates the largest tenant on one shard.
Observability
tenantId and rawTenantId are on MongoObservationConvention's forbidden tag list. Cardinality
grows with the customer list, and the tag ships tenant identity into the metrics backend.
2. Database per tenant (Experimental)
MongoTenantClientRegistry holds one client per tenant under a cap with idle eviction; mapping a
tenant to its database is the adopter's code.
Experimental for a specific reason: it is correct in the small and unbounded in the large. Each tenant database costs connections, file handles and monitoring cardinality. It works beautifully at 20 tenants and falls over at 2,000, and nothing in a functional test distinguishes the two. Promotion requires operational scale evidence.
MongoTenantLifecyclePolicy:
requireActivationReady(tenantKey, schemaAndIndexesValidated)— a tenant is not activated until its schema and indexes are validated. Activating first means the first customer request is the migration test.requireDeleteAllowed(...)— deletion requires an explicit retention decision. Dropping a tenant database is irreversible and takes the backup surface with it.
MongoTenantMigrationCoordinator runs a migration across tenant databases with per-tenant results.
Partial failure is normal and must be reported per tenant: "migration failed" across 500 databases is
not a report anyone can act on.
3. Choosing
| Shared collection | Database per tenant | |
|---|---|---|
| Isolation | Logical, enforced by injection | Physical |
| Tenant count | Unbounded | Bounded by connections and file handles |
| Per-tenant restore | Hard | Natural |
| Noisy neighbour | Shared resources | Isolated |
| Migration | One collection | N databases, partial failures |
| Cross-tenant query | Possible (and must be forbidden) | Structurally impossible |
Shared collection is the default. Database-per-tenant is for a small number of tenants with a contractual isolation or per-tenant-restore requirement.
4. Failure recovery
| Symptom | Cause | Action |
|---|---|---|
| Cross-tenant data visible | An operation skipped MongoTenantPredicateInjector |
Treat as a security incident. Find the path, close it, audit access. |
| Unique constraint fires across tenants | Unique index missing the tenant field | Rebuild the index with the tenant field as prefix; the validator catches this before it ships. |
| One shard holds most data | Tenant id as shard-key prefix with a dominant tenant | Refine the shard key with a high-cardinality suffix. |
| Connection exhaustion | Database-per-tenant beyond the connection budget | The scale limit. Consolidate or move to shared collections. |
| Migration partially applied across tenants | Normal | MongoTenantMigrationCoordinator reports per tenant; re-run for the failures only. |
5. Promotion evidence
Shared-collection tenancy: actual-topology evidence, a security review covering cross-tenant access, a migration path, failure cases (injection proven on query, atomic filter and first aggregation stage), this runbook. Database-per-tenant additionally requires operational scale evidence and stays Experimental until it exists.