# Copyright (c) 2026 ttldtor.
# SPDX-License-Identifier: BSL-1.0
cmake_minimum_required(VERSION 3.24)

# Script-mode help must not validate paths, discover tools or create artifacts.
if(HELP)
  message([=[Usage: cmake -DHELP=ON -P tools/quality/performance.cmake
       cmake -DMODE=record <record settings> -P tools/quality/performance.cmake
       cmake -DMODE=compare <comparison settings> -P tools/quality/performance.cmake
Normalize benchmark observations and compare compatible performance receipts.
MODE is required: record or compare; no default.
record settings (all required, no defaults):
  KIND           pss, managed, compact, mvp or style_layers; raw JSON validation/metrics.
  RAW_FILE       Existing benchmark JSON with required complete provenance.
  METADATA_FILE  Existing JSON: revision, toolchain, configuration, host, workload.
  OUTPUT_DIR     New history directory; refuses an existing path.
compare settings (all required, no defaults):
  BEFORE_DIR     Existing directory containing a validated record.json and raw.json.
  AFTER_DIR      Existing compatible candidate history directory.
  OUTPUT_FILE    New comparison JSON file; parent must exist; never overwritten.
Optional: HELP=OFF; ON prints usage and returns before validation or writes.
Requires CMake >=3.24. Paths may be relative to the invocation directory.
Input metrics use nonnegative exact integers <=9007199254740991; PSS decimals
support at most 15 fractional places after trailing zero removal. Records must
match actual workload and provenance. See docs/performance.md for schemas.
Effects: record copies raw.json and writes record.json; compare writes OUTPUT_FILE.
Does not run benchmarks or decide causality/acceptance. No environment overrides.
Exit 0 on success/help; nonzero on missing, invalid or incompatible observations.
Example: cmake -DMODE=compare -DBEFORE_DIR=history/before -DAFTER_DIR=history/after -DOUTPUT_FILE=history/comparison.json -P tools/quality/performance.cmake
]=])
  return()
endif()

function(jsonQuote output value)
  string(REPLACE "\\" "\\\\" text "${value}")
  string(REPLACE "\"" "\\\"" text "${text}")
  string(REPLACE "\n" "\\n" text "${text}")
  string(REPLACE "\r" "\\r" text "${text}")
  string(REPLACE "\t" "\\t" text "${text}")
  set(${output} "\"${text}\"" PARENT_SCOPE)
endfunction()

function(fail reason)
  message(FATAL_ERROR "FAIL: ${reason}")
endfunction()

function(readJson output path)
  if(NOT EXISTS "${path}" OR IS_DIRECTORY "${path}")
    fail("JSON input is missing or not a file: ${path}")
  endif()
  file(READ "${path}" json)
  string(JSON type ERROR_VARIABLE error TYPE "${json}")
  if(NOT error STREQUAL "NOTFOUND" OR NOT type STREQUAL "OBJECT")
    fail("invalid JSON object: ${path}: ${error}")
  endif()
  set(${output} "${json}" PARENT_SCOPE)
endfunction()

function(get output json)
  string(JSON value ERROR_VARIABLE error GET "${json}" ${ARGN})
  if(NOT error STREQUAL "NOTFOUND")
    fail("missing/invalid JSON field ${ARGN}: ${error}")
  endif()
  set(${output} "${value}" PARENT_SCOPE)
endfunction()

function(requireType json expected)
  string(JSON type ERROR_VARIABLE error TYPE "${json}" ${ARGN})
  if(NOT error STREQUAL "NOTFOUND" OR NOT type STREQUAL expected)
    fail("JSON field ${ARGN} must have type ${expected}")
  endif()
endfunction()

function(requireTrue json)
  requireType("${json}" BOOLEAN ${ARGN})
  get(value "${json}" ${ARGN})
  if(NOT value)
    fail("incomplete/unverified benchmark: ${ARGN}")
  endif()
endfunction()

function(integer output json)
  requireType("${json}" NUMBER ${ARGN})
  get(value "${json}" ${ARGN})
  if(NOT value MATCHES "^[0-9]+$" OR value GREATER 9007199254740991)
    fail("unsupported numeric value at ${ARGN}; require a nonnegative integer <= 2^53-1")
  endif()
  set(${output} "${value}" PARENT_SCOPE)
endfunction()

# Keep arithmetic within the adapter's existing exact JSON integer range.
set(MAX_EXACT_INTEGER 9007199254740991)
set(MAX_PSS_FRACTIONAL_PLACES 15)
set(PSS_CASE_IDS empty small rules_64 rules_1024 duplicate_declaration invalid_early invalid_late)

function(boundedDigits output digits)
  string(REGEX REPLACE "^0+" "" digits "${digits}")
  if(digits STREQUAL "")
    set(digits 0)
  endif()
  string(LENGTH "${digits}" length)
  if(length GREATER 16 OR (length EQUAL 16 AND digits STRGREATER "${MAX_EXACT_INTEGER}"))
    fail("PSS scaled value exceeds supported 2^53-1 bound")
  endif()
  set(${output} "${digits}" PARENT_SCOPE)
endfunction()

function(boundedProduct output left right)
  math(EXPR limit "${MAX_EXACT_INTEGER} / ${right}")
  if(left GREATER limit)
    fail("PSS scaled value exceeds supported 2^53-1 bound")
  endif()
  math(EXPR value "${left} * ${right}")
  set(${output} "${value}" PARENT_SCOPE)
endfunction()

function(pssScaledDecimal output literal batch)
  if(NOT literal MATCHES "^([0-9]+)(\\.([0-9]+))?$")
    fail("unsupported PSS decimal; require nonnegative ordinary decimal notation")
  endif()
  set(whole "${CMAKE_MATCH_1}")
  set(fraction "${CMAKE_MATCH_3}")
  boundedDigits(whole "${whole}")
  boundedProduct(whole "${whole}" "${batch}")
  string(REGEX REPLACE "0+$" "" fraction "${fraction}")
  set(part 0)
  if(NOT fraction STREQUAL "")
    string(LENGTH "${fraction}" places)
    if(places GREATER MAX_PSS_FRACTIONAL_PLACES)
      fail("unsupported PSS decimal precision; at most 15 fractional places after trailing zeros")
    endif()
    set(denominator 1)
    foreach(place RANGE 1 ${places})
      math(EXPR denominator "${denominator} * 10")
    endforeach()
    boundedDigits(numerator "${fraction}")
    # Reduce the scale first, so intermediate multiplication cannot overflow.
    set(divisor "${denominator}")
    set(remainder "${batch}")
    while(NOT remainder EQUAL 0)
      math(EXPR next "${divisor} % ${remainder}")
      set(divisor "${remainder}")
      set(remainder "${next}")
    endwhile()
    math(EXPR denominator "${denominator} / ${divisor}")
    math(EXPR factor "${batch} / ${divisor}")
    math(EXPR remainder "${numerator} % ${denominator}")
    if(NOT remainder EQUAL 0)
      fail("PSS decimal cannot be scaled exactly to integer ns_per_batch")
    endif()
    math(EXPR numerator "${numerator} / ${denominator}")
    boundedProduct(part "${numerator}" "${factor}")
  endif()
  math(EXPR limit "${MAX_EXACT_INTEGER} - ${part}")
  if(whole GREATER limit)
    fail("PSS scaled value exceeds supported 2^53-1 bound")
  endif()
  math(EXPR value "${whole} + ${part}")
  set(${output} "${value}" PARENT_SCOPE)
endfunction()

function(pssSeriesMetrics output metrics data name samples batch)
  requireType("${data}" ARRAY raw)
  string(JSON count LENGTH "${data}" raw)
  if(NOT count EQUAL samples)
    fail("PSS sample count differs from retained raw values: ${name}")
  endif()
  # Extract original tokens: string(JSON GET) may round binary floating values.
  string(REGEX MATCH "\"raw\"[ \t\r\n]*:[ \t\r\n]*\\[([^]]*)\\]" matched "${data}")
  set(rawValues "${CMAKE_MATCH_1}")
  string(REGEX REPLACE "[ \t\r\n]" "" rawValues "${rawValues}")
  string(REPLACE "," ";" rawValues "${rawValues}")
  set(values "")
  foreach(literal IN LISTS rawValues)
    pssScaledDecimal(value "${literal}" "${batch}")
    list(APPEND values "${value}")
  endforeach()
  list(LENGTH values retained)
  if(NOT retained EQUAL count)
    fail("unsupported PSS raw array representation: ${name}")
  endif()
  list(SORT values COMPARE NATURAL ORDER ASCENDING)
  math(EXPR last "${count} - 1")
  list(GET values 0 minimum)
  list(GET values ${last} maximum)
  math(EXPR medianIndex "(${count} * 50 + 99) / 100 - 1")
  math(EXPR tailIndex "(${count} * 95 + 99) / 100 - 1")
  list(GET values ${medianIndex} expected_p50)
  list(GET values ${tailIndex} expected_p95)
  set(evidence "{\"status\":\"MEASURED\",\"count\":${count},\"retained_min\":${minimum},\"retained_max\":${maximum},\"raw_values_preserved\":true,\"distribution\":\"batch_means\",\"percentile\":\"nearest_rank\",\"scale\":${batch},\"original_unit\":\"ns_per_parse\"}")
  set(result "${metrics}")
  foreach(stat p50 p95)
    requireType("${data}" NUMBER "${stat}")
    string(REGEX MATCH "\"${stat}\"[ \t\r\n]*:[ \t\r\n]*([^,} \t\r\n]+)" matched "${data}")
    pssScaledDecimal(actual "${CMAKE_MATCH_1}" "${batch}")
    if(NOT actual EQUAL expected_${stat})
      fail("raw samples disagree with ${name}/${stat}")
    endif()
    appendMetric(result "${result}" "${name}/${stat}" ns_per_batch lower_is_better "${actual}" "${evidence}")
  endforeach()
  set(${output} "${result}" PARENT_SCOPE)
endfunction()

function(readPssCaseObjects output raw)
  # Tokenize complete quoted strings before braces, so escaped quotes and key-like
  # text inside string values cannot be mistaken for object members.
  set(remaining "${raw}")
  set(depth 0)
  set(position 0)
  set(caseObjects "[]")
  while(NOT remaining STREQUAL "")
    string(REGEX MATCH "\"([^\"\\\\]|\\\\.)*\"|[{}]" token "${remaining}")
    if(token STREQUAL "")
      break()
    endif()
    string(FIND "${remaining}" "${token}" offset)
    string(LENGTH "${token}" length)
    math(EXPR consumed "${offset} + ${length}")
    math(EXPR position "${position} + ${consumed}")
    string(SUBSTRING "${remaining}" ${consumed} -1 remaining)
    if(token STREQUAL "{")
      math(EXPR depth "${depth} + 1")
      set(keys${depth} "")
      set(isCase${depth} FALSE)
      math(EXPR start${depth} "${position} - 1")
    elseif(token STREQUAL "}")
      if(isCase${depth})
        math(EXPR objectLength "${position} - ${start${depth}}")
        string(SUBSTRING "${raw}" ${start${depth}} ${objectLength} object)
        jsonQuote(object "${object}")
        string(JSON count LENGTH "${caseObjects}")
        string(JSON caseObjects SET "${caseObjects}" ${count} "${object}")
      endif()
      math(EXPR depth "${depth} - 1")
    elseif(remaining MATCHES "^[ \t\r\n]*:")
      # Decode escaped key spellings through JSON, then hash to a list-safe id.
      string(JSON key GET "{\"key\":${token}}" key)
      string(SHA256 identity "${key}")
      if(identity IN_LIST keys${depth})
        fail("duplicate PSS JSON key: ${key}")
      endif()
      list(APPEND keys${depth} "${identity}")
      if(key STREQUAL "case")
        set(isCase${depth} TRUE)
      endif()
    endif()
  endwhile()
  set(${output} "${caseObjects}" PARENT_SCOPE)
endfunction()

function(normalizePss output raw)
  readPssCaseObjects(caseObjects "${raw}")
  foreach(key schema api unit timing successful_result_destruction partial_error_cleanup memory)
    requireType("${raw}" STRING "${key}")
    get(${key} "${raw}" "${key}")
  endforeach()
  if(NOT schema STREQUAL "portals.pss.v1" OR NOT api STREQUAL "parsePss" OR NOT unit STREQUAL "ns_per_parse"
      OR NOT timing STREQUAL "parse_return_with_clock_overhead" OR NOT successful_result_destruction STREQUAL "excluded"
      OR NOT partial_error_cleanup STREQUAL "included" OR NOT memory STREQUAL "NOT_MEASURED")
    fail("unsupported PSS schema, timing, cleanup or units")
  endif()
  foreach(key samples warmup batch checksum)
    integer(${key} "${raw}" "${key}")
  endforeach()
  if(samples EQUAL 0 OR batch EQUAL 0 OR checksum EQUAL 0)
    fail("PSS samples, batch and validation checksum must be positive")
  endif()
  requireType("${raw}" BOOLEAN reverse)
  copyFields(signature "${raw}" schema api unit timing successful_result_destruction partial_error_cleanup
    memory samples warmup batch reverse)
  requireType("${raw}" ARRAY cases)
  string(JSON caseCount LENGTH "${raw}" cases)
  list(LENGTH PSS_CASE_IDS expectedCases)
  if(NOT caseCount EQUAL expectedCases)
    fail("PSS benchmark must contain all seven cases")
  endif()
  string(JSON retainedCases LENGTH "${caseObjects}")
  if(NOT retainedCases EQUAL caseCount)
    fail("unsupported PSS case object representation")
  endif()
  set(metrics "[]")
  set(caseSignatures "[]")
  set(names "")
  math(EXPR lastCase "${caseCount} - 1")
  foreach(index RANGE 0 ${lastCase})
    get(data "${caseObjects}" ${index})
    string(JSON canonical GET "${data}")
    get(expected "${raw}" cases ${index})
    if(NOT canonical STREQUAL expected)
      fail("unsupported PSS case object representation")
    endif()
    # v1 cases contain only scalar fields and the direct raw numeric array.
    # Reject nested extensions before regex-based numeric token extraction.
    string(JSON memberCount LENGTH "${data}")
    math(EXPR lastMember "${memberCount} - 1")
    foreach(memberIndex RANGE 0 ${lastMember})
      string(JSON member MEMBER "${data}" ${memberIndex})
      string(JSON memberType TYPE "${data}" "${member}")
      if(memberType STREQUAL "OBJECT" OR (memberType STREQUAL "ARRAY" AND NOT member STREQUAL "raw"))
        fail("unsupported nested PSS case field: ${member}")
      endif()
    endforeach()
    requireType("${data}" STRING case)
    get(name "${data}" case)
    if(NOT name IN_LIST PSS_CASE_IDS OR name IN_LIST names)
      fail("unknown/duplicate PSS case identity: ${name}")
    endif()
    list(APPEND names "${name}")
    foreach(key source_bytes expected_rules)
      integer(value "${data}" "${key}")
    endforeach()
    requireType("${data}" BOOLEAN valid)
    copyFields(caseSignature "${data}" case source_bytes valid expected_rules)
    string(JSON caseSignatures SET "${caseSignatures}" ${index} "${caseSignature}")
    pssSeriesMetrics(metrics "${metrics}" "${data}" "${name}" "${samples}" "${batch}")
  endforeach()
  string(JSON signature SET "${signature}" cases "${caseSignatures}")
  set(${output} "{\"signature\":${signature},\"metrics\":${metrics}}" PARENT_SCOPE)
endfunction()

function(copyFields output json)
  set(object "{}")
  foreach(key IN LISTS ARGN)
    string(JSON type ERROR_VARIABLE error TYPE "${json}" "${key}")
    if(NOT error STREQUAL "NOTFOUND")
      fail("missing workload/signature field ${key}")
    endif()
    get(value "${json}" "${key}")
    if(type STREQUAL "STRING")
      jsonQuote(value "${value}")
    elseif(type STREQUAL "BOOLEAN")
      if(value)
        set(value true)
      else()
        set(value false)
      endif()
    elseif(type STREQUAL "NULL")
      set(value null)
    endif()
    string(JSON object SET "${object}" "${key}" "${value}")
  endforeach()
  set(${output} "${object}" PARENT_SCOPE)
endfunction()

function(appendMetric output metrics name unit direction value evidence)
  jsonQuote(nameJson "${name}")
  jsonQuote(unitJson "${unit}")
  string(JSON count LENGTH "${metrics}")
  set(metric "{\"name\":${nameJson},\"unit\":${unitJson},\"direction\":\"${direction}\",\"value\":${value},\"evidence\":${evidence}}")
  string(JSON result SET "${metrics}" ${count} "${metric}")
  set(${output} "${result}" PARENT_SCOPE)
endfunction()

function(scalarMetric output metrics raw name unit direction)
  string(JSON type ERROR_VARIABLE error TYPE "${raw}" ${ARGN})
  if(NOT error STREQUAL "NOTFOUND")
    fail("missing metric ${name}")
  endif()
  if(type STREQUAL "NULL")
    set(value null)
  else()
    integer(value "${raw}" ${ARGN})
  endif()
  appendMetric(result "${metrics}" "${name}" "${unit}" "${direction}" "${value}" "{}")
  set(${output} "${result}" PARENT_SCOPE)
endfunction()

function(seriesMetrics output metrics data name rawKey)
  # An explicit unit selects the style-layer count/p50/p95/samples summary shape.
  set(shortSummary FALSE)
  if(ARGC GREATER 5)
    set(shortSummary TRUE)
  endif()
  integer(count "${data}" count)
  requireType("${data}" ARRAY "${rawKey}")
  string(JSON retained LENGTH "${data}" "${rawKey}")
  if(NOT retained EQUAL count)
    fail("sample count differs from retained raw values: ${name}")
  endif()
  set(complete TRUE)
  if(rawKey STREQUAL "raw")
    integer(overflow "${data}" overflow)
    requireType("${data}" BOOLEAN percentiles_complete)
    get(declaredComplete "${data}" percentiles_complete)
    requireType("${data}" STRING unit)
    get(unit "${data}" unit)
    set(supportedUnits "ns" "ns including wait" "ms" "ns (logical ms * 1000000)")
    if(NOT unit IN_LIST supportedUnits)
      fail("unsupported sample units: ${unit}")
    endif()
    if(overflow GREATER 0 OR count EQUAL 0)
      set(complete FALSE)
    endif()
    if(NOT "${complete}" STREQUAL "${declaredComplete}")
      # CMake JSON booleans use ON/OFF, while local booleans use TRUE/FALSE.
      if((complete AND NOT declaredComplete) OR (NOT complete AND declaredComplete))
        fail("inconsistent percentile completeness: ${name}")
      endif()
    endif()
  else()
    set(overflow 0)
    set(unit ns)
    if(shortSummary)
      set(unit "${ARGV5}")
    endif()
    if(count EQUAL 0)
      fail("managed sample set must not be empty")
    endif()
  endif()
  # Parse the retained array once; repeated string(JSON ... index) reparses the whole array.
  get(rawValues "${data}" "${rawKey}")
  string(REGEX REPLACE "[ \t\r\n]" "" rawValues "${rawValues}")
  if(NOT rawValues MATCHES "^\\[([0-9]+(,[0-9]+)*)?\\]$")
    fail("unsupported raw sample values: ${name}")
  endif()
  string(REGEX REPLACE "^\\[|\\]$" "" values "${rawValues}")
  string(REPLACE "," ";" values "${values}")
  foreach(value IN LISTS values)
    if(value GREATER 9007199254740991)
      fail("raw sample exceeds supported 2^53-1 bound: ${name}")
    endif()
  endforeach()
  if(count GREATER 0)
    math(EXPR last "${count} - 1")
    list(SORT values COMPARE NATURAL ORDER ASCENDING)
    list(GET values 0 minimum)
    list(GET values ${last} maximum)
  else()
    set(minimum null)
    set(maximum null)
  endif()
  if(complete)
    math(EXPR medianIndex "(${count} * 50 + 99) / 100 - 1")
    math(EXPR tailIndex "(${count} * 95 + 99) / 100 - 1")
    list(GET values ${medianIndex} expected_p50)
    list(GET values ${tailIndex} expected_p95)
    set(expected_max "${maximum}")
    set(summaryStats p50 p95)
    if(NOT shortSummary)
      list(APPEND summaryStats max)
    endif()
    foreach(stat IN LISTS summaryStats)
      integer(actual "${data}" "${stat}")
      if(NOT actual EQUAL expected_${stat})
        fail("raw samples disagree with ${name}/${stat}")
      endif()
    endforeach()
    if(rawKey STREQUAL "samples" AND NOT shortSummary)
      integer(actualMin "${data}" min)
      if(NOT actualMin EQUAL minimum)
        fail("raw samples disagree with ${name}/min")
      endif()
    endif()
    set(state MEASURED)
  else()
    foreach(stat p50 p95 max)
      requireType("${data}" NULL "${stat}")
      set(expected_${stat} null)
    endforeach()
    set(state NOT_MEASURED)
  endif()
  set(evidence "{\"status\":\"${state}\",\"count\":${count},\"overflow\":${overflow},\"retained_min\":${minimum},\"retained_max\":${maximum},\"raw_values_preserved\":true}")
  set(result "${metrics}")
  foreach(stat p50 p95)
    appendMetric(result "${result}" "${name}/${stat}" "${unit}" lower_is_better "${expected_${stat}}" "${evidence}")
  endforeach()
  set(${output} "${result}" PARENT_SCOPE)
endfunction()

# Called by normalize for schema-1 style-layer reports. Retained summaries are
# checked against raw samples; invalid identities or workload stamps fail import.
function(normalizeStyleLayers output raw)
  integer(schema "${raw}" schema)
  if(NOT schema EQUAL 1)
    fail("unsupported style_layers schema")
  endif()
  requireTrue("${raw}" complete)
  requireTrue("${raw}" correctness_verified)
  requireType("${raw}" BOOLEAN check_only)
  get(checkOnly "${raw}" check_only)
  if(checkOnly)
    fail("--check observations are correctness fixtures, not performance baselines")
  endif()
  requireType("${raw}" BOOLEAN assertions_enabled)
  foreach(key compiler build clock unit percentile frame_workload)
    requireType("${raw}" STRING "${key}")
    get(value "${raw}" "${key}")
    if(value STREQUAL "")
      fail("empty style_layers workload field: ${key}")
    endif()
  endforeach()
  foreach(key pointer_bits samples_per_case warmup_per_case)
    integer(${key} "${raw}" "${key}")
  endforeach()
  if(samples_per_case EQUAL 0)
    fail("style_layers sample count must be positive")
  endif()
  get(unit "${raw}" unit)
  get(percentile "${raw}" percentile)
  if(NOT unit STREQUAL "ns" OR NOT percentile STREQUAL "nearest_rank")
    fail("unsupported style_layers units/percentile method")
  endif()
  copyFields(signature "${raw}" schema compiler build assertions_enabled pointer_bits clock unit percentile
    samples_per_case warmup_per_case frame_workload)
  set(allocationsMeasured FALSE)
  set(allocationScope not_instrumented)
  string(JSON allocationType ERROR_VARIABLE allocationError TYPE "${raw}" allocations)
  if(allocationError STREQUAL "NOTFOUND" AND NOT allocationType STREQUAL "NULL")
    requireType("${raw}" STRING allocations)
    get(allocationScope "${raw}" allocations)
    if(NOT allocationScope STREQUAL "ordinary_new_calls_and_requested_bytes")
      fail("unsupported style_layers allocation scope")
    endif()
    set(allocationsMeasured TRUE)
  endif()
  # Allocation counters run inside timed phases and change the timing workload.
  jsonQuote(allocationScopeJson "${allocationScope}")
  string(JSON signature SET "${signature}" allocation_instrumentation "${allocationScopeJson}")
  requireType("${raw}" ARRAY cases)
  string(JSON caseCount LENGTH "${raw}" cases)
  if(caseCount EQUAL 0)
    fail("style_layers benchmark cases are empty")
  endif()
  set(metrics "[]")
  set(caseSignatures "[]")
  set(identities "")
  math(EXPR lastCase "${caseCount} - 1")
  foreach(index RANGE 0 ${lastCase})
    get(data "${raw}" cases ${index})
    foreach(key api visibility operation update_kind)
      requireType("${data}" STRING "${key}")
      get(${key} "${data}" "${key}")
      if("${${key}}" STREQUAL "")
        fail("empty style_layers case identity: ${key}")
      endif()
    endforeach()
    foreach(key controls theme_rules)
      integer(${key} "${data}" "${key}")
    endforeach()
    copyFields(caseSignature "${data}" api controls theme_rules visibility operation update_kind)
    string(SHA256 identity "${caseSignature}")
    if(identity IN_LIST identities)
      fail("duplicate style_layers case identity")
    endif()
    list(APPEND identities "${identity}")
    string(JSON caseSignatures SET "${caseSignatures}" ${index} "${caseSignature}")
    set(caseName "${api}/controls-${controls}/rules-${theme_rules}/${visibility}/${operation}/${update_kind}")
    foreach(phase update frame_render)
      get(series "${data}" "${phase}")
      integer(count "${series}" count)
      if(NOT count EQUAL samples_per_case)
        fail("style_layers per-case sample count differs: ${caseName}/${phase}")
      endif()
      seriesMetrics(metrics "${metrics}" "${series}" "${caseName}/${phase}" samples ns)
    endforeach()
    foreach(field update_allocations frame_allocations update_allocated_bytes frame_allocated_bytes)
      if(field MATCHES "_bytes$")
        set(allocationUnit bytes)
      else()
        set(allocationUnit calls)
      endif()
      if(allocationsMeasured)
        get(series "${data}" "${field}")
        integer(count "${series}" count)
        if(NOT count EQUAL samples_per_case)
          fail("style_layers allocation sample count differs: ${caseName}/${field}")
        endif()
        seriesMetrics(metrics "${metrics}" "${series}" "${caseName}/${field}" samples "${allocationUnit}")
      else()
        string(JSON fieldType ERROR_VARIABLE fieldError TYPE "${data}" "${field}")
        if(fieldError STREQUAL "NOTFOUND" AND NOT fieldType STREQUAL "NULL")
          fail("style_layers allocation series requires measured allocation scope")
        endif()
        foreach(stat p50 p95)
          appendMetric(metrics "${metrics}" "${caseName}/${field}/${stat}" "${allocationUnit}"
            lower_is_better null "{\"status\":\"NOT_MEASURED\",\"raw_values_preserved\":false}")
        endforeach()
      endif()
    endforeach()
    foreach(counter defaults_calls paint_calls render_commands effective_invalidation update_redraw_requests
        explicit_frame_count idle_redraws terminal_output_bytes)
      if(counter STREQUAL "terminal_output_bytes")
        set(counterUnit bytes)
      elseif(counter STREQUAL "render_commands")
        set(counterUnit commands)
      elseif(counter STREQUAL "effective_invalidation")
        set(counterUnit flags)
      elseif(counter STREQUAL "explicit_frame_count")
        set(counterUnit frames)
      else()
        set(counterUnit calls)
      endif()
      integer(value "${data}" "${counter}")
      scalarMetric(metrics "${metrics}" "${data}" "${caseName}/${counter}" "${counterUnit}" context "${counter}")
    endforeach()
  endforeach()
  # Preserve producer order so reordered or missing scenarios cannot pair by index.
  string(JSON signature SET "${signature}" cases "${caseSignatures}")
  set(${output} "{\"signature\":${signature},\"metrics\":${metrics}}" PARENT_SCOPE)
endfunction()

function(normalize output raw kind)
  set(metrics "[]")
  if(kind STREQUAL "pss")
    normalizePss(result "${raw}")
    set(${output} "${result}" PARENT_SCOPE)
    return()
  elseif(kind STREQUAL "style_layers")
    normalizeStyleLayers(result "${raw}")
    set(${output} "${result}" PARENT_SCOPE)
    return()
  elseif(kind STREQUAL "managed")
    integer(schema "${raw}" schema)
    if(NOT schema EQUAL 1)
      fail("unsupported managed schema")
    endif()
    requireTrue("${raw}" complete)
    requireTrue("${raw}" correctness_verified)
    requireType("${raw}" BOOLEAN check_only)
    requireType("${raw}" BOOLEAN assertions_enabled)
    foreach(key compiler build clock unit percentile)
      requireType("${raw}" STRING "${key}")
    endforeach()
    foreach(key pointer_bits samples_per_case warmup_per_case)
      integer(value "${raw}" "${key}")
    endforeach()
    get(checkOnly "${raw}" check_only)
    if(checkOnly)
      fail("--check observations are correctness fixtures, not performance baselines")
    endif()
    copyFields(signature "${raw}" compiler build assertions_enabled pointer_bits clock unit percentile
      samples_per_case warmup_per_case check_only)
    get(unit "${raw}" unit)
    get(percentile "${raw}" percentile)
    if(NOT unit STREQUAL "ns" OR NOT percentile STREQUAL "nearest_rank")
      fail("unsupported managed units/percentile method")
    endif()
  elseif(kind STREQUAL "compact")
    foreach(key samples warmup nodes)
      integer(value "${raw}" "${key}")
    endforeach()
    copyFields(signature "${raw}" samples warmup nodes)
    scalarMetric(metrics "${metrics}" "${raw}" scene_nodes nodes context nodes)
  elseif(kind STREQUAL "mvp")
    integer(schema "${raw}" schema)
    if(NOT schema EQUAL 1)
      fail("unsupported MVP schema")
    endif()
    requireTrue("${raw}" complete)
    get(mvpKind "${raw}" kind)
    if(mvpKind STREQUAL "application")
      foreach(flag application_ok frame_cap_respected fixed_viewport_baseline runner_accounting_matches)
        requireTrue("${raw}" "${flag}")
      endforeach()
      integer(exitCode "${raw}" exit_code)
      if(NOT exitCode EQUAL 0)
        fail("incomplete MVP application observation")
      endif()
      copyFields(signature "${raw}" kind compiler build platform transport generator configured_rate seed rows
        fps_cap warmup_ms duration_ms delay_ms ascii ansi16 diagnostics_enabled sample_capacity sample_boundary)
      foreach(key kind compiler build platform transport generator sample_boundary)
        requireType("${raw}" STRING "${key}")
      endforeach()
      foreach(key configured_rate seed rows fps_cap warmup_ms duration_ms delay_ms sample_capacity)
        integer(value "${raw}" "${key}")
      endforeach()
      foreach(key ascii ansi16 diagnostics_enabled)
        requireType("${raw}" BOOLEAN "${key}")
      endforeach()
      get(acceptance "${raw}" acceptance)
      requireTrue("${acceptance}" lossless_ohlc)
      requireTrue("${raw}" shutdown provider_stopped)
      requireTrue("${raw}" shutdown terminal_closed)
      foreach(viewportKey viewport initial_viewport)
        foreach(dimension width height)
          integer(value "${acceptance}" "${viewportKey}" "${dimension}")
        endforeach()
      endforeach()
      integer(value "${acceptance}" resize_batches)
      copyFields(viewport "${acceptance}" viewport initial_viewport resize_batches)
      string(JSON signature SET "${signature}" viewports "${viewport}")
      get(phases "${raw}" phase_samples_ns)
      string(JSON phaseCount LENGTH "${phases}")
      if(phaseCount EQUAL 0)
        fail("MVP phase series are missing")
      endif()
      math(EXPR lastPhase "${phaseCount} - 1")
      foreach(index RANGE 0 ${lastPhase})
        string(JSON phase MEMBER "${phases}" ${index})
        get(data "${phases}" "${phase}")
        seriesMetrics(metrics "${metrics}" "${data}" "phase/${phase}" raw)
      endforeach()
      foreach(series transport_read_ns dashboard_display_ingress_ms runner_input_control_ns)
        get(data "${raw}" "${series}")
        seriesMetrics(metrics "${metrics}" "${data}" "${series}" raw)
      endforeach()
      foreach(counter accepted_frames confirmed_bytes encoded_bytes wall_ns process_cpu_ns)
        if(counter STREQUAL "accepted_frames")
          set(counterUnit frames)
        elseif(counter MATCHES "bytes$")
          set(counterUnit bytes)
        else()
          set(counterUnit ns)
        endif()
        scalarMetric(metrics "${metrics}" "${raw}" "window/${counter}" "${counterUnit}" context window "${counter}")
      endforeach()
    elseif(mvpKind STREQUAL "separate_encoding")
      requireTrue("${raw}" oracle_verified)
      requireType("${raw}" STRING capture)
      foreach(key ascii ansi16)
        requireType("${raw}" BOOLEAN "${key}")
      endforeach()
      foreach(key frames repetitions full_bytes diff_bytes)
        integer(value "${raw}" "${key}")
      endforeach()
      copyFields(signature "${raw}" kind capture frames repetitions ascii ansi16)
      foreach(series encode_full_ns encode_diff_ns render_saved_cell_scene_ns)
        get(data "${raw}" "${series}")
        seriesMetrics(metrics "${metrics}" "${data}" "${series}" raw)
      endforeach()
      foreach(counter frames full_bytes diff_bytes)
        if(counter STREQUAL "frames")
          set(counterUnit frames)
        else()
          set(counterUnit bytes)
        endif()
        scalarMetric(metrics "${metrics}" "${raw}" "${counter}" "${counterUnit}" context "${counter}")
      endforeach()
    else()
      fail("unsupported MVP kind: ${mvpKind}")
    endif()
  else()
    fail("KIND must be managed, compact, mvp, pss, or style_layers")
  endif()

  if(kind STREQUAL "managed" OR kind STREQUAL "compact")
    requireType("${raw}" ARRAY cases)
    string(JSON caseCount LENGTH "${raw}" cases)
    if(caseCount EQUAL 0)
      fail("benchmark cases are empty")
    endif()
    set(caseSignatures "[]")
    math(EXPR lastCase "${caseCount} - 1")
    foreach(case RANGE 0 ${lastCase})
      get(caseData "${raw}" cases ${case})
      get(api "${caseData}" api)
      requireType("${caseData}" STRING api)
      if(kind STREQUAL "managed")
        foreach(key rows scene_nodes styled_controls)
          integer(value "${caseData}" "${key}")
        endforeach()
        copyFields(caseSignature "${caseData}" api rows scene_nodes styled_controls)
        get(rows "${caseData}" rows)
        set(caseName "${api}/rows-${rows}")
        scalarMetric(metrics "${metrics}" "${caseData}" "${caseName}/scene_nodes" nodes context scene_nodes)
        get(phases "${caseData}" phases)
        requireType("${caseData}" OBJECT phases)
      else()
        copyFields(caseSignature "${caseData}" api)
        string(JSON columnsType ERROR_VARIABLE columnsError TYPE "${caseData}" columns)
        if(columnsError STREQUAL "NOTFOUND")
          integer(columns "${caseData}" columns)
          string(JSON caseSignature SET "${caseSignature}" columns "${columns}")
        endif()
        set(caseName "${api}")
        get(phases "${caseData}" phases)
        requireType("${caseData}" ARRAY phases)
      endif()
      string(JSON phaseCount LENGTH "${phases}")
      if(phaseCount EQUAL 0)
        fail("benchmark phases are empty: ${caseName}")
      endif()
      math(EXPR lastPhase "${phaseCount} - 1")
      foreach(index RANGE 0 ${lastPhase})
        if(kind STREQUAL "managed")
          string(JSON phase MEMBER "${phases}" ${index})
          get(data "${phases}" "${phase}")
          integer(samples "${data}" count)
          integer(expectedSamples "${raw}" samples_per_case)
          if(NOT samples EQUAL expectedSamples)
            fail("managed per-case sample count differs")
          endif()
          seriesMetrics(metrics "${metrics}" "${data}" "${caseName}/${phase}" samples)
        else()
          get(data "${phases}" ${index})
          get(phase "${data}" phase)
          integer(samples "${raw}" samples)
          if(samples EQUAL 0)
            fail("compact sample count must be positive")
          endif()
          integer(p50 "${data}" p50_ns)
          integer(p95 "${data}" p95_ns)
          integer(minimum "${data}" allocation_calls_min)
          integer(maximum "${data}" allocation_calls_max)
          if(p50 GREATER p95 OR minimum GREATER maximum)
            fail("inconsistent compact percentile/allocation bounds")
          endif()
          set(evidence "{\"count\":${samples},\"raw_values_preserved\":false,\"timing_variance\":null,\"allocation_min\":${minimum},\"allocation_max\":${maximum}}")
          foreach(stat p50 p95)
            appendMetric(metrics "${metrics}" "${caseName}/${phase}/${stat}" ns lower_is_better "${${stat}}" "${evidence}")
          endforeach()
          foreach(bound min max)
            scalarMetric(metrics "${metrics}" "${data}" "${caseName}/${phase}/allocation_calls_${bound}"
              allocation_calls lower_is_better "allocation_calls_${bound}")
          endforeach()
        endif()
      endforeach()
      string(JSON caseSignatures SET "${caseSignatures}" ${case} "${caseSignature}")
    endforeach()
    string(JSON signature SET "${signature}" cases "${caseSignatures}")
  endif()
  set(${output} "{\"signature\":${signature},\"metrics\":${metrics}}" PARENT_SCOPE)
endfunction()

function(validateMetadata metadata)
  foreach(key revision configuration workload)
    requireType("${metadata}" STRING "${key}")
    get(value "${metadata}" "${key}")
    if(value STREQUAL "")
      fail("metadata ${key} must not be empty")
    endif()
  endforeach()
  requireType("${metadata}" OBJECT toolchain)
  foreach(key compiler configure_command)
    requireType("${metadata}" STRING toolchain "${key}")
    get(value "${metadata}" toolchain "${key}")
    if(value STREQUAL "")
      fail("toolchain metadata ${key} must not be empty")
    endif()
  endforeach()
  requireType("${metadata}" OBJECT host)
  foreach(key os cpu power_mode background_load)
    requireType("${metadata}" STRING host "${key}")
    get(value "${metadata}" host "${key}")
    if(value STREQUAL "")
      fail("host metadata ${key} must not be empty")
    endif()
  endforeach()
  requireType("${metadata}" ARRAY command)
  string(JSON commandCount LENGTH "${metadata}" command)
  if(commandCount EQUAL 0)
    fail("metadata command must record actual benchmark argv")
  endif()
  math(EXPR last "${commandCount} - 1")
  foreach(index RANGE 0 ${last})
    requireType("${metadata}" STRING command ${index})
  endforeach()
  integer(exitCode "${metadata}" benchmark_exit_code)
  if(NOT exitCode EQUAL 0)
    fail("benchmark process did not exit successfully")
  endif()
endfunction()

function(validateRawProvenance raw metadata)
  foreach(key compiler build)
    string(JSON type ERROR_VARIABLE error TYPE "${raw}" "${key}")
    if(error STREQUAL "NOTFOUND")
      get(actual "${raw}" "${key}")
      if(key STREQUAL "compiler")
        get(recorded "${metadata}" toolchain compiler)
      else()
        get(recorded "${metadata}" configuration)
      endif()
      if(NOT actual STREQUAL recorded)
        fail("metadata contradicts raw benchmark ${key} stamp")
      endif()
    endif()
  endforeach()
endfunction()

function(validateMetricNames normalized)
  get(metrics "${normalized}" metrics)
  string(JSON count LENGTH "${metrics}")
  if(count EQUAL 0)
    fail("no supported measurements in benchmark JSON")
  endif()
  math(EXPR last "${count} - 1")
  set(names)
  foreach(index RANGE 0 ${last})
    get(name "${metrics}" ${index} name)
    if(name IN_LIST names)
      fail("duplicate measurement identity: ${name}")
    endif()
    list(APPEND names "${name}")
  endforeach()
endfunction()

function(loadRecord output directory)
  readJson(record "${directory}/record.json")
  readJson(raw "${directory}/raw.json")
  file(SHA256 "${directory}/raw.json" actualHash)
  get(expectedHash "${record}" raw_sha256)
  integer(schema "${record}" schema)
  get(adapter "${record}" adapter)
  if(NOT schema EQUAL 1 OR NOT adapter STREQUAL "portals-performance-1" OR NOT actualHash STREQUAL expectedHash)
    fail("unsupported record schema or raw SHA256 mismatch: ${directory}")
  endif()
  get(metadata "${record}" metadata)
  validateMetadata("${metadata}")
  validateRawProvenance("${raw}" "${metadata}")
  get(kind "${record}" benchmark_kind)
  normalize(normalized "${raw}" "${kind}")
  validateMetricNames("${normalized}")
  # Recompute normalized data from the retained raw bytes rather than trusting cached numbers.
  get(storedNormalized "${record}" normalized)
  string(JSON recomputed GET "${normalized}")
  if(NOT storedNormalized STREQUAL recomputed)
    fail("normalized record differs from its raw input: ${directory}")
  endif()
  set(${output} "${record}" PARENT_SCOPE)
endfunction()

function(ratio output numerator denominator)
  if(denominator EQUAL 0)
    set(${output} null PARENT_SCOPE)
    return()
  endif()
  # Long division avoids multiplying a large counter by one million.
  math(EXPR quotient "${numerator} / ${denominator}")
  math(EXPR remainder "${numerator} % ${denominator}")
  set(result "${quotient}.")
  foreach(digit RANGE 1 6)
    math(EXPR remainder "${remainder} * 10")
    math(EXPR part "${remainder} / ${denominator}")
    math(EXPR remainder "${remainder} % ${denominator}")
    string(APPEND result "${part}")
  endforeach()
  set(${output} "${result}" PARENT_SCOPE)
endfunction()

if(NOT DEFINED MODE)
  fail("MODE=record or MODE=compare is required")
endif()

if(MODE STREQUAL "record")
  foreach(required RAW_FILE METADATA_FILE OUTPUT_DIR KIND)
    if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "")
      fail("${required} is required in record mode")
    endif()
  endforeach()
  get_filename_component(OUTPUT_DIR "${OUTPUT_DIR}" ABSOLUTE)
  if(EXISTS "${OUTPUT_DIR}")
    fail("refusing to overwrite an existing history directory: ${OUTPUT_DIR}")
  endif()
  readJson(raw "${RAW_FILE}")
  readJson(metadata "${METADATA_FILE}")
  validateMetadata("${metadata}")
  validateRawProvenance("${raw}" "${metadata}")
  normalize(normalized "${raw}" "${KIND}")
  validateMetricNames("${normalized}")
  file(SHA256 "${RAW_FILE}" rawHash)
  string(TIMESTAMP captured "%Y-%m-%dT%H:%M:%SZ" UTC)
  set(record "{\"schema\":1,\"adapter\":\"portals-performance-1\",\"benchmark_kind\":\"${KIND}\",\"captured_utc\":\"${captured}\",\"raw_sha256\":\"${rawHash}\",\"metadata\":${metadata},\"normalized\":${normalized}}")
  # Preserve the original JSON bytes, including whitespace, line endings, and retained raw samples.
  file(MAKE_DIRECTORY "${OUTPUT_DIR}")
  file(COPY_FILE "${RAW_FILE}" "${OUTPUT_DIR}/raw.json")
  file(WRITE "${OUTPUT_DIR}/record.json" "${record}\n")
  message(STATUS "RECORDED: ${KIND} raw observation and provenance in ${OUTPUT_DIR}")
elseif(MODE STREQUAL "compare")
  foreach(required BEFORE_DIR AFTER_DIR OUTPUT_FILE)
    if(NOT DEFINED ${required} OR "${${required}}" STREQUAL "")
      fail("${required} is required in compare mode")
    endif()
  endforeach()
  if(EXISTS "${OUTPUT_FILE}")
    fail("refusing to overwrite comparison output: ${OUTPUT_FILE}")
  endif()
  loadRecord(before "${BEFORE_DIR}")
  loadRecord(after "${AFTER_DIR}")
  get(beforeMetadata "${before}" metadata)
  get(afterMetadata "${after}" metadata)
  get(beforeKind "${before}" benchmark_kind)
  get(afterKind "${after}" benchmark_kind)
  if(NOT beforeKind STREQUAL afterKind)
    fail("incompatible benchmark kinds")
  endif()
  foreach(key toolchain configuration host workload)
    get(baseline "${beforeMetadata}" "${key}")
    get(candidate "${afterMetadata}" "${key}")
    if(NOT baseline STREQUAL candidate)
      fail("incompatible metadata: ${key}")
    endif()
  endforeach()
  get(beforeSignature "${before}" normalized signature)
  get(afterSignature "${after}" normalized signature)
  if(NOT beforeSignature STREQUAL afterSignature)
    fail("incompatible actual benchmark workload/signature")
  endif()
  get(beforeMetrics "${before}" normalized metrics)
  get(afterMetrics "${after}" normalized metrics)
  string(JSON beforeCount LENGTH "${beforeMetrics}")
  string(JSON afterCount LENGTH "${afterMetrics}")
  if(NOT beforeCount EQUAL afterCount)
    fail("incompatible measurement shapes")
  endif()
  set(comparisons "[]")
  math(EXPR last "${beforeCount} - 1")
  foreach(index RANGE 0 ${last})
    foreach(key name unit direction)
      get(baseline "${beforeMetrics}" ${index} "${key}")
      get(candidate "${afterMetrics}" ${index} "${key}")
      if(NOT baseline STREQUAL candidate)
        fail("incompatible measurement ${key} at index ${index}")
      endif()
      set(${key} "${baseline}")
    endforeach()
    string(JSON beforeType TYPE "${beforeMetrics}" ${index} value)
    string(JSON afterType TYPE "${afterMetrics}" ${index} value)
    get(beforeEvidence "${beforeMetrics}" ${index} evidence)
    get(afterEvidence "${afterMetrics}" ${index} evidence)
    if(beforeType STREQUAL "NULL" OR afterType STREQUAL "NULL")
      set(baseline null)
      set(candidate null)
      if(NOT beforeType STREQUAL "NULL")
        get(baseline "${beforeMetrics}" ${index} value)
      endif()
      if(NOT afterType STREQUAL "NULL")
        get(candidate "${afterMetrics}" ${index} value)
      endif()
      set(delta null)
      set(relative null)
      set(observation NOT_MEASURED)
    else()
      get(baseline "${beforeMetrics}" ${index} value)
      get(candidate "${afterMetrics}" ${index} value)
      math(EXPR delta "${candidate} - ${baseline}")
      ratio(relative "${candidate}" "${baseline}")
      if(direction STREQUAL "context")
        set(observation CONTEXT)
      elseif(candidate GREATER baseline)
        set(observation CANDIDATE_REGRESSION)
      elseif(candidate LESS baseline)
        set(observation OBSERVED_DECREASE)
      else()
        set(observation UNCHANGED)
      endif()
    endif()
    jsonQuote(nameJson "${name}")
    jsonQuote(unitJson "${unit}")
    set(comparison "{\"name\":${nameJson},\"unit\":${unitJson},\"before\":${baseline},\"after\":${candidate},\"delta\":${delta},\"after_over_before\":${relative},\"observation\":\"${observation}\",\"before_evidence\":${beforeEvidence},\"after_evidence\":${afterEvidence}}")
    string(JSON comparisons SET "${comparisons}" ${index} "${comparison}")
  endforeach()
  get(beforeRevision "${beforeMetadata}" revision)
  get(afterRevision "${afterMetadata}" revision)
  jsonQuote(beforeRevisionJson "${beforeRevision}")
  jsonQuote(afterRevisionJson "${afterRevision}")
  file(WRITE "${OUTPUT_FILE}" "{\"schema\":1,\"status\":\"COMPARED\",\"benchmark_kind\":\"${beforeKind}\",\"before_revision\":${beforeRevisionJson},\"after_revision\":${afterRevisionJson},\"independent_runs_per_side\":1,\"causality\":\"NOT_ESTABLISHED\",\"interpretation\":\"Candidate changes require repeated observations under controlled noise; within-run samples are not independent runs.\",\"metrics\":${comparisons}}\n")
  message(STATUS "COMPARED: ${beforeCount} observations; no causal or acceptance verdict")
else()
  fail("MODE must be record or compare")
endif()
