param( [string]$BaseUrl = "http://127.0.0.1:18080", [string]$EnvFile = ".env", [int]$RequestCount = 40, [string]$OutputFile = "" ) $ErrorActionPreference = "Stop" $project = Split-Path -Parent $PSScriptRoot if (-not $OutputFile) { $OutputFile = Join-Path $project "evidence\head-sampling-probe.json" } function Get-TempoStatus([string]$traceId) { try { $response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 10 "http://127.0.0.1:3200/api/traces/$traceId" return [int]$response.StatusCode } catch { if ($_.Exception.Response) { return [int]$_.Exception.Response.StatusCode } return 0 } } Push-Location $project try { $apiId = docker compose --env-file $EnvFile ps -q api if (-not $apiId) { throw 'API container is not running' } $since = [DateTimeOffset]::UtcNow.AddSeconds(-2) $statuses = @{} for ($i = 0; $i -lt $RequestCount; $i++) { try { $response = Invoke-WebRequest -UseBasicParsing -TimeoutSec 5 "$BaseUrl/health/not-found" $status = [int]$response.StatusCode } catch { $status = if ($_.Exception.Response) { [int]$_.Exception.Response.StatusCode } else { 0 } } $key = [string]$status $statuses[$key] = 1 + [int]$statuses[$key] } Start-Sleep -Seconds 15 $rawLogs = @(docker logs --since $since.ToString('o') $apiId 2>&1) $events = @() foreach ($line in $rawLogs) { $text = [string]$line $jsonStart = $text.IndexOf('{') if ($jsonStart -lt 0) { continue } try { $entry = $text.Substring($jsonStart) | ConvertFrom-Json } catch { continue } if ($entry.event -eq 'http_request_completed' -and [int]$entry.'http.response.status_code' -eq 500) { $flags = [Convert]::ToInt32([string]$entry.trace_flags, 16) $events += [pscustomobject]@{ trace_id = [string]$entry.trace_id sampled = (($flags -band 1) -eq 1) } } } $sampled = @($events | Where-Object sampled) $unsampled = @($events | Where-Object { -not $_.sampled }) if ($sampled.Count -eq 0 -or $unsampled.Count -eq 0) { throw "Expected both sampled and unsampled 500 events; sampled=$($sampled.Count), unsampled=$($unsampled.Count)" } $sampledId = $sampled[0].trace_id $unsampledId = $unsampled[0].trace_id $result = [ordered]@{ captured_at = [DateTimeOffset]::UtcNow.ToString('o') request_count = $RequestCount response_status_counts = $statuses correlated_log_count = $events.Count sampled_log_count = $sampled.Count unsampled_log_count = $unsampled.Count sampled_ratio = [Math]::Round($sampled.Count / [double]$events.Count, 4) sampled_example = [ordered]@{ trace_id = $sampledId tempo_http_status = Get-TempoStatus $sampledId } unsampled_example = [ordered]@{ trace_id = $unsampledId tempo_http_status = Get-TempoStatus $unsampledId } interpretation = 'Head sampling is decided before the HTTP outcome: a non-2xx log can exist even when its trace was not emitted to Tempo.' } $parent = Split-Path -Parent $OutputFile New-Item -ItemType Directory -Force -Path $parent | Out-Null $result | ConvertTo-Json -Depth 10 | Set-Content -Encoding utf8 $OutputFile $result | ConvertTo-Json -Depth 10 } finally { Pop-Location }