설계: 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>
127 lines
5.5 KiB
Markdown
127 lines
5.5 KiB
Markdown
# Query and Aggregation Guide
|
|
|
|
Design §17–§19, decision D-11. Every query and every pipeline is a registered, bounded thing. Free-form
|
|
JSON queries and unbounded pipelines are explicitly unsupported (§3.4).
|
|
|
|
## 1. Registered operations
|
|
|
|
Every execution carries a `MongoOperationContext`: a `MongoOperationName`, a `DatabaseProfileName`, a
|
|
`CollectionProfileName`, a `MongoOperationType` and a `MongoOperationScope`.
|
|
|
|
`MongoOperationName` matches `[a-z][a-z0-9.-]{2,95}`. It is the join key for the budget registry, the
|
|
consistency registry, the metric tag and the log line — a free-form or interpolated name breaks all
|
|
four at once, which is why the pattern is enforced at construction.
|
|
|
|
`MongoOperationScope` uses an `UNSPECIFIED` sentinel rather than `null`, so "the caller did not say"
|
|
is a value the policy layer can reject rather than an NPE further down.
|
|
|
|
## 2. Query guardrails
|
|
|
|
`PolicyAwareMongoQueryBuilder` builds a query from `MongoFieldDescriptor` + `MongoOperator` pairs
|
|
against a `MongoQueryPolicy`. The policy refuses:
|
|
|
|
- a field not in the collection's allowlist
|
|
- an operator not allowed for that field
|
|
- a sort on an unindexed field
|
|
- `$where`, `$expr` with arbitrary JavaScript, and server-side evaluation generally
|
|
- an unbounded `$regex`
|
|
|
|
`MongoRegexPolicy` requires an anchored prefix pattern and bounds the pattern length. An unanchored
|
|
regex is a collection scan wearing an index's clothes, and a user-supplied one is a denial-of-service
|
|
primitive.
|
|
|
|
`MongoSortDescriptor` pairs a field with a direction and is validated against the index manifest, so
|
|
a sort that would spill to disk fails review rather than production.
|
|
|
|
## 3. Operation budgets
|
|
|
|
`MongoOperationBudget` bounds four things at once:
|
|
|
|
| Bound | Why |
|
|
|---|---|
|
|
| `maxTimeMS` | The server stops working on a query nobody is waiting for. |
|
|
| result limit | An unbounded result set is an OOM with extra steps. |
|
|
| batch size | Bounds the per-round-trip memory. |
|
|
| examined-document ceiling | Catches an index regression that a time limit alone would hide on a fast day. |
|
|
|
|
`MongoBudgetPolicyRegistry` binds a budget to an operation name; `MongoBudgetEnforcer` applies it and
|
|
raises `MongoOperationRejectedException` before execution when a request exceeds it, and
|
|
`MongoTimeoutException` when the server enforces it.
|
|
|
|
## 4. Keyset pagination
|
|
|
|
Unbounded `skip` is unsupported: `skip(1_000_000)` makes the server walk a million documents to throw
|
|
them away, so page 1000 costs a thousand times page 1.
|
|
|
|
`MongoKeysetQueryBuilder` builds the resume predicate lexicographically. For a sort on `(a DESC, _id
|
|
DESC)` resuming after `(A, I)`:
|
|
|
|
```
|
|
(a < A) OR (a = A AND _id < I)
|
|
```
|
|
|
|
`validate()` rejects a `MongoKeysetSort` without a unique tie-breaker. Without one, two documents with
|
|
the same sort value straddle the page boundary and one of them is skipped or repeated — invisibly,
|
|
and only under concurrency.
|
|
|
|
`MongoNullSortOrdering` makes null placement explicit, because MongoDB's own ordering of missing
|
|
versus null versus present is not what most people assume.
|
|
|
|
### Cursors are authenticated
|
|
|
|
`MongoKeysetCursorCodec` signs the cursor with HMAC-SHA256 and compares with
|
|
`MessageDigest.isEqual` (constant time). An unsigned cursor is a client-controlled query predicate: a
|
|
caller can edit it to read a range they were never offered. A tampered or truncated cursor yields
|
|
`MongoCursorException`, never a partially-decoded resume position.
|
|
|
|
## 5. Aggregation guardrails
|
|
|
|
`MongoAggregationPlan` is a registered pipeline: an ordered list of `MongoAggregationStageDescriptor`
|
|
validated against a `MongoAggregationProfile`. `PolicyAwareMongoAggregationExecutor` runs only a
|
|
registered plan.
|
|
|
|
`MongoAggregationRisk` grades each stage, and the profile sets the ceiling:
|
|
|
|
| Risk | Stages | Policy |
|
|
|---|---|---|
|
|
| low | `$match` on an indexed prefix, `$limit`, `$project` | Always allowed. |
|
|
| moderate | `$group`, `$sort` with an index, `$unwind` with a bound | Allowed within budget. |
|
|
| high | `$lookup`, `$graphLookup`, `$facet`, unindexed `$sort` | Requires explicit approval in the profile. |
|
|
| forbidden | `$out`, `$merge` outside the admin plane, `$function`, `$accumulator` | Refused. |
|
|
|
|
`allowDiskUse` is a declared property of the plan, not a runtime flag. A pipeline that needs disk is a
|
|
pipeline whose shape should be reviewed.
|
|
|
|
## 6. Geospatial
|
|
|
|
`MongoGeoQuery` + `MongoGeoPoint` + `MongoGeoDistance` over a `2dsphere` index. Distances are metres
|
|
on a sphere (`nearSphere` with `maxDistance`), never degrees — a degree of longitude is a different
|
|
distance in Oslo than in Nairobi, and a radius expressed in degrees is a bug that only shows up away
|
|
from the equator. `SpringMongoGeospatialOperations` is the Spring Data binding;
|
|
`MongoGeospatialOperations` is the port.
|
|
|
|
## 7. Native capability gateway
|
|
|
|
When a registered operation genuinely needs something outside the Stable API, it goes through
|
|
`MongoNativeCapabilityGateway` (`PolicyAwareMongoNativeGateway`), never through the driver directly.
|
|
The admission order is fixed:
|
|
|
|
```
|
|
capability registered
|
|
→ database profile
|
|
→ collection allowlist
|
|
→ operation name present
|
|
→ timeout / maxTimeMS
|
|
→ consistency profile
|
|
→ result / batch limit
|
|
→ trace
|
|
→ log redaction
|
|
→ command category (MongoNativeCommandCategory)
|
|
→ D4 admin command refused
|
|
→ execute
|
|
```
|
|
|
|
`ApprovedMongoNativeOperation` is the registration record; `MongoNativeOperationPolicy` is the policy.
|
|
An admin-plane command reaching this gateway is refused regardless of capability — the admin plane has
|
|
its own credential and its own client (see [security-observability.md](security-observability.md)).
|