//go:build selected_root_capacity_evidence

package records

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"math"
	"os"
	"path/filepath"
	"runtime"
	"sort"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	mysqldriver "github.com/go-sql-driver/mysql"
	issuetrackerconformance "github.com/nexuscrm/app-packs-conformance/issue-tracker"
	"github.com/nexuscrm/db"
	"github.com/nexuscrm/kernel/pkg/ports"
	"github.com/nexuscrm/metadata"
	"github.com/nexuscrm/permissions"
	"github.com/nexuscrm/persistence"
	"github.com/nexuscrm/shared/pkg/constants"
	"github.com/nexuscrm/shared/pkg/contract"
	"github.com/nexuscrm/shared/pkg/models"
	"github.com/rs/zerolog"
)

const (
	p1cM1RevisionFile = "../tests/performance/selected-root-read/revisions.env"
	p1cM1RecordID     = "ISS-CAPACITY-001"
	p1cM1Object       = "Issue"
)

type p1cM1PackObject struct {
	APIName string `json:"apiName"`
	Fields  []struct {
		APIName string `json:"apiName"`
	} `json:"fields"`
}

type p1cM1Percentiles struct {
	P50  int `json:"p50"`
	P95  int `json:"p95"`
	P99  int `json:"p99"`
	P999 int `json:"p999"`
	Max  int `json:"max"`
}

type p1cM1BoundaryPair struct {
	Boundary int    `json:"boundary"`
	OneOver  int    `json:"one_over"`
	Basis    string `json:"basis"`
}

type p1cM1Latency struct {
	P50Micros  int64 `json:"p50_micros"`
	P95Micros  int64 `json:"p95_micros"`
	P99Micros  int64 `json:"p99_micros"`
	P999Micros int64 `json:"p999_micros"`
	MaxMicros  int64 `json:"max_micros"`
}

type p1cM1PoolStats struct {
	OpenConnections   int   `json:"open_connections"`
	InUse             int   `json:"in_use"`
	Idle              int   `json:"idle"`
	WaitCount         int64 `json:"wait_count"`
	WaitMicros        int64 `json:"wait_micros"`
	MaxIdleClosed     int64 `json:"max_idle_closed"`
	MaxIdleTimeClosed int64 `json:"max_idle_time_closed"`
	MaxLifetimeClosed int64 `json:"max_lifetime_closed"`
}

type p1cM1Measurement struct {
	Name                    string         `json:"name"`
	SelectedFields          int            `json:"selected_fields"`
	Concurrency             int            `json:"concurrency"`
	ConcurrencyClass        string         `json:"concurrency_class"`
	Warmup                  int            `json:"warmup"`
	Samples                 int            `json:"samples"`
	AdapterSamples          int            `json:"adapter_samples"`
	SemanticRequestBytes    int            `json:"semantic_request_bytes"`
	CompleteResponseBytes   int            `json:"complete_authorized_response_bytes"`
	AdapterLatency          p1cM1Latency   `json:"adapter_latency"`
	EndToEndLatency         p1cM1Latency   `json:"end_to_end_latency"`
	RepositoryQueries       int64          `json:"repository_queries"`
	DatabaseQueries         int64          `json:"database_queries"`
	QueriesPerRequest       float64        `json:"repository_queries_per_request"`
	QueryCountScope         string         `json:"query_count_scope"`
	AllocatedBytes          uint64         `json:"allocated_bytes"`
	AllocatedBytesPerSample float64        `json:"allocated_bytes_per_sample"`
	Mallocs                 uint64         `json:"mallocs"`
	MallocsPerSample        float64        `json:"mallocs_per_sample"`
	AllocationScope         string         `json:"allocation_scope"`
	Errors                  int            `json:"errors"`
	PoolBefore              p1cM1PoolStats `json:"pool_before"`
	PoolAfter               p1cM1PoolStats `json:"pool_after"`
}

type p1cM1Outcome struct {
	Name              string `json:"name"`
	SemanticOutcome   string `json:"semantic_outcome"`
	ContextError      string `json:"context_error,omitempty"`
	RepositoryQueries int64  `json:"repository_queries"`
	LatencyMicros     int64  `json:"latency_micros"`
}

type p1cM1IdentifierEvidence struct {
	Dimension                  string `json:"dimension"`
	ValidatorGrammar           string `json:"validator_grammar"`
	ValidatorLengthBehavior    string `json:"validator_length_behavior"`
	MetadataStorageWidth       int    `json:"metadata_storage_width,omitempty"`
	PhysicalStorageAt          int    `json:"physical_storage_at,omitempty"`
	PhysicalStorageJustOver    int    `json:"physical_storage_just_over,omitempty"`
	PhysicalAtAccepted         bool   `json:"physical_at_accepted"`
	PhysicalJustOverAccepted   bool   `json:"physical_just_over_accepted"`
	PublicAPIBehavior          string `json:"public_api_behavior"`
	ObservedPackMaximum        int    `json:"observed_pack_maximum,omitempty"`
	ObservedEnvironmentMaximum *int   `json:"observed_environment_maximum,omitempty"`
	ProductionEvidence         string `json:"production_evidence"`
	OwnershipNote              string `json:"ownership_note"`
}

type p1cM1AnonymousAggregates struct {
	NexusCRMRevision             string           `json:"nexuscrm_revision"`
	AppPacksRevision             string           `json:"app_packs_revision"`
	FixtureRevision              string           `json:"fixture_revision"`
	SourceEnvironment            string           `json:"source_environment"`
	ObservationTimeUTC           string           `json:"observation_time_utc"`
	DatabaseRevisionAvailable    bool             `json:"database_revision_available"`
	MetadataObjects              int              `json:"metadata_objects"`
	MetadataFieldCount           p1cM1Percentiles `json:"metadata_field_count"`
	MaxObjectIdentifierLength    int              `json:"max_object_identifier_length"`
	MaxFieldIdentifierLength     int              `json:"max_field_identifier_length"`
	MaxCRMRecordIdentifierLength int              `json:"max_crm_record_identifier_length"`
	CRMRecordTablesSampled       int              `json:"crm_record_tables_sampled"`
	PayloadPolicy                string           `json:"payload_policy"`
}

type p1cM1Report struct {
	SchemaVersion string `json:"schema_version"`
	RunID         string `json:"run_id"`
	Complete      bool   `json:"complete"`
	Revisions     struct {
		NexusCRM string `json:"nexuscrm"`
		AppPacks string `json:"app_packs"`
		Fixture  string `json:"fixture"`
	} `json:"revisions"`
	Environment struct {
		Classification          string            `json:"classification"`
		Representative          bool              `json:"representative"`
		RepresentativenessScope string            `json:"representativeness_scope"`
		GoVersion               string            `json:"go_version"`
		OS                      string            `json:"os"`
		Architecture            string            `json:"architecture"`
		CPU                     string            `json:"cpu"`
		MemoryBytes             uint64            `json:"memory_bytes"`
		TiDBVersion             string            `json:"tidb_version"`
		Database                string            `json:"database"`
		PoolConfig              map[string]int    `json:"pool_config"`
		DatabaseConfig          map[string]string `json:"database_config"`
	} `json:"environment"`
	Command string `json:"command"`
	Dataset struct {
		SyntheticOnly       bool `json:"synthetic_only"`
		Rows                int  `json:"rows"`
		DeclaredFields      int  `json:"declared_fields"`
		StoredColumns       int  `json:"stored_columns"`
		CurrentSelectsStar  bool `json:"current_repository_selects_star"`
		SelectionPushedDown bool `json:"selection_pushed_down"`
	} `json:"dataset"`
	CRMFieldCounts struct {
		Source             string           `json:"source"`
		Objects            int              `json:"objects"`
		Distribution       p1cM1Percentiles `json:"distribution"`
		ObservedSelections string           `json:"observed_production_selections"`
	} `json:"crm_field_counts"`
	SelectedFieldProbeCounts []int                     `json:"selected_field_probe_counts"`
	CandidateBoundaryPairs   []p1cM1BoundaryPair       `json:"candidate_boundary_pairs"`
	Measurements             []p1cM1Measurement        `json:"measurements"`
	Outcomes                 []p1cM1Outcome            `json:"outcomes"`
	Identifiers              []p1cM1IdentifierEvidence `json:"identifiers"`
	ValueShapes              []string                  `json:"value_shapes"`
	ValueShapeResult         any                       `json:"value_shape_result"`
	KnownObservations        []string                  `json:"known_observations"`
	AnonymousAggregates      *p1cM1AnonymousAggregates `json:"anonymous_aggregates,omitempty"`
	Wire                     struct {
		SemanticEncoding       string `json:"semantic_encoding"`
		GeneratedCodec         string `json:"generated_codec"`
		TransportHeadroom      string `json:"transport_headroom"`
		RequiredFollowUp       string `json:"required_follow_up"`
		SemanticSizeDisclaimer string `json:"semantic_size_disclaimer"`
	} `json:"wire"`
	LimitsDecision     string `json:"limits_decision"`
	DeadlineEvidence   string `json:"deadline_evidence"`
	HarnessReadTimeout string `json:"harness_read_timeout"`
	RawArtifact        string `json:"raw_artifact"`
}

type p1cM1CountingRepository struct {
	ports.RecordRepository
	findOne atomic.Int64
}

func (r *p1cM1CountingRepository) FindOne(ctx context.Context, tableName, id string) (models.SObject, error) {
	r.findOne.Add(1)
	return r.RecordRepository.FindOne(ctx, tableName, id)
}

type p1cM1TimedReader struct {
	reader  issuetrackerconformance.PointReader
	observe func(time.Duration)
}

func TestSelectedRootCapacityEvidence_CreateScratchDatabase(t *testing.T) {
	zerolog.SetGlobalLevel(zerolog.WarnLevel)
	scratchDatabase, scratchToken := p1cM1ScratchIdentity(t)
	p1cM1RequireSourceDatabase(t)
	dbConn := p1cM1OpenConfiguredDB(t)

	if _, err := dbConn.Exec("CREATE DATABASE `" + scratchDatabase + "` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); err != nil {
		t.Fatalf("create owned scratch database: %v", err)
	}
	created := true
	t.Cleanup(func() {
		if created {
			_, _ = dbConn.Exec("DROP DATABASE `" + scratchDatabase + "`")
		}
	})
	markerTable := "`" + scratchDatabase + "`.`_P1C_M1_ScratchGuard`"
	if _, err := dbConn.Exec("CREATE TABLE " + markerTable + " (`GuardToken` VARCHAR(64) NOT NULL)"); err != nil {
		t.Fatalf("create scratch ownership marker: %v", err)
	}
	if _, err := dbConn.Exec("INSERT INTO "+markerTable+" (`GuardToken`) VALUES (?)", scratchToken); err != nil {
		t.Fatalf("write scratch ownership marker: %v", err)
	}
	created = false
}

func TestSelectedRootCapacityEvidence_CollectAnonymousAggregates(t *testing.T) {
	zerolog.SetGlobalLevel(zerolog.WarnLevel)
	p1cM1RequireSourceDatabase(t)
	outPath := requiredP1cM1Env(t, "P1C_M1_ANON_AGGREGATES_FILE")
	packSpec := requiredP1cM1Env(t, "P1C_M1_CRM_OBJECT_SPEC")
	objects := readP1cM1PackObjects(t, packSpec)
	appPacksRevision, fixtureRevision := p1cM1PinnedRevisions(t)
	p1cM1RequireRevisionEnvironment(t, appPacksRevision, fixtureRevision)
	dbConn := p1cM1OpenConfiguredDB(t)

	rows, err := dbConn.Query("SELECT COUNT(*) FROM `_System_Field` GROUP BY `ObjectId` ORDER BY COUNT(*)")
	if err != nil {
		t.Fatalf("collect metadata field-count aggregates: %v", err)
	}
	var fieldCounts []int
	for rows.Next() {
		var count int
		if err := rows.Scan(&count); err != nil {
			_ = rows.Close()
			t.Fatalf("scan metadata field-count aggregate: %v", err)
		}
		fieldCounts = append(fieldCounts, count)
	}
	if err := rows.Close(); err != nil {
		t.Fatalf("close metadata aggregate rows: %v", err)
	}
	if err := rows.Err(); err != nil {
		t.Fatalf("iterate metadata aggregate rows: %v", err)
	}
	if len(fieldCounts) == 0 {
		t.Fatal("no metadata field-count aggregates returned")
	}

	var maxObjectIdentifier, maxFieldIdentifier int
	if err := dbConn.QueryRow("SELECT COALESCE(MAX(CHAR_LENGTH(`ApiName`)),0) FROM `_System_Object`").Scan(&maxObjectIdentifier); err != nil {
		t.Fatalf("collect object identifier aggregate: %v", err)
	}
	if err := dbConn.QueryRow("SELECT COALESCE(MAX(CHAR_LENGTH(`ApiName`)),0) FROM `_System_Field`").Scan(&maxFieldIdentifier); err != nil {
		t.Fatalf("collect field identifier aggregate: %v", err)
	}

	maxRecordIdentifier, sampledTables := 0, 0
	for _, object := range objects {
		if !p1cM1SafeIdentifier(object.APIName) {
			t.Fatalf("pinned CRM object identifier %q is invalid", object.APIName)
		}
		var length int
		err := dbConn.QueryRow("SELECT COALESCE(MAX(CHAR_LENGTH(`Id`)),0) FROM `" + object.APIName + "`").Scan(&length)
		if err != nil {
			var mysqlErr *mysqldriver.MySQLError
			if errors.As(err, &mysqlErr) && mysqlErr.Number == 1146 {
				continue
			}
			t.Fatalf("collect public CRM record identifier aggregate: %v", err)
		}
		sampledTables++
		if length > maxRecordIdentifier {
			maxRecordIdentifier = length
		}
	}
	if sampledTables == 0 {
		t.Fatal("no pinned public CRM object table was available for anonymous record identifier aggregation")
	}

	aggregate := p1cM1AnonymousAggregates{
		NexusCRMRevision:             requiredP1cM1Env(t, "P1C_M1_NEXUSCRM_REVISION"),
		AppPacksRevision:             appPacksRevision,
		FixtureRevision:              fixtureRevision,
		SourceEnvironment:            requiredP1cM1Env(t, "P1C_M1_AGGREGATE_ENVIRONMENT"),
		ObservationTimeUTC:           time.Now().UTC().Format(time.RFC3339Nano),
		DatabaseRevisionAvailable:    false,
		MetadataObjects:              len(fieldCounts),
		MetadataFieldCount:           p1cM1IntegerDistribution(fieldCounts),
		MaxObjectIdentifierLength:    maxObjectIdentifier,
		MaxFieldIdentifierLength:     maxFieldIdentifier,
		MaxCRMRecordIdentifierLength: maxRecordIdentifier,
		CRMRecordTablesSampled:       sampledTables,
		PayloadPolicy:                "numeric-aggregates-only; no identifiers, names, records, or traffic payloads",
	}
	if !p1cM1SafeLabel(aggregate.SourceEnvironment) {
		t.Fatalf("aggregate environment label %q is invalid", aggregate.SourceEnvironment)
	}
	encoded, err := json.MarshalIndent(aggregate, "", "  ")
	if err != nil {
		t.Fatalf("encode anonymous aggregate evidence: %v", err)
	}
	if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
		t.Fatalf("create anonymous aggregate directory: %v", err)
	}
	if err := os.WriteFile(outPath, append(encoded, '\n'), 0o644); err != nil {
		t.Fatalf("write anonymous aggregate evidence: %v", err)
	}
}

func TestSelectedRootCapacityEvidence_DropScratchDatabase(t *testing.T) {
	zerolog.SetGlobalLevel(zerolog.WarnLevel)
	scratchDatabase, scratchToken := p1cM1ScratchIdentity(t)
	p1cM1RequireSourceDatabase(t)
	dbConn := p1cM1OpenConfiguredDB(t)
	var databases int
	if err := dbConn.QueryRow("SELECT COUNT(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?", scratchDatabase).Scan(&databases); err != nil {
		t.Fatalf("check scratch database existence: %v", err)
	}
	if databases == 0 {
		t.Logf("owned scratch database %s is already absent", scratchDatabase)
		return
	}
	markerTable := "`" + scratchDatabase + "`.`_P1C_M1_ScratchGuard`"
	var storedToken string
	if err := dbConn.QueryRow("SELECT `GuardToken` FROM " + markerTable + " LIMIT 1").Scan(&storedToken); err != nil {
		t.Fatalf("refuse to drop scratch database without its ownership marker: %v", err)
	}
	if storedToken != scratchToken {
		t.Fatal("refuse to drop scratch database whose ownership token differs")
	}
	if _, err := dbConn.Exec("DROP DATABASE `" + scratchDatabase + "`"); err != nil {
		t.Fatalf("drop owned scratch database: %v", err)
	}
}

func TestSelectedRootCapacityEvidence_RecoverScratchDatabase(t *testing.T) {
	zerolog.SetGlobalLevel(zerolog.WarnLevel)
	runID := requiredP1cM1Env(t, "P1C_M1_RECOVERY_RUN_ID")
	if !p1cM1SafeLabel(runID) {
		t.Fatalf("recovery run ID %q is invalid", runID)
	}
	prefix := "p1c_m1_" + p1cM1DatabaseSuffix(runID) + "_"
	p1cM1RequireSourceDatabase(t)
	dbConn := p1cM1OpenConfiguredDB(t)
	rows, err := dbConn.Query("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE LEFT(SCHEMA_NAME, ?) = ?", len(prefix), prefix)
	if err != nil {
		t.Fatalf("find recovery scratch database: %v", err)
	}
	var matches []string
	for rows.Next() {
		var databaseName string
		if err := rows.Scan(&databaseName); err != nil {
			_ = rows.Close()
			t.Fatalf("scan recovery scratch database: %v", err)
		}
		matches = append(matches, databaseName)
	}
	if err := rows.Close(); err != nil {
		t.Fatalf("close recovery scratch rows: %v", err)
	}
	if err := rows.Err(); err != nil {
		t.Fatalf("iterate recovery scratch rows: %v", err)
	}
	if len(matches) == 0 {
		t.Logf("no scratch database remains for run %s", runID)
		return
	}
	if len(matches) != 1 {
		t.Fatalf("refuse recovery for run %s: found %d matching scratch databases", runID, len(matches))
	}
	databaseName := matches[0]
	if !p1cM1SafeIdentifier(databaseName) || !strings.HasPrefix(databaseName, prefix) {
		t.Fatalf("refuse invalid recovery database %q", databaseName)
	}
	markerTable := "`" + databaseName + "`.`_P1C_M1_ScratchGuard`"
	var storedToken string
	if err := dbConn.QueryRow("SELECT `GuardToken` FROM " + markerTable + " LIMIT 1").Scan(&storedToken); err != nil {
		t.Fatalf("refuse recovery without scratch ownership marker: %v", err)
	}
	if len(storedToken) != 64 || !p1cM1LowerHex(storedToken) {
		t.Fatal("refuse recovery with invalid scratch ownership token")
	}
	if _, err := dbConn.Exec("DROP DATABASE `" + databaseName + "`"); err != nil {
		t.Fatalf("drop recovered scratch database: %v", err)
	}
	t.Logf("recovered marker-owned scratch database for run %s", runID)
}

func (r p1cM1TimedReader) Retrieve(ctx context.Context, objectName, id string, user *models.UserSession) (contract.Record, error) {
	started := time.Now()
	record, err := r.reader.Retrieve(ctx, objectName, id, user)
	r.observe(time.Since(started))
	return record, err
}

func TestSelectedRootCapacityEvidence(t *testing.T) {
	zerolog.SetGlobalLevel(zerolog.WarnLevel)
	outDir := requiredP1cM1Env(t, "P1C_M1_OUT_DIR")
	packSpec := requiredP1cM1Env(t, "P1C_M1_CRM_OBJECT_SPEC")
	runID := requiredP1cM1Env(t, "P1C_M1_RUN_ID")
	nexusRevision := requiredP1cM1Env(t, "P1C_M1_NEXUSCRM_REVISION")
	appPacksRevision, fixtureRevision := p1cM1PinnedRevisions(t)
	p1cM1RequireRevisionEnvironment(t, appPacksRevision, fixtureRevision)
	scratchDatabase, scratchToken := p1cM1RequiredScratchConfig(t)

	objects := readP1cM1PackObjects(t, packSpec)
	fieldCounts, maxObjectLen, maxFieldLen := p1cM1PackShape(objects)
	distribution := p1cM1IntegerDistribution(fieldCounts)
	candidates := p1cM1Candidates(distribution)
	maxFields := candidates[len(candidates)-1]

	dbConn, err := database.OpenDBFromEnv(database.DefaultPoolOptions())
	if err != nil {
		t.Fatalf("open configured TiDB database: %v", err)
	}
	t.Cleanup(func() { _ = dbConn.Close() })
	if err := dbConn.PingContext(context.Background()); err != nil {
		t.Fatalf("ping configured TiDB database: %v", err)
	}
	p1cM1VerifyScratchDatabase(t, dbConn, scratchDatabase, scratchToken)

	fields, selections := p1cM1Fields(maxFields)
	p1cM1CreateDataset(t, dbConn, fields)
	t.Cleanup(func() {
		_, _ = dbConn.Exec("DROP VIEW IF EXISTS `Issue`")
		_, _ = dbConn.Exec("DROP TABLE IF EXISTS `Issue`")
		_, _ = dbConn.Exec("DROP TABLE IF EXISTS `IssueBase`")
	})

	realRepo := persistence.NewRecordRepository(dbConn)
	countingRepo := &p1cM1CountingRepository{RecordRepository: realRepo}
	adapter, user := p1cM1Adapter(countingRepo, fields, true, map[string]bool{"flshidden": false})
	realRepo.SetSchemaProvider(adapter.persistence.metadata)

	report := p1cM1Report{SchemaVersion: "p1c-m1.v1", RunID: runID}
	report.Revisions.NexusCRM = nexusRevision
	report.Revisions.AppPacks = appPacksRevision
	report.Revisions.Fixture = fixtureRevision
	report.Environment.Classification = getenvDefault("P1C_M1_ENVIRONMENT", "local-development-probe")
	report.Environment.Representative = envBool("P1C_M1_REPRESENTATIVE")
	report.Environment.RepresentativenessScope = getenvDefault("P1C_M1_REPRESENTATIVENESS_SCOPE", "local development only; not representative of production traffic or deployment topology")
	report.Environment.GoVersion = runtime.Version()
	report.Environment.OS = runtime.GOOS
	report.Environment.Architecture = runtime.GOARCH
	report.Environment.CPU = getenvDefault("P1C_M1_CPU", "not-recorded")
	report.Environment.MemoryBytes = envUint64("P1C_M1_MEMORY_BYTES")
	report.Environment.Database = "temporary synthetic TiDB database"
	report.Environment.PoolConfig = map[string]int{
		"max_open_connections": database.DefaultPoolOptions().MaxOpenConns,
		"max_idle_connections": database.DefaultPoolOptions().MaxIdleConns,
	}
	_ = dbConn.QueryRow("SELECT VERSION()").Scan(&report.Environment.TiDBVersion)
	report.Environment.DatabaseConfig = p1cM1DatabaseConfig(dbConn)
	report.Command = getenvDefault("P1C_M1_COMMAND", "scripts/performance/run-selected-root-capacity-evidence.sh")
	report.Dataset.SyntheticOnly = true
	report.Dataset.Rows = 2
	report.Dataset.DeclaredFields = len(fields)
	report.Dataset.StoredColumns = len(fields) + 1 // Id + OwnerId + fields, except DeclaredAbsent.
	report.Dataset.CurrentSelectsStar = true
	report.Dataset.SelectionPushedDown = false
	report.CRMFieldCounts.Source = "nexuscrm-app-packs@" + appPacksRevision + ":salesforce-crm-standard/objects/standard_objects_spec.json"
	report.CRMFieldCounts.Objects = len(fieldCounts)
	report.CRMFieldCounts.Distribution = distribution
	report.CRMFieldCounts.ObservedSelections = "unavailable: current CRM route requests the full root record and no public/anonymized production selected-field traffic histogram was supplied"
	report.SelectedFieldProbeCounts = candidates
	report.CandidateBoundaryPairs = []p1cM1BoundaryPair{
		{Boundary: distribution.Max, OneOver: distribution.Max + 1, Basis: "current production CRM pack-declared observed maximum"},
		{Boundary: 64, OneOver: 65, Basis: "exploratory power-of-two candidate; not an approved limit"},
		{Boundary: 128, OneOver: 129, Basis: "exploratory power-of-two candidate; not an approved limit"},
		{Boundary: 256, OneOver: 257, Basis: "exploratory power-of-two candidate; not an approved limit"},
	}
	report.ValueShapes = []string{"string", "boolean:true", "boolean:false", "integer:signed", "integer:zero", "decimal:zero", "decimal:large-precision", "date", "datetime", "reference-id", "explicit-null", "declared-but-absent", "FLS-hidden", "empty-string"}
	valueConsumer, err := issuetrackerconformance.NewConsumer(adapter, issuetrackerconformance.CurrentInProcessErrorClassifier)
	if err != nil {
		t.Fatalf("create value-shape consumer: %v", err)
	}
	valueResult, err := valueConsumer.Read(context.Background(), issuetrackerconformance.Request{RecordID: p1cM1RecordID, Fields: selections[:14]}, user)
	if err != nil {
		t.Fatalf("read value-shape matrix: %v", err)
	}
	if valueResult.Outcome != issuetrackerconformance.OutcomeOK {
		t.Fatalf("value-shape outcome = %s, want ok", valueResult.Outcome)
	}
	report.ValueShapeResult = valueResult
	report.KnownObservations = []string{
		"the current repository reads every stored column with SELECT * before selected-root projection",
		"the current numeric hydration path converts DECIMAL values through float64; the large-precision and zero-scale observations in value_shape_result are lossy current behavior",
		"metadata and permission inputs are deterministic public-service test seams, so the measured database query is the single real RecordRepository.FindOne query, not a cold-cache production metadata query count",
		"no public/anonymized production selected-field traffic histogram was supplied",
	}
	if aggregatePath := strings.TrimSpace(os.Getenv("P1C_M1_ANON_AGGREGATES_FILE")); aggregatePath != "" {
		report.AnonymousAggregates = readP1cM1AnonymousAggregates(t, aggregatePath)
	}
	report.Wire.SemanticEncoding = "Go encoding/json compact JSON over the fixture semantic Request and Result structs"
	report.Wire.GeneratedCodec = "unavailable by design: P2 protobuf generation is blocked"
	report.Wire.TransportHeadroom = "not measurable until a reviewed generated codec and configured transport send/receive limits exist"
	report.Wire.RequiredFollowUp = "replay these exact semantic vectors through the future generated codec and compare encoded maxima with configured send/receive limits before approving transport headroom"
	report.Wire.SemanticSizeDisclaimer = "canonical semantic JSON is a reproducible logical-size proxy, not a prediction or approval of protobuf/gRPC wire bytes"
	report.LimitsDecision = "none; P1c remains blocked and this artifact records evidence only"
	report.DeadlineEvidence = "already-canceled, in-flight cancellation, and 25ms in-flight deadline propagation are measured; no route SLO or total retry budget is present, so a maximum request deadline cannot be selected from this artifact alone"
	readTimeout := envDuration(t, "P1C_M1_READ_TIMEOUT", 30*time.Second)
	report.HarnessReadTimeout = readTimeout.String() + " per benchmark read; harness liveness guard only, not a proposed or observed Runtime request deadline"
	report.RawArtifact = outDir + "/result.json"
	if err := os.MkdirAll(outDir, 0o755); err != nil {
		t.Fatalf("create artifact directory: %v", err)
	}

	samples := envInt("P1C_M1_SAMPLES", 1200)
	warmup := envInt("P1C_M1_WARMUP", 100)
	concurrencyGrid := p1cM1ConcurrencyGrid()
	stopLoadEscalation := false
	for _, selectedCount := range candidates {
		for _, concurrency := range concurrencyGrid {
			fmt.Printf("P1C_M1_PROGRESS starting fields-%d/concurrency-%d warmup=%d samples=%d read-timeout=%s\n", selectedCount, concurrency, warmup, samples, readTimeout)
			measurement := p1cM1Measure(t, adapter, countingRepo, user, selections[:selectedCount], selectedCount, concurrency, warmup, samples, readTimeout, dbConn)
			report.Measurements = append(report.Measurements, measurement)
			p1cM1WriteReport(t, outDir+"/partial-result.json", report)
			fmt.Printf("P1C_M1_PROGRESS completed %s errors=%d p99=%dµs max=%dµs\n", measurement.Name, measurement.Errors, measurement.EndToEndLatency.P99Micros, measurement.EndToEndLatency.MaxMicros)
			if measurement.Errors > 0 {
				t.Logf("stopping concurrency escalation after %s produced %d errors", measurement.Name, measurement.Errors)
				stopLoadEscalation = true
				break
			}
		}
		if stopLoadEscalation {
			break
		}
	}

	report.Outcomes = p1cM1MeasureOutcomes(t, dbConn, fields, selections, user)
	report.Identifiers = p1cM1MeasureIdentifiers(t, dbConn, maxObjectLen, maxFieldLen)
	if report.AnonymousAggregates != nil {
		for i := range report.Identifiers {
			switch report.Identifiers[i].Dimension {
			case "object API identifier":
				report.Identifiers[i].ObservedEnvironmentMaximum = &report.AnonymousAggregates.MaxObjectIdentifierLength
				report.Identifiers[i].ProductionEvidence = "anonymized aggregate from " + report.AnonymousAggregates.SourceEnvironment + "; not a production payload or approved maximum"
			case "field API identifier":
				report.Identifiers[i].ObservedEnvironmentMaximum = &report.AnonymousAggregates.MaxFieldIdentifierLength
				report.Identifiers[i].ProductionEvidence = "anonymized aggregate from " + report.AnonymousAggregates.SourceEnvironment + "; not a production payload or approved maximum"
			case "record identifier":
				report.Identifiers[i].ObservedEnvironmentMaximum = &report.AnonymousAggregates.MaxCRMRecordIdentifierLength
				report.Identifiers[i].ProductionEvidence = "anonymized aggregate across pinned public CRM object tables in " + report.AnonymousAggregates.SourceEnvironment + "; not a production payload or approved maximum"
			}
		}
	}

	report.Complete = true
	p1cM1WriteReport(t, outDir+"/result.json", report)
	if err := os.WriteFile(outDir+"/interpretation.md", []byte(p1cM1Markdown(report)), 0o644); err != nil {
		t.Fatalf("write Markdown report: %v", err)
	}
	t.Logf("P1c-M1 evidence written to %s", outDir)
}

func p1cM1Measure(t *testing.T, adapter *ContractService, repo *p1cM1CountingRepository, user *models.UserSession, selection []issuetrackerconformance.FieldSelection, selectedCount, concurrency, warmup, samples int, readTimeout time.Duration, dbConn *sql.DB) p1cM1Measurement {
	t.Helper()
	var adapterMu sync.Mutex
	adapterDurations := make([]time.Duration, 0, samples+warmup)
	timed := p1cM1TimedReader{reader: adapter, observe: func(d time.Duration) {
		adapterMu.Lock()
		adapterDurations = append(adapterDurations, d)
		adapterMu.Unlock()
	}}
	consumer, err := issuetrackerconformance.NewConsumer(timed, issuetrackerconformance.CurrentInProcessErrorClassifier)
	if err != nil {
		t.Fatalf("NewConsumer: %v", err)
	}
	req := issuetrackerconformance.Request{RecordID: p1cM1RecordID, Fields: selection}
	requestBytes, err := json.Marshal(req)
	if err != nil {
		t.Fatalf("encode semantic request: %v", err)
	}
	for i := 0; i < warmup; i++ {
		readCtx, cancelRead := context.WithTimeout(context.Background(), readTimeout)
		_, readErr := consumer.Read(readCtx, req, user)
		cancelRead()
		if readErr != nil {
			t.Fatalf("warmup read: %v", readErr)
		}
	}
	adapterMu.Lock()
	adapterDurations = adapterDurations[:0]
	adapterMu.Unlock()

	beforeQueries := repo.findOne.Load()
	poolBefore := p1cM1DBStats(dbConn.Stats())
	var memBefore, memAfter runtime.MemStats
	runtime.ReadMemStats(&memBefore)
	endToEnd := make([]time.Duration, samples)
	responses := make([]int, samples)
	errorsBySample := make([]error, samples)
	jobs := make(chan int)
	cellCtx, cancelCell := context.WithCancel(context.Background())
	defer cancelCell()
	var workers sync.WaitGroup
	workers.Add(concurrency)
	for worker := 0; worker < concurrency; worker++ {
		go func() {
			defer workers.Done()
			for index := range jobs {
				started := time.Now()
				readCtx, cancelRead := context.WithTimeout(cellCtx, readTimeout)
				result, readErr := consumer.Read(readCtx, req, user)
				cancelRead()
				if readErr == nil {
					encoded, encodeErr := json.Marshal(result)
					if encodeErr != nil {
						readErr = encodeErr
					} else {
						responses[index] = len(encoded)
					}
				}
				endToEnd[index] = time.Since(started)
				errorsBySample[index] = readErr
				if readErr != nil {
					cancelCell()
				}
			}
		}()
	}
	for index := 0; index < samples; index++ {
		jobs <- index
	}
	close(jobs)
	workers.Wait()
	runtime.ReadMemStats(&memAfter)
	poolAfter := p1cM1DBStats(dbConn.Stats())
	queryCount := repo.findOne.Load() - beforeQueries
	adapterMu.Lock()
	adapterCopy := append([]time.Duration(nil), adapterDurations...)
	adapterMu.Unlock()
	if len(adapterCopy) == 0 {
		t.Fatal("adapter produced no timing samples")
	}
	errorCount := 0
	for _, sampleErr := range errorsBySample {
		if sampleErr != nil {
			errorCount++
		}
	}
	responseMax := 0
	for _, size := range responses {
		if size > responseMax {
			responseMax = size
		}
	}
	allocated := memAfter.TotalAlloc - memBefore.TotalAlloc
	mallocs := memAfter.Mallocs - memBefore.Mallocs
	return p1cM1Measurement{
		Name:                    fmt.Sprintf("fields-%d/concurrency-%d", selectedCount, concurrency),
		SelectedFields:          selectedCount,
		Concurrency:             concurrency,
		ConcurrencyClass:        p1cM1ConcurrencyClass(concurrency),
		Warmup:                  warmup,
		Samples:                 samples,
		AdapterSamples:          len(adapterCopy),
		SemanticRequestBytes:    len(requestBytes),
		CompleteResponseBytes:   responseMax,
		AdapterLatency:          p1cM1LatencyDistribution(adapterCopy),
		EndToEndLatency:         p1cM1LatencyDistribution(endToEnd),
		RepositoryQueries:       queryCount,
		DatabaseQueries:         queryCount,
		QueriesPerRequest:       float64(queryCount) / float64(samples),
		QueryCountScope:         "one real RecordRepository.FindOne SQL query per repository call; metadata and permission repositories are deterministic test seams",
		AllocatedBytes:          allocated,
		AllocatedBytesPerSample: float64(allocated) / float64(samples),
		Mallocs:                 mallocs,
		MallocsPerSample:        float64(mallocs) / float64(samples),
		AllocationScope:         "process-wide runtime.MemStats delta over the measured sample window; concurrent values include Go runtime/background activity",
		Errors:                  errorCount,
		PoolBefore:              poolBefore,
		PoolAfter:               poolAfter,
	}
}

func p1cM1MeasureOutcomes(t *testing.T, dbConn *sql.DB, fields []models.FieldMetadata, selections []issuetrackerconformance.FieldSelection, user *models.UserSession) []p1cM1Outcome {
	t.Helper()
	selection := selections[:min(len(selections), 14)]
	type outcomeCase struct {
		name    string
		adapter func() (*ContractService, *p1cM1CountingRepository)
		ctx     func() (context.Context, context.CancelFunc)
		want    issuetrackerconformance.Outcome
		ctxErr  error
	}
	newAdapter := func(grant bool, owner string) (*ContractService, *p1cM1CountingRepository) {
		base := persistence.NewRecordRepository(dbConn)
		counted := &p1cM1CountingRepository{RecordRepository: base}
		adapter, _ := p1cM1Adapter(counted, fields, grant, map[string]bool{"flshidden": false})
		base.SetSchemaProvider(adapter.persistence.metadata)
		if owner != "" {
			if _, err := dbConn.Exec("UPDATE `Issue` SET `OwnerId` = ? WHERE `Id` = ?", owner, p1cM1RecordID); err != nil {
				t.Fatalf("set outcome owner: %v", err)
			}
		}
		return adapter, counted
	}
	cases := []outcomeCase{
		{name: "success", adapter: func() (*ContractService, *p1cM1CountingRepository) { return newAdapter(true, user.ID) }, want: issuetrackerconformance.OutcomeOK},
		{name: "missing-record", adapter: func() (*ContractService, *p1cM1CountingRepository) {
			return newAdapter(true, user.ID)
		}, want: issuetrackerconformance.OutcomeMissing},
		{name: "rls-masked", adapter: func() (*ContractService, *p1cM1CountingRepository) { return newAdapter(true, "different-owner") }, want: issuetrackerconformance.OutcomeMissing},
		{name: "object-read-forbidden", adapter: func() (*ContractService, *p1cM1CountingRepository) { return newAdapter(false, user.ID) }, want: issuetrackerconformance.OutcomeForbidden},
		{name: "cancellation-before-repository", adapter: func() (*ContractService, *p1cM1CountingRepository) { return newAdapter(true, user.ID) }, ctx: func() (context.Context, context.CancelFunc) {
			ctx, cancel := context.WithCancel(context.Background())
			cancel()
			return ctx, func() {}
		}, want: issuetrackerconformance.OutcomeCanceled, ctxErr: context.Canceled},
	}
	results := make([]p1cM1Outcome, 0, len(cases)+2)
	for _, tc := range cases {
		adapter, repo := tc.adapter()
		reader := issuetrackerconformance.PointReader(adapter)
		if tc.name == "missing-record" {
			reader = p1cM1RecordIDReader{reader: adapter, id: "missing"}
		}
		consumer, err := issuetrackerconformance.NewConsumer(reader, issuetrackerconformance.CurrentInProcessErrorClassifier)
		if err != nil {
			t.Fatalf("%s NewConsumer: %v", tc.name, err)
		}
		ctx, cancel := context.WithCancel(context.Background())
		if tc.ctx != nil {
			ctx, cancel = tc.ctx()
		}
		before := repo.findOne.Load()
		started := time.Now()
		result, err := consumer.Read(ctx, issuetrackerconformance.Request{RecordID: p1cM1RecordID, Fields: selection}, user)
		elapsed := time.Since(started)
		cancel()
		if err != nil {
			t.Fatalf("%s Read: %v", tc.name, err)
		}
		if result.Outcome != tc.want {
			t.Fatalf("%s outcome = %s, want %s", tc.name, result.Outcome, tc.want)
		}
		ctxErr := ""
		if tc.ctxErr != nil {
			ctxErr = tc.ctxErr.Error()
		}
		results = append(results, p1cM1Outcome{Name: tc.name, SemanticOutcome: string(result.Outcome), ContextError: ctxErr, RepositoryQueries: repo.findOne.Load() - before, LatencyMicros: elapsed.Microseconds()})
	}

	// TiDB evaluates SLEEP inside this synthetic view, allowing cancellation and
	// deadline propagation to be measured while the real RecordRepository query
	// is executing. No production table or payload is touched.
	p1cM1InstallSlowView(t, dbConn)
	defer p1cM1RestoreFastTable(t, dbConn)
	for _, tc := range []struct {
		name string
		ctx  func() (context.Context, context.CancelFunc)
		err  error
	}{
		{name: "cancellation-during-execution", ctx: func() (context.Context, context.CancelFunc) {
			ctx, cancel := context.WithCancel(context.Background())
			time.AfterFunc(25*time.Millisecond, cancel)
			return ctx, cancel
		}, err: context.Canceled},
		{name: "deadline-exceeded", ctx: func() (context.Context, context.CancelFunc) {
			return context.WithTimeout(context.Background(), 25*time.Millisecond)
		}, err: context.DeadlineExceeded},
	} {
		base := persistence.NewRecordRepository(dbConn)
		counted := &p1cM1CountingRepository{RecordRepository: base}
		adapter, _ := p1cM1Adapter(counted, fields, true, map[string]bool{"flshidden": false})
		base.SetSchemaProvider(adapter.persistence.metadata)
		ctx, cancel := tc.ctx()
		started := time.Now()
		_, err := adapter.Retrieve(ctx, p1cM1Object, p1cM1RecordID, user)
		elapsed := time.Since(started)
		cancel()
		if !errors.Is(ctx.Err(), tc.err) {
			t.Fatalf("%s context error = %v, want %v (adapter error %v)", tc.name, ctx.Err(), tc.err, err)
		}
		semanticOutcome := "canceled"
		if errors.Is(tc.err, context.DeadlineExceeded) {
			semanticOutcome = "deadline-exceeded"
		}
		results = append(results, p1cM1Outcome{Name: tc.name, SemanticOutcome: semanticOutcome, ContextError: tc.err.Error(), RepositoryQueries: counted.findOne.Load(), LatencyMicros: elapsed.Microseconds()})
	}
	return results
}

type p1cM1RecordIDReader struct {
	reader issuetrackerconformance.PointReader
	id     string
}

func (r p1cM1RecordIDReader) Retrieve(ctx context.Context, objectName, _ string, user *models.UserSession) (contract.Record, error) {
	return r.reader.Retrieve(ctx, objectName, r.id, user)
}

func p1cM1Adapter(repo ports.RecordRepository, fields []models.FieldMetadata, grantRead bool, fieldRead map[string]bool) (*ContractService, *models.UserSession) {
	schema := &models.ObjectMetadata{APIName: p1cM1Object, SharingModel: constants.SharingModelPrivate, Fields: fields}
	metaSvc := metadata.NewMetadataService(&stubMetaRepoRMR{schema: schema}, nil, nil)
	permissionSvc := permissions.NewPermissionService(&stubPermRepoRMR{grantRead: grantRead, fieldRead: fieldRead}, metaSvc, nil)
	service := NewContractService(&PersistenceService{repo: repo, permissions: permissionSvc, metadata: metaSvc})
	return service, &models.UserSession{ID: "capacity-user", ProfileID: constants.ProfileStandardUser}
}

func p1cM1Fields(count int) ([]models.FieldMetadata, []issuetrackerconformance.FieldSelection) {
	type seed struct {
		name      string
		modelType models.FieldType
		kind      issuetrackerconformance.FieldKind
	}
	seeds := []seed{
		{"StringValue", constants.FieldTypeString, issuetrackerconformance.FieldString},
		{"BoolTrue", constants.FieldTypeBoolean, issuetrackerconformance.FieldBoolean},
		{"BoolFalse", constants.FieldTypeBoolean, issuetrackerconformance.FieldBoolean},
		{"IntegerNegative", constants.SchemaFieldType("integer"), issuetrackerconformance.FieldInteger},
		{"IntegerZero", constants.SchemaFieldType("integer"), issuetrackerconformance.FieldInteger},
		{"DecimalZero", constants.FieldTypeDouble, issuetrackerconformance.FieldDecimal},
		{"DecimalLarge", constants.FieldTypeDouble, issuetrackerconformance.FieldDecimal},
		{"DateValue", constants.FieldTypeDate, issuetrackerconformance.FieldDate},
		{"DateTimeValue", constants.FieldTypeDatetime, issuetrackerconformance.FieldDateTime},
		{"ReferenceValue", constants.FieldTypeReference, issuetrackerconformance.FieldReference},
		{"ExplicitNull", constants.FieldTypeString, issuetrackerconformance.FieldString},
		{"DeclaredAbsent", constants.FieldTypeString, issuetrackerconformance.FieldString},
		{"FLSHidden", constants.FieldTypeString, issuetrackerconformance.FieldString},
		{"EmptyString", constants.FieldTypeString, issuetrackerconformance.FieldString},
	}
	for len(seeds) < count {
		index := len(seeds) + 1
		seeds = append(seeds, seed{fmt.Sprintf("Field%03d", index), constants.FieldTypeString, issuetrackerconformance.FieldString})
	}
	fields := make([]models.FieldMetadata, len(seeds))
	selection := make([]issuetrackerconformance.FieldSelection, len(seeds))
	for i, seed := range seeds {
		fields[i] = models.FieldMetadata{APIName: seed.name, Type: seed.modelType}
		selection[i] = issuetrackerconformance.FieldSelection{Name: seed.name, Kind: seed.kind}
	}
	return fields, selection
}

func p1cM1CreateDataset(t *testing.T, dbConn *sql.DB, fields []models.FieldMetadata) {
	t.Helper()
	_, _ = dbConn.Exec("DROP VIEW IF EXISTS `Issue`")
	_, _ = dbConn.Exec("DROP TABLE IF EXISTS `Issue`")
	_, _ = dbConn.Exec("DROP TABLE IF EXISTS `IssueBase`")
	columns := []string{"`Id` VARCHAR(255) PRIMARY KEY", "`OwnerId` VARCHAR(255) NOT NULL"}
	names := []string{"Id", "OwnerId"}
	values := []any{p1cM1RecordID, "capacity-user"}
	for _, field := range fields {
		if field.APIName == "DeclaredAbsent" {
			continue
		}
		sqlType := "VARCHAR(255) NULL"
		value := any("value-" + field.APIName)
		switch field.APIName {
		case "StringValue":
			value = "selected-root"
		case "BoolTrue":
			sqlType, value = "BOOLEAN NULL", true
		case "BoolFalse":
			sqlType, value = "BOOLEAN NULL", false
		case "IntegerNegative":
			sqlType, value = "BIGINT NULL", int64(-7)
		case "IntegerZero":
			sqlType, value = "BIGINT NULL", int64(0)
		case "DecimalZero":
			sqlType, value = "DECIMAL(38,9) NULL", "0.000000000"
		case "DecimalLarge":
			sqlType, value = "DECIMAL(38,9) NULL", "12345678901234567890123456789.123456789"
		case "DateValue":
			sqlType, value = "DATE NULL", "2026-07-11"
		case "DateTimeValue":
			// The neutral fixture contract carries datetime as an RFC3339 string;
			// the current adapter has no separate datetime carrier type.
			sqlType, value = "VARCHAR(64) NULL", "2026-07-11T09:10:11Z"
		case "ReferenceValue":
			value = "REF-001"
		case "ExplicitNull":
			value = nil
		case "FLSHidden":
			value = "must-not-project"
		case "EmptyString":
			value = ""
		}
		columns = append(columns, fmt.Sprintf("`%s` %s", field.APIName, sqlType))
		names = append(names, field.APIName)
		values = append(values, value)
	}
	if _, err := dbConn.Exec("CREATE TABLE `Issue` (" + strings.Join(columns, ",") + ")"); err != nil {
		t.Fatalf("create synthetic Issue table: %v", err)
	}
	quoted := make([]string, len(names))
	placeholders := make([]string, len(names))
	for i, name := range names {
		quoted[i] = "`" + name + "`"
		placeholders[i] = "?"
	}
	if _, err := dbConn.Exec("INSERT INTO `Issue` ("+strings.Join(quoted, ",")+") VALUES ("+strings.Join(placeholders, ",")+")", values...); err != nil {
		t.Fatalf("insert synthetic Issue row: %v", err)
	}
	if _, err := dbConn.Exec("INSERT INTO `Issue` (`Id`,`OwnerId`,`StringValue`) VALUES ('ISS-CAPACITY-RLS','different-owner','denied')"); err != nil {
		t.Fatalf("insert RLS row: %v", err)
	}
}

func p1cM1InstallSlowView(t *testing.T, dbConn *sql.DB) {
	t.Helper()
	if _, err := dbConn.Exec("RENAME TABLE `Issue` TO `IssueBase`"); err != nil {
		t.Fatalf("rename Issue for slow view: %v", err)
	}
	if _, err := dbConn.Exec("CREATE VIEW `Issue` AS SELECT `IssueBase`.*, SLEEP(0.2) AS `CapacityDelay` FROM `IssueBase`"); err != nil {
		t.Fatalf("create slow Issue view: %v", err)
	}
}

func p1cM1RestoreFastTable(t *testing.T, dbConn *sql.DB) {
	t.Helper()
	if _, err := dbConn.Exec("DROP VIEW IF EXISTS `Issue`"); err != nil {
		t.Fatalf("drop slow Issue view: %v", err)
	}
	if _, err := dbConn.Exec("RENAME TABLE `IssueBase` TO `Issue`"); err != nil {
		t.Fatalf("restore Issue table: %v", err)
	}
}

func p1cM1MeasureIdentifiers(t *testing.T, dbConn *sql.DB, packObjectMax, packFieldMax int) []p1cM1IdentifierEvidence {
	t.Helper()
	objectAt, objectOver := p1cM1ProbeIdentifierDDL(dbConn, "table", 64, 65)
	fieldAt, fieldOver := p1cM1ProbeIdentifierDDL(dbConn, "column", 64, 65)
	recordAt, recordOver := p1cM1ProbeRecordLength(dbConn, 255, 256)
	grammar := "^[a-zA-Z_][a-zA-Z0-9_]*$"
	return []p1cM1IdentifierEvidence{
		{Dimension: "object API identifier", ValidatorGrammar: grammar, ValidatorLengthBehavior: "grammar-only; no validator length cap", MetadataStorageWidth: 255, PhysicalStorageAt: 64, PhysicalStorageJustOver: 65, PhysicalAtAccepted: objectAt, PhysicalJustOverAccepted: objectOver, PublicAPIBehavior: "contract.Records.Retrieve accepts string; no neutral length check", ObservedPackMaximum: packObjectMax, ProductionEvidence: "no public/anonymized production aggregate supplied", OwnershipNote: "metadata VARCHAR width and TiDB identifier width are storage constraints, not approved public API maxima"},
		{Dimension: "field API identifier", ValidatorGrammar: grammar, ValidatorLengthBehavior: "grammar-only; no validator length cap", MetadataStorageWidth: 255, PhysicalStorageAt: 64, PhysicalStorageJustOver: 65, PhysicalAtAccepted: fieldAt, PhysicalJustOverAccepted: fieldOver, PublicAPIBehavior: "selected-field semantics are not yet a public Runtime operation", ObservedPackMaximum: packFieldMax, ProductionEvidence: "no public/anonymized production aggregate supplied", OwnershipNote: "metadata VARCHAR width and TiDB identifier width are storage constraints, not approved public API maxima"},
		{Dimension: "record identifier", ValidatorGrammar: "none at contract.Records.Retrieve", ValidatorLengthBehavior: "neutral adapter accepts any string", MetadataStorageWidth: 0, PhysicalStorageAt: 255, PhysicalStorageJustOver: 256, PhysicalAtAccepted: recordAt, PhysicalJustOverAccepted: recordOver, PublicAPIBehavior: "contract.Records.Retrieve accepts string; schemas use differing widths", ObservedPackMaximum: 0, ProductionEvidence: "no public/anonymized production aggregate supplied", OwnershipNote: "the synthetic VARCHAR(255) probe demonstrates one current storage shape only and is not an approved public API maximum"},
	}
}

func p1cM1ProbeIdentifierDDL(dbConn *sql.DB, kind string, at, over int) (bool, bool) {
	probe := func(length int) bool {
		name := "x" + strings.Repeat("a", length-1)
		if kind == "table" {
			_, err := dbConn.Exec("CREATE TABLE `" + name + "` (`Id` INT)")
			if err == nil {
				_, _ = dbConn.Exec("DROP TABLE `" + name + "`")
			}
			return err == nil
		}
		_, err := dbConn.Exec("CREATE TABLE `P1CIdentifierProbe` (`" + name + "` INT)")
		if err == nil {
			_, _ = dbConn.Exec("DROP TABLE `P1CIdentifierProbe`")
		}
		return err == nil
	}
	return probe(at), probe(over)
}

func p1cM1ProbeRecordLength(dbConn *sql.DB, at, over int) (bool, bool) {
	_, _ = dbConn.Exec("DROP TABLE IF EXISTS `P1CRecordIDProbe`")
	if _, err := dbConn.Exec("CREATE TABLE `P1CRecordIDProbe` (`Id` VARCHAR(255) PRIMARY KEY)"); err != nil {
		return false, false
	}
	defer func() { _, _ = dbConn.Exec("DROP TABLE `P1CRecordIDProbe`") }()
	_, errAt := dbConn.Exec("INSERT INTO `P1CRecordIDProbe` (`Id`) VALUES (?)", strings.Repeat("a", at))
	_, errOver := dbConn.Exec("INSERT INTO `P1CRecordIDProbe` (`Id`) VALUES (?)", strings.Repeat("b", over))
	return errAt == nil, errOver == nil
}

func readP1cM1PackObjects(t *testing.T, path string) []p1cM1PackObject {
	t.Helper()
	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read CRM object spec: %v", err)
	}
	var objects []p1cM1PackObject
	if err := json.Unmarshal(data, &objects); err != nil {
		t.Fatalf("decode CRM object spec: %v", err)
	}
	if len(objects) == 0 {
		t.Fatal("CRM object spec contains no objects")
	}
	return objects
}

func readP1cM1AnonymousAggregates(t *testing.T, path string) *p1cM1AnonymousAggregates {
	t.Helper()
	data, err := os.ReadFile(path)
	if err != nil {
		t.Fatalf("read anonymous aggregate evidence: %v", err)
	}
	var aggregate p1cM1AnonymousAggregates
	if err := json.Unmarshal(data, &aggregate); err != nil {
		t.Fatalf("decode anonymous aggregate evidence: %v", err)
	}
	if aggregate.SourceEnvironment == "" || aggregate.ObservationTimeUTC == "" {
		t.Fatal("anonymous aggregate evidence lacks source environment or observation time")
	}
	appPacksRevision, fixtureRevision := p1cM1PinnedRevisions(t)
	if aggregate.NexusCRMRevision != requiredP1cM1Env(t, "P1C_M1_NEXUSCRM_REVISION") || aggregate.AppPacksRevision != appPacksRevision || aggregate.FixtureRevision != fixtureRevision {
		t.Fatalf("anonymous aggregate revisions do not match the measured run")
	}
	if aggregate.PayloadPolicy != "numeric-aggregates-only; no identifiers, names, records, or traffic payloads" {
		t.Fatalf("anonymous aggregate payload policy = %q", aggregate.PayloadPolicy)
	}
	if aggregate.MetadataObjects < 1 || aggregate.MetadataFieldCount.Max < 1 {
		t.Fatal("anonymous aggregate evidence contains no metadata distribution")
	}
	return &aggregate
}

func p1cM1PackShape(objects []p1cM1PackObject) ([]int, int, int) {
	counts := make([]int, 0, len(objects))
	maxObject, maxField := 0, 0
	for _, object := range objects {
		counts = append(counts, len(object.Fields))
		if len(object.APIName) > maxObject {
			maxObject = len(object.APIName)
		}
		for _, field := range object.Fields {
			if len(field.APIName) > maxField {
				maxField = len(field.APIName)
			}
		}
	}
	return counts, maxObject, maxField
}

func p1cM1IntegerDistribution(values []int) p1cM1Percentiles {
	copyValues := append([]int(nil), values...)
	sort.Ints(copyValues)
	value := func(q float64) int { return copyValues[int(math.Floor(float64(len(copyValues)-1)*q))] }
	return p1cM1Percentiles{P50: value(.50), P95: value(.95), P99: value(.99), P999: value(.999), Max: copyValues[len(copyValues)-1]}
}

func p1cM1Candidates(d p1cM1Percentiles) []int {
	values := []int{1, d.P50, d.P95, d.P99, d.P999, d.Max, d.Max + 1, 64, 65, 128, 129, 256, 257}
	seen := map[int]bool{}
	out := make([]int, 0, len(values))
	for _, value := range values {
		if value > 0 && !seen[value] {
			seen[value] = true
			out = append(out, value)
		}
	}
	sort.Ints(out)
	return out
}

func p1cM1ConcurrencyGrid() []int {
	raw := getenvDefault("P1C_M1_CONCURRENCY", "1,4,16,64")
	var out []int
	for _, item := range strings.Split(raw, ",") {
		value, err := strconv.Atoi(strings.TrimSpace(item))
		if err == nil && value > 0 {
			out = append(out, value)
		}
	}
	if len(out) == 0 {
		return []int{1, 4, 16, 64}
	}
	return out
}

func p1cM1ConcurrencyClass(value int) string {
	switch {
	case value <= 1:
		return "single-request"
	case value <= 4:
		return "low"
	case value <= 16:
		return "expected-normal-probe"
	default:
		return "saturation-probe"
	}
}

func p1cM1LatencyDistribution(values []time.Duration) p1cM1Latency {
	copyValues := append([]time.Duration(nil), values...)
	sort.Slice(copyValues, func(i, j int) bool { return copyValues[i] < copyValues[j] })
	if len(copyValues) == 0 {
		return p1cM1Latency{}
	}
	value := func(q float64) int64 {
		index := int(math.Ceil(q*float64(len(copyValues)))) - 1
		if index < 0 {
			index = 0
		}
		if index >= len(copyValues) {
			index = len(copyValues) - 1
		}
		return copyValues[index].Microseconds()
	}
	return p1cM1Latency{P50Micros: value(.50), P95Micros: value(.95), P99Micros: value(.99), P999Micros: value(.999), MaxMicros: copyValues[len(copyValues)-1].Microseconds()}
}

func p1cM1DBStats(stats sql.DBStats) p1cM1PoolStats {
	return p1cM1PoolStats{
		OpenConnections:   stats.OpenConnections,
		InUse:             stats.InUse,
		Idle:              stats.Idle,
		WaitCount:         stats.WaitCount,
		WaitMicros:        stats.WaitDuration.Microseconds(),
		MaxIdleClosed:     stats.MaxIdleClosed,
		MaxIdleTimeClosed: stats.MaxIdleTimeClosed,
		MaxLifetimeClosed: stats.MaxLifetimeClosed,
	}
}

func TestP1cM1DBStatsPreservesConnectionClosureCounters(t *testing.T) {
	got := p1cM1DBStats(sql.DBStats{
		OpenConnections:   16,
		Idle:              16,
		MaxIdleClosed:     3,
		MaxIdleTimeClosed: 5,
		MaxLifetimeClosed: 7,
	})
	if got.OpenConnections != 16 || got.Idle != 16 || got.MaxIdleClosed != 3 || got.MaxIdleTimeClosed != 5 || got.MaxLifetimeClosed != 7 {
		t.Fatalf("pool stats lost closure evidence: %#v", got)
	}
}

func p1cM1DatabaseConfig(dbConn *sql.DB) map[string]string {
	result := map[string]string{}
	rows, err := dbConn.Query("SHOW VARIABLES WHERE Variable_name IN ('max_connections','tidb_isolation_read_engines','tidb_mem_quota_query','max_execution_time','transaction_isolation')")
	if err != nil {
		result["collection_error"] = err.Error()
		return result
	}
	defer rows.Close()
	for rows.Next() {
		var name, value string
		if err := rows.Scan(&name, &value); err != nil {
			result["collection_error"] = err.Error()
			return result
		}
		result[name] = value
	}
	if err := rows.Err(); err != nil {
		result["collection_error"] = err.Error()
	}
	return result
}

func p1cM1Markdown(report p1cM1Report) string {
	var b strings.Builder
	fmt.Fprintf(&b, "# P1c-M1 selected-root capacity evidence — `%s`\n\n", report.RunID)
	fmt.Fprintf(&b, "Revisions: NexusCRM `%s`; app-packs `%s`; fixture `%s`.\n\n", report.Revisions.NexusCRM, report.Revisions.AppPacks, report.Revisions.Fixture)
	fmt.Fprintf(&b, "Environment: `%s` (representative: `%t`), Go `%s`, TiDB `%s`, `%s/%s`.\n\n", report.Environment.Classification, report.Environment.Representative, report.Environment.GoVersion, report.Environment.TiDBVersion, report.Environment.OS, report.Environment.Architecture)
	b.WriteString("This run uses only synthetic records. It traverses `ContractService.Retrieve -> PersistenceService.Retrieve -> RecordRepository.FindOne -> RLS -> FLS -> neutral projection`. The current repository selects `*`; selected fields are projected after the adapter, so these numbers do not claim storage-level selection pushdown.\n\n")
	fmt.Fprintf(&b, "CRM pack-declared field counts: p50 `%d`, p95 `%d`, p99 `%d`, p999 `%d`, observed max `%d` across `%d` objects. No production selection histogram was available.\n\n", report.CRMFieldCounts.Distribution.P50, report.CRMFieldCounts.Distribution.P95, report.CRMFieldCounts.Distribution.P99, report.CRMFieldCounts.Distribution.P999, report.CRMFieldCounts.Distribution.Max, report.CRMFieldCounts.Objects)
	if report.AnonymousAggregates != nil {
		a := report.AnonymousAggregates
		fmt.Fprintf(&b, "Anonymized `%s` metadata field counts: p50 `%d`, p95 `%d`, p99 `%d`, p999 `%d`, max `%d` across `%d` objects. Only numeric aggregates were retained.\n\n", a.SourceEnvironment, a.MetadataFieldCount.P50, a.MetadataFieldCount.P95, a.MetadataFieldCount.P99, a.MetadataFieldCount.P999, a.MetadataFieldCount.Max, a.MetadataObjects)
	}
	b.WriteString("The scalar matrix preserves booleans (including false), signed/zero integers, strings (including empty), date/datetime strings, a reference ID, explicit null, and omission for declared-absent/FLS-hidden fields. Current DECIMAL hydration is lossy through float64; `value_shape_result` records the observed precision/scale rather than hiding it.\n\n")
	b.WriteString("| fields | concurrency | class | request bytes | response bytes | adapter p50/p95/p99/p999/max µs | end-to-end p50/p95/p99/p999/max µs | queries/request | errors |\n|---:|---:|---|---:|---:|---|---|---:|---:|\n")
	for _, m := range report.Measurements {
		fmt.Fprintf(&b, "| %d | %d | %s | %d | %d | %d/%d/%d/%d/%d | %d/%d/%d/%d/%d | %.3f | %d |\n", m.SelectedFields, m.Concurrency, m.ConcurrencyClass, m.SemanticRequestBytes, m.CompleteResponseBytes, m.AdapterLatency.P50Micros, m.AdapterLatency.P95Micros, m.AdapterLatency.P99Micros, m.AdapterLatency.P999Micros, m.AdapterLatency.MaxMicros, m.EndToEndLatency.P50Micros, m.EndToEndLatency.P95Micros, m.EndToEndLatency.P99Micros, m.EndToEndLatency.P999Micros, m.EndToEndLatency.MaxMicros, m.QueriesPerRequest, m.Errors)
	}
	b.WriteString("\nWire-size decision remains blocked: the reported compact JSON sizes are a reproducible semantic proxy, not future protobuf/gRPC bytes. P2 must replay the same vectors through the reviewed generated codec and compare them with configured transport limits before headroom can be approved.\n\n")
	fmt.Fprintf(&b, "Deadline evidence: %s\n\n", report.DeadlineEvidence)
	b.WriteString("No production numeric limit or deadline is approved by this artifact; P1c remains blocked pending the follow-up decision review.\n")
	return b.String()
}

func p1cM1WriteReport(t *testing.T, path string, report p1cM1Report) {
	t.Helper()
	jsonBytes, err := json.MarshalIndent(report, "", "  ")
	if err != nil {
		t.Fatalf("encode report checkpoint: %v", err)
	}
	temporaryPath := path + ".tmp"
	if err := os.WriteFile(temporaryPath, append(jsonBytes, '\n'), 0o644); err != nil {
		t.Fatalf("write report checkpoint: %v", err)
	}
	if err := os.Rename(temporaryPath, path); err != nil {
		t.Fatalf("publish report checkpoint: %v", err)
	}
}

func requiredP1cM1Env(t *testing.T, name string) string {
	t.Helper()
	value := strings.TrimSpace(os.Getenv(name))
	if value == "" {
		t.Fatalf("%s is required", name)
	}
	return value
}

func p1cM1PinnedRevisions(t *testing.T) (string, string) {
	t.Helper()
	data, err := os.ReadFile(p1cM1RevisionFile)
	if err != nil {
		t.Fatalf("read capacity revision SSoT: %v", err)
	}
	values := make(map[string]string, 2)
	for lineNumber, rawLine := range strings.Split(string(data), "\n") {
		line := strings.TrimSpace(rawLine)
		if line == "" || strings.HasPrefix(line, "#") {
			continue
		}
		name, value, ok := strings.Cut(line, "=")
		if !ok || strings.TrimSpace(name) == "" || strings.TrimSpace(value) == "" {
			t.Fatalf("invalid capacity revision SSoT line %d", lineNumber+1)
		}
		values[strings.TrimSpace(name)] = strings.TrimSpace(value)
	}
	appPacksRevision := values["P1C_M1_APP_PACKS_REVISION"]
	fixtureRevision := values["P1C_M1_FIXTURE_REVISION"]
	if len(appPacksRevision) != 40 || !p1cM1LowerHex(appPacksRevision) {
		t.Fatal("capacity app-packs revision must be a full lowercase Git SHA")
	}
	if len(fixtureRevision) != 40 || !p1cM1LowerHex(fixtureRevision) {
		t.Fatal("capacity fixture revision must be a full lowercase Git SHA")
	}
	return appPacksRevision, fixtureRevision
}

func p1cM1RequireRevisionEnvironment(t *testing.T, appPacksRevision, fixtureRevision string) {
	t.Helper()
	if got := requiredP1cM1Env(t, "P1C_M1_APP_PACKS_REVISION"); got != appPacksRevision {
		t.Fatalf("app-packs revision = %s, want pinned %s", got, appPacksRevision)
	}
	if got := requiredP1cM1Env(t, "P1C_M1_FIXTURE_REVISION"); got != fixtureRevision {
		t.Fatalf("fixture revision = %s, want pinned %s", got, fixtureRevision)
	}
}

func p1cM1RequiredScratchConfig(t *testing.T) (string, string) {
	t.Helper()
	databaseName, token := p1cM1ScratchIdentity(t)
	if databaseName != strings.TrimSpace(os.Getenv("TIDB_DATABASE")) {
		t.Fatal("P1C_M1_SCRATCH_DATABASE must exactly match TIDB_DATABASE")
	}
	return databaseName, token
}

func p1cM1ScratchIdentity(t *testing.T) (string, string) {
	t.Helper()
	databaseName := requiredP1cM1Env(t, "P1C_M1_SCRATCH_DATABASE")
	if !strings.HasPrefix(databaseName, "p1c_m1_") || !p1cM1SafeIdentifier(databaseName) {
		t.Fatalf("scratch database %q is not an owned p1c_m1_ identifier", databaseName)
	}
	token := requiredP1cM1Env(t, "P1C_M1_SCRATCH_TOKEN")
	if len(token) != 64 || !p1cM1LowerHex(token) {
		t.Fatal("P1C_M1_SCRATCH_TOKEN must be a 64-character lowercase hex nonce")
	}
	return databaseName, token
}

func p1cM1RequireSourceDatabase(t *testing.T) string {
	t.Helper()
	sourceDatabase := requiredP1cM1Env(t, "P1C_M1_SOURCE_DATABASE")
	if sourceDatabase != strings.TrimSpace(os.Getenv("TIDB_DATABASE")) {
		t.Fatal("P1C_M1_SOURCE_DATABASE must exactly match TIDB_DATABASE for lifecycle/aggregate operations")
	}
	return sourceDatabase
}

func p1cM1OpenConfiguredDB(t *testing.T) *sql.DB {
	t.Helper()
	dbConn, err := database.OpenDBFromEnv(database.DefaultPoolOptions())
	if err != nil {
		t.Fatalf("open configured TiDB database: %v", err)
	}
	t.Cleanup(func() { _ = dbConn.Close() })
	if err := dbConn.PingContext(context.Background()); err != nil {
		t.Fatalf("ping configured TiDB database: %v", err)
	}
	return dbConn
}

func p1cM1VerifyScratchDatabase(t *testing.T, dbConn *sql.DB, expectedDatabase, expectedToken string) {
	t.Helper()
	var currentDatabase string
	if err := dbConn.QueryRow("SELECT DATABASE()").Scan(&currentDatabase); err != nil {
		t.Fatalf("read current scratch database: %v", err)
	}
	if currentDatabase != expectedDatabase {
		t.Fatalf("connected database = %q, want owned scratch database %q", currentDatabase, expectedDatabase)
	}
	var storedToken string
	if err := dbConn.QueryRow("SELECT `GuardToken` FROM `_P1C_M1_ScratchGuard` LIMIT 1").Scan(&storedToken); err != nil {
		t.Fatalf("scratch ownership marker is missing: %v", err)
	}
	if storedToken != expectedToken {
		t.Fatal("scratch ownership marker does not match this run")
	}
}

func p1cM1SafeIdentifier(value string) bool {
	if value == "" {
		return false
	}
	for _, char := range value {
		if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') || char == '_' {
			continue
		}
		return false
	}
	return true
}

func p1cM1SafeLabel(value string) bool {
	if value == "" {
		return false
	}
	for _, char := range value {
		if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') || char == '_' || char == '-' || char == '.' {
			continue
		}
		return false
	}
	return true
}

func p1cM1DatabaseSuffix(runID string) string {
	var suffix strings.Builder
	for _, char := range runID {
		if suffix.Len() == 40 {
			break
		}
		if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') || char == '_' {
			suffix.WriteRune(char)
		} else {
			suffix.WriteByte('_')
		}
	}
	return suffix.String()
}

func p1cM1LowerHex(value string) bool {
	for _, char := range value {
		if (char >= '0' && char <= '9') || (char >= 'a' && char <= 'f') {
			continue
		}
		return false
	}
	return true
}
func getenvDefault(name, fallback string) string {
	if value := strings.TrimSpace(os.Getenv(name)); value != "" {
		return value
	}
	return fallback
}
func envInt(name string, fallback int) int {
	value, err := strconv.Atoi(strings.TrimSpace(os.Getenv(name)))
	if err != nil || value <= 0 {
		return fallback
	}
	return value
}

func envDuration(t *testing.T, name string, fallback time.Duration) time.Duration {
	t.Helper()
	value := strings.TrimSpace(os.Getenv(name))
	if value == "" {
		return fallback
	}
	parsed, err := time.ParseDuration(value)
	if err != nil || parsed <= 0 {
		t.Fatalf("invalid positive duration %s=%q", name, value)
	}
	return parsed
}
func envUint64(name string) uint64 {
	value, _ := strconv.ParseUint(strings.TrimSpace(os.Getenv(name)), 10, 64)
	return value
}
func envBool(name string) bool {
	value, _ := strconv.ParseBool(strings.TrimSpace(os.Getenv(name)))
	return value
}
