feat(assessment): assign the demonstration category and keep result history
This commit is contained in:
1 parent
b3c6dc870b
commit
8277133712
61 files changed
+4338
-268
No files matched your search
@@ -49,6 +49,14 @@ assessment-review-build: ## Build the local assessment review operator command
|
||||
@mkdir -p bin
|
||||
$(GO) build -buildvcs=false -trimpath -o bin/assessment-review ./cmd/assessment-review
|
||||
|
||||
.PHONY: assessment-category-attest assessment-category-attest-build
|
||||
assessment-category-attest: ## Attest a category opening for synthetic demonstration categories (set ARGS)
|
||||
$(GO) run ./cmd/assessment-category-attest $(ARGS)
|
||||
|
||||
assessment-category-attest-build: ## Build the local category attestation operator command
|
||||
@mkdir -p bin
|
||||
$(GO) build -buildvcs=false -trimpath -o bin/assessment-category-attest ./cmd/assessment-category-attest
|
||||
|
||||
.PHONY: deps install install-tools
|
||||
deps: ## Download pinned Go module dependencies
|
||||
$(GO) mod download
|
||||
|
||||
@@ -88,7 +88,11 @@ Creation pins the policy, bank and algorithm versions, the published family mani
|
||||
|
||||
Repeating a command with the same key and body returns its stored response for 24 hours. Reusing a key with another body returns 422; an unavailable bank or exhausted quota returns 409 `state_conflict`. PostgreSQL serializes quota checks and session updates, and domain time is read after lock waits. Migration 24 adds attempts, question instances, training bindings, and stored command responses; rolling it back deletes these records.
|
||||
|
||||
Answer submission evaluates the frozen server key and stores each answer once. Numeric comparison preserves the JSON number token without floating-point rounding; order answers must include every task exactly once. Finalization rejects unfinished required questions with their IDs, then stores the raw basic score, policy rationale, version pins, and result projection in one transaction. Reads use that immutable result. Duration does not add points, trailing seed items are unscored, and express results contain no qualification score. Migration 29 refuses rollback while command or result records depend on it. Category assignment remains separate work; a basic threshold is not evidence of calibration.
|
||||
Answer submission evaluates the frozen server key and stores each answer once. Numeric comparison preserves the JSON number token without floating-point rounding; order answers must include every task exactly once. Finalization rejects unfinished required questions with their IDs, then stores the raw basic score, policy rationale, version pins, and result projection in one transaction. Reads use that immutable result. Duration does not add points, trailing seed items are unscored, and express results contain no qualification score. Migration 29 refuses rollback while command or result records depend on it. A basic threshold is not evidence of calibration.
|
||||
|
||||
Demonstration category. Finalizing a real attempt writes a version 2 result: the immutable document gains a category decision and the grade in force at the moment of the decision (migration 31). A `demo_express` result stays a version 1 record without these fields and never creates a category. The decision depends on the `basic_pass_mark_bp` threshold of the policy version pinned to the attempt; the HTTP handler sets no parameter. A current category row (`candidate_assessment_categories`, one per candidate and specialization) appears only when all of the following hold: `ASSESSMENT_DEMO_CATEGORIES_ENABLED` is on (off by default; turn it on only on a synthetic stand), the pinned policy is a complete demonstration policy with `demo_basic` (its threshold is the policy's own `basic_pass_mark_bp`), the result is confirmed, and an operator attestation exists for the exact category opening, catalog manifest, and policy version (`assessment_synthetic_category_reviews`, `source = synthetic_demo`). Otherwise the decision is stored as `not_eligible` or `not_confirmed`. A candidate and specialization lock serializes promotions; the database accepts only a strict upgrade, forbids deletion and manual replacement of the source, and a current category always points at a stored version 2 result of the same candidate. A failure, an equal grade, or a lower grade keep the category in force, and both attempts stay in the history.
|
||||
|
||||
The candidate reads the history through `GET /api/v1/me/assessment-results` (`usecase/assessment/category_history.go`): own `root` and `corrective` results only, paged by a cursor that a server HMAC binds to the candidate. An employer gets no history; a separate projection of the current category is part of the visible-candidate query (`privacy_cohort.sql`) and selects only the specialization and grade, so the anonymous card shows the category with strength `standard` when the candidate published the `categories` field. A change of the current policy changes no stored result or category; opened categories are bound to the policy they were opened under, so no attempt is created after a new policy version until the categories are opened again. The attestation is created by the local command `make -C backend assessment-category-attest` (see [DEPLOY.md](../docs/en/DEPLOY.md#demonstration-categories-on-a-stand)). Calibration of the threshold is not implemented.
|
||||
|
||||
## Assessment signals
|
||||
|
||||
|
||||
+5
-1
@@ -88,7 +88,11 @@
|
||||
|
||||
Повтор команды с тем же ключом и телом возвращает сохраненный ответ в течение 24 часов. Повтор ключа с другим телом возвращает 422; недоступный банк или исчерпанная квота - 409 `state_conflict`. PostgreSQL сериализует проверку квоты и изменения сессии, а доменное время берется после ожидания блокировок. Миграция 24 добавляет попытки, экземпляры вопросов, учебные привязки и сохраненные ответы команд; ее откат удаляет эти данные.
|
||||
|
||||
Прием ответа проверяет закрепленный серверный ключ и сохраняет каждый ответ один раз. Сравнение чисел сохраняет исходную числовую запись JSON без округления через плавающую точку; ответ с порядком должен содержать каждую задачу ровно один раз. Завершение отклоняет неотвеченные обязательные вопросы с перечнем их ID, затем сохраняет сырой базовый балл, правило политики, закрепленные версии и представление результата в одной транзакции. Чтение использует этот неизменяемый результат. Длительность не добавляет баллы, последние seed-вопросы не оцениваются, а экспресс-результат не содержит квалификационного балла. Миграция 29 запрещает откат при наличии зависящих от нее записей команд или результатов. Присвоение категории остается отдельной работой; базовый порог не подтверждает калибровку.
|
||||
Прием ответа проверяет закрепленный серверный ключ и сохраняет каждый ответ один раз. Сравнение чисел сохраняет исходную числовую запись JSON без округления через плавающую точку; ответ с порядком должен содержать каждую задачу ровно один раз. Завершение отклоняет неотвеченные обязательные вопросы с перечнем их ID, затем сохраняет сырой базовый балл, правило политики, закрепленные версии и представление результата в одной транзакции. Чтение использует этот неизменяемый результат. Длительность не добавляет баллы, последние seed-вопросы не оцениваются, а экспресс-результат не содержит квалификационного балла. Миграция 29 запрещает откат при наличии зависящих от нее записей команд или результатов. Базовый порог не подтверждает калибровку.
|
||||
|
||||
Демонстрационная категория. Завершение реальной попытки записывает результат версии 2: к неизменяемому документу добавляются решение о категории и грейд, действовавший на момент решения (миграция 31). Результат `demo_express` остается записью версии 1 без этих полей и никогда не создает категорию. Решение зависит от порога `basic_pass_mark_bp` версии политики, закрепленной за попыткой; обработчик HTTP параметров не задает. Строка текущей категории (`candidate_assessment_categories`, по одной на кандидата и специализацию) появляется, только если одновременно выполнено следующее: включен `ASSESSMENT_DEMO_CATEGORIES_ENABLED` (по умолчанию выключен; включать только на синтетическом стенде), закрепленная политика является полной демонстрационной политикой с `demo_basic` (порог берется из ее `basic_pass_mark_bp`), результат подтвержден, а для точного открытия категории, манифеста каталога и версии политики есть аттестация оператора (`assessment_synthetic_category_reviews`, `source = synthetic_demo`). Иначе решение записывается как `not_eligible` или `not_confirmed`. Блокировка кандидата и специализации сериализует повышения; база принимает только строгое повышение, запрещает удаление и ручную подмену источника, а текущая категория всегда ссылается на сохраненный результат версии 2 того же кандидата. Неудача, равный или более низкий грейд сохраняют действующую категорию, а обе попытки остаются в истории.
|
||||
|
||||
История кандидата читается через `GET /api/v1/me/assessment-results` (`usecase/assessment/category_history.go`): только собственные `root` и `corrective` результаты, постранично, с курсором, привязанным к кандидату серверным HMAC. Работодатель историю не получает; отдельная проекция текущей категории входит в запрос видимых кандидатов (`privacy_cohort.sql`) и выбирает только специализацию и грейд, поэтому анонимная карточка показывает категорию с силой `standard`, если кандидат опубликовал поле `categories`. Смена текущей политики не меняет сохраненные результаты и категории; открытые категории привязаны к политике, под которой их открыли, поэтому после новой версии политики попытки не создаются, пока категории не открыты заново. Аттестацию создает локальная команда `make -C backend assessment-category-attest` (см. [DEPLOY.md](../docs/ru/DEPLOY.md#демонстрационные-категории-на-стенде)). Не реализована калибровка порога.
|
||||
|
||||
## Сигналы прохождения оценки
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
// Command assessment-category-attest attests the current opening of one
|
||||
// assessment category as a source of synthetic demonstration categories. It
|
||||
// is for isolated synthetic stands only and changes nothing else.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/cli/categoryattest"
|
||||
)
|
||||
|
||||
func main() {
|
||||
os.Exit(run())
|
||||
}
|
||||
|
||||
func run() int {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := categoryattest.Run(ctx, os.Args[1:], os.LookupEnv, os.Stdout); err != nil {
|
||||
_, _ = fmt.Fprintf(os.Stderr, "assessment-category-attest: %v\n", err)
|
||||
return 2
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -97,12 +97,11 @@ BEGIN
|
||||
AND policy.policy_key = 'product'
|
||||
AND policy.kind = 'demo'
|
||||
AND policy.version = NEW.product_policy_version
|
||||
AND policy.document #>> '{assessment,attempt,real_mode}' = 'demo_basic'
|
||||
AND policy.document #>> '{assessment,attempt,basic_pass_mark_bp}' = '8000';
|
||||
AND policy.document #>> '{assessment,attempt,real_mode}' = 'demo_basic';
|
||||
IF NOT FOUND OR policy_version <> NEW.product_policy_version THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_synthetic_category_review_policy',
|
||||
MESSAGE = 'synthetic category review policy is not an explicit demo basic policy';
|
||||
MESSAGE = 'synthetic category review policy is not a demo basic policy';
|
||||
END IF;
|
||||
|
||||
NEW.reviewed_at := clock_timestamp();
|
||||
@@ -263,6 +262,7 @@ LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
review assessment_synthetic_category_reviews%ROWTYPE;
|
||||
attempt assessment_attempts%ROWTYPE;
|
||||
pass_mark_text text;
|
||||
BEGIN
|
||||
IF NEW.schema_version = 1 THEN
|
||||
RETURN NEW;
|
||||
@@ -337,6 +337,21 @@ BEGIN
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_assignment',
|
||||
MESSAGE = 'category assignment is not a passing reviewed demo decision';
|
||||
END IF;
|
||||
|
||||
-- The threshold that confirmed the result is the pass mark of the policy
|
||||
-- version pinned to the attempt, read from the stored document and not
|
||||
-- from a constant. The text is checked before the cast.
|
||||
IF NEW.category_decision->>'status' = 'assigned' THEN
|
||||
SELECT policy.document #>> '{assessment,attempt,basic_pass_mark_bp}' INTO pass_mark_text
|
||||
FROM policy_versions AS policy
|
||||
WHERE policy.id = NEW.product_policy_version_id AND policy.policy_key = 'product';
|
||||
IF NOT FOUND OR pass_mark_text IS NULL OR pass_mark_text !~ '^[0-9]{1,5}$' OR
|
||||
NEW.pass_mark_basis_points IS DISTINCT FROM pass_mark_text::integer THEN
|
||||
RAISE EXCEPTION USING
|
||||
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_category_threshold',
|
||||
MESSAGE = 'category assignment does not use the pass mark of its pinned policy version';
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
@@ -21,7 +21,8 @@ INSERT INTO assessment_attempt_results (
|
||||
-- Returns both immutable result versions. NULL category fields identify a
|
||||
-- legacy v1 record and must not be reconstructed from current state.
|
||||
-- name: GetAssessmentAttemptResultHistoryEntry :one
|
||||
SELECT schema_version, result_snapshot::text, category_decision::text, current_confirmed_grade
|
||||
SELECT schema_version, result_snapshot::text,
|
||||
COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id);
|
||||
|
||||
@@ -29,7 +30,7 @@ WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id);
|
||||
-- applies the keyset to the same stable order and fetches one extra row.
|
||||
-- name: ListCandidateAssessmentResults :many
|
||||
SELECT attempt_id, user_id, schema_version, result_snapshot::text,
|
||||
category_decision::text, current_confirmed_grade, decided_at
|
||||
COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade, decided_at
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND kind IN ('root', 'corrective')
|
||||
@@ -69,8 +70,10 @@ WHERE review.opening_id = sqlc.arg(opening_id)
|
||||
AND opening.policy_version_id = sqlc.arg(grading_policy_version_id);
|
||||
|
||||
-- The application accepts only a validated immutable review snapshot. The
|
||||
-- trigger independently checks the source opening, manifest and policy.
|
||||
-- name: InsertSyntheticCategoryReview :exec
|
||||
-- trigger independently checks the source opening, manifest and policy. A
|
||||
-- concurrent or repeated attestation of the same exact source inserts nothing,
|
||||
-- and the caller reads the stored one.
|
||||
-- name: InsertSyntheticCategoryReview :execrows
|
||||
INSERT INTO assessment_synthetic_category_reviews (
|
||||
id, opening_id, category, source, opening_manifest_sha256,
|
||||
product_policy_version_id, product_policy_version, reviewed_by, reviewed_at
|
||||
@@ -78,10 +81,13 @@ INSERT INTO assessment_synthetic_category_reviews (
|
||||
sqlc.arg(id), sqlc.arg(opening_id), sqlc.arg(category), sqlc.arg(source),
|
||||
sqlc.arg(opening_manifest_sha256), sqlc.arg(product_policy_version_id),
|
||||
sqlc.arg(product_policy_version), sqlc.arg(reviewed_by), sqlc.arg(reviewed_at)
|
||||
);
|
||||
)
|
||||
ON CONFLICT ON CONSTRAINT assessment_synthetic_category_reviews_exact_source_key DO NOTHING;
|
||||
|
||||
-- Only strict grade upgrades replace the current row. The trigger enforces
|
||||
-- the same monotonic rule as a final guard against adapter mistakes.
|
||||
-- the same monotonic rule as a final guard against adapter mistakes. The
|
||||
-- grading policy is read from the immutable opening, and the guard trigger
|
||||
-- compares it with the policy captured in the assigned result.
|
||||
-- name: SaveCandidateAssessmentCategory :execrows
|
||||
INSERT INTO candidate_assessment_categories (
|
||||
candidate_id, specialization, grade, source_attempt_id, source_review_id,
|
||||
@@ -90,7 +96,12 @@ INSERT INTO candidate_assessment_categories (
|
||||
) VALUES (
|
||||
sqlc.arg(candidate_id), sqlc.arg(specialization), sqlc.arg(grade), sqlc.arg(source_attempt_id),
|
||||
sqlc.arg(source_review_id), sqlc.arg(product_policy_version_id), sqlc.arg(product_policy_version),
|
||||
sqlc.arg(grading_policy_version_id), sqlc.arg(opening_id), sqlc.arg(opening_manifest_sha256),
|
||||
(
|
||||
SELECT opening.policy_version_id
|
||||
FROM assessment_category_openings AS opening
|
||||
WHERE opening.id = sqlc.arg(opening_id)
|
||||
),
|
||||
sqlc.arg(opening_id), sqlc.arg(opening_manifest_sha256),
|
||||
sqlc.arg(source), sqlc.arg(calibration_status), sqlc.arg(assigned_at)
|
||||
)
|
||||
ON CONFLICT (candidate_id, specialization) DO UPDATE SET
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
-- candidates hidden from this organization before any profile value is read.
|
||||
-- The projection reads only stack, declared role, and experience dates. It
|
||||
-- deliberately excludes names, contacts, salary, location, soft skills,
|
||||
-- employer names, summaries, and imported excerpts.
|
||||
-- employer names, summaries, and imported excerpts. The only assessment data
|
||||
-- is the current category (specialization and grade) of the separate current
|
||||
-- category table; it carries no attempt, score, review, policy, or history.
|
||||
-- name: ListVisibleCandidateViewSources :many
|
||||
SELECT
|
||||
effective.user_id,
|
||||
@@ -47,7 +49,18 @@ SELECT
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
) AS parallel_period_acknowledgements,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object('specialization', category.specialization, 'grade', category.grade)
|
||||
ORDER BY category.specialization
|
||||
)::text
|
||||
FROM candidate_assessment_categories AS category
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
@@ -170,7 +183,18 @@ SELECT
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
) AS parallel_period_acknowledgements,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object('specialization', category.specialization, 'grade', category.grade)
|
||||
ORDER BY category.specialization
|
||||
)::text
|
||||
FROM candidate_assessment_categories AS category
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
|
||||
@@ -491,6 +491,18 @@ type assessmentAttemptHTTPHarness struct {
|
||||
}
|
||||
|
||||
func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *testEnvironment) *assessmentAttemptHTTPHarness {
|
||||
t.Helper()
|
||||
return newAssessmentAttemptHTTPHarnessWithCategories(ctx, t, env, assessment.AssessmentCategoryDecisionSettings{})
|
||||
}
|
||||
|
||||
// newAssessmentAttemptHTTPHarnessWithCategories builds the attempt router with
|
||||
// explicit category assignment settings. The zero settings deny assignment.
|
||||
func newAssessmentAttemptHTTPHarnessWithCategories(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
env *testEnvironment,
|
||||
categories assessment.AssessmentCategoryDecisionSettings,
|
||||
) *assessmentAttemptHTTPHarness {
|
||||
t.Helper()
|
||||
pool := env.newPool(ctx, t)
|
||||
store := postgresadapter.NewIdentityStore(pool)
|
||||
@@ -521,9 +533,9 @@ func newAssessmentAttemptHTTPHarness(ctx context.Context, t *testing.T, env *tes
|
||||
)
|
||||
questionnaireHandler := v1.NewQuestionnaireHandler(questionnaireusecase.NewService(transactor, clock.Now))
|
||||
catalogHandler := v1.NewCatalogHandler(assessment.NewBank(transactor))
|
||||
attemptService, err := assessment.NewAttemptService(transactor, transactor, keyring, clock.Now)
|
||||
attemptService, err := assessment.NewAttemptServiceWithCategorySettings(transactor, transactor, keyring, clock.Now, categories)
|
||||
if err != nil {
|
||||
t.Fatalf("NewAttemptService() error = %v", err)
|
||||
t.Fatalf("NewAttemptServiceWithCategorySettings() error = %v", err)
|
||||
}
|
||||
signalObserver, err := assessment.NewSignalObserver(keyring)
|
||||
if err != nil {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -353,6 +353,10 @@ func TestOrganizationNeedsStorage(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// needCreationResultMigrationVersion is the migration that creates
|
||||
// organization_need_creation_results.
|
||||
const needCreationResultMigrationVersion = 26
|
||||
|
||||
func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
|
||||
env := bootstrap(t, postgresService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), organizationTestTimeout)
|
||||
@@ -362,6 +366,10 @@ func TestNeedCreationResultMigrationRollbackPreflight(t *testing.T) {
|
||||
if _, err := migrator.Up(ctx); err != nil {
|
||||
t.Fatalf("apply migrations to rollback test database: %v", err)
|
||||
}
|
||||
// The preflight belongs to the migration that created the replay table, so
|
||||
// the migrations added after it are rolled back first. The database holds
|
||||
// no data yet, which keeps their own guarded rollbacks out of this test.
|
||||
rollBackAboveMigration(ctx, t, migrator, needCreationResultMigrationVersion)
|
||||
pool := newPoolFor(ctx, t, databaseURL)
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
fixture := organizationFixture{
|
||||
|
||||
@@ -49,7 +49,7 @@ var (
|
||||
{"candidate_questionnaire_specializations"}, {"candidate_questionnaires"},
|
||||
}
|
||||
assessmentAttemptTables = []pgx.Identifier{
|
||||
{"assessment_attempt_results"},
|
||||
{"candidate_assessment_categories"}, {"assessment_attempt_results"},
|
||||
{"assessment_signal_idempotency_outcomes"}, {"assessment_signal_events"}, {"assessment_signal_batches"},
|
||||
{"assessment_answer_observations"}, {"assessment_attempt_origin_marks"}, {"assessment_attempt_reviews"},
|
||||
{"assessment_attempt_items"}, {"assessment_attempts"}, {"assessment_attempt_idempotency_outcomes"},
|
||||
@@ -57,10 +57,15 @@ var (
|
||||
supportCaseTables = []pgx.Identifier{
|
||||
{"support_case_events"}, {"support_cases"}, {"support_case_create_outcomes"}, {"support_case_request_events"},
|
||||
}
|
||||
// userNoticeTables hold per-user notices that refer to users and, for the
|
||||
// inbox, to organizations.
|
||||
userNoticeTables = []pgx.Identifier{
|
||||
{"assessment_signal_notice_acknowledgements"}, {"notification_inbox_events"},
|
||||
}
|
||||
// usersDependentTables is every table that references users, directly or
|
||||
// through another table of the list. A TRUNCATE of users must name all of
|
||||
// them, so a migration that adds such a table adds it here.
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables, assessmentAttemptTables, supportCaseTables)
|
||||
usersDependentTables = slices.Concat(identityTables, deliveryTables, consentTables, organizationTables, candidateProfileTables, candidateQuestionnaireTables, candidatePrivacyTables, assessmentAttemptTables, supportCaseTables, userNoticeTables)
|
||||
)
|
||||
|
||||
// organizationFixture works on the bootstrap database. The tables are
|
||||
|
||||
@@ -249,7 +249,8 @@ func TestPolicyVersions(t *testing.T) {
|
||||
assessment_training_bank_binding_families, assessment_attempts, assessment_attempt_items,
|
||||
support_cases, support_case_events, assessment_signal_idempotency_outcomes,
|
||||
assessment_signal_events, assessment_signal_batches, assessment_attempt_results,
|
||||
assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks`},
|
||||
assessment_attempt_reviews, assessment_answer_observations, assessment_attempt_origin_marks,
|
||||
assessment_synthetic_category_reviews, candidate_assessment_categories`},
|
||||
}
|
||||
for _, statement := range statements {
|
||||
_, err := fixture.pool.Exec(ctx, statement.sql, statement.args...)
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// Package categoryattest implements the local operator command that attests the
|
||||
// current opening of an assessment category as a source of synthetic
|
||||
// demonstration categories. It is meant for isolated synthetic stands: a
|
||||
// category is assigned only when the runtime gate
|
||||
// ASSESSMENT_DEMO_CATEGORIES_ENABLED is also on.
|
||||
package categoryattest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// syntheticOnlyWarning is printed before any work, also when the command fails.
|
||||
const syntheticOnlyWarning = "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand\n"
|
||||
|
||||
const usage = "usage: assessment-category-attest attest --specialization <code> --grade <code> [--task-language <code>] --actor operator:<handle>"
|
||||
|
||||
// Command is a parsed, validated attestation request.
|
||||
type Command struct {
|
||||
Specialization domain.SpecializationCode
|
||||
Grade domain.GradeCode
|
||||
TaskLanguage *domain.TaskLanguageCode
|
||||
Actor string
|
||||
}
|
||||
|
||||
// Attestor stores an attestation.
|
||||
type Attestor interface {
|
||||
Attest(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
actor string,
|
||||
) (assessment.CategoryAttestation, error)
|
||||
}
|
||||
|
||||
// Parse validates every argument before Run reads configuration or connects
|
||||
// to PostgreSQL.
|
||||
func Parse(args []string) (Command, error) {
|
||||
if len(args) == 0 || args[0] != "attest" {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
flags := flag.NewFlagSet("assessment-category-attest attest", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
specialization := flags.String("specialization", "", "specialization code")
|
||||
grade := flags.String("grade", "", "grade code")
|
||||
language := flags.String("task-language", "", "task language code")
|
||||
actor := flags.String("actor", "", "operator handle")
|
||||
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
command := Command{
|
||||
Specialization: domain.SpecializationCode(strings.TrimSpace(*specialization)),
|
||||
Grade: domain.GradeCode(strings.TrimSpace(*grade)),
|
||||
Actor: strings.TrimSpace(*actor),
|
||||
}
|
||||
if !command.Specialization.IsKnown() {
|
||||
return Command{}, errors.New("specialization must be a known specialization code")
|
||||
}
|
||||
if !command.Grade.IsKnown() {
|
||||
return Command{}, errors.New("grade must be intern, junior, middle, or senior")
|
||||
}
|
||||
if trimmed := strings.TrimSpace(*language); trimmed != "" {
|
||||
taskLanguage := domain.TaskLanguageCode(trimmed)
|
||||
if !taskLanguage.IsKnown() {
|
||||
return Command{}, errors.New("task language must be a known task language code")
|
||||
}
|
||||
command.TaskLanguage = &taskLanguage
|
||||
}
|
||||
if _, err := domain.ParseAssessmentOperator(command.Actor); err != nil {
|
||||
return Command{}, errors.New("actor must be operator:<handle>")
|
||||
}
|
||||
return command, nil
|
||||
}
|
||||
|
||||
// Run parses the command, loads only DATABASE_URL from the supplied
|
||||
// environment, and executes the attestation. It does not load dotenv files.
|
||||
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer) error {
|
||||
command, err := Parse(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lookup == nil || output == nil {
|
||||
return errors.New("category attestation command dependencies are required")
|
||||
}
|
||||
databaseURL := config.DatabaseURLFromEnv(lookup)
|
||||
if databaseURL == "" {
|
||||
return errors.New("DATABASE_URL is not set")
|
||||
}
|
||||
pool, err := postgres.NewPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return errors.New("database configuration is invalid")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return errors.New("database is unavailable")
|
||||
}
|
||||
attestor, err := assessment.NewCategoryAttestor(postgres.NewTransactor(pool))
|
||||
if err != nil {
|
||||
return errors.New("category attestation is unavailable")
|
||||
}
|
||||
return Execute(ctx, command, attestor, output)
|
||||
}
|
||||
|
||||
// Execute stores the attestation and prints identifiers and versions only; it
|
||||
// prints no candidate, answer, or contact data.
|
||||
func Execute(ctx context.Context, command Command, attestor Attestor, output io.Writer) error {
|
||||
if attestor == nil || output == nil {
|
||||
return errors.New("category attestation command dependencies are required")
|
||||
}
|
||||
if _, err := io.WriteString(output, syntheticOnlyWarning); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
attestation, err := attestor.Attest(ctx, command.Specialization, command.Grade, command.TaskLanguage, command.Actor)
|
||||
if err != nil {
|
||||
return safeOperationError(err)
|
||||
}
|
||||
status := "already attested"
|
||||
if attestation.Created {
|
||||
status = "attested"
|
||||
}
|
||||
if _, err := fmt.Fprintf(output,
|
||||
"%s: category %s, opening %s, review %s, policy_version %d, by %s\n"+
|
||||
"note: synthetic demonstration only; categories are assigned only while ASSESSMENT_DEMO_CATEGORIES_ENABLED is true on this stand\n",
|
||||
status, attestation.Category, attestation.OpeningID, attestation.ReviewID, attestation.ProductPolicyVersion, attestation.ReviewedBy,
|
||||
); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeOperationError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, outbound.ErrAssessmentSelectionUnavailable), errors.Is(err, outbound.ErrAssessmentSelectionAmbiguous):
|
||||
return errors.New("no single current reviewed category matches the request")
|
||||
case errors.Is(err, domain.ErrInvalidAssessmentCategory):
|
||||
return errors.New("the request is invalid or the current policy is not the explicit demo_basic demonstration policy")
|
||||
default:
|
||||
return errors.New("category attestation failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package categoryattest
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
type attestorFake struct {
|
||||
attestation assessment.CategoryAttestation
|
||||
err error
|
||||
calls int
|
||||
command Command
|
||||
}
|
||||
|
||||
func (attestor *attestorFake) Attest(
|
||||
_ context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
actor string,
|
||||
) (assessment.CategoryAttestation, error) {
|
||||
attestor.calls++
|
||||
attestor.command = Command{Specialization: specialization, Grade: grade, TaskLanguage: language, Actor: actor}
|
||||
return attestor.attestation, attestor.err
|
||||
}
|
||||
|
||||
func TestParseRequiresATrackAndAnOperatorHandle(t *testing.T) {
|
||||
command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "intern", "--task-language", "go", "--actor", "operator:night"})
|
||||
if err != nil || command.Specialization != domain.SpecializationBackend || command.Grade != domain.GradeIntern ||
|
||||
command.TaskLanguage == nil || *command.TaskLanguage != domain.TaskLanguageGo || command.Actor != "operator:night" {
|
||||
t.Fatalf("Parse(valid) = %+v, %v", command, err)
|
||||
}
|
||||
if command, err := Parse([]string{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night"}); err != nil || command.TaskLanguage != nil {
|
||||
t.Fatalf("Parse(without language) = %+v, %v", command, err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
nil,
|
||||
{"list"},
|
||||
{"attest"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "alice"},
|
||||
{"attest", "--specialization", "chef", "--grade", "junior", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "lead", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--task-language", "cobol", "--actor", "operator:night"},
|
||||
{"attest", "--specialization", "backend", "--grade", "junior", "--actor", "operator:night", "extra"},
|
||||
} {
|
||||
if _, err := Parse(args); err == nil {
|
||||
t.Errorf("Parse(%v) accepted invalid arguments", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunValidatesArgumentsBeforeReadingTheEnvironment(t *testing.T) {
|
||||
lookup := func(string) (string, bool) {
|
||||
t.Fatal("environment read before arguments were validated")
|
||||
return "", false
|
||||
}
|
||||
if err := Run(context.Background(), []string{"attest"}, lookup, &bytes.Buffer{}); err == nil {
|
||||
t.Fatal("Run(invalid arguments) succeeded")
|
||||
}
|
||||
var noDatabase config.LookupEnv = func(string) (string, bool) { return "", false }
|
||||
err := Run(context.Background(), []string{"attest", "--specialization", "backend", "--grade", "intern", "--actor", "operator:night"}, noDatabase, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), "DATABASE_URL") {
|
||||
t.Fatalf("Run(no database) error = %v, want a DATABASE_URL message", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutePrintsIdentifiersAndTheSyntheticOnlyNote(t *testing.T) {
|
||||
attestor := &attestorFake{attestation: assessment.CategoryAttestation{
|
||||
ReviewID: uuid.New(), OpeningID: uuid.New(), Category: "backend-intern", ProductPolicyVersion: 2,
|
||||
ReviewedBy: "operator:night", Created: true,
|
||||
}}
|
||||
var output bytes.Buffer
|
||||
command := Command{Specialization: domain.SpecializationBackend, Grade: domain.GradeIntern, Actor: "operator:night"}
|
||||
if err := Execute(context.Background(), command, attestor, &output); err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(output.String(), "warning: synthetic demonstration categories are enabled by this attestation; never on a production stand") {
|
||||
t.Errorf("output does not start with the synthetic-only warning:\n%s", output.String())
|
||||
}
|
||||
for _, want := range []string{"attested: category backend-intern", attestor.attestation.ReviewID.String(), "policy_version 2", "by operator:night", "synthetic demonstration only", "ASSESSMENT_DEMO_CATEGORIES_ENABLED"} {
|
||||
if !strings.Contains(output.String(), want) {
|
||||
t.Errorf("output lacks %q:\n%s", want, output.String())
|
||||
}
|
||||
}
|
||||
attestor.attestation.Created = false
|
||||
output.Reset()
|
||||
if err := Execute(context.Background(), command, attestor, &output); err != nil || !strings.Contains(output.String(), "\nalready attested") {
|
||||
t.Fatalf("Execute(repeat) = %v, %q, want an already attested line", err, output.String())
|
||||
}
|
||||
if attestor.calls != 2 || attestor.command.Actor != "operator:night" || attestor.command.Grade != domain.GradeIntern {
|
||||
t.Fatalf("attestor calls/command = %d/%+v, want the parsed request", attestor.calls, attestor.command)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteMapsFailuresToSafeMessages(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{outbound.ErrAssessmentSelectionUnavailable, "no single current reviewed category"},
|
||||
{domain.ErrInvalidAssessmentCategory, "demo_basic"},
|
||||
{errors.New("pq: password authentication failed for user lincodex at 10.0.0.5"), "attestation failed"},
|
||||
} {
|
||||
err := Execute(context.Background(), Command{}, &attestorFake{err: test.err}, &bytes.Buffer{})
|
||||
if err == nil || !strings.Contains(err.Error(), test.want) || strings.Contains(err.Error(), "10.0.0.5") {
|
||||
t.Errorf("Execute(%v) error = %v, want a safe %q message", test.err, err, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -302,6 +302,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
continue
|
||||
}
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, schema)) {
|
||||
if searchResultMayReachCardBand(name, reached) {
|
||||
continue
|
||||
}
|
||||
if isPrivacySchema(reached) && reached != "AnonymousCardContent" && reached != "CardCategory" && reached != "CardField" && reached != "CardFieldSet" {
|
||||
t.Errorf("%s reaches the candidate-private schema %s", name, reached)
|
||||
}
|
||||
@@ -320,6 +323,9 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}, reached) {
|
||||
continue
|
||||
}
|
||||
if path == "/api/v1/organizations/{org_id}/matches" && searchResultMayReachCardBand("Match", reached) {
|
||||
continue
|
||||
}
|
||||
if isPrivacySchema(reached) {
|
||||
t.Errorf("%s reaches the candidate-private schema %s", path, reached)
|
||||
}
|
||||
@@ -332,6 +338,18 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// searchResultMayReachCardBand reports whether a match search schema reaches
|
||||
// one of the two coarse leaves that the anonymous card itself carries: the
|
||||
// salary compatibility (a compatible or not_compatible verdict, never an
|
||||
// amount) and the experience band (a coarse bucket, never a date). The search
|
||||
// contract reuses the card content, so its filters and results legitimately
|
||||
// name these leaves. Only match schemas get this allowance; no other
|
||||
// organization-visible schema may reach a privacy schema.
|
||||
func searchResultMayReachCardBand(schema, reached string) bool {
|
||||
return strings.HasPrefix(schema, "Match") &&
|
||||
(reached == "CandidateSalaryCompatibility" || reached == "CandidateExperienceBand")
|
||||
}
|
||||
|
||||
// The generated request DTOs carry only what the candidate may choose: no
|
||||
// consent identifier, time, interval, or policy version.
|
||||
func TestGeneratedPrivacyDTOsCarryNoServerOwnedFields(t *testing.T) {
|
||||
|
||||
@@ -36,6 +36,10 @@ var ownerCompanyOperations = map[apiadapter.OperationName]struct{}{
|
||||
apiadapter.GetOrganizationInvitationContactsOperation: {},
|
||||
apiadapter.WithdrawOrganizationInvitationOperation: {},
|
||||
apiadapter.RaiseOrganizationInvitationSalaryOperation: {},
|
||||
// The match search contract requires an active owner membership. The
|
||||
// operation has no handler yet; classifying it here keeps it closed to
|
||||
// every other role when the handler arrives.
|
||||
apiadapter.SearchOrganizationMatchesOperation: {},
|
||||
}
|
||||
|
||||
// NewCompanyContextMiddleware verifies every owner-scoped company operation
|
||||
|
||||
@@ -124,8 +124,8 @@ func TestCompanyContextOperationInventoryMatchesOpenAPI(t *testing.T) {
|
||||
if err := yaml.Unmarshal(data, &document); err != nil {
|
||||
t.Fatalf("decode OpenAPI bundle: %v", err)
|
||||
}
|
||||
if len(ownerCompanyOperations) != 14 {
|
||||
t.Fatalf("owner operation inventory has %d entries, want 14", len(ownerCompanyOperations))
|
||||
if len(ownerCompanyOperations) != 15 {
|
||||
t.Fatalf("owner operation inventory has %d entries, want 15", len(ownerCompanyOperations))
|
||||
}
|
||||
candidateExceptions := map[string]string{
|
||||
"HideOrganization": "/api/v1/me/privacy/hidden-organizations/{org_id}",
|
||||
|
||||
@@ -507,25 +507,40 @@ func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult)
|
||||
NextSteps: []api.AssessmentNextStep{}, Summary: result.Summary, DecidedAt: api.Timestamp(result.DecidedAt),
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
|
||||
return api.AssessmentResult{}, errors.New("real result kind is invalid")
|
||||
}
|
||||
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
|
||||
return api.AssessmentResult{}, errors.New("real result track or decision time is incomplete")
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
realResult, err := assessmentRealResultResponse(result)
|
||||
if err != nil {
|
||||
return api.AssessmentResult{}, err
|
||||
}
|
||||
if realResult.Type == api.AssessmentQualifiedResultAssessmentRealResult {
|
||||
return api.NewAssessmentQualifiedResultAssessmentResult(realResult.AssessmentQualifiedResult), nil
|
||||
}
|
||||
return api.NewAssessmentCorrectiveResultAssessmentResult(realResult.AssessmentCorrectiveResult), nil
|
||||
}
|
||||
|
||||
// assessmentRealResultResponse maps a completed root or corrective result. It
|
||||
// serves both the single result read and the owner's history, so the two never
|
||||
// describe the same stored result differently.
|
||||
func assessmentRealResultResponse(result assessmentusecase.AssessmentAttemptResult) (api.AssessmentRealResult, error) {
|
||||
if result.Attempt.Kind != domain.AssessmentAttemptKindRoot && result.Attempt.Kind != domain.AssessmentAttemptKindCorrective {
|
||||
return api.AssessmentRealResult{}, errors.New("real result kind is invalid")
|
||||
}
|
||||
if result.Attempt.Specialization == nil || result.Attempt.TargetGrade == nil || result.DecidedAt.IsZero() {
|
||||
return api.AssessmentRealResult{}, errors.New("real result track or decision time is incomplete")
|
||||
}
|
||||
fields, err := assessmentRealResultFields(result)
|
||||
if err != nil {
|
||||
return api.AssessmentRealResult{}, err
|
||||
}
|
||||
if result.Attempt.Kind == domain.AssessmentAttemptKindRoot {
|
||||
return api.NewAssessmentQualifiedResultAssessmentResult(api.AssessmentQualifiedResult{
|
||||
return api.NewAssessmentQualifiedResultAssessmentRealResult(api.AssessmentQualifiedResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentQualifiedResultKindRoot, Mode: api.AssessmentQualifiedResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
PreviousConfirmedGrade: fields.previousGrade, CategoryDecision: fields.categoryDecision,
|
||||
Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
@@ -533,16 +548,17 @@ func assessmentResultResponse(result assessmentusecase.AssessmentAttemptResult)
|
||||
}), nil
|
||||
}
|
||||
if result.Attempt.RootAttemptID == nil || result.Attempt.ChainDeadline == nil {
|
||||
return api.AssessmentResult{}, errors.New("corrective result chain is incomplete")
|
||||
return api.AssessmentRealResult{}, errors.New("corrective result chain is incomplete")
|
||||
}
|
||||
return api.NewAssessmentCorrectiveResultAssessmentResult(api.AssessmentCorrectiveResult{
|
||||
return api.NewAssessmentCorrectiveResultAssessmentRealResult(api.AssessmentCorrectiveResult{
|
||||
AttemptID: result.Attempt.ID.UUID(), Specialization: api.SpecializationCode(*result.Attempt.Specialization),
|
||||
TargetGrade: api.GradeCode(*result.Attempt.TargetGrade), RootAttemptID: fields.rootAttemptID,
|
||||
ChainDeadline: fields.chainDeadline, TaskLanguage: fields.taskLanguage,
|
||||
Kind: api.AssessmentCorrectiveResultKindCorrective, Mode: api.AssessmentCorrectiveResultMode(result.Attempt.Mode),
|
||||
Versions: assessmentResultVersions(result.Attempt), Outcome: fields.outcome,
|
||||
NotDeterminedReason: fields.reason, ConfirmedGrade: fields.confirmedGrade,
|
||||
PreviousConfirmedGrade: fields.previousGrade, Strength: fields.strength,
|
||||
PreviousConfirmedGrade: fields.previousGrade, CategoryDecision: fields.categoryDecision,
|
||||
Strength: fields.strength,
|
||||
CalibrationStatus: api.CalibrationStatusUncalibrated, Limitations: fields.limitations,
|
||||
Uncertainty: fields.uncertainty, BasicScore: fields.basicScore, Practices: []api.AssessmentPracticeResult{},
|
||||
Gaps: []api.AssessmentGap{}, Durations: api.AssessmentDurations{ItemsSeconds: assessmentItemsSeconds(result), PracticeSeconds: nilInt32()},
|
||||
@@ -558,10 +574,13 @@ type assessmentRealResultResponseFields struct {
|
||||
reason api.NilAssessmentNotDeterminedReason
|
||||
confirmedGrade api.NilGradeCode
|
||||
previousGrade api.NilGradeCode
|
||||
strength api.NilAssessmentStrength
|
||||
limitations []api.AssessmentLimitation
|
||||
uncertainty api.NilAssessmentUncertainty
|
||||
basicScore api.NilBasicScore
|
||||
// categoryDecision is absent for a legacy result stored before category
|
||||
// decisions existed; its grade is never inferred from the current state.
|
||||
categoryDecision api.OptAssessmentCategoryDecisionView
|
||||
strength api.NilAssessmentStrength
|
||||
limitations []api.AssessmentLimitation
|
||||
uncertainty api.NilAssessmentUncertainty
|
||||
basicScore api.NilBasicScore
|
||||
}
|
||||
|
||||
func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult) (assessmentRealResultResponseFields, error) {
|
||||
@@ -588,8 +607,7 @@ func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult
|
||||
} else {
|
||||
fields.reason.SetTo(api.AssessmentNotDeterminedReason(result.NotDeterminedReason))
|
||||
}
|
||||
fields.confirmedGrade.SetToNull()
|
||||
fields.previousGrade.SetToNull()
|
||||
setAssessmentCategoryFields(&fields, result.CategoryDecision)
|
||||
fields.strength.SetToNull()
|
||||
fields.uncertainty.SetToNull()
|
||||
if result.BasicScore == nil {
|
||||
@@ -605,6 +623,45 @@ func assessmentRealResultFields(result assessmentusecase.AssessmentAttemptResult
|
||||
return fields, nil
|
||||
}
|
||||
|
||||
// setAssessmentCategoryFields copies the stored category decision. A result
|
||||
// confirms its target grade only when a reviewed synthetic source accepted the
|
||||
// outcome (assigned, or unchanged because the grade was not higher); a passing
|
||||
// score without such a source claims no category.
|
||||
func setAssessmentCategoryFields(fields *assessmentRealResultResponseFields, decision *domain.AssessmentCategoryDecisionSnapshot) {
|
||||
fields.confirmedGrade.SetToNull()
|
||||
fields.previousGrade.SetToNull()
|
||||
if decision == nil {
|
||||
return
|
||||
}
|
||||
view := api.AssessmentCategoryDecisionView{Status: api.AssessmentCategoryDecisionViewStatus(decision.Status)}
|
||||
view.PreviousConfirmedGrade.SetToNull()
|
||||
view.CurrentConfirmedGrade.SetToNull()
|
||||
view.Method.SetToNull()
|
||||
view.Source.SetToNull()
|
||||
view.CalibrationStatus.SetToNull()
|
||||
if decision.PreviousGrade != nil {
|
||||
fields.previousGrade.SetTo(api.GradeCode(*decision.PreviousGrade))
|
||||
view.PreviousConfirmedGrade.SetTo(api.GradeCode(*decision.PreviousGrade))
|
||||
}
|
||||
if decision.CurrentGrade != nil {
|
||||
view.CurrentConfirmedGrade.SetTo(api.GradeCode(*decision.CurrentGrade))
|
||||
}
|
||||
if decision.Method != "" {
|
||||
view.Method.SetTo(api.AssessmentCategoryDecisionViewMethod(decision.Method))
|
||||
}
|
||||
if decision.Source != "" {
|
||||
view.Source.SetTo(api.AssessmentCategoryDecisionViewSource(decision.Source))
|
||||
}
|
||||
if decision.CalibrationStatus != "" {
|
||||
view.CalibrationStatus.SetTo(api.CalibrationStatus(decision.CalibrationStatus))
|
||||
}
|
||||
if (decision.Status == domain.AssessmentCategoryDecisionAssigned || decision.Status == domain.AssessmentCategoryDecisionUnchanged) &&
|
||||
decision.AttemptedGrade != nil {
|
||||
fields.confirmedGrade.SetTo(api.GradeCode(*decision.AttemptedGrade))
|
||||
}
|
||||
fields.categoryDecision.SetTo(view)
|
||||
}
|
||||
|
||||
func assessmentResultVersions(snapshot domain.AssessmentAttemptPublicSnapshot) api.AssessmentVersions {
|
||||
return api.AssessmentVersions{
|
||||
PolicyVersion: snapshot.PolicyVersion, BankVersion: api.AssessmentVersionLabel(snapshot.BankVersion),
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/adapter/primary/http/api"
|
||||
"lincodex/backend/internal/adapter/primary/http/problem"
|
||||
assessmentusecase "lincodex/backend/internal/usecase/assessment"
|
||||
)
|
||||
|
||||
// AssessmentResultOperations reads the candidate's immutable result history.
|
||||
// An employer has no operation here; the current category reaches an employer
|
||||
// only through the anonymous card.
|
||||
type AssessmentResultOperations interface {
|
||||
ListMyResults(ctx context.Context, userID uuid.UUID, cursor string, limit int32) (assessmentusecase.AssessmentResultHistoryPage, error)
|
||||
}
|
||||
|
||||
func (handler *Handler) ListMyAssessmentResults(
|
||||
ctx context.Context,
|
||||
params api.ListMyAssessmentResultsParams,
|
||||
) (api.ListMyAssessmentResultsRes, error) {
|
||||
if handler.assessment == nil {
|
||||
return handler.UnimplementedHandler.ListMyAssessmentResults(ctx, params)
|
||||
}
|
||||
return handler.assessment.ListMyAssessmentResults(ctx, params)
|
||||
}
|
||||
|
||||
// ListMyAssessmentResults serves the owner-only history. The operations of
|
||||
// AssessmentHandler provide it as an optional capability, like GetMyResult.
|
||||
func (handler *AssessmentHandler) ListMyAssessmentResults(
|
||||
ctx context.Context,
|
||||
params api.ListMyAssessmentResultsParams,
|
||||
) (api.ListMyAssessmentResultsRes, error) {
|
||||
const location = "AssessmentHandler.ListMyAssessmentResults"
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.ListMyAssessmentResultsUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
operations, ok := handler.operations.(AssessmentResultOperations)
|
||||
if !ok {
|
||||
return nil, errors.New(location + " - result history operation is unavailable")
|
||||
}
|
||||
// The generated validator has already bounded limit to the contract range.
|
||||
page, err := operations.ListMyResults(ctx, principal.UserID, params.Cursor.Or(""), params.Limit.Or(0))
|
||||
if err != nil {
|
||||
return assessmentResultsFailure(ctx, err)
|
||||
}
|
||||
items := make([]api.AssessmentRealResult, 0, len(page.Entries))
|
||||
for _, entry := range page.Entries {
|
||||
item, err := assessmentRealResultResponse(assessmentusecase.AssessmentAttemptResultFromHistoryEntry(entry))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - map stored result: %w", location, err)
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
next := api.NilString{}
|
||||
if page.NextCursor == "" {
|
||||
next.SetToNull()
|
||||
} else {
|
||||
next.SetTo(page.NextCursor)
|
||||
}
|
||||
return &api.AssessmentResultHistoryPageHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.AssessmentResultHistoryPage{Items: items, Page: api.PageInfo{HasMore: page.NextCursor != "", NextCursor: next}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func assessmentResultsFailure(ctx context.Context, err error) (api.ListMyAssessmentResultsRes, error) {
|
||||
switch {
|
||||
case errors.Is(err, assessmentusecase.ErrInvalidAssessmentResultHistoryRequest):
|
||||
return (*api.ListMyAssessmentResultsBadRequest)(&problem.InvalidField(ctx, api.ProblemFieldLocationQuery, "/cursor").Response), nil
|
||||
case errors.Is(err, assessmentusecase.ErrAttemptForbidden), errors.Is(err, assessmentusecase.ErrAttemptEmailNotVerified):
|
||||
return (*api.ListMyAssessmentResultsForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package v1
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
func gradePtr(grade domain.GradeCode) *domain.GradeCode { return &grade }
|
||||
|
||||
func TestAssessmentCategoryFieldsClaimAGradeOnlyForAReviewedConfirmation(t *testing.T) {
|
||||
specialization := domain.SpecializationBackend
|
||||
reviewed := func(status domain.AssessmentCategoryDecisionStatus, attempted domain.GradeCode, previous, current *domain.GradeCode) *domain.AssessmentCategoryDecisionSnapshot {
|
||||
return &domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(uuid.New()), Specialization: &specialization, AttemptedGrade: gradePtr(attempted),
|
||||
PreviousGrade: previous, CurrentGrade: current, Status: status,
|
||||
Method: domain.AssessmentCategoryDecisionDemoBasicPassMark, Source: domain.AssessmentCategorySourceSyntheticDemo,
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationUncalibrated, DecidedAt: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC),
|
||||
}
|
||||
}
|
||||
notEligible := &domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(uuid.New()), Specialization: &specialization, AttemptedGrade: gradePtr(domain.GradeJunior),
|
||||
PreviousGrade: gradePtr(domain.GradeIntern), CurrentGrade: gradePtr(domain.GradeIntern),
|
||||
Status: domain.AssessmentCategoryDecisionNotEligible,
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
decision *domain.AssessmentCategoryDecisionSnapshot
|
||||
wantConfirmed string
|
||||
wantPrevious string
|
||||
wantView bool
|
||||
}{
|
||||
{name: "legacy result without a decision", decision: nil},
|
||||
{name: "assigned", decision: reviewed(domain.AssessmentCategoryDecisionAssigned, domain.GradeJunior, gradePtr(domain.GradeIntern), gradePtr(domain.GradeJunior)),
|
||||
wantConfirmed: "junior", wantPrevious: "intern", wantView: true},
|
||||
{name: "unchanged", decision: reviewed(domain.AssessmentCategoryDecisionUnchanged, domain.GradeIntern, gradePtr(domain.GradeMiddle), gradePtr(domain.GradeMiddle)),
|
||||
wantConfirmed: "intern", wantPrevious: "middle", wantView: true},
|
||||
{name: "not confirmed keeps the previous grade", decision: reviewed(domain.AssessmentCategoryDecisionNotConfirmed, domain.GradeJunior, gradePtr(domain.GradeIntern), gradePtr(domain.GradeIntern)),
|
||||
wantPrevious: "intern", wantView: true},
|
||||
{name: "not eligible claims no grade", decision: notEligible, wantPrevious: "intern", wantView: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var fields assessmentRealResultResponseFields
|
||||
setAssessmentCategoryFields(&fields, test.decision)
|
||||
confirmed, confirmedSet := fields.confirmedGrade.Get()
|
||||
previous, previousSet := fields.previousGrade.Get()
|
||||
if (test.wantConfirmed == "") == confirmedSet || confirmedSet && string(confirmed) != test.wantConfirmed {
|
||||
t.Fatalf("confirmed_grade = %q (set %v), want %q", confirmed, confirmedSet, test.wantConfirmed)
|
||||
}
|
||||
if (test.wantPrevious == "") == previousSet || previousSet && string(previous) != test.wantPrevious {
|
||||
t.Fatalf("previous_confirmed_grade = %q (set %v), want %q", previous, previousSet, test.wantPrevious)
|
||||
}
|
||||
if fields.categoryDecision.IsSet() != test.wantView {
|
||||
t.Fatalf("category_decision present = %v, want %v", fields.categoryDecision.IsSet(), test.wantView)
|
||||
}
|
||||
if view, ok := fields.categoryDecision.Get(); ok && test.decision.Status == domain.AssessmentCategoryDecisionNotEligible {
|
||||
_, hasMethod := view.Method.Get()
|
||||
_, hasSource := view.Source.Get()
|
||||
if hasMethod || hasSource {
|
||||
t.Fatalf("not eligible view names a method or source: %+v", view)
|
||||
}
|
||||
}
|
||||
if view, ok := fields.categoryDecision.Get(); ok && string(view.Status) != string(test.decision.Status) {
|
||||
t.Fatalf("view status = %s, want %s", view.Status, test.decision.Status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -566,50 +566,20 @@ func (repository assessmentAttemptRepository) SaveResult(
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode result snapshot: %w", location, err)
|
||||
}
|
||||
var gradingPolicyID, openingID, trainingBindingID pgtype.UUID
|
||||
var openingHash, trainingHash []byte
|
||||
if validated.Pins.GradingPolicyVersionID != domain.PolicyVersionID(uuid.Nil) {
|
||||
gradingPolicyID = pgUUID(uuid.UUID(validated.Pins.GradingPolicyVersionID))
|
||||
}
|
||||
if validated.Pins.OpeningID != uuid.Nil {
|
||||
openingID = pgUUID(validated.Pins.OpeningID)
|
||||
}
|
||||
if validated.Pins.TrainingBindingID != uuid.Nil {
|
||||
trainingBindingID = pgUUID(validated.Pins.TrainingBindingID)
|
||||
}
|
||||
if validated.Pins.OpeningManifestHash != [sha256.Size]byte{} {
|
||||
openingHash = bytes.Clone(validated.Pins.OpeningManifestHash[:])
|
||||
}
|
||||
if validated.Pins.TrainingManifestHash != [sha256.Size]byte{} {
|
||||
trainingHash = bytes.Clone(validated.Pins.TrainingManifestHash[:])
|
||||
}
|
||||
var passMark pgtype.Int4
|
||||
var scoredItems, rawScore, passPoints pgtype.Int2
|
||||
if score := validated.BasicScore; score != nil {
|
||||
scoredItems, err = assessmentSmallint(validated.Rationale.ScoredItems)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - scored item count exceeds storage range: %w", location, err)
|
||||
}
|
||||
rawScore, err = assessmentSmallint(score.Points)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - raw score exceeds storage range: %w", location, err)
|
||||
}
|
||||
passPoints, err = assessmentSmallint(score.PassPoints)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - pass points exceed storage range: %w", location, err)
|
||||
}
|
||||
passMark = pgtype.Int4{Int32: validated.Rationale.PassMarkBasisPoints, Valid: true}
|
||||
columns, err := newAssessmentResultColumns(validated)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build result columns: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentAttemptResult(ctx, sqlc.InsertAssessmentAttemptResultParams{
|
||||
AttemptID: pgUUID(validated.Attempt.ID.UUID()), UserID: pgUUID(userID),
|
||||
ResultSnapshot: encoded, Kind: string(validated.Attempt.Kind), Mode: string(validated.Attempt.Mode),
|
||||
Outcome: string(validated.Outcome), ProductPolicyVersionID: pgUUID(uuid.UUID(validated.Pins.ProductPolicyVersionID)),
|
||||
ProductPolicyVersion: validated.Pins.ProductPolicyVersion, GradingPolicyVersionID: gradingPolicyID,
|
||||
OpeningID: openingID, OpeningManifestSha256: openingHash, TrainingBindingID: trainingBindingID,
|
||||
TrainingManifestSha256: trainingHash, BankVersion: validated.Pins.BankVersion,
|
||||
ProductPolicyVersion: validated.Pins.ProductPolicyVersion, GradingPolicyVersionID: columns.gradingPolicyID,
|
||||
OpeningID: columns.openingID, OpeningManifestSha256: columns.openingHash, TrainingBindingID: columns.trainingBindingID,
|
||||
TrainingManifestSha256: columns.trainingHash, BankVersion: validated.Pins.BankVersion,
|
||||
AlgorithmVersion: validated.Pins.AlgorithmVersion, RationaleRule: validated.Rationale.Rule,
|
||||
PassMarkBasisPoints: passMark, ScoredItems: scoredItems, RawScore: rawScore,
|
||||
PassPoints: passPoints, DecidedAt: pgTime(validated.DecidedAt),
|
||||
PassMarkBasisPoints: columns.passMark, ScoredItems: columns.scoredItems, RawScore: columns.rawScore,
|
||||
PassPoints: columns.passPoints, DecidedAt: pgTime(validated.DecidedAt),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert immutable result: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,467 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const maxAssessmentCategoryDecisionBytes = 4096
|
||||
|
||||
// assessmentCategoryDecisionDocument is the stored category extension of one
|
||||
// result. The key names are read by the migration constraints and triggers, so
|
||||
// they are part of the storage contract. Optional review fields are omitted,
|
||||
// not written as null, for decisions that have no reviewed source.
|
||||
type assessmentCategoryDecisionDocument struct {
|
||||
AttemptID uuid.UUID `json:"attempt_id"`
|
||||
BankCategory domain.AssessmentCategory `json:"bank_category"`
|
||||
Specialization domain.SpecializationCode `json:"specialization"`
|
||||
AttemptedGrade domain.GradeCode `json:"attempted_grade"`
|
||||
PreviousGrade *domain.GradeCode `json:"previous_grade"`
|
||||
CurrentGrade *domain.GradeCode `json:"current_grade"`
|
||||
Status domain.AssessmentCategoryDecisionStatus `json:"status"`
|
||||
Method domain.AssessmentCategoryDecisionMethod `json:"method,omitempty"`
|
||||
ProductPolicyVersionID uuid.UUID `json:"product_policy_version_id"`
|
||||
ProductPolicyVersion int32 `json:"product_policy_version"`
|
||||
GradingPolicyVersionID uuid.UUID `json:"grading_policy_version_id"`
|
||||
OpeningID uuid.UUID `json:"opening_id"`
|
||||
OpeningManifestHash string `json:"opening_manifest_sha256"`
|
||||
ReviewID *uuid.UUID `json:"review_id,omitempty"`
|
||||
Source domain.AssessmentCategorySource `json:"source,omitempty"`
|
||||
CalibrationStatus domain.AssessmentCategoryCalibrationStatus `json:"calibration_status,omitempty"`
|
||||
DecidedAt time.Time `json:"decided_at"`
|
||||
}
|
||||
|
||||
func marshalAssessmentCategoryDecision(decision domain.AssessmentCategoryDecisionSnapshot) ([]byte, error) {
|
||||
const location = "postgres.marshalAssessmentCategoryDecision"
|
||||
if decision.Specialization == nil || decision.AttemptedGrade == nil {
|
||||
return nil, fmt.Errorf("%s - decision has no track: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
document := assessmentCategoryDecisionDocument{
|
||||
AttemptID: decision.AttemptID.UUID(), BankCategory: decision.BankCategory,
|
||||
Specialization: *decision.Specialization, AttemptedGrade: *decision.AttemptedGrade,
|
||||
PreviousGrade: decision.PreviousGrade, CurrentGrade: decision.CurrentGrade,
|
||||
Status: decision.Status, Method: decision.Method,
|
||||
ProductPolicyVersionID: uuid.UUID(decision.ProductPolicyVersionID),
|
||||
ProductPolicyVersion: decision.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: uuid.UUID(decision.GradingPolicyVersionID),
|
||||
OpeningID: decision.OpeningID, OpeningManifestHash: hex.EncodeToString(decision.OpeningManifestHash[:]),
|
||||
Source: decision.Source, CalibrationStatus: decision.CalibrationStatus, DecidedAt: decision.DecidedAt.UTC(),
|
||||
}
|
||||
if decision.ReviewID != uuid.Nil {
|
||||
reviewID := decision.ReviewID
|
||||
document.ReviewID = &reviewID
|
||||
}
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil || len(encoded) > maxAssessmentCategoryDecisionBytes {
|
||||
return nil, fmt.Errorf("%s - encode bounded decision: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func decodeAssessmentCategoryDecision(encoded string) (domain.AssessmentCategoryDecisionSnapshot, error) {
|
||||
const location = "postgres.decodeAssessmentCategoryDecision"
|
||||
if encoded == "" || len(encoded) > maxAssessmentCategoryDecisionBytes {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - stored decision size is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader([]byte(encoded)))
|
||||
decoder.DisallowUnknownFields()
|
||||
var document assessmentCategoryDecisionDocument
|
||||
if err := decoder.Decode(&document); err != nil {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - decode stored decision: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - stored decision has trailing data: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
manifestHash, err := restoreOptionalAssessmentDigest(&document.OpeningManifestHash)
|
||||
if err != nil {
|
||||
return domain.AssessmentCategoryDecisionSnapshot{}, fmt.Errorf("%s - stored manifest digest is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
specialization, attempted := document.Specialization, document.AttemptedGrade
|
||||
snapshot := domain.AssessmentCategoryDecisionSnapshot{
|
||||
AttemptID: domain.AssessmentAttemptID(document.AttemptID), BankCategory: document.BankCategory,
|
||||
Specialization: &specialization, AttemptedGrade: &attempted,
|
||||
PreviousGrade: document.PreviousGrade, CurrentGrade: document.CurrentGrade,
|
||||
Status: document.Status, Method: document.Method,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(document.ProductPolicyVersionID),
|
||||
ProductPolicyVersion: document.ProductPolicyVersion,
|
||||
GradingPolicyVersionID: domain.PolicyVersionID(document.GradingPolicyVersionID),
|
||||
OpeningID: document.OpeningID, OpeningManifestHash: manifestHash,
|
||||
Source: document.Source, CalibrationStatus: document.CalibrationStatus, DecidedAt: document.DecidedAt,
|
||||
}
|
||||
if document.ReviewID != nil {
|
||||
snapshot.ReviewID = *document.ReviewID
|
||||
}
|
||||
return snapshot, nil
|
||||
}
|
||||
|
||||
// assessmentResultColumns are the denormalized, query-visible copies of a
|
||||
// result document that the table constraints compare with the snapshot.
|
||||
type assessmentResultColumns struct {
|
||||
gradingPolicyID, openingID, trainingBindingID pgtype.UUID
|
||||
openingHash, trainingHash []byte
|
||||
passMark pgtype.Int4
|
||||
scoredItems, rawScore, passPoints pgtype.Int2
|
||||
}
|
||||
|
||||
func newAssessmentResultColumns(result domain.AssessmentAttemptResultSnapshot) (assessmentResultColumns, error) {
|
||||
var columns assessmentResultColumns
|
||||
pins := result.Pins
|
||||
if pins.GradingPolicyVersionID != domain.PolicyVersionID(uuid.Nil) {
|
||||
columns.gradingPolicyID = pgUUID(uuid.UUID(pins.GradingPolicyVersionID))
|
||||
}
|
||||
if pins.OpeningID != uuid.Nil {
|
||||
columns.openingID = pgUUID(pins.OpeningID)
|
||||
}
|
||||
if pins.TrainingBindingID != uuid.Nil {
|
||||
columns.trainingBindingID = pgUUID(pins.TrainingBindingID)
|
||||
}
|
||||
if pins.OpeningManifestHash != [sha256.Size]byte{} {
|
||||
columns.openingHash = bytes.Clone(pins.OpeningManifestHash[:])
|
||||
}
|
||||
if pins.TrainingManifestHash != [sha256.Size]byte{} {
|
||||
columns.trainingHash = bytes.Clone(pins.TrainingManifestHash[:])
|
||||
}
|
||||
score := result.BasicScore
|
||||
if score == nil {
|
||||
return columns, nil
|
||||
}
|
||||
var err error
|
||||
if columns.scoredItems, err = assessmentSmallint(result.Rationale.ScoredItems); err != nil {
|
||||
return assessmentResultColumns{}, fmt.Errorf("scored item count exceeds storage range: %w", err)
|
||||
}
|
||||
if columns.rawScore, err = assessmentSmallint(score.Points); err != nil {
|
||||
return assessmentResultColumns{}, fmt.Errorf("raw score exceeds storage range: %w", err)
|
||||
}
|
||||
if columns.passPoints, err = assessmentSmallint(score.PassPoints); err != nil {
|
||||
return assessmentResultColumns{}, fmt.Errorf("pass points exceed storage range: %w", err)
|
||||
}
|
||||
columns.passMark = pgtype.Int4{Int32: result.Rationale.PassMarkBasisPoints, Valid: true}
|
||||
return columns, nil
|
||||
}
|
||||
|
||||
// SaveResultHistoryEntry stores a legacy v1 result unchanged or a v2 result
|
||||
// with its category decision in one immutable row.
|
||||
func (repository assessmentAttemptRepository) SaveResultHistoryEntry(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
entry domain.AssessmentAttemptResultHistoryEntry,
|
||||
) error {
|
||||
const location = "assessmentAttemptRepository.SaveResultHistoryEntry"
|
||||
if userID == uuid.Nil {
|
||||
return fmt.Errorf("%s - owner ID is required: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
validated, err := domain.RestoreAssessmentAttemptResultHistoryEntry(entry)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - result history entry is invalid: %w", location, err)
|
||||
}
|
||||
if validated.SchemaVersion == domain.AssessmentAttemptResultHistorySchemaV1 {
|
||||
if err := repository.SaveResult(ctx, userID, validated.Result); err != nil {
|
||||
return fmt.Errorf("%s - store legacy result: %w", location, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
result := validated.Result
|
||||
encodedResult, err := marshalAssessmentAttemptResultDocument(result)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode result snapshot: %w", location, err)
|
||||
}
|
||||
encodedDecision, err := marshalAssessmentCategoryDecision(*validated.CategoryDecision)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - encode category decision: %w", location, err)
|
||||
}
|
||||
columns, err := newAssessmentResultColumns(result)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - build result columns: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
if err := repository.queries.InsertAssessmentAttemptResultV2(ctx, sqlc.InsertAssessmentAttemptResultV2Params{
|
||||
AttemptID: pgUUID(result.Attempt.ID.UUID()), UserID: pgUUID(userID),
|
||||
ResultSnapshot: encodedResult, CategoryDecision: encodedDecision,
|
||||
CurrentConfirmedGrade: pgNullableAttemptText(validated.CurrentConfirmedGrade),
|
||||
Kind: string(result.Attempt.Kind), Mode: string(result.Attempt.Mode),
|
||||
Outcome: string(result.Outcome),
|
||||
ProductPolicyVersionID: pgUUID(uuid.UUID(result.Pins.ProductPolicyVersionID)),
|
||||
ProductPolicyVersion: result.Pins.ProductPolicyVersion, GradingPolicyVersionID: columns.gradingPolicyID,
|
||||
OpeningID: columns.openingID, OpeningManifestSha256: columns.openingHash,
|
||||
BankVersion: result.Pins.BankVersion, AlgorithmVersion: result.Pins.AlgorithmVersion,
|
||||
RationaleRule: result.Rationale.Rule, PassMarkBasisPoints: columns.passMark,
|
||||
ScoredItems: columns.scoredItems, RawScore: columns.rawScore, PassPoints: columns.passPoints,
|
||||
DecidedAt: pgTime(result.DecidedAt),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert immutable category result: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetResultHistoryEntry returns the exact stored record; a v1 row carries no
|
||||
// category data and none is reconstructed from the current category.
|
||||
func (repository assessmentAttemptRepository) GetResultHistoryEntry(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
attemptID domain.AssessmentAttemptID,
|
||||
) (domain.AssessmentAttemptResultHistoryEntry, error) {
|
||||
const location = "assessmentAttemptRepository.GetResultHistoryEntry"
|
||||
if userID == uuid.Nil || attemptID.IsZero() {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - owner and attempt IDs are required: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
row, err := repository.queries.GetAssessmentAttemptResultHistoryEntry(ctx, sqlc.GetAssessmentAttemptResultHistoryEntryParams{
|
||||
UserID: pgUUID(userID), AttemptID: pgUUID(attemptID.UUID()),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - immutable result is missing: %w", location, outbound.ErrAssessmentAttemptResultNotFound)
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - select immutable result: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
entry, err := restoreStoredResultHistoryEntry(row.SchemaVersion, row.ResultSnapshot, row.CategoryDecision, row.CurrentConfirmedGrade)
|
||||
if err != nil || entry.Result.Attempt.ID != attemptID {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, fmt.Errorf("%s - stored result is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return entry, nil
|
||||
}
|
||||
|
||||
// ListCandidateAssessmentResults reads one owner-scoped keyset page. It asks
|
||||
// for one row more than limit and reports that row as HasMore.
|
||||
func (repository assessmentAttemptRepository) ListCandidateAssessmentResults(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
cursor *outbound.AssessmentAttemptResultCursor,
|
||||
limit int32,
|
||||
) (outbound.AssessmentAttemptResultPage, error) {
|
||||
const location = "assessmentAttemptRepository.ListCandidateAssessmentResults"
|
||||
if userID == uuid.Nil || limit < 1 || cursor != nil && (cursor.AttemptID.IsZero() || cursor.DecidedAt.IsZero()) {
|
||||
return outbound.AssessmentAttemptResultPage{}, fmt.Errorf("%s - owner, limit or cursor is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
params := sqlc.ListCandidateAssessmentResultsParams{UserID: pgUUID(userID), LimitCount: limit}
|
||||
if cursor != nil {
|
||||
params.CursorDecidedAt = pgTime(cursor.DecidedAt)
|
||||
params.CursorAttemptID = pgUUID(cursor.AttemptID.UUID())
|
||||
}
|
||||
rows, err := repository.queries.ListCandidateAssessmentResults(ctx, params)
|
||||
if err != nil {
|
||||
return outbound.AssessmentAttemptResultPage{}, fmt.Errorf("%s - select result history: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
page := outbound.AssessmentAttemptResultPage{HasMore: len(rows) > int(limit)}
|
||||
if page.HasMore {
|
||||
rows = rows[:limit]
|
||||
}
|
||||
page.Records = make([]outbound.AssessmentAttemptResultRecord, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
entry, err := restoreStoredResultHistoryEntry(row.SchemaVersion, row.ResultSnapshot, row.CategoryDecision, row.CurrentConfirmedGrade)
|
||||
if err != nil || !row.AttemptID.Valid || !row.UserID.Valid || entry.Result.Attempt.ID.UUID() != row.AttemptID.Bytes {
|
||||
return outbound.AssessmentAttemptResultPage{}, fmt.Errorf("%s - stored result is invalid: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
page.Records = append(page.Records, outbound.AssessmentAttemptResultRecord{UserID: row.UserID.Bytes, Entry: entry})
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func restoreStoredResultHistoryEntry(
|
||||
schemaVersion int16,
|
||||
resultSnapshot, categoryDecision string,
|
||||
currentGrade pgtype.Text,
|
||||
) (domain.AssessmentAttemptResultHistoryEntry, error) {
|
||||
result, err := decodeAssessmentAttemptResultDocument([]byte(resultSnapshot))
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, err
|
||||
}
|
||||
entry := domain.AssessmentAttemptResultHistoryEntry{SchemaVersion: int32(schemaVersion), Result: result}
|
||||
if categoryDecision != "" {
|
||||
decision, err := decodeAssessmentCategoryDecision(categoryDecision)
|
||||
if err != nil {
|
||||
return domain.AssessmentAttemptResultHistoryEntry{}, err
|
||||
}
|
||||
entry.CategoryDecision = &decision
|
||||
}
|
||||
if currentGrade.Valid {
|
||||
grade := domain.GradeCode(currentGrade.String)
|
||||
entry.CurrentConfirmedGrade = &grade
|
||||
}
|
||||
return domain.RestoreAssessmentAttemptResultHistoryEntry(entry)
|
||||
}
|
||||
|
||||
// LockCandidateCategory serializes category upgrades of one candidate and
|
||||
// specialization for the rest of the transaction.
|
||||
func (repository assessmentAttemptRepository) LockCandidateCategory(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
) error {
|
||||
const location = "assessmentAttemptRepository.LockCandidateCategory"
|
||||
if candidateID == uuid.Nil || !specialization.IsKnown() {
|
||||
return fmt.Errorf("%s - candidate scope is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
if err := repository.queries.LockCandidateAssessmentCategory(ctx, sqlc.LockCandidateAssessmentCategoryParams{
|
||||
CandidateID: candidateID.String(), Specialization: string(specialization),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - lock candidate category: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository assessmentAttemptRepository) GetCandidateCategory(
|
||||
ctx context.Context,
|
||||
candidateID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
) (domain.CandidateAssessmentCategory, bool, error) {
|
||||
const location = "assessmentAttemptRepository.GetCandidateCategory"
|
||||
if candidateID == uuid.Nil || !specialization.IsKnown() {
|
||||
return domain.CandidateAssessmentCategory{}, false, fmt.Errorf("%s - candidate scope is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
row, err := repository.queries.GetCandidateAssessmentCategory(ctx, sqlc.GetCandidateAssessmentCategoryParams{
|
||||
CandidateID: pgUUID(candidateID), Specialization: string(specialization),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.CandidateAssessmentCategory{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.CandidateAssessmentCategory{}, false, fmt.Errorf("%s - select current category: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
category, err := restoreCandidateAssessmentCategory(row)
|
||||
if err != nil {
|
||||
return domain.CandidateAssessmentCategory{}, false, fmt.Errorf("%s - stored category is invalid: %w", location, err)
|
||||
}
|
||||
return category, true, nil
|
||||
}
|
||||
|
||||
func restoreCandidateAssessmentCategory(row sqlc.CandidateAssessmentCategory) (domain.CandidateAssessmentCategory, error) {
|
||||
manifestHash, err := assessmentManifestHash(row.OpeningManifestSha256)
|
||||
if err != nil || !row.CandidateID.Valid || !row.SourceAttemptID.Valid || !row.SourceReviewID.Valid ||
|
||||
!row.ProductPolicyVersionID.Valid || !row.OpeningID.Valid || !row.AssignedAt.Valid {
|
||||
return domain.CandidateAssessmentCategory{}, domain.ErrInvalidAssessmentCategory
|
||||
}
|
||||
return domain.RestoreCandidateAssessmentCategory(domain.CandidateAssessmentCategorySnapshot{
|
||||
CandidateID: row.CandidateID.Bytes, Specialization: domain.SpecializationCode(row.Specialization),
|
||||
Grade: domain.GradeCode(row.Grade), SourceAttemptID: domain.AssessmentAttemptID(row.SourceAttemptID.Bytes),
|
||||
SourceReviewID: row.SourceReviewID.Bytes,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes),
|
||||
ProductPolicyVersion: row.ProductPolicyVersion, OpeningID: row.OpeningID.Bytes,
|
||||
OpeningManifestHash: manifestHash, Source: domain.AssessmentCategorySource(row.Source),
|
||||
CalibrationStatus: domain.AssessmentCategoryCalibrationStatus(row.CalibrationStatus),
|
||||
AssignedAt: row.AssignedAt.Time,
|
||||
})
|
||||
}
|
||||
|
||||
func assessmentManifestHash(value []byte) ([sha256.Size]byte, error) {
|
||||
var hash [sha256.Size]byte
|
||||
if len(value) != sha256.Size {
|
||||
return hash, domain.ErrInvalidAssessmentCategory
|
||||
}
|
||||
copy(hash[:], value)
|
||||
return hash, nil
|
||||
}
|
||||
|
||||
// GetSyntheticCategoryReview finds the attestation that matches the exact
|
||||
// opening, manifest, product policy and the opening's grading policy.
|
||||
func (repository assessmentAttemptRepository) GetSyntheticCategoryReview(
|
||||
ctx context.Context,
|
||||
openingID uuid.UUID,
|
||||
category domain.AssessmentCategory,
|
||||
openingManifestHash [32]byte,
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
gradingPolicyID domain.PolicyVersionID,
|
||||
) (domain.AssessmentSyntheticCategoryReview, bool, error) {
|
||||
const location = "assessmentAttemptRepository.GetSyntheticCategoryReview"
|
||||
if openingID == uuid.Nil || openingManifestHash == [32]byte{} || productPolicyID.IsZero() ||
|
||||
productPolicyVersion <= 0 || gradingPolicyID.IsZero() {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - review pins are invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
row, err := repository.queries.GetSyntheticCategoryReview(ctx, sqlc.GetSyntheticCategoryReviewParams{
|
||||
OpeningID: pgUUID(openingID), Category: string(category),
|
||||
OpeningManifestSha256: bytes.Clone(openingManifestHash[:]),
|
||||
ProductPolicyVersionID: pgUUID(productPolicyID.UUID()), ProductPolicyVersion: productPolicyVersion,
|
||||
GradingPolicyVersionID: pgUUID(gradingPolicyID.UUID()),
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - select review: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
manifestHash, err := assessmentManifestHash(row.OpeningManifestSha256)
|
||||
if err != nil || !row.ID.Valid || !row.OpeningID.Valid || !row.ProductPolicyVersionID.Valid || !row.ReviewedAt.Valid {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - stored review is invalid: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
review, err := domain.RestoreAssessmentSyntheticCategoryReview(domain.AssessmentSyntheticCategoryReviewSnapshot{
|
||||
ID: row.ID.Bytes, OpeningID: row.OpeningID.Bytes, Category: domain.AssessmentCategory(row.Category),
|
||||
Source: domain.AssessmentCategorySource(row.Source), OpeningManifestHash: manifestHash,
|
||||
ProductPolicyVersionID: domain.PolicyVersionID(row.ProductPolicyVersionID.Bytes),
|
||||
ProductPolicyVersion: row.ProductPolicyVersion, ReviewedBy: domain.AssessmentOperator(row.ReviewedBy),
|
||||
ReviewedAt: row.ReviewedAt.Time,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.AssessmentSyntheticCategoryReview{}, false, fmt.Errorf("%s - restore review: %w", location, err)
|
||||
}
|
||||
return review, true, nil
|
||||
}
|
||||
|
||||
// CreateSyntheticCategoryReview stores one attestation. The database stamps the
|
||||
// review time and re-checks the opening, manifest and policy it names. A
|
||||
// duplicate of the same exact source stores nothing and reports false.
|
||||
func (repository assessmentAttemptRepository) CreateSyntheticCategoryReview(
|
||||
ctx context.Context,
|
||||
review domain.AssessmentSyntheticCategoryReview,
|
||||
) (bool, error) {
|
||||
const location = "assessmentAttemptRepository.CreateSyntheticCategoryReview"
|
||||
if review.IsZero() {
|
||||
return false, fmt.Errorf("%s - review is required: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
snapshot := review.Snapshot()
|
||||
rows, err := repository.queries.InsertSyntheticCategoryReview(ctx, sqlc.InsertSyntheticCategoryReviewParams{
|
||||
ID: pgUUID(snapshot.ID), OpeningID: pgUUID(snapshot.OpeningID), Category: string(snapshot.Category),
|
||||
Source: string(snapshot.Source), OpeningManifestSha256: bytes.Clone(snapshot.OpeningManifestHash[:]),
|
||||
ProductPolicyVersionID: pgUUID(snapshot.ProductPolicyVersionID.UUID()),
|
||||
ProductPolicyVersion: snapshot.ProductPolicyVersion, ReviewedBy: string(snapshot.ReviewedBy),
|
||||
ReviewedAt: pgTime(snapshot.ReviewedAt),
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s - insert review: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
return rows == 1, nil
|
||||
}
|
||||
|
||||
// SaveCandidateAssessmentCategory writes a strict upgrade. Zero affected rows
|
||||
// mean the stored grade is not lower than the new one, which the caller's
|
||||
// category lock should have made impossible.
|
||||
func (repository assessmentAttemptRepository) SaveCandidateAssessmentCategory(
|
||||
ctx context.Context,
|
||||
category domain.CandidateAssessmentCategory,
|
||||
) error {
|
||||
const location = "assessmentAttemptRepository.SaveCandidateAssessmentCategory"
|
||||
if category.IsZero() {
|
||||
return fmt.Errorf("%s - category is required: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
snapshot := category.Snapshot()
|
||||
rows, err := repository.queries.SaveCandidateAssessmentCategory(ctx, sqlc.SaveCandidateAssessmentCategoryParams{
|
||||
CandidateID: pgUUID(snapshot.CandidateID), Specialization: string(snapshot.Specialization),
|
||||
Grade: string(snapshot.Grade), SourceAttemptID: pgUUID(snapshot.SourceAttemptID.UUID()),
|
||||
SourceReviewID: pgUUID(snapshot.SourceReviewID),
|
||||
ProductPolicyVersionID: pgUUID(snapshot.ProductPolicyVersionID.UUID()),
|
||||
ProductPolicyVersion: snapshot.ProductPolicyVersion, OpeningID: pgUUID(snapshot.OpeningID),
|
||||
OpeningManifestSha256: bytes.Clone(snapshot.OpeningManifestHash[:]), Source: string(snapshot.Source),
|
||||
CalibrationStatus: string(snapshot.CalibrationStatus), AssignedAt: pgTime(snapshot.AssignedAt),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - upsert current category: %w", location, mapAssessmentAttemptError(err))
|
||||
}
|
||||
if rows != 1 {
|
||||
return fmt.Errorf("%s - category was not upgraded: %w", location, outbound.ErrAssessmentCategoryConflict)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -184,21 +184,9 @@ func notificationInboxOptionalUUID(value *uuid.UUID) pgtype.UUID {
|
||||
return pgUUID(*value)
|
||||
}
|
||||
|
||||
func notificationInboxEntryFromRow(row sqlc.GetNotificationInboxEventRow) (domain.NotificationInboxEntry, error) {
|
||||
return restoreNotificationInboxEntryRow(
|
||||
row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType,
|
||||
row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt,
|
||||
)
|
||||
}
|
||||
|
||||
func notificationInboxEntryFromListRow(row sqlc.ListNotificationInboxEventsRow) (domain.NotificationInboxEntry, error) {
|
||||
return restoreNotificationInboxEntryRow(
|
||||
row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType,
|
||||
row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt,
|
||||
)
|
||||
}
|
||||
|
||||
func notificationInboxEntryFromReadRow(row sqlc.MarkNotificationInboxEventReadRow) (domain.NotificationInboxEntry, error) {
|
||||
// The three inbox queries select every column of the table in table order, so
|
||||
// sqlc returns the shared model type for all of them.
|
||||
func notificationInboxEntryFromRow(row sqlc.NotificationInboxEvent) (domain.NotificationInboxEntry, error) {
|
||||
return restoreNotificationInboxEntryRow(
|
||||
row.RecipientUserID, row.EventID, row.OrganizationID, row.EventType,
|
||||
row.SchemaVersion, row.SourceType, row.SourceID, row.OccurredAt, row.ReadAt,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -55,6 +56,7 @@ type privacyCohortCandidate struct {
|
||||
claims []domain.StoredProfileClaim
|
||||
acknowledgements []domain.ProfileParallelPeriodAcknowledgement
|
||||
workFormats []domain.QuestionnaireWorkFormat
|
||||
categories []domain.CandidateViewConfirmedCategoryInput
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
@@ -88,7 +90,7 @@ func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
current = privacyCohortCandidate{}
|
||||
}
|
||||
if current.id == uuid.Nil {
|
||||
current, err = newPrivacyCohortCandidate(candidateID, row.Fields, row.WorkFormats, row.ParallelPeriodAcknowledgements)
|
||||
current, err = newPrivacyCohortCandidate(candidateID, row.Fields, row.WorkFormats, row.ParallelPeriodAcknowledgements, row.ConfirmedCategories)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
|
||||
}
|
||||
@@ -114,6 +116,7 @@ func newPrivacyCohortCandidate(
|
||||
fieldCodes []string,
|
||||
workFormatCodes []string,
|
||||
acknowledgementsValue any,
|
||||
confirmedCategoriesValue any,
|
||||
) (privacyCohortCandidate, error) {
|
||||
fields := make([]domain.CardField, 0, len(fieldCodes))
|
||||
for _, code := range fieldCodes {
|
||||
@@ -135,12 +138,47 @@ func newPrivacyCohortCandidate(
|
||||
if err := json.Unmarshal(acknowledgementsJSON, &acknowledgements); err != nil {
|
||||
return privacyCohortCandidate{}, fmt.Errorf("invalid overlap acknowledgements: %w", domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
categories, err := privacyCohortConfirmedCategories(confirmedCategoriesValue)
|
||||
if err != nil {
|
||||
return privacyCohortCandidate{}, err
|
||||
}
|
||||
return privacyCohortCandidate{
|
||||
id: candidateID, fields: fieldSet, workFormats: workFormats,
|
||||
acknowledgements: acknowledgements,
|
||||
acknowledgements: acknowledgements, categories: categories,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// privacyCohortCategoryStrength is the card strength of a demonstration
|
||||
// category. The synthetic demo source has no adaptive confirmation, so no
|
||||
// category is reported as strong.
|
||||
const privacyCohortCategoryStrength = domain.CandidateViewStrengthStandard
|
||||
|
||||
// privacyCohortConfirmedCategories reads the current categories selected by
|
||||
// the cohort query: only a specialization and a grade of each, never the
|
||||
// attempt, score, policy, or review that produced it.
|
||||
func privacyCohortConfirmedCategories(value any) ([]domain.CandidateViewConfirmedCategoryInput, error) {
|
||||
encoded, err := privacyCohortEncodedJSONBytes(value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid confirmed categories: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
var stored []struct {
|
||||
Specialization domain.SpecializationCode `json:"specialization"`
|
||||
Grade domain.GradeCode `json:"grade"`
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(encoded))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&stored); err != nil {
|
||||
return nil, fmt.Errorf("invalid confirmed categories: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
categories := make([]domain.CandidateViewConfirmedCategoryInput, 0, len(stored))
|
||||
for _, category := range stored {
|
||||
categories = append(categories, domain.CandidateViewConfirmedCategoryInput{
|
||||
Specialization: category.Specialization, Grade: category.Grade, Strength: privacyCohortCategoryStrength,
|
||||
})
|
||||
}
|
||||
return categories, nil
|
||||
}
|
||||
|
||||
func privacyCohortStoredClaim(row sqlc.ListVisibleCandidateViewSourcesRow) (domain.StoredProfileClaim, error) {
|
||||
value, err := privacyCohortJSONBytes(row.SafeValue)
|
||||
if err != nil {
|
||||
@@ -166,7 +204,7 @@ func buildPrivacyCohortSource(candidate privacyCohortCandidate) (domain.Candidat
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("validate safe profile claims: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
return domain.NewCandidateViewSource(
|
||||
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), nil,
|
||||
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), candidate.categories,
|
||||
candidate.workFormats, nil,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ func buildPreviewCandidateViewSource(
|
||||
if got, err := privacyCohortUUID(first.UserID); err != nil || got != candidateID {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - projection identity is invalid: %w", location, domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
candidate, err := newPrivacyCohortCandidate(candidateID, first.Fields, first.WorkFormats, first.ParallelPeriodAcknowledgements)
|
||||
candidate, err := newPrivacyCohortCandidate(candidateID, first.Fields, first.WorkFormats, first.ParallelPeriodAcknowledgements, first.ConfirmedCategories)
|
||||
if err != nil {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate input: %w", location, err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: assessment_results.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getAssessmentAttemptResultHistoryEntry = `-- name: GetAssessmentAttemptResultHistoryEntry :one
|
||||
SELECT schema_version, result_snapshot::text,
|
||||
COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = $1 AND attempt_id = $2
|
||||
`
|
||||
|
||||
type GetAssessmentAttemptResultHistoryEntryParams struct {
|
||||
UserID pgtype.UUID
|
||||
AttemptID pgtype.UUID
|
||||
}
|
||||
|
||||
type GetAssessmentAttemptResultHistoryEntryRow struct {
|
||||
SchemaVersion int16
|
||||
ResultSnapshot string
|
||||
CategoryDecision string
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
}
|
||||
|
||||
// Returns both immutable result versions. NULL category fields identify a
|
||||
// legacy v1 record and must not be reconstructed from current state.
|
||||
func (q *Queries) GetAssessmentAttemptResultHistoryEntry(ctx context.Context, arg GetAssessmentAttemptResultHistoryEntryParams) (GetAssessmentAttemptResultHistoryEntryRow, error) {
|
||||
row := q.db.QueryRow(ctx, getAssessmentAttemptResultHistoryEntry, arg.UserID, arg.AttemptID)
|
||||
var i GetAssessmentAttemptResultHistoryEntryRow
|
||||
err := row.Scan(
|
||||
&i.SchemaVersion,
|
||||
&i.ResultSnapshot,
|
||||
&i.CategoryDecision,
|
||||
&i.CurrentConfirmedGrade,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getCandidateAssessmentCategory = `-- name: GetCandidateAssessmentCategory :one
|
||||
SELECT candidate_id, specialization, grade, source_attempt_id, source_review_id,
|
||||
product_policy_version_id, product_policy_version, grading_policy_version_id,
|
||||
opening_id, opening_manifest_sha256, source, calibration_status, assigned_at
|
||||
FROM candidate_assessment_categories
|
||||
WHERE candidate_id = $1 AND specialization = $2
|
||||
`
|
||||
|
||||
type GetCandidateAssessmentCategoryParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
Specialization string
|
||||
}
|
||||
|
||||
func (q *Queries) GetCandidateAssessmentCategory(ctx context.Context, arg GetCandidateAssessmentCategoryParams) (CandidateAssessmentCategory, error) {
|
||||
row := q.db.QueryRow(ctx, getCandidateAssessmentCategory, arg.CandidateID, arg.Specialization)
|
||||
var i CandidateAssessmentCategory
|
||||
err := row.Scan(
|
||||
&i.CandidateID,
|
||||
&i.Specialization,
|
||||
&i.Grade,
|
||||
&i.SourceAttemptID,
|
||||
&i.SourceReviewID,
|
||||
&i.ProductPolicyVersionID,
|
||||
&i.ProductPolicyVersion,
|
||||
&i.GradingPolicyVersionID,
|
||||
&i.OpeningID,
|
||||
&i.OpeningManifestSha256,
|
||||
&i.Source,
|
||||
&i.CalibrationStatus,
|
||||
&i.AssignedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getSyntheticCategoryReview = `-- name: GetSyntheticCategoryReview :one
|
||||
SELECT review.id, review.opening_id, review.category, review.source,
|
||||
review.opening_manifest_sha256, review.product_policy_version_id,
|
||||
review.product_policy_version, review.reviewed_by, review.reviewed_at
|
||||
FROM assessment_synthetic_category_reviews AS review
|
||||
JOIN assessment_category_openings AS opening ON opening.id = review.opening_id
|
||||
WHERE review.opening_id = $1
|
||||
AND review.category = $2
|
||||
AND review.source = 'synthetic_demo'
|
||||
AND review.opening_manifest_sha256 = $3
|
||||
AND review.product_policy_version_id = $4
|
||||
AND review.product_policy_version = $5
|
||||
AND opening.policy_version_id = $6
|
||||
`
|
||||
|
||||
type GetSyntheticCategoryReviewParams struct {
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
OpeningManifestSha256 []byte
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetSyntheticCategoryReview(ctx context.Context, arg GetSyntheticCategoryReviewParams) (AssessmentSyntheticCategoryReview, error) {
|
||||
row := q.db.QueryRow(ctx, getSyntheticCategoryReview,
|
||||
arg.OpeningID,
|
||||
arg.Category,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.GradingPolicyVersionID,
|
||||
)
|
||||
var i AssessmentSyntheticCategoryReview
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OpeningID,
|
||||
&i.Category,
|
||||
&i.Source,
|
||||
&i.OpeningManifestSha256,
|
||||
&i.ProductPolicyVersionID,
|
||||
&i.ProductPolicyVersion,
|
||||
&i.ReviewedBy,
|
||||
&i.ReviewedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertAssessmentAttemptResultV2 = `-- name: InsertAssessmentAttemptResultV2 :exec
|
||||
INSERT INTO assessment_attempt_results (
|
||||
attempt_id, user_id, result_snapshot, schema_version, category_decision,
|
||||
current_confirmed_grade, kind, mode, outcome, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, rationale_rule, pass_mark_basis_points,
|
||||
scored_items, raw_score, pass_points, decided_at
|
||||
) VALUES (
|
||||
$1, $2, $3, 2,
|
||||
$4::jsonb, $5,
|
||||
$6, $7, $8, $9,
|
||||
$10, $11, $12,
|
||||
$13, NULL, NULL, $14,
|
||||
$15, $16, $17,
|
||||
$18, $19, $20, $21
|
||||
)
|
||||
`
|
||||
|
||||
type InsertAssessmentAttemptResultV2Params struct {
|
||||
AttemptID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
ResultSnapshot []byte
|
||||
CategoryDecision []byte
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
Kind string
|
||||
Mode string
|
||||
Outcome string
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
BankVersion string
|
||||
AlgorithmVersion string
|
||||
RationaleRule string
|
||||
PassMarkBasisPoints pgtype.Int4
|
||||
ScoredItems pgtype.Int2
|
||||
RawScore pgtype.Int2
|
||||
PassPoints pgtype.Int2
|
||||
DecidedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Stores the category decision and current grade captured at real-attempt
|
||||
// finalization. The base result document remains its original v1 shape.
|
||||
func (q *Queries) InsertAssessmentAttemptResultV2(ctx context.Context, arg InsertAssessmentAttemptResultV2Params) error {
|
||||
_, err := q.db.Exec(ctx, insertAssessmentAttemptResultV2,
|
||||
arg.AttemptID,
|
||||
arg.UserID,
|
||||
arg.ResultSnapshot,
|
||||
arg.CategoryDecision,
|
||||
arg.CurrentConfirmedGrade,
|
||||
arg.Kind,
|
||||
arg.Mode,
|
||||
arg.Outcome,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.GradingPolicyVersionID,
|
||||
arg.OpeningID,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.BankVersion,
|
||||
arg.AlgorithmVersion,
|
||||
arg.RationaleRule,
|
||||
arg.PassMarkBasisPoints,
|
||||
arg.ScoredItems,
|
||||
arg.RawScore,
|
||||
arg.PassPoints,
|
||||
arg.DecidedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSyntheticCategoryReview = `-- name: InsertSyntheticCategoryReview :execrows
|
||||
INSERT INTO assessment_synthetic_category_reviews (
|
||||
id, opening_id, category, source, opening_manifest_sha256,
|
||||
product_policy_version_id, product_policy_version, reviewed_by, reviewed_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4,
|
||||
$5, $6,
|
||||
$7, $8, $9
|
||||
)
|
||||
ON CONFLICT ON CONSTRAINT assessment_synthetic_category_reviews_exact_source_key DO NOTHING
|
||||
`
|
||||
|
||||
type InsertSyntheticCategoryReviewParams struct {
|
||||
ID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
Source string
|
||||
OpeningManifestSha256 []byte
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
ReviewedBy string
|
||||
ReviewedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// The application accepts only a validated immutable review snapshot. The
|
||||
// trigger independently checks the source opening, manifest and policy. A
|
||||
// concurrent or repeated attestation of the same exact source inserts nothing,
|
||||
// and the caller reads the stored one.
|
||||
func (q *Queries) InsertSyntheticCategoryReview(ctx context.Context, arg InsertSyntheticCategoryReviewParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertSyntheticCategoryReview,
|
||||
arg.ID,
|
||||
arg.OpeningID,
|
||||
arg.Category,
|
||||
arg.Source,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.ReviewedBy,
|
||||
arg.ReviewedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const listCandidateAssessmentResults = `-- name: ListCandidateAssessmentResults :many
|
||||
SELECT attempt_id, user_id, schema_version, result_snapshot::text,
|
||||
COALESCE(category_decision::text, '')::text AS category_decision, current_confirmed_grade, decided_at
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = $1
|
||||
AND kind IN ('root', 'corrective')
|
||||
AND ($2::timestamptz IS NULL OR
|
||||
(decided_at, attempt_id) <
|
||||
($2::timestamptz, $3::uuid))
|
||||
ORDER BY decided_at DESC, attempt_id DESC
|
||||
LIMIT $4::integer + 1
|
||||
`
|
||||
|
||||
type ListCandidateAssessmentResultsParams struct {
|
||||
UserID pgtype.UUID
|
||||
CursorDecidedAt pgtype.Timestamptz
|
||||
CursorAttemptID pgtype.UUID
|
||||
LimitCount int32
|
||||
}
|
||||
|
||||
type ListCandidateAssessmentResultsRow struct {
|
||||
AttemptID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
SchemaVersion int16
|
||||
ResultSnapshot string
|
||||
CategoryDecision string
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
DecidedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// The caller validates and signs an opaque owner-bound cursor. This query
|
||||
// applies the keyset to the same stable order and fetches one extra row.
|
||||
func (q *Queries) ListCandidateAssessmentResults(ctx context.Context, arg ListCandidateAssessmentResultsParams) ([]ListCandidateAssessmentResultsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateAssessmentResults,
|
||||
arg.UserID,
|
||||
arg.CursorDecidedAt,
|
||||
arg.CursorAttemptID,
|
||||
arg.LimitCount,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateAssessmentResultsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateAssessmentResultsRow
|
||||
if err := rows.Scan(
|
||||
&i.AttemptID,
|
||||
&i.UserID,
|
||||
&i.SchemaVersion,
|
||||
&i.ResultSnapshot,
|
||||
&i.CategoryDecision,
|
||||
&i.CurrentConfirmedGrade,
|
||||
&i.DecidedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockCandidateAssessmentCategory = `-- name: LockCandidateAssessmentCategory :exec
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(
|
||||
'lincodex.assessment.category:candidate:' || $1::text || ':' || $2::text,
|
||||
0
|
||||
))
|
||||
`
|
||||
|
||||
type LockCandidateAssessmentCategoryParams struct {
|
||||
CandidateID string
|
||||
Specialization string
|
||||
}
|
||||
|
||||
// Acquired after C3, candidate/specialization scope, and attempt row locks.
|
||||
// This independent lock serializes current category upgrades for one scope.
|
||||
func (q *Queries) LockCandidateAssessmentCategory(ctx context.Context, arg LockCandidateAssessmentCategoryParams) error {
|
||||
_, err := q.db.Exec(ctx, lockCandidateAssessmentCategory, arg.CandidateID, arg.Specialization)
|
||||
return err
|
||||
}
|
||||
|
||||
const saveCandidateAssessmentCategory = `-- name: SaveCandidateAssessmentCategory :execrows
|
||||
INSERT INTO candidate_assessment_categories (
|
||||
candidate_id, specialization, grade, source_attempt_id, source_review_id,
|
||||
product_policy_version_id, product_policy_version, grading_policy_version_id,
|
||||
opening_id, opening_manifest_sha256, source, calibration_status, assigned_at
|
||||
) VALUES (
|
||||
$1, $2, $3, $4,
|
||||
$5, $6, $7,
|
||||
(
|
||||
SELECT opening.policy_version_id
|
||||
FROM assessment_category_openings AS opening
|
||||
WHERE opening.id = $8
|
||||
),
|
||||
$8, $9,
|
||||
$10, $11, $12
|
||||
)
|
||||
ON CONFLICT (candidate_id, specialization) DO UPDATE SET
|
||||
grade = EXCLUDED.grade,
|
||||
source_attempt_id = EXCLUDED.source_attempt_id,
|
||||
source_review_id = EXCLUDED.source_review_id,
|
||||
product_policy_version_id = EXCLUDED.product_policy_version_id,
|
||||
product_policy_version = EXCLUDED.product_policy_version,
|
||||
grading_policy_version_id = EXCLUDED.grading_policy_version_id,
|
||||
opening_id = EXCLUDED.opening_id,
|
||||
opening_manifest_sha256 = EXCLUDED.opening_manifest_sha256,
|
||||
source = EXCLUDED.source,
|
||||
calibration_status = EXCLUDED.calibration_status,
|
||||
assigned_at = EXCLUDED.assigned_at
|
||||
WHERE CASE candidate_assessment_categories.grade
|
||||
WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END
|
||||
< CASE EXCLUDED.grade
|
||||
WHEN 'intern' THEN 0 WHEN 'junior' THEN 1 WHEN 'middle' THEN 2 WHEN 'senior' THEN 3 ELSE -1 END
|
||||
`
|
||||
|
||||
type SaveCandidateAssessmentCategoryParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
Specialization string
|
||||
Grade string
|
||||
SourceAttemptID pgtype.UUID
|
||||
SourceReviewID pgtype.UUID
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
Source string
|
||||
CalibrationStatus string
|
||||
AssignedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Only strict grade upgrades replace the current row. The trigger enforces
|
||||
// the same monotonic rule as a final guard against adapter mistakes. The
|
||||
// grading policy is read from the immutable opening, and the guard trigger
|
||||
// compares it with the policy captured in the assigned result.
|
||||
func (q *Queries) SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, saveCandidateAssessmentCategory,
|
||||
arg.CandidateID,
|
||||
arg.Specialization,
|
||||
arg.Grade,
|
||||
arg.SourceAttemptID,
|
||||
arg.SourceReviewID,
|
||||
arg.ProductPolicyVersionID,
|
||||
arg.ProductPolicyVersion,
|
||||
arg.OpeningID,
|
||||
arg.OpeningManifestSha256,
|
||||
arg.Source,
|
||||
arg.CalibrationStatus,
|
||||
arg.AssignedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -134,6 +134,8 @@ type AssessmentAttemptResult struct {
|
||||
RawScore pgtype.Int2
|
||||
PassPoints pgtype.Int2
|
||||
DecidedAt pgtype.Timestamptz
|
||||
CategoryDecision []byte
|
||||
CurrentConfirmedGrade pgtype.Text
|
||||
}
|
||||
|
||||
type AssessmentAttemptReview struct {
|
||||
@@ -240,6 +242,18 @@ type AssessmentSignalNoticeAcknowledgement struct {
|
||||
AcknowledgedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentSyntheticCategoryReview struct {
|
||||
ID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
Category string
|
||||
Source string
|
||||
OpeningManifestSha256 []byte
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
ReviewedBy string
|
||||
ReviewedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AssessmentTrainingBankBinding struct {
|
||||
ID pgtype.UUID
|
||||
Category string
|
||||
@@ -260,6 +274,22 @@ type AssessmentTrainingBankBindingFamily struct {
|
||||
ContentSha256 []byte
|
||||
}
|
||||
|
||||
type CandidateAssessmentCategory struct {
|
||||
CandidateID pgtype.UUID
|
||||
Specialization string
|
||||
Grade string
|
||||
SourceAttemptID pgtype.UUID
|
||||
SourceReviewID pgtype.UUID
|
||||
ProductPolicyVersionID pgtype.UUID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID pgtype.UUID
|
||||
OpeningID pgtype.UUID
|
||||
OpeningManifestSha256 []byte
|
||||
Source string
|
||||
CalibrationStatus string
|
||||
AssignedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CandidateCardAccessEvent struct {
|
||||
ID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
@@ -584,6 +614,18 @@ type Membership struct {
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type NotificationInboxEvent struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
SourceType string
|
||||
SourceID pgtype.UUID
|
||||
OccurredAt pgtype.Timestamptz
|
||||
ReadAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type Organization struct {
|
||||
ID pgtype.UUID
|
||||
Name string
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: notification_inbox.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const getNotificationInboxEvent = `-- name: GetNotificationInboxEvent :one
|
||||
SELECT
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at,
|
||||
read_at
|
||||
FROM notification_inbox_events
|
||||
WHERE recipient_user_id = $1
|
||||
AND event_id = $2
|
||||
`
|
||||
|
||||
type GetNotificationInboxEventParams struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
}
|
||||
|
||||
// Read the existing row after a duplicate insert so the repository can reject
|
||||
// an event ID whose immutable metadata changed on redelivery.
|
||||
func (q *Queries) GetNotificationInboxEvent(ctx context.Context, arg GetNotificationInboxEventParams) (NotificationInboxEvent, error) {
|
||||
row := q.db.QueryRow(ctx, getNotificationInboxEvent, arg.RecipientUserID, arg.EventID)
|
||||
var i NotificationInboxEvent
|
||||
err := row.Scan(
|
||||
&i.RecipientUserID,
|
||||
&i.EventID,
|
||||
&i.OrganizationID,
|
||||
&i.EventType,
|
||||
&i.SchemaVersion,
|
||||
&i.SourceType,
|
||||
&i.SourceID,
|
||||
&i.OccurredAt,
|
||||
&i.ReadAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertNotificationInboxEvent = `-- name: InsertNotificationInboxEvent :execrows
|
||||
INSERT INTO notification_inbox_events (
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at
|
||||
) VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8
|
||||
)
|
||||
ON CONFLICT (recipient_user_id, event_id) DO NOTHING
|
||||
`
|
||||
|
||||
type InsertNotificationInboxEventParams struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
EventType string
|
||||
SchemaVersion int32
|
||||
SourceType string
|
||||
SourceID pgtype.UUID
|
||||
OccurredAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// Store one recipient's reference to a delivered invitation event. The
|
||||
// unique key absorbs at-least-once redelivery without copying event content.
|
||||
func (q *Queries) InsertNotificationInboxEvent(ctx context.Context, arg InsertNotificationInboxEventParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, insertNotificationInboxEvent,
|
||||
arg.RecipientUserID,
|
||||
arg.EventID,
|
||||
arg.OrganizationID,
|
||||
arg.EventType,
|
||||
arg.SchemaVersion,
|
||||
arg.SourceType,
|
||||
arg.SourceID,
|
||||
arg.OccurredAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const listNotificationInboxEvents = `-- name: ListNotificationInboxEvents :many
|
||||
SELECT
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at,
|
||||
read_at
|
||||
FROM notification_inbox_events
|
||||
WHERE recipient_user_id = $1
|
||||
AND (
|
||||
$2::uuid IS NULL
|
||||
OR organization_id = $2::uuid
|
||||
)
|
||||
AND (
|
||||
$3::timestamptz IS NULL
|
||||
OR (occurred_at, event_id) < (
|
||||
$3::timestamptz,
|
||||
$4::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY occurred_at DESC, event_id DESC
|
||||
LIMIT $5
|
||||
`
|
||||
|
||||
type ListNotificationInboxEventsParams struct {
|
||||
RecipientUserID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
AfterOccurredAt pgtype.Timestamptz
|
||||
AfterEventID pgtype.UUID
|
||||
PageLimit int32
|
||||
}
|
||||
|
||||
// List only the authenticated recipient's rows, optionally narrowed to one
|
||||
// organization context. The caller resolves current source visibility before
|
||||
// returning content.
|
||||
func (q *Queries) ListNotificationInboxEvents(ctx context.Context, arg ListNotificationInboxEventsParams) ([]NotificationInboxEvent, error) {
|
||||
rows, err := q.db.Query(ctx, listNotificationInboxEvents,
|
||||
arg.RecipientUserID,
|
||||
arg.OrganizationID,
|
||||
arg.AfterOccurredAt,
|
||||
arg.AfterEventID,
|
||||
arg.PageLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []NotificationInboxEvent
|
||||
for rows.Next() {
|
||||
var i NotificationInboxEvent
|
||||
if err := rows.Scan(
|
||||
&i.RecipientUserID,
|
||||
&i.EventID,
|
||||
&i.OrganizationID,
|
||||
&i.EventType,
|
||||
&i.SchemaVersion,
|
||||
&i.SourceType,
|
||||
&i.SourceID,
|
||||
&i.OccurredAt,
|
||||
&i.ReadAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markNotificationInboxEventRead = `-- name: MarkNotificationInboxEventRead :one
|
||||
UPDATE notification_inbox_events
|
||||
SET read_at = COALESCE(read_at, $1::timestamptz)
|
||||
WHERE recipient_user_id = $2
|
||||
AND organization_id = $3
|
||||
AND event_id = $4
|
||||
RETURNING
|
||||
recipient_user_id,
|
||||
event_id,
|
||||
organization_id,
|
||||
event_type,
|
||||
schema_version,
|
||||
source_type,
|
||||
source_id,
|
||||
occurred_at,
|
||||
read_at
|
||||
`
|
||||
|
||||
type MarkNotificationInboxEventReadParams struct {
|
||||
ReadAt pgtype.Timestamptz
|
||||
RecipientUserID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
EventID pgtype.UUID
|
||||
}
|
||||
|
||||
// Persist the first read time under exact recipient and organization scope.
|
||||
// Repeated calls preserve the original read timestamp.
|
||||
func (q *Queries) MarkNotificationInboxEventRead(ctx context.Context, arg MarkNotificationInboxEventReadParams) (NotificationInboxEvent, error) {
|
||||
row := q.db.QueryRow(ctx, markNotificationInboxEventRead,
|
||||
arg.ReadAt,
|
||||
arg.RecipientUserID,
|
||||
arg.OrganizationID,
|
||||
arg.EventID,
|
||||
)
|
||||
var i NotificationInboxEvent
|
||||
err := row.Scan(
|
||||
&i.RecipientUserID,
|
||||
&i.EventID,
|
||||
&i.OrganizationID,
|
||||
&i.EventType,
|
||||
&i.SchemaVersion,
|
||||
&i.SourceType,
|
||||
&i.SourceID,
|
||||
&i.OccurredAt,
|
||||
&i.ReadAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -53,7 +53,18 @@ SELECT
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
) AS parallel_period_acknowledgements,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object('specialization', category.specialization, 'grade', category.grade)
|
||||
ORDER BY category.specialization
|
||||
)::text
|
||||
FROM candidate_assessment_categories AS category
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
@@ -82,6 +93,7 @@ type ListVisibleCandidateViewSourcesRow struct {
|
||||
ConfirmedAt pgtype.Timestamptz
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
ConfirmedCategories interface{}
|
||||
}
|
||||
|
||||
// Organization-facing anonymous candidate projection inputs. The calling
|
||||
@@ -90,7 +102,9 @@ type ListVisibleCandidateViewSourcesRow struct {
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts.
|
||||
// employer names, summaries, and imported excerpts. The only assessment data
|
||||
// is the current category (specialization and grade) of the separate current
|
||||
// category table; it carries no attempt, score, review, policy, or history.
|
||||
func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error) {
|
||||
rows, err := q.db.Query(ctx, listVisibleCandidateViewSources, organizationID)
|
||||
if err != nil {
|
||||
@@ -113,6 +127,7 @@ func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizat
|
||||
&i.ConfirmedAt,
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
&i.ConfirmedCategories,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -267,7 +282,18 @@ SELECT
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
) AS parallel_period_acknowledgements,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object('specialization', category.specialization, 'grade', category.grade)
|
||||
ORDER BY category.specialization
|
||||
)::text
|
||||
FROM candidate_assessment_categories AS category
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
@@ -291,6 +317,7 @@ type ReadCandidateViewSourceForPreviewRow struct {
|
||||
ConfirmedAt pgtype.Timestamptz
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
ConfirmedCategories interface{}
|
||||
}
|
||||
|
||||
// Read the candidate's current private projection inputs after the caller
|
||||
@@ -318,6 +345,7 @@ func (q *Queries) ReadCandidateViewSourceForPreview(ctx context.Context, candida
|
||||
&i.ConfirmedAt,
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
&i.ConfirmedCategories,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -227,6 +227,9 @@ type Querier interface {
|
||||
GetAssessmentAttemptKindForCandidate(ctx context.Context, arg GetAssessmentAttemptKindForCandidateParams) (string, error)
|
||||
// Reads a result only for the owning candidate.
|
||||
GetAssessmentAttemptResult(ctx context.Context, arg GetAssessmentAttemptResultParams) (string, error)
|
||||
// Returns both immutable result versions. NULL category fields identify a
|
||||
// legacy v1 record and must not be reconstructed from current state.
|
||||
GetAssessmentAttemptResultHistoryEntry(ctx context.Context, arg GetAssessmentAttemptResultHistoryEntryParams) (GetAssessmentAttemptResultHistoryEntryRow, error)
|
||||
GetAssessmentAttemptReview(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentAttemptReviewRow, error)
|
||||
// Reads an active real attempt without taking the write lock used by create.
|
||||
// The availability GET never expires or otherwise mutates this row.
|
||||
@@ -245,6 +248,7 @@ type Querier interface {
|
||||
GetAssessmentSignalNoticeAcknowledgement(ctx context.Context, arg GetAssessmentSignalNoticeAcknowledgementParams) (pgtype.Timestamptz, error)
|
||||
// Read only the receipt associated with the reserved idempotency scope.
|
||||
GetAssessmentSignalOutcome(ctx context.Context, scopeHash []byte) (GetAssessmentSignalOutcomeRow, error)
|
||||
GetCandidateAssessmentCategory(ctx context.Context, arg GetCandidateAssessmentCategoryParams) (CandidateAssessmentCategory, error)
|
||||
// Reads one hiding of the candidate with the current name of the
|
||||
// organization.
|
||||
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
|
||||
@@ -297,6 +301,9 @@ type Querier interface {
|
||||
GetMailQuotaUsage(ctx context.Context, arg GetMailQuotaUsageParams) ([]GetMailQuotaUsageRow, error)
|
||||
// Reads the membership of one account in one organization, in any state.
|
||||
GetMembership(ctx context.Context, arg GetMembershipParams) (Membership, error)
|
||||
// Read the existing row after a duplicate insert so the repository can reject
|
||||
// an event ID whose immutable metadata changed on redelivery.
|
||||
GetNotificationInboxEvent(ctx context.Context, arg GetNotificationInboxEventParams) (NotificationInboxEvent, error)
|
||||
// Reads only the historical result. It intentionally does not join the live
|
||||
// organization or membership, whose profile and state may have since changed.
|
||||
GetOrganizationCreationResult(ctx context.Context, scopeHash []byte) ([]byte, error)
|
||||
@@ -334,6 +341,7 @@ type Querier interface {
|
||||
// selects no token hash. A missing binding or token row gives NULL token
|
||||
// columns.
|
||||
GetServiceMailState(ctx context.Context, id pgtype.UUID) (GetServiceMailStateRow, error)
|
||||
GetSyntheticCategoryReview(ctx context.Context, arg GetSyntheticCategoryReviewParams) (AssessmentSyntheticCategoryReview, error)
|
||||
GetUnrevokedConsentRecordByVersion(ctx context.Context, arg GetUnrevokedConsentRecordByVersionParams) (GetUnrevokedConsentRecordByVersionRow, error)
|
||||
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
|
||||
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
|
||||
@@ -347,6 +355,9 @@ type Querier interface {
|
||||
// Stores one immutable candidate-visible result with the decision rationale
|
||||
// and source versions used by its finalized attempt.
|
||||
InsertAssessmentAttemptResult(ctx context.Context, arg InsertAssessmentAttemptResultParams) error
|
||||
// Stores the category decision and current grade captured at real-attempt
|
||||
// finalization. The base result document remains its original v1 shape.
|
||||
InsertAssessmentAttemptResultV2(ctx context.Context, arg InsertAssessmentAttemptResultV2Params) error
|
||||
// Stores an explicit mapping against a newly-created immutable opening. The
|
||||
// insert trigger checks the opening, declared reviewer, current policy, and
|
||||
// live coverage; the adapter supplies the fingerprint of the published set.
|
||||
@@ -439,6 +450,9 @@ type Querier interface {
|
||||
InsertMailQuotaReservation(ctx context.Context, arg InsertMailQuotaReservationParams) error
|
||||
InsertMailRequest(ctx context.Context, arg InsertMailRequestParams) error
|
||||
InsertMembership(ctx context.Context, arg InsertMembershipParams) error
|
||||
// Store one recipient's reference to a delivered invitation event. The
|
||||
// unique key absorbs at-least-once redelivery without copying event content.
|
||||
InsertNotificationInboxEvent(ctx context.Context, arg InsertNotificationInboxEventParams) (int64, error)
|
||||
// Stores a new organization with the verification level that the domain
|
||||
// gave it. The deferred constraint organizations_owner_required fails the
|
||||
// transaction at commit unless an active owner membership was inserted in
|
||||
@@ -483,6 +497,11 @@ type Querier interface {
|
||||
InsertSupportCaseCreateOutcome(ctx context.Context, arg InsertSupportCaseCreateOutcomeParams) error
|
||||
InsertSupportCaseEvent(ctx context.Context, arg InsertSupportCaseEventParams) error
|
||||
InsertSupportCaseRequestEvent(ctx context.Context, arg InsertSupportCaseRequestEventParams) error
|
||||
// The application accepts only a validated immutable review snapshot. The
|
||||
// trigger independently checks the source opening, manifest and policy. A
|
||||
// concurrent or repeated attestation of the same exact source inserts nothing,
|
||||
// and the caller reads the stored one.
|
||||
InsertSyntheticCategoryReview(ctx context.Context, arg InsertSyntheticCategoryReviewParams) (int64, error)
|
||||
InsertUser(ctx context.Context, arg InsertUserParams) error
|
||||
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
|
||||
// Read the latest serialized event so a temporarily regressing application
|
||||
@@ -523,6 +542,9 @@ type Querier interface {
|
||||
ListAssessmentOriginMarks(ctx context.Context, attemptID pgtype.UUID) ([]AssessmentAttemptOriginMark, error)
|
||||
// Reads the exact family membership pinned by a training binding.
|
||||
ListAssessmentTrainingBindingFamilies(ctx context.Context, bindingID pgtype.UUID) ([]ListAssessmentTrainingBindingFamiliesRow, error)
|
||||
// The caller validates and signs an opaque owner-bound cursor. This query
|
||||
// applies the keyset to the same stable order and fetches one extra row.
|
||||
ListCandidateAssessmentResults(ctx context.Context, arg ListCandidateAssessmentResultsParams) ([]ListCandidateAssessmentResultsRow, error)
|
||||
// Lists only the current candidate's own access history. It deliberately
|
||||
// omits the employee, requested card fields, and search context. The privacy
|
||||
// read adapter resolves an organization name only through this recorded
|
||||
@@ -559,6 +581,10 @@ type Querier interface {
|
||||
// fingerprint; stale bindings are omitted fail-closed.
|
||||
ListCurrentSpecializationAvailability(ctx context.Context) ([]ListCurrentSpecializationAvailabilityRow, error)
|
||||
ListDeliveryAttempts(ctx context.Context, deliveryID pgtype.UUID) ([]DeliveryAttempt, error)
|
||||
// List only the authenticated recipient's rows, optionally narrowed to one
|
||||
// organization context. The caller resolves current source visibility before
|
||||
// returning content.
|
||||
ListNotificationInboxEvents(ctx context.Context, arg ListNotificationInboxEventsParams) ([]NotificationInboxEvent, error)
|
||||
// Read one bounded newest-first page of current needs. Both the organization
|
||||
// scope and the tuple cursor are applied before the limit.
|
||||
ListOrganizationNeeds(ctx context.Context, arg ListOrganizationNeedsParams) ([]ListOrganizationNeedsRow, error)
|
||||
@@ -579,7 +605,9 @@ type Querier interface {
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts.
|
||||
// employer names, summaries, and imported excerpts. The only assessment data
|
||||
// is the current category (specialization and grade) of the separate current
|
||||
// category table; it carries no attempt, score, review, policy, or history.
|
||||
ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error)
|
||||
// Locks the organization first and then the active membership, using the
|
||||
// same order as organization profile writes. A company operation keeps both
|
||||
@@ -604,6 +632,9 @@ type Querier interface {
|
||||
// a hide either commits before the later visibility recheck or waits for the
|
||||
// read transaction to finish.
|
||||
LockCandidateAccountForView(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
|
||||
// Acquired after C3, candidate/specialization scope, and attempt row locks.
|
||||
// This independent lock serializes current category upgrades for one scope.
|
||||
LockCandidateAssessmentCategory(ctx context.Context, arg LockCandidateAssessmentCategoryParams) error
|
||||
// Locks the candidate's published row only when it refers to a C2 record
|
||||
// revoked by this transaction. The setting remains linked to that immutable
|
||||
// record; ReadCandidatePublication computes the effective closed state and
|
||||
@@ -685,6 +716,9 @@ type Querier interface {
|
||||
// gate stops admitting sends until the window resets or an operator raises
|
||||
// the limit. The caller holds the row lock.
|
||||
MarkMailQuotaExhausted(ctx context.Context, arg MarkMailQuotaExhaustedParams) (int64, error)
|
||||
// Persist the first read time under exact recipient and organization scope.
|
||||
// Repeated calls preserve the original read timestamp.
|
||||
MarkNotificationInboxEventRead(ctx context.Context, arg MarkNotificationInboxEventReadParams) (NotificationInboxEvent, error)
|
||||
// Marks the events that the broker acknowledged. The relay passes only IDs
|
||||
// whose rows its own transaction locked, so the statement never waits and the
|
||||
// count equals the number of distinct IDs.
|
||||
@@ -835,6 +869,11 @@ type Querier interface {
|
||||
RevokeContactConsentRecords(ctx context.Context, arg RevokeContactConsentRecordsParams) ([]RevokeContactConsentRecordsRow, error)
|
||||
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
|
||||
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
|
||||
// Only strict grade upgrades replace the current row. The trigger enforces
|
||||
// the same monotonic rule as a final guard against adapter mistakes. The
|
||||
// grading policy is read from the immutable opening, and the guard trigger
|
||||
// compares it with the policy captured in the assigned result.
|
||||
SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error)
|
||||
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
|
||||
// Stores the immutable domain snapshot of a successful create command. The
|
||||
// generic idempotency row and this result are committed with the organization
|
||||
|
||||
@@ -32,6 +32,10 @@ func newAssessmentHandler(
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("bootstrap.newAssessmentHandler - create pool: %w", err)
|
||||
}
|
||||
if settings.AssessmentDemoCategoriesEnabled {
|
||||
logger.Warn("synthetic demonstration categories are enabled; never on a production stand",
|
||||
slog.String("setting", "ASSESSMENT_DEMO_CATEGORIES_ENABLED"))
|
||||
}
|
||||
transactor := postgres.NewTransactor(pool)
|
||||
service, err := assessment.NewAttemptServiceWithCategorySettings(
|
||||
transactor,
|
||||
|
||||
@@ -292,40 +292,36 @@ func newRealCategoryDecision(
|
||||
}
|
||||
|
||||
func eligibleSyntheticCategoryPolicy(policy PolicyVersion, result AssessmentAttemptResultSnapshot) bool {
|
||||
product := policy.Policy()
|
||||
return policy.Kind() == PolicyKindDemo && policy.Key() == ProductPolicyKey &&
|
||||
sameAssessmentPolicy(product.Assessment, DemoProductPolicyV2().Assessment) &&
|
||||
return completeDemoBasicPolicy(policy) &&
|
||||
result.Attempt.Mode == AssessmentAttemptModeDemoBasic && result.Rationale.Rule == assessmentResultRuleBasicPassMark &&
|
||||
int32(product.Assessment.Attempt.BasicPassMark) == result.Rationale.PassMarkBasisPoints &&
|
||||
int32(policy.Policy().Assessment.Attempt.BasicPassMark) == result.Rationale.PassMarkBasisPoints &&
|
||||
(result.Outcome == AssessmentAttemptOutcomeConfirmed || result.Outcome == AssessmentAttemptOutcomeNotConfirmed)
|
||||
}
|
||||
|
||||
func sameAssessmentPolicy(left, right AssessmentPolicy) bool {
|
||||
return sameAssessmentPolicyRules(left, right) &&
|
||||
sameOptionalAssessmentAttemptPolicy(left.Attempt, right.Attempt) &&
|
||||
sameOptionalAssessmentTrainingPolicy(left.Training, right.Training)
|
||||
}
|
||||
|
||||
func sameAssessmentPolicyRules(left, right AssessmentPolicy) bool {
|
||||
return left.Calibration == right.Calibration && left.SameGradeRetryAfter == right.SameGradeRetryAfter &&
|
||||
left.MaxAttemptsPerWindow == right.MaxAttemptsPerWindow && left.AttemptWindow == right.AttemptWindow &&
|
||||
left.PromotionMinInterval == right.PromotionMinInterval && left.ConfirmationThreshold == right.ConfirmationThreshold &&
|
||||
left.HighStrengthThreshold == right.HighStrengthThreshold && left.PracticeRequired == right.PracticeRequired &&
|
||||
left.StopRule == right.StopRule
|
||||
}
|
||||
|
||||
func sameOptionalAssessmentAttemptPolicy(left, right *AssessmentAttemptPolicy) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
// completeDemoBasicPolicy reports whether a stored policy version is a demo
|
||||
// policy whose assessment section is complete for the demo_basic mode: explicit
|
||||
// attempt and training settings and an uncalibrated method. The stored version
|
||||
// has already passed policy validation, so its own pass mark is the threshold;
|
||||
// no fixed value is compared.
|
||||
func completeDemoBasicPolicy(policy PolicyVersion) bool {
|
||||
if policy.IsZero() || policy.Key() != ProductPolicyKey || policy.Kind() != PolicyKindDemo {
|
||||
return false
|
||||
}
|
||||
return *left == *right
|
||||
assessment := policy.Policy().Assessment
|
||||
return assessment.Calibration == AssessmentCalibrationUncalibratedInitial &&
|
||||
assessment.Attempt != nil && assessment.Attempt.RealMode == AssessmentRealModeDemoBasic &&
|
||||
assessment.Training != nil
|
||||
}
|
||||
|
||||
func sameOptionalAssessmentTrainingPolicy(left, right *AssessmentTrainingPolicy) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
// ValidateSyntheticCategoryPolicy reports whether a policy version is a
|
||||
// complete demonstration policy with the demo_basic mode, the only kind of
|
||||
// policy under which a synthetic demonstration category may be attested.
|
||||
func ValidateSyntheticCategoryPolicy(policy PolicyVersion) error {
|
||||
const location = "domain.ValidateSyntheticCategoryPolicy"
|
||||
if !completeDemoBasicPolicy(policy) {
|
||||
return fmt.Errorf("%s - the policy is not a complete demo_basic demonstration policy: %w", location, ErrInvalidAssessmentCategory)
|
||||
}
|
||||
return *left == *right
|
||||
return nil
|
||||
}
|
||||
|
||||
func reviewMatchesCategoryAttempt(
|
||||
|
||||
@@ -227,25 +227,41 @@ func TestDecideAssessmentCategoryIsDefaultOffEvenWithReviewedSource(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestSyntheticCategoryPolicyRequiresTheCompleteAcceptedAssessmentPolicy(t *testing.T) {
|
||||
accepted := DemoProductPolicyV2().Assessment
|
||||
if !sameAssessmentPolicy(accepted, DemoProductPolicyV2().Assessment) {
|
||||
t.Fatal("sameAssessmentPolicy(accepted) = false, want exact accepted policy")
|
||||
func categoryTestPolicyVersion(t *testing.T, policy ProductPolicy, version int32) PolicyVersion {
|
||||
t.Helper()
|
||||
draft, err := NewPolicyVersionDraft(NewPolicyVersionDraftInput{
|
||||
Key: ProductPolicyKey, Kind: PolicyKindDemo, Author: DemoPolicySeedAuthor,
|
||||
EffectiveAt: testPolicyEffectiveAt, Policy: policy,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewPolicyVersionDraft() error = %v", err)
|
||||
}
|
||||
changed := DemoProductPolicyV2().Assessment
|
||||
changed.StopRule.SeedItems++
|
||||
if sameAssessmentPolicy(changed, accepted) {
|
||||
t.Fatal("sameAssessmentPolicy(changed stop rule) = true, want false")
|
||||
numbered, err := draft.WithVersion(version)
|
||||
if err != nil {
|
||||
t.Fatalf("WithVersion() error = %v", err)
|
||||
}
|
||||
changed = DemoProductPolicyV2().Assessment
|
||||
changed.Attempt.IdleTimeoutSeconds++
|
||||
if sameAssessmentPolicy(changed, accepted) {
|
||||
t.Fatal("sameAssessmentPolicy(changed session settings) = true, want false")
|
||||
return mustRestore(t, storedFrom(numbered))
|
||||
}
|
||||
|
||||
func TestSyntheticCategoryPolicyIsAnyCompleteDemoBasicPolicyWithItsOwnThreshold(t *testing.T) {
|
||||
if err := ValidateSyntheticCategoryPolicy(testCategoryPolicyVersion(t)); err != nil {
|
||||
t.Fatalf("ValidateSyntheticCategoryPolicy(demo v2) error = %v", err)
|
||||
}
|
||||
changed = DemoProductPolicyV2().Assessment
|
||||
changed.Training = nil
|
||||
if sameAssessmentPolicy(changed, accepted) {
|
||||
t.Fatal("sameAssessmentPolicy(missing training settings) = true, want false")
|
||||
stricter := DemoProductPolicyV2()
|
||||
stricter.Assessment.Attempt.BasicPassMark = 9000
|
||||
if err := ValidateSyntheticCategoryPolicy(categoryTestPolicyVersion(t, stricter, 3)); err != nil {
|
||||
t.Fatalf("ValidateSyntheticCategoryPolicy(pass mark 9000) error = %v, want the policy's own threshold accepted", err)
|
||||
}
|
||||
if err := ValidateSyntheticCategoryPolicy(PolicyVersion{}); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("ValidateSyntheticCategoryPolicy(zero) error = %v, want invalid category", err)
|
||||
}
|
||||
if err := ValidateSyntheticCategoryPolicy(categoryTestPolicyVersion(t, DemoProductPolicyV1(), 1)); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("ValidateSyntheticCategoryPolicy(no attempt settings) error = %v, want invalid category", err)
|
||||
}
|
||||
noTraining := DemoProductPolicyV2()
|
||||
noTraining.Assessment.Training = nil
|
||||
if err := ValidateSyntheticCategoryPolicy(categoryTestPolicyVersion(t, noTraining, 4)); !errors.Is(err, ErrInvalidAssessmentCategory) {
|
||||
t.Fatalf("ValidateSyntheticCategoryPolicy(no training settings) error = %v, want invalid category", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -287,7 +287,10 @@ type AssessmentAttemptRepository interface {
|
||||
|
||||
// CreateSyntheticCategoryReview stores an operator-attributed immutable
|
||||
// attestation after the domain has validated its explicit synthetic source.
|
||||
CreateSyntheticCategoryReview(ctx context.Context, review domain.AssessmentSyntheticCategoryReview) error
|
||||
// It reports false, and stores nothing, when an attestation of the same
|
||||
// opening, manifest, and policy already exists, also when a concurrent
|
||||
// transaction created it; the caller then reads the stored one.
|
||||
CreateSyntheticCategoryReview(ctx context.Context, review domain.AssessmentSyntheticCategoryReview) (bool, error)
|
||||
|
||||
// SaveCandidateAssessmentCategory writes only an assigned category upgrade.
|
||||
SaveCandidateAssessmentCategory(ctx context.Context, category domain.CandidateAssessmentCategory) error
|
||||
|
||||
@@ -21,8 +21,6 @@ type AssessmentCategoryDecisionSettings struct {
|
||||
SyntheticDemoAssignmentsEnabled bool
|
||||
}
|
||||
|
||||
// AssessmentCategoryReviewPins identify one exact reviewed source. The
|
||||
// repository must not substitute a current opening or a different manifest.
|
||||
// AssessmentCategoryDecisionRepository is bound to the finalization
|
||||
// transaction. Its category lock is acquired after the caller has obtained
|
||||
// C3, candidate/specialization scope, and the attempt row lock, in that order.
|
||||
@@ -35,6 +33,9 @@ type AssessmentCategoryDecisionRepository interface {
|
||||
candidateID uuid.UUID,
|
||||
specialization domain.SpecializationCode,
|
||||
) (domain.CandidateAssessmentCategory, bool, error)
|
||||
// GetSyntheticCategoryReview takes the pins of one exact reviewed source.
|
||||
// The repository must not substitute a current opening or a different
|
||||
// manifest.
|
||||
GetSyntheticCategoryReview(
|
||||
ctx context.Context,
|
||||
openingID uuid.UUID,
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// CategoryAttestation describes one stored attestation of a synthetic
|
||||
// demonstration category. It holds no candidate data.
|
||||
type CategoryAttestation struct {
|
||||
ReviewID uuid.UUID
|
||||
OpeningID uuid.UUID
|
||||
Category domain.AssessmentCategory
|
||||
ProductPolicyVersion int32
|
||||
ReviewedBy domain.AssessmentOperator
|
||||
// Created is false when an identical attestation already existed.
|
||||
Created bool
|
||||
}
|
||||
|
||||
// CategoryAttestor lets an operator attest the exact current opening of a
|
||||
// category, its published manifest, and the product policy now in force as a
|
||||
// source for synthetic demonstration categories. The attestation row is the
|
||||
// audit record: it is immutable and keeps the operator handle and the database
|
||||
// time. It grants nothing by itself; assignment also needs the runtime gate.
|
||||
type CategoryAttestor struct {
|
||||
transactor outbound.Transactor
|
||||
}
|
||||
|
||||
func NewCategoryAttestor(transactor outbound.Transactor) (*CategoryAttestor, error) {
|
||||
if transactor == nil {
|
||||
return nil, errors.New("assessment.NewCategoryAttestor - transactor must be set")
|
||||
}
|
||||
return &CategoryAttestor{transactor: transactor}, nil
|
||||
}
|
||||
|
||||
// Attest resolves the same current selection that a new attempt would pin and
|
||||
// stores the attestation in one transaction. The policy must be the complete
|
||||
// explicit demo_basic demonstration policy. Repeating the call for the same
|
||||
// opening, manifest, and policy returns the stored attestation unchanged.
|
||||
func (attestor *CategoryAttestor) Attest(
|
||||
ctx context.Context,
|
||||
specialization domain.SpecializationCode,
|
||||
grade domain.GradeCode,
|
||||
language *domain.TaskLanguageCode,
|
||||
actor string,
|
||||
) (CategoryAttestation, error) {
|
||||
const location = "CategoryAttestor.Attest"
|
||||
operator, err := domain.ParseAssessmentOperator(actor)
|
||||
if err != nil || !specialization.IsKnown() || !grade.IsKnown() || language != nil && !language.IsKnown() {
|
||||
return CategoryAttestation{}, fmt.Errorf("%s - validate request: %w", location, domain.ErrInvalidAssessmentCategory)
|
||||
}
|
||||
reviewID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("%s - generate review ID: %w", location, err)
|
||||
}
|
||||
var result CategoryAttestation
|
||||
err = attestor.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
selection, err := unit.AssessmentBank().ResolveCurrentSelection(ctx, specialization, grade, language)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve current selection: %w", err)
|
||||
}
|
||||
policy, err := unit.Policies().GetByID(ctx, selection.ProductPolicyVersionID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read product policy: %w", err)
|
||||
}
|
||||
if err := domain.ValidateSyntheticCategoryPolicy(policy); err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = storeCategoryAttestation(ctx, unit, selection, policy, operator, reviewID)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// storeCategoryAttestation returns the stored attestation of the exact opening,
|
||||
// manifest, and policy, or creates it.
|
||||
func storeCategoryAttestation(
|
||||
ctx context.Context,
|
||||
unit outbound.UnitOfWork,
|
||||
selection outbound.AssessmentBankSelection,
|
||||
policy domain.PolicyVersion,
|
||||
operator domain.AssessmentOperator,
|
||||
reviewID uuid.UUID,
|
||||
) (CategoryAttestation, error) {
|
||||
repository := unit.AssessmentAttempts()
|
||||
category := selection.Opening.Category
|
||||
stored, err := readStoredCategoryAttestation(ctx, repository, selection, policy)
|
||||
if err == nil {
|
||||
return stored, nil
|
||||
}
|
||||
if !errors.Is(err, errCategoryAttestationMissing) {
|
||||
return CategoryAttestation{}, err
|
||||
}
|
||||
at, err := unit.AssessmentBank().DatabaseTime(ctx)
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("read database time: %w", err)
|
||||
}
|
||||
review, err := domain.NewAssessmentSyntheticCategoryReview(domain.AssessmentSyntheticCategoryReviewSnapshot{
|
||||
ID: reviewID, OpeningID: selection.Opening.ID, Category: category,
|
||||
Source: domain.AssessmentCategorySourceSyntheticDemo, OpeningManifestHash: selection.ManifestSHA,
|
||||
ProductPolicyVersionID: policy.ID(), ProductPolicyVersion: policy.Version(),
|
||||
ReviewedBy: operator, ReviewedAt: at.UTC().Truncate(time.Microsecond),
|
||||
})
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("build attestation: %w", err)
|
||||
}
|
||||
created, err := repository.CreateSyntheticCategoryReview(ctx, review)
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("store attestation: %w", err)
|
||||
}
|
||||
if !created {
|
||||
// A concurrent operator stored the same exact source first.
|
||||
stored, err := readStoredCategoryAttestation(ctx, repository, selection, policy)
|
||||
if errors.Is(err, errCategoryAttestationMissing) {
|
||||
return CategoryAttestation{}, fmt.Errorf("attestation vanished after a conflict: %w", err)
|
||||
}
|
||||
return stored, err
|
||||
}
|
||||
return CategoryAttestation{
|
||||
ReviewID: reviewID, OpeningID: selection.Opening.ID, Category: category,
|
||||
ProductPolicyVersion: policy.Version(), ReviewedBy: operator, Created: true,
|
||||
}, nil
|
||||
}
|
||||
|
||||
var errCategoryAttestationMissing = errors.New("category attestation is missing")
|
||||
|
||||
// readStoredCategoryAttestation reads the attestation of the exact opening,
|
||||
// manifest, and policy, or reports errCategoryAttestationMissing.
|
||||
func readStoredCategoryAttestation(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
selection outbound.AssessmentBankSelection,
|
||||
policy domain.PolicyVersion,
|
||||
) (CategoryAttestation, error) {
|
||||
category := selection.Opening.Category
|
||||
existing, found, err := repository.GetSyntheticCategoryReview(
|
||||
ctx, selection.Opening.ID, category, selection.ManifestSHA,
|
||||
policy.ID(), policy.Version(), selection.Opening.PolicyVersionID,
|
||||
)
|
||||
if err != nil {
|
||||
return CategoryAttestation{}, fmt.Errorf("read existing attestation: %w", err)
|
||||
}
|
||||
if !found {
|
||||
return CategoryAttestation{}, errCategoryAttestationMissing
|
||||
}
|
||||
snapshot := existing.Snapshot()
|
||||
return CategoryAttestation{
|
||||
ReviewID: snapshot.ID, OpeningID: snapshot.OpeningID, Category: category,
|
||||
ProductPolicyVersion: snapshot.ProductPolicyVersion, ReviewedBy: snapshot.ReviewedBy,
|
||||
}, nil
|
||||
}
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -48,12 +48,18 @@ type AssessmentResultHistoryPage struct {
|
||||
NextCursor string
|
||||
}
|
||||
|
||||
type AssessmentResultHistoryService struct {
|
||||
repository AssessmentResultHistoryRepository
|
||||
keyring Keyring
|
||||
// ResultHistoryCursorSigner signs history page positions under a key that no
|
||||
// other operation uses.
|
||||
type ResultHistoryCursorSigner interface {
|
||||
ResultHistoryCursorSignature(position, candidateID string) [outbound.IdempotencyDigestSize]byte
|
||||
}
|
||||
|
||||
func NewAssessmentResultHistoryService(repository AssessmentResultHistoryRepository, keyring Keyring) AssessmentResultHistoryService {
|
||||
type AssessmentResultHistoryService struct {
|
||||
repository AssessmentResultHistoryRepository
|
||||
keyring ResultHistoryCursorSigner
|
||||
}
|
||||
|
||||
func NewAssessmentResultHistoryService(repository AssessmentResultHistoryRepository, keyring ResultHistoryCursorSigner) AssessmentResultHistoryService {
|
||||
return AssessmentResultHistoryService{repository: repository, keyring: keyring}
|
||||
}
|
||||
|
||||
@@ -99,9 +105,40 @@ func (service AssessmentResultHistoryService) ListMine(
|
||||
return AssessmentResultHistoryPage{Entries: entries, NextCursor: nextCursor}, nil
|
||||
}
|
||||
|
||||
// ListMyResults serves the candidate's result history. The candidate account
|
||||
// check and the page read share one read-only snapshot, so a page never mixes
|
||||
// states of two moments. The page contains only the candidate's own immutable
|
||||
// root and corrective results; an employer account is refused.
|
||||
func (service *AttemptService) ListMyResults(
|
||||
ctx context.Context,
|
||||
userID uuid.UUID,
|
||||
cursor string,
|
||||
limit int32,
|
||||
) (AssessmentResultHistoryPage, error) {
|
||||
const location = "AttemptService.ListMyResults"
|
||||
var page AssessmentResultHistoryPage
|
||||
err := service.snapshotExecutor.WithinReadOnlySnapshot(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireAttemptCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
var listErr error
|
||||
signer, ok := service.keyring.(ResultHistoryCursorSigner)
|
||||
if !ok {
|
||||
return fmt.Errorf("%s - the keyring cannot sign history cursors", location)
|
||||
}
|
||||
page, listErr = NewAssessmentResultHistoryService(unit.AssessmentAttempts(), signer).
|
||||
ListMine(ctx, userID, cursor, limit)
|
||||
return listErr
|
||||
})
|
||||
if err != nil {
|
||||
return AssessmentResultHistoryPage{}, fmt.Errorf("%s - read snapshot: %w", location, err)
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func invalidAssessmentResultHistoryRequest(
|
||||
repository AssessmentResultHistoryRepository,
|
||||
keyring Keyring,
|
||||
keyring ResultHistoryCursorSigner,
|
||||
candidateID uuid.UUID,
|
||||
cursor string,
|
||||
limit int32,
|
||||
@@ -110,12 +147,12 @@ func invalidAssessmentResultHistoryRequest(
|
||||
len(cursor) > assessmentResultHistoryMaxCursorBytes
|
||||
}
|
||||
|
||||
const assessmentResultHistoryCursorOperation = "assessment.result-history.cursor.v1"
|
||||
|
||||
const assessmentResultHistoryCursorPayloadSize = 8 + 4 + 16
|
||||
|
||||
// The cursor is base64url(MAC || position). The position is the decimal
|
||||
// microsecond timestamp and the attempt ID of the last returned row, so the
|
||||
// token holds only [A-Za-z0-9_-] as the contract requires. The MAC binds the
|
||||
// position to the candidate and the listing.
|
||||
func encodeAssessmentResultHistoryCursor(
|
||||
keyring Keyring,
|
||||
keyring ResultHistoryCursorSigner,
|
||||
candidateID uuid.UUID,
|
||||
cursor outbound.AssessmentAttemptResultCursor,
|
||||
) (string, error) {
|
||||
@@ -123,18 +160,13 @@ func encodeAssessmentResultHistoryCursor(
|
||||
cursor.DecidedAt.Nanosecond()%1000 != 0 {
|
||||
return "", ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
payload := make([]byte, assessmentResultHistoryCursorPayloadSize)
|
||||
binary.BigEndian.PutUint64(payload[:8], uint64(cursor.DecidedAt.Unix()))
|
||||
binary.BigEndian.PutUint32(payload[8:12], uint32(cursor.DecidedAt.Nanosecond()))
|
||||
attemptID := cursor.AttemptID.UUID()
|
||||
copy(payload[12:], attemptID[:])
|
||||
encodedPayload := base64.RawURLEncoding.EncodeToString(payload)
|
||||
mac := keyring.IdempotencyScope(assessmentResultHistoryCursorOperation, encodedPayload, candidateID.String())
|
||||
return encodedPayload + "." + base64.RawURLEncoding.EncodeToString(mac[:]), nil
|
||||
position := strconv.FormatInt(cursor.DecidedAt.UnixMicro(), 10) + ":" + cursor.AttemptID.String()
|
||||
mac := keyring.ResultHistoryCursorSignature(position, candidateID.String())
|
||||
return base64.RawURLEncoding.EncodeToString(append(mac[:], position...)), nil
|
||||
}
|
||||
|
||||
func decodeAssessmentResultHistoryCursor(
|
||||
keyring Keyring,
|
||||
keyring ResultHistoryCursorSigner,
|
||||
candidateID uuid.UUID,
|
||||
token string,
|
||||
) (*outbound.AssessmentAttemptResultCursor, error) {
|
||||
@@ -144,40 +176,26 @@ func decodeAssessmentResultHistoryCursor(
|
||||
if keyring == nil || candidateID == uuid.Nil || len(token) > assessmentResultHistoryMaxCursorBytes {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
encodedPayload, encodedMAC, found := strings.Cut(token, ".")
|
||||
if !found || encodedPayload == "" || encodedMAC == "" || strings.Contains(encodedMAC, ".") {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(token)
|
||||
if err != nil || len(raw) <= outbound.IdempotencyDigestSize || base64.RawURLEncoding.EncodeToString(raw) != token {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
payload, err := base64.RawURLEncoding.DecodeString(encodedPayload)
|
||||
if err != nil || len(payload) != assessmentResultHistoryCursorPayloadSize ||
|
||||
base64.RawURLEncoding.EncodeToString(payload) != encodedPayload {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
suppliedMAC, err := base64.RawURLEncoding.DecodeString(encodedMAC)
|
||||
if err != nil || len(suppliedMAC) != outbound.IdempotencyDigestSize ||
|
||||
base64.RawURLEncoding.EncodeToString(suppliedMAC) != encodedMAC {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
expectedMAC := keyring.IdempotencyScope(assessmentResultHistoryCursorOperation, encodedPayload, candidateID.String())
|
||||
suppliedMAC, position := raw[:outbound.IdempotencyDigestSize], string(raw[outbound.IdempotencyDigestSize:])
|
||||
expectedMAC := keyring.ResultHistoryCursorSignature(position, candidateID.String())
|
||||
if !hmac.Equal(suppliedMAC, expectedMAC[:]) {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
seconds := int64(binary.BigEndian.Uint64(payload[:8]))
|
||||
nanos := binary.BigEndian.Uint32(payload[8:12])
|
||||
if nanos >= uint32(time.Second) || nanos%1000 != 0 {
|
||||
microseconds, attemptText, found := strings.Cut(position, ":")
|
||||
if !found {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
var attemptUUID uuid.UUID
|
||||
copy(attemptUUID[:], payload[12:])
|
||||
decidedMicro, err := strconv.ParseInt(microseconds, 10, 64)
|
||||
attemptUUID, uuidErr := uuid.Parse(attemptText)
|
||||
attemptID := domain.AssessmentAttemptID(attemptUUID)
|
||||
if attemptID.IsZero() {
|
||||
if err != nil || uuidErr != nil || attemptID.IsZero() {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
decidedAt := time.Unix(seconds, int64(nanos)).UTC()
|
||||
if decidedAt.Unix() != seconds || uint32(decidedAt.Nanosecond()) != nanos {
|
||||
return nil, ErrInvalidAssessmentResultHistoryRequest
|
||||
}
|
||||
return &outbound.AssessmentAttemptResultCursor{DecidedAt: decidedAt, AttemptID: attemptID}, nil
|
||||
return &outbound.AssessmentAttemptResultCursor{DecidedAt: time.UnixMicro(decidedMicro).UTC(), AttemptID: attemptID}, nil
|
||||
}
|
||||
|
||||
func restoreAssessmentResultHistoryPage(
|
||||
|
||||
@@ -2,7 +2,9 @@ package assessment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -10,32 +12,86 @@ import (
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
func legacyHistoryRecord(t *testing.T, ownerID uuid.UUID, result domain.AssessmentAttemptResultSnapshot) outbound.AssessmentAttemptResultRecord {
|
||||
t.Helper()
|
||||
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
return outbound.AssessmentAttemptResultRecord{UserID: ownerID, Entry: entry}
|
||||
}
|
||||
|
||||
func TestAssessmentResultHistoryReadsOwnerScopedV1WithoutInventingGrade(t *testing.T) {
|
||||
ownerID := uuid.New()
|
||||
policy := categoryServiceTestPolicy(t)
|
||||
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
repository := &assessmentResultHistoryRepositoryFake{page: AssessmentResultHistoryRepositoryPage{
|
||||
Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: entry}}, NextCursor: "next-page-token",
|
||||
record := legacyHistoryRecord(t, ownerID, result)
|
||||
repository := &assessmentResultHistoryRepositoryFake{page: outbound.AssessmentAttemptResultPage{
|
||||
Records: []outbound.AssessmentAttemptResultRecord{record}, HasMore: true,
|
||||
}}
|
||||
service := NewAssessmentResultHistoryService(repository)
|
||||
service := NewAssessmentResultHistoryService(repository, historyCursorSigner{})
|
||||
|
||||
page, err := service.ListMine(t.Context(), ownerID, "", 0)
|
||||
if err != nil {
|
||||
t.Fatalf("ListMine(default limit) error = %v", err)
|
||||
}
|
||||
if repository.ownerID != ownerID || repository.cursor != "" || repository.limit != AssessmentResultHistoryDefaultLimit {
|
||||
t.Fatalf("repository request = owner %s cursor %q limit %d", repository.ownerID, repository.cursor, repository.limit)
|
||||
if repository.ownerID != ownerID || repository.cursor != nil || repository.limit != AssessmentResultHistoryDefaultLimit {
|
||||
t.Fatalf("repository request = owner %s cursor %v limit %d", repository.ownerID, repository.cursor, repository.limit)
|
||||
}
|
||||
if len(page.Entries) != 1 || page.NextCursor != "next-page-token" ||
|
||||
if !regexp.MustCompile(`^[A-Za-z0-9_-]{1,512}$`).MatchString(page.NextCursor) {
|
||||
t.Fatalf("next cursor %q is outside the contract alphabet [A-Za-z0-9_-]", page.NextCursor)
|
||||
}
|
||||
if len(page.Entries) != 1 || page.NextCursor == "" ||
|
||||
page.Entries[0].SchemaVersion != domain.AssessmentAttemptResultHistorySchemaV1 ||
|
||||
page.Entries[0].CategoryDecision != nil || page.Entries[0].CurrentConfirmedGrade != nil {
|
||||
t.Fatalf("history page = %+v, want one legacy result with unknown category", page)
|
||||
t.Fatalf("history page = %+v, want one legacy result with unknown category and a next cursor", page)
|
||||
}
|
||||
|
||||
// The next-page token resumes after the last returned row of the same owner.
|
||||
repository.page = outbound.AssessmentAttemptResultPage{}
|
||||
if _, err := service.ListMine(t.Context(), ownerID, page.NextCursor, 5); err != nil {
|
||||
t.Fatalf("ListMine(next cursor) error = %v", err)
|
||||
}
|
||||
last := page.Entries[0].Result
|
||||
if repository.cursor == nil || !repository.cursor.DecidedAt.Equal(last.DecidedAt) || repository.cursor.AttemptID != last.Attempt.ID || repository.limit != 5 {
|
||||
t.Fatalf("repository keyset = %+v limit %d, want the last row %s at %s", repository.cursor, repository.limit, last.Attempt.ID, last.DecidedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentResultHistoryCursorIsBoundToItsOwner(t *testing.T) {
|
||||
ownerID := uuid.New()
|
||||
policy := categoryServiceTestPolicy(t)
|
||||
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
repository := &assessmentResultHistoryRepositoryFake{page: outbound.AssessmentAttemptResultPage{
|
||||
Records: []outbound.AssessmentAttemptResultRecord{legacyHistoryRecord(t, ownerID, result)}, HasMore: true,
|
||||
}}
|
||||
service := NewAssessmentResultHistoryService(repository, historyCursorSigner{})
|
||||
page, err := service.ListMine(t.Context(), ownerID, "", 1)
|
||||
if err != nil {
|
||||
t.Fatalf("ListMine() error = %v", err)
|
||||
}
|
||||
repository.ownerID = uuid.Nil
|
||||
tampered := page.NextCursor[:len(page.NextCursor)-1] + "A"
|
||||
if page.NextCursor == tampered {
|
||||
tampered = page.NextCursor[:len(page.NextCursor)-1] + "B"
|
||||
}
|
||||
for name, test := range map[string]struct {
|
||||
owner uuid.UUID
|
||||
cursor string
|
||||
}{
|
||||
"foreign owner": {owner: uuid.New(), cursor: page.NextCursor},
|
||||
"tampered token": {owner: ownerID, cursor: tampered},
|
||||
"not a token": {owner: ownerID, cursor: "cursor"},
|
||||
} {
|
||||
if _, err := service.ListMine(t.Context(), test.owner, test.cursor, 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
|
||||
t.Fatalf("ListMine(%s) error = %v, want invalid request", name, err)
|
||||
}
|
||||
}
|
||||
if repository.ownerID != uuid.Nil {
|
||||
t.Fatal("a rejected cursor reached the repository")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,25 +99,17 @@ func TestAssessmentResultHistoryRejectsForeignOwnerAndExpressRows(t *testing.T)
|
||||
ownerID := uuid.New()
|
||||
policy := categoryServiceTestPolicy(t)
|
||||
attempt, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
service := NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
|
||||
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{{CandidateID: uuid.New(), Entry: entry}}},
|
||||
})
|
||||
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{legacyHistoryRecord(t, uuid.New(), result)}},
|
||||
}, historyCursorSigner{})
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 10); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(foreign owner) error = %v, want invalid history", err)
|
||||
}
|
||||
|
||||
express, expressResult := completedExpressCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
expressEntry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(expressResult)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry(express) error = %v", err)
|
||||
}
|
||||
service = NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
|
||||
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: expressEntry}}},
|
||||
})
|
||||
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{legacyHistoryRecord(t, ownerID, expressResult)}},
|
||||
}, historyCursorSigner{})
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 10); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(express row) error = %v, want invalid history", err)
|
||||
}
|
||||
@@ -74,31 +122,32 @@ func TestAssessmentResultHistoryRejectsInvalidBoundsAndDuplicateResults(t *testi
|
||||
ownerID := uuid.New()
|
||||
policy := categoryServiceTestPolicy(t)
|
||||
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(result)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry() error = %v", err)
|
||||
}
|
||||
repository := &assessmentResultHistoryRepositoryFake{page: AssessmentResultHistoryRepositoryPage{
|
||||
Records: []AssessmentResultHistoryRecord{{CandidateID: ownerID, Entry: entry}},
|
||||
record := legacyHistoryRecord(t, ownerID, result)
|
||||
repository := &assessmentResultHistoryRepositoryFake{page: outbound.AssessmentAttemptResultPage{
|
||||
Records: []outbound.AssessmentAttemptResultRecord{record},
|
||||
}}
|
||||
service := NewAssessmentResultHistoryService(repository)
|
||||
service := NewAssessmentResultHistoryService(repository, historyCursorSigner{})
|
||||
if _, err := service.ListMine(t.Context(), ownerID, strings.Repeat("x", assessmentResultHistoryMaxCursorBytes+1), 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
|
||||
t.Fatalf("ListMine(oversized cursor) error = %v, want invalid request", err)
|
||||
}
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", AssessmentResultHistoryMaxLimit+1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
|
||||
t.Fatalf("ListMine(oversized limit) error = %v, want invalid request", err)
|
||||
}
|
||||
repository.page.NextCursor = strings.Repeat("x", assessmentResultHistoryMaxCursorBytes+1)
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(oversized next cursor) error = %v, want invalid history", err)
|
||||
if _, err := service.ListMine(t.Context(), uuid.Nil, "", 1); !errors.Is(err, ErrInvalidAssessmentResultHistoryRequest) {
|
||||
t.Fatalf("ListMine(nil owner) error = %v, want invalid request", err)
|
||||
}
|
||||
repository.page.NextCursor = ""
|
||||
|
||||
repository.page.Records = append(repository.page.Records,
|
||||
AssessmentResultHistoryRecord{CandidateID: ownerID, Entry: entry})
|
||||
repository.page.Records = append(repository.page.Records, record)
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(more rows than the limit) error = %v, want invalid history", err)
|
||||
}
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 2); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(duplicate result) error = %v, want invalid history", err)
|
||||
}
|
||||
repository.page = outbound.AssessmentAttemptResultPage{HasMore: true}
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 1); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(HasMore without rows) error = %v, want invalid history", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *testing.T) {
|
||||
@@ -107,27 +156,20 @@ func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *test
|
||||
_, result := completedCategoryServiceAttempt(t, policy, ownerID, categoryServiceTestTime)
|
||||
decidedAt := time.Date(2026, time.September, 1, 11, 0, 0, 0, time.UTC)
|
||||
|
||||
entryForID := func(id string) domain.AssessmentAttemptResultHistoryEntry {
|
||||
recordForID := func(id string) outbound.AssessmentAttemptResultRecord {
|
||||
t.Helper()
|
||||
resultCopy := result
|
||||
resultCopy.Attempt.ID = domain.AssessmentAttemptID(uuid.MustParse(id))
|
||||
resultCopy.DecidedAt = decidedAt
|
||||
resultCopy.Attempt.FinishedAt = &decidedAt
|
||||
entry, err := domain.NewLegacyAssessmentAttemptResultHistoryEntry(resultCopy)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLegacyAssessmentAttemptResultHistoryEntry(%s) error = %v", id, err)
|
||||
}
|
||||
return entry
|
||||
return legacyHistoryRecord(t, ownerID, resultCopy)
|
||||
}
|
||||
|
||||
higherID := entryForID("ffffffff-ffff-4fff-bfff-ffffffffffff")
|
||||
lowerID := entryForID("00000000-0000-4000-8000-000000000001")
|
||||
higherID := recordForID("ffffffff-ffff-4fff-bfff-ffffffffffff")
|
||||
lowerID := recordForID("00000000-0000-4000-8000-000000000001")
|
||||
service := NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
|
||||
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{
|
||||
{CandidateID: ownerID, Entry: higherID},
|
||||
{CandidateID: ownerID, Entry: lowerID},
|
||||
}},
|
||||
})
|
||||
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{higherID, lowerID}},
|
||||
}, historyCursorSigner{})
|
||||
page, err := service.ListMine(t.Context(), ownerID, "", 2)
|
||||
if err != nil {
|
||||
t.Fatalf("ListMine(descending tie order) error = %v", err)
|
||||
@@ -139,20 +181,17 @@ func TestAssessmentResultHistoryOrdersTiedDecisionsByAttemptIDDescending(t *test
|
||||
}
|
||||
|
||||
service = NewAssessmentResultHistoryService(&assessmentResultHistoryRepositoryFake{
|
||||
page: AssessmentResultHistoryRepositoryPage{Records: []AssessmentResultHistoryRecord{
|
||||
{CandidateID: ownerID, Entry: lowerID},
|
||||
{CandidateID: ownerID, Entry: higherID},
|
||||
}},
|
||||
})
|
||||
page: outbound.AssessmentAttemptResultPage{Records: []outbound.AssessmentAttemptResultRecord{lowerID, higherID}},
|
||||
}, historyCursorSigner{})
|
||||
if _, err := service.ListMine(t.Context(), ownerID, "", 2); !errors.Is(err, ErrAssessmentCategoryHistoryInvalid) {
|
||||
t.Fatalf("ListMine(ascending tie order) error = %v, want invalid history", err)
|
||||
}
|
||||
}
|
||||
|
||||
type assessmentResultHistoryRepositoryFake struct {
|
||||
page AssessmentResultHistoryRepositoryPage
|
||||
page outbound.AssessmentAttemptResultPage
|
||||
ownerID uuid.UUID
|
||||
cursor string
|
||||
cursor *outbound.AssessmentAttemptResultCursor
|
||||
limit int32
|
||||
readErr error
|
||||
}
|
||||
@@ -160,9 +199,15 @@ type assessmentResultHistoryRepositoryFake struct {
|
||||
func (repository *assessmentResultHistoryRepositoryFake) ListCandidateAssessmentResults(
|
||||
_ context.Context,
|
||||
ownerID uuid.UUID,
|
||||
cursor string,
|
||||
cursor *outbound.AssessmentAttemptResultCursor,
|
||||
limit int32,
|
||||
) (AssessmentResultHistoryRepositoryPage, error) {
|
||||
) (outbound.AssessmentAttemptResultPage, error) {
|
||||
repository.ownerID, repository.cursor, repository.limit = ownerID, cursor, limit
|
||||
return repository.page, repository.readErr
|
||||
}
|
||||
|
||||
type historyCursorSigner struct{}
|
||||
|
||||
func (historyCursorSigner) ResultHistoryCursorSignature(position, candidateID string) [32]byte {
|
||||
return sha256.Sum256([]byte("cursor\x00" + position + "\x00" + candidateID))
|
||||
}
|
||||
@@ -60,7 +60,8 @@ func TestAssessmentCategoryDecisionServiceAssignsOnlyTheExactReviewedPolicySourc
|
||||
repository.reviewPins.OpeningID != result.Pins.OpeningID ||
|
||||
repository.reviewPins.OpeningManifestHash != result.Pins.OpeningManifestHash ||
|
||||
repository.reviewPins.ProductPolicyVersionID != result.Pins.ProductPolicyVersionID ||
|
||||
repository.reviewPins.ProductPolicyVersion != result.Pins.ProductPolicyVersion {
|
||||
repository.reviewPins.ProductPolicyVersion != result.Pins.ProductPolicyVersion ||
|
||||
repository.reviewPins.GradingPolicyVersionID != result.Pins.GradingPolicyVersionID {
|
||||
t.Fatalf("review query pins = %+v, want exact finalized source pins", repository.reviewPins)
|
||||
}
|
||||
}
|
||||
@@ -89,7 +90,18 @@ type categoryDecisionRepositoryFake struct {
|
||||
calls []string
|
||||
current *domain.CandidateAssessmentCategory
|
||||
review *domain.AssessmentSyntheticCategoryReview
|
||||
reviewPins AssessmentCategoryReviewPins
|
||||
reviewPins categoryReviewQuery
|
||||
}
|
||||
|
||||
// categoryReviewQuery records the pins that the service passes to the
|
||||
// repository when it looks for a reviewed source.
|
||||
type categoryReviewQuery struct {
|
||||
OpeningID uuid.UUID
|
||||
Category domain.AssessmentCategory
|
||||
OpeningManifestHash [32]byte
|
||||
ProductPolicyVersionID domain.PolicyVersionID
|
||||
ProductPolicyVersion int32
|
||||
GradingPolicyVersionID domain.PolicyVersionID
|
||||
}
|
||||
|
||||
func (repository *categoryDecisionRepositoryFake) LockCandidateCategory(
|
||||
@@ -115,8 +127,18 @@ func (repository *categoryDecisionRepositoryFake) GetCandidateCategory(
|
||||
|
||||
func (repository *categoryDecisionRepositoryFake) GetSyntheticCategoryReview(
|
||||
_ context.Context,
|
||||
pins AssessmentCategoryReviewPins,
|
||||
openingID uuid.UUID,
|
||||
category domain.AssessmentCategory,
|
||||
openingManifestHash [32]byte,
|
||||
productPolicyID domain.PolicyVersionID,
|
||||
productPolicyVersion int32,
|
||||
gradingPolicyID domain.PolicyVersionID,
|
||||
) (domain.AssessmentSyntheticCategoryReview, bool, error) {
|
||||
pins := categoryReviewQuery{
|
||||
OpeningID: openingID, Category: category, OpeningManifestHash: openingManifestHash,
|
||||
ProductPolicyVersionID: productPolicyID, ProductPolicyVersion: productPolicyVersion,
|
||||
GradingPolicyVersionID: gradingPolicyID,
|
||||
}
|
||||
repository.calls = append(repository.calls, "review")
|
||||
repository.reviewPins = pins
|
||||
if repository.review == nil {
|
||||
|
||||
@@ -170,13 +170,21 @@ func lockAttemptForFinalize(
|
||||
}
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - lock owner-scoped attempt: %w", location, err)
|
||||
}
|
||||
if current.Kind() != kind || current.Snapshot().Specialization == nil && selectedSnapshot.Specialization != nil ||
|
||||
current.Snapshot().Specialization != nil && (selectedSnapshot.Specialization == nil || *current.Snapshot().Specialization != *selectedSnapshot.Specialization) {
|
||||
if current.Kind() != kind || !sameAttemptSpecialization(current.Snapshot().Specialization, selectedSnapshot.Specialization) {
|
||||
return domain.AssessmentAttempt{}, fmt.Errorf("%s - immutable attempt scope changed: %w", location, domain.ErrInvalidAssessmentAttempt)
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
// sameAttemptSpecialization compares the optional specializations of two reads
|
||||
// of one attempt; training attempts have none.
|
||||
func sameAttemptSpecialization(left, right *domain.SpecializationCode) bool {
|
||||
if left == nil || right == nil {
|
||||
return left == right
|
||||
}
|
||||
return *left == *right
|
||||
}
|
||||
|
||||
func storeCompletedFinalize(
|
||||
ctx context.Context,
|
||||
repository outbound.AssessmentAttemptRepository,
|
||||
@@ -394,9 +402,7 @@ func readCompletedAttemptResult(
|
||||
if err != nil {
|
||||
return AssessmentAttemptResult{}, fmt.Errorf("%s - restore stored category result: %w", location, err)
|
||||
}
|
||||
result := assessmentAttemptResultFromSnapshot(entry.Result)
|
||||
result.CategoryDecision = entry.CategoryDecision
|
||||
return result, nil
|
||||
return AssessmentAttemptResultFromHistoryEntry(entry), nil
|
||||
}
|
||||
|
||||
func terminalAttemptResult(attempt domain.AssessmentAttempt) (AssessmentAttemptResult, error) {
|
||||
@@ -448,3 +454,15 @@ func assessmentAttemptResultFromSnapshot(
|
||||
Summary: snapshot.Summary, DecidedAt: snapshot.DecidedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// AssessmentAttemptResultFromHistoryEntry is the candidate-visible form of one
|
||||
// stored result, with the category decision captured when it was stored. A
|
||||
// legacy v1 entry has no decision.
|
||||
func AssessmentAttemptResultFromHistoryEntry(entry domain.AssessmentAttemptResultHistoryEntry) AssessmentAttemptResult {
|
||||
result := assessmentAttemptResultFromSnapshot(entry.Result)
|
||||
if entry.CategoryDecision != nil {
|
||||
decision := *entry.CategoryDecision
|
||||
result.CategoryDecision = &decision
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -31,6 +31,7 @@ const (
|
||||
labelAnswerFingerprint = "lincodex/assessment/answer-fingerprint/v1"
|
||||
labelSignalSession = "lincodex/assessment/signal-session/v1"
|
||||
labelSignalNetwork = "lincodex/assessment/signal-network/v1"
|
||||
labelResultCursor = "lincodex/assessment/result-history-cursor/v1"
|
||||
)
|
||||
|
||||
// Keyring computes the keyed digests of the anonymous identity operations:
|
||||
@@ -49,6 +50,7 @@ type Keyring struct {
|
||||
answerKey []byte
|
||||
signalSessionKey []byte
|
||||
signalNetworkKey []byte
|
||||
resultCursorKey []byte
|
||||
}
|
||||
|
||||
// NewKeyring derives the purpose keys from secret.
|
||||
@@ -67,6 +69,7 @@ func NewKeyring(secret []byte) (*Keyring, error) {
|
||||
answerKey: derive(secret, labelAnswerFingerprint),
|
||||
signalSessionKey: derive(secret, labelSignalSession),
|
||||
signalNetworkKey: derive(secret, labelSignalNetwork),
|
||||
resultCursorKey: derive(secret, labelResultCursor),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -103,6 +106,17 @@ func (keyring *Keyring) IdempotencyScope(operation, key, normalizedEmail string)
|
||||
return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// ResultHistoryCursorSignature signs the position of a result history page for
|
||||
// one candidate under a key of its own, so a cursor can never be replayed as an
|
||||
// idempotency scope or the other way round.
|
||||
func (keyring *Keyring) ResultHistoryCursorSignature(position, candidateID string) [outbound.IdempotencyDigestSize]byte {
|
||||
mac := hmac.New(sha256.New, keyring.resultCursorKey)
|
||||
mac.Write([]byte(position))
|
||||
mac.Write([]byte{0})
|
||||
mac.Write([]byte(candidateID))
|
||||
return [outbound.IdempotencyDigestSize]byte(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// Fingerprint identifies a request by its canonical body.
|
||||
func (keyring *Keyring) Fingerprint(canonicalBody []byte) [outbound.IdempotencyDigestSize]byte {
|
||||
mac := hmac.New(sha256.New, keyring.fingerprintKey)
|
||||
|
||||
@@ -3,6 +3,7 @@ package identity
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -123,3 +124,22 @@ func TestAssessmentSessionAndNetworkDigestsAreBoundToTheAttempt(t *testing.T) {
|
||||
t.Fatal("session and network digests share a key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResultHistoryCursorKeyIsSeparateFromIdempotencyAndBoundToTheCandidate(t *testing.T) {
|
||||
keyring, err := NewKeyring([]byte(strings.Repeat("k", MinKeySecretBytes)))
|
||||
if err != nil {
|
||||
t.Fatalf("NewKeyring() error = %v", err)
|
||||
}
|
||||
signature := keyring.ResultHistoryCursorSignature("position", "candidate-a")
|
||||
if signature != keyring.ResultHistoryCursorSignature("position", "candidate-a") {
|
||||
t.Fatal("the cursor signature is not deterministic")
|
||||
}
|
||||
if signature == keyring.ResultHistoryCursorSignature("position", "candidate-b") ||
|
||||
signature == keyring.ResultHistoryCursorSignature("other", "candidate-a") {
|
||||
t.Fatal("the cursor signature does not depend on the position and the candidate")
|
||||
}
|
||||
if signature == keyring.IdempotencyScope("position", "", "candidate-a") ||
|
||||
signature == keyring.IdempotencyScope("assessment.result-history.cursor.v1", "position", "candidate-a") {
|
||||
t.Fatal("the cursor signature shares a key with the idempotency scope")
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,8 @@ func validInboxText(value string, maxRunes int, allowNewlines bool) bool {
|
||||
return false
|
||||
}
|
||||
for _, character := range value {
|
||||
if character == 0 || (character < 0x20 && !(allowNewlines && (character == '\n' || character == '\t'))) || character == 0x7f {
|
||||
allowedControl := allowNewlines && (character == '\n' || character == '\t')
|
||||
if character == 0 || (character < 0x20 && !allowedControl) || character == 0x7f {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -173,11 +174,12 @@ func (service *InboxService) List(ctx context.Context, request InboxListRequest)
|
||||
}
|
||||
item := InboxItem{Entry: entry}
|
||||
content, resolveErr := service.resolver.Resolve(ctx, entry)
|
||||
if errors.Is(resolveErr, ErrInboxContentUnavailable) {
|
||||
switch {
|
||||
case errors.Is(resolveErr, ErrInboxContentUnavailable):
|
||||
item.ContentUnavailable = true
|
||||
} else if resolveErr != nil {
|
||||
case resolveErr != nil:
|
||||
return InboxPage{}, fmt.Errorf("%s - resolve current event content: %w", location, resolveErr)
|
||||
} else {
|
||||
default:
|
||||
item.Content = &content
|
||||
}
|
||||
page.Items = append(page.Items, item)
|
||||
|
||||
Reference in new issue
Block a user