feat(policy): add immutable versioned product policy store
This commit is contained in:
1 parent
0e2a3b02ab
commit
7a5105acc7
30 files changed
+3893
-37
No files matched your search
+62
-10
@@ -89,6 +89,57 @@ Implemented: the outbound `MailSender` port (`backend/internal/port/outbound/mai
|
||||
|
||||
A non-nil error means the message certainly did not leave the process: `ErrMailChannelUnavailable` in `disabled` mode, `ErrInvalidOutgoingMail` for an invalid message, or the context error. Retries, backoff, and recording outcomes belong to a single planned delivery layer, not to the transport. The verification flows (TASK-053, TASK-054) must treat `ErrMailChannelUnavailable` as not sent: it never confirms an address or replaces an account check. `OutgoingMail` redacts itself in `fmt` and `slog` output, and transport errors and logs never contain recipients, subjects, bodies, credentials, or raw provider responses.
|
||||
|
||||
### Product policy versions
|
||||
|
||||
Implemented as storage, a publisher, and a startup seed (TASK-005): migration `backend/db/migrations/00003_create_policy_versions.sql`, queries in `backend/db/queries/policy.sql`, the typed policy in `backend/internal/domain/` (`policy.go`, `policy_document.go`, `policy_version.go`, `policy_demo.go`), the `outbound.PolicyRepository` port (`port/outbound/policy.go`), the sqlc-backed adapter in `backend/internal/adapter/secondary/postgres/policy.go`, and the publisher in `backend/internal/usecase/policy/`. No product rule reads the policy yet; invitations, quotas, assessment, sessions, and the search status will read it as their tasks are implemented.
|
||||
|
||||
`policy_versions` columns:
|
||||
|
||||
- `id`: uuid primary key, a UUIDv7 generated in Go (`domain.PolicyVersionID`).
|
||||
- `policy_key`: the policy family. Each family has one document layout and one decoder; `product`, decoded as `domain.ProductPolicy`, is the only family, and both the domain and the `policy_versions_policy_key_known` CHECK reject any other. `version`: an integer above zero, unique within the family (`policy_versions_policy_key_version_key`); the newest publication has the highest number.
|
||||
- `kind`: `demo` or `calibrated`, the calibration state of the whole version. Consumers read this flag. The `policy_versions_calibrated_kind_matches_document` CHECK and the domain refuse a `calibrated` version whose document marks the assessment section as uncalibrated.
|
||||
- `created_at`: the publication time from the database clock. The BEFORE INSERT trigger `policy_versions_stamp_creation` sets it to `clock_timestamp()` on every insert and ignores a value from the caller.
|
||||
- `effective_at`: when the version can start to apply. A NULL in the insert means "at publication", and the same trigger sets it to `created_at`; a scheduled time must not be earlier (`policy_versions_effective_after_creation`, mapped to `outbound.ErrPolicyVersionBackdated`).
|
||||
- `author`: `system:<name>` or `operator:<handle>`, at most 128 bytes of lowercase letters, digits, `.`, `_`, and `-`. It excludes `@`, so it cannot hold an email address. It is text rather than a reference to `users`: the seed has no account, admin roles do not exist yet, and a version must outlive any account, while a cascading or nulling foreign key would conflict with immutability. An admin editor can add an account reference in an additive migration.
|
||||
- `document`: a jsonb object with the typed policy. `document_sha256`: the SHA-256 of the canonical document, 32 raw bytes.
|
||||
|
||||
The database enforces immutability. The trigger function `policy_versions_refuse_change` refuses every UPDATE and DELETE (row trigger) and TRUNCATE (statement trigger) with SQLSTATE 23000 and the constraint name `policy_versions_immutable`; the adapter maps exactly that pair to `outbound.ErrPolicyVersionImmutable`, never the message. The port has no update or delete method, so a change is always a new version. The guarantee covers application statements and manual SQL; a role that owns the table can still disable the trigger or drop the table, so a least-privilege runtime role remains future work.
|
||||
|
||||
Typed policy, `domain.ProductPolicy`: every value is a named field whose type carries the unit: `CalendarDays`, `BusinessDays` (no conversion to a duration; the consuming feature supplies the business calendar), `Hours`, and `BasisPoints` for probabilities and the standard error, an integer count of 0.0001 (0.80 is 8000). Basis points compare exactly, without floating-point drift, and keep integers in the document. The `Validate` method of each section rejects zero, missing, and out-of-range values and inconsistent combinations, such as a default deadline outside the options, a higher quota tier with a lower limit, an inactive E0, an active tier above an inactive one, or stop probabilities that do not surround the confirmation threshold. The ranges are sanity bounds against unit mistakes, not product decisions. Quota tiers E0 < E1 < E2 are looked up with `OrganizationQuotaPolicy.Tier(domain.OrganizationTier)` (for TASK-087); every organization starts at E0, and the rules that move it between tiers belong to the quota feature.
|
||||
|
||||
Open question for the attempt tasks (TASK-157 and TASK-158): `MaxAttemptsPerWindow` stores only the number. Whether the limit counts per grade, per specialty, or across all assessments of a candidate is not decided.
|
||||
|
||||
The document has `schema_version` 1 and the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`; field names carry their unit (`_days`, `_business_days`, `_hours`, `_bp`). Decoding is strict: it rejects unknown fields, missing or null fields, wrong types, fractions, values outside int32, an unknown schema version, trailing data, and documents over 64 KiB. The canonical form is the compact Go encoding in field declaration order. jsonb normalizes key order, so `domain.RestorePolicyVersion` decodes the stored document, validates it, encodes it again, and compares its SHA-256 with `document_sha256`; a mismatch returns `domain.ErrPolicyDocumentIntegrity`. A golden test pins the canonical form, because a change would make every stored version fail this check; a new layout needs a new schema version and decoder.
|
||||
|
||||
The port `outbound.PolicyRepository` is available through `UnitOfWork.Policies()` and outside a transaction through `postgres.PolicyStore`. Methods that take a family reject an unknown one before reading storage.
|
||||
|
||||
- `Create` stores a numbered `domain.PolicyVersionDraft` and returns the stored `domain.PolicyVersion` with the database times. The insert uses `ON CONFLICT DO NOTHING`, so a taken number or ID returns `ErrPolicyVersionConflict` without aborting a surrounding transaction.
|
||||
- `GetByID` reads one version.
|
||||
- `GetEffective(key, at)` returns the newest publication, the highest number, among the versions whose `effective_at` is not after `at`. A version scheduled for later therefore never undoes a version published after it: an urgent correction stays in effect when an earlier scheduled version reaches its time, and the scheduled version is superseded. The unique `(policy_key, version)` index serves this lookup.
|
||||
- `GetLatest(key)` returns the highest number, effective or not.
|
||||
- `HasVersions(key)` reports presence without reading a document.
|
||||
- Misses return `ErrPolicyVersionNotFound`.
|
||||
|
||||
`policy.Publisher` validates the whole input before it reads storage. It takes the application clock only to refuse a scheduled effective time that has already passed; the publication time comes from the database. `Publish` assigns the highest stored number plus one; when a concurrent publication takes the number, it reads again and retries up to 10 times, then returns `policy.ErrPublishContended`. It works on a standalone repository or inside a unit of work.
|
||||
|
||||
Demo and calibrated policy: `domain.DemoProductPolicyV1()` is the accepted initial policy for verifying the product flow. It is published as version 1 of `product` with kind `demo` and author `system:demo-seed`, and its assessment section is marked `uncalibrated_initial`. These values make no calibrated quality claim. The policy holds rules only; assessment content (the task bank, blueprints, and variants) is a separate task. Demo version 1:
|
||||
|
||||
| Section | Values |
|
||||
| --- | --- |
|
||||
| `invitations` | response deadline options 3, 7, and 14 days, default 7; at most 20 pending invitations per need; repeat after a decline in 30 days; interview proposal within 5 business days; 30-day pause after no deal |
|
||||
| `organization_quotas` | rolling windows of 7 days for invitations and 24 hours for distinct card views; E0 10 invitations and 50 views, E1 40 and 150, E2 100 and 400; E2 is inactive until the organization verification that grants it exists |
|
||||
| `assessment`, uncalibrated initial | same-grade retry after 30 days; at most 3 attempts per 180 days; at most one promotion per 90 days; confirmation at P_G >= 0.80, high strength from 0.90; after at least 8 scored items stop at P_G >= 0.90 or <= 0.10 or SE <= 0.25; at most 23 scored items plus 2 seed items; practice is mandatory |
|
||||
| `identity` | verification token 24 hours; unverified account deleted 7 days after the latest registration; session idle timeout 24 hours, absolute lifetime 7 days |
|
||||
| `search_status` | the "searching" status is confirmed every 30 days |
|
||||
|
||||
The identity lifetimes in this table are the values of the identity contract ([api/README.en.md](../../api/README.en.md#identity-sessions-cookie-and-csrf)). They come from the versioned product policy, not from configuration: the registration, verification, and session usecases will read them from the effective policy version. The grade rules in [Assessment and grade verification](#assessment-and-grade-verification) use the same assessment values.
|
||||
|
||||
Seeding: at startup, after migrations and under the same condition (`DATABASE_MIGRATE_ON_START` is true and `DATABASE_URL` is set), bootstrap calls `Publisher.EnsureDemoProductPolicy`. It checks only whether `product` has any version and never decodes one, so a stored version of a newer or unknown layout cannot block startup. When the family is empty, it publishes demo version 1 effective at publication; otherwise it changes nothing and logs that the seed was skipped. Instances that start together race for version 1, and the loser skips. The log line names only the key, number, kind, and ID. A database error stops startup. The seed is not a data insert in a migration, so the schema and the policy values change independently.
|
||||
|
||||
Referencing a version (planned): tables that record a decision built under a policy, such as grade decisions, selection snapshots, and invitations, carry `policy_version_id uuid NOT NULL REFERENCES policy_versions (id)` and store the version used when the decision was made. An existing decision reads that version with `GetByID` and is never recomputed through `GetEffective`, whose answer for a given time changes when a scheduled version is superseded. A referenced version cannot be deleted, by the foreign key and by the trigger, and a new version never rewrites past decisions.
|
||||
|
||||
Test fixtures use their own values. Since `product` is the only family, the integration tests give every case its own database, and no fixture stands in for the demo policy.
|
||||
|
||||
## Repository map and package purpose
|
||||
|
||||
```text
|
||||
@@ -119,11 +170,12 @@ backend/
|
||||
cmd/app/main.go calls bootstrap.Run and reports errors
|
||||
config/ shared runtime configuration
|
||||
internal/
|
||||
domain/ flat package; DomainEvent, identity types
|
||||
domain/ flat package; DomainEvent, identity types, product policy
|
||||
usecase/health/ operational readiness usecase
|
||||
port/inbound/ readiness input boundary
|
||||
usecase/identity/ password validation before hashing (Credentials)
|
||||
port/outbound/ readiness, cache, object storage, transaction, outbox, identity, password hashing, and mail boundaries
|
||||
usecase/policy/ publication of policy versions and the demo policy seed
|
||||
port/outbound/ readiness, cache, object storage, transaction, outbox, identity, policy, password hashing, and mail boundaries
|
||||
adapter/primary/http/
|
||||
api/ generated ogen handler
|
||||
middleware/ request metrics
|
||||
@@ -134,22 +186,22 @@ backend/
|
||||
argon2id/ Argon2id password hasher with a memory budget
|
||||
mail/disabled/ mail transport that sends nothing and reports the channel unavailable
|
||||
ml/api/ generated client from backend/codegen/ogen-ml.yml
|
||||
postgres/ pool, migrator, transactor, outbox writer, identity repositories, health check
|
||||
postgres/ pool, migrator, transactor, outbox writer, identity and policy repositories, health check
|
||||
postgres/sqlc/ generated SQL adapter
|
||||
redis/ cache adapter and Redis check
|
||||
seaweedfs/ S3 adapter and bucket check
|
||||
prometheus/ bounded Go/process and request metrics
|
||||
bootstrap/ configuration, wiring, lifecycle, shutdown
|
||||
db/ embedded migrations and SQL queries; outbox and identity tables
|
||||
db/ embedded migrations and SQL queries; outbox, identity, and policy tables
|
||||
codegen/ ogen and sqlc configs
|
||||
pkg/ reserved for justified shared technical helpers
|
||||
```
|
||||
|
||||
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`.
|
||||
Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.go`, and other files as their models are defined. Do not nest directories by entity or feature. The first type is `DomainEvent` in `domain_event.go`, the validated event that a transaction writes to the outbox. Identity storage types live in `email_address.go`, `secret_token.go`, `user.go`, `email_token.go`, and `session.go`; the normalized password is in `password.go`. The product policy and its versions live in `policy.go`, `policy_document.go`, `policy_version.go`, and `policy_demo.go`.
|
||||
|
||||
Product domain types and usecase modules, the Resend, SMTP, and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
|
||||
|
||||
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, and the `MailSender` port with the `disabled` transport. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
|
||||
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, and the `MailSender` port with the `disabled` transport. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
|
||||
|
||||
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `emailtemplate`, `mailer`, and test helpers. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
|
||||
|
||||
@@ -196,11 +248,11 @@ Grade state rules:
|
||||
- Before the first passing assessment, status is unverified and a claimed grade does not grant verified category access.
|
||||
- A failed attempt never lowers an existing verified grade.
|
||||
- After an initial failure, the candidate may choose a lower-level test; the system does not assign it automatically.
|
||||
- Changes after a successful qualification are rate limited; 90 days is the initial proposal.
|
||||
- The first lower-level test after failure is outside that interval. Repeating the same level may use a separate cooldown, initially proposed at 24 hours.
|
||||
- A promotion after a successful qualification is allowed at most once per 90 days.
|
||||
- The first lower-level test after failure is outside that interval. A retry of the same grade waits 30 days, and a candidate takes at most 3 attempts in any 180 days.
|
||||
- A strong result may suggest a higher-level test. Keep the grade history available.
|
||||
|
||||
Thresholds and intervals are pilot proposals, not a validated psychometric model. Task rotation and attempt limits reduce the value of leaked answers but do not prove resistance to hints or LLMs. Difficulty comparability needs measurement.
|
||||
These intervals are the accepted initial policy, stored as demo version 1 of the [product policy](#product-policy-versions); its thresholds are uncalibrated and are not a validated psychometric model. Task rotation and attempt limits reduce the value of leaked answers but do not prove resistance to hints or LLMs. Difficulty comparability needs measurement.
|
||||
|
||||
## Matching and explanations
|
||||
|
||||
@@ -369,7 +421,7 @@ These are proposed acceptance targets, not results: 30 concurrent users; p95 pro
|
||||
|
||||
- No contact data appears before a grant in API, search, PDF, errors, or employer-facing ML explanations. Another company never receives it after acceptance.
|
||||
- Candidates cannot read other users' invitations, documents, jobs, or attempts. Companies cannot read other companies' needs or search runs.
|
||||
- Failure never lowers grade; first lower-level retry is permitted; concurrent requests cannot bypass the proposed 90-day limit.
|
||||
- Failure never lowers grade; first lower-level retry is permitted; concurrent requests cannot bypass the 90-day promotion limit.
|
||||
- Repeated submit/accept does not create duplicate results; concurrent state transitions are consistent.
|
||||
- The manual path works when ML is off; a worker recovers an expired lease; an old response cannot overwrite a newer document version.
|
||||
- Empty FSP history differs from an integration error and does not exclude a candidate.
|
||||
|
||||
Reference in new issue
Block a user