Files
lincodex/backend/internal/adapter/secondary/postgres/sqlc/assessment_signal_review.sql.go
T

618 lines
17 KiB
Go

// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: assessment_signal_review.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const getAssessmentAttemptReview = `-- name: GetAssessmentAttemptReview :one
SELECT
review.attempt_id,
review.policy_version_id,
policy.version AS policy_version,
review.band,
review.reasons,
review.answered_items,
review.fast_answers,
review.deviating_answers,
review.parallel_alternations,
review.extra_networks,
review.matched_integer_items,
review.matched_sequence_items,
review.duplicate_evidence_bits,
review.client_focus_loss_ms,
review.client_clipboard_events,
review.client_fullscreen_exits,
review.extra_agents,
review.client_screenshot_keys,
review.client_devtools_opens,
review.evaluated_at,
review.updated_at
FROM assessment_attempt_reviews AS review
JOIN policy_versions AS policy ON policy.id = review.policy_version_id
WHERE review.attempt_id = $1
`
type GetAssessmentAttemptReviewRow struct {
AttemptID pgtype.UUID
PolicyVersionID pgtype.UUID
PolicyVersion int32
Band string
Reasons []string
AnsweredItems int32
FastAnswers int32
DeviatingAnswers int32
ParallelAlternations int32
ExtraNetworks int32
MatchedIntegerItems int32
MatchedSequenceItems int32
DuplicateEvidenceBits int32
ClientFocusLossMs int64
ClientClipboardEvents int32
ClientFullscreenExits int32
ExtraAgents int32
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
EvaluatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
func (q *Queries) GetAssessmentAttemptReview(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentAttemptReviewRow, error) {
row := q.db.QueryRow(ctx, getAssessmentAttemptReview, attemptID)
var i GetAssessmentAttemptReviewRow
err := row.Scan(
&i.AttemptID,
&i.PolicyVersionID,
&i.PolicyVersion,
&i.Band,
&i.Reasons,
&i.AnsweredItems,
&i.FastAnswers,
&i.DeviatingAnswers,
&i.ParallelAlternations,
&i.ExtraNetworks,
&i.MatchedIntegerItems,
&i.MatchedSequenceItems,
&i.DuplicateEvidenceBits,
&i.ClientFocusLossMs,
&i.ClientClipboardEvents,
&i.ClientFullscreenExits,
&i.ExtraAgents,
&i.ClientScreenshotKeys,
&i.ClientDevtoolsOpens,
&i.EvaluatedAt,
&i.UpdatedAt,
)
return i, err
}
const getAssessmentClientSignalTotals = `-- name: GetAssessmentClientSignalTotals :one
SELECT
COALESCE(sum(duration_ms) FILTER (WHERE kind = 'focus_loss'), 0)::bigint AS focus_loss_ms,
(count(*) FILTER (WHERE kind IN ('copy', 'paste', 'cut')))::integer AS clipboard_events,
(count(*) FILTER (WHERE kind = 'fullscreen_exit'))::integer AS fullscreen_exits,
(count(*) FILTER (WHERE kind = 'screenshot_key'))::integer AS screenshot_keys,
(count(*) FILTER (WHERE kind = 'devtools_open'))::integer AS devtools_opens
FROM assessment_signal_events
WHERE attempt_id = $1
`
type GetAssessmentClientSignalTotalsRow struct {
FocusLossMs int64
ClipboardEvents int32
FullscreenExits int32
ScreenshotKeys int32
DevtoolsOpens int32
}
func (q *Queries) GetAssessmentClientSignalTotals(ctx context.Context, attemptID pgtype.UUID) (GetAssessmentClientSignalTotalsRow, error) {
row := q.db.QueryRow(ctx, getAssessmentClientSignalTotals, attemptID)
var i GetAssessmentClientSignalTotalsRow
err := row.Scan(
&i.FocusLossMs,
&i.ClipboardEvents,
&i.FullscreenExits,
&i.ScreenshotKeys,
&i.DevtoolsOpens,
)
return i, err
}
const getAssessmentReviewSubject = `-- name: GetAssessmentReviewSubject :one
SELECT product_policy_version_id
FROM assessment_attempts
WHERE id = $1 AND kind IN ('root', 'corrective')
`
// The attempt a review job works on: real attempts only.
func (q *Queries) GetAssessmentReviewSubject(ctx context.Context, attemptID pgtype.UUID) (pgtype.UUID, error) {
row := q.db.QueryRow(ctx, getAssessmentReviewSubject, attemptID)
var product_policy_version_id pgtype.UUID
err := row.Scan(&product_policy_version_id)
return product_policy_version_id, err
}
const getLastAssessmentOriginMark = `-- name: GetLastAssessmentOriginMark :one
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version, agent_digest
FROM assessment_attempt_origin_marks
WHERE attempt_id = $1
ORDER BY observed_at DESC, id DESC
LIMIT 1
`
// The caller holds the attempt row lock, so the last mark is stable.
func (q *Queries) GetLastAssessmentOriginMark(ctx context.Context, attemptID pgtype.UUID) (AssessmentAttemptOriginMark, error) {
row := q.db.QueryRow(ctx, getLastAssessmentOriginMark, attemptID)
var i AssessmentAttemptOriginMark
err := row.Scan(
&i.ID,
&i.AttemptID,
&i.Source,
&i.ObservedAt,
&i.SessionDigest,
&i.NetworkDigest,
&i.KeyVersion,
&i.AgentDigest,
)
return i, err
}
const insertAssessmentAnswerObservation = `-- name: InsertAssessmentAnswerObservation :exec
INSERT INTO assessment_answer_observations (
attempt_id,
item_instance_id,
user_id,
family_id,
variant_seed,
answer_format,
answer_fingerprint,
key_version,
elapsed_ms,
measured_from_answer,
observed_at
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8,
$9,
$10,
$11
)
`
type InsertAssessmentAnswerObservationParams struct {
AttemptID pgtype.UUID
ItemInstanceID pgtype.UUID
UserID pgtype.UUID
FamilyID pgtype.UUID
VariantSeed int64
AnswerFormat string
AnswerFingerprint []byte
KeyVersion int16
ElapsedMs int32
MeasuredFromAnswer bool
ObservedAt pgtype.Timestamptz
}
func (q *Queries) InsertAssessmentAnswerObservation(ctx context.Context, arg InsertAssessmentAnswerObservationParams) error {
_, err := q.db.Exec(ctx, insertAssessmentAnswerObservation,
arg.AttemptID,
arg.ItemInstanceID,
arg.UserID,
arg.FamilyID,
arg.VariantSeed,
arg.AnswerFormat,
arg.AnswerFingerprint,
arg.KeyVersion,
arg.ElapsedMs,
arg.MeasuredFromAnswer,
arg.ObservedAt,
)
return err
}
const insertAssessmentOriginMark = `-- name: InsertAssessmentOriginMark :exec
INSERT INTO assessment_attempt_origin_marks (
id,
attempt_id,
source,
observed_at,
session_digest,
network_digest,
agent_digest,
key_version
) VALUES (
$1,
$2,
$3,
$4,
$5,
$6,
$7,
$8
)
`
type InsertAssessmentOriginMarkParams struct {
ID pgtype.UUID
AttemptID pgtype.UUID
Source string
ObservedAt pgtype.Timestamptz
SessionDigest []byte
NetworkDigest []byte
AgentDigest []byte
KeyVersion int16
}
func (q *Queries) InsertAssessmentOriginMark(ctx context.Context, arg InsertAssessmentOriginMarkParams) error {
_, err := q.db.Exec(ctx, insertAssessmentOriginMark,
arg.ID,
arg.AttemptID,
arg.Source,
arg.ObservedAt,
arg.SessionDigest,
arg.NetworkDigest,
arg.AgentDigest,
arg.KeyVersion,
)
return err
}
const insertAssessmentReviewRead = `-- name: InsertAssessmentReviewRead :exec
INSERT INTO assessment_review_reads (id, attempt_id, actor, found, read_at)
VALUES ($1, $2, $3, $4, $5)
`
type InsertAssessmentReviewReadParams struct {
ID pgtype.UUID
AttemptID pgtype.UUID
Actor string
Found bool
ReadAt pgtype.Timestamptz
}
func (q *Queries) InsertAssessmentReviewRead(ctx context.Context, arg InsertAssessmentReviewReadParams) error {
_, err := q.db.Exec(ctx, insertAssessmentReviewRead,
arg.ID,
arg.AttemptID,
arg.Actor,
arg.Found,
arg.ReadAt,
)
return err
}
const listAssessmentAnswerTimes = `-- name: ListAssessmentAnswerTimes :many
SELECT answer_format, elapsed_ms, measured_from_answer
FROM assessment_answer_observations
WHERE attempt_id = $1
ORDER BY observed_at, item_instance_id
LIMIT 220
`
type ListAssessmentAnswerTimesRow struct {
AnswerFormat string
ElapsedMs int32
MeasuredFromAnswer bool
}
// An attempt holds at most 220 items, so the list is bounded by the attempt.
func (q *Queries) ListAssessmentAnswerTimes(ctx context.Context, attemptID pgtype.UUID) ([]ListAssessmentAnswerTimesRow, error) {
rows, err := q.db.Query(ctx, listAssessmentAnswerTimes, attemptID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAssessmentAnswerTimesRow
for rows.Next() {
var i ListAssessmentAnswerTimesRow
if err := rows.Scan(&i.AnswerFormat, &i.ElapsedMs, &i.MeasuredFromAnswer); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAssessmentDuplicatePairs = `-- name: ListAssessmentDuplicatePairs :many
WITH mine AS (
SELECT
own.family_id,
own.key_version,
own.answer_fingerprint,
own.answer_format,
own.variant_seed,
own.user_id
FROM assessment_answer_observations AS own
WHERE own.attempt_id = $5
),
pair_items AS (
SELECT
other.attempt_id AS other_attempt_id,
mine.answer_format,
least(
CASE
WHEN mine.answer_format = 'integer' THEN $6::float8
ELSE $7::float8
END,
greatest(0::float8, -ln(holders.holders::float8 / totals.answer_count::float8) / ln(2::float8))
) AS bits
FROM mine
INNER JOIN assessment_answer_observations AS other
ON mine.family_id = other.family_id
AND mine.key_version = other.key_version
AND mine.answer_fingerprint = other.answer_fingerprint
AND mine.user_id <> other.user_id
AND mine.variant_seed <> other.variant_seed
INNER JOIN assessment_answer_fingerprint_holders AS holders
ON mine.family_id = holders.family_id
AND mine.key_version = holders.key_version
AND mine.answer_fingerprint = holders.answer_fingerprint
INNER JOIN assessment_answer_family_totals AS totals
ON mine.family_id = totals.family_id
AND mine.key_version = totals.key_version
)
SELECT
pair_items.other_attempt_id,
other_attempt.product_policy_version_id,
floor(sum(pair_items.bits))::integer AS evidence_bits,
(count(*) FILTER (WHERE pair_items.answer_format = 'integer'))::integer AS integer_items,
(count(*) FILTER (WHERE pair_items.answer_format = 'integer_sequence'))::integer AS sequence_items
FROM pair_items
INNER JOIN assessment_attempts AS other_attempt ON pair_items.other_attempt_id = other_attempt.id
WHERE
NOT $1::boolean
OR other_attempt.state IN ('completed', 'expired', 'insufficient_bank')
OR other_attempt.expires_at <= $2::timestamptz
GROUP BY pair_items.other_attempt_id, other_attempt.product_policy_version_id
HAVING floor(sum(pair_items.bits)) >= $3::float8
ORDER BY evidence_bits DESC, pair_items.other_attempt_id
LIMIT $4
`
type ListAssessmentDuplicatePairsParams struct {
EndedOnly bool
Now pgtype.Timestamptz
MinBits float64
RowLimit int32
AttemptID pgtype.UUID
IntegerCapBits float64
SequenceCapBits float64
}
type ListAssessmentDuplicatePairsRow struct {
OtherAttemptID pgtype.UUID
ProductPolicyVersionID pgtype.UUID
EvidenceBits int32
IntegerItems int32
SequenceItems int32
}
// Compares this attempt with every other attempt separately. A matched answer
// is an equal fingerprint of the same family version under the same key
// generation, given by another candidate to a different seed variant. It
// carries -log2 of the share of answers that hold that fingerprint, read from
// the maintained counters, between
// zero and the cap of its format, and the bits of one pair add up. Pairs under
// min_bits are dropped, the strongest come first, and the list is bounded.
// An attempt has ended when its state is terminal or its deadline has passed.
func (q *Queries) ListAssessmentDuplicatePairs(ctx context.Context, arg ListAssessmentDuplicatePairsParams) ([]ListAssessmentDuplicatePairsRow, error) {
rows, err := q.db.Query(ctx, listAssessmentDuplicatePairs,
arg.EndedOnly,
arg.Now,
arg.MinBits,
arg.RowLimit,
arg.AttemptID,
arg.IntegerCapBits,
arg.SequenceCapBits,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ListAssessmentDuplicatePairsRow
for rows.Next() {
var i ListAssessmentDuplicatePairsRow
if err := rows.Scan(
&i.OtherAttemptID,
&i.ProductPolicyVersionID,
&i.EvidenceBits,
&i.IntegerItems,
&i.SequenceItems,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAssessmentOriginMarks = `-- name: ListAssessmentOriginMarks :many
SELECT id, attempt_id, source, observed_at, session_digest, network_digest, key_version, agent_digest
FROM assessment_attempt_origin_marks
WHERE attempt_id = $1
ORDER BY observed_at, id
LIMIT 5000
`
// Marks exist only where the session or the network changed. The bound keeps a
// request that flaps between networks from growing the list without limit.
func (q *Queries) ListAssessmentOriginMarks(ctx context.Context, attemptID pgtype.UUID) ([]AssessmentAttemptOriginMark, error) {
rows, err := q.db.Query(ctx, listAssessmentOriginMarks, attemptID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AssessmentAttemptOriginMark
for rows.Next() {
var i AssessmentAttemptOriginMark
if err := rows.Scan(
&i.ID,
&i.AttemptID,
&i.Source,
&i.ObservedAt,
&i.SessionDigest,
&i.NetworkDigest,
&i.KeyVersion,
&i.AgentDigest,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockAssessmentReview = `-- name: LockAssessmentReview :exec
SELECT pg_advisory_xact_lock(hashtextextended(
'lincodex.assessment.signal_review:' || $1::text,
0
))
`
// Serializes the evaluations of one review. A job takes these locks for every
// attempt it will write, in ascending attempt order, before it reads any fact,
// so what it reads is what the previous writer committed.
func (q *Queries) LockAssessmentReview(ctx context.Context, attemptID string) error {
_, err := q.db.Exec(ctx, lockAssessmentReview, attemptID)
return err
}
const upsertAssessmentAttemptReview = `-- name: UpsertAssessmentAttemptReview :exec
INSERT INTO assessment_attempt_reviews (
attempt_id,
policy_version_id,
band,
reasons,
answered_items,
fast_answers,
deviating_answers,
parallel_alternations,
extra_networks,
matched_integer_items,
matched_sequence_items,
duplicate_evidence_bits,
client_focus_loss_ms,
client_clipboard_events,
client_fullscreen_exits,
extra_agents,
client_screenshot_keys,
client_devtools_opens,
evaluated_at,
updated_at
) VALUES (
$1,
$2,
$3,
$4::text[],
$5,
$6,
$7,
$8,
$9,
$10,
$11,
$12,
$13,
$14,
$15,
$16,
$17,
$18,
clock_timestamp(),
clock_timestamp()
)
ON CONFLICT (attempt_id) DO UPDATE SET
policy_version_id = EXCLUDED.policy_version_id,
band = EXCLUDED.band,
reasons = EXCLUDED.reasons,
answered_items = EXCLUDED.answered_items,
fast_answers = EXCLUDED.fast_answers,
deviating_answers = EXCLUDED.deviating_answers,
parallel_alternations = EXCLUDED.parallel_alternations,
extra_networks = EXCLUDED.extra_networks,
matched_integer_items = EXCLUDED.matched_integer_items,
matched_sequence_items = EXCLUDED.matched_sequence_items,
duplicate_evidence_bits = EXCLUDED.duplicate_evidence_bits,
client_focus_loss_ms = EXCLUDED.client_focus_loss_ms,
client_clipboard_events = EXCLUDED.client_clipboard_events,
client_fullscreen_exits = EXCLUDED.client_fullscreen_exits,
extra_agents = EXCLUDED.extra_agents,
client_screenshot_keys = EXCLUDED.client_screenshot_keys,
client_devtools_opens = EXCLUDED.client_devtools_opens,
updated_at = greatest(
clock_timestamp(), assessment_attempt_reviews.evaluated_at, assessment_attempt_reviews.updated_at
)
`
type UpsertAssessmentAttemptReviewParams struct {
AttemptID pgtype.UUID
PolicyVersionID pgtype.UUID
Band string
Reasons []string
AnsweredItems int32
FastAnswers int32
DeviatingAnswers int32
ParallelAlternations int32
ExtraNetworks int32
MatchedIntegerItems int32
MatchedSequenceItems int32
DuplicateEvidenceBits int32
ClientFocusLossMs int64
ClientClipboardEvents int32
ClientFullscreenExits int32
ExtraAgents int32
ClientScreenshotKeys int32
ClientDevtoolsOpens int32
}
// The times come from the database clock, never from a caller, and the update
// time cannot fall behind the stored times, so two jobs writing one review in
// either order keep the order check. The first evaluation time and the policy
// version stay; the guard trigger refuses a change of either.
func (q *Queries) UpsertAssessmentAttemptReview(ctx context.Context, arg UpsertAssessmentAttemptReviewParams) error {
_, err := q.db.Exec(ctx, upsertAssessmentAttemptReview,
arg.AttemptID,
arg.PolicyVersionID,
arg.Band,
arg.Reasons,
arg.AnsweredItems,
arg.FastAnswers,
arg.DeviatingAnswers,
arg.ParallelAlternations,
arg.ExtraNetworks,
arg.MatchedIntegerItems,
arg.MatchedSequenceItems,
arg.DuplicateEvidenceBits,
arg.ClientFocusLossMs,
arg.ClientClipboardEvents,
arg.ClientFullscreenExits,
arg.ExtraAgents,
arg.ClientScreenshotKeys,
arg.ClientDevtoolsOpens,
)
return err
}