feat(assessment): add the review band of attempt signals and the disclosed collector
This commit is contained in:
1 parent
68286af8b7
commit
b3c6dc870b
124 files changed
+13522
-633
No files matched your search
+17
-2
@@ -174,7 +174,7 @@ The metric `lincodex_event_consumer_records_total{consumer,outcome}` counts fini
|
||||
|
||||
### Scheduled jobs
|
||||
|
||||
Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. No product handler is registered yet: `jobHandlers()` in `backend/internal/bootstrap/jobs.go` returns an empty list, so the backend logs `no scheduled job kind is registered` and starts no worker. The tests use a test-only kind. The first planned product kind is the invitation response deadline. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs).
|
||||
Implemented: durable jobs that run once when they fall due, such as a response deadline. The runtime is in `backend/internal/worker/jobrunner/`, the handler port `inbound.JobHandler` in `backend/internal/port/inbound/job_handler.go`, the `outbound.JobScheduler` and `outbound.JobStore` ports in `backend/internal/port/outbound/scheduled_job.go`, the validated `domain.ScheduledJob` in `backend/internal/domain/scheduled_job.go`, the PostgreSQL store and scheduler in `adapter/secondary/postgres/scheduled_job.go`, and migration `00008_create_scheduled_jobs.sql` with the `scheduled_jobs` table. One product handler is registered in `jobHandlers()` (`backend/internal/bootstrap/jobs.go`): `assessment.signal_review`, which computes the [assessment review band](#assessment-signals-and-the-review-band). The tests also use a test-only kind. The first planned deadline kind is the invitation response deadline. Settings are in [DEPLOY.md](DEPLOY.md#scheduled-jobs).
|
||||
|
||||
Scheduling. A usecase calls `unit.ScheduledJobs().Schedule(ctx, job)` in its business transaction, so the job exists exactly when the change that needs it committed, and `Cancel(ctx, kind, key)` stops a job that has not finished. A job has a kind (the handler name, a lowercase dotted name), a key that identifies the logical job within its kind (for example an aggregate ID), a due time from the application clock, an optional attempt limit, and a payload: a flat JSON object of identifiers of at most 2 KiB. Neither the key nor the payload may contain personal data; the handler reads everything else from the source tables when it runs. `(kind, key)` is unique and the first schedule wins: a repeat inserts nothing (`INSERT ... ON CONFLICT DO NOTHING`) and reports `false`, also after the job ran or was canceled. This is insert-or-ignore rather than an upsert on purpose: a repeated command cannot move a deadline that must not be reset, and a stale writer cannot revive a finished job. A new occurrence needs a new key, for example `<id>:<version>`.
|
||||
|
||||
@@ -430,7 +430,7 @@ Typed policy, `domain.ProductPolicy`: every value is a named field whose type ca
|
||||
|
||||
The MVP attempt accounting decision is candidate-wide: `MaxAttemptsPerWindow` counts root attempts across specializations in the rolling `AttemptWindow`. A corrective attempt shares its root slot, and training does not consume it. Retry and promotion timers remain independent by specialization.
|
||||
|
||||
Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, and `support`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility.
|
||||
Legacy documents use `schema_version` 1 with the sections `invitations`, `organization_quotas`, `assessment`, `identity`, and `search_status`. Schema 2 adds independently optional `assessment.attempt`, `assessment.training`, `assessment.signals`, and `support`, and requires at least one of those extensions. Encoding selects schema 1 without extensions and schema 2 otherwise. Each schema has a strict decoder: the legacy decoder rejects extension keys even when null, and an absent optional section never acquires defaults. Required fields reject missing/null values, wrong types, fractions, and values outside int32; both decoders reject unknown fields, unknown schema versions, trailing data, and documents over 64 KiB. Field names carry their unit (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). The canonical form is compact Go JSON in field declaration order. `domain.RestorePolicyVersion` decodes, validates, re-encodes, and compares SHA-256 with `document_sha256`; mismatch returns `domain.ErrPolicyDocumentIntegrity`. The schema 1 golden bytes and hash stay unchanged. Deploy readers supporting schema 2 before publishing it; a previous binary cannot read schema 2, so publishing it prevents rollback to that binary. Stored policy documents are never rewritten for compatibility.
|
||||
|
||||
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.
|
||||
|
||||
@@ -608,6 +608,21 @@ Implemented as storage and a loader, not as a candidate-facing feature: migratio
|
||||
- Demo bundle. `backend/testdata/assessment/backend_demo_bundle.json` holds four original practice problems for the category `backend`. They are an AI-generated draft (author `ai:claude-draft`) with a pending review and no reviewer, so the loader imports them as drafts, publication is refused, and the category stays closed. No human has reviewed the statements, solutions, rubrics, or difficulty; the bundle makes no validity or calibration claim. A real review produces a new version of the families that carries the approval.
|
||||
- Not implemented: authorship and review of a real task bank, blueprints per specialty and grade, selection of tasks for an attempt, the storage of attempts and answers, grading, an HTTP or admin interface, authenticated reviewer and operator identities, and a wiring of the loader in bootstrap.
|
||||
|
||||
### Assessment signals and the review band
|
||||
|
||||
Implemented as server-side signals of a real attempt (root or corrective), a review band computed by a scheduled job under the policy version pinned to the attempt, and an operator-only reader. The band is a hint for a manual check by a person. It does not change the result, the category, or a quota; no candidate or employer operation carries it, and the public contract has no field for it (a test walks every operation, request, response, and header to check this). Until staff roles exist, the only reader is the local command `assessment-review`, which records each read ([DEPLOY.md](DEPLOY.md#assessment-review-band)). Browser signals are described separately by the signal receipt contract; this section covers what the server observes itself.
|
||||
|
||||
Code: migration `backend/db/migrations/00033_create_assessment_signal_review.sql`, queries `backend/db/queries/assessment_signal_review.sql`, the policy section and band rules in `backend/internal/domain/` (`assessment_signal_policy.go`, `assessment_signal_review.go`), the observer, the review job, and `ReviewOperator` in `backend/internal/usecase/assessment/signal_review.go`, the repository in `backend/internal/adapter/secondary/postgres/assessment_signal_review.go`, and the command in `backend/cmd/assessment-review/`.
|
||||
|
||||
- Facts. `assessment_answer_observations` has one row per accepted answer: the family, the seed, the answer format, the server time from the last activity of the attempt (the previous answer or the start of the current work session) to the accepted answer, whether that time starts at the previous answer, and a keyed answer fingerprint. `assessment_attempt_origin_marks` has a row when the login session or the client network of an accepted answer or signal batch differs from the last row (digests of both), so the list stays short however many requests arrive. The browser events of the signal receipt contract only add totals (focus loss time, clipboard events, fullscreen exits). Rows are append-only, removed only by the cascade from the attempt or the account, and written in the same transaction as the answer or the batch, which already holds the attempt row lock. Two maintained counters, `assessment_answer_fingerprint_holders` (answers per family version, key generation, and fingerprint) and `assessment_answer_family_totals` (answers per family version and key generation), are increased by a trigger in the transaction of each observation insert; they only grow, so an answer removed with an account stays counted, and they are derived caches without foreign keys. A transaction touches one row of each, always in the same order.
|
||||
- No answer text, keyed digests only. The new tables store no answer text; the raw answer already exists in `assessment_attempt_items` and is untouched. Fingerprints and digests are HMAC-SHA-256 values under purpose keys derived from `IDENTITY_KEY_SECRET` with their own domain labels (`Keyring.AssessmentAnswerFingerprint`, `AssessmentSessionDigest`, `AssessmentNetworkDigest`); no new secret exists. Each stored value carries a `key_version` (now 1) and only values of one generation are compared, so a future key rotation is an explicit step. The answer fingerprint covers the family version and the canonical answer and is the same for every candidate and seed. The session and network digests also bind the attempt, so they cannot be linked between attempts. The HTTP adapter passes the session ID and the limiter key of the client address (an IPv6 address reduced to its /64) to the usecase, which hashes them; no address, session ID, token, or answer text is logged or stored. The digests live as long as the attempt (the retention period is an open question). Changing `IDENTITY_KEY_SECRET` makes old and new fingerprints incomparable.
|
||||
- Server signals. Response time: an answer faster than the per-format floor of the policy is fast, and within one format an answer more than the policy ratio below the median of the attempt is an anomalous deviation (only the fast side; a slow answer is not suspicious, and a format needs enough answers of its own). One answer counts once: an answer under its floor is fast and not also a deviation. The first item of a work session is measured from the session start, which only bounds when the item was shown, so it is excluded from both. Parallel sessions: requests that return to an earlier login session after another session was used (a single move to a new session is not counted). Networks: the number of distinct client networks beyond the first, so a move to another network and back counts once. Parallel sessions and extra networks are weak and correlated (a phone and a laptop produce both), so they form one group: alone it reaches attention at most, and review only together with a strong signal (fast, deviating, or duplicate answers) at attention or above. Client time only complements server time: it is never the source of a response time, and client signals can raise a normal band to attention but never to review.
|
||||
- Identical answers of different candidates, compared pairwise. For one attempt the comparison looks at every other attempt separately: matched answers are equal fingerprints of the same family version and key generation, given by another candidate to a different seed variant, so an expected agreement on one seed is not a signal and a candidate never matches their own attempt. A matched answer carries -log2 of the share of answers that hold that fingerprint among the answers of the family version and key generation, read from the maintained counters (so a rotation does not skew the share), between zero and the cap of its format (`duplicate_integer_cap_bits`, `duplicate_sequence_cap_bits`). A popular value, such as the correct answer of a variant, therefore carries little, and so does a population of a few attempts. The bits of one pair add up, the strongest pair decides, and `duplicate_bits_attention` and `duplicate_bits_review` are thresholds on that sum. The list of pairs is bounded and never leaves the usecase; nothing identifies the other attempt or candidate in any output, and the operator output holds counts only.
|
||||
- Why the demo thresholds are 48 and 64 bits, and what the figure means. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` samples 4000 seeds of each of the four demo families (the three integer families have 36 to 47 distinct answers, the dependency order about 2250), builds the distribution of shared values and their bits, and computes the probability that one pair of honest candidates who answer a 23-item attempt correctly reaches each threshold. Multiplied by 10,000 rivals (union bound), the per-attempt false flag rate is about 4e-5 for attention and 3e-9 for review, against test targets of 1e-3 and 1e-8. The model uses the distribution of reference answers: it does not model the distribution of wrong answers or correlated mistakes (candidates who make the same common error, or a shared tutorial), which can make honest coincidences more likely than computed. These are demo values pending calibration on a real bank, with four AI-drafted families. In the other direction, `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` calculates how many answers per family a copied pair needs before the demo thresholds flag it, when the pair copies every answer and nobody else holds those values: for an attempt of 13 items, attention from 26 answers per family and review from 61; for 23 items, from 9 and from 14. A stand with fewer attempts flags nothing by design. To try the feature on a small stand, publish a policy version with lower thresholds in `assessment.signals` (the integration tests do this with 4 and 6 bits); the demo policy is not changed for that.
|
||||
- Policy. The optional section `assessment.signals` of a schema 2 policy document holds every threshold (`domain.AssessmentSignalPolicy`); a version without it computes no band. `DemoProductPolicyV3` is `DemoProductPolicyV2` plus `DemoAssessmentSignalPolicy`; `DemoProductPolicyV1` and `DemoProductPolicyV2` and the startup seed are unchanged, and a stored version is never rewritten. The band uses the thresholds of the product policy version in `assessment_attempts.product_policy_version_id`, so a policy published later does not change an attempt in progress or a stored review; `assessment_attempt_reviews.policy_version_id` records the version, and a trigger refuses to change it. A matched attempt is re-evaluated under its own pinned version; pairs are selected with the attention level of the evaluating attempt, so across versions with different levels a pair can be missed on the side with the lower level.
|
||||
- When and how. The review never runs in a candidate's transaction. The first accepted answer schedules the job `assessment.signal_review` with the key `<attempt>:deadline`, due one minute after the deadline of the attempt (so an answer committed right at the deadline is in its facts), and finalization schedules `<attempt>:ended`, due at once; both are inserts into `scheduled_jobs` in the transaction of the answer or the finalization, and repeats do nothing. The deadline job also covers an attempt that expires or is abandoned, however and whenever its state changes. A review is a point-in-time evaluation: it describes the facts committed when its job ran, and the job at the deadline runs it again for a finalized attempt, which picks up later matches. The job computes the review of its attempt and refreshes the review of every other attempt that has ended (terminal state or past its deadline) and shares answers with it at the attention level or above, at most 50 per job; a ring of more than 50 attempts that share answers is covered because each member runs its own deadline job and sees the others. An attempt that is still running is flagged by its own job when it ends and sees the other facts then. Writers are ordered by a transaction-scoped advisory lock per review: the job locks the review of every attempt it will write, in ascending attempt order, before it reads any fact, so the later of two jobs over one attempt waits and then reads what the earlier committed (no lost update, and no lock cycle). The times of a review come from the database clock inside the upsert and the update time never falls behind the stored times. Nothing else is locked: the facts are append-only and a job is scheduled after its facts are committed. A failure is retried by the runner with backoff and can never block or change a result; without the worker (`JOBS_ENABLED=false`) reviews wait with their jobs. The only review statement in a candidate's transaction is the insert of the job (and the two counter updates of the answer). The job logs one line with the number of reviews it wrote and its duration, and no answer, address, or candidate. Applicability bound: the share is read from the counters in constant time, but the comparison joins the answers of the attempt with the answers that hold the same values, so its cost grows with the number of holders of popular values, at most 23 items times the holders of each; it is fine for background jobs on populations of up to about 100,000 answers per family and needs sampling or a cap above that.
|
||||
- Limits. Browser signals can be forged or suppressed, so they are a hint only. A helper such as an LLM on another device is not visible. False positives are possible: a shared or changing network (mobile data, NAT), a reload, two tabs, copying the task text, and coinciding answers of a small answer space. The retention period of these facts, whether collecting them needs a separate consent beyond the notice, and who calibrates the thresholds are not decided.
|
||||
|
||||
## Matching and explanations
|
||||
|
||||
Before ranking, Go applies hard filters: published profile, specialty, verified grade, required skills, and other selected criteria. A strong resume or achievement cannot compensate for a missing mandatory requirement. Distinguish an unverified skill from evidence that the skill is absent.
|
||||
|
||||
+18
-1
@@ -187,7 +187,7 @@ To inspect an `invalid_record` while the topic retains it, read exactly that rec
|
||||
|
||||
### Scheduled jobs
|
||||
|
||||
The backend runs the scheduled job worker as a goroutine of the backend process next to the HTTP servers, the relay, and the consumers. It runs jobs that usecases scheduled in their transactions once they fall due; the design is in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs). Current state: no product job kind is registered, so the backend logs `no scheduled job kind is registered` at startup and runs no worker; the settings below are still validated. With a registered kind, the worker runs when `JOBS_ENABLED` is true and `DATABASE_URL` is set. Compose passes none of the settings, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup, also with the worker disabled.
|
||||
The backend runs the scheduled job worker as a goroutine of the backend process next to the HTTP servers, the relay, and the consumers. It runs jobs that usecases scheduled in their transactions once they fall due; the design is in [ARCHITECTURE.md](ARCHITECTURE.md#scheduled-jobs). Current state: one product kind is registered, `assessment.signal_review` (see [Assessment review band](#assessment-review-band)), so the worker runs when `JOBS_ENABLED` is true and `DATABASE_URL` is set; the settings below are validated in any case. Compose passes none of the settings, so the stack uses the defaults; to change one, add it to the backend `environment` in `deploy/docker/docker-compose.yml`. A directly launched backend reads them from its environment. An invalid value stops startup, also with the worker disabled.
|
||||
|
||||
| Variable | Default | Meaning |
|
||||
| --- | --- | --- |
|
||||
@@ -310,6 +310,23 @@ Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate
|
||||
- The renderer does not log. A rendering and notification data print only the kind, version, and content hash in `fmt` and `slog` output; tokens, links, and bodies are never printed.
|
||||
- Golden files in `testdata/` make every copy change visible in review. After an intended change, run `go test ./internal/usecase/notification/mailtemplate -update` from `backend/` and review the diff.
|
||||
|
||||
## Assessment review band
|
||||
|
||||
The server computes a manual-review band (`normal`, `attention`, `review`) for real assessment attempts from the server signals and the policy version pinned to the attempt (see [ARCHITECTURE.md](ARCHITECTURE.md#assessment-signals-and-the-review-band)). The band is a hint for a person who checks an attempt by hand. It changes no result, category, or quota, and no HTTP endpoint serves it. Until staff roles exist, an operator reads it with a local command:
|
||||
|
||||
```sh
|
||||
make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operator:<handle>'
|
||||
```
|
||||
|
||||
- The band is computed by the scheduled job kind `assessment.signal_review`, never in a candidate's request. The jobs are inserted into `scheduled_jobs` with the first answer (due one minute after the deadline of the attempt) and with finalization (due at once). The worker must run (`JOBS_ENABLED=true`, [Scheduled jobs](#scheduled-jobs)); with the worker off the reviews wait with their jobs and no result is affected. A failed job is retried with the worker's backoff; a dead job (see [Dead jobs](#dead-jobs)) leaves the attempt without a refreshed review and does not touch its result.
|
||||
- The command needs `DATABASE_URL` and reads nothing else from the environment or a dotenv file; the local database credential is its operator boundary. `make -C backend assessment-review-build` builds `backend/bin/assessment-review`.
|
||||
- It prints the attempt ID, the band, the reason codes, the policy version, the evaluation and update times, and the counts behind the band. It prints no answer, address, session, candidate, or contact data, and it never names another candidate of a duplicate match.
|
||||
- Every read is recorded in `assessment_review_reads` (attempt ID, actor handle, found or missing, database time) in the same transaction as the read, also when the attempt has no review. The table refuses UPDATE, DELETE, and TRUNCATE. The actor is an audit handle, not authentication: any holder of the database credential can type any handle. Rolling migration 33 back is refused while the audit holds a row; export or resolve it first.
|
||||
- A band can be missing for a real reason: the policy version of the attempt has no `assessment.signals` section, the review job has not run yet, or the attempt has neither ended nor reached its deadline.
|
||||
- A review is updated in place when a later attempt matches one of its answers; the policy version and the first evaluation time stay.
|
||||
- To use thresholds other than the demo values, publish a policy version with an `assessment.signals` section through the policy publisher. `DemoProductPolicyV3` is the demo example and is published only explicitly (the isolated browser fixture does so); the startup seed publishes version 1 only. Attempts that already started keep the version they started with. The demo duplicate thresholds assume a population: a copied pair is flagged only from about 26 answers per family (attention) and 61 (review) at 13 items, or 9 and 14 at 23 items. To try the feature on a smaller stand, publish a policy version with lower `duplicate_bits_attention` and `duplicate_bits_review` (the integration tests use 4 and 6); do not edit the demo policy. A review is a point-in-time evaluation, run again by the job at the deadline. The job logs one line per run with the number of reviews and its duration (`assessment review job finished`).
|
||||
- The rows hold counts, durations, and keyed digests (HMAC-SHA-256 under keys derived from `IDENTITY_KEY_SECRET`, each with a key version) and no answer text. Rotating the secret keeps the stored rows but makes new fingerprints incomparable with old ones. Deleting an account deletes its attempts and, by cascade, their facts and reviews; the audit rows keep only the attempt ID and the handle. The digests are kept for the lifetime of the attempt; no retention period is defined yet.
|
||||
|
||||
## Separate ML Compose project
|
||||
|
||||
ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
|
||||
|
||||
@@ -439,6 +439,26 @@ Unit tests (`make -C backend test`) check the visibility rules without a databas
|
||||
|
||||
`TestPostgresMigrations` rolls migration 00011 back with the others and checks that its two tables and five functions disappear while the policy table stays. The suite proves the storage and loader rules only: it does not validate the content of the demo bundle, task difficulty, or any grade, it does not prove the serialization of concurrent publications beyond the held-lock case, and it does not cover a candidate-facing flow, because none exists yet. Integration tests need Docker.
|
||||
|
||||
## Assessment signal and review band tests
|
||||
|
||||
`backend/internal/domain/assessment_signal_policy_test.go` and `assessment_signal_review_test.go` check without a database: the demo signal section is valid and round-trips through the schema 2 document, a signal section alone is a valid extension and never acquires defaults, schema 1 rejects the key, out-of-range and inconsistent thresholds are refused, response times follow the per-format floors and the median ratio only on the fast side within one format and leave out the first item of a session, origin marks count alternations and distinct networks in time order (a return to an earlier network is not a new one), the band follows the policy, weak signals (parallel sessions and extra networks, one correlated group) stop at attention unless a strong signal is raised, an answer counts once as fast or as a deviation, client signals only raise a band to attention, and the operator handle must be `operator:<handle>`. `backend/internal/usecase/identity/keyring_test.go` checks the new keyring methods: the answer fingerprint is deterministic, keyed, and scoped to the family version; session and network digests differ across attempts (no linking), across sessions, and across client keys, and use separate purpose keys.
|
||||
|
||||
`backend/internal/usecase/assessment/signal_review_test.go` checks the observer and the review job with fake ports: an accepted answer stores the server time, whether it is measured from the previous answer, the key version, and the keyed fingerprint only, with no answer text, address, or session ID in the stored values or in the error text; origin marks are written only when the session or network changes; the first answer schedules the deadline job (one minute after the deadline) and finalization the ended job; training attempts and requests without a session store nothing; a policy version without a signal section makes no review; the job rejects a broken payload, ignores a missing attempt, locks the reviews of a pair in ascending attempt order before it reads any fact and writes them under their own pinned policies, and refreshes only ended attempts at the attention level, bounded. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` samples 4000 seeds of each demo family, builds the distribution of shared values with their bits, and computes the probability that one honest pair reaches each demo threshold on a 23-item attempt; times 10,000 rivals it gives about 4e-5 (attention) and 3e-9 (review), against the targets 1e-3 and 1e-8. `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` calculates how many answers per family a copied pair needs for the demo thresholds to flag it (26 for attention and 61 for review at 13 items, 9 and 14 at 23 items). The FP model uses the distribution of reference answers only, not wrong answers or correlated mistakes. The targets are test constants chosen here, not a product decision, and the measurement covers four AI-drafted families.
|
||||
|
||||
`backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go` walks every path of the public contract through its references and refuses any property, schema name, or enum that would carry the band, its reasons, fingerprints, or origin digests, and checks that the signal receipt still has exactly `status`, `accepted_events`, and `received_at`. `backend/internal/adapter/primary/cli/assessmentreview/command_test.go` checks argument validation before any environment read, the printed fields, and sanitized errors. The bootstrap test checks that the review job kind is registered.
|
||||
|
||||
`TestAssessmentSignalReviewOverHTTP` in `backend/integration_test/assessment_signal_review_http_test.go` runs the real router, PostgreSQL, and the scheduled job worker:
|
||||
|
||||
- A candidate answers every item within milliseconds from two login sessions and three network addresses and sends paste events from the second session. Before the worker runs no review exists and the review jobs are pending, so nothing was computed in a candidate's transaction. Then the attempt has the band `attention` with the reasons fast answers, parallel sessions, extra networks, and client signals, and its result is `confirmed`, equal in outcome, score, limitations, and mode to the result of an equally correct attempt with band `normal`; no assessment table other than the review table has a band column.
|
||||
- A policy version with other thresholds is published while attempts are in progress and the category is opened under it. The attempts started earlier keep the first version, the attempt created later is pinned to the new version and stays `normal` for the same behavior, and its facts are still stored.
|
||||
- Two candidates with different seeds copy the same wrong answers: the first attempt has no duplicate flag until the second candidate has answered and ended, and then both have the band `review` with the reason duplicate answers. A third copying attempt is abandoned: while it runs it is not flagged, and after it ends its job at the deadline (the worker clock is moved past it) flags it. Honest attempts with correct answers are not flagged even when a low-entropy answer coincides, and an attempt with one session and one network has exactly one origin mark.
|
||||
- Candidate reads of the attempt, the result, and the availability contain no band, reasons, fingerprints, or signal names. The operator command prints the band and its audit rows are written for a found and a missing attempt; an actor without the `operator:` prefix is refused. Facts, reviews, and audit rows refuse UPDATE and DELETE, and the audit refuses TRUNCATE.
|
||||
- The logs and the text of the new tables and of `scheduled_jobs` contain no network address, answer value, session token, or CSRF token.
|
||||
|
||||
`TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag` creates 30 honest candidates with different seeds who answer each item correctly or not at random (a fixed generator) and two who copy the same answers: no honest attempt is flagged as a duplicate and both copied attempts are. The population is small, so the test uses thresholds of 32 and 44 bits instead of the demo ones. `TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt` ends four copied attempts at the same moment among eight honest ones and runs their jobs on four workers at once: no job fails or is retried and every copied attempt is flagged. `TestAssessmentSignalReviewJobWaitsForTheReviewLock` holds the review lock of an attempt in one transaction and checks that the review job waits, writes nothing, and computes the review from the committed facts once the lock is released; this is the ordering that prevents a stale evaluation from overwriting a newer review. The concurrent test was run ten times in a row (`-count=10`). `TestAssessmentSignalReviewMigrationDownRetainsAudit` checks that the rollback of migration 33 is refused while the audit holds a row (the tables and the row stay, TRUNCATE is refused) and succeeds with an empty audit.
|
||||
|
||||
The tests prove the stored facts, the policy pinning, the job-based computation, and the absence of the band from the contract and from candidate reads. They do not prove detection quality: the thresholds are uncalibrated, the false-positive measurement covers four drafted families, and no study of real candidates exists. The employer reads are covered by the contract walk, not by an HTTP call per operation.
|
||||
|
||||
## Future software validation
|
||||
|
||||
Go unit tests should exercise domain/usecase rules with explicit inputs, results, and errors. Integration tests should use a real PostgreSQL at the same major version, apply goose migrations, and exercise sqlc, constraints, transactions, rollback, and concurrent transitions. The HTTP path should use chi, middleware, usecases, and the database; replace external ML with a controlled HTTP fake and email with a test adapter.
|
||||
|
||||
+17
-2
@@ -174,7 +174,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
### Задания по сроку
|
||||
|
||||
Реализовано: устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. Продуктовый обработчик пока не зарегистрирован: `jobHandlers()` в `backend/internal/bootstrap/jobs.go` возвращает пустой список, поэтому backend пишет в журнал `no scheduled job kind is registered` и не запускает worker. Тесты используют вид задания, который есть только в тестах. Первый запланированный продуктовый вид - срок ответа на приглашение. Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку).
|
||||
Реализовано: устойчивые задания, которые выполняются один раз, когда наступает их срок, например срок ответа. Runtime находится в `backend/internal/worker/jobrunner/`, порт обработчика `inbound.JobHandler` - в `backend/internal/port/inbound/job_handler.go`, порты `outbound.JobScheduler` и `outbound.JobStore` - в `backend/internal/port/outbound/scheduled_job.go`, проверенный `domain.ScheduledJob` - в `backend/internal/domain/scheduled_job.go`, хранилище и планировщик PostgreSQL - в `adapter/secondary/postgres/scheduled_job.go`, миграция `00008_create_scheduled_jobs.sql` создает таблицу `scheduled_jobs`. В `jobHandlers()` (`backend/internal/bootstrap/jobs.go`) зарегистрирован один продуктовый обработчик: `assessment.signal_review`, который считает [полосу проверки оценки](#серверные-сигналы-оценки-и-полоса-проверки). Тесты используют и вид задания, который есть только в тестах. Первый запланированный вид по сроку - срок ответа на приглашение. Настройки описаны в [DEPLOY.md](DEPLOY.md#задания-по-сроку).
|
||||
|
||||
Планирование. Usecase вызывает `unit.ScheduledJobs().Schedule(ctx, job)` в своей бизнес-транзакции, поэтому задание существует ровно тогда, когда зафиксировано изменение, которому оно нужно; `Cancel(ctx, kind, key)` останавливает незавершенное задание. У задания есть вид (имя обработчика, строчное имя с точками), ключ логического задания внутри вида (например, ID агрегата), срок по часам приложения, необязательный лимит попыток и payload: плоский JSON-объект из идентификаторов не больше 2 КиБ. Ни ключ, ни payload не должны содержать персональные данные; остальное обработчик читает из исходных таблиц в момент выполнения. Пара `(kind, key)` уникальна, и побеждает первое планирование: повтор ничего не вставляет (`INSERT ... ON CONFLICT DO NOTHING`) и возвращает `false`, в том числе после выполнения или отмены задания. Это намеренно insert-or-ignore, а не upsert: повторная команда не может сдвинуть срок, который нельзя сбрасывать, а устаревший писатель не может оживить завершенное задание. Для нового повторения нужен новый ключ, например `<id>:<version>`.
|
||||
|
||||
@@ -430,7 +430,7 @@ Offsets и партиции. Каждый обработчик - один уча
|
||||
|
||||
Решение для учета попыток MVP: `MaxAttemptsPerWindow` считает корневые попытки кандидата по всем специализациям в скользящем окне `AttemptWindow`. Корректирующая попытка использует место своего корня, учебная его не расходует. Таймеры пересдачи и повышения остаются независимыми по специализациям.
|
||||
|
||||
Старые документы используют `schema_version` 1 с разделами `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`. Схема 2 добавляет независимые необязательные разделы `assessment.attempt`, `assessment.training` и `support` и требует хотя бы один из них. Кодирование выбирает схему 1 без расширений и схему 2 при наличии любого расширения. У каждой схемы строгий декодер: старый отклоняет ключи расширений даже с null, а отсутствующий необязательный раздел не получает значений по умолчанию. Обязательные поля отклоняют отсутствие/null, неверные типы, дроби и значения вне int32; оба декодера отклоняют неизвестные поля, неизвестную версию схемы, данные после объекта и документы больше 64 KiB. Имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). Каноническая форма - компактный Go JSON в порядке объявления полей. `domain.RestorePolicyVersion` разбирает, проверяет, повторно кодирует документ и сравнивает SHA-256 с `document_sha256`; несовпадение дает `domain.ErrPolicyDocumentIntegrity`. Эталонные байты и хеш схемы 1 не меняются. Читающие процессы с поддержкой схемы 2 нужно развернуть до ее публикации; прежний бинарный файл не читает схему 2, поэтому после публикации откат к нему невозможен. Сохраненные политики ради совместимости не переписываются.
|
||||
Старые документы используют `schema_version` 1 с разделами `invitations`, `organization_quotas`, `assessment`, `identity` и `search_status`. Схема 2 добавляет независимые необязательные разделы `assessment.attempt`, `assessment.training`, `assessment.signals` и `support` и требует хотя бы один из них. Кодирование выбирает схему 1 без расширений и схему 2 при наличии любого расширения. У каждой схемы строгий декодер: старый отклоняет ключи расширений даже с null, а отсутствующий необязательный раздел не получает значений по умолчанию. Обязательные поля отклоняют отсутствие/null, неверные типы, дроби и значения вне int32; оба декодера отклоняют неизвестные поля, неизвестную версию схемы, данные после объекта и документы больше 64 KiB. Имена полей несут единицу (`_days`, `_business_days`, `_hours`, `_seconds`, `_bp`). Каноническая форма - компактный Go JSON в порядке объявления полей. `domain.RestorePolicyVersion` разбирает, проверяет, повторно кодирует документ и сравнивает SHA-256 с `document_sha256`; несовпадение дает `domain.ErrPolicyDocumentIntegrity`. Эталонные байты и хеш схемы 1 не меняются. Читающие процессы с поддержкой схемы 2 нужно развернуть до ее публикации; прежний бинарный файл не читает схему 2, поэтому после публикации откат к нему невозможен. Сохраненные политики ради совместимости не переписываются.
|
||||
|
||||
Порт `outbound.PolicyRepository` доступен через `UnitOfWork.Policies()` и вне транзакции через `postgres.PolicyStore`. Методы, принимающие семейство, отклоняют неизвестное до обращения к хранилищу.
|
||||
|
||||
@@ -608,6 +608,21 @@ contact_grant относится к паре кандидат-компания
|
||||
- Демонстрационный пакет. `backend/testdata/assessment/backend_demo_bundle.json` содержит четыре оригинальные практические задачи категории `backend`. Это черновик, созданный ИИ (автор `ai:claude-draft`), с рецензией `pending` и без рецензента, поэтому загрузчик импортирует их черновиками, публикация отклоняется, а категория остается закрытой. Условия, решения, рубрики и сложность никто из людей не проверял; пакет не заявляет ни валидности, ни калибровки. Настоящая рецензия порождает новую версию семейств с одобрением.
|
||||
- Не реализовано: авторство и рецензирование настоящего банка, blueprint по специализации и уровню, выбор задач для попытки, хранение попыток и ответов, проверка ответов, HTTP- или административный интерфейс, аутентифицированные личности рецензентов и операторов и подключение загрузчика в bootstrap.
|
||||
|
||||
### Серверные сигналы оценки и полоса проверки
|
||||
|
||||
Реализовано как серверные сигналы реальной попытки (root или corrective), полоса проверки, которую считает задание по сроку под версией политики, закрепленной за попыткой, и чтение только оператором. Полоса - подсказка для ручной проверки человеком. Она не меняет результат, категорию или квоту; ни одна операция кандидата или работодателя ее не содержит, и в публичном контракте для нее нет поля (тест обходит каждую операцию, запрос, ответ и заголовок). Пока служебных ролей нет, единственный читатель - локальная команда `assessment-review`, которая записывает каждое чтение ([DEPLOY.md](DEPLOY.md#полоса-проверки-оценки)). Браузерные сигналы описывает контракт квитанции сигналов; этот раздел - о том, что сервер наблюдает сам.
|
||||
|
||||
Код: миграция `backend/db/migrations/00033_create_assessment_signal_review.sql`, запросы `backend/db/queries/assessment_signal_review.sql`, раздел политики и правила полосы в `backend/internal/domain/` (`assessment_signal_policy.go`, `assessment_signal_review.go`), наблюдатель, задание проверки и `ReviewOperator` в `backend/internal/usecase/assessment/signal_review.go`, репозиторий в `backend/internal/adapter/secondary/postgres/assessment_signal_review.go` и команда в `backend/cmd/assessment-review/`.
|
||||
|
||||
- Факты. В `assessment_answer_observations` одна строка на принятый ответ: семейство, seed, формат ответа, серверное время от последней активности попытки (предыдущий ответ или начало текущей рабочей сессии) до принятого ответа, считается ли оно от предыдущего ответа, и ключевой отпечаток ответа. В `assessment_attempt_origin_marks` строка появляется, когда сессия входа или сеть клиента принятого ответа или пакета сигналов отличается от последней строки (дайджесты обоих), поэтому список короткий при любом числе запросов. Браузерные события из контракта квитанции добавляют только суммы (время потери фокуса, события буфера обмена, выходы из полноэкранного режима). Строки только добавляются, удаляются лишь каскадом от попытки или аккаунта и пишутся в той же транзакции, что ответ или пакет, которая уже держит блокировку строки попытки. Два поддерживаемых счетчика, `assessment_answer_fingerprint_holders` (ответов на версию семейства, поколение ключа и отпечаток) и `assessment_answer_family_totals` (ответов на версию семейства и поколение ключа), увеличивает триггер в транзакции каждой вставки наблюдения; они только растут, поэтому ответ, удаленный вместе с аккаунтом, остается в счете, а сами они - производный кэш без внешних ключей. Транзакция трогает по одной строке каждого, всегда в одном порядке.
|
||||
- Без текста ответа, только ключевые дайджесты. Новые таблицы не хранят текст ответа; сырой ответ уже есть в `assessment_attempt_items` и не затрагивается. Отпечатки и дайджесты - HMAC-SHA-256 под ключами назначения, выведенными из `IDENTITY_KEY_SECRET` со своими метками домена (`Keyring.AssessmentAnswerFingerprint`, `AssessmentSessionDigest`, `AssessmentNetworkDigest`); нового секрета нет. Каждое сохраненное значение несет `key_version` (сейчас 1), сравниваются только значения одного поколения, поэтому будущая ротация ключа - явный шаг. Отпечаток ответа покрывает версию семейства и канонический ответ и одинаков для любого кандидата и seed. Дайджесты сессии и сети дополнительно привязаны к попытке, поэтому их нельзя связать между попытками. HTTP-адаптер передает usecase идентификатор сессии и ключ лимитера адреса клиента (IPv6 сокращается до /64), а usecase их хеширует; адрес, идентификатор сессии, токен и текст ответа не пишутся в журнал и не хранятся. Дайджесты живут столько же, сколько попытка (срок хранения - открытый вопрос). После смены `IDENTITY_KEY_SECRET` старые и новые отпечатки несравнимы.
|
||||
- Серверные сигналы. Время ответа: ответ быстрее порога формата из политики считается быстрым, а в пределах одного формата ответ, который меньше медианы попытки более чем в заданное политикой число раз, считается аномальным отклонением (только быстрая сторона: медленный ответ не подозрителен, и формату нужно достаточно собственных ответов). Один ответ считается один раз: ответ ниже порога - быстрый, а не еще и отклонение. Первый элемент рабочей сессии отсчитывается от начала сессии, что лишь ограничивает время показа элемента, поэтому он исключен из обоих счетчиков. Параллельные сессии: запросы, которые возвращаются к прежней сессии входа после использования другой (одиночный переход на новую сессию не считается). Сети: число различных сетей клиента сверх первой, так что переход в другую сеть и обратно считается один раз. Параллельные сессии и лишние сети слабые и коррелированы (телефон и ноутбук дают оба), поэтому они образуют одну группу: сама по себе она дает не выше «внимание», а «проверить» только вместе с сильным сигналом (быстрые, отклоняющиеся или одинаковые ответы) уровня «внимание» и выше. Клиентское время только дополняет серверное: оно никогда не источник времени ответа, а клиентские сигналы могут поднять нормальную полосу до «внимание», но не до «проверить».
|
||||
- Одинаковые ответы разных кандидатов, сравнение попарное. Для одной попытки сравнение смотрит на каждую другую попытку отдельно: совпавший ответ - это равные отпечатки одной версии семейства и поколения ключа, данные другим кандидатом на другой вариант seed, поэтому ожидаемое совпадение при одном seed не сигнал, а кандидат не совпадает со своей же попыткой. Совпавший ответ несет -log2 доли ответов с этим отпечатком среди ответов версии семейства и поколения ключа, она читается из поддерживаемых счетчиков (поэтому ротация ключа не искажает долю), от нуля до предела его формата (`duplicate_integer_cap_bits`, `duplicate_sequence_cap_bits`). Поэтому популярное значение, например верный ответ варианта, несет мало, как и совокупность из нескольких попыток. Биты одной пары складываются, решает самая сильная пара, а `duplicate_bits_attention` и `duplicate_bits_review` - пороги на эту сумму. Список пар ограничен и не покидает usecase; ничто в выводе не называет другую попытку или кандидата, а вывод оператора содержит только числа.
|
||||
- Почему демо-пороги равны 48 и 64 битам и что означает эта цифра. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` берет по 4000 seed каждого из четырех демо-семейств (у трех целочисленных 36-47 различных ответов, у порядка зависимостей около 2250), строит распределение общих значений и их битов и считает вероятность того, что одна пара честных кандидатов, верно ответивших на попытку из 23 заданий, достигнет каждого порога. Умноженная на 10 000 соперников (граница объединения), доля ложных пометок на попытку - около 4e-5 для «внимание» и 3e-9 для «проверить» при целях теста 1e-3 и 1e-8. Модель использует распределение эталонных ответов: она не моделирует распределение неверных ответов и коррелированные ошибки (одинаковая типичная ошибка многих кандидатов, общий учебник), из-за которых честные совпадения могут быть вероятнее расчетных. Это демо-значения до калибровки на настоящем банке, измеренные на четырех семействах, написанных ИИ. В обратную сторону `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` считает, сколько ответов на семейство нужно скопированной паре, чтобы демо-пороги ее пометили, когда пара копирует все ответы и больше никто эти значения не держит: для попытки из 13 заданий «внимание» от 26 ответов на семейство и «проверить» от 61; для 23 заданий от 9 и от 14. Стенд с меньшим числом попыток по замыслу ничего не помечает. Чтобы попробовать функцию на малом стенде, опубликуйте версию политики с меньшими порогами в `assessment.signals` (интеграционные тесты делают так с 4 и 6 битами); демо-политика для этого не меняется.
|
||||
- Политика. Необязательный раздел `assessment.signals` документа схемы 2 хранит все пороги (`domain.AssessmentSignalPolicy`); версия без него не считает полосу. `DemoProductPolicyV3` - это `DemoProductPolicyV2` плюс `DemoAssessmentSignalPolicy`; `DemoProductPolicyV1`, `DemoProductPolicyV2` и стартовый seed не изменились, сохраненная версия не переписывается. Полоса использует пороги версии продуктовой политики из `assessment_attempts.product_policy_version_id`, поэтому политика, опубликованная позже, не меняет попытку в процессе и сохраненную проверку; `assessment_attempt_reviews.policy_version_id` фиксирует версию, а триггер запрещает ее менять. Попытка из пары пересчитывается под своей закрепленной версией; пары выбираются по уровню «внимание» считающей попытки, поэтому между версиями с разными уровнями пара может быть пропущена на стороне с меньшим уровнем.
|
||||
- Когда и как. Проверка никогда не считается в транзакции кандидата. Первый принятый ответ планирует задание `assessment.signal_review` с ключом `<попытка>:deadline`, срок - через минуту после дедлайна попытки (чтобы ответ, зафиксированный прямо на дедлайне, попал в факты), а завершение планирует `<попытка>:ended`, срок - сразу; оба - вставки в `scheduled_jobs` в транзакции ответа или завершения, повтор ничего не делает. Задание дедлайна покрывает и попытку, которая истекает или брошена, как и когда бы ни менялось ее состояние. Проверка - оценка на момент: она описывает факты, зафиксированные к запуску ее задания, а задание на дедлайне для завершенной попытки запускает ее снова и подхватывает поздние совпадения. Задание считает проверку своей попытки и обновляет проверку каждой другой завершившейся (терминальное состояние или срок прошел) попытки с общими ответами на уровне «внимание» и выше, не более 50 за задание; кольцо больше 50 попыток с общими ответами покрыто тем, что каждый участник запускает свое задание дедлайна и видит остальных. Еще идущую попытку помечает ее собственное задание, когда она закончится и увидит остальные факты. Писатели упорядочены транзакционной advisory-блокировкой на каждую проверку: задание берет блокировки проверок всех попыток, которые будет писать, по возрастанию идентификатора, до чтения любого факта, поэтому более позднее из двух заданий по одной попытке ждет и затем читает то, что зафиксировало раннее (нет потерянного обновления и нет цикла блокировок). Время проверки берется из часов базы внутри upsert, а время обновления не отстает от сохраненного. Больше ничего не блокируется: факты только добавляются, а задание планируется после фиксации его фактов. Сбой повторяется исполнителем с задержкой и никогда не блокирует и не меняет результат; без worker (`JOBS_ENABLED=false`) проверки ждут вместе со своими заданиями. В транзакции кандидата из запросов проверки только вставка задания (и два обновления счетчиков ответа). Задание пишет в журнал одну строку с числом записанных проверок и длительностью, без ответов, адресов и кандидатов. Граница применимости: доля читается из счетчиков за постоянное время, но сравнение соединяет ответы попытки с ответами, у которых те же значения, поэтому цена растет с числом держателей популярных значений, не более 23 заданий на число держателей каждого; для фоновых заданий это нормально на совокупностях до порядка 100 000 ответов на семейство, выше нужна выборка или предел.
|
||||
- Ограничения. Браузерные сигналы можно подделать или подавить, поэтому это только подсказка. Помощь, например LLM на другом устройстве, не видна. Возможны ложные срабатывания: общая или меняющаяся сеть (мобильный интернет, NAT), перезагрузка страницы, две вкладки, копирование условия и случайные совпадения ответов из малого пространства. Срок хранения этих фактов, нужно ли для их сбора отдельное согласие сверх уведомления и кто калибрует пороги, не решено.
|
||||
|
||||
## Подбор и объяснение
|
||||
|
||||
До ранжирования Go применяет жесткие фильтры: опубликованный профиль, специализация, подтвержденный грейд, обязательные навыки и другие выбранные требования. Хорошее резюме или достижение не компенсирует отсутствующий обязательный критерий. Отсутствие подтверждения навыка нужно отличать от подтвержденного отсутствия.
|
||||
|
||||
+18
-1
@@ -189,7 +189,7 @@ Dead letter - запись, от которой обработчик отказ
|
||||
|
||||
### Задания по сроку
|
||||
|
||||
Backend запускает worker заданий по сроку как горутину процесса backend рядом с HTTP-серверами, relay и обработчиками событий. Он выполняет задания, которые usecase запланировали в своих транзакциях, когда наступает их срок; устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#задания-по-сроку). Текущее состояние: продуктовый вид задания не зарегистрирован, поэтому backend при старте пишет в журнал `no scheduled job kind is registered` и не запускает worker; настройки ниже все равно проверяются. С зарегистрированным видом worker работает, когда `JOBS_ENABLED` равно true и задан `DATABASE_URL`. Compose не передает ни одну из этих настроек, поэтому стенд использует значения по умолчанию; чтобы изменить значение, добавьте его в `environment` backend в `deploy/docker/docker-compose.yml`. Backend, запущенный напрямую, читает их из своего окружения. Недопустимое значение останавливает запуск, даже когда worker выключен.
|
||||
Backend запускает worker заданий по сроку как горутину процесса backend рядом с HTTP-серверами, relay и обработчиками событий. Он выполняет задания, которые usecase запланировали в своих транзакциях, когда наступает их срок; устройство описано в [ARCHITECTURE.md](ARCHITECTURE.md#задания-по-сроку). Текущее состояние: зарегистрирован один продуктовый вид, `assessment.signal_review` (см. [Полоса проверки оценки](#полоса-проверки-оценки)), поэтому worker работает, когда `JOBS_ENABLED` равно true и задан `DATABASE_URL`; настройки ниже проверяются в любом случае. Compose не передает ни одну из этих настроек, поэтому стенд использует значения по умолчанию; чтобы изменить значение, добавьте его в `environment` backend в `deploy/docker/docker-compose.yml`. Backend, запущенный напрямую, читает их из своего окружения. Недопустимое значение останавливает запуск, даже когда worker выключен.
|
||||
|
||||
| Переменная | По умолчанию | Значение |
|
||||
| --- | --- | --- |
|
||||
@@ -312,6 +312,23 @@ Compose передает эти переменные из корневого `.e
|
||||
- Renderer ничего не пишет в лог. Результат и данные уведомления в выводе `fmt` и `slog` показывают только тип, версию и content hash; токены, ссылки и тела писем не печатаются.
|
||||
- Golden файлы в `testdata/` делают каждое изменение текста видимым на ревью. После намеренного изменения выполните `go test ./internal/usecase/notification/mailtemplate -update` из `backend/` и проверьте diff.
|
||||
|
||||
## Полоса проверки оценки
|
||||
|
||||
Сервер считает для реальных попыток оценки полосу ручной проверки (`normal`, `attention`, `review`) по серверным сигналам и версии политики, закрепленной за попыткой (см. [ARCHITECTURE.md](ARCHITECTURE.md#серверные-сигналы-оценки-и-полоса-проверки)). Полоса - подсказка для человека, который проверяет попытку вручную. Она не меняет результат, категорию или квоту, и ни один HTTP endpoint ее не отдает. Пока служебных ролей нет, оператор читает ее локальной командой:
|
||||
|
||||
```sh
|
||||
make -C backend assessment-review ARGS='inspect --attempt <uuid> --actor operator:<handle>'
|
||||
```
|
||||
|
||||
- Полосу считает задание по сроку вида `assessment.signal_review`, никогда не запрос кандидата. Задания вставляются в `scheduled_jobs` с первым ответом (срок - через минуту после дедлайна попытки) и с завершением (срок - сразу). Worker должен работать (`JOBS_ENABLED=true`, [Задания по сроку](#задания-по-сроку)); при выключенном worker проверки ждут вместе со своими заданиями, и ни один результат не затрагивается. Упавшее задание повторяется с задержкой worker; мертвое задание (см. [Dead задания](#dead-задания)) оставляет попытку без обновленной проверки и не трогает ее результат.
|
||||
- Команде нужен `DATABASE_URL`, больше она ничего не читает из окружения и dotenv-файла; границей оператора служит локальный доступ к базе. `make -C backend assessment-review-build` собирает `backend/bin/assessment-review`.
|
||||
- Она печатает идентификатор попытки, полосу, коды причин, версию политики, время вычисления и обновления и числа, из которых составлена полоса. Она не печатает ответы, адреса, сессии, данные кандидата или контакты и никогда не называет другого кандидата при совпадении ответов.
|
||||
- Каждое чтение записывается в `assessment_review_reads` (идентификатор попытки, имя оператора, найдено или нет, время базы) в той же транзакции, что и чтение, в том числе когда у попытки нет проверки. Таблица отклоняет UPDATE, DELETE и TRUNCATE. Имя оператора - метка для аудита, а не аутентификация: любой, у кого есть доступ к базе, может ввести любое имя. Откат миграции 33 отклоняется, пока в аудите есть строка; сначала экспортируйте или разберите ее.
|
||||
- Полосы может не быть по реальной причине: в версии политики попытки нет раздела `assessment.signals`, задание проверки еще не выполнено, либо попытка еще не завершилась и не достигла дедлайна.
|
||||
- Проверка обновляется на месте, когда более поздняя попытка совпала с одним из ее ответов; версия политики и время первого вычисления остаются.
|
||||
- Чтобы использовать пороги, отличные от демо, опубликуйте версию политики с разделом `assessment.signals` через публикатор политик. `DemoProductPolicyV3` - демо-пример, он публикуется только явно (так делает изолированная браузерная фикстура); стартовый seed публикует только версию 1. Попытки, которые уже начались, сохраняют версию, с которой начались. Демо-пороги дубликатов рассчитаны на совокупность: скопированная пара помечается лишь примерно от 26 ответов на семейство («внимание») и 61 («проверить») при 13 заданиях или от 9 и 14 при 23. Чтобы попробовать функцию на меньшем стенде, опубликуйте версию политики с меньшими `duplicate_bits_attention` и `duplicate_bits_review` (интеграционные тесты используют 4 и 6); демо-политику не редактируйте. Проверка - оценка на момент, задание на дедлайне запускает ее снова. Задание пишет в журнал одну строку на запуск с числом проверок и длительностью (`assessment review job finished`).
|
||||
- Строки хранят числа, длительности и ключевые дайджесты (HMAC-SHA-256 под ключами, выведенными из `IDENTITY_KEY_SECRET`, у каждого есть версия ключа) и не хранят текст ответа. Смена секрета сохраняет строки, но делает новые отпечатки несравнимыми со старыми. Удаление аккаунта удаляет его попытки и каскадом их факты и проверки; строки аудита хранят только идентификатор попытки и имя. Дайджесты хранятся столько же, сколько попытка; срок хранения пока не определен.
|
||||
|
||||
## Отдельный ML Compose
|
||||
|
||||
ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.
|
||||
|
||||
@@ -439,6 +439,26 @@ Unit-тесты (`make -C backend test`) проверяют правила жу
|
||||
|
||||
`TestPostgresMigrations` откатывает миграцию 00011 вместе с остальными и проверяет, что две ее таблицы и пять функций исчезают, а таблица политик остается. Набор доказывает только правила хранилища и загрузчика: он не проверяет содержимое демонстрационного пакета, сложность задач и какие-либо грейды, не доказывает сериализацию одновременных публикаций сверх случая с удерживаемой блокировкой и не покрывает сценарий кандидата, потому что его еще нет. Интеграционным тестам нужен Docker.
|
||||
|
||||
## Тесты сигналов оценки и полосы проверки
|
||||
|
||||
`backend/internal/domain/assessment_signal_policy_test.go` и `assessment_signal_review_test.go` проверяют без базы: демо-раздел сигналов корректен и проходит круг через документ схемы 2, один раздел сигналов - допустимое расширение и никогда не получает значений по умолчанию, схема 1 отклоняет ключ, значения вне диапазона и несогласованные пороги отвергаются, время ответа следует порогам формата и отношению к медиане только на быстрой стороне в пределах одного формата и не учитывает первый элемент сессии, метки происхождения считают чередования и различные сети по времени (возврат в прежнюю сеть не новая сеть), полоса следует политике, слабые сигналы (параллельные сессии и лишние сети - одна коррелированная группа) останавливаются на «внимание», пока нет сильного сигнала, ответ считается один раз как быстрый или как отклонение, клиентские сигналы поднимают полосу только до «внимание», и имя оператора должно быть `operator:<handle>`. `backend/internal/usecase/identity/keyring_test.go` проверяет новые методы keyring: отпечаток ответа детерминирован, ключевой и привязан к версии семейства; дайджесты сессии и сети различаются между попытками (связать нельзя), между сессиями и между ключами клиента и используют отдельные ключи назначения.
|
||||
|
||||
`backend/internal/usecase/assessment/signal_review_test.go` проверяет наблюдателя и задание проверки на поддельных портах: принятый ответ сохраняет серверное время, признак отсчета от предыдущего ответа, версию ключа и только ключевой отпечаток, без текста ответа, адреса и идентификатора сессии ни в сохраняемых значениях, ни в тексте ошибки; метки происхождения пишутся только при смене сессии или сети; первый ответ планирует задание дедлайна (через минуту после дедлайна), а завершение - задание завершения; тренировочные попытки и запросы без сессии ничего не сохраняют; версия политики без раздела сигналов не создает проверку; задание отклоняет испорченную нагрузку, пропускает отсутствующую попытку, блокирует проверки пары по возрастанию идентификатора попытки до чтения любого факта и пишет их под своими закрепленными политиками, и обновляет только завершившиеся попытки на уровне «внимание», ограниченно. `TestDemoDuplicateThresholdsKeepThePerAttemptFalseFlagRateLow` берет по 4000 seed каждого демо-семейства, строит распределение общих значений с их битами и считает вероятность того, что одна честная пара достигнет каждого демо-порога на попытке из 23 заданий; умноженная на 10 000 соперников она равна примерно 4e-5 («внимание») и 3e-9 («проверить») при целях 1e-3 и 1e-8. `TestDemoThresholdsNeedAPopulationBeforeACopiedPairIsFlagged` считает, сколько ответов на семейство нужно скопированной паре, чтобы демо-пороги ее пометили (26 для «внимание» и 61 для «проверить» при 13 заданиях, 9 и 14 при 23). Модель ложных срабатываний использует только распределение эталонных ответов, а не неверные ответы и коррелированные ошибки. Цели - константы теста, выбранные здесь, а не продуктовое решение, а измерение покрывает четыре семейства, написанных ИИ.
|
||||
|
||||
`backend/internal/adapter/primary/http/assessment_signal_review_contract_test.go` обходит каждый путь публичного контракта по ссылкам и отвергает любое свойство, имя схемы или enum, которые несли бы полосу, ее причины, отпечатки или дайджесты происхождения, и проверяет, что в квитанции сигналов по-прежнему ровно `status`, `accepted_events` и `received_at`. `backend/internal/adapter/primary/cli/assessmentreview/command_test.go` проверяет проверку аргументов до чтения окружения, выводимые поля и очищенные ошибки. Тест bootstrap проверяет, что вид задания проверки зарегистрирован.
|
||||
|
||||
`TestAssessmentSignalReviewOverHTTP` в `backend/integration_test/assessment_signal_review_http_test.go` запускает настоящий роутер, PostgreSQL и worker заданий по сроку:
|
||||
|
||||
- Кандидат отвечает на все задания за миллисекунды из двух сессий входа и с трех сетевых адресов и шлет события вставки из второй сессии. Пока worker не запущен, проверки нет, а задания проверки ожидают, то есть в транзакции кандидата ничего не считалось. Затем у попытки полоса `attention` с причинами быстрые ответы, параллельные сессии, лишние сети и клиентские сигналы, а результат `confirmed` совпадает по исходу, баллам, ограничениям и режиму с результатом столь же верной попытки с полосой `normal`; ни в одной таблице оценки, кроме таблицы проверок, нет колонки полосы.
|
||||
- Пока попытки идут, публикуется версия политики с другими порогами и под ней открывается категория. Попытки, начатые раньше, сохраняют первую версию, попытка, созданная позже, закреплена за новой версией и остается `normal` при том же поведении, а ее факты все равно сохранены.
|
||||
- Двое кандидатов с разными seed копируют одинаковые неверные ответы: у первой попытки нет признака дубликата, пока второй кандидат не ответил и не завершил попытку, после чего у обеих полоса `review` с причиной одинаковые ответы. Третья копирующая попытка брошена: пока она идет, ее не помечают, а после окончания ее задание дедлайна (часы worker сдвинуты за срок) ее помечает. Честные попытки с верными ответами не помечаются, даже если совпал ответ из малого пространства, а у попытки с одной сессией и одной сетью ровно одна метка происхождения.
|
||||
- Чтения кандидатом попытки, результата и доступности не содержат полосу, причины, отпечатки и названия сигналов. Команда оператора выводит полосу, а строки аудита пишутся для найденной и для отсутствующей попытки; имя без префикса `operator:` отклоняется. Факты, проверки и строки аудита отклоняют UPDATE и DELETE, а аудит - и TRUNCATE.
|
||||
- Журналы и текст новых таблиц и `scheduled_jobs` не содержат сетевых адресов, значений ответов, токенов сессии и CSRF.
|
||||
|
||||
`TestAssessmentSignalReviewHonestPopulationHasNoDuplicateFlag` создает 30 честных кандидатов с разными seed, которые отвечают на каждое задание верно или нет случайно (фиксированный генератор), и двоих, копирующих одинаковые ответы: ни одна честная попытка не помечена дубликатом, обе копирующие помечены. Совокупность мала, поэтому тест использует пороги 32 и 44 бита, а не демо-пороги. `TestAssessmentSignalReviewConcurrentJobsFlagEveryCopiedAttempt` завершает четыре копирующие попытки одновременно среди восьми честных и запускает их задания на четырех worker сразу: ни одно задание не падает и не повторяется, и каждая копирующая попытка помечена. `TestAssessmentSignalReviewJobWaitsForTheReviewLock` держит блокировку проверки попытки в одной транзакции и проверяет, что задание проверки ждет, ничего не пишет и считает проверку по зафиксированным фактам после снятия блокировки; именно этот порядок не дает устаревшей оценке затереть более новую проверку. Тест параллельных заданий прогнан десять раз подряд (`-count=10`). `TestAssessmentSignalReviewMigrationDownRetainsAudit` проверяет, что откат миграции 33 отклоняется, пока в аудите есть строка (таблицы и строка остаются, TRUNCATE отклоняется), и проходит при пустом аудите.
|
||||
|
||||
Тесты доказывают сохраненные факты, закрепление политики, вычисление заданием и отсутствие полосы в контракте и в чтениях кандидата. Они не доказывают качество обнаружения: пороги не откалиброваны, измерение ложных срабатываний покрывает четыре написанных семейства, исследования на реальных кандидатах нет. Чтения работодателя покрыты обходом контракта, а не HTTP-вызовом каждой операции.
|
||||
|
||||
## Будущая программная валидация
|
||||
|
||||
Для Go unit tests нужны правила domain/usecase с конкретными входами, результатами и ошибками. Интеграционные тесты используют настоящую PostgreSQL той же major версии, применяют goose migrations и проверяют sqlc, ограничения, транзакции, rollback и конкурентные переходы. Для HTTP путь собирается через chi, middleware, usecase и БД; внешний ML заменяется контролируемым HTTP fake, почта - тестовым адаптером.
|
||||
|
||||
Reference in new issue
Block a user