feat: add assessment, privacy and support flows
This commit is contained in:
1 parent
ee3738ee73
commit
e4f24fa202
339 files changed
+56454
-1126
No files matched your search
@@ -0,0 +1,442 @@
|
||||
//go:build integration
|
||||
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const assessmentSignalHTTPTimeout = 6 * time.Minute
|
||||
|
||||
func TestAssessmentSignalsOverHTTP(t *testing.T) {
|
||||
env := bootstrap(t, postgresService, redisService)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), assessmentSignalHTTPTimeout)
|
||||
defer cancel()
|
||||
databaseURL := env.createIsolatedDatabase(ctx, t)
|
||||
applyMigrations(ctx, t, databaseURL)
|
||||
isolatedEnv := *env
|
||||
isolatedEnv.Config.DatabaseURL = databaseURL
|
||||
harness := newAssessmentAttemptHTTPHarness(ctx, t, &isolatedEnv)
|
||||
t.Cleanup(harness.pool.Close)
|
||||
seedAssessmentAttemptHTTPBank(ctx, t, harness.pool)
|
||||
|
||||
passwordHash, err := harness.credentials.HashNewPassword(ctx, sessionHTTPTestPass)
|
||||
if err != nil {
|
||||
t.Fatalf("HashNewPassword() error = %v", err)
|
||||
}
|
||||
candidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "signal-owner@example.test", passwordHash, true)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", candidate.ID); err != nil {
|
||||
t.Fatalf("set candidate onboarding step: %v", err)
|
||||
}
|
||||
cookie, csrf := loginConsentHTTP(t, harness.sessionHTTPHarness, candidate.Email.Address(), "192.0.2.201:1234")
|
||||
if response := assessmentAttemptQuestionnaireRequest(t, harness, cookie.Value, csrf, "192.0.2.202:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("save candidate questionnaire = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
|
||||
trainingCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts", `{"kind":"demo_express"}`,
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "signal-training", "192.0.2.203:1234")
|
||||
if trainingCreate.Code != http.StatusCreated {
|
||||
t.Fatalf("create demo attempt = %d %s", trainingCreate.Code, trainingCreate.Body.String())
|
||||
}
|
||||
trainingAttempt, trainingItem := assessmentSignalAttemptItem(t, trainingCreate.Body.Bytes())
|
||||
grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.204:1234")
|
||||
|
||||
trainingBody := assessmentSignalBody(t, trainingItem, time.Now().UTC().Truncate(time.Microsecond), "fullscreen_exit", nil)
|
||||
trainingSignal := submitAssessmentSignal(t, harness, trainingAttempt, cookie, csrf, "signal-demo", trainingBody, "192.0.2.205:1234")
|
||||
requireSessionProblem(t, trainingSignal, http.StatusConflict, "state_conflict")
|
||||
|
||||
rootCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, cookie.Value, csrf, "signal-root", "192.0.2.206:1234")
|
||||
if rootCreate.Code != http.StatusCreated {
|
||||
t.Fatalf("create real assessment attempt = %d %s", rootCreate.Code, rootCreate.Body.String())
|
||||
}
|
||||
attemptID, itemID := assessmentSignalAttemptItem(t, rootCreate.Body.Bytes())
|
||||
occurredAt := time.Now().UTC().Truncate(time.Microsecond)
|
||||
body := assessmentSignalBody(t, itemID, occurredAt, "fullscreen_exit", nil)
|
||||
|
||||
badItemBody := assessmentSignalBody(t, uuid.New(), occurredAt, "fullscreen_exit", nil)
|
||||
badItem := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-bad-item", badItemBody, "192.0.2.207:1234")
|
||||
if badItem.Code != http.StatusBadRequest {
|
||||
t.Fatalf("foreign item signal = %d %s, want 400", badItem.Code, badItem.Body.String())
|
||||
}
|
||||
oldTimestampBody := assessmentSignalBody(t, itemID, occurredAt.Add(-10*time.Minute), "fullscreen_exit", nil)
|
||||
oldTimestamp := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-old-time", oldTimestampBody, "192.0.2.208:1234")
|
||||
if oldTimestamp.Code != http.StatusBadRequest {
|
||||
t.Fatalf("out-of-window client timestamp = %d %s, want 400", oldTimestamp.Code, oldTimestamp.Body.String())
|
||||
}
|
||||
|
||||
oversizedBody := `{"events":[]}` + strings.Repeat(" ", 32<<10)
|
||||
oversized := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-oversized", oversizedBody, "192.0.2.209:1234")
|
||||
requireSessionProblem(t, oversized, http.StatusRequestEntityTooLarge, "payload_too_large")
|
||||
|
||||
accepted := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", body, "192.0.2.210:1234")
|
||||
assertSignalReceipt(t, accepted, http.StatusOK, "accepted", 1)
|
||||
if accepted.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatalf("signal receipt Cache-Control = %q, want no-store", accepted.Header().Get("Cache-Control"))
|
||||
}
|
||||
var receipt map[string]any
|
||||
if err := json.Unmarshal(accepted.Body.Bytes(), &receipt); err != nil || len(receipt) != 3 {
|
||||
t.Fatalf("receipt fields = %+v, decode error %v", receipt, err)
|
||||
}
|
||||
for _, privateField := range []string{"events", "item_instance_id", "size_bytes", "answer", "score", "result"} {
|
||||
if _, exposed := receipt[privateField]; exposed {
|
||||
t.Fatalf("signal receipt exposed %q", privateField)
|
||||
}
|
||||
}
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 1, 1, 1)
|
||||
assertAssessmentSignalImmutability(t, ctx, harness.pool, attemptID)
|
||||
|
||||
replay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", body, "192.0.2.211:1234")
|
||||
if replay.Code != accepted.Code || replay.Body.String() != accepted.Body.String() {
|
||||
t.Fatalf("same-key signal replay = %d %s, want original %d %s", replay.Code, replay.Body.String(), accepted.Code, accepted.Body.String())
|
||||
}
|
||||
changedBody := assessmentSignalBody(t, itemID, occurredAt.Add(time.Second), "fullscreen_exit", nil)
|
||||
changedReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "192.0.2.212:1234")
|
||||
requireSessionProblem(t, changedReplay, http.StatusUnprocessableEntity, "idempotency_key_reused")
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 1, 1, 1)
|
||||
expiredScope := harness.keyring.IdempotencyScope("assessment_attempt.signals", "signal-first", candidate.ID.String())
|
||||
applicationNow := harness.clock.Now()
|
||||
if _, err := harness.pool.Exec(ctx, `UPDATE idempotency_records
|
||||
SET created_at = $2::timestamptz - INTERVAL '25 hours', expires_at = $2::timestamptz - INTERVAL '1 second'
|
||||
WHERE scope_hash = $1`, expiredScope[:], applicationNow); err != nil {
|
||||
t.Fatalf("expire signal idempotency scope fixture: %v", err)
|
||||
}
|
||||
expiredReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "192.0.2.224:1234")
|
||||
assertSignalReceipt(t, expiredReplay, http.StatusOK, "accepted", 1)
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 2, 2, 1)
|
||||
|
||||
assertAssessmentSignalMeasurementChecks(t, ctx, harness.pool, attemptID, itemID)
|
||||
|
||||
concurrentBodies := []string{
|
||||
assessmentSignalBody(t, itemID, occurredAt.Add(2*time.Second), "copy", int32Pointer(12)),
|
||||
assessmentSignalBody(t, itemID, occurredAt.Add(3*time.Second), "copy", int32Pointer(13)),
|
||||
}
|
||||
concurrentResponses := make([]*httptest.ResponseRecorder, len(concurrentBodies))
|
||||
start := make(chan struct{})
|
||||
var wait sync.WaitGroup
|
||||
for index := range concurrentBodies {
|
||||
wait.Add(1)
|
||||
go func(index int) {
|
||||
defer wait.Done()
|
||||
<-start
|
||||
concurrentResponses[index] = submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-concurrent", concurrentBodies[index], fmt.Sprintf("198.51.100.%d:1234", index+10))
|
||||
}(index)
|
||||
}
|
||||
close(start)
|
||||
wait.Wait()
|
||||
acceptedIndex := -1
|
||||
conflictIndex := -1
|
||||
for index, response := range concurrentResponses {
|
||||
switch response.Code {
|
||||
case http.StatusOK:
|
||||
acceptedIndex = index
|
||||
case http.StatusUnprocessableEntity:
|
||||
requireSessionProblem(t, response, http.StatusUnprocessableEntity, "idempotency_key_reused")
|
||||
conflictIndex = index
|
||||
default:
|
||||
t.Fatalf("concurrent signal %d = %d %s", index, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
if acceptedIndex < 0 || conflictIndex < 0 || acceptedIndex == conflictIndex {
|
||||
t.Fatalf("concurrent same-key outcomes accepted=%d conflict=%d", acceptedIndex, conflictIndex)
|
||||
}
|
||||
assertSignalReceipt(t, concurrentResponses[acceptedIndex], http.StatusOK, "accepted", 1)
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 3, 3, 2)
|
||||
|
||||
otherCandidate := createSessionHTTPUser(ctx, t, harness.sessionHTTPHarness, "signal-other@example.test", passwordHash, true)
|
||||
if _, err := harness.pool.Exec(ctx, "UPDATE users SET onboarding_step = 'candidate_questionnaire' WHERE id = $1", otherCandidate.ID); err != nil {
|
||||
t.Fatalf("set cascade candidate onboarding step: %v", err)
|
||||
}
|
||||
otherCookie, otherCSRF := loginConsentHTTP(t, harness.sessionHTTPHarness, otherCandidate.Email.Address(), "192.0.2.213:1234")
|
||||
if response := assessmentAttemptQuestionnaireRequest(t, harness, otherCookie.Value, otherCSRF, "192.0.2.220:1234"); response.Code != http.StatusOK {
|
||||
t.Fatalf("save cascade candidate questionnaire = %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
grantCurrentAttemptConsent(t, harness, otherCookie, otherCSRF, "192.0.2.221:1234")
|
||||
foreignAttempt := submitAssessmentSignal(t, harness, attemptID, otherCookie, otherCSRF, "signal-foreign", body, "192.0.2.214:1234")
|
||||
requireSessionProblem(t, foreignAttempt, http.StatusNotFound, "not_found")
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 3, 3, 2)
|
||||
otherRootCreate := assessmentAttemptHTTPRequest(t, harness, http.MethodPost, "/api/v1/me/assessment-attempts",
|
||||
assessmentAttemptCreateBody(t, "backend"), sessionHTTPTestOrigin, otherCookie.Value, otherCSRF, "signal-cascade", "192.0.2.222:1234")
|
||||
if otherRootCreate.Code != http.StatusCreated {
|
||||
t.Fatalf("create cascade candidate attempt = %d %s", otherRootCreate.Code, otherRootCreate.Body.String())
|
||||
}
|
||||
otherAttemptID, otherItemID := assessmentSignalAttemptItem(t, otherRootCreate.Body.Bytes())
|
||||
otherSignalBody := assessmentSignalBody(t, otherItemID, time.Now().UTC().Truncate(time.Microsecond), "fullscreen_exit", nil)
|
||||
otherAccepted := submitAssessmentSignal(t, harness, otherAttemptID, otherCookie, otherCSRF, "signal-cascade", otherSignalBody, "192.0.2.223:1234")
|
||||
assertSignalReceipt(t, otherAccepted, http.StatusOK, "accepted", 1)
|
||||
assertSignalStoredCounts(t, ctx, harness, otherAttemptID, 1, 1, 1)
|
||||
|
||||
revokeC3 := assessmentAttemptHTTPRequest(t, harness, http.MethodDelete, "/api/v1/me/consents/c3", "",
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, "", "192.0.2.215:1234")
|
||||
if revokeC3.Code != http.StatusNoContent {
|
||||
t.Fatalf("revoke C3 = %d %s", revokeC3.Code, revokeC3.Body.String())
|
||||
}
|
||||
withoutC3 := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-no-c3", body, "192.0.2.216:1234")
|
||||
requireSessionProblem(t, withoutC3, http.StatusForbidden, "forbidden")
|
||||
grantCurrentAttemptConsent(t, harness, cookie, csrf, "192.0.2.217:1234")
|
||||
|
||||
seedAssessmentSignalCapacity(ctx, t, harness.pool, attemptID, itemID, 10000)
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 2)
|
||||
saturatedBody := assessmentSignalBody(t, itemID, occurredAt.Add(4*time.Second), "fullscreen_exit", nil)
|
||||
saturated := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-saturated", saturatedBody, "192.0.2.218:1234")
|
||||
assertSignalReceipt(t, saturated, http.StatusOK, "saturated", 0)
|
||||
saturatedReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-saturated", saturatedBody, "192.0.2.219:1234")
|
||||
if saturatedReplay.Body.String() != saturated.Body.String() {
|
||||
t.Fatalf("saturated replay = %s, want %s", saturatedReplay.Body.String(), saturated.Body.String())
|
||||
}
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 3)
|
||||
|
||||
for next := signalOutcomeCount(t, ctx, harness.pool, attemptID); next < 30; next++ {
|
||||
key := fmt.Sprintf("signal-rate-%02d", next)
|
||||
response := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, key, saturatedBody, fmt.Sprintf("203.0.113.%d:1234", next+1))
|
||||
assertSignalReceipt(t, response, http.StatusOK, "saturated", 0)
|
||||
}
|
||||
limitedKey := "signal-rate-retry"
|
||||
limited := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, limitedKey, saturatedBody, "203.0.113.80:1234")
|
||||
requireSessionProblem(t, limited, http.StatusTooManyRequests, "rate_limited")
|
||||
if limited.Header().Get("Retry-After") == "" {
|
||||
t.Fatal("rate-limited signal response omitted Retry-After")
|
||||
}
|
||||
scope := harness.keyring.IdempotencyScope("assessment_attempt.signals", limitedKey, candidate.ID.String())
|
||||
var consumed int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM idempotency_records WHERE scope_hash = $1", scope[:]).Scan(&consumed); err != nil {
|
||||
t.Fatalf("check rejected idempotency scope: %v", err)
|
||||
}
|
||||
if consumed != 0 {
|
||||
t.Fatalf("rate-limited idempotency scopes = %d, want 0", consumed)
|
||||
}
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 10000, 203, 30)
|
||||
|
||||
terminalizeAttempt(t, ctx, harness.pool, attemptID)
|
||||
terminal := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-terminal", saturatedBody, "203.0.113.81:1234")
|
||||
requireSessionProblem(t, terminal, http.StatusConflict, "state_conflict")
|
||||
|
||||
if _, err := harness.pool.Exec(ctx, "DELETE FROM assessment_attempts WHERE id = $1", attemptID); err != nil {
|
||||
t.Fatalf("delete attempt for signal cascade test: %v", err)
|
||||
}
|
||||
deletedAttemptReplay := submitAssessmentSignal(t, harness, attemptID, cookie, csrf, "signal-first", changedBody, "203.0.113.82:1234")
|
||||
requireSessionProblem(t, deletedAttemptReplay, http.StatusNotFound, "not_found")
|
||||
assertSignalStoredCounts(t, ctx, harness, attemptID, 0, 0, 0)
|
||||
|
||||
_, accountDeleteErr := harness.pool.Exec(ctx, "DELETE FROM users WHERE id = $1", otherCandidate.ID)
|
||||
assertSQLError(t, "delete account with retained consent history", accountDeleteErr, consentRestrictViolation, "consent_records_subject_id_fkey")
|
||||
var retainedConsentRecords int64
|
||||
if err := harness.pool.QueryRow(ctx, "SELECT count(*) FROM consent_records WHERE subject_id = $1", otherCandidate.ID).Scan(&retainedConsentRecords); err != nil {
|
||||
t.Fatalf("count retained consent records after rejected account deletion: %v", err)
|
||||
}
|
||||
if retainedConsentRecords == 0 {
|
||||
t.Fatal("account deletion removed the candidate's retained consent records")
|
||||
}
|
||||
assertSignalStoredCounts(t, ctx, harness, otherAttemptID, 1, 1, 1)
|
||||
}
|
||||
|
||||
func assessmentSignalAttemptItem(t *testing.T, body []byte) (uuid.UUID, uuid.UUID) {
|
||||
t.Helper()
|
||||
var attempt struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
CurrentItem *struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
} `json:"current_item"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &attempt); err != nil || attempt.ID == uuid.Nil || attempt.CurrentItem == nil || attempt.CurrentItem.ID == uuid.Nil {
|
||||
t.Fatalf("decode signal test attempt and item: %+v, error %v", attempt, err)
|
||||
}
|
||||
return attempt.ID, attempt.CurrentItem.ID
|
||||
}
|
||||
|
||||
func assessmentSignalBody(t *testing.T, itemID uuid.UUID, occurredAt time.Time, kind string, size *int32) string {
|
||||
t.Helper()
|
||||
event := map[string]any{
|
||||
"kind": kind, "item_instance_id": itemID, "occurred_at": occurredAt.UTC().Format(time.RFC3339Nano),
|
||||
}
|
||||
if size != nil {
|
||||
event["size_bytes"] = *size
|
||||
}
|
||||
body, err := json.Marshal(map[string]any{"events": []any{event}})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal signal test body: %v", err)
|
||||
}
|
||||
return string(body)
|
||||
}
|
||||
|
||||
func int32Pointer(value int32) *int32 { return &value }
|
||||
|
||||
func submitAssessmentSignal(
|
||||
t *testing.T,
|
||||
harness *assessmentAttemptHTTPHarness,
|
||||
attemptID uuid.UUID,
|
||||
cookie *http.Cookie,
|
||||
csrf, key, body, remoteAddr string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
path := "/api/v1/me/assessment-attempts/" + attemptID.String() + "/signals"
|
||||
return assessmentAttemptHTTPRequest(t, harness, http.MethodPost, path, body,
|
||||
sessionHTTPTestOrigin, cookie.Value, csrf, key, remoteAddr)
|
||||
}
|
||||
|
||||
func assertSignalReceipt(t *testing.T, response *httptest.ResponseRecorder, status int, receiptStatus string, accepted int) {
|
||||
t.Helper()
|
||||
var receipt struct {
|
||||
Status string `json:"status"`
|
||||
AcceptedEvents int `json:"accepted_events"`
|
||||
ReceivedAt time.Time `json:"received_at"`
|
||||
}
|
||||
if response.Code != status || json.Unmarshal(response.Body.Bytes(), &receipt) != nil ||
|
||||
receipt.Status != receiptStatus || receipt.AcceptedEvents != accepted || receipt.ReceivedAt.IsZero() {
|
||||
t.Fatalf("signal receipt = %d %s, want %d/%s/%d", response.Code, response.Body.String(), status, receiptStatus, accepted)
|
||||
}
|
||||
}
|
||||
|
||||
func assertSignalStoredCounts(
|
||||
t *testing.T,
|
||||
ctx context.Context,
|
||||
harness *assessmentAttemptHTTPHarness,
|
||||
attemptID uuid.UUID,
|
||||
wantEvents, wantBatches, wantOutcomes int64,
|
||||
) {
|
||||
t.Helper()
|
||||
for _, check := range []struct {
|
||||
table string
|
||||
want int64
|
||||
}{
|
||||
{table: "assessment_signal_events", want: wantEvents},
|
||||
{table: "assessment_signal_batches", want: wantBatches},
|
||||
{table: "assessment_signal_idempotency_outcomes", want: wantOutcomes},
|
||||
} {
|
||||
var got int64
|
||||
query := "SELECT count(*) FROM " + check.table + " WHERE attempt_id = $1"
|
||||
if err := harness.pool.QueryRow(ctx, query, attemptID).Scan(&got); err != nil {
|
||||
t.Fatalf("count %s: %v", check.table, err)
|
||||
}
|
||||
if got != check.want {
|
||||
t.Fatalf("%s rows = %d, want %d", check.table, got, check.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertAssessmentSignalMeasurementChecks(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID, itemID uuid.UUID) {
|
||||
t.Helper()
|
||||
for index, kind := range []string{"focus_loss", "copy"} {
|
||||
batchID := uuid.New()
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("begin measurement check %d: %v", index, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
|
||||
VALUES ($1, $2, clock_timestamp(), 1)`, batchID, attemptID); err != nil {
|
||||
t.Fatalf("insert measurement boundary batch: %v", err)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO assessment_signal_events (
|
||||
batch_id, attempt_id, ordinal, item_instance_id, kind, occurred_at, duration_ms, size_bytes
|
||||
) VALUES ($1, $2, 1, $3, $4, clock_timestamp(), NULL, NULL)`, batchID, attemptID, itemID, kind)
|
||||
assertPgError(t, "reject null measurement for "+kind, err, "23514", "assessment_signal_events_measurement")
|
||||
if err := tx.Rollback(ctx); err != nil {
|
||||
t.Fatalf("rollback measurement check %d: %v", index, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertAssessmentSignalImmutability(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) {
|
||||
t.Helper()
|
||||
var batchID uuid.UUID
|
||||
if err := pool.QueryRow(ctx, `SELECT id FROM assessment_signal_batches
|
||||
WHERE attempt_id = $1 ORDER BY received_at, id LIMIT 1`, attemptID).Scan(&batchID); err != nil {
|
||||
t.Fatalf("read signal batch for immutability checks: %v", err)
|
||||
}
|
||||
_, err := pool.Exec(ctx, "UPDATE assessment_signal_batches SET event_count = event_count WHERE id = $1", batchID)
|
||||
assertPgError(t, "reject signal batch update", err, "23000", "assessment_signal_batches_immutable")
|
||||
_, err = pool.Exec(ctx, "DELETE FROM assessment_signal_batches WHERE id = $1", batchID)
|
||||
assertPgError(t, "reject direct signal batch deletion", err, "23000", "assessment_signal_batches_immutable")
|
||||
var ordinal int32
|
||||
if err := pool.QueryRow(ctx, `SELECT ordinal FROM assessment_signal_events
|
||||
WHERE batch_id = $1 ORDER BY ordinal LIMIT 1`, batchID).Scan(&ordinal); err != nil {
|
||||
t.Fatalf("read signal event for immutability checks: %v", err)
|
||||
}
|
||||
_, err = pool.Exec(ctx, "UPDATE assessment_signal_events SET occurred_at = occurred_at WHERE batch_id = $1 AND ordinal = $2", batchID, ordinal)
|
||||
assertPgError(t, "reject signal event update", err, "23000", "assessment_signal_events_immutable")
|
||||
_, err = pool.Exec(ctx, "DELETE FROM assessment_signal_events WHERE batch_id = $1 AND ordinal = $2", batchID, ordinal)
|
||||
assertPgError(t, "reject direct signal event deletion", err, "23000", "assessment_signal_events_immutable")
|
||||
|
||||
var scopeHash []byte
|
||||
if err := pool.QueryRow(ctx, `SELECT scope_hash FROM assessment_signal_idempotency_outcomes
|
||||
WHERE attempt_id = $1 ORDER BY received_at LIMIT 1`, attemptID).Scan(&scopeHash); err != nil {
|
||||
t.Fatalf("read signal outcome for immutability check: %v", err)
|
||||
}
|
||||
_, err = pool.Exec(ctx, "UPDATE assessment_signal_idempotency_outcomes SET status = status WHERE scope_hash = $1", scopeHash)
|
||||
assertPgError(t, "reject signal outcome update", err, "23000", "assessment_signal_idempotency_outcomes_immutable")
|
||||
}
|
||||
|
||||
func seedAssessmentSignalCapacity(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
pool *pgxpool.Pool,
|
||||
attemptID, itemID uuid.UUID,
|
||||
wantTotal int64,
|
||||
) {
|
||||
t.Helper()
|
||||
var existing int64
|
||||
if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_events WHERE attempt_id = $1", attemptID).Scan(&existing); err != nil {
|
||||
t.Fatalf("read signal count before capacity fixture: %v", err)
|
||||
}
|
||||
remaining := wantTotal - existing
|
||||
if remaining <= 0 {
|
||||
t.Fatalf("capacity fixture has no remaining rows: existing=%d target=%d", existing, wantTotal)
|
||||
}
|
||||
batchCount := int((remaining + 49) / 50)
|
||||
batchIDs := make([]uuid.UUID, batchCount)
|
||||
for index := range batchIDs {
|
||||
batchIDs[index] = uuid.New()
|
||||
}
|
||||
tx, err := pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("begin bounded capacity fixture: %v", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
if _, err := tx.Exec(ctx, "ALTER TABLE assessment_signal_events DISABLE TRIGGER assessment_signal_event_guard"); err != nil {
|
||||
t.Fatalf("disable only the capacity backstop for isolated fixture: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
|
||||
SELECT batch.batch_id, $1, clock_timestamp(), LEAST(50, $3::bigint - ((batch.ordinality - 1) * 50))::integer
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS batch(batch_id, ordinality)`, attemptID, batchIDs, remaining); err != nil {
|
||||
t.Fatalf("insert bounded signal capacity batches: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `WITH batches AS (
|
||||
SELECT batch.batch_id, LEAST(50, $3::bigint - ((batch.ordinality - 1) * 50))::integer AS event_count
|
||||
FROM unnest($2::uuid[]) WITH ORDINALITY AS batch(batch_id, ordinality)
|
||||
)
|
||||
INSERT INTO assessment_signal_events (
|
||||
batch_id, attempt_id, ordinal, item_instance_id, kind, occurred_at, duration_ms, size_bytes
|
||||
)
|
||||
SELECT batches.batch_id, $1, event.ordinality::integer, $4, 'fullscreen_exit', clock_timestamp(), NULL, NULL
|
||||
FROM batches
|
||||
CROSS JOIN LATERAL generate_series(1, batches.event_count) AS event(ordinality)`, attemptID, batchIDs, remaining, itemID); err != nil {
|
||||
t.Fatalf("insert bounded signal capacity events: %v", err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "ALTER TABLE assessment_signal_events ENABLE TRIGGER assessment_signal_event_guard"); err != nil {
|
||||
t.Fatalf("restore signal capacity trigger: %v", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
t.Fatalf("commit isolated signal capacity fixture: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func signalOutcomeCount(t *testing.T, ctx context.Context, pool *pgxpool.Pool, attemptID uuid.UUID) int64 {
|
||||
t.Helper()
|
||||
var count int64
|
||||
if err := pool.QueryRow(ctx, "SELECT count(*) FROM assessment_signal_idempotency_outcomes WHERE attempt_id = $1", attemptID).Scan(&count); err != nil {
|
||||
t.Fatalf("count signal receipts: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
Reference in new issue
Block a user