feat(assessment): assign the demonstration category and keep result history

This commit is contained in:
shira committed 2026-10-09 00:35:13 +03:00
1 parent b3c6dc870b
commit 8277133712
61 files changed
+4338 -268

No files matched your search

@@ -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