screening

package
v0.42.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package screening is the contract of R40's automatic content flagging (docs/71 D3): what the relay's keyframe route serves, what gawk-admin's flagger API accepts and answers, and the window rule both the sampler and gawk-admin's replay apply.

It is PUBLIC (not internal/) for the reason `wire`, `events` and `adminapi` are: gawk-admin and gawk-sampler import it through their repo-root `replace`, so the three parties compile one definition instead of mirroring JSON tags. A semantic change here needs commits touching gawk-admin/ AND gawk-sampler/ in the same PR (CONTRIBUTING.md), or release-please cuts a relay release and leaves the deployed consumers on the old contract.

Keep it dependency-light: the standard library and internal/broadcastid, nothing else. No frame bytes ever pass through a type here (D8): the contract carries scores, windows and identities only.

Index

Constants

View Source
const (
	// FlagStatusRaised: a tripped POST with no unresolved flag raised one.
	FlagStatusRaised = "raised"
	// FlagStatusUpdated: a tripped POST updated the unresolved flag.
	FlagStatusUpdated = "updated"
	// FlagStatusResolved: a cleared POST resolved the unresolved flag.
	FlagStatusResolved = "resolved"
	// FlagStatusMuted: the broadcast is muted by a dismissal; nothing
	// changed (flag mode only — observe POSTs ignore mutes).
	FlagStatusMuted = "muted"
	// FlagStatusEnded: the POST names a publisher session that is not the
	// broadcast's active one; nothing changed.
	FlagStatusEnded = "ended"
	// FlagStatusIgnored: a cleared POST with no unresolved flag to resolve.
	FlagStatusIgnored = "ignored"
)

Content-flag POST outcomes (D9, D10, D2). The HTTP status travels with each: raised 201, updated and resolved 200, the rest 202.

View Source
const (
	MaxBatchSessions = 4096
	MaxBatchSamples  = 16384
)

Batch limits. A healthy sampler sends one batch every 5 s holding at most one sample per screened broadcast per interval, far below these.

View Source
const (
	// SchemaContentFlag names the POST /api/v1/content-flags body, frozen by
	// docs/42 §4.11 and extended additively by docs/71.
	SchemaContentFlag = "gawk.content-flag.v1"
	// SchemaTargets names the GET /api/v1/screening/targets response (D2).
	SchemaTargets = "gawk.screening.targets.v1"
	// SchemaSamples names the POST /api/v1/screening/samples body (D20).
	SchemaSamples = "gawk.screening.samples.v1"
	// SchemaReplay names the POST /api/v1/screening/replay response (D21).
	SchemaReplay = "gawk.screening.replay.v1"
)

Schema names. Versioned strings, not implied by the route, so a consumer pins the shape it parses (the docs/42 §4.5 discipline).

View Source
const (
	PathContentFlags = "/api/v1/content-flags"
	PathTargets      = "/api/v1/screening/targets"
	PathSamples      = "/api/v1/screening/samples"
)

gawk-admin routes the sampler calls, relative to -admin-url.

View Source
const (
	ModeObserve = "observe"
	ModeFlag    = "flag"
)

Sampler modes (D19). Required on every content-flag POST: it decides between paging and silence, so no default is safe.

View Source
const (
	// StateTripped is sent after every sample while the window is tripped.
	StateTripped = "tripped"
	// StateCleared is sent once, when a tripped window clears.
	StateCleared = "cleared"
)

Window states a content-flag POST reports (D9).

View Source
const (
	// KeyframeRoutePattern is the Go 1.22 ServeMux pattern the relay
	// registers.
	KeyframeRoutePattern = "GET /internal/screening/broadcasts/{id}/keyframe"
	// HeaderCodec carries the hub's probed codec family ("h264", "vp8",
	// "vp9", "av1"): the sampler's choice of bitstream conversion (D4).
	HeaderCodec = "X-Gawk-Codec"
	// HeaderPublisherEpoch carries the publisher session the frame belongs
	// to (adminapi.Broadcast.PublisherEpoch). A change of value is a new
	// publisher session: the sampler resets that broadcast's window (D7).
	HeaderPublisherEpoch = "X-Gawk-Publisher-Epoch"
	// KeyframeContentType is the media type of the 200 body: one StreamFrame
	// message verbatim (24-byte header, embedded DecoderConfig, payload).
	KeyframeContentType = "application/vnd.gawk.stream-frame"
)

The keyframe route on the relay's ops listener (D1). It is authorized by its own bearer, -screening-token, never by the admin token, and is not registered at all when that token is empty.

View Source
const (
	// MaxRecent caps a content flag's `recent` (D14). gawk-admin refuses
	// to start with an auto-kill policy that names more samples.
	MaxRecent = 64
	// MaxLabels caps every label list and score map.
	MaxLabels = 32
	// MaxLabelLen caps one label name.
	MaxLabelLen = 64
	// MaxSamplerIDLen caps samplerId.
	MaxSamplerIDLen = 128
	// MaxSummaryLen caps the human summary.
	MaxSummaryLen = 512
	// MaxEpochLen caps a publisher epoch.
	MaxEpochLen = 64
	// MaxBroadcastKeyLen caps a broadcast key.
	MaxBroadcastKeyLen = 64
	// MaxWindow caps a window rule's size (and so a replay's).
	MaxWindow = 64
	// MaxShards caps -shard-count. Far beyond any fleet that needs it; it
	// exists so a typo cannot make gawk-admin track a million shards.
	MaxShards = 64
)

Limits the validators enforce. They bound what one request can make gawk-admin store or compute, not what a healthy sampler sends.

View Source
const MaxReplayRange = 92 * 24 * time.Hour

MaxReplayRange bounds a replay's time range; samples are pruned after -screening-sample-retention (30 d) anyway.

View Source
const MaxReplayTrips = 1000

MaxReplayTrips caps the trips a replay lists. The count beyond it is still exact; only the list is truncated.

Variables

View Source
var ErrInvalid = errors.New("screening: invalid")

ErrInvalid wraps every validation failure in this package, so a handler maps the whole class onto one 400 with errors.Is.

Functions

func DefaultLabels

func DefaultLabels() []string

DefaultLabels is the flagged label set (D7, OD3): explicit nudity only. Partial nudity is deliberately absent — game footage triggers it constantly. A fresh slice per call, because the default is policy that a caller must not be able to edit for everyone.

func KeyframeETag

func KeyframeETag(publisherEpoch string, frameID uint32) string

KeyframeETag is the strong entity tag of a cached keyframe: publisher session and frame ID, so a new session never matches an old tag even when its frame IDs restart at the same numbers (D1).

func KeyframePath

func KeyframePath(broadcastID string) string

KeyframePath is the request path for one broadcast's cached keyframe.

func SampleScore

func SampleScore(scores map[string]float64, labels []string) float64

SampleScore is D7's per-sample score: the maximum confidence among labels. A label absent from scores counts as 0.

func Shard

func Shard(broadcastKey string, n int) int

Shard is the one broadcast-to-sampler assignment (D22): the share of broadcastKey among n samplers. It is deterministic, in [0, n) for every n ≥ 1, and depends only on the key — which never changes while a broadcast is live, so a broadcast stays on one sampler for its whole life. n < 1 is treated as 1.

The key is hashed again rather than reduced directly: it is already an HMAC prefix, but the uniformity of the split should not depend on how some other component happens to derive its keys. The golden values in the tests pin the function, so a change to it is a visible break: changing it reshuffles every live broadcast between samplers.

func ValidMode

func ValidMode(m string) bool

ValidMode reports whether m is one of the two modes.

func ValidateLabels

func ValidateLabels(labels []string) error

ValidateLabels checks a label list the way every body field is checked: at most MaxLabels distinct names of [A-Z0-9_]. The sampler applies it to -labels at start-up.

func ValidateShard

func ValidateShard(shard, of int) error

ValidateShard checks a (shard, of) pair: 1 ≤ of ≤ MaxShards, 0 ≤ shard < of.

Types

type BatchRule added in v0.34.0

type BatchRule struct {
	Threshold  float64 `json:"threshold"`
	Window     int     `json:"window"`
	WindowHits int     `json:"windowHits"`
}

BatchRule is a WindowRule as a sample batch reports it.

func (BatchRule) WindowRule added in v0.34.0

func (r BatchRule) WindowRule() WindowRule

WindowRule is the rule in the sampler's own terms.

type ContentFlag

type ContentFlag struct {
	Schema string `json:"schema"`
	// BroadcastID is the raw broadcast ID the window belongs to.
	BroadcastID string `json:"broadcastId"`
	// PublisherEpoch is the publisher session the window was built over
	// (R40 addition). gawk-admin answers a tripped POST for a session that is
	// no longer the broadcast's active one with 202 ended (D2's backstop).
	PublisherEpoch string `json:"publisherEpoch"`
	SamplerID      string `json:"samplerId"`
	// Mode is ModeObserve or ModeFlag, required (D19).
	Mode string `json:"mode"`
	// State is StateTripped or StateCleared (D9).
	State  string        `json:"state"`
	Window WindowSummary `json:"window"`
	Scores Scores        `json:"scores"`
	// Labels are the flagged labels that fired in the window, and
	// LabelCounts how many of its samples each fired in (D8: "the labels
	// that fired and their counts"). LabelCounts is an R40 addition.
	Labels      []string       `json:"labels"`
	LabelCounts map[string]int `json:"labelCounts,omitempty"`
	// Recent is the session's last -report-samples per-sample scores, oldest
	// first, each the max over the flagged labels — below-floor scores
	// included (D14). Empty on a cleared POST and after a reset.
	Recent  []float64 `json:"recent,omitempty"`
	Summary string    `json:"summary,omitempty"`
}

ContentFlag is the POST /api/v1/content-flags body: the `gawk.content-flag.v1` schema docs/42 §4.11 froze, with the additive fields docs/71 gives it. Scores and metadata only — never a frame (D8).

func (*ContentFlag) Validate

func (f *ContentFlag) Validate() error

Validate checks a content flag. Every failure wraps ErrInvalid: the whole class is a 400.

type Episode

type Episode struct {
	At        time.Time
	PeakScore float64
}

Episode is one trip found by ReplaySession: when the window tripped and the highest score seen while it stayed tripped.

func ReplaySession

func ReplaySession(rule WindowRule, taken int64, stored []StoredSample) []Episode

ReplaySession runs rule over one publisher session as gawk-admin stored it (D20, D21): taken samples numbered 1…taken, of which only those in stored (ascending Seq) were kept. A missing number is a sample that scored below the floor, so it counts as 0 — below every threshold the caller allows (a threshold under the floor is refused before this runs), which keeps the replay exact. Stored samples numbered past taken are ignored.

type FlagResponse

type FlagResponse struct {
	// Status is one of the FlagStatus* values.
	Status string `json:"status"`
	// FlagID is the content_flags row the POST raised, updated or resolved;
	// absent when it touched none.
	FlagID int64 `json:"flagId,omitempty"`
}

FlagResponse is the body of every non-error content-flag POST answer.

type ReplayRequest

type ReplayRequest struct {
	Threshold  float64 `json:"threshold"`
	Window     int     `json:"window"`
	WindowHits int     `json:"windowHits"`
	// Labels restricts the score to a subset of the stored labels; empty
	// means every stored label.
	Labels []string  `json:"labels,omitempty"`
	From   time.Time `json:"from"`
	To     time.Time `json:"to"`
}

ReplayRequest is the POST /api/v1/screening/replay body (D21): a candidate window rule and the stored data to run it over.

func (ReplayRequest) Rule

func (r ReplayRequest) Rule() WindowRule

Rule is the request's window rule.

func (ReplayRequest) Validate

func (r ReplayRequest) Validate() error

Validate checks the request's own shape. The floor check needs the stored data and is gawk-admin's.

type ReplayResponse

type ReplayResponse struct {
	Schema  string        `json:"schema"`
	Request ReplayRequest `json:"request"`
	// Floor is the highest floor among the replayed sessions.
	Floor float64 `json:"floor"`
	// Sessions, SamplesTaken and SamplesStored size the data replayed.
	Sessions      int   `json:"sessions"`
	SamplesTaken  int64 `json:"samplesTaken"`
	SamplesStored int64 `json:"samplesStored"`
	// BroadcastHours is the sum of the sessions' sampled spans.
	BroadcastHours float64 `json:"broadcastHours"`
	// WouldTrips counts every trip; WouldTripsPer100h normalizes it (0 when
	// there are no broadcast-hours).
	WouldTrips        int     `json:"wouldTrips"`
	WouldTripsPer100h float64 `json:"wouldTripsPer100h"`
	// Trips lists them, newest first, at most MaxReplayTrips; Truncated says
	// the list was cut.
	Trips     []ReplayTrip `json:"trips"`
	Truncated bool         `json:"truncated"`
}

ReplayResponse answers a replay.

type ReplayTrip

type ReplayTrip struct {
	BroadcastKey   string    `json:"broadcastKey"`
	BroadcastID    string    `json:"broadcastId"`
	PublisherEpoch string    `json:"publisherEpoch"`
	At             time.Time `json:"at"`
	PeakScore      float64   `json:"peakScore"`
}

ReplayTrip is one would-have-tripped episode.

type Sample

type Sample struct {
	// Position is the sample's 1-based place among the session's Taken.
	Position int       `json:"position"`
	At       time.Time `json:"at"`
	// Scores holds every label of the batch's Labels: the label's highest
	// detection confidence in the frame, 0 when it was not detected.
	Scores map[string]float64 `json:"scores"`
}

Sample is one stored sample.

type SampleBatch

type SampleBatch struct {
	Schema    string `json:"schema"`
	SamplerID string `json:"samplerId"`
	// Mode is the sampler's mode, recorded with each session for the
	// Calibration view; samples are stored in both modes (D20).
	Mode string `json:"mode"`
	// Floor is -sample-floor: only samples where some label in Labels
	// scores at or above it are sent. Replay refuses a threshold below the
	// highest floor among the sessions it reads (D21).
	Floor float64 `json:"floor"`
	// Labels is -labels: the label set every sample's Scores covers.
	Labels []string `json:"labels"`
	// Rule is the sampler's window rule (-threshold, -window, -window-hits),
	// reported so gawk-admin draws and reasons with the threshold that was in
	// force rather than a copy of it in its own config (docs/72 D1). Absent
	// from a sampler older than R70; gawk-admin then knows no threshold.
	Rule     *BatchRule       `json:"rule,omitempty"`
	Sessions []SessionSamples `json:"sessions"`
}

SampleBatch is the POST /api/v1/screening/samples body (D20): one sampler's samples since its previous batch, grouped by publisher session.

gawk-admin, not the sampler, numbers the samples. Each session reports how many samples it TOOK in this batch and, for every sample it SENDS, that sample's 1-based position among them; gawk-admin numbers a sent sample as the session's count before the batch plus its position, and adds Taken to the count, under a row lock. A sample is a scored frame: a failed fetch, decode or inference is neither counted nor sent, and a 304 counts with the previous score.

func (*SampleBatch) Validate

func (b *SampleBatch) Validate() error

Validate checks a batch. Every failure wraps ErrInvalid.

type SamplesResponse

type SamplesResponse struct {
	// Stored is how many samples were written.
	Stored int `json:"stored"`
}

SamplesResponse answers a stored batch.

type Scores

type Scores struct {
	Max  float64 `json:"max"`
	Mean float64 `json:"mean"`
}

Scores are the window's max and mean sample score.

type SessionSamples

type SessionSamples struct {
	BroadcastID    string `json:"broadcastId"`
	BroadcastKey   string `json:"broadcastKey"`
	PublisherEpoch string `json:"publisherEpoch"`
	// Taken is how many samples this batch scored for the session, sent or
	// not. At least 1: a session with nothing scored is left out.
	Taken int `json:"taken"`
	// FirstAt and LastAt bound the scored samples, for the broadcast-hours
	// denominator.
	FirstAt time.Time `json:"firstAt"`
	LastAt  time.Time `json:"lastAt"`
	// Samples are the sent ones, in position order.
	Samples []Sample `json:"samples"`
}

SessionSamples is one publisher session's share of a batch.

type StoredSample

type StoredSample struct {
	Seq   int64
	At    time.Time
	Score float64
}

StoredSample is one row of gawk-admin's screening_samples as replay reads it: the sample's per-session sequence number (1-based), its time, and its score under the replay's label set.

type Target

type Target struct {
	// BroadcastID is the raw, joinable ID: the keyframe route's path segment
	// and the content flag's subject.
	BroadcastID string `json:"broadcastId"`
	// BroadcastKey is the HMAC'd key; Shard is computed over it.
	BroadcastKey string `json:"broadcastKey"`
	// PublisherEpoch identifies the publisher session the listing saw. The
	// keyframe response's HeaderPublisherEpoch is authoritative for a
	// sample; this one lets the sampler drop a window early.
	PublisherEpoch string `json:"publisherEpoch"`
	// Relay is the base URL of the ops listener of the pod holding the
	// origin, e.g. "http://10.42.0.7:2112". The keyframe route lives there.
	Relay string `json:"relay"`
	// Muted is true while a dismissal mutes the broadcast (D10). It is still
	// sampled — observe-mode data and samples continue — but flag-mode POSTs
	// answer 202 muted.
	Muted bool `json:"muted"`
	// Exempt is true while the broadcast is attached to an exempt room
	// (D11). It is listed so the sampler's metrics see it, and never sampled.
	Exempt bool `json:"exempt"`
}

Target is one broadcast to screen. Only origin broadcasts whose publisher is active are listed: a broadcast in its away grace has a frozen cached keyframe nobody is broadcasting (D2).

type TargetsResponse

type TargetsResponse struct {
	Schema string `json:"schema"`
	// Shard and Of echo the query, so a sampler can assert it got the share
	// it asked for.
	Shard int `json:"shard"`
	Of    int `json:"of"`
	// FlagRoute is false when no enabled webhook would deliver
	// content_flag.raised (D12). A sampler in flag mode samples nothing while
	// it is false; observe mode is unaffected.
	FlagRoute bool     `json:"flagRoute"`
	Targets   []Target `json:"targets"`
}

TargetsResponse is the body of GET /api/v1/screening/targets (D2, D22): one shard's live origin broadcasts.

type Transition

type Transition int

Transition is what one observed sample did to a window.

const (
	// Unchanged: the window stayed tripped or stayed clear.
	Unchanged Transition = iota
	// Tripped: the window went from clear to tripped on this sample.
	Tripped
	// Cleared: the window went from tripped to clear on this sample.
	Cleared
)

type Window

type Window struct {
	// contains filtered or unexported fields
}

Window is one publisher session's sliding window. The zero value is not usable; build one with NewWindow. Not safe for concurrent use.

func NewWindow

func NewWindow(rule WindowRule) *Window

NewWindow returns an empty window for rule, which the caller has validated.

func (*Window) Hits

func (w *Window) Hits() int

Hits is how many held samples score at or above the threshold.

func (*Window) Len

func (w *Window) Len() int

Len is how many samples the window holds.

func (*Window) Observe

func (w *Window) Observe(score float64) Transition

Observe adds one sample's score and reports the transition it caused.

func (*Window) Scores

func (w *Window) Scores() []float64

Scores returns the held samples, oldest first, in a fresh slice.

func (*Window) Tripped

func (w *Window) Tripped() bool

Tripped reports whether the window is tripped.

type WindowRule

type WindowRule struct {
	Threshold float64
	Size      int
	Hits      int
}

WindowRule is D7's hysteresis: over the last Size samples, a window TRIPS when at least Hits score at or above Threshold, and a tripped window CLEARS only when all Size are below it. It is one definition for the live sampler and for gawk-admin's replay (D21), so "what would this setting have done?" is answered by the code that would have done it.

func (WindowRule) Validate

func (r WindowRule) Validate() error

Validate checks 0 < Threshold ≤ 1, 1 ≤ Size ≤ MaxWindow, 1 ≤ Hits ≤ Size.

type WindowSummary

type WindowSummary struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
	// Samples is how many samples the window holds, FlaggedSamples how many
	// of them scored at or above the threshold.
	Samples        int `json:"samples"`
	FlaggedSamples int `json:"flaggedSamples"`
}

WindowSummary summarizes the sampler's window at the time of the POST.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL