Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

33.2 KB
Raw Blame
"""
DRF serializers for visual_review.

Converts DTOs to/from JSON using DataclassSerializer.
"""

from datetime import datetime

from django.utils import timezone

from rest_framework import serializers
from rest_framework_dataclasses.serializers import DataclassSerializer

from ..facade.contracts import (
    AGENT_QUARANTINE_MAX_DAYS,
    FLAKINESS_RATE_DAYS,
    FLAKINESS_WINDOW_DAYS,
    PIXEL_DIFF_THRESHOLD_PERCENT,
    TOLERATION_PILEUP_WINDOW_DAYS,
    VARIANT_PILEUP_MIN,
    AddSnapshotsInput,
    AddSnapshotsResult,
    ApproveRunRequestInput,
    ApproveSnapshotInput,
    Artifact,
    BaselineEntry,
    BaselineOverview,
    BaselineQuarantineSummary,
    BaselineTotals,
    ClusterSummary,
    CreateRepoInput,
    CreateRunInput,
    CreateRunResult,
    DiffCluster,
    FinalizeResult,
    FinalizeRunRequestInput,
    FlakinessEntry,
    FlakinessOverview,
    FlakinessTotals,
    LiftOnMergeInput,
    QuarantinedIdentifierEntry,
    QuarantineInput,
    QuarantineLiftEntry,
    QuarantineSourceRun,
    RecomputeResult,
    Repo,
    RowShift,
    Run,
    RunSummary,
    ShiftBand,
    Snapshot,
    SnapshotHistoryEntry,
    SnapshotManifestItem,
    ToleratedHashEntry,
    TolerationPileupEntry,
    TolerationPileups,
    UpdateRepoRequestInput,
    UploadTarget,
    UserBasicInfo,
)
from ..facade.enums import FlakinessState, QuarantineLiftState, RunPurpose, ShiftBandKind

# --- Output Serializers ---


class ReviewStateCountsSerializer(serializers.Serializer):
    needs_review = serializers.IntegerField()
    clean = serializers.IntegerField()
    processing = serializers.IntegerField()
    stale = serializers.IntegerField()


class RunSummarySerializer(DataclassSerializer):
    class Meta:
        dataclass = RunSummary


class ArtifactSerializer(DataclassSerializer):
    class Meta:
        dataclass = Artifact


class UserBasicInfoSerializer(DataclassSerializer):
    class Meta:
        dataclass = UserBasicInfo


class DiffClusterSerializer(DataclassSerializer):
    class Meta:
        dataclass = DiffCluster


class ClusterSummarySerializer(DataclassSerializer):
    items = DiffClusterSerializer(many=True)

    class Meta:
        dataclass = ClusterSummary


class ShiftBandSerializer(DataclassSerializer):
    y = serializers.IntegerField(help_text="First row of the band, in current-image coordinates.")
    rows = serializers.IntegerField(help_text="How many rows the band covers.")
    kind = serializers.ChoiceField(
        choices=ShiftBandKind.choices,
        help_text=(
            "'inserted' when the current image gained these rows, 'deleted' when it lost them. "
            "A deleted band has no rows of its own in the current image, so its y is the seam "
            "the removed rows left behind."
        ),
    )

    class Meta:
        dataclass = ShiftBand


class RowShiftSerializer(DataclassSerializer):
    bands = ShiftBandSerializer(
        many=True,
        help_text="Where the shift happened, in current-image coordinates.",
    )
    inserted_rows = serializers.IntegerField(help_text="Rows the current image gained.")
    deleted_rows = serializers.IntegerField(help_text="Rows the current image lost.")
    residual_percentage = serializers.FloatField(
        help_text=(
            "Percentage of pixels that differ inside the rows present in both images, 0 to 100. "
            "Excludes the shift itself. The stored diff_percentage adds the area of the rows the shift "
            "added or removed, and that combined number is what the pixel threshold judges."
        )
    )
    raw_diff_percentage = serializers.FloatField(
        help_text="Percentage of pixels that differ without alignment, which is what the shift would have cost."
    )

    class Meta:
        dataclass = RowShift


class SnapshotSerializer(DataclassSerializer):
    # Explicitly mark artifact fields as nullable for OpenAPI schema
    current_artifact = ArtifactSerializer(allow_null=True, required=False)
    baseline_artifact = ArtifactSerializer(allow_null=True, required=False)
    diff_artifact = ArtifactSerializer(allow_null=True, required=False)
    reviewed_by = UserBasicInfoSerializer(allow_null=True, required=False)
    cluster_summary = ClusterSummarySerializer(allow_null=True, required=False)
    row_shift = RowShiftSerializer(allow_null=True, required=False)
    is_quarantined = serializers.BooleanField(
        required=False,
        help_text=(
            "Whether a quarantine covered this snapshot when the run was last gated, so its diff did not "
            "block the pull request. It keeps that value after the quarantine ends or a new one starts."
        ),
    )

    class Meta:
        dataclass = Snapshot


class RunSerializer(DataclassSerializer):
    approved_by = UserBasicInfoSerializer(allow_null=True, required=False)
    purpose = serializers.ChoiceField(
        choices=[p.value for p in RunPurpose],
        read_only=True,
        help_text=(
            "Why CI submitted the run. `review` runs gate the PR and need approval. `observe` runs are "
            "tracking-only, for example default-branch pushes and merge-queue runs, and can never be approved."
        ),
    )
    search_match_type = serializers.ChoiceField(
        choices=["exact", "similar"],
        allow_null=True,
        required=False,
        read_only=True,
        help_text=(
            "How this row matched the `search` query parameter: `exact` (the term is a "
            "case-insensitive substring of branch/run type, a commit SHA prefix, or an exact PR "
            "number) or `similar` (a fuzzy trigram match, returned only when no exact match "
            "exists). Null when the list is not filtered by `search`."
        ),
    )

    class Meta:
        dataclass = Run


class RepoSerializer(DataclassSerializer):
    class Meta:
        dataclass = Repo


class UploadTargetSerializer(DataclassSerializer):
    class Meta:
        dataclass = UploadTarget


class CreateRunResultSerializer(DataclassSerializer):
    class Meta:
        dataclass = CreateRunResult


class RecomputeResultSerializer(DataclassSerializer):
    class Meta:
        dataclass = RecomputeResult


class FinalizeResultSerializer(DataclassSerializer):
    class Meta:
        dataclass = FinalizeResult


# --- Input Serializers ---


class SnapshotManifestItemSerializer(DataclassSerializer):
    class Meta:
        dataclass = SnapshotManifestItem


class CreateRunInputSerializer(DataclassSerializer):
    class Meta:
        dataclass = CreateRunInput


class AddSnapshotsInputSerializer(DataclassSerializer):
    class Meta:
        dataclass = AddSnapshotsInput
        extra_kwargs = {
            "story_index_hash": {
                "help_text": (
                    "SHA-256 of the story-to-file map the CLI built from the Storybook index.json of this "
                    "run's build. Every shard of a run sends the same value. Empty when the run sends no map."
                )
            },
        }


class AddSnapshotsResultSerializer(DataclassSerializer):
    story_index_upload = UploadTargetSerializer(
        allow_null=True,
        required=False,
        help_text=(
            "Where to upload the story-to-file map, as a presigned POST with a JSON body. Null when the "
            "request sent no map, or the store already holds a map with that hash."
        ),
    )

    class Meta:
        dataclass = AddSnapshotsResult


class UpdateRepoInputSerializer(DataclassSerializer):
    class Meta:
        dataclass = UpdateRepoRequestInput
        extra_kwargs = {
            "enable_pr_comments": {
                "help_text": "Post a pull request comment when a run finds visual changes to review."
            },
            "debt_digest_enabled": {
                "help_text": (
                    "Post the visual review debt digest to the Slack channels of the teams that own the "
                    "snapshots. Off by default. The digest goes out every Monday morning."
                )
            },
        }


class ApproveSnapshotInputSerializer(DataclassSerializer):
    identifier = serializers.CharField(
        help_text="The snapshot identifier to approve (e.g. Storybook story id plus theme).",
    )
    new_hash = serializers.CharField(
        help_text="The content hash of the new baseline image to record for this identifier.",
    )

    class Meta:
        dataclass = ApproveSnapshotInput


class ApproveRunInputSerializer(DataclassSerializer):
    snapshots = ApproveSnapshotInputSerializer(
        many=True,
        required=True,
        allow_empty=False,
        help_text=(
            "Snapshots to mark reviewed, each with `identifier` and `new_hash`. This only records the "
            'review in the database (the per-snapshot "Accept change" action) — it does not change the '
            "baseline or the GitHub gate. Commit the baseline and green the gate with the finalize endpoint."
        ),
    )

    class Meta:
        dataclass = ApproveRunRequestInput


class FinalizeRunInputSerializer(DataclassSerializer):
    approve_all = serializers.BooleanField(
        required=False,
        default=False,
        help_text=(
            "Approve every still-pending changed and new snapshot before finalizing (tolerated snapshots are "
            "left untouched). Leave false to finalize a run you've already reviewed — finalizing fails if any "
            "changed/new snapshot is still unreviewed."
        ),
    )
    commit_to_github = serializers.BooleanField(
        required=False,
        default=True,
        help_text=(
            "Whether the server commits the approved baseline to the PR branch and greens the gate (the normal "
            "path — leave true). Set false only for tooling that commits the baseline itself: the server skips "
            "the commit and returns the signed YAML in `baseline_content` instead. With false, the gate is NOT "
            "greened, `metadata.baseline_commit_sha` is absent, and no post-approval PR comment is posted."
        ),
    )
    add_images_to_comment_on_pr = serializers.BooleanField(
        required=False,
        default=False,
        help_text=(
            "Whether to embed the before/after snapshot images in the post-approval PR comment. The comment "
            "itself is posted when the repo has PR comments enabled and `commit_to_github` is true: it updates "
            "the run's review prompt when the run has one, and posts a new comment when it does not. This flag "
            "only controls the images. Defaults false — the comment stays a text summary unless the reviewer "
            "opts in to attach the snapshots."
        ),
    )

    class Meta:
        dataclass = FinalizeRunRequestInput


class SnapshotHistoryEntrySerializer(DataclassSerializer):
    current_artifact = ArtifactSerializer(allow_null=True, required=False)
    row_shift = RowShiftSerializer(allow_null=True, required=False)

    class Meta:
        dataclass = SnapshotHistoryEntry


class ToleratedHashEntrySerializer(DataclassSerializer):
    class Meta:
        dataclass = ToleratedHashEntry


class MarkToleratedInputSerializer(serializers.Serializer):
    snapshot_id = serializers.UUIDField(
        help_text=(
            "UUID of the changed snapshot to mark as a known tolerated alternate. "
            "Future runs that produce the same alternate hash for this identifier will not be flagged as changes."
        ),
    )


class CompleteRunInputSerializer(serializers.Serializer):
    check_run_id = serializers.RegexField(
        r"^\d+$",
        max_length=32,
        required=False,
        help_text=(
            "Numeric GitHub Actions job ID of the CI job that completes the run, from "
            "`${{ job.check_run_id }}`. Recompute re-runs this job, so it re-reads the verdict "
            "without capturing the snapshots again. Omit it outside GitHub Actions."
        ),
    )


class QuarantineSourceRunSerializer(DataclassSerializer):
    class Meta:
        dataclass = QuarantineSourceRun


class QuarantinedIdentifierEntrySerializer(DataclassSerializer):
    created_by = UserBasicInfoSerializer(allow_null=True, required=False)
    source_run = QuarantineSourceRunSerializer(
        allow_null=True,
        required=False,
        help_text="Run whose failing snapshot prompted this quarantine. Null when quarantine was created without run context.",
    )

    class Meta:
        dataclass = QuarantinedIdentifierEntry


class BaselineQuarantineSummarySerializer(DataclassSerializer):
    created_by = UserBasicInfoSerializer(allow_null=True, required=False)
    source_run = QuarantineSourceRunSerializer(allow_null=True, required=False)

    class Meta:
        dataclass = BaselineQuarantineSummary


class QuarantineInputSerializer(DataclassSerializer):
    identifier = serializers.CharField(max_length=512, help_text="Snapshot identifier to quarantine.")
    reason = serializers.CharField(max_length=255, help_text="Why this snapshot is being quarantined.")
    expires_at = serializers.DateTimeField(
        required=False,
        allow_null=True,
        help_text=(
            "When the quarantine lifts itself, as an ISO 8601 datetime. Through MCP an omitted or later "
            f"expiry becomes {AGENT_QUARANTINE_MAX_DAYS} days from now; anywhere else omitting it means no expiry."
        ),
    )
    source_run_id = serializers.UUIDField(
        required=False,
        allow_null=True,
        help_text=(
            "Optional pointer to the run whose failing snapshot prompted this quarantine — "
            "used to surface a 'view the failing run' link later."
        ),
    )
    notify_owners = serializers.BooleanField(
        required=False,
        default=False,
        help_text=(
            "Post the quarantine to the Slack channel of the team that owns the story, naming the user "
            "who quarantined it. Only Storybook snapshots have an owning team. Best effort: skipped when "
            "the story has no owning team or the project has no Slack integration."
        ),
    )

    class Meta:
        dataclass = QuarantineInput

    def validate_expires_at(self, value: datetime | None) -> datetime | None:
        # A past expiry would end the active quarantine and store one that is already over.
        if value is not None and value <= timezone.now():
            raise serializers.ValidationError("The expiry must be in the future.")
        return value


class UnquarantineQuerySerializer(serializers.Serializer):
    identifier = serializers.CharField(max_length=512, help_text="Snapshot identifier to unquarantine")


class ErrorDetailSerializer(serializers.Serializer):
    detail = serializers.CharField(help_text="What went wrong and what to do next.")
    code = serializers.CharField(
        required=False, help_text="A stable code for the error, such as `lift_commit_unknown` or `rate_limited`."
    )


class LiftOnMergeInputSerializer(DataclassSerializer):
    identifier = serializers.CharField(
        max_length=512,
        help_text=(
            "Identifier of a quarantined snapshot in this run, such as a Storybook story ID. The snapshot's "
            "picture is what a default-branch run must render for the quarantine to lift. An unchanged snapshot "
            "uses its baseline. A changed or new snapshot must be approved first, because requesting a lift never "
            "approves a picture."
        ),
    )

    class Meta:
        dataclass = LiftOnMergeInput


class QuarantineLiftEntrySerializer(DataclassSerializer):
    id = serializers.UUIDField(help_text="UUID of the lift request.")
    quarantine_id = serializers.UUIDField(
        help_text="UUID of the quarantine event this request lifts. A later quarantine of the same snapshot is a different event."
    )
    identifier = serializers.CharField(help_text="Snapshot identifier under quarantine.")
    run_type = serializers.CharField(help_text="Run type of the quarantine, for example storybook.")
    pr_number = serializers.IntegerField(help_text="Pull request whose merge the lift waits for.")
    expected_hash = serializers.CharField(
        help_text=(
            "Content hash a default-branch run must render, against a baseline entry with the same hash, "
            "for the lift to apply."
        )
    )
    state = serializers.ChoiceField(
        choices=QuarantineLiftState.choices,
        help_text=(
            "`pending` waits for the merge and a matching default-branch run. `applied` lifted the quarantine. "
            "`cancelled` was withdrawn, or the pull request closed without merging into the run's branch. "
            "`superseded` means the quarantine ended some other way, or another request lifted it."
        ),
    )
    detail = serializers.CharField(help_text="The latest verification outcome, in plain words.")
    created_at = serializers.DateTimeField(help_text="When the lift was requested.")
    updated_at = serializers.DateTimeField(help_text="When the request last changed.")
    resolved_at = serializers.DateTimeField(
        allow_null=True, required=False, help_text="When the request left `pending`. Null while it waits."
    )
    source_run_id = serializers.UUIDField(
        allow_null=True, required=False, help_text="Run the lift was requested from. Null after that run is deleted."
    )
    requested_by = UserBasicInfoSerializer(
        allow_null=True, required=False, help_text="User who requested the lift, or on whose behalf an agent did."
    )
    merge_commit_sha = serializers.CharField(
        allow_null=True, required=False, help_text="Merge commit of the pull request. Set when the lift applies."
    )
    lifted_at_sha = serializers.CharField(
        allow_null=True,
        required=False,
        help_text=(
            "Commit of the default-branch run that proved the fix and lifted the quarantine. A branch that "
            "does not contain it still treats the snapshot as quarantined."
        ),
    )

    class Meta:
        dataclass = QuarantineLiftEntry
        # Declared here because a serializer attribute named `source` shadows `Field.source`.
        extra_kwargs = {
            "source": {
                "help_text": "Who requested the lift: `human` for a person in the UI, `agent` for an agent through MCP."
            },
        }


class CreateRepoInputSerializer(DataclassSerializer):
    class Meta:
        dataclass = CreateRepoInput


class BaselineEntrySerializer(DataclassSerializer):
    quarantine = BaselineQuarantineSummarySerializer(
        allow_null=True,
        required=False,
        help_text="Active quarantine details when `is_quarantined` is true. Null otherwise.",
    )
    active_variants_current_baseline = serializers.IntegerField(
        help_text=(
            "Accepted variants still recorded against this baseline's current hash. Unlike the "
            "30-day and 90-day counts, this has no time window: an accepted variant keeps matching "
            "without a new record. A baseline change resets it to zero."
        )
    )

    class Meta:
        dataclass = BaselineEntry


class BaselineTotalsSerializer(DataclassSerializer):
    by_run_type = serializers.DictField(child=serializers.IntegerField())
    variant_pileups = serializers.IntegerField(
        help_text="Baselines carrying three or more accepted variants of their current hash."
    )

    class Meta:
        dataclass = BaselineTotals


class BaselineOverviewSerializer(DataclassSerializer):
    entries = BaselineEntrySerializer(many=True)
    totals = BaselineTotalsSerializer()

    class Meta:
        dataclass = BaselineOverview


class FlakinessEntrySerializer(DataclassSerializer):
    variant_count = serializers.IntegerField(
        help_text=(
            "Distinct alternate hashes the classifier can still match for this snapshot's current "
            "baseline. Reads as how many different images this snapshot is currently allowed to "
            "produce. Resets when the baseline moves, because tolerations recorded against an old "
            "baseline hash can never match again."
        )
    )
    hard_count = serializers.IntegerField(
        help_text=(
            f"Default-branch runs in the last {FLAKINESS_RATE_DAYS} days where this snapshot failed "
            "the gate, so somebody could not merge until it was resolved. Counts every result that "
            "is not `unchanged`: a diff over a threshold, a baseline that was never committed or "
            "was dropped, and a baseline whose story no longer renders."
        )
    )
    soft_count = serializers.IntegerField(
        help_text=(
            f"Default-branch runs in the last {FLAKINESS_RATE_DAYS} days where this snapshot "
            "rendered differently from its baseline and a toleration absorbed it, blocking nobody."
        )
    )
    window_runs = serializers.IntegerField(
        help_text=(
            f"Completed default-branch runs of this run type in the last {FLAKINESS_RATE_DAYS} "
            "days. The rate denominator, so a reader can tell 2 failures out of 3 runs from 2 out "
            "of 300."
        )
    )
    hard_rate = serializers.FloatField(
        help_text=(
            "`hard_count` over `window_runs`. The denominator counts every run of this run type, "
            "so a snapshot that only started rendering partway through the window reads lower "
            "than it is."
        )
    )
    soft_rate = serializers.FloatField(help_text="`soft_count` over `window_runs`.")
    last_flaked_at = serializers.DateTimeField(
        allow_null=True,
        required=False,
        help_text=(
            f"Last default-branch run in the last {FLAKINESS_WINDOW_DAYS} days that rendered this "
            "snapshot differently from its baseline, whether the gate failed or a toleration "
            "absorbed it. Reads over the full window rather than the rate span, so a snapshot that "
            "stopped failing still reports when it last did. Null when nothing happened at all."
        ),
    )
    avg_diff_percentage = serializers.FloatField(
        allow_null=True,
        required=False,
        help_text=(
            "Mean fraction of pixels that differed across the live variants. Separates sub-pixel "
            "noise from a small but real rendering change."
        ),
    )
    worst_soft_diff_percentage = serializers.FloatField(
        allow_null=True,
        required=False,
        help_text=(
            f"Largest pixel diff any absorbed run in the last {FLAKINESS_WINDOW_DAYS} days "
            "produced. Reads the full window rather than the rate span, because it asks for the "
            "worst case a snapshot can produce and more days are better evidence of that. Null "
            "when nothing was absorbed."
        ),
    )
    headroom = serializers.FloatField(
        allow_null=True,
        required=False,
        help_text=(
            f"Fraction of the {PIXEL_DIFF_THRESHOLD_PERCENT}% pixel threshold that "
            "`worst_soft_diff_percentage` leaves free. A snapshot is absorbed only while it stays "
            "under the threshold, so this is what says whether it will keep doing so: 1.0 means it "
            "rendered identically every time it was absorbed, 0.0 means it reached the line and "
            "only luck kept it on the passing side. Null when nothing was absorbed, which is not "
            "the same as full headroom."
        ),
    )
    baseline_age_days = serializers.IntegerField(
        allow_null=True,
        required=False,
        help_text=(
            "Days since the first default-branch run that compared against the current baseline, "
            "which is when that baseline took effect. Reads too new for a `broken` snapshot, which "
            "records a change against an unmoved baseline on every run."
        ),
    )
    daily_hard_counts = serializers.ListField(
        child=serializers.IntegerField(),
        help_text=(
            f"Gate-failing runs per day over the last {FLAKINESS_WINDOW_DAYS} days, oldest first. "
            "Always that length, so a fixed time axis can be rendered."
        ),
    )
    daily_soft_counts = serializers.ListField(
        child=serializers.IntegerField(),
        help_text=f"Absorbed runs per day over the same {FLAKINESS_WINDOW_DAYS} days, oldest first.",
    )
    baseline_moved_day_index = serializers.IntegerField(
        allow_null=True,
        required=False,
        help_text=(
            "Index into the daily series where the baseline moved. Null when it moved before the "
            "window opened, which is the common case."
        ),
    )
    flakiness_state = serializers.ChoiceField(
        choices=[(state.value, state.value) for state in FlakinessState],
        help_text=(
            "An urgency ladder, where each rung asks for a different fix. `broken` fails nearly "
            "every run, so its baseline is wrong and quarantining it only hides that. `unstable` "
            "fails some runs and not others, the classic flake. `at_risk` never fails, but its "
            "worst absorbed diff is already touching the threshold, so the next unrelated change "
            "turns it red. `clean` has no gate failure inside the rate span, and any diff it absorbed "
            "sits far below the threshold."
        ),
    )
    needs_decision = serializers.BooleanField(
        help_text=(
            "True when an active quarantine has run out, is about to, or covers a snapshot that "
            "has stopped failing the gate. All three mean a human has to extend it or lift it."
        )
    )
    quarantine = BaselineQuarantineSummarySerializer(
        allow_null=True,
        required=False,
        help_text="Active quarantine details when `is_quarantined` is true. Null otherwise.",
    )
    owner_team = serializers.CharField(
        allow_null=True,
        required=False,
        help_text=(
            "Slug of the team that owns the file this snapshot's story lives in, from the repository's "
            "ownership files. `unowned` when no entry covers the file. Null when ownership is unknown: "
            "the snapshot is not a Storybook snapshot, the newest default-branch run sent no story index, "
            "the story is not in it, or the ownership files could not be read."
        ),
    )

    class Meta:
        dataclass = FlakinessEntry


class FlakinessTotalsSerializer(DataclassSerializer):
    listed = serializers.IntegerField(help_text="Identifiers with an entry in `entries`.")
    tracked = serializers.IntegerField(
        help_text=(
            "Identifiers with a current baseline, listed or not. The denominator that says how much "
            "of the repo renders consistently."
        )
    )
    broken = serializers.IntegerField(help_text="Identifiers whose `flakiness_state` is `broken`.")
    unstable = serializers.IntegerField(help_text="Identifiers whose `flakiness_state` is `unstable`.")
    at_risk = serializers.IntegerField(help_text="Identifiers whose `flakiness_state` is `at_risk`.")
    clean = serializers.IntegerField(
        help_text=(
            "Identifiers whose `flakiness_state` is `clean`. They are listed because they carry a "
            "quarantine or older gate failures, and reported here so every listed entry is reachable."
        )
    )
    by_run_type = serializers.DictField(
        child=serializers.IntegerField(),
        help_text="Listed identifiers per run type, so one suite's noise can be told from another's.",
    )

    class Meta:
        dataclass = FlakinessTotals


class FlakinessOverviewSerializer(DataclassSerializer):
    entries = FlakinessEntrySerializer(many=True)
    totals = FlakinessTotalsSerializer()

    class Meta:
        dataclass = FlakinessOverview


class RunSnapshotsQuerySerializer(serializers.Serializer):
    include_quarantined = serializers.BooleanField(
        default=False,
        help_text=(
            "Whether to include snapshots whose identifier is currently quarantined. "
            "Defaults to false: quarantined snapshots are excluded from results and reported "
            "in quarantined_count instead, since they are noise when reviewing real changes. "
            "This filter uses the quarantines active now. Each snapshot's `is_quarantined` flag "
            "holds the state when the run was gated, so for an older run pass true and read the flag."
        ),
    )
    exclude_unchanged = serializers.BooleanField(
        default=False,
        help_text=(
            "Whether to leave out snapshots whose result is `unchanged`. Defaults to false. "
            "Pass true to list only the changed, new and removed snapshots, which is what a "
            "review needs. A large run holds thousands of unchanged snapshots and few changes."
        ),
    )
    snapshot_id = serializers.UUIDField(
        required=False,
        help_text=(
            "Return only the snapshot with this id, read from the `id` field of a snapshot in "
            "the run. Use it to fetch one snapshot without listing the whole run."
        ),
    )
    quarantined_only = serializers.BooleanField(
        default=False,
        help_text=(
            "Whether to list only the snapshots whose identifier is currently quarantined. "
            "Defaults to false. When true, `include_quarantined` is ignored and quarantined "
            "snapshots are returned. Combine with `exclude_unchanged=false` to find a quarantined "
            "story that rendered `unchanged`, which is the snapshot to request a lift on merge for. "
            "This uses the quarantines active now, not each snapshot's `is_quarantined` flag, so on an "
            "older run it misses stories whose quarantine has ended since."
        ),
    )


class TolerationPileupsQuerySerializer(serializers.Serializer):
    min_tolerations = serializers.IntegerField(
        default=VARIANT_PILEUP_MIN,
        min_value=1,
        max_value=100,
        help_text=(
            "List a snapshot when a person or agent tolerated it at least this many times in the window. "
            f"The default, {VARIANT_PILEUP_MIN}, is the weekly debt digest's rule. Lower it to see snapshots that "
            "are starting to pile up, raise it to see only the worst ones."
        ),
    )
    min_automatic_tolerations = serializers.IntegerField(
        required=False,
        min_value=1,
        max_value=10000,
        help_text=(
            "Also list a snapshot when it collected at least this many automatic tolerations in the window. "
            "An automatic toleration is a rendering under both diff thresholds, so it never blocked anybody; "
            "many of them still mean the story is unstable. Omit to ignore automatic tolerations when "
            "deciding what to list. With 10, the list matches the Tolerate dialog's quarantine suggestion."
        ),
    )
    window_days = serializers.IntegerField(
        default=TOLERATION_PILEUP_WINDOW_DAYS,
        min_value=1,
        max_value=90,
        help_text=f"How many days back to count tolerations. Defaults to {TOLERATION_PILEUP_WINDOW_DAYS}.",
    )
    include_quarantined = serializers.BooleanField(
        default=True,
        help_text=(
            "Keep snapshots that an active quarantine already covers. They are marked with `is_quarantined`. "
            "Set to false to see only piles nobody has acted on yet."
        ),
    )
    run_type = serializers.CharField(
        required=False,
        max_length=64,
        help_text="Only list snapshots of this run type, for example `storybook` or `playwright`.",
    )
    limit = serializers.IntegerField(
        default=100,
        min_value=1,
        max_value=500,
        help_text="Maximum number of snapshots to return. `total` and `truncated` say whether more matched.",
    )


class TolerationPileupEntrySerializer(DataclassSerializer):
    identifier = serializers.CharField(help_text="Snapshot identifier, for example a Storybook story id plus theme.")
    run_type = serializers.CharField(help_text="Run type the snapshot belongs to, for example `storybook`.")
    intentional_count = serializers.IntegerField(
        help_text=(
            "Tolerations a person or agent recorded for this snapshot in the window, across every baseline. "
            "Each one accepted a different exact rendering, so a high count means the snapshot renders "
            "differently from run to run."
        )
    )
    automatic_count = serializers.IntegerField(
        help_text="Automatic tolerations in the window: renderings that came in under both diff thresholds."
    )
    is_quarantined = serializers.BooleanField(
        help_text="Whether an active quarantine already covers this snapshot, so it no longer blocks pull requests."
    )

    class Meta:
        dataclass = TolerationPileupEntry


class TolerationPileupsSerializer(DataclassSerializer):
    entries = TolerationPileupEntrySerializer(many=True, help_text="Matching snapshots, most manual tolerations first.")
    window_days = serializers.IntegerField(help_text="Length of the counting window in days that was applied.")
    min_tolerations = serializers.IntegerField(help_text="Manual toleration threshold that was applied.")
    min_automatic_tolerations = serializers.IntegerField(
        allow_null=True, help_text="Automatic toleration threshold that was applied, or null when none was."
    )
    total = serializers.IntegerField(help_text="How many snapshots matched before `limit` was applied.")
    truncated = serializers.BooleanField(help_text="True when `limit` cut the list short.")
    generated_at = serializers.DateTimeField(help_text="When the list was computed.")

    class Meta:
        dataclass = TolerationPileups