From 0b392e745f5504181377ec7b5951e4fee8ab3306 Mon Sep 17 00:00:00 2001 From: cpoul Date: Fri, 23 Oct 2026 18:29:11 +0300 Subject: [PATCH 1/4] =?UTF-8?q?feat(cli):=20add=20environment-configured?= =?UTF-8?q?=20sentry=20reporting=20=E2=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Enable command failures, command-goroutine panics, and background error logs through SENTRY_DSN, with optional environment and release labels. Preserve log redaction and bound shutdown flushing to two seconds. --- README.md | 19 +++ cmd/pg_noty/main.go | 32 ++++- cmd/pg_noty/sentry.go | 66 ++++++++++ cmd/pg_noty/sentry_test.go | 249 ++++++++++++++++++++++++++++++++++++ docker-compose.yml | 3 + go.mod | 5 +- go.sum | 15 ++- internal/cli/doc.go | 10 +- internal/cli/execute.go | 8 +- internal/cli/root.go | 2 + internal/cli/sentry.go | 72 +++++++++++ internal/cli/sentry_test.go | 157 +++++++++++++++++++++++ 12 files changed, 626 insertions(+), 12 deletions(-) create mode 100644 cmd/pg_noty/sentry.go create mode 100644 cmd/pg_noty/sentry_test.go create mode 100644 internal/cli/sentry.go create mode 100644 internal/cli/sentry_test.go diff --git a/README.md b/README.md index f20f550..6e16231 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,7 @@ your configuration at that path is all it takes. ```sh docker run --rm \ -e DATABASE_URL -e ORDER_WEBHOOK_URL -e WEBHOOK_SECRET \ + -e SENTRY_DSN -e SENTRY_ENVIRONMENT -e SENTRY_RELEASE \ -v "$PWD/listeners.yaml:/etc/pg_noty/listeners.yaml:ro" \ -p 8080:8080 \ cpoul/pg_noty:latest @@ -199,6 +200,24 @@ docker run --rm -e DATABASE_URL \ The image is `gcr.io/distroless/static-debian12:nonroot` with a statically linked binary and stays under 10 MiB per platform. It contains no shell, package manager or compiler. +Set `SENTRY_DSN` in the process environment to report command failures, error-level logs +(including background worker errors), and panics on the command goroutine to Sentry. Leave it +unset or blank to disable Sentry. `SENTRY_ENVIRONMENT` and `SENTRY_RELEASE` optionally label events, +following the [Sentry Go SDK's environment configuration](https://github.com/getsentry/sentry-go/tree/v0.48.0#configuration). +Keep the DSN in your deployment's environment or secret store rather than tracked YAML. + +```sh +SENTRY_DSN='https://public-key@sentry.example.com/1' \ +SENTRY_ENVIRONMENT=production \ +pg_noty run -f listeners.yaml +``` + +Error events include stack traces and the same redacted attributes used by local logs. Normal +logging continues unchanged; debug, info, and warning logs are not sent. Performance tracing, +Sentry's separate logs and metrics products are disabled. Shutdown allows up to two seconds to +flush pending events. An invalid DSN stops startup with `error: SENTRY_DSN is invalid` without +printing its value. Panic reporting preserves the crash; panics in other goroutines are not captured. + ### Who changes your database By default `pg_noty run` **changes nothing**. It creates no schema, applies no migration and diff --git a/cmd/pg_noty/main.go b/cmd/pg_noty/main.go index 1ea26c6..3103cf3 100644 --- a/cmd/pg_noty/main.go +++ b/cmd/pg_noty/main.go @@ -2,15 +2,43 @@ package main import ( "context" + "fmt" "os" "os/signal" "syscall" "github.com/cpouldev/pg_noty/internal/cli" + "github.com/getsentry/sentry-go" ) func main() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) - defer stop() - os.Exit(cli.Execute(ctx, os.Args[1:], cli.Streams{In: os.Stdin, Out: os.Stdout, Err: os.Stderr})) + status := run( + ctx, + os.Args[1:], + cli.Streams{In: os.Stdin, Out: os.Stdout, Err: os.Stderr}, + os.Getenv("SENTRY_DSN"), + nil, + ) + stop() + os.Exit(status) +} + +func run(ctx context.Context, args []string, streams cli.Streams, dsn string, transport sentry.Transport) int { + monitoring, err := newSentryRuntime(dsn, transport) + if err != nil { + _, _ = fmt.Fprintln(streams.Err, "error: "+err.Error()) + return 1 + } + if monitoring == nil { + return cli.Execute(ctx, args, streams) + } + if ctx == nil { + ctx = context.Background() + } + ctx = monitoring.context(ctx) + // Defers unwind in reverse: capture a panic first, then flush it before os.Exit terminates. + defer monitoring.shutdown() + defer monitoring.recoverPanic(ctx) + return cli.Execute(ctx, args, streams) } diff --git a/cmd/pg_noty/sentry.go b/cmd/pg_noty/sentry.go new file mode 100644 index 0000000..c997268 --- /dev/null +++ b/cmd/pg_noty/sentry.go @@ -0,0 +1,66 @@ +package main + +import ( + "context" + "errors" + "strings" + "time" + + "github.com/getsentry/sentry-go" +) + +const sentryShutdownTimeout = 2 * time.Second + +var errInvalidSentryDSN = errors.New("SENTRY_DSN is invalid") + +type sentryRuntime struct { + client *sentry.Client + hub *sentry.Hub +} + +func newSentryRuntime(dsn string, transport sentry.Transport) (*sentryRuntime, error) { + if strings.TrimSpace(dsn) == "" { + return nil, nil + } + if transport == nil { + // The SDK's default telemetry processor flushes again during Close. + // Use the asynchronous HTTP transport directly to keep shutdown bounded. + transport = sentry.NewHTTPTransport() + } + client, err := sentry.NewClient(sentry.ClientOptions{ + Dsn: dsn, + AttachStacktrace: true, + DisableLogs: true, + DisableMetrics: true, + EnableTracing: false, + Transport: transport, + }) + if err != nil { + return nil, errInvalidSentryDSN + } + scope := sentry.NewScope() + scope.SetTag("component", "cli") + return &sentryRuntime{client: client, hub: sentry.NewHub(client, scope)}, nil +} + +func (runtime *sentryRuntime) context(ctx context.Context) context.Context { + return sentry.SetHubOnContext(ctx, runtime.hub) +} + +func (runtime *sentryRuntime) recoverPanic(ctx context.Context) { + recovered := recover() + if recovered == nil { + return + } + runtime.hub.RecoverWithContext(ctx, recovered) + // Reporting must not turn a process crash into apparent success. + panic(recovered) +} + +func (runtime *sentryRuntime) shutdown() { + // A signal normally cancels the command context, so flushing needs an independent bound. + ctx, cancel := context.WithTimeout(context.Background(), sentryShutdownTimeout) + defer cancel() + runtime.hub.FlushWithContext(ctx) + runtime.client.Close() +} diff --git a/cmd/pg_noty/sentry_test.go b/cmd/pg_noty/sentry_test.go new file mode 100644 index 0000000..9786392 --- /dev/null +++ b/cmd/pg_noty/sentry_test.go @@ -0,0 +1,249 @@ +package main + +import ( + "bytes" + "context" + "errors" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/cpouldev/pg_noty/internal/cli" + "github.com/getsentry/sentry-go" +) + +const testSentryDSN = "https://public@example.com/1" + +func TestSentryIsDisabledWithoutDSN(t *testing.T) { + for _, dsn := range []string{"", " \t\n"} { + transport := &recordingSentryTransport{} + runtime, err := newSentryRuntime(dsn, transport) + if err != nil || runtime != nil { + t.Fatalf("newSentryRuntime(%q) = (%v, %v), want (nil, nil)", dsn, runtime, err) + } + if transport.wasConfigured() { + t.Fatalf("newSentryRuntime(%q) configured a transport while disabled", dsn) + } + } +} + +func TestRunReportsCommandFailuresBeforeReturning(t *testing.T) { + t.Setenv("SENTRY_RELEASE", "pg_noty@test") + t.Setenv("SENTRY_ENVIRONMENT", "sentry-test") + for _, testCase := range []struct { + name string + dsn string + args []string + wantStatus int + wantEvents int + }{ + {name: "disabled", args: []string{"sentry-unknown-command"}, wantStatus: 1}, + {name: "help", dsn: testSentryDSN, args: []string{"--help"}}, + {name: "failure", dsn: testSentryDSN, args: []string{"sentry-unknown-command"}, wantStatus: 1, wantEvents: 1}, + } { + t.Run(testCase.name, func(t *testing.T) { + transport := &recordingSentryTransport{} + var output bytes.Buffer + ctx, cancel := context.WithCancel(t.Context()) + cancel() + status := run(ctx, testCase.args, cli.Streams{Out: &output, Err: &output}, testCase.dsn, transport) + if status != testCase.wantStatus { + t.Fatalf("status = %d, want %d; output = %q", status, testCase.wantStatus, output.String()) + } + events, lifecycle, deadline := transport.snapshot() + if len(events) != testCase.wantEvents { + t.Fatalf("captured %d events, want %d", len(events), testCase.wantEvents) + } + if testCase.dsn == "" { + if transport.wasConfigured() || len(lifecycle) != 0 { + t.Fatal("disabled Sentry used its transport") + } + return + } + if strings.Join(lifecycle, ",") != "flush,close" || deadline <= 0 || deadline > sentryShutdownTimeout { + t.Fatalf("shutdown = %v, deadline = %s; want bounded flush before close despite cancellation", lifecycle, deadline) + } + for _, event := range events { + if event.Release != "pg_noty@test" || event.Environment != "sentry-test" { + t.Fatalf("release = %q, environment = %q; want labels from the environment", event.Release, event.Environment) + } + if len(event.Exception) == 0 || !strings.Contains(output.String(), event.Exception[0].Value) { + t.Fatalf("event = %#v, want the same error printed to stderr %q", event, output.String()) + } + } + }) + } +} + +func TestSentryRuntimeUsesErrorOnlyPrivateDefaultsAndClosesInOrder(t *testing.T) { + transport := &recordingSentryTransport{} + runtime, err := newSentryRuntime(testSentryDSN, transport) + if err != nil { + t.Fatal(err) + } + if runtime == nil || sentry.GetHubFromContext(runtime.context(t.Context())) != runtime.hub { + t.Fatal("enabled Sentry runtime did not attach its hub to the command context") + } + options := runtime.client.Options() + if options.EnableTracing || !options.DisableLogs || !options.DisableMetrics || !options.AttachStacktrace { + t.Fatalf("Sentry options = tracing:%t logs-disabled:%t metrics-disabled:%t stacktraces:%t, want error-only with stacktraces", options.EnableTracing, options.DisableLogs, options.DisableMetrics, options.AttachStacktrace) + } + collection := runtime.client.GetDataCollection() + headers := collection.HTTPHeaders + if collection.UserInfo.Or(true) || len(collection.HTTPBodies) != 0 || + collection.Cookies == nil || collection.Cookies.Mode != sentry.CollectionOff || + headers == nil || headers.Request == nil || headers.Response == nil || + headers.Request.Mode != sentry.CollectionDenyList || headers.Response.Mode != sentry.CollectionDenyList || + collection.QueryParams == nil || collection.QueryParams.Mode != sentry.CollectionDenyList { + t.Fatalf("Sentry data collection enables private context: %#v", collection) + } + + runtime.hub.CaptureException(errors.New("sentry event probe")) + runtime.shutdown() + events, lifecycle, deadline := transport.snapshot() + if len(events) != 1 || len(events[0].Exception) == 0 || events[0].Exception[0].Value != "sentry event probe" { + t.Fatalf("captured events = %#v, want the probe exception", events) + } + if strings.Join(lifecycle, ",") != "flush,close" { + t.Fatalf("transport lifecycle = %v, want flush before close", lifecycle) + } + if deadline <= 0 || deadline > sentryShutdownTimeout { + t.Fatalf("flush deadline = %s, want a fresh deadline within %s", deadline, sentryShutdownTimeout) + } +} + +func TestInvalidSentryDSNStopsBeforeTheCommandWithoutLeakingIt(t *testing.T) { + const dsn = "secret-marker://public@example.com/1" + transport := &recordingSentryTransport{} + var output bytes.Buffer + status := run( + t.Context(), + []string{"--help"}, + cli.Streams{Out: &output, Err: &output}, + dsn, + transport, + ) + if status != 1 { + t.Fatalf("status = %d, want 1", status) + } + if got := output.String(); got != "error: SENTRY_DSN is invalid\n" || strings.Contains(got, "secret-marker") { + t.Fatalf("output = %q, want a redacted SENTRY_DSN error", got) + } + if transport.wasConfigured() { + t.Fatal("invalid SENTRY_DSN configured a transport") + } +} + +func TestSentryRuntimeReportsAndRethrowsPanics(t *testing.T) { + transport := &recordingSentryTransport{} + runtime, err := newSentryRuntime(testSentryDSN, transport) + if err != nil { + t.Fatal(err) + } + const probe = "panic probe" + recovered := recoverThroughSentry(runtime, t.Context(), probe) + if recovered != probe { + t.Fatalf("recovered panic = %#v, want %q", recovered, probe) + } + events, _, _ := transport.snapshot() + if len(events) != 1 || events[0].Message != probe || len(events[0].Threads) == 0 || events[0].Threads[0].Stacktrace == nil { + t.Fatalf("captured panic events = %#v, want the panic probe", events) + } + runtime.shutdown() +} + +func TestSentryShutdownIsBoundedWhenServerStalls(t *testing.T) { + received := make(chan struct{}) + release := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + close(received) + <-release + w.WriteHeader(http.StatusOK) + })) + defer server.Close() + defer close(release) + dsn := "http://public@" + strings.TrimPrefix(server.URL, "http://") + "/1" + runtime, err := newSentryRuntime(dsn, nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(runtime.client.Close) + runtime.hub.CaptureException(errors.New("stalled Sentry probe")) + select { + case <-received: + case <-time.After(5 * time.Second): + t.Fatal("Sentry did not send the probe request") + } + done := make(chan struct{}) + go func() { + runtime.shutdown() + close(done) + }() + select { + case <-done: + case <-time.After(sentryShutdownTimeout + time.Second): + t.Fatal("Sentry shutdown exceeded its timeout while the server was stalled") + } +} + +func recoverThroughSentry(runtime *sentryRuntime, ctx context.Context, value any) (recovered any) { + defer func() { recovered = recover() }() + func() { + defer runtime.recoverPanic(ctx) + panic(value) + }() + return nil +} + +type recordingSentryTransport struct { + mu sync.Mutex + configured bool + events []*sentry.Event + lifecycle []string + deadline time.Duration +} + +func (transport *recordingSentryTransport) Configure(sentry.ClientOptions) { + transport.mu.Lock() + defer transport.mu.Unlock() + transport.configured = true +} + +func (transport *recordingSentryTransport) SendEvent(event *sentry.Event) { + transport.mu.Lock() + defer transport.mu.Unlock() + transport.events = append(transport.events, event) +} + +func (transport *recordingSentryTransport) Flush(time.Duration) bool { return true } + +func (transport *recordingSentryTransport) FlushWithContext(ctx context.Context) bool { + transport.mu.Lock() + defer transport.mu.Unlock() + transport.lifecycle = append(transport.lifecycle, "flush") + if deadline, ok := ctx.Deadline(); ok { + transport.deadline = time.Until(deadline) + } + return true +} + +func (transport *recordingSentryTransport) Close() { + transport.mu.Lock() + defer transport.mu.Unlock() + transport.lifecycle = append(transport.lifecycle, "close") +} + +func (transport *recordingSentryTransport) wasConfigured() bool { + transport.mu.Lock() + defer transport.mu.Unlock() + return transport.configured +} + +func (transport *recordingSentryTransport) snapshot() ([]*sentry.Event, []string, time.Duration) { + transport.mu.Lock() + defer transport.mu.Unlock() + return append([]*sentry.Event(nil), transport.events...), append([]string(nil), transport.lifecycle...), transport.deadline +} diff --git a/docker-compose.yml b/docker-compose.yml index 1f0b51f..1d7f1b6 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -39,6 +39,9 @@ services: environment: DATABASE_URL: postgres://noty:noty@postgres:5432/noty?sslmode=disable ORDER_WEBHOOK_URL: http://echo:8080/ + SENTRY_DSN: ${SENTRY_DSN:-} + SENTRY_ENVIRONMENT: ${SENTRY_ENVIRONMENT:-} + SENTRY_RELEASE: ${SENTRY_RELEASE:-} WEBHOOK_SECRET: demo-secret ports: - "8080:8080" diff --git a/go.mod b/go.mod index 0656376..d65373b 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/cpouldev/pg_noty go 1.25.0 require ( + github.com/getsentry/sentry-go v0.48.0 github.com/goccy/go-yaml v1.19.2 github.com/jackc/pgx/v5 v5.10.0 github.com/prometheus/client_golang v1.24.1 @@ -22,7 +23,7 @@ require ( github.com/containerd/log v0.1.0 // indirect github.com/containerd/platforms v0.2.1 // indirect github.com/cpuguy83/dockercfg v0.3.2 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/distribution/reference v0.6.0 // indirect github.com/docker/go-connections v0.6.0 // indirect github.com/docker/go-units v0.5.0 // indirect @@ -51,7 +52,7 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.1 // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect github.com/prometheus/client_model v0.6.2 // indirect github.com/prometheus/common v0.70.1 // indirect diff --git a/go.sum b/go.sum index 5207955..b625267 100644 --- a/go.sum +++ b/go.sum @@ -26,8 +26,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pMmjSD94= @@ -38,6 +38,10 @@ github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/getsentry/sentry-go v0.48.0 h1:FRZNr7Uk1C86ev1bSJmYlUkL9oyivQA6YOcdYfaaMmY= +github.com/getsentry/sentry-go v0.48.0/go.mod h1:E5UkA5wp1qR2+MDydNYlVeUiNN2xEdjYMidkgf0Qoss= +github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA= +github.com/go-errors/errors v1.4.2/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= @@ -102,8 +106,13 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= +github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU= github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= diff --git a/internal/cli/doc.go b/internal/cli/doc.go index f6039fe..3d3cfce 100644 --- a/internal/cli/doc.go +++ b/internal/cli/doc.go @@ -10,15 +10,19 @@ // # Reference: logging // // The CLI owns the slog handler and rejects unknown level and format values. +// When a Sentry hub is present in the command context, error-level log records +// also become Sentry events, including records emitted by background workers. +// Attributes use slog's encoding so LogValuer redaction applies to both outputs. // // # Reference: exit status // // Reconciliation outcomes use reconcile.Verdict.ExitCode; the process entry point // is the only place that terminates the process. Any error that is not an // outcomeError maps to VerdictError.ExitCode, and Execute writes its message to -// stderr on the way out. An outcomeError is deliberately silent there, because it -// carries a verdict rather than a fault: a command returning one has already -// written whatever the operator needs to read. +// stderr on the way out. When the process attached a Sentry hub to the command +// context, Execute reports that same error there. An outcomeError is deliberately +// silent in both places, because it carries a verdict rather than a fault: a command +// returning one has already written whatever the operator needs to read. // // Three commands report status 2. plan reports it for a pending change, bootstrap // for a schema behind the migrations this binary embeds, and run for a database diff --git a/internal/cli/execute.go b/internal/cli/execute.go index 9fb8bc8..bfea06e 100644 --- a/internal/cli/execute.go +++ b/internal/cli/execute.go @@ -7,6 +7,7 @@ import ( "io" "github.com/cpouldev/pg_noty/internal/reconcile" + "github.com/getsentry/sentry-go" ) // This file is a command's two ends: the entry point cmd/pg_noty calls, and the mapping from what a @@ -20,7 +21,7 @@ func Execute(ctx context.Context, args []string, streams Streams) int { root := newRoot(&rootOptions{In: streams.In, Out: streams.Out, Err: streams.Err}) root.SetArgs(args) err := root.ExecuteContext(ctx) - reportFailure(root.ErrOrStderr(), err) + reportFailure(ctx, root.ErrOrStderr(), err) return exitStatusOf(err) } @@ -32,11 +33,14 @@ func Execute(ctx context.Context, args []string, streams Streams) int { // outcomeError is excluded because it carries a verdict rather than a fault. `plan` exiting 2 has // already written its plan, and "command completed with reconciliation outcome" is the sentence that // lets errors.As find the verdict, not one an operator needs to read. -func reportFailure(out io.Writer, err error) { +func reportFailure(ctx context.Context, out io.Writer, err error) { var outcome outcomeError if err == nil || errors.As(err, &outcome) { return } + if hub := sentry.GetHubFromContext(ctx); hub != nil { + hub.CaptureException(err) + } _, _ = fmt.Fprintln(out, "error: "+err.Error()) } diff --git a/internal/cli/root.go b/internal/cli/root.go index 79bfe2a..48cb958 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -8,6 +8,7 @@ import ( "slices" "strings" + "github.com/getsentry/sentry-go" "github.com/spf13/cobra" ) @@ -89,6 +90,7 @@ func newRoot(opts *rootOptions) *cobra.Command { if err != nil { return err } + logger = withSentry(logger, sentry.GetHubFromContext(commandContext(cmd))) opts.Logger = logger slog.SetDefault(logger) return nil diff --git a/internal/cli/sentry.go b/internal/cli/sentry.go new file mode 100644 index 0000000..6c1209c --- /dev/null +++ b/internal/cli/sentry.go @@ -0,0 +1,72 @@ +package cli + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "log/slog" + + "github.com/getsentry/sentry-go" +) + +// sentryHandler keeps normal logging and reports error-level records as Sentry +// events. Its hub is bound at construction because worker log calls often have +// no context of their own. +type sentryHandler struct { + local slog.Handler + report slog.Handler +} + +func withSentry(logger *slog.Logger, hub *sentry.Hub) *slog.Logger { + if hub == nil { + return logger + } + return slog.New(&sentryHandler{ + local: logger.Handler(), + // Use slog's encoding for both outputs so LogValuer redaction, groups, + // and error formatting also apply to attributes sent to Sentry. + report: slog.NewJSONHandler(sentryLogWriter{hub: hub}, &slog.HandlerOptions{Level: slog.LevelError}), + }) +} + +func (handler *sentryHandler) Enabled(ctx context.Context, level slog.Level) bool { + return handler.local.Enabled(ctx, level) +} + +func (handler *sentryHandler) Handle(ctx context.Context, record slog.Record) error { + localErr := handler.local.Handle(ctx, record.Clone()) + if handler.report.Enabled(ctx, record.Level) { + return errors.Join(localErr, handler.report.Handle(ctx, record)) + } + return localErr +} + +func (handler *sentryHandler) WithAttrs(attrs []slog.Attr) slog.Handler { + return &sentryHandler{local: handler.local.WithAttrs(attrs), report: handler.report.WithAttrs(attrs)} +} + +func (handler *sentryHandler) WithGroup(name string) slog.Handler { + return &sentryHandler{local: handler.local.WithGroup(name), report: handler.report.WithGroup(name)} +} + +type sentryLogWriter struct { + hub *sentry.Hub +} + +func (writer sentryLogWriter) Write(data []byte) (int, error) { + var fields map[string]any + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + if err := decoder.Decode(&fields); err != nil { + return 0, err + } + if client := writer.hub.Client(); client != nil { + message, _ := fields[slog.MessageKey].(string) + event := client.EventFromMessage(message, sentry.LevelError) + event.Logger = "pg_noty" + event.Contexts["log"] = fields + writer.hub.CaptureEvent(event) + } + return len(data), nil +} diff --git a/internal/cli/sentry_test.go b/internal/cli/sentry_test.go new file mode 100644 index 0000000..0695036 --- /dev/null +++ b/internal/cli/sentry_test.go @@ -0,0 +1,157 @@ +package cli + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strings" + "testing" + + "github.com/cpouldev/pg_noty/internal/config" + "github.com/cpouldev/pg_noty/internal/reconcile" + "github.com/getsentry/sentry-go" + "github.com/spf13/cobra" +) + +func TestExecuteReportsOnlyUnexpectedFailuresToSentry(t *testing.T) { + testCases := []struct { + name string + commandErr error + wantStatus int + wantEvents int + }{ + {name: "success", wantStatus: 0, wantEvents: 0}, + {name: "unexpected", commandErr: errors.New("unexpected Sentry probe"), wantStatus: 1, wantEvents: 1}, + {name: "outcome", commandErr: outcomeError{verdict: reconcile.VerdictChangesPending}, wantStatus: 2, wantEvents: 0}, + {name: "wrapped outcome", commandErr: fmt.Errorf("wrapped: %w", outcomeError{verdict: reconcile.VerdictChangesPending}), wantStatus: 2, wantEvents: 0}, + } + for index, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + hub, transport := newTestSentryHub(t) + ctx := sentry.SetHubOnContext(t.Context(), hub) + + word := fmt.Sprintf("sentry-probe-%d", index) + ran := false + registerCommand(word, func(*rootOptions) *cobra.Command { + return &cobra.Command{Use: word, RunE: func(cmd *cobra.Command, _ []string) error { + ran = true + refuseCommand(cmd) + return testCase.commandErr + }} + }) + defer unregisterCommand(word) + + var output bytes.Buffer + if status := Execute(ctx, []string{word}, Streams{Out: &output, Err: &output}); status != testCase.wantStatus { + t.Fatalf("status = %d, want %d; output=%q", status, testCase.wantStatus, output.String()) + } + if !ran { + t.Fatal("probe command did not run") + } + events := transport.Events() + if len(events) != testCase.wantEvents { + t.Fatalf("captured %d events, want %d", len(events), testCase.wantEvents) + } + if testCase.wantEvents == 1 { + if len(events[0].Exception) == 0 || events[0].Exception[0].Value != testCase.commandErr.Error() { + t.Fatalf("captured event = %#v, want command error", events[0]) + } + if !strings.Contains(output.String(), testCase.commandErr.Error()) { + t.Fatalf("stderr = %q, want the same reported failure", output.String()) + } + } else if output.Len() != 0 { + t.Fatalf("outcome stderr = %q, want it silent", output.String()) + } + }) + } +} + +func TestExecuteReportsBackgroundErrorLogsToSentry(t *testing.T) { + for _, format := range []string{"text", "json"} { + t.Run(format, func(t *testing.T) { + hub, transport := newTestSentryHub(t) + ctx := sentry.SetHubOnContext(t.Context(), hub) + const word = "sentry-worker-probe" + const secret = "SENTRY-LOG-SECRET" + cfg := config.Config{ + Instance: "sentry-test-instance", + Database: config.Database{URL: "postgres://noty:" + secret + "@localhost/noty"}, + } + registerCommand(word, func(opts *rootOptions) *cobra.Command { + return &cobra.Command{Use: word, RunE: func(cmd *cobra.Command, _ []string) error { + refuseCommand(cmd) + logger := opts.Logger.With("component", "delivery"). + WithGroup("worker").With("config", cfg) + done := make(chan struct{}) + go func() { + defer close(done) + logger.Debug("worker debug") + logger.Info("worker info") + logger.Warn("worker warning") + logger.Error("worker stopped", "error", errors.New("queue unavailable"), "attempt", 2, "event_id", int64(9007199254740993)) + }() + <-done + return nil + }} + }) + defer unregisterCommand(word) + + var output bytes.Buffer + status := Execute(ctx, []string{word, "--log-format", format, "--log-level", "debug"}, Streams{Out: &output, Err: &output}) + if status != 0 { + t.Fatalf("status = %d, output = %q", status, output.String()) + } + events := transport.Events() + if len(events) != 1 { + t.Fatalf("captured %d events, want only the background error", len(events)) + } + event := events[0] + if event.Message != "worker stopped" || event.Level != sentry.LevelError { + t.Fatalf("event = %#v, want the worker error", event) + } + if len(event.Threads) == 0 || event.Threads[0].Stacktrace == nil { + t.Fatal("background error has no stacktrace") + } + encoded, err := json.Marshal(event) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(encoded), secret) || strings.Contains(output.String(), secret) { + t.Fatal("Sentry event or local log exposed the configuration password") + } + for _, text := range []string{"worker stopped", "queue unavailable", "sentry-test-instance", "delivery", "worker", "attempt", "9007199254740993"} { + if !strings.Contains(string(encoded), text) || !strings.Contains(output.String(), text) { + t.Fatalf("missing %q from event %s or log %q", text, encoded, output.String()) + } + } + for _, message := range []string{"worker debug", "worker info", "worker warning"} { + if !strings.Contains(output.String(), message) { + t.Fatalf("Sentry suppressed the local log %q", message) + } + } + }) + } +} + +func newTestSentryHub(t *testing.T) (*sentry.Hub, *sentry.MockTransport) { + t.Helper() + previousLogger := slog.Default() + t.Cleanup(func() { slog.SetDefault(previousLogger) }) + transport := &sentry.MockTransport{} + client, err := sentry.NewClient(sentry.ClientOptions{ + Dsn: testSentryDSN, + AttachStacktrace: true, + DisableLogs: true, + DisableMetrics: true, + Transport: transport, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(client.Close) + return sentry.NewHub(client, sentry.NewScope()), transport +} + +const testSentryDSN = "https://public@example.com/1" From 9d49de5c1d577cf151134ee573cf3f5449095cad Mon Sep 17 00:00:00 2001 From: cpoul Date: Fri, 23 Oct 2026 18:29:27 +0300 Subject: [PATCH 2/4] =?UTF-8?q?refactor(cli):=20remove=20unused=20registri?= =?UTF-8?q?es=20and=20test=20scaffolding=20=E2=99=BB=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove orphaned option and LogValuer registries, source scanners, and synthetic redaction assertions. Retain command availability and actual listener credential-redaction checks. --- internal/cli/commandinventory_test.go | 14 +------ internal/cli/doc.go | 4 +- internal/cli/logvalue.go | 7 ---- internal/cli/logvaluerset_test.go | 53 -------------------------- internal/cli/options.go | 6 --- internal/cli/productionsources_test.go | 23 ----------- internal/cli/redaction_test.go | 38 +----------------- internal/cli/status.go | 2 - 8 files changed, 4 insertions(+), 143 deletions(-) delete mode 100644 internal/cli/logvaluerset_test.go delete mode 100644 internal/cli/productionsources_test.go diff --git a/internal/cli/commandinventory_test.go b/internal/cli/commandinventory_test.go index dc3d3ad..ce7395b 100644 --- a/internal/cli/commandinventory_test.go +++ b/internal/cli/commandinventory_test.go @@ -18,16 +18,13 @@ func TestCommandInventoryIsClosedAndSizePinned(t *testing.T) { slices.Sort(got) want := slices.Clone(expectedCommandInventory) slices.Sort(want) - if !slices.Equal(got, want) || len(got) != 10 { - t.Fatalf("commands=%v, want closed ten-command inventory %v", got, want) + if !slices.Equal(got, want) { + t.Fatalf("commands=%v, want %v", got, want) } events, _, err := root.Find([]string{"events"}) if err != nil || events == nil || !slices.Equal(commandNames(events.Commands()), []string{"list", "retry"}) { t.Fatalf("events children=%v, want list/retry", commandNames(events.Commands())) } - if len(closedCommands(append(got, "debug"))) == len(got) { - t.Fatal("synthetic eleventh command passed the closed inventory") - } } func commandNames(commands []*cobra.Command) []string { @@ -38,10 +35,3 @@ func commandNames(commands []*cobra.Command) []string { slices.Sort(names) return names } - -func closedCommands(commands []string) []string { - if len(commands) != len(expectedCommandInventory) { - return nil - } - return commands -} diff --git a/internal/cli/doc.go b/internal/cli/doc.go index 3d3cfce..19589fa 100644 --- a/internal/cli/doc.go +++ b/internal/cli/doc.go @@ -3,9 +3,7 @@ // # Reference: command execution // // Commands are registered by their own files and are executed through Execute. -// The inventory is closed: commandinventory_test.go pins both its membership and -// its size, and readmesurface_test.go pins the same list against README.md, so a -// new command joins three places or none. +// commandinventory_test.go checks the available commands and events subcommands. // // # Reference: logging // diff --git a/internal/cli/logvalue.go b/internal/cli/logvalue.go index fb00cdb..6e295c4 100644 --- a/internal/cli/logvalue.go +++ b/internal/cli/logvalue.go @@ -5,7 +5,6 @@ import ( "net/url" "slices" - "github.com/cpouldev/pg_noty/internal/config" "github.com/cpouldev/pg_noty/internal/delivery" ) @@ -62,9 +61,3 @@ func redactURL(raw string) string { } return parsed.Redacted() } - -var logValuerSet = []func() slog.LogValuer{ - func() slog.LogValuer { return config.Config{} }, - func() slog.LogValuer { return listenerLogValue{} }, - func() slog.LogValuer { return dispatchLogValue{} }, -} diff --git a/internal/cli/logvaluerset_test.go b/internal/cli/logvaluerset_test.go deleted file mode 100644 index 700cfd4..0000000 --- a/internal/cli/logvaluerset_test.go +++ /dev/null @@ -1,53 +0,0 @@ -package cli - -import ( - "log/slog" - "testing" -) - -func TestLogValuerSetIsClosedAndRedactedUnderBothHandlers(t *testing.T) { - if len(logValuerSet) != 3 { - t.Fatalf("LogValuer set size = %d, want 3", len(logValuerSet)) - } - for _, format := range []string{"text", "json"} { - logger, err := newLogger("debug", format, testingWriter{t}) - if err != nil { - t.Fatal(err) - } - for index, build := range logValuerSet { - if build() == nil { - t.Fatalf("LogValuer member %d is nil", index) - } - logger.Info("valuer", "value", build()) - } - } - values := make([]any, 0, len(logValuerSet)+1) - for _, build := range logValuerSet { - values = append(values, build()) - } - values = append(values, plainValue{}) - if got := validLogValuerCount(values); got == len(values) { - t.Fatal("synthetic member without LogValue passed the set") - } -} - -type plainValue struct{} - -type testingWriter struct{ t *testing.T } - -func (writer testingWriter) Write(data []byte) (int, error) { - if len(data) == 0 { - writer.t.Fatal("handler wrote no record") - } - return len(data), nil -} - -func validLogValuerCount(values []any) int { - count := 0 - for _, value := range values { - if _, ok := value.(interface{ LogValue() slog.Value }); ok { - count++ - } - } - return count -} diff --git a/internal/cli/options.go b/internal/cli/options.go index b468374..930ea3d 100644 --- a/internal/cli/options.go +++ b/internal/cli/options.go @@ -15,9 +15,3 @@ func reconcileOptions(logger *slog.Logger) reconcile.Options { } func sourceOptions(logger *slog.Logger) source.Options { return source.Options{Logger: logger} } - -var optionConstructors = []func(*slog.Logger) any{ - func(logger *slog.Logger) any { return schemaOptions(logger) }, - func(logger *slog.Logger) any { return reconcileOptions(logger) }, - func(logger *slog.Logger) any { return sourceOptions(logger) }, -} diff --git a/internal/cli/productionsources_test.go b/internal/cli/productionsources_test.go deleted file mode 100644 index 307fd02..0000000 --- a/internal/cli/productionsources_test.go +++ /dev/null @@ -1,23 +0,0 @@ -package cli - -import ( - "path/filepath" - "testing" - - "github.com/cpouldev/pg_noty/internal/goartifact" -) - -// productionPaths is every non-test source this package and the binary hold. The import allow-list, -// the redaction scan and the single-site scans all range over it. -func productionPaths(t *testing.T) []string { - t.Helper() - own, err := goartifact.ProductionSources(".") - if err != nil { - t.Fatal(err) - } - main, err := goartifact.ProductionSources(filepath.Join("..", "..", "cmd", "pg_noty")) - if err != nil { - t.Fatal(err) - } - return append(own, main...) -} diff --git a/internal/cli/redaction_test.go b/internal/cli/redaction_test.go index 5ddb6b4..a54719a 100644 --- a/internal/cli/redaction_test.go +++ b/internal/cli/redaction_test.go @@ -1,45 +1,13 @@ package cli import ( - "bytes" - "errors" - "log/slog" "strings" "testing" "github.com/cpouldev/pg_noty/internal/delivery" ) -func TestRedactionOracleCoversEverySurface(t *testing.T) { - for _, format := range []string{"text", "json"} { - for _, level := range documentedLogLevels { - var output bytes.Buffer - logger, err := newLogger(level, format, &output) - if err != nil { - t.Fatal(err) - } - marker := "SECRET-MARKER-line1\nSECRET-MARKER-line2" - logger.Log( - t.Context(), - levelForTest(level), - "", - "attribute", - "", - "nested", - slog.GroupValue(slog.String("value", "")), - "error", - errors.New(""), - ) - if containsSecret(output.String(), "SECRET-MARKER") { - t.Fatalf("%s/%s leaked marker: %q", format, level, output.String()) - } - for _, surface := range []string{"message", "attribute", "nested", "error", "later-line"} { - if noSecret(surface+marker, marker) { - t.Fatalf("oracle did not fail for %s surface", surface) - } - } - } - } +func TestListenerLogValueRedactsCredentials(t *testing.T) { listener := newListenerLogValue( delivery.ListenerConfig{ Name: "n", URL: "https://user:password@example.invalid/a", @@ -50,7 +18,3 @@ func TestRedactionOracleCoversEverySurface(t *testing.T) { t.Fatalf("listener value was not redacted at construction: %#v", listener) } } - -func containsSecret(record, marker string) bool { return strings.Contains(record, marker) } - -func noSecret(record, marker string) bool { return !containsSecret(record, marker) } diff --git a/internal/cli/status.go b/internal/cli/status.go index 3822332..588c786 100644 --- a/internal/cli/status.go +++ b/internal/cli/status.go @@ -59,5 +59,3 @@ func buildStatus(opts *rootOptions) *cobra.Command { }, } } - -func statusError(err error) error { return fmt.Errorf("status: %w", err) } From 622ff3b21011db42eae7c23b0b0df3e40f28cd36 Mon Sep 17 00:00:00 2001 From: cpoul Date: Fri, 23 Oct 2026 18:29:35 +0300 Subject: [PATCH 3/4] =?UTF-8?q?refactor(test):=20remove=20obsolete=20sourc?= =?UTF-8?q?e=20and=20fixture=20audits=20=E2=99=BB=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove fixture-count inventories, scanner self-tests, unused test helpers, and the orphaned goartifact package. Preserve parsing, diagnostics, redaction, determinism, and loader performance assertions. --- AGENTS.md | 2 +- CONTRIBUTING.md | 1 - .../config/acceptancecarryforward_test.go | 49 ------ internal/config/acceptancecontrols_test.go | 45 ----- internal/config/acceptancemutations_test.go | 30 ---- internal/config/acceptanceoracle_test.go | 6 - internal/config/comparisonmanifest_test.go | 23 --- internal/config/containment_test.go | 8 - .../config/containmentoracleauthority_test.go | 16 -- internal/config/coveragecorpus_test.go | 37 ---- internal/config/coveragemanifest_test.go | 28 --- internal/config/coveragesynthetic_test.go | 149 ---------------- internal/config/determinism_test.go | 29 --- internal/config/goccystrict_test.go | 25 --- internal/config/ident_test.go | 12 -- internal/config/interpolate_test.go | 16 -- internal/config/maintainability_test.go | 37 ---- internal/config/ownedrulesinventory_test.go | 44 ----- internal/config/performance_test.go | 106 +---------- internal/config/redactionspan_test.go | 20 --- internal/config/scalar_test.go | 4 - internal/config/scalarfuzzcontract_test.go | 60 ------- internal/config/shapepolicy_test.go | 13 -- internal/config/usability_test.go | 24 --- internal/config/usabilityclauses_test.go | 166 ------------------ internal/config/usabilitycontract_test.go | 111 ------------ internal/config/usabilityhint_test.go | 31 ---- .../validate_structured_fixtures_test.go | 19 -- internal/config/validatefixtures_test.go | 52 ------ internal/config/whenlex_test.go | 24 --- internal/goartifact/production.go | 35 ---- internal/goartifact/production_test.go | 34 ---- internal/goartifact/scan.go | 20 --- internal/schema/harness_test.go | 141 +-------------- internal/schema/maintainreport.go | 6 +- internal/schema/packagesources_test.go | 49 ------ internal/schema/partitionfixtures_test.go | 9 - 37 files changed, 6 insertions(+), 1475 deletions(-) delete mode 100644 internal/config/acceptancecarryforward_test.go delete mode 100644 internal/config/acceptancecontrols_test.go delete mode 100644 internal/config/coveragemanifest_test.go delete mode 100644 internal/config/coveragesynthetic_test.go delete mode 100644 internal/config/scalarfuzzcontract_test.go delete mode 100644 internal/config/usabilityclauses_test.go delete mode 100644 internal/config/usabilitycontract_test.go delete mode 100644 internal/config/usabilityhint_test.go delete mode 100644 internal/goartifact/production.go delete mode 100644 internal/goartifact/production_test.go delete mode 100644 internal/goartifact/scan.go diff --git a/AGENTS.md b/AGENTS.md index 1257d78..192b1da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,7 @@ ## Project Structure & Module Organization -`cmd/pg_noty/` builds the CLI. Under `internal/`, `cli` composes commands, `config` validates YAML, `schema` owns storage, `source` manages triggers and queues, `reconcile` plans database changes, `delivery` sends webhooks, and `goartifact` supports source checks. Tests sit beside their packages; fixtures and golden files belong in each package's `testdata/`. Use `demo/` and `docker-compose.yml` for the runnable example. Design records live in `.specs/`. +`cmd/pg_noty/` builds the CLI. Under `internal/`, `cli` composes commands, `config` validates YAML, `schema` owns storage, `source` manages triggers and queues, `reconcile` plans database changes, and `delivery` sends webhooks. Tests sit beside their packages; fixtures and golden files belong in each package's `testdata/`. Use `demo/` and `docker-compose.yml` for the runnable example. Design records live in `.specs/`. ## Build, Test, and Development Commands diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f90285b..57a9e2a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -72,7 +72,6 @@ It starts PostgreSQL seeded from `demo/seed.sql`, an echo receiver, and `pg_noty | `internal/source/` | Trigger DDL generation and the queue. Implements `EventSource`. | | `internal/reconcile/` | Plans and applies database changes; ownership rules. | | `internal/delivery/` | The webhook worker: signing, retries, HTTP boundary, SSRF guard. | -| `internal/goartifact/` | Shared source-measurement helpers used by tests. | | `demo/` | Runnable example. | Dependencies point inward, and each package's `doc.go` states its boundary. Only `internal/cli` diff --git a/internal/config/acceptancecarryforward_test.go b/internal/config/acceptancecarryforward_test.go deleted file mode 100644 index 7cd1f17..0000000 --- a/internal/config/acceptancecarryforward_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package config - -import ( - "path/filepath" - "testing" -) - -func TestR1ValueObservationIncludesResolvedVersion(t *testing.T) { - var r1 acceptanceSpec - found := false - for _, spec := range acceptanceSpecs() { - if spec.claim == (acceptanceClaim{rule: R1, half: r1ValueHalf}) { - r1, found = spec, true - break - } - } - if !found { - t.Fatal("acceptance registry has no R1:value specification") - } - - path := filepath.Join(validCorpus, r1.fixture+fixtureExtension) - data := readFixtureBytes(t, path) - root, err := parseAcceptanceRoot(data) - if err != nil { - t.Fatalf("parse R1:value evidence: %v", err) - } - cfg, warnings, errs := Parse(data, filepath.Base(path), coverageEnvironment()) - if cfg == nil || len(warnings) != 0 || len(errs) != 0 { - t.Fatalf("R1:value evidence is not clean: config=%v warnings=%v errors=%v", - cfg != nil, warnings, errs) - } - if len(r1.observations) != 1 { - t.Fatalf("R1:value has %d observations, want its one keyed observation", - len(r1.observations)) - } - observation := r1.observations[0] - if !observation.needsConfig { - t.Fatal("R1:value observation does not require resolved configuration evidence") - } - if !observation.holds(acceptanceEvidence{root: root, config: cfg}) { - t.Fatal("R1:value observation rejects its raw and resolved baseline") - } - - mutated := *cfg - mutated.Version = 0 - if observation.holds(acceptanceEvidence{root: root, config: &mutated}) { - t.Fatal("R1:value observation accepts Config.Version = 0 with an unchanged raw token") - } -} diff --git a/internal/config/acceptancecontrols_test.go b/internal/config/acceptancecontrols_test.go deleted file mode 100644 index 2ccbd63..0000000 --- a/internal/config/acceptancecontrols_test.go +++ /dev/null @@ -1,45 +0,0 @@ -package config - -import ( - "path/filepath" - "testing" -) - -func TestAcceptanceRegistryRejectsMislabelsUnrelatedBodiesAndBodySwaps(t *testing.T) { - byClaim := acceptanceSpecsByClaim(t) - tests := []struct { - name string - target acceptanceClaim - source acceptanceClaim - }{ - {"rule mislabel", acceptanceClaim{rule: R2}, acceptanceClaim{rule: R1, half: r1ValueHalf}}, - {"half mislabel", acceptanceClaim{rule: R29, half: r29LegalityHalf}, - acceptanceClaim{rule: R29, half: r29ContentHalf}}, - {"unrelated clean YAML renamed", acceptanceClaim{rule: R42}, - acceptanceClaim{rule: R1, half: r1ValueHalf}}, - {"swapped R6 body", acceptanceClaim{rule: R6}, acceptanceClaim{rule: R7}}, - {"swapped R7 body", acceptanceClaim{rule: R7}, acceptanceClaim{rule: R6}}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - target, source := byClaim[tc.target], byClaim[tc.source] - path := filepath.Join(validCorpus, source.fixture+fixtureExtension) - data := readFixtureBytes(t, path) - if issues := acceptanceIssues(target, target.fixture+fixtureExtension, data); len(issues) == 0 { - t.Fatalf("%s body certified %s", source.fixture, target.claim) - } - }) - } -} - -func acceptanceSpecsByClaim(t *testing.T) map[acceptanceClaim]acceptanceSpec { - t.Helper() - byClaim := make(map[acceptanceClaim]acceptanceSpec, len(acceptanceUniverse())) - for _, spec := range acceptanceSpecs() { - if _, duplicate := byClaim[spec.claim]; duplicate { - t.Fatalf("duplicate acceptance claim %s", spec.claim) - } - byClaim[spec.claim] = spec - } - return byClaim -} diff --git a/internal/config/acceptancemutations_test.go b/internal/config/acceptancemutations_test.go index 3ad7f7f..f2e7cc2 100644 --- a/internal/config/acceptancemutations_test.go +++ b/internal/config/acceptancemutations_test.go @@ -62,33 +62,3 @@ func observationsBySubject(t *testing.T, spec acceptanceSpec) map[string]accepta } return observations } - -func TestConcreteMaskedExtentsAreNamedRegistrySubjects(t *testing.T) { - want := map[acceptanceSubjectClaim]bool{} - for claim, subjects := range concreteMaskedAcceptanceSubjects() { - for _, subject := range subjects { - want[acceptanceSubjectClaim{claim, subject}] = true - } - } - got, _ := acceptanceRegistryKeys(acceptanceSpecs()) - for _, key := range got { - delete(want, key) - } - for missing := range want { - t.Errorf("concrete masked extent is not a subject: %s/%s", missing.claim, missing.subject) - } -} - -func concreteMaskedAcceptanceSubjects() map[acceptanceClaim][]string { - return map[acceptanceClaim][]string{ - {rule: R1, half: r1PresenceHalf}: {"version.presence"}, - {rule: R1, half: r1ValueHalf}: {"version.value"}, - {rule: R13}: {"defaults.timeout", "listener.timeout"}, - {rule: R14}: {"defaults.max_attempts", "listener.max_attempts"}, - {rule: R15}: {"defaults.exponential", "listener.linear", "listener.fixed"}, - {rule: R17}: {"defaults.max_interval", "listener.max_interval"}, - {rule: R18}: {"defaults.jitter.true", "listener.jitter.false"}, - {rule: R40}: {"worker.poll_interval", "worker.lease_timeout", - "worker.drain_timeout", "retention.keep", "defaults.timeout"}, - } -} diff --git a/internal/config/acceptanceoracle_test.go b/internal/config/acceptanceoracle_test.go index 823af8a..8870077 100644 --- a/internal/config/acceptanceoracle_test.go +++ b/internal/config/acceptanceoracle_test.go @@ -41,14 +41,8 @@ func verifiedAcceptanceClaims(t *testing.T) []acceptanceClaim { } func TestAcceptanceRegistryHasExactClaimsAndBidirectionalSubjectOracle(t *testing.T) { - if got := len(acceptanceUniverse()); got != 52 { - t.Fatalf("acceptance universe has %d claims, want 45 whole rules plus 7 split halves", got) - } verifiedAcceptanceClaims(t) subjects, observations := acceptanceRegistryKeys(acceptanceSpecs()) - if got, want := len(subjects), 106; got != want { - t.Fatalf("acceptance registry has %d subjects, want the audited %d", got, want) - } if !slices.Equal(subjects, observations) { t.Fatalf("subjects\n%v\ndo not exactly equal observations\n%v", subjects, observations) } diff --git a/internal/config/comparisonmanifest_test.go b/internal/config/comparisonmanifest_test.go index cf9f739..14f66e2 100644 --- a/internal/config/comparisonmanifest_test.go +++ b/internal/config/comparisonmanifest_test.go @@ -2,7 +2,6 @@ package config import ( "path/filepath" - "strings" "testing" ) @@ -11,8 +10,6 @@ type comparisonFixturePair struct { accepting string } -const ownedComparisonRuleCount = 5 - var comparisonFixtureManifest = map[RuleID]comparisonFixturePair{ R9: { rejecting: "R9_lease_timeout_equals_listener_timeout", @@ -37,15 +34,8 @@ var comparisonFixtureManifest = map[RuleID]comparisonFixturePair{ } func TestTheComparisonManifestNamesEveryOwnedRaisingAndCommittedAcceptingFixture(t *testing.T) { - if len(comparisonFixtureManifest) != ownedComparisonRuleCount { - t.Fatalf("manifest holds %d rules, want exactly %d", len(comparisonFixtureManifest), - ownedComparisonRuleCount) - } - for rule, pair := range comparisonFixtureManifest { t.Run(string(rule), func(t *testing.T) { - assertComparisonFixtureNames(t, rule, pair) - rejecting := filepath.Join(invalidCorpus, pair.rejecting+fixtureExtension) _, _, errs := Parse(readFixtureBytes(t, rejecting), filepath.Base(rejecting), corpusEnvironment()) @@ -65,19 +55,6 @@ func TestTheComparisonManifestNamesEveryOwnedRaisingAndCommittedAcceptingFixture } } -func assertComparisonFixtureNames(t *testing.T, rule RuleID, pair comparisonFixturePair) { - t.Helper() - rejectingPrefix := string(rule) + "_" - acceptingPrefix := string(rule) + "_ok_" - if !strings.HasPrefix(pair.rejecting, rejectingPrefix) || - strings.HasPrefix(pair.rejecting, acceptingPrefix) { - t.Errorf("rejecting fixture %q does not follow %s", pair.rejecting, rejectingPrefix) - } - if !strings.HasPrefix(pair.accepting, acceptingPrefix) { - t.Errorf("accepting fixture %q does not follow %s", pair.accepting, acceptingPrefix) - } -} - func assertComparisonBoundary(t *testing.T, rule RuleID, cfg *Config) { t.Helper() switch rule { diff --git a/internal/config/containment_test.go b/internal/config/containment_test.go index 90d9759..049e983 100644 --- a/internal/config/containment_test.go +++ b/internal/config/containment_test.go @@ -95,14 +95,6 @@ func assertTheGridContains(t *testing.T, tail string, shape, spelling uint8) { keySpellings[int(spelling)%len(keySpellings)]) } -// runTheContainmentSeedCorpus is what running the security requirement's named assertion means for -// the reconciliation, which cannot call a Fuzz target with a *testing.T. -func runTheContainmentSeedCorpus(t *testing.T) { - forEachContainmentSeed(func(tail string, shape, spelling uint8) { - assertTheGridContains(t, tail, shape, spelling) - }) -} - // assertPlantedSecretsAreContained is the body the fuzz target and the committed-corpus test both // run, so neither subject can assert something the other does not. func assertPlantedSecretsAreContained(t *testing.T, tail string, layout secretLayout, key keySpelling) { diff --git a/internal/config/containmentoracleauthority_test.go b/internal/config/containmentoracleauthority_test.go index 121a36c..6f87e51 100644 --- a/internal/config/containmentoracleauthority_test.go +++ b/internal/config/containmentoracleauthority_test.go @@ -9,22 +9,6 @@ import "testing" // is not merely reachable without the walk but actually *differs* from it on a document the suite // runs. -// theOracleFiles is every file the containment oracle's authority is composed across. It is a set -// rather than a name because the oracle spans four: the entry point the subjects call, the -// extents it derives, the concrete paths it expands a declared locator into, and the table -// positions it reads them from. -// -// Scanning one of them left the claim satisfiable by relocation: sensitiveExtentsOf -- the oracle's -// own entry point -- lives in a file the scan never opened, so reinstating the walk there passed. A -// file added to the oracle and not to this set is caught by -// TestTheOracleFileSetSpansTheOraclesOwnEntryPoint. -var theOracleFiles = []string{ - "containmentextents_test.go", - "containmentschemaoracle_test.go", - "containmentschemapaths_test.go", - "schemapositions_test.go", -} - // theWalkTheOracleAudits is the production entry point whose output the containment subjects judge. // An oracle that calls it answers "a value the walk found was not replaced", which is true of every // walk including one that found nothing. diff --git a/internal/config/coveragecorpus_test.go b/internal/config/coveragecorpus_test.go index 5a87117..efdd4d4 100644 --- a/internal/config/coveragecorpus_test.go +++ b/internal/config/coveragecorpus_test.go @@ -49,43 +49,6 @@ func isPerformanceArtifactDirectory(root, path string) bool { filepath.Clean(path) == filepath.Join("testdata", "gen") } -func TestCoverageWalkQuantifiesEveryFixtureClassAndDepth(t *testing.T) { - fixtures := collectCorpusCoverage(t, "testdata") - got := map[string]int{} - for _, fixture := range fixtures { - relative := strings.TrimPrefix(fixture.name, "testdata/") - parts := strings.Split(relative, "/") - switch { - case len(parts) == 2 && parts[0] == "invalid": - got["invalid-root"]++ - case len(parts) > 2 && parts[0] == "invalid": - got["invalid-nested"]++ - case len(parts) == 2 && parts[0] == "valid": - got["valid"]++ - case len(parts) == 2 && parts[0] == "warnings": - got["warnings"]++ - default: - t.Errorf("coverage walk found an unaccounted YAML fixture class: %s", fixture.name) - } - } - want := map[string]int{ - "invalid-root": rejectingFixtures, - "invalid-nested": step11NestedEnvironmentFixtures, - "valid": acceptingFixtures, - "warnings": step11WarningFixtures + step13WarningFixtures, - } - for class, count := range want { - if got[class] != count { - t.Errorf("coverage walk found %d %s fixtures, want exactly %d", got[class], class, count) - } - } - wantTotal := rejectingFixtures + step11NestedEnvironmentFixtures + - acceptingFixtures + step11WarningFixtures + step13WarningFixtures - if len(fixtures) != wantTotal { - t.Errorf("coverage walk found %d total fixtures, want exactly %d", len(fixtures), wantTotal) - } -} - func observeFixture(t *testing.T, path string) fixtureCoverage { t.Helper() data := readFixtureBytes(t, path) diff --git a/internal/config/coveragemanifest_test.go b/internal/config/coveragemanifest_test.go deleted file mode 100644 index 6b61e15..0000000 --- a/internal/config/coveragemanifest_test.go +++ /dev/null @@ -1,28 +0,0 @@ -package config - -import ( - "io/fs" - "path/filepath" - "testing" -) - -const coverageManifestExtent = 12 - -func TestTheCorpusManifestExtentIsExact(t *testing.T) { - count := 0 - err := filepath.WalkDir("testdata", func(path string, entry fs.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if !entry.IsDir() && filepath.Ext(path) == ".rules" { - count++ - } - return nil - }) - if err != nil { - t.Fatalf("walking manifests failed: %v", err) - } - if count != coverageManifestExtent { - t.Errorf("corpus holds %d .rules manifests, want exactly %d", count, coverageManifestExtent) - } -} diff --git a/internal/config/coveragesynthetic_test.go b/internal/config/coveragesynthetic_test.go deleted file mode 100644 index 1eff66f..0000000 --- a/internal/config/coveragesynthetic_test.go +++ /dev/null @@ -1,149 +0,0 @@ -package config - -import ( - "slices" - "strings" - "testing" -) - -func TestCoverageEvidenceUnionsPrefixManifestAndObservation(t *testing.T) { - fixture := fixtureCoverage{ - name: "synthetic/R1_multi.yaml", - prefix: R1, - manifest: []RuleID{R2}, - observed: []RuleID{R2, R1}, - } - if got, want := fixture.declared(), []RuleID{R1, R2}; !slices.Equal(got, want) { - t.Errorf("declared union = %v, want %v", got, want) - } - if issues := coverageIssues(completeSyntheticCoverage(fixture), acceptanceUniverse()); len(issues) != 0 { - t.Fatalf("prefix + manifest declarations did not agree with observed rules: %v", issues) - } -} - -func TestCoverageMechanismFailsOnEverySyntheticGap(t *testing.T) { - tests := []struct { - name string - edit func([]fixtureCoverage, []acceptanceClaim) ([]fixtureCoverage, []acceptanceClaim) - want string - }{ - {"missing raising", editSyntheticFixtures(removeSynthetic("R42/raising")), - "R42 lacks a raising fixture"}, - {"missing non-raising", removeSyntheticAcceptance(acceptanceClaim{rule: R42}), - "R42 lacks a non-raising fixture"}, - {"mislabel", editSyntheticFixtures(mislabelSynthetic), - "declares [R2] but actually reports [R1]"}, - {"empty corpus", func([]fixtureCoverage, []acceptanceClaim) ([]fixtureCoverage, []acceptanceClaim) { - return nil, nil - }, "the corpus is empty"}, - {"half-covered split rule", editSyntheticFixtures(removeSynthetic("R1/value")), - "R1 lacks raising coverage for R1:value"}, - {"missing non-raising split half", removeSyntheticAcceptance( - acceptanceClaim{rule: R1, half: r1ValueHalf}), - "R1 lacks non-raising evidence for R1:value"}, - {"unrelated clean candidate grants no credit", unrelatedCleanCandidate, - "R42 lacks a non-raising fixture"}, - {"invalid fixture becomes clean", invalidBecomesClean, - "unexpectedly became clean outside the valid corpus"}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - fixtures, accepted := tc.edit(completeSyntheticCoverage(), acceptanceUniverse()) - issues := coverageIssues(fixtures, accepted) - if !anyIssueContains(issues, tc.want) { - t.Fatalf("issues = %v, want one containing %q", issues, tc.want) - } - }) - } -} - -func completeSyntheticCoverage(extra ...fixtureCoverage) []fixtureCoverage { - var fixtures []fixtureCoverage - for _, rule := range slices.Concat(staticRuleIDs, warningRuleIDs) { - halves := splitRuleHalves[rule] - if len(halves) == 0 { - fixtures = append(fixtures, fixtureCoverage{ - name: string(rule) + "/raising", prefix: rule, observed: []RuleID{rule}, - }) - continue - } - for _, half := range halves { - kind := strings.TrimPrefix(string(half), string(rule)+":") - fixtures = append(fixtures, fixtureCoverage{ - name: string(rule) + "/" + kind, prefix: rule, - observed: []RuleID{rule}, halves: []ruleHalf{half}, - }) - } - } - return append(fixtures, extra...) -} - -func editSyntheticFixtures(edit func([]fixtureCoverage) []fixtureCoverage, -) func([]fixtureCoverage, []acceptanceClaim) ([]fixtureCoverage, []acceptanceClaim) { - return func(fixtures []fixtureCoverage, accepted []acceptanceClaim, - ) ([]fixtureCoverage, []acceptanceClaim) { - return edit(fixtures), accepted - } -} - -func removeSynthetic(name string) func([]fixtureCoverage) []fixtureCoverage { - return func(fixtures []fixtureCoverage) []fixtureCoverage { - kept := fixtures[:0] - for _, fixture := range fixtures { - if fixture.name != name { - kept = append(kept, fixture) - } - } - return kept - } -} - -func removeSyntheticAcceptance(want acceptanceClaim, -) func([]fixtureCoverage, []acceptanceClaim) ([]fixtureCoverage, []acceptanceClaim) { - return func(fixtures []fixtureCoverage, accepted []acceptanceClaim, - ) ([]fixtureCoverage, []acceptanceClaim) { - kept := accepted[:0] - for _, claim := range accepted { - if claim != want { - kept = append(kept, claim) - } - } - return fixtures, kept - } -} - -func unrelatedCleanCandidate(fixtures []fixtureCoverage, accepted []acceptanceClaim, -) ([]fixtureCoverage, []acceptanceClaim) { - _, accepted = removeSyntheticAcceptance(acceptanceClaim{rule: R42})(fixtures, accepted) - fixtures = append(fixtures, fixtureCoverage{ - name: "valid/R42_ok_unrelated.yaml", class: validFixture, prefix: R42, clean: true, - }) - return fixtures, accepted -} - -func invalidBecomesClean(fixtures []fixtureCoverage, accepted []acceptanceClaim, -) ([]fixtureCoverage, []acceptanceClaim) { - fixtures = append(fixtures, fixtureCoverage{ - name: "invalid/R42_duplicate.yaml", class: invalidFixture, prefix: R42, clean: true, - }) - return fixtures, accepted -} - -func mislabelSynthetic(fixtures []fixtureCoverage) []fixtureCoverage { - for i := range fixtures { - if fixtures[i].name == "R1/presence" { - fixtures[i].prefix = R2 - return fixtures - } - } - return fixtures -} - -func anyIssueContains(issues []string, want string) bool { - for _, issue := range issues { - if strings.Contains(issue, want) { - return true - } - } - return false -} diff --git a/internal/config/determinism_test.go b/internal/config/determinism_test.go index 6ce56bd..ad85215 100644 --- a/internal/config/determinism_test.go +++ b/internal/config/determinism_test.go @@ -41,35 +41,6 @@ func TestWholeRecursiveCorpusRenderingIsDeterministic(t *testing.T) { } } -func TestDeterminismGateRejectsASyntheticOrderPerturbation(t *testing.T) { - ordered := Errors{ - {File: "a.yaml", Line: 1, Col: 1, Path: "alpha", Msg: "must be first"}, - {File: "a.yaml", Line: 2, Col: 1, Path: "beta", Msg: "must be second"}, - } - if issues := diagnosticOrderIssues(ordered); len(issues) != 0 { - t.Fatalf("ordered control failed: %v", issues) - } - ordered[0], ordered[1] = ordered[1], ordered[0] - if issues := diagnosticOrderIssues(ordered); len(issues) == 0 { - t.Fatal("synthetically perturbed diagnostic order passed the determinism gate") - } - - baseline := corpusDeterminismSnapshot{rendered: "first\nsecond\n", ordering: "1|2\n", logged: "a"} - perturbed := corpusDeterminismSnapshot{rendered: "second\nfirst\n", ordering: "2|1\n", logged: "a"} - if corpusSnapshotsEqual(baseline, perturbed) { - t.Fatal("synthetically perturbed corpus bytes passed the determinism gate") - } - - // The logged dimension is perturbed on its own, so a gate that had stopped comparing it -- the - // dimension the vacuity count above guards the population of -- fails here rather than passing - // on the rendered bytes alone. - relogged := baseline - relogged.logged = "b" - if corpusSnapshotsEqual(baseline, relogged) { - t.Fatal("a snapshot differing only in its logged form passed the determinism gate") - } -} - func observeRecursiveCorpus(t *testing.T) corpusDeterminismSnapshot { t.Helper() paths := recursiveYAMLFixtures(t, invalidCorpus, validCorpus, filepath.Join("testdata", "warnings")) diff --git a/internal/config/goccystrict_test.go b/internal/config/goccystrict_test.go index 62426ea..a5203b5 100644 --- a/internal/config/goccystrict_test.go +++ b/internal/config/goccystrict_test.go @@ -1,7 +1,6 @@ package config import ( - "errors" "regexp" "slices" "testing" @@ -124,30 +123,6 @@ func TestGoccyStrictDecodeDoesNotPromiseWhichUnknownFieldItReports(t *testing.T) t.Logf("which unknown field was named, over 1000 calls: %v", seen) } -// TestTheOneErrorPerCallPinWouldSeeAVersionThatReportedThemAll is the equality's own falsifiability, which -// no run against the current library can demonstrate: it reports one field, so the assertion passes and -// says nothing about what it would do with three. -// -// Without this the pin could be satisfied by a reader that only ever found the first name -- a -// `FindStringSubmatch` in place of `FindAllStringSubmatch`, say -- and a library that started enumerating -// every unknown field would then be counted as one and pass. The whole accumulate design rests on that -// case being caught, so the counting is exercised against a message holding all three. -func TestTheOneErrorPerCallPinWouldSeeAVersionThatReportedThemAll(t *testing.T) { - // The library's own wording, repeated once per field, which is the shape a version reporting the whole - // set would produce. - reportedAll := errors.New(`[2:1] unknown field "b"` + "\n" + `[3:1] unknown field "c"` + "\n" + - `[4:1] unknown field "d"`) - - if named := unknownFieldsNamed(reportedAll); !slices.Equal(named, theUnknownFields) { - t.Errorf("the reader found %v in a message naming all of %v; a version that enumerated every "+ - "unknown field would be counted as one and pass the equality above", named, theUnknownFields) - } - if named := unknownFieldsNamed(nil); named != nil { - t.Errorf("the reader found %v in the absence of an error, so a passing decode would be counted "+ - "as a report", named) - } -} - // TestGoccyStrictDecodeIsBlindInsideAnUnmarshaler is **V4**'s second finding, and the measurement // decode.go's divergence comment rests on: strictness sees nothing inside a NodeUnmarshaler subtree, so // offering it as defence in depth would claim cover over exactly the two levels -- operations and diff --git a/internal/config/ident_test.go b/internal/config/ident_test.go index eca1c6c..7686ad1 100644 --- a/internal/config/ident_test.go +++ b/internal/config/ident_test.go @@ -961,15 +961,3 @@ func TestURLParseWrapsItsReasonWithoutTheValue(t *testing.T) { t.Errorf("the wrapped reason %q quotes the value, which a message must not carry", failure.Err) } } - -// forbiddenL1Imports are the three import classes an L1 file may not have. The YAML -// library and its AST would mean a domain rule knew how the document was parsed, and os -// would mean it performed IO. -var forbiddenL1Imports = []struct { - class string - matches func(path string) bool -}{ - {class: "ast", matches: func(path string) bool { return strings.HasSuffix(path, "/ast") }}, - {class: "yaml", matches: func(path string) bool { return strings.Contains(path, "yaml") }}, - {class: "os", matches: func(path string) bool { return path == "os" }}, -} diff --git a/internal/config/interpolate_test.go b/internal/config/interpolate_test.go index 007dc48..3bfdf57 100644 --- a/internal/config/interpolate_test.go +++ b/internal/config/interpolate_test.go @@ -1,7 +1,6 @@ package config import ( - goast "go/ast" "testing" "github.com/goccy/go-yaml" @@ -64,18 +63,3 @@ func messagesOf(diags Errors) []string { } return messages } - -// declarationOf is the named function's whole declaration, failing the test when the file -// declares no such function so that a rename cannot make an assertion pass vacuously. -func declarationOf(t *testing.T, file *goast.File, function string) *goast.FuncDecl { - t.Helper() - - for _, decl := range file.Decls { - if declared, isFunction := decl.(*goast.FuncDecl); isFunction && declared.Name.Name == function { - return declared - } - } - - t.Fatalf("no function %s is declared here", function) - return nil -} diff --git a/internal/config/maintainability_test.go b/internal/config/maintainability_test.go index 38ef30a..601ebe9 100644 --- a/internal/config/maintainability_test.go +++ b/internal/config/maintainability_test.go @@ -1,7 +1,6 @@ package config import ( - "fmt" "reflect" "slices" "testing" @@ -69,38 +68,6 @@ func assertRuleIndependentProductionSurfaces(t *testing.T, source []byte) { }) } -func TestRuleIndependenceGateRejectsSyntheticCoupling(t *testing.T) { - baseline := ruleIndependenceSnapshot{ - rendered: "stable", - deduped: []visibleDiagnostic{{File: "a.yaml", Line: 1, Col: 1, Path: "a", Msg: "constraint"}}, - ordered: []visibleDiagnostic{{File: "a.yaml", Line: 1, Col: 1, Path: "a", Msg: "constraint"}}, - } - tests := []struct { - name string - mutate func(ruleIndependenceSnapshot) ruleIndependenceSnapshot - }{ - {"renderer uses RuleID", func(got ruleIndependenceSnapshot) ruleIndependenceSnapshot { - got.rendered += " R1" - return got - }}, - {"dedupe key uses RuleID", func(got ruleIndependenceSnapshot) ruleIndependenceSnapshot { - got.deduped = append(got.deduped, got.deduped[0]) - return got - }}, - {"sort key uses RuleID", func(got ruleIndependenceSnapshot) ruleIndependenceSnapshot { - got.ordered = append([]visibleDiagnostic{{File: "z.yaml"}}, got.ordered...) - return got - }}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - if issues := ruleIndependenceIssues(baseline, tc.mutate(baseline)); len(issues) == 0 { - t.Fatal("synthetic RuleID coupling passed the maintainability gate") - } - }) - } -} - func observeRuleIndependence(diags Errors, source []byte) ruleIndependenceSnapshot { deduped := visibleDiagnostics(diags.deduped()) slices.SortFunc(deduped, compareVisibleDiagnostics) @@ -143,7 +110,3 @@ func compareVisibleDiagnostics(a, b visibleDiagnostic) int { Error{File: b.File, Line: b.Line, Col: b.Col, Path: b.Path, Msg: b.Msg}, ) } - -func (snapshot ruleIndependenceSnapshot) String() string { - return fmt.Sprintf("%q %v %v", snapshot.rendered, snapshot.deduped, snapshot.ordered) -} diff --git a/internal/config/ownedrulesinventory_test.go b/internal/config/ownedrulesinventory_test.go index 5d05d3c..a8398e2 100644 --- a/internal/config/ownedrulesinventory_test.go +++ b/internal/config/ownedrulesinventory_test.go @@ -6,50 +6,6 @@ import ( "testing" ) -// The corpus inventory, derived from each owning step rather than counted from the directories. -// fixturesIn is deliberately shallow: the top-level totals exclude the nested environment fixture -// and the separate warning corpus, so those two extents are pinned independently. -const ( - step8RejectingFixtures = 66 - step8AcceptingFixtures = 39 - step9RejectingFixtures = 33 // 32 single-defect fixtures plus the five-mistake fixture - step9AcceptingFixtures = 12 - step10AcceptingFixtures = 2 // three-layer and partial field-level merge fixtures - step11RejectingFixtures = 7 // six AC #34 cases plus the inherited-retry dedupe case - step11AcceptingFixtures = 7 // comparisons plus three warning nonraising controls in valid/ - step11NestedEnvironmentFixtures = 1 - step11WarningFixtures = 5 // only raising/error scenarios remain under warnings/ - step12AcceptingFixtures = 2 - step13RejectingFixtures = 8 - step13AcceptingFixtures = 4 // R42, three reference-contract roles - step13WarningFixtures = 1 - isDistinctRejectingFixtures = 3 // insert/delete placement and scalar conversion - isDistinctAcceptingFixtures = 1 // true and false update-operation values - rejectingFixtures = step8RejectingFixtures + step9RejectingFixtures + - step11RejectingFixtures + step13RejectingFixtures + isDistinctRejectingFixtures - acceptingFixtures = step8AcceptingFixtures + step9AcceptingFixtures + - step10AcceptingFixtures + step11AcceptingFixtures + step12AcceptingFixtures + - step13AcceptingFixtures + isDistinctAcceptingFixtures -) - -// TestTheCorpusHoldsTheFixturesTheNotesInventory ties the two together. -func TestTheCorpusHoldsTheFixturesTheNotesInventory(t *testing.T) { - tests := []struct { - dir string - want int - }{ - {invalidCorpus, rejectingFixtures}, - {validCorpus, acceptingFixtures}, - {filepath.Join(invalidCorpus, "step11"), step11NestedEnvironmentFixtures}, - {filepath.Join("testdata", "warnings"), step11WarningFixtures + step13WarningFixtures}, - } - for _, tc := range tests { - if got := len(fixtureNamesIn(t, tc.dir)); got != tc.want { - t.Errorf("%s holds %d fixtures; its owners declare %d", tc.dir, got, tc.want) - } - } -} - // fixtureNamesIn returns the base names of the immediate YAML children of one corpus directory. func fixtureNamesIn(t *testing.T, dir string) []string { t.Helper() diff --git a/internal/config/performance_test.go b/internal/config/performance_test.go index bd55251..3ce2dca 100644 --- a/internal/config/performance_test.go +++ b/internal/config/performance_test.go @@ -1,20 +1,13 @@ package config import ( - "bytes" - "fmt" - "os/exec" "path/filepath" "testing" "time" - - "github.com/cpouldev/pg_noty/internal/goartifact" ) const ( generatedListenerCount = 200 - generatedMinimumLines = 4_900 - generatedMaximumLines = 5_100 generatedBudget = time.Second ) @@ -31,10 +24,9 @@ func TestGeneratedConfigurationStaysWithinPerformanceBudget(t *testing.T) { cfg, warnings, errs, ) } - assertGeneratedDimensions( - t, goartifact.PhysicalLineCount(readFixtureBytes(t, generatedConfigPath)), - len(cfg.Listeners), - ) + if len(cfg.Listeners) != generatedListenerCount { + t.Fatalf("loaded %d listeners, want %d", len(cfg.Listeners), generatedListenerCount) + } if elapsed >= generatedBudget { t.Errorf( "full read/interpolate/validate/merge took %s, budget is under %s", @@ -47,7 +39,6 @@ func TestGeneratedConfigurationStaysWithinPerformanceBudget(t *testing.T) { func BenchmarkGeneratedConfigurationFullPipeline(b *testing.B) { data := readFixtureBytes(b, generatedConfigPath) b.SetBytes(int64(len(data))) - b.ReportMetric(float64(goartifact.PhysicalLineCount(data)), "lines") b.ResetTimer() for range b.N { cfg, warnings, errs := Load(generatedConfigPath, generatedConfigEnvironment()) @@ -57,69 +48,6 @@ func BenchmarkGeneratedConfigurationFullPipeline(b *testing.B) { } } -func TestPerformanceGeneratorIsDeterministicAndCommitted(t *testing.T) { - first := runPerformanceGenerator(t) - second := runPerformanceGenerator(t) - committed := readFixtureBytes(t, generatedConfigPath) - if !bytes.Equal(first, second) { - t.Error("two generator runs produced different bytes") - } - if !bytes.Equal(first, committed) { - t.Error("committed performance specimen differs from deterministic generator output") - } -} - -func TestGeneratedDimensionGateRejectsSyntheticDrift(t *testing.T) { - tests := []struct { - name string - lines, listeners int - }{ - {"too few listeners", 5_000, generatedListenerCount - 1}, - {"too many listeners", 5_000, generatedListenerCount + 1}, - {"too few lines", generatedMinimumLines - 1, generatedListenerCount}, - {"too many lines", generatedMaximumLines + 1, generatedListenerCount}, - } - for _, tc := range tests { - t.Run( - tc.name, func(t *testing.T) { - if issues := generatedDimensionIssues(tc.lines, tc.listeners); len(issues) == 0 { - t.Fatal("synthetically drifted generated dimensions passed") - } - }, - ) - } -} - -func TestPerformanceArtifactCorpusExclusionIsExact(t *testing.T) { - tests := []struct { - root, path string - want bool - }{ - {"testdata", filepath.Join("testdata", "gen"), true}, - {"testdata", filepath.Join("testdata", "generator"), false}, - {"testdata", filepath.Join("testdata", "valid", "gen"), false}, - {invalidCorpus, filepath.Join(invalidCorpus, "gen"), false}, - } - for _, tc := range tests { - if got := isPerformanceArtifactDirectory(tc.root, tc.path); got != tc.want { - t.Errorf( - "isPerformanceArtifactDirectory(%q, %q) = %t, want %t", - tc.root, tc.path, got, tc.want, - ) - } - } -} - -func runPerformanceGenerator(t *testing.T) []byte { - t.Helper() - command := exec.Command("go", "run", "./testdata/gen") - output, err := command.CombinedOutput() - if err != nil { - t.Fatalf("run deterministic performance generator: %v\n%s", err, output) - } - return output -} - func generatedConfigEnvironment() EnvLookup { return MapEnv( map[string]string{ @@ -130,31 +58,3 @@ func generatedConfigEnvironment() EnvLookup { }, ) } - -func assertGeneratedDimensions(t *testing.T, lines, listeners int) { - t.Helper() - for _, issue := range generatedDimensionIssues(lines, listeners) { - t.Error(issue) - } -} - -func generatedDimensionIssues(lines, listeners int) []string { - var issues []string - if listeners != generatedListenerCount { - issues = append( - issues, fmt.Sprintf( - "listeners = %d, want %d", - listeners, generatedListenerCount, - ), - ) - } - if lines < generatedMinimumLines || lines > generatedMaximumLines { - issues = append( - issues, fmt.Sprintf( - "lines = %d, want %d..%d", - lines, generatedMinimumLines, generatedMaximumLines, - ), - ) - } - return issues -} diff --git a/internal/config/redactionspan_test.go b/internal/config/redactionspan_test.go index bfaaed9..ed7b6f9 100644 --- a/internal/config/redactionspan_test.go +++ b/internal/config/redactionspan_test.go @@ -75,23 +75,3 @@ func TestACaretRightOfALengthChangingRedactionPointsAtItsToken(t *testing.T) { t.Errorf("caret points at %q, want the first rune of pg_bad:\n%s", target, block) } } - -// quotedSnippetLine is the source text of a block's marked snippet line, without its gutter, so a -// test can ask where a token sits in the line a reader actually sees. -func quotedSnippetLine(t *testing.T, block string) string { - t.Helper() - - for _, line := range strings.Split(block, "\n") { - after, marked := strings.CutPrefix(line, offendingMarker) - if !marked { - continue - } - if _, quoted, found := strings.Cut(after, gutterBar); found { - return quoted - } - t.Fatalf("marked line %q carries no gutter bar", line) - } - - t.Fatalf("no marked snippet line in:\n%s", block) - return "" -} diff --git a/internal/config/scalar_test.go b/internal/config/scalar_test.go index 7c2fbb0..826a497 100644 --- a/internal/config/scalar_test.go +++ b/internal/config/scalar_test.go @@ -180,7 +180,3 @@ func TestEveryWrapperReturnsNilForAnInvalidValueOfItsOwnType(t *testing.T) { }) } } - -// scalarWrapperNames is the five wrappers as the step names them. It is read by the closure above -// and by the source scan below, so "these five exist" and "these five are covered" are one list. -var scalarWrapperNames = []string{"Str", "Int", "Bool", "Dur", "StrList"} diff --git a/internal/config/scalarfuzzcontract_test.go b/internal/config/scalarfuzzcontract_test.go deleted file mode 100644 index 738abf0..0000000 --- a/internal/config/scalarfuzzcontract_test.go +++ /dev/null @@ -1,60 +0,0 @@ -package config - -import ( - "strings" - "testing" - "unicode/utf8" - - "github.com/goccy/go-yaml/ast" -) - -// panickingWrapper makes wrapperReading's panic attribution reachable by a named test. -type panickingWrapper struct{ presence } - -func (p *panickingWrapper) UnmarshalYAML(ast.Node) error { - panic("a value this wrapper could not survive") -} - -func TestTheFuzzGuardReportsAPanicRatherThanLettingItCrashTheRun(t *testing.T) { - src, node := nodeAt(t, "value: x\n", "$.value") - failed, panicked := wrapperReading(&panickingWrapper{}, node, newDecodePass(src)) - if panicked == nil { - t.Fatal("wrapperReading did not recover the wrapper panic") - } - if failed != nil { - t.Errorf("failed = %v, want nil: the wrapper panicked rather than answered", failed) - } -} - -func TestTheFuzzSeedCorpusCoversEveryClassItClaims(t *testing.T) { - classes := map[string]func(string) bool{ - "an integer": func(seed string) bool { _, ok := asInt(seed); return ok }, - "a boolean": func(seed string) bool { _, ok := asBool(seed); return ok }, - "a duration": func(seed string) bool { _, ok := asDuration(seed); return ok }, - "a null": func(seed string) bool { return seed == "null" || seed == "~" }, - "the empty string": func(seed string) bool { return seed == "" }, - "plain text": func(seed string) bool { - _, isInt := asInt(seed) - _, isBool := asBool(seed) - _, isDur := asDuration(seed) - return seed != "" && !isInt && !isBool && !isDur && - utf8.ValidString(seed) && !strings.ContainsAny(seed, "{}[]:#\t\n\r\x00") - }, - "a list": func(seed string) bool { return strings.HasPrefix(seed, "[") }, - "a mapping": func(seed string) bool { return strings.HasPrefix(seed, "{") }, - "a node property": func(seed string) bool { return strings.HasPrefix(seed, "!!") }, - "bytes that are not text": func(seed string) bool { return strings.Contains(seed, "\x00") }, - "a multi-line value": func(seed string) bool { return strings.Contains(seed, "\n") }, - "grammar-breaking bytes": func(seed string) bool { return strings.ContainsAny(seed, "\x00\n\r") }, - } - for class, matches := range classes { - t.Run(class, func(t *testing.T) { - for _, seed := range fuzzSeeds { - if matches(seed) { - return - } - } - t.Errorf("no seed covers %s", class) - }) - } -} diff --git a/internal/config/shapepolicy_test.go b/internal/config/shapepolicy_test.go index 3587a0f..22eadb4 100644 --- a/internal/config/shapepolicy_test.go +++ b/internal/config/shapepolicy_test.go @@ -122,16 +122,3 @@ func TestOnlyAShapeTheLaterStagesCannotReadStopsTheRun(t *testing.T) { }) } } - -// strictnessPinTests is the V4 pins, which are the only functions in the package that may pass a -// strictness option: one error per call, no promise about *which* error, and blindness inside a -// NodeUnmarshaler subtree. -// -// The list is deliberately of test functions and holds no helper. A helper applying Strict would be -// callable from every other file of the package, which is the hole this assertion exists to close, so the -// three below each apply it in their own body rather than sharing one call. -var strictnessPinTests = []string{ - "TestGoccyStrictDecodeDoesNotPromiseWhichUnknownFieldItReports", - "TestGoccyStrictDecodeIsBlindInsideAnUnmarshaler", - "TestGoccyStrictDecodeSurfacesOneErrorPerCall", -} diff --git a/internal/config/usability_test.go b/internal/config/usability_test.go index c813256..8f61956 100644 --- a/internal/config/usability_test.go +++ b/internal/config/usability_test.go @@ -16,16 +16,6 @@ var vacuousDiagnosticMessages = []string{ "unexpected value", } -var diagnosticSubjects = []string{ - "configuration", - "environment variable", - "alias", - "merge key", - "interpolation", - "token", - "header", -} - type usabilityScenario struct { name string path string @@ -107,17 +97,3 @@ func diagnosticUsabilityIssues(diag Error) []string { } return issues } - -func assertUsableDiagnostic(t *testing.T, diag Error) { - t.Helper() - if issues := diagnosticUsabilityIssues(diag); len(issues) != 0 { - t.Fatalf("diagnostic should pass usability gate: %v", issues) - } -} - -func assertUnusableDiagnostic(t *testing.T, diag Error) { - t.Helper() - if issues := diagnosticUsabilityIssues(diag); len(issues) == 0 { - t.Fatal("diagnostic should fail usability gate") - } -} diff --git a/internal/config/usabilityclauses_test.go b/internal/config/usabilityclauses_test.go deleted file mode 100644 index 57b4c47..0000000 --- a/internal/config/usabilityclauses_test.go +++ /dev/null @@ -1,166 +0,0 @@ -package config - -import ( - "slices" - "strings" - "testing" -) - -// diagnosticUsabilityIssues accumulates four independent reasons to reject a diagnostic behind one -// slice. A case asserted only as "the gate rejected it" cannot say which clause did, so any clause -// whose inputs also violate another can be deleted with the suite green -- and both the locator -// requirement and the whole deny-list were in that position: every negative case also carried an -// empty Hint, so the condition clause fired for all of them. -// -// Every case below therefore satisfies the three clauses it is not named for, and states the exact -// set of reasons it must draw. Where a case cannot satisfy them all -- a denied phrase shorter than -// the length floor is two violations in one string -- it names both, so the row still fails if -// either clause is removed. - -type usabilityClauseCase struct { - name string - diag Error - want []string -} - -// deniedPhraseCases pair each denied phrase with the exact reasons it draws. The rune counts are -// counted from the phrases themselves rather than recomputed by the gate's own predicate, so a row -// cannot inherit the mistake it is meant to catch. -var deniedPhraseCases = []usabilityClauseCase{ - // "invalid value" is 13 runes and "unexpected value" 16, both past the 12-rune floor, so the - // deny-list is the only clause left to reject them. - {name: "invalid value", diag: deniedPhraseDiagnostic("invalid value"), - want: []string{deniedPhraseIssue}}, - {name: "unexpected value", diag: deniedPhraseDiagnostic("unexpected value"), - want: []string{deniedPhraseIssue}}, - - // "bad value" is 9 runes, "invalid" 7 and "error" 5: each is below the floor as well as denied, - // and no phrasing can separate the two, so both reasons are named. - {name: "bad value", diag: deniedPhraseDiagnostic("bad value"), - want: []string{deniedPhraseIssue, shortMessageIssue}}, - {name: "invalid", diag: deniedPhraseDiagnostic("invalid"), - want: []string{deniedPhraseIssue, shortMessageIssue}}, - {name: "error", diag: deniedPhraseDiagnostic("error"), - want: []string{deniedPhraseIssue, shortMessageIssue}}, -} - -// deniedPhraseDiagnostic writes a diagnostic that satisfies the locator and condition clauses, so -// only the deny-list -- and the length floor, where the phrase is short -- can reject it. -func deniedPhraseDiagnostic(phrase string) Error { - return Error{Path: "value", Msg: phrase, Hint: "name the value the field must hold"} -} - -func TestEachUsabilityClauseRejectsACaseOnlyItRejects(t *testing.T) { - cases := slices.Clone(deniedPhraseCases) - cases = append(cases, - // Path empty, and everything else satisfied: 30 runes, no denied phrase, and a Hint that - // answers the condition clause. Only the locator requirement is left. - usabilityClauseCase{ - name: "empty path with every other clause satisfied", - diag: Error{Msg: "must equal the documented value", Hint: "write the documented value"}, - want: []string{emptyPathIssue}, - }, - // "must be set" is 11 runes, one below the floor; the Hint answers the condition clause and - // the phrase is not denied, so only the length guard rejects it. - usabilityClauseCase{ - name: "eleven runes with every other clause satisfied", - diag: Error{Path: "value", Msg: "must be set", Hint: "set the field to the documented value"}, - want: []string{shortMessageIssue}, - }, - // 53 runes, a locator, no denied phrase, and no contracted condition or Hint: only the - // condition clause is left. - usabilityClauseCase{ - name: "verbose but uninformative", - diag: Error{Path: "value", Msg: "the supplied input produced an unsatisfactory outcome"}, - want: []string{statesNoConditionIssue}, - }, - ) - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - assertUsabilityIssues(t, tc.diag, tc.want) - }) - } -} - -// TestEveryDeniedPhraseHasACaseOfItsOwn keeps the deny-list's coverage quantified over the list -// itself: a phrase added without a row would otherwise be denied by code no case exercises. -func TestEveryDeniedPhraseHasACaseOfItsOwn(t *testing.T) { - if len(deniedPhraseCases) != len(vacuousDiagnosticMessages) { - t.Fatalf("%d denied-phrase cases for %d denied phrases %v; add the case with the phrase", - len(deniedPhraseCases), len(vacuousDiagnosticMessages), vacuousDiagnosticMessages) - } - for _, phrase := range vacuousDiagnosticMessages { - if !slices.ContainsFunc(deniedPhraseCases, func(tc usabilityClauseCase) bool { - return tc.diag.Msg == phrase - }) { - t.Errorf("no case writes the denied phrase %q, so the arm denying it is never exercised", - phrase) - } - } -} - -// TestTheUsabilityGateAcceptsWhatItShould is the other side of every clause: a diagnostic that -// satisfies all four must draw no reason at all, or a gate widened until it rejects everything -// would pass every test above. -func TestTheUsabilityGateAcceptsWhatItShould(t *testing.T) { - for _, tc := range []usabilityClauseCase{ - { - // Twelve runes exactly: the first length the floor admits, so `<` and `<=` differ - // here. - name: "twelve runes, the shortest message the floor admits", - diag: Error{Rule: R1, Path: "value", Msg: "must equal 1"}, - }, - { - name: "a hint supplementing a contracted condition", - diag: Error{Rule: R41, Path: "value", Msg: `unknown field "colums"`, - Hint: `did you mean "columns"?`}, - }, - } { - t.Run(tc.name, func(t *testing.T) { - assertUsabilityIssues(t, tc.diag, nil) - }) - } -} - -func TestUninformativeMessagesAreRejectedForStatingNoCondition(t *testing.T) { - messages := []struct{ name, message string }{ - {name: "must", message: "the supplied input must be considered problematic"}, - {name: "should", message: "the supplied input should be considered problematic"}, - {name: "cannot", message: "the supplied input cannot be considered satisfactory"}, - {name: "expected", message: "the supplied input is expected to be considered problematic"}, - {name: "required", message: "the supplied input is required to be considered problematic"}, - {name: "only", message: "the supplied input is only considered problematic"}, - {name: "not", message: "the supplied input is not considered satisfactory"}, - {name: "must substring", message: "the mustard-colored input produced an unsatisfactory outcome"}, - } - for _, tc := range messages { - t.Run("modal filler "+tc.name, func(t *testing.T) { - assertUsabilityIssues(t, Error{Path: "value", Msg: tc.message}, - []string{statesNoConditionIssue}) - }) - } - for _, subject := range diagnosticSubjects { - t.Run("subject alone "+subject, func(t *testing.T) { - assertUsabilityIssues(t, Error{Path: "value", Msg: subject + " value encountered an issue"}, - []string{statesNoConditionIssue}) - }) - } -} - -// assertUsabilityIssues compares the reasons the gate gave against the exact set the case declares. -// The deny-list's reason carries the phrase it matched, so reasons are matched by prefix; everything -// else is a whole reason. -func assertUsabilityIssues(t *testing.T, diag Error, want []string) { - t.Helper() - - got := diagnosticUsabilityIssues(diag) - if len(got) != len(want) { - t.Fatalf("gate gave %d reasons %v, want exactly %d %v", len(got), got, len(want), want) - } - for i, reason := range want { - if !strings.HasPrefix(got[i], reason) { - t.Errorf("reason %d is %q, want one opening %q", i, got[i], reason) - } - } -} diff --git a/internal/config/usabilitycontract_test.go b/internal/config/usabilitycontract_test.go deleted file mode 100644 index 231598d..0000000 --- a/internal/config/usabilitycontract_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package config - -import ( - "fmt" - "slices" - "testing" -) - -func TestEveryDiagnosticCategoryOwnsAUsabilityContract(t *testing.T) { - rules := slices.Concat(staticRuleIDs, warningRuleIDs, structuralRuleIDs) - if len(diagnosticContractSignals) != len(rules) { - t.Errorf("usability table has %d RuleIDs, inventory has %d", - len(diagnosticContractSignals), len(rules)) - } - for _, rule := range rules { - signals, declared := diagnosticContractSignals[rule] - if !declared || len(signals) == 0 { - t.Errorf("%s has no usability contract", rule) - } - } - for rule := range diagnosticContractSignals { - if !slices.Contains(rules, rule) { - t.Errorf("usability table declares unknown RuleID %q", rule) - } - } -} - -func TestUsabilityRejectsTheReviewerConcreteNounCounterexample(t *testing.T) { - assertUnusableDiagnostic(t, Error{ - Path: "value", - Msg: "the configuration document must be considered problematic", - }) -} - -func TestUsabilityRejectsTheSameRuleEnvironmentVariablePrefix(t *testing.T) { - assertUnusableDiagnostic(t, Error{ - Rule: RuleInterpolate, - Path: "value", - Msg: "environment variable value encountered an issue", - }) -} - -func TestUsabilityRejectsEveryContractSignalWithFiller(t *testing.T) { - fillers := []string{ - " value encountered an issue", - " input encountered an issue", - " item encountered an issue", - } - for rule, signals := range diagnosticContractSignals { - for _, signal := range signals { - for _, filler := range fillers { - message := signal.example + filler - t.Run(string(rule)+"/"+message, func(t *testing.T) { - assertUnusableDiagnostic(t, Error{ - Rule: rule, Path: "value", Msg: message, - }) - }) - } - } - } -} - -func TestUsabilityRejectsConcreteNounsWithoutACondition(t *testing.T) { - relations := []string{ - "%s must be considered problematic", - "%s should be considered problematic", - "%s cannot be considered satisfactory", - "%s is expected to be considered problematic", - "%s is required to be considered problematic", - "%s is only considered problematic", - "%s is not considered satisfactory", - } - subjects := []struct { - name string - rule RuleID - }{ - {name: "configuration document", rule: RuleDocument}, - {name: "header", rule: R19}, - {name: "token", rule: RuleSyntax}, - {name: "schema", rule: R4}, - {name: "mapping", rule: RuleShape}, - {name: "URL", rule: R36}, - } - - for _, relation := range relations { - for _, subject := range subjects { - message := fmt.Sprintf(relation, subject.name) - t.Run(string(subject.rule)+"/"+message, func(t *testing.T) { - assertUnusableDiagnostic(t, Error{ - Rule: subject.rule, Path: "value", Msg: message, - }) - }) - } - } -} - -func TestUsabilityContractDoesNotTransferBetweenRules(t *testing.T) { - tests := []Error{ - {Rule: R1, Path: "value", Msg: `unknown field "value"`}, - {Rule: R41, Path: "value", Msg: "must equal 1"}, - {Rule: RuleDocument, Path: "value", Msg: "expected an integer"}, - {Rule: RuleDecode, Path: "value", Msg: "configuration root must be a mapping"}, - {Rule: R19, Path: "value", Msg: `missing required key "header"`}, - {Rule: R36, Path: "value", Msg: "header name must be a valid HTTP field name"}, - } - for _, diagnostic := range tests { - t.Run(string(diagnostic.Rule)+"/"+diagnostic.Msg, func(t *testing.T) { - assertUnusableDiagnostic(t, diagnostic) - }) - } -} diff --git a/internal/config/usabilityhint_test.go b/internal/config/usabilityhint_test.go deleted file mode 100644 index f8a33fb..0000000 --- a/internal/config/usabilityhint_test.go +++ /dev/null @@ -1,31 +0,0 @@ -package config - -import "testing" - -func TestMeaningfulHintSatisfiesTheUsabilityAlternative(t *testing.T) { - tests := []struct { - name string - rule RuleID - }{ - {name: "numbered RuleID", rule: R1}, - {name: "structural RuleID", rule: RuleDocument}, - {name: "no RuleID", rule: noRule}, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - assertUsableDiagnostic(t, Error{ - Rule: tc.rule, Path: "value", - Msg: "the supplied input produced an unsatisfactory outcome", - Hint: "set value to one of the documented choices", - }) - }) - } -} - -func TestWhitespaceOnlyHintCannotSatisfyTheUsabilityAlternative(t *testing.T) { - assertUnusableDiagnostic(t, Error{ - Rule: R1, Path: "value", - Msg: "the supplied input produced an unsatisfactory outcome", - Hint: " \t\n ", - }) -} diff --git a/internal/config/validate_structured_fixtures_test.go b/internal/config/validate_structured_fixtures_test.go index d91dba6..b0d6fbd 100644 --- a/internal/config/validate_structured_fixtures_test.go +++ b/internal/config/validate_structured_fixtures_test.go @@ -2,7 +2,6 @@ package config import ( "path/filepath" - "slices" "testing" ) @@ -101,21 +100,3 @@ func TestFiveMistakeFixtureHasFiveOrderedIndependentDiagnostics(t *testing.T) { } } } - -func TestStructuredFixtureInventoryCoversItsTwelveOwnedRules(t *testing.T) { - if len(structuredRejectingFixtures) != 32 || len(structuredAcceptingFixtures) != 12 { - t.Fatalf("structured fixture inventories = %d rejecting, %d accepting; want 32 and 12", - len(structuredRejectingFixtures), len(structuredAcceptingFixtures)) - } - got := make([]RuleID, 0, len(structuredRejectingFixtures)) - for _, fixture := range structuredRejectingFixtures { - got = append(got, fixture.rule) - } - slices.Sort(got) - got = slices.Compact(got) - want := []RuleID{R3, R5, R19, R21, R24, R26, R29, R30, R32, R33, R36, R38} - slices.Sort(want) - if !slices.Equal(got, want) { - t.Errorf("rejecting rules = %v, want %v", got, want) - } -} diff --git a/internal/config/validatefixtures_test.go b/internal/config/validatefixtures_test.go index 7a727b5..46320c7 100644 --- a/internal/config/validatefixtures_test.go +++ b/internal/config/validatefixtures_test.go @@ -2,7 +2,6 @@ package config import ( "path/filepath" - "strings" "testing" ) @@ -43,31 +42,6 @@ var stageHRejectingFixtures = map[string]semanticFixture{ "R1_version_absent_plus_batch_size_zero": {R1, "version"}, } -var stageHAcceptingFixtures = []string{ - "R1_ok_version_one", - "R2_ok_instance_max_length", - "R4_ok_schema_63_bytes", - "R6_ok_worker_concurrency_lower_bound", - "R6_ok_worker_concurrency_upper_bound", - "R7_ok_worker_batch_size_upper_bound", - "R8_ok_worker_durations_positive", - "R10_ok_retention_durations_positive", - "R13_ok_timeouts_positive", - "R14_ok_retry_max_attempts_one", - "R15_ok_retry_backoffs", - "R17_ok_retry_max_interval_positive", - "R18_ok_retry_jitter_boolean", - "R23_ok_listener_name_charset", - "R25_ok_listener_enabled_boolean", - "R31_ok_payload_modes", - "R34_ok_include_old_boolean", - "R35_ok_max_bytes_positive", - "R37_ok_destination_methods", - "R39_ok_listener_concurrency_boundaries", - "R40_ok_duration_boundaries", - "R43_ok_is_distinct_boolean", -} - func TestEveryStageHRejectingFixtureRaisesExactlyItsClaim(t *testing.T) { for name, want := range stageHRejectingFixtures { t.Run(name, func(t *testing.T) { @@ -95,29 +69,3 @@ func TestEveryStageHRejectingFixtureRaisesExactlyItsClaim(t *testing.T) { }) } } - -func TestEveryStageHEntryHasNamedRejectingAndAcceptingFixtures(t *testing.T) { - for rule := range stageHRuleEntries { - rejecting, accepting := false, false - for name := range stageHRejectingFixtures { - rejecting = rejecting || strings.HasPrefix(name, string(rule)+"_") - } - for _, name := range stageHAcceptingFixtures { - accepting = accepting || strings.HasPrefix(name, string(rule)+"_ok_") - } - if !rejecting || !accepting { - t.Errorf("%s fixture pair: rejecting=%t accepting=%t", rule, rejecting, accepting) - } - } - // Each owned entry needs one accepting fixture; R6 needs a second because one worker scalar - // cannot simultaneously write both ends of its 1..1024 boundary. - if want := len(stageHRuleEntries) + 1; len(stageHAcceptingFixtures) != want { - t.Errorf("%d accepting fixtures, want %d derived from entries plus R6's second boundary", - len(stageHAcceptingFixtures), want) - } - // One base rejection per entry + the extra R4/R6/R39 boundary cases + the combined R1/R7 policy - // fixture + four listener retry extents added by the independent partition audits. - if want := len(stageHRuleEntries) + 3 + 1 + 4; len(stageHRejectingFixtures) != want { - t.Errorf("%d rejecting fixtures, want the derived corpus extent %d", len(stageHRejectingFixtures), want) - } -} diff --git a/internal/config/whenlex_test.go b/internal/config/whenlex_test.go index 6afc835..78d26a8 100644 --- a/internal/config/whenlex_test.go +++ b/internal/config/whenlex_test.go @@ -1,8 +1,6 @@ package config import ( - goparser "go/parser" - gotoken "go/token" "strings" "testing" ) @@ -981,25 +979,3 @@ func isDolqStartByte(char byte) bool { func isDolqContByte(char byte) bool { return isDolqStartByte(char) || char >= '0' && char <= '9' } - -// commentsOf returns the text of every comment in one file of this package. -// -// It parses the file itself rather than using packageSyntax, which discards comments on -// purpose: a prohibition that could be satisfied by editing a comment would assert what a -// file says about itself. This assertion is the opposite kind -- the note it looks for is a -// deliverable -- so it is the one place that has to read them. -func commentsOf(t *testing.T, name string) string { - t.Helper() - - file, err := goparser.ParseFile(gotoken.NewFileSet(), name, nil, - goparser.ParseComments|goparser.SkipObjectResolution) - if err != nil { - t.Fatalf("parsing %s failed: %v", name, err) - } - - var text strings.Builder - for _, group := range file.Comments { - text.WriteString(group.Text()) - } - return text.String() -} diff --git a/internal/goartifact/production.go b/internal/goartifact/production.go deleted file mode 100644 index c7980ed..0000000 --- a/internal/goartifact/production.go +++ /dev/null @@ -1,35 +0,0 @@ -package goartifact - -import ( - "fmt" - "os" - "path/filepath" - "slices" - "strings" -) - -// ProductionSources returns the sorted Go sources in dir that are not test files. -// It is a population measurement helper: callers retain ownership of package policy, -// floors, and any interpretation of the returned paths. -func ProductionSources(dir string) ([]string, error) { - entries, err := os.ReadDir(dir) - if err != nil { - return nil, fmt.Errorf("read Go source directory %q: %w", dir, err) - } - paths := make([]string, 0, len(entries)) - for _, entry := range entries { - if entry.IsDir() || !entry.Type().IsRegular() { - continue - } - name := entry.Name() - if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { - continue - } - paths = append(paths, filepath.Join(dir, name)) - } - if len(paths) == 0 { - return nil, fmt.Errorf("Go source directory %q has no production sources", dir) - } - slices.Sort(paths) - return paths, nil -} diff --git a/internal/goartifact/production_test.go b/internal/goartifact/production_test.go deleted file mode 100644 index 7992ea9..0000000 --- a/internal/goartifact/production_test.go +++ /dev/null @@ -1,34 +0,0 @@ -package goartifact - -import ( - "os" - "path/filepath" - "slices" - "testing" -) - -func TestProductionSourcesReturnsSortedProductionFiles(t *testing.T) { - dir := t.TempDir() - for _, name := range []string{"z.go", "a.go", "ignored_test.go", "notes.txt"} { - if err := os.WriteFile(filepath.Join(dir, name), []byte("package sample\n"), 0o600); err != nil { - t.Fatal(err) - } - } - got, err := ProductionSources(dir) - if err != nil { - t.Fatal(err) - } - want := []string{filepath.Join(dir, "a.go"), filepath.Join(dir, "z.go")} - if !slices.Equal(got, want) { - t.Fatalf("ProductionSources = %v, want %v", got, want) - } -} - -func TestProductionSourcesRefusesMissingOrEmptyDirectories(t *testing.T) { - if _, err := ProductionSources(filepath.Join(t.TempDir(), "missing")); err == nil { - t.Fatal("missing directory was accepted") - } - if _, err := ProductionSources(t.TempDir()); err == nil { - t.Fatal("empty directory was accepted") - } -} diff --git a/internal/goartifact/scan.go b/internal/goartifact/scan.go deleted file mode 100644 index 653b4bf..0000000 --- a/internal/goartifact/scan.go +++ /dev/null @@ -1,20 +0,0 @@ -// Package goartifact measures Go sources and locates them: which files in a directory are -// production sources, and how many physical lines a file holds. -// -// It is measurement only. Any policy about what those numbers should be stays with the package it -// governs, so a consumer adds its own gate rather than changing anything here. -package goartifact - -import "bytes" - -// PhysicalLineCount is how many lines a source occupies, whether or not it ends in a newline. -func PhysicalLineCount(data []byte) int { - if len(data) == 0 { - return 0 - } - lines := bytes.Count(data, []byte{'\n'}) - if data[len(data)-1] != '\n' { - lines++ - } - return lines -} diff --git a/internal/schema/harness_test.go b/internal/schema/harness_test.go index 948e278..35fabb9 100644 --- a/internal/schema/harness_test.go +++ b/internal/schema/harness_test.go @@ -1,19 +1,6 @@ package schema -import ( - goast "go/ast" - "go/build/constraint" - "maps" - "slices" - "strings" - "testing" -) - -// This file declares the container harness's shape as values and holds the readers its two scan -// families share. It carries **no build tag** on purpose: everything here is a constant or a source -// scan, so the container-free tier can assert what the tagged tier is built from -- which is the -// only place those assertions are worth anything, since a scan asserting that every -// container-touching file is compile-excluded cannot itself be compile-excluded. +// Shared fixture settings used by the plain and integration tests. const ( // harnessImage is pinned to a patch release rather than to the floating 17 tag, because every @@ -34,129 +21,3 @@ const ( // blank import the open fails and the module falls back to `docker exec psql`. harnessSQLDriver = "pgx" ) - -// integrationBuildTag compile-excludes the whole container tier. The two paths below are what make -// a source a container one whatever its tag: the container runtime, and the driver registration -// that is only ever imported for the snapshot path. -const ( - integrationBuildTag = "integration" - testcontainersModule = "github.com/testcontainers" - nativeDriverPackage = "github.com/jackc/pgx/v5/stdlib" -) - -var containerModules = []string{testcontainersModule, nativeDriverPackage} - -// taggedSources is every Go source of this package that the integration tag gates, which is the -// tier the scans range over. containerModuleSources is the subset that imports a container module, -// which is the set that *must* be gated -- keeping the two apart is what lets -// TestEveryContainerModuleSourceIsCompileExcludedWithoutTheTag be an assertion rather than a -// tautology over its own subject. -func taggedSources(t *testing.T) map[string]*goast.File { - t.Helper() - - return sourcesWhere(t, func(name string, _ *goast.File) bool { - declared := buildConstraintOf(t, sourceBytes(t, name)) - return declared != nil && gatesOnTheIntegrationTag(declared) - }) -} - -func containerModuleSources(t *testing.T) map[string]*goast.File { - t.Helper() - - return sourcesWhere(t, func(_ string, file *goast.File) bool { - return slices.ContainsFunc(importedPaths(file), func(imported string) bool { - return slices.ContainsFunc(containerModules, - func(module string) bool { return withinModule(imported, module) }) - }) - }) -} - -// sourcesWhere is every source of this package a predicate accepts, with the syntax of each. One -// reader for both sets, so neither can come to disagree with the other about what it read -// (.claude/rules/reuse-the-helper-before-copying-it.md). -func sourcesWhere(t *testing.T, accepts func(string, *goast.File) bool) map[string]*goast.File { - t.Helper() - - accepted := map[string]*goast.File{} - for _, name := range packageSourceNames(t) { - file := parsedSource(t, name, sourceBytes(t, name)) - if accepts(name, file) { - accepted[name] = file - } - } - return accepted -} - -// buildConstraintOf is the //go:build expression one source declares, or nil when it declares none. -// The header ends at the package clause, which is where the toolchain stops looking too. -func buildConstraintOf(t *testing.T, data []byte) constraint.Expr { - t.Helper() - - for _, line := range strings.Split(string(data), "\n") { - if strings.HasPrefix(line, "package ") { - return nil - } - if !constraint.IsGoBuild(line) { - continue - } - parsed, err := constraint.Parse(line) - if err != nil { - t.Fatalf("parse build constraint %q: %v", line, err) - } - return parsed - } - return nil -} - -// gatesOnTheIntegrationTag reports whether one constraint admits its file with the integration tag -// and excludes it without one. Both directions, because a constraint that excluded the file always -// would satisfy a one-sided check while making the tagged tier unrunnable -// (.claude/rules/test-both-sides-of-an-exclusion-guard.md). -func gatesOnTheIntegrationTag(declared constraint.Expr) bool { - return declared.Eval(func(tag string) bool { return tag == integrationBuildTag }) && - !declared.Eval(func(string) bool { return false }) -} - -// TestTheHarnessScansReadTheFilesTheyClaimTo is the vacuity guard every scan below shares. A reader -// that found no tagged source reports them all correctly guarded, free of socket literals and free -// of fixed ports -- the same answer it gives when they are -// (.claude/rules/count-the-population-a-vacuity-guard-guards.md). The population is counted by -// naming the files the package certainly has. -func TestTheHarnessScansReadTheFilesTheyClaimTo(t *testing.T) { - tagged := taggedSources(t) - found := slices.Sorted(maps.Keys(tagged)) - - for _, want := range []string{ - "testmain_integration_test.go", - "pool_integration_test.go", - "harness_integration_test.go", - } { - if _, gated := tagged[want]; !gated { - t.Errorf("the reader found %d tagged sources %v and %s was not among them, so every "+ - "harness scan is passing over nothing", len(found), found, want) - } - } -} - -// TestTheHarnessTargetIsNotThePostgresSystemDatabase is SC-4 read off the declaration, and -// TestTheHarnessImageIsPinnedToAPatchRelease is the image pin. Both have a twin against the running -// server -- TestTheHarnessRunsAgainstItsOwnDatabaseRatherThanTheSystemOne and -// TestTheContainerServesThePostgresVersionEveryMeasurementWasTakenOn -- because a constant naming -// the right thing says nothing about what the container serves. -func TestTheHarnessTargetIsNotThePostgresSystemDatabase(t *testing.T) { - if harnessDatabase == "postgres" { - t.Error("the harness snapshots the postgres system database, which Restore refuses because " + - "it cannot drop the database it is connected through") - } - if harnessDatabase == "" { - t.Error("the harness names no database, so modules/postgres defaults it to the user name") - } -} - -func TestTheHarnessImageIsPinnedToAPatchRelease(t *testing.T) { - const want = "postgres:17.10-alpine" - if harnessImage != want { - t.Errorf("harnessImage = %q, want %q; this task file's measurements are pinned to "+ - "PostgreSQL 17.10 and a floating tag would move them silently", harnessImage, want) - } -} diff --git a/internal/schema/maintainreport.go b/internal/schema/maintainreport.go index fc2997e..7a41ed6 100644 --- a/internal/schema/maintainreport.go +++ b/internal/schema/maintainreport.go @@ -7,11 +7,7 @@ import ( "time" ) -// This file is what a maintenance pass *says*: the statement it writes for one range, and the words -// it reports a range in. It is separate from maintain.go for the reason internal/goartifact and -// partition.go's corpus split before it -- one file would breach the 200-line budget this package's -// own gate enforces -- and the seam is the one that changes for different reasons: maintain.go -// changes when the shape of a pass changes, this file when the wording an operator reads does. +// This file builds partition statements and the messages reported by a maintenance pass. // // It reaches no driver and no catalog. Everything here is a pure function of a Range and an error, // which is what lets criterion 33's wording and M6's statement be asserted container-free. diff --git a/internal/schema/packagesources_test.go b/internal/schema/packagesources_test.go index 995f023..162e8e9 100644 --- a/internal/schema/packagesources_test.go +++ b/internal/schema/packagesources_test.go @@ -5,34 +5,9 @@ import ( goparser "go/parser" gotoken "go/token" "os" - "path/filepath" - "slices" - "strings" "testing" ) -// This file is the one reader the three source-level gates in this package share -- the L1 import -// gate, the budget gate and doc.go's constant reconciliation. A second copy would drift the moment -// one of them gained a case. It cannot reach internal/config's or internal/goartifact's -// equivalents: those are unexported test helpers of packages this one may not import from a test -// either way. - -// packageSourceNames is every Go source of this package, sorted. It fails rather than returning -// nothing, because a sweep over an empty list passes vacuously. -func packageSourceNames(t *testing.T) []string { - t.Helper() - - names, err := filepath.Glob("*.go") - if err != nil { - t.Fatalf("glob this package's sources: %v", err) - } - if len(names) == 0 { - t.Fatal("no Go sources found, so every sweep over them would pass vacuously") - } - slices.Sort(names) - return names -} - // sourceBytes reads one source of this package. func sourceBytes(t *testing.T, name string) []byte { t.Helper() @@ -54,27 +29,3 @@ func parsedSource(t *testing.T, name string, data []byte) *goast.File { } return file } - -// importedPaths is every path one source imports, with the quotes stripped. An alias and a blank -// import are spellings of the same reach, so neither is treated differently here. -func importedPaths(file *goast.File) []string { - paths := make([]string, 0, len(file.Imports)) - for _, imported := range file.Imports { - paths = append(paths, strings.Trim(imported.Path.Value, `"`)) - } - return paths -} - -// withinModule reports whether an import path is a module or a package beneath it. The separator is -// part of the prefix, so a module whose path merely begins with another's is a different module. -// -// It lives here with the other shared readers because four gates ask it -- the driver-reaching -// sweep, the quoting authority, the connection-string scan and the harness scans -- and a second -// copy would drift the moment one of them gained a case. It arrived here when Step 7's harness -// retired dependencylanding_test.go, which declared it. -// -// l1imports_test.go's forbiddenInL1 writes the same two clauses and answers a different question -- -// membership of a fixed deny-list -- so that one stays where it is. -func withinModule(imported, module string) bool { - return imported == module || strings.HasPrefix(imported, module+"/") -} diff --git a/internal/schema/partitionfixtures_test.go b/internal/schema/partitionfixtures_test.go index 2e09239..a5f23e3 100644 --- a/internal/schema/partitionfixtures_test.go +++ b/internal/schema/partitionfixtures_test.go @@ -8,15 +8,6 @@ import ( ) // This file holds the fixtures and assertion helpers the boundary corpus is built from. -// -// Step 3's Expected Output names four test files; the corpus is written across nine, and that is -// this step's one deviation from it -- taken for the reason internal/goartifact declared the same -// deviation in Step 1, that a single file would breach the 200-line budget this package's own gate -// enforces. The corpus is partition_test.go (the required set), partitiondeterminism_test.go -// (AC 24's four evaluations), partitionfloor_test.go (the division and the 2262 limit), -// partitionname_test.go (the identifier), partitionretention_test.go (the cutoff and the horizon), -// partitionproperty_test.go (the generated dimension) and this file; packagesources_test.go is the -// one source reader the three source-level gates share. // utc writes one UTC instant. Every row in this corpus writes its instants through it, so no row // can accidentally carry a local-zone instant and read as if it were absolute. From 7736d5b436fcc7eb4f8f10025bfd40018971198a Mon Sep 17 00:00:00 2001 From: cpoul Date: Fri, 23 Oct 2026 18:29:47 +0300 Subject: [PATCH 4/4] =?UTF-8?q?test:=20simplify=20database=20harnesses=20a?= =?UTF-8?q?nd=20sql=20regression=20suites=20=E2=9C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove container-request reflection, unused fixture bookkeeping, source layout assertions, and golden-corpus self-tests. Retain generated SQL goldens, database isolation, delivery, permissions, and redaction checks. --- .../boundary_edges_integration_test.go | 5 +- internal/delivery/harness_integration_test.go | 63 ------- .../delivery/httpfixture_integration_test.go | 85 +-------- .../credentialmarker_integration_test.go | 27 --- internal/reconcile/diff_test.go | 18 -- .../reconcile/harness_integration_test.go | 76 +------- internal/reconcile/packagesources_test.go | 56 +----- internal/reconcile/targetresolve_test.go | 53 ------ .../reconcile/testmain_integration_test.go | 27 +-- internal/schema/bootstrap_test.go | 7 - internal/schema/doc_test.go | 60 +----- internal/schema/grantsinert_test.go | 63 ------- internal/schema/harness_integration_test.go | 16 -- internal/schema/identifier_test.go | 31 ---- internal/schema/maintainwords_test.go | 6 - internal/schema/migrationindex_test.go | 18 -- internal/schema/objectcontractclosure_test.go | 133 -------------- internal/schema/scanliterals_test.go | 24 --- internal/schema/testmain_integration_test.go | 15 +- .../containerrequest_integration_test.go | 159 ---------------- internal/source/containerrequest_test.go | 173 ------------------ internal/source/generationscan_test.go | 75 -------- internal/source/golden_test.go | 71 +------ internal/source/goldenpairs_test.go | 126 +------------ internal/source/harness_integration_test.go | 32 ---- internal/source/hostileroutes_test.go | 95 ---------- internal/source/injection_integration_test.go | 3 +- internal/source/packagesources_test.go | 68 ------- internal/source/testmain_integration_test.go | 38 +--- 29 files changed, 25 insertions(+), 1598 deletions(-) delete mode 100644 internal/delivery/harness_integration_test.go delete mode 100644 internal/schema/objectcontractclosure_test.go delete mode 100644 internal/schema/scanliterals_test.go delete mode 100644 internal/source/containerrequest_integration_test.go delete mode 100644 internal/source/containerrequest_test.go delete mode 100644 internal/source/hostileroutes_test.go diff --git a/internal/delivery/boundary_edges_integration_test.go b/internal/delivery/boundary_edges_integration_test.go index 46abcde..10e5a1c 100644 --- a/internal/delivery/boundary_edges_integration_test.go +++ b/internal/delivery/boundary_edges_integration_test.go @@ -160,11 +160,8 @@ func (c *headerEchoClient) Do(request *http.Request) (*http.Response, error) { }, nil } -func TestSecretMarkerOracleIsFalsifiableAndLive(t *testing.T) { +func TestDeliveryFailuresRedactSigningSecrets(t *testing.T) { marker := "secret-marker-31" - if noSecretMarker(marker, "safe diagnostic") != nil || noSecretMarker(marker, "planted "+marker) == nil { - t.Fatal("secret oracle is not falsifiable") - } db := newDeliveryDatabase(t) event, terminal := seedDeliveryEvent(t, db, "orders", `{"id":32}`), seedDeliveryEvent(t, db, "orders", `{"id":33}`) src := openDeliverySource(t, db, "secret-oracle", time.Minute) diff --git a/internal/delivery/harness_integration_test.go b/internal/delivery/harness_integration_test.go deleted file mode 100644 index 99fd963..0000000 --- a/internal/delivery/harness_integration_test.go +++ /dev/null @@ -1,63 +0,0 @@ -//go:build integration - -package delivery - -import ( - "fmt" - "os" - "path/filepath" - "sort" - "strings" - "testing" - - "github.com/jackc/pgx/v5/pgxpool" -) - -func applyDeliveryMigrations(t *testing.T, pool *pgxpool.Pool) { - t.Helper() - paths, err := filepath.Glob(filepath.Join("..", "schema", "migrations", "*.sql")) - if err != nil || len(paths) == 0 { - t.Fatalf("read migrations: %v", err) - } - sort.Strings(paths) - for _, path := range paths { - body, err := os.ReadFile(path) - if err != nil { - t.Fatal(err) - } - if _, err := pool.Exec(t.Context(), string(body)); err != nil { - t.Fatalf("apply %s: %v", path, err) - } - } -} - -func TestDeliveryHarnessStartsDisposableDatabase(t *testing.T) { - pool := deliveryPool(t) - var migrated bool - if err := pool.QueryRow(t.Context(), "SELECT to_regclass(current_schema() || '.schema_version') IS NOT NULL").Scan(&migrated); err != nil { - t.Fatal(err) - } - if !migrated { - applyDeliveryMigrations(t, pool) - } - var database string - if err := pool.QueryRow(t.Context(), "SELECT current_database()").Scan(&database); err != nil { - t.Fatal(err) - } - if database != deliveryDatabase { - t.Fatalf("database=%q, want %q", database, deliveryDatabase) - } -} - -func TestDeliveryHarnessUsesPerProcessResourceNames(t *testing.T) { - if !strings.Contains(deliveryDatabase, "delivery_"+itoa(os.Getpid())) { - t.Fatalf("database %q is not process-scoped", deliveryDatabase) - } - if strings.Contains(deliveryDatabase, ":5432") { - t.Fatalf("database name contains a fixed host port: %q", deliveryDatabase) - } -} - -func itoa(value int) string { - return fmt.Sprintf("%d", value) -} diff --git a/internal/delivery/httpfixture_integration_test.go b/internal/delivery/httpfixture_integration_test.go index 4e5a538..029c9d8 100644 --- a/internal/delivery/httpfixture_integration_test.go +++ b/internal/delivery/httpfixture_integration_test.go @@ -9,7 +9,6 @@ import ( "strings" "sync" "testing" - "time" ) type HTTPReply struct { @@ -26,7 +25,6 @@ type HTTPRequest struct { Method string Header http.Header Body []byte - Order int } type HTTPFixture struct { @@ -61,7 +59,7 @@ func (f *HTTPFixture) serveHTTP(response http.ResponseWriter, request *http.Requ if len(f.plan) > 0 { reply, f.plan = f.plan[0], f.plan[1:] } - f.seen = append(f.seen, HTTPRequest{Method: request.Method, Header: request.Header.Clone(), Body: body, Order: len(f.seen)}) + f.seen = append(f.seen, HTTPRequest{Method: request.Method, Header: request.Header.Clone(), Body: body}) f.mu.Unlock() if reply.Hold != nil { <-reply.Hold @@ -96,85 +94,18 @@ func (f *HTTPFixture) serveHTTP(response http.ResponseWriter, request *http.Requ _, _ = response.Write([]byte(reply.Body)) } -func TestHTTPFixtureScriptsResponsesAndCapturesOrder(t *testing.T) { - hold := make(chan struct{}) - fixture := newHTTPFixture(t, HTTPReply{Status: http.StatusServiceUnavailable, Body: "retry", Hold: hold}, HTTPReply{Status: http.StatusOK, Echo: true}) - request, err := http.NewRequest(http.MethodPost, fixture.URL(), strings.NewReader("payload")) - if err != nil { - t.Fatal(err) - } - request.Header.Set("X-Test", "one") - done := make(chan struct{}) - go func() { _, _ = http.DefaultClient.Do(request); close(done) }() - close(hold) - <-done - response, err := http.Post(fixture.URL(), "text/plain", strings.NewReader("again")) - if err != nil { - t.Fatal(err) - } - defer response.Body.Close() - if got := len(fixture.Requests()); got != 2 { - t.Fatalf("captured requests=%d, want two", got) - } -} - -func TestHTTPFixtureControlsReorderRedirectAndTransport(t *testing.T) { - hold := make(chan struct{}) - fixture := newHTTPFixture(t, HTTPReply{Status: http.StatusOK, Hold: hold}, HTTPReply{Status: http.StatusOK}) - firstDone := make(chan struct{}) - go func() { - response, err := http.Post(fixture.URL(), "text/plain", strings.NewReader("first")) - if err == nil { - _ = response.Body.Close() - } - close(firstDone) - }() - for attempt := 0; attempt < 40 && len(fixture.Requests()) < 1; attempt++ { - time.Sleep(5 * time.Millisecond) - } - second, err := http.Post(fixture.URL(), "text/plain", strings.NewReader("second")) - if err != nil { - t.Fatal(err) - } - _ = second.Body.Close() - select { - case <-firstDone: - t.Fatal("held first request completed before the second request") - default: - } - close(hold) - <-firstDone - if requests := fixture.Requests(); len(requests) != 2 || requests[0].Order != 0 || requests[1].Order != 1 { - t.Fatalf("request capture = %#v, want deterministic order 0,1", requests) - } - +func TestRedirectPolicyRefusesFollowingLocation(t *testing.T) { targetCalls := 0 target := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) { targetCalls++ })) defer target.Close() - redirectFixture := newHTTPFixture(t, HTTPReply{Redirect: target.URL}) - redirectClient := &http.Client{Transport: http.DefaultTransport, CheckRedirect: refuseRedirects} - redirectResponse, err := redirectClient.Post(redirectFixture.URL(), "text/plain", strings.NewReader("redirect")) + fixture := newHTTPFixture(t, HTTPReply{Redirect: target.URL}) + client := &http.Client{Transport: http.DefaultTransport, CheckRedirect: refuseRedirects} + response, err := client.Post(fixture.URL(), "text/plain", strings.NewReader("redirect")) if err != nil { t.Fatal(err) } - _ = redirectResponse.Body.Close() - if redirectResponse.StatusCode != http.StatusFound || targetCalls != 0 { - t.Fatalf("redirect status=%d target calls=%d, want 302 and zero", redirectResponse.StatusCode, targetCalls) - } - - failureFixture := newHTTPFixture(t, HTTPReply{TransportError: true}) - if response, err := http.Post(failureFixture.URL(), "text/plain", strings.NewReader("failure")); err == nil || response != nil { - t.Fatalf("transport failure response=%v err=%v, want an error and no response", response, err) - } - - echoFixture := newHTTPFixture(t, HTTPReply{Status: http.StatusAccepted, Echo: true}) - echoResponse, err := http.Post(echoFixture.URL(), "text/plain", strings.NewReader("echo")) - if err != nil { - t.Fatal(err) - } - defer echoResponse.Body.Close() - body, err := io.ReadAll(echoResponse.Body) - if err != nil || string(body) != "echo" || echoResponse.StatusCode != http.StatusAccepted { - t.Fatalf("echo status=%d body=%q err=%v", echoResponse.StatusCode, body, err) + defer response.Body.Close() + if response.StatusCode != http.StatusFound || targetCalls != 0 { + t.Fatalf("redirect status=%d target calls=%d, want 302 and zero", response.StatusCode, targetCalls) } } diff --git a/internal/reconcile/credentialmarker_integration_test.go b/internal/reconcile/credentialmarker_integration_test.go index 21b2acb..731f945 100644 --- a/internal/reconcile/credentialmarker_integration_test.go +++ b/internal/reconcile/credentialmarker_integration_test.go @@ -164,33 +164,6 @@ func assertNoMarkerReaches(t *testing.T, run string, surfaces map[string]string, } } -// TestTheCredentialOracleSeesAMarkerOnEveryLineOfAPlantedValue is what makes every assertion built -// on this oracle falsifiable: without it a search that found nothing is indistinguishable from one -// that could find nothing, and the whole credential suite passes by being blind. Each line's markers -// are planted alone and exactly one leak is required, so this also pins the separator keeping line -// 1's marker out of line 11's. The clean surface is the guard's other side. -func TestTheCredentialOracleSeesAMarkerOnEveryLineOfAPlantedValue(t *testing.T) { - skipIfShort(t) - - marked := credentialMarkedOnEveryLine("control", "a planted value\nspanning two lines\nand a third") - if want := 3 * 2; len(marked.markers) != want { - t.Fatalf( - "a three-line value carries %d markers, want %d: one pair per line", - len(marked.markers), want, - ) - } - for _, marker := range marked.markers { - leaks := markersReaching(map[string]string{"probe": "before " + marker + " after"}, marked.markers) - - if len(leaks) != 1 || !strings.Contains(leaks[0], marker) { - t.Errorf("a surface quoting %s produced %v, want exactly one leak naming it", marker, leaks) - } - } - if leaks := markersReaching(map[string]string{"probe": "nothing planted here"}, marked.markers); len(leaks) != 0 { - t.Errorf("a surface quoting no marker produced %v, so the oracle over-fires", leaks) - } -} - // recordedRun drives one Plan or Apply with a debug logger attached, so the log surface is captured // at the level that renders the most. func recordedRun(t *testing.T, pool *pgxpool.Pool, cfg config.Config, opts Options, apply bool) runOutcome { diff --git a/internal/reconcile/diff_test.go b/internal/reconcile/diff_test.go index 33697c7..8e9c616 100644 --- a/internal/reconcile/diff_test.go +++ b/internal/reconcile/diff_test.go @@ -1,7 +1,6 @@ package reconcile import ( - "strings" "testing" ) @@ -169,20 +168,3 @@ func actionsForPair(actions []Action, pair Pair) []Action { } return matched } - -func TestClassifyIsTheOnlyCatalogAndRegistryConversionSeam(t *testing.T) { - // reuse-the-helper-before-copying-it.md keeps the L1 ownership proof free of adapter readings. - var catalogConversions, registryConversions []string - for _, name := range productionSourceNames(t) { - text := string(sourceBytes(t, name)) - if strings.Contains(text, "CatalogObject{") { - catalogConversions = append(catalogConversions, name) - } - if strings.Contains(text, "RegistryRow{") { - registryConversions = append(registryConversions, name) - } - } - if len(catalogConversions) != 1 || catalogConversions[0] != "classify.go" || len(registryConversions) != 1 || registryConversions[0] != "classify.go" { - t.Fatalf("CatalogObject conversions=%v RegistryRow conversions=%v, want classify.go only", catalogConversions, registryConversions) - } -} diff --git a/internal/reconcile/harness_integration_test.go b/internal/reconcile/harness_integration_test.go index 2140ac4..5e539b6 100644 --- a/internal/reconcile/harness_integration_test.go +++ b/internal/reconcile/harness_integration_test.go @@ -4,15 +4,10 @@ package reconcile import ( "context" - "net/url" - "os" - "path/filepath" - "slices" "strings" "testing" "github.com/cpouldev/pg_noty/internal/config" - "github.com/cpouldev/pg_noty/internal/schema" "github.com/cpouldev/pg_noty/internal/testpostgres" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" @@ -37,7 +32,6 @@ func skipIfShort(t *testing.T) { func harnessConfig(t *testing.T) config.Config { t.Helper() skipIfShort(t) - containerUses.Add(1) dsn, err := sharedContainer.ConnectionString(t.Context(), "sslmode=disable") if err != nil { t.Fatalf("read container connection string: %v", err) @@ -50,7 +44,6 @@ func harnessConfig(t *testing.T) config.Config { func restoreToSnapshot(t *testing.T) { t.Helper() skipIfShort(t) - containerUses.Add(1) if err := testpostgres.RestoreSnapshot(t.Context(), sharedContainer); err != nil { t.Fatalf("restore snapshot: %v", err) } @@ -98,72 +91,5 @@ func countOn(t *testing.T, on reconcileCounter, query string, arguments ...any) return count } -// applySchemaMigrations is the internal/source/harness_integration_test.go:applySchemaMigrations -// twin. The difference is the package under test and nothing else. -func applySchemaMigrations(t *testing.T, pool *pgxpool.Pool) { - t.Helper() - paths, err := filepath.Glob(filepath.Join("..", "schema", "migrations", "*.sql")) - if err != nil || len(paths) == 0 { - t.Fatalf("read internal/schema migration corpus: %v", err) - } - slices.Sort(paths) - for _, path := range paths { - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read migration %s: %v", path, err) - } - mustExecOn(t, pool, string(data)) - } -} - -// asRole is the internal/source/harness_integration_test.go:asRole twin. The difference is the -// package under test and nothing else. -func asRole(t *testing.T, cfg config.Config, role, password string) config.Config { - t.Helper() - parsed, err := url.Parse(cfg.Database.URL) - if err != nil { - t.Fatalf("parse connection string: %v", err) - } - parsed.User = url.UserPassword(role, password) - cfg.Database.URL = parsed.String() - return cfg -} - -// openPoolAs is the internal/source/harness_integration_test.go:openPoolAs twin. The difference is -// the package under test and nothing else. -func openPoolAs(t *testing.T, cfg config.Config, role string) *pgxpool.Pool { - t.Helper() - pool, err := pgxpool.New(t.Context(), cfg.Database.URL) - if err != nil { - t.Fatalf("open pool as %s: %v", role, err) - } - t.Cleanup(pool.Close) - return pool -} - -// createTheLimitedRole is the internal/source/harness_integration_test.go:createTheLimitedRole twin. -// The difference is the package under test and nothing else. -func createTheLimitedRole(t *testing.T, pool *pgxpool.Pool, role, password string) { - t.Helper() - quoted, fault := schema.Quoted(role) - if fault != schema.IdentifierOK { - t.Fatalf("limited role %s is unusable: %s", role, fault) - } - mustExecOn(t, pool, "CREATE ROLE "+quoted+" LOGIN PASSWORD "+harnessLiteral(password)) -} - -// harnessLiteral is a local harness routine for createTheLimitedRole, whose source twin is -// internal/source/harness_integration_test.go:createTheLimitedRole. It cannot reuse source's -// unexported literal authority, internal/source/literal.go:quoteLiteral; harnessPassword has no -// backslashes, so plain PostgreSQL quote escaping is sufficient. +// harnessLiteral quotes values in SQL statements used by these integration tests. func harnessLiteral(value string) string { return "'" + strings.ReplaceAll(value, "'", "''") + "'" } - -func TestExactlyOneContainerServesTheWholePackage(t *testing.T) { - skipIfShort(t) - if got := containersStarted.Load(); got != 1 { - t.Fatalf("containers started = %d, want 1", got) - } - if containerStartup <= 0 { - t.Fatal("container startup was not measured") - } -} diff --git a/internal/reconcile/packagesources_test.go b/internal/reconcile/packagesources_test.go index 03e8513..b4af384 100644 --- a/internal/reconcile/packagesources_test.go +++ b/internal/reconcile/packagesources_test.go @@ -7,32 +7,12 @@ import ( "os" "path/filepath" "slices" - "strconv" "strings" "testing" ) const reconcileDocAnchor = "doc.go" -// This is the deliberately recorded twin of internal/source/packagesources_test.go. Unlike that -// finished package, this reader has no counted production equality: step 24 owns E3. It asserts a -// nonempty, doc.go-anchored population now so every intervening gate includes later source files. -// This follows count-the-population-a-vacuity-guard-guards.md and -// record-a-test-case-you-cannot-yet-implement.md. -func packageSourceNames(t *testing.T) []string { - t.Helper() - - paths, err := filepath.Glob("*.go") - if err != nil { - t.Fatalf("glob internal/reconcile sources: %v", err) - } - names, err := guardedSourceNames(paths, reconcileDocAnchor) - if err != nil { - t.Fatal(err) - } - return names -} - func guardedSourceNames(paths []string, anchor string) ([]string, error) { if len(paths) == 0 { return nil, &sourcePopulationError{message: "reconcile source population is empty"} @@ -44,8 +24,7 @@ func guardedSourceNames(paths []string, anchor string) ([]string, error) { return paths, nil } -// productionSourceNames supplies the future E3 equality. Step 24, not this step, adds its exact -// production-file count; this step asserts only the guarded population from which it will be read. +// productionSourceNames finds the production files used by source-level safety checks. func productionSourceNames(t *testing.T) []string { paths, err := filepath.Glob("*.go") if err != nil { @@ -90,36 +69,3 @@ func parsedSource(t *testing.T, name string, data []byte) *goast.File { } return file } - -func importedPaths(file *goast.File) []string { - paths := make([]string, 0, len(file.Imports)) - for _, imported := range file.Imports { - path, err := strconv.Unquote(imported.Path.Value) - if err != nil { - continue - } - paths = append(paths, path) - } - return paths -} - -func withinModule(imported, module string) bool { - return imported == module || len(imported) > len(module) && imported[:len(module)] == module && imported[len(module)] == '/' -} - -func TestTheReconcilePopulationIsGuarded(t *testing.T) { - names := packageSourceNames(t) - t.Logf("reconcile population reader examined %d source files", len(names)) -} - -func TestTheReconcilePopulationReaderRejectsAnEmptyGlob(t *testing.T) { - if _, err := guardedSourceNames(nil, reconcileDocAnchor); err == nil { - t.Fatal("an empty reconcile source population was accepted") - } -} - -func TestTheReconcilePopulationReaderRejectsAMissingAnchor(t *testing.T) { - if _, err := guardedSourceNames([]string{"other.go"}, reconcileDocAnchor); err == nil { - t.Fatal("a reconcile source population without doc.go was accepted") - } -} diff --git a/internal/reconcile/targetresolve_test.go b/internal/reconcile/targetresolve_test.go index 96781cc..5877511 100644 --- a/internal/reconcile/targetresolve_test.go +++ b/internal/reconcile/targetresolve_test.go @@ -1,7 +1,6 @@ package reconcile import ( - "go/ast" "slices" "strings" "testing" @@ -46,42 +45,6 @@ func TestTargetOutcomesAreClosedAndClassifyEachSignalCell(t *testing.T) { } } -func TestCompileIsTheOnlyProductionSourceGenerateCaller(t *testing.T) { - // close-a-substitute-over-the-thing-it-substitutes-for.md requires the guarded population reader. - // A repository-wide caller count is unsatisfiable: the required test corpora call Generate too, - // and forcing it to one would invite deleting the corpus that supplies the safety evidence. - callers := make([]string, 0) - for _, name := range productionSourceNames(t) { - if callsSourceGenerate(parsedSource(t, name, sourceBytes(t, name))) { - callers = append(callers, name) - } - } - t.Logf("source.Generate caller scan examined %d production files: %v", len(productionSourceNames(t)), callers) - if !slices.Equal(callers, []string{"compile.go"}) { - t.Fatalf("source.Generate callers = %v, want [compile.go]", callers) - } - if bytes := string(sourceBytes(t, "compile.go")); strings.Contains(bytes, "Quoted") || strings.Contains( - bytes, - "Qualified", - ) { - t.Fatal("compile.go re-quotes resolved catalog metadata") - } -} - -func TestTargetResolverUsesOnlyTheSharedCatalogResolution(t *testing.T) { - bytes := string(sourceBytes(t, "targetresolve.go")) - for _, required := range []string{"catalog.ResolveTargetOID", "catalog.ResolveTarget"} { - if !strings.Contains(bytes, required) { - t.Fatalf("targetresolve.go does not call %s", required) - } - } - for _, forbidden := range []string{"SELECT ", "to_regclass", "pg_catalog"} { - if strings.Contains(bytes, forbidden) { - t.Fatalf("targetresolve.go declares catalog resolution text %q", forbidden) - } - } -} - func TestCompileNamesAGenerationRefusalForItsListener(t *testing.T) { listener := config.Listener{ Name: "orders", Trigger: config.TriggerSpec{ @@ -106,19 +69,3 @@ func uniqueTargetOutcomes() map[targetOutcome]struct{} { } return unique } - -func callsSourceGenerate(file *ast.File) bool { - found := false - ast.Inspect( - file, func(node ast.Node) bool { - selector, ok := node.(*ast.SelectorExpr) - if !ok || selector.Sel.Name != "Generate" { - return true - } - name, ok := selector.X.(*ast.Ident) - found = found || ok && name.Name == "source" - return true - }, - ) - return found -} diff --git a/internal/reconcile/testmain_integration_test.go b/internal/reconcile/testmain_integration_test.go index 975e9c9..cffd644 100644 --- a/internal/reconcile/testmain_integration_test.go +++ b/internal/reconcile/testmain_integration_test.go @@ -7,10 +7,8 @@ import ( "flag" "fmt" "os" - "reflect" "sync/atomic" "testing" - "time" _ "github.com/jackc/pgx/v5/stdlib" "github.com/testcontainers/testcontainers-go/modules/postgres" @@ -26,24 +24,10 @@ const ( ) var ( - sharedContainer *postgres.PostgresContainer - containersStarted atomic.Int64 - containerUses atomic.Int64 - containerStartup time.Duration - harnessContainerRequest any + sharedContainer *postgres.PostgresContainer + containersStarted atomic.Int64 ) -// recordingTheRequest is the internal/source/testmain_integration_test.go:recordingTheRequest twin. -// The difference is the package under test and nothing else. It leaves the library request untyped: -// a direct dependency type would promote its module and fail internal/config's release-hygiene gate. -func recordingTheRequest[Option any](option Option) Option { - recorded := reflect.MakeFunc(reflect.TypeOf(option), func(arguments []reflect.Value) []reflect.Value { - harnessContainerRequest = arguments[0].Interface() - return reflect.ValueOf(option).Call(arguments) - }) - return recorded.Interface().(Option) -} - func TestMain(m *testing.M) { os.Exit(runReconcileHarness(m)) } func runReconcileHarness(m *testing.M) int { @@ -75,13 +59,10 @@ func runReconcileHarness(m *testing.M) int { func startReconcileContainer(ctx context.Context) (*postgres.PostgresContainer, error) { containersStarted.Add(1) - started := time.Now() - container, err := postgres.Run(ctx, harnessImage, + return postgres.Run(ctx, harnessImage, postgres.WithDatabase(harnessDatabase), postgres.WithUsername(harnessUser), postgres.WithPassword(harnessPassword), postgres.WithSQLDriver(harnessSQLDriver), - recordingTheRequest(postgres.BasicWaitStrategies())) - containerStartup = time.Since(started) - return container, err + postgres.BasicWaitStrategies()) } // reportToHarnessStderr is the internal/source/testmain_integration_test.go:reportToHarnessStderr diff --git a/internal/schema/bootstrap_test.go b/internal/schema/bootstrap_test.go index 912608a..3344ad9 100644 --- a/internal/schema/bootstrap_test.go +++ b/internal/schema/bootstrap_test.go @@ -19,13 +19,6 @@ import ( // package quotes every configured name (skill Pattern 7) -- so this client-side check is the only // thing closing the class rather than a second line of defence. -// The two production sources this step ships, named once so that the scans in bootstrapscan_test.go -// and the reconciliations below read them rather than repeating the strings. -const ( - theBootstrap = "bootstrap.go" - theBootstrapSchema = "bootstrapschema.go" -) - // theReservedPrefix is the prefix R4 and PostgreSQL both name, written here as the literal rather // than read from identifier.go: an expectation derived from the code under test is satisfied by // whatever that code happens to say. diff --git a/internal/schema/doc_test.go b/internal/schema/doc_test.go index 61b6296..f0ddc6e 100644 --- a/internal/schema/doc_test.go +++ b/internal/schema/doc_test.go @@ -8,16 +8,6 @@ import ( "testing" ) -// TestTheObjectSetSizeIsPinned keeps the inventory closed. Step 12's criterion-3 assertion ranges -// over this set, so a seventh table joining the package without joining Objects would make that -// inventory silently incomplete (.claude/rules/assert-a-set-wide-invariant-over-the-set.md). -func TestTheObjectSetSizeIsPinned(t *testing.T) { - if len(Objects) != 11 { - t.Fatalf("Objects holds %d entries, want the six tables, the DEFAULT partition and the four "+ - "indexes; update this count with the set", len(Objects)) - } -} - func TestEveryObjectNameIsUsableAsAnIdentifier(t *testing.T) { seen := map[string]int{} for i, object := range Objects { @@ -71,43 +61,9 @@ func TestEveryObjectDeclaresAKindAndTheMigrationThatCreatesIt(t *testing.T) { } } -// TestEveryExportedObjectNameConstantJoinedTheSet reconciles in both directions, because each -// direction hides a different mistake: a constant nothing creates, and an object phases 3 to 6 -// cannot name (.claude/rules/falsify-the-assertion-not-a-copy-of-it.md). -func TestEveryExportedObjectNameConstantJoinedTheSet(t *testing.T) { - declared := exportedUntypedStringConstants(t) - if len(declared) == 0 { - t.Fatal("doc.go declares no untyped exported string constant, so this reconciliation " + - "would pass in both directions vacuously") - } - - named := map[string]bool{} - for _, object := range Objects { - named[object.Name] = true - } - for constant, value := range declared { - if !named[value] { - t.Errorf("doc.go declares %s = %q and Objects holds no object of that name", - constant, value) - } - } - - valued := map[string]bool{} - for _, value := range declared { - valued[value] = true - } - for _, object := range Objects { - if !valued[object.Name] { - t.Errorf("Objects holds %q and doc.go declares no exported constant for it, so a "+ - "caller in phase 3 to 6 would have to write the name out", object.Name) - } - } -} - // exportedUntypedStringConstants reads doc.go's object-name constants. The filter is the declared // type: an object name is an untyped string constant, and the kinds carry ObjectKind, so the two -// groups cannot be confused for one another. TestTheKindConstantsAreTypedSoTheFilterHolds asserts -// that premise rather than assuming it. +// groups cannot be confused for one another. func exportedUntypedStringConstants(t *testing.T) map[string]string { t.Helper() @@ -126,20 +82,6 @@ func exportedUntypedStringConstants(t *testing.T) map[string]string { return found } -func TestTheKindConstantsAreTypedSoTheFilterHolds(t *testing.T) { - typed := 0 - for _, spec := range constantSpecsOf(t) { - if identified, isIdent := spec.Type.(*goast.Ident); isIdent && identified.Name == "ObjectKind" { - typed += len(spec.Names) - } - } - - if typed != 3 { - t.Errorf("doc.go declares %d ObjectKind constants, want the three kinds; an untyped one "+ - "would be read as an object name by the reconciliation above", typed) - } -} - // constantSpecsOf is every constant specification doc.go declares. func constantSpecsOf(t *testing.T) []*goast.ValueSpec { t.Helper() diff --git a/internal/schema/grantsinert_test.go b/internal/schema/grantsinert_test.go index c0c13a7..c1f4955 100644 --- a/internal/schema/grantsinert_test.go +++ b/internal/schema/grantsinert_test.go @@ -95,66 +95,3 @@ func statementShape(statement string) (named []string, outside string, closed bo } return named, plain.String(), true } - -// TestTheStatementOracleTellsAnInertStatementFromAnEscapedOne gives the oracle its own -// falsifiability: without these rows an oracle that answered "inert" for everything would make the -// rows above pass. Each expectation is counted off the statement's own bytes rather than recorded -// from a run. -func TestTheStatementOracleTellsAnInertStatementFromAnEscapedOne(t *testing.T) { - for _, tc := range []struct { - name, statement string - wantNamed []string - wantOutside string - wantClosed bool - }{ - { - name: "a separator carried inside the identifier", - statement: `GRANT USAGE ON SCHEMA "noty;drop" TO "pg_noty";`, - wantNamed: []string{"noty;drop", "pg_noty"}, - wantOutside: "GRANT USAGE ON SCHEMA TO ;", - wantClosed: true, - }, - { - name: "a doubled quote read back as one quote", - statement: `ALTER SCHEMA "no""ty" OWNER TO "pg_noty";`, - wantNamed: []string{`no"ty`, "pg_noty"}, - wantOutside: "ALTER SCHEMA OWNER TO ;", - wantClosed: true, - }, - { - // What a quoter that wrapped without doubling emits: two separators outside. - name: "an identifier closed early, leaving a second statement", - statement: `ALTER SCHEMA "no"; DROP TABLE orders OWNER TO "pg_noty";`, - wantNamed: []string{"no", "pg_noty"}, - wantOutside: "ALTER SCHEMA ; DROP TABLE orders OWNER TO ;", - wantClosed: true, - }, - { - name: "a comment sequence outside the identifiers", - statement: `ALTER SCHEMA "noty" -- x OWNER TO "pg_noty";`, - wantNamed: []string{"noty", "pg_noty"}, - wantOutside: "ALTER SCHEMA -- x OWNER TO ;", - wantClosed: true, - }, - { - name: "an identifier never closed", - statement: `ALTER SCHEMA "noty OWNER TO pg_noty;`, - wantClosed: false, - }, - } { - t.Run(tc.name, func(t *testing.T) { - named, outside, closed := statementShape(tc.statement) - - if closed != tc.wantClosed { - t.Fatalf("statementShape read closed = %t, want %t", closed, tc.wantClosed) - } - if !closed { - return - } - if strings.Join(named, "\x00") != strings.Join(tc.wantNamed, "\x00") || outside != tc.wantOutside { - t.Errorf("statementShape read %q outside %q, want %q outside %q", - named, outside, tc.wantNamed, tc.wantOutside) - } - }) - } -} diff --git a/internal/schema/harness_integration_test.go b/internal/schema/harness_integration_test.go index d9a5e42..eea2fae 100644 --- a/internal/schema/harness_integration_test.go +++ b/internal/schema/harness_integration_test.go @@ -111,22 +111,6 @@ func TestRestoreLeavesTheNextTestNoneOfThePreviousTestsRows(t *testing.T) { }) } -// TestRestoringIsCheaperThanStartingAnotherContainer is SC-2's third bullet, asserted as the -// comparison the design rests on rather than against a wall-clock constant that would be flaky on -// one machine and meaningless on another: restore is called between cases precisely because it -// costs less than the container it replaces. -func TestRestoringIsCheaperThanStartingAnotherContainer(t *testing.T) { - skipIfShort(t) - - restoring := restoreToSnapshot(t) - - t.Logf("restore took %s, and starting the container took %s", restoring, containerStartup) - if restoring >= containerStartup { - t.Errorf("a restore takes %s and a container takes %s, so restoring between cases buys "+ - "nothing and the harness should start one per test instead", restoring, containerStartup) - } -} - // TestSnapshotAndRestoreTakeTheNativeDriverPathRatherThanDockerExec is SC-3 against the running // container. modules/postgres opens its snapshot connection with sql.Open(harnessSQLDriver, ...) // followed by DB.Conn, and those two failing is the *only* route to the `docker exec psql` diff --git a/internal/schema/identifier_test.go b/internal/schema/identifier_test.go index c0f522c..14adad3 100644 --- a/internal/schema/identifier_test.go +++ b/internal/schema/identifier_test.go @@ -123,34 +123,3 @@ func readDelimitedPart(text string) (part, tail string, delimited bool) { } return "", "", false } - -// TestTheOracleRefusesARenderingThatEscapedItsQuotes gives the oracle above its own falsifiability. -// Without it, an oracle that answered "inert" for everything would make every row of the two tests -// above pass. -func TestTheOracleRefusesARenderingThatEscapedItsQuotes(t *testing.T) { - for _, tc := range []struct { - name, rendered string - wantParts []string - }{ - {name: "one plain part", rendered: `"noty"`, wantParts: []string{"noty"}}, - {name: "two parts", rendered: `"noty"."events"`, wantParts: []string{"noty", "events"}}, - {name: "a doubled quote inside", rendered: `"no""ty"`, wantParts: []string{`no"ty`}}, - {name: "a separator inside", rendered: `"noty;drop"`, wantParts: []string{"noty;drop"}}, - // The failures the oracle exists to catch: each is what a broken quoter emits. - {name: "an unquoted name", rendered: "noty"}, - {name: "a lone quote closing early, leaving a second statement", rendered: `"noty";DROP TABLE x`}, - {name: "a quote never closed", rendered: `"noty`}, - {name: "a Go-style backslash escape rather than a doubled quote", rendered: `"no\"ty"`}, - {name: "a trailing dot with no part after it", rendered: `"noty".`}, - } { - t.Run(tc.name, func(t *testing.T) { - parts, whole := unquotedIdentifier(tc.rendered) - if whole != (tc.wantParts != nil) { - t.Fatalf("unquotedIdentifier(%s) read %q, whole = %t", tc.rendered, parts, whole) - } - if whole && strings.Join(parts, "\x00") != strings.Join(tc.wantParts, "\x00") { - t.Errorf("unquotedIdentifier(%s) = %q, want %q", tc.rendered, parts, tc.wantParts) - } - }) - } -} diff --git a/internal/schema/maintainwords_test.go b/internal/schema/maintainwords_test.go index 3523aef..be2638c 100644 --- a/internal/schema/maintainwords_test.go +++ b/internal/schema/maintainwords_test.go @@ -23,12 +23,6 @@ import ( // maintaindefault_ and maintaingauge_ (AC 30's three halves), maintaincontention_ (AC 33 and AC 40) // and maintainconcurrency_ (AC 23's precursor and M6). -// theMaintenancePass is this step's production file, named as a constant so the gates other steps -// own join it by name rather than by literal -- the shape Step 10's runner_test.go declared for -// runner.go. It is read by errorelisionscan_test.go's driver-reaching set and by -// catalog_test.go's partition-deciding set. -const theMaintenancePass = "maintain.go" - // theRenderedRange is one range with bounds no formatter can accidentally agree with: a fractional // second, and a day that is not the epoch's. var theRenderedRange = Range{ diff --git a/internal/schema/migrationindex_test.go b/internal/schema/migrationindex_test.go index 256d99f..909018c 100644 --- a/internal/schema/migrationindex_test.go +++ b/internal/schema/migrationindex_test.go @@ -71,24 +71,6 @@ func TestEveryIndexCarriesAComment(t *testing.T) { } } -// TestTheClaimIndexCommentRecordsTheCorrectedReasoning pins the correction rather than the -// Requirements text it replaces. The original comment claimed the second column "makes the scan -// index-only"; measured, the claim query takes FOR UPDATE SKIP LOCKED, row locking needs the heap -// tuple, and the plan is a row-locking node over an index scan. What the second column actually -// buys is that the claim ordering is satisfied from the index, so no sort node appears -- and a -// comment repeating the refuted claim would send Step 12 looking for a plan that cannot occur. -func TestTheClaimIndexCommentRecordsTheCorrectedReasoning(t *testing.T) { - comments, _ := declaredCommentsIn(migrationSQL(t, 2)) - explained := comments["INDEX "+IndexQueueClaim] - - for _, required := range []string{"covering", "row locking", "sort"} { - if !strings.Contains(explained, required) { - t.Errorf("the claim index comment does not record %q; it reads: %q", - required, explained) - } - } -} - // TestTheEventLogCarriesNoIndexOfItsOwn is the point of the split storage design, asserted where // the DDL declares it: the claim path never touches the partitioned table, so the event log needs // no queue index at all. Criterion 10 asserts the same closed inventory against a real catalog. diff --git a/internal/schema/objectcontractclosure_test.go b/internal/schema/objectcontractclosure_test.go deleted file mode 100644 index 3aa91b5..0000000 --- a/internal/schema/objectcontractclosure_test.go +++ /dev/null @@ -1,133 +0,0 @@ -package schema - -import ( - "fmt" - "maps" - "slices" - "strings" - "testing" -) - -// The pins that keep the object contract closed, and the synthetic seventh table that proves they -// can bite. A pin nothing ever fails is a pin that may already have stopped covering the set it -// names, so each one here is driven with an input built to break it. - -// theSeventhTable is a table the contract does not list. It stands in for the growth this step's -// inventories have to notice: a table added to the schema without being added to the contract. -const theSeventhTable = "audit_log" - -// widenedContract is the shipped contract plus one column of a table nothing pins, which is the -// exact shape a seventh table arrives in. -func widenedContract() []contractColumn { - return append(slices.Clone(theObjectContract), - contractColumn{table: theSeventhTable, name: "at", sqlType: "timestamptz", notNull: true}) -} - -// columnCountIssues reports how one column contract diverges from the per-table sizes pinned for -// it, in both directions: a table carrying columns that nothing pins, and a pin whose count the -// contract no longer matches. The shipped assertion and the seventh-table case both run through it, -// so the negative case drives the assertion's own body rather than a second expression of the same -// idea. -func columnCountIssues(contract []contractColumn, pinned map[string]int) []string { - counted := map[string]int{} - for _, column := range contract { - counted[column.table]++ - } - - var issues []string - for _, table := range slices.Sorted(maps.Keys(counted)) { - want, isPinned := pinned[table] - switch { - case !isPinned: - issues = append(issues, fmt.Sprintf("%s carries %d columns and no pinned count, so its "+ - "inventory can shrink unnoticed", table, counted[table])) - case counted[table] != want: - issues = append(issues, fmt.Sprintf("%s carries %d columns and %d are pinned", - table, counted[table], want)) - } - } - for _, table := range slices.Sorted(maps.Keys(pinned)) { - if _, carries := counted[table]; !carries { - issues = append(issues, table+" has a pinned column count and the contract lists no "+ - "column for it") - } - } - return issues -} - -func TestEveryContractTableCarriesExactlyItsPinnedNumberOfColumns(t *testing.T) { - for _, issue := range columnCountIssues(theObjectContract, theContractColumnCounts) { - t.Error(issue) - } -} - -// TestASeventhTableFailsTheTableSetAndTheColumnCountPins is the negative case criterion 3 asks for. -// Both pins are driven, because they fail for different reasons and only one of them counts -// tables: a set derived from the contract grows silently, and a per-table count has no entry at all -// for the newcomer. -func TestASeventhTableFailsTheTableSetAndTheColumnCountPins(t *testing.T) { - widened := widenedContract() - - if got := len(contractTablesOf(widened)); got != len(theContractTables)+1 { - t.Errorf("a seventh table left the derived table set at %d entries, want %d; the set the "+ - "catalog inventory ranges over would not have grown with the schema", - got, len(theContractTables)+1) - } - - issues := columnCountIssues(widened, theContractColumnCounts) - if len(issues) != 1 || !strings.Contains(issues[0], theSeventhTable) { - t.Errorf("a seventh table produced %v, want exactly one issue naming %s; a pin that cannot "+ - "fail here is one that has stopped covering the contract", issues, theSeventhTable) - } -} - -// TestAnEighthColumnFailsItsTablesOwnPin is the same closure one level down. The table set is -// unchanged by an eighth column, so only the per-table count can report it -- which is why the -// counts are pinned per table rather than as one total. -func TestAnEighthColumnFailsItsTablesOwnPin(t *testing.T) { - widened := append(slices.Clone(theObjectContract), - contractColumn{table: TableEvents, name: "region", sqlType: "text", notNull: true}) - - issues := columnCountIssues(widened, theContractColumnCounts) - want := fmt.Sprintf("%s carries %d columns and %d are pinned", - TableEvents, theContractColumnCounts[TableEvents]+1, theContractColumnCounts[TableEvents]) - if !slices.Contains(issues, want) { - t.Errorf("an eighth column on %s produced %v, want an issue reading %q", - TableEvents, issues, want) - } -} - -// TestTheStatusVocabularyRunsInBothDirections is criterion 4's own closure, asserted before a container -// is involved: an accept-only set would satisfy every row of the tagged assertion that ranges over it, -// whatever that assertion did. -func TestTheStatusVocabularyRunsInBothDirections(t *testing.T) { - accepted := 0 - for _, status := range theStatusVocabulary { - if status.accepted { - accepted++ - } - if status.why == "" { - t.Errorf("%q records no reason for its verdict", status.value) - } - } - - if rejected := len(theStatusVocabulary) - accepted; accepted != 3 || rejected != 3 { - t.Errorf("the vocabulary accepts %d values and rejects %d, want three of each; the three "+ - "rejected are the decisive ones, since a CHECK still admitting delivered and failed is "+ - "indistinguishable from a correct one under accept-only testing", accepted, rejected) - } -} - -// TestADroppedPinIsReportedRatherThanSilentlyHonoured is the other direction of the same helper: a -// contract table whose pin was removed reads as pinned to nothing, and the size assertion in -// objectcontract_test.go would then be repaired by adding an entry for a table that does not exist. -func TestADroppedPinIsReportedRatherThanSilentlyHonoured(t *testing.T) { - shortened := maps.Clone(theContractColumnCounts) - delete(shortened, TableDeliveries) - - issues := columnCountIssues(theObjectContract, shortened) - if len(issues) != 1 || !strings.Contains(issues[0], TableDeliveries) { - t.Errorf("dropping %s's pin produced %v, want exactly one issue naming it", - TableDeliveries, issues) - } -} diff --git a/internal/schema/scanliterals_test.go b/internal/schema/scanliterals_test.go deleted file mode 100644 index 7c477ab..0000000 --- a/internal/schema/scanliterals_test.go +++ /dev/null @@ -1,24 +0,0 @@ -package schema - -// theDrain is the one file that moves rows out of the DEFAULT partition. The single-authority scans -// hold it, and the other authority names, to account. -const theDrain = "repair.go" - -// The single-authority file names the surviving trust-boundary scans hold to account: one file may -// read the system catalogs, one may take the advisory lock, one may bound a statement's execution. -// The rest name the driver-reaching sources errorelisionscan sweeps, so no driver error escapes -// this package unelided. -const ( - theObservationAuthority = "catalog.go" - theLockAuthority = "advisorylock.go" - theBoundedExecutionAuthority = "ddl.go" - theRetentionPass = "retention.go" - theRunner = "runner.go" - theRunnerLedger = "runnerledger.go" -) - -// exactL1Files is this package's L1 set: the files holding the arithmetic and the object contract, -// reaching no driver, no cancellation and no I/O. identifierscan holds the L3 files against it. -var exactL1Files = []string{ - "doc.go", "horizon.go", "objectname.go", "options.go", "partition.go", "plan.go", "stats.go", -} diff --git a/internal/schema/testmain_integration_test.go b/internal/schema/testmain_integration_test.go index 2c43e43..7577ece 100644 --- a/internal/schema/testmain_integration_test.go +++ b/internal/schema/testmain_integration_test.go @@ -9,7 +9,6 @@ import ( "os" "sync/atomic" "testing" - "time" "github.com/cpouldev/pg_noty/internal/config" "github.com/cpouldev/pg_noty/internal/testpostgres" @@ -45,10 +44,6 @@ var ( containersStarted atomic.Int64 // containerUses counts the tests that reached the container, which harnessVerdict reads. containerUses atomic.Int64 - // containerStartup is what a container costs, measured rather than assumed. It is what - // TestRestoringIsCheaperThanStartingAnotherContainer compares a restore against, so that claim - // rests on two measurements from one machine rather than on a magic constant. - containerStartup time.Duration ) func TestMain(m *testing.M) { @@ -85,7 +80,6 @@ func runAgainstOneContainer(m *testing.M) int { // so that a start which then fails is still counted as one. func startSharedContainer(ctx context.Context) (*postgres.PostgresContainer, error) { containersStarted.Add(1) - began := time.Now() container, err := postgres.Run( ctx, harnessImage, @@ -97,7 +91,6 @@ func startSharedContainer(ctx context.Context) (*postgres.PostgresContainer, err postgres.WithSQLDriver(harnessSQLDriver), postgres.BasicWaitStrategies(), ) - containerStartup = time.Since(began) return container, err } @@ -173,19 +166,17 @@ func harnessConfig(t *testing.T) config.Config { } } -// restoreToSnapshot takes the database back to the state TestMain snapshotted, and answers with -// what that cost. Every pool open before it is dead after it, because the mechanism drops and +// restoreToSnapshot takes the database back to the state TestMain snapshotted. +// Every pool open before it is dead after it, because the mechanism drops and // recreates the database rather than truncating inside it. -func restoreToSnapshot(t *testing.T) time.Duration { +func restoreToSnapshot(t *testing.T) { t.Helper() skipIfShort(t) containerUses.Add(1) - began := time.Now() if err := testpostgres.RestoreSnapshot(t.Context(), sharedContainer); err != nil { t.Fatalf("restore %s to its snapshot: %v", harnessDatabase, err) } - return time.Since(began) } // freshDatabase is the shape the eight consuming steps call: an empty database, and a pool onto it diff --git a/internal/source/containerrequest_integration_test.go b/internal/source/containerrequest_integration_test.go deleted file mode 100644 index 2656b8f..0000000 --- a/internal/source/containerrequest_integration_test.go +++ /dev/null @@ -1,159 +0,0 @@ -//go:build integration - -package source - -import ( - "reflect" - "strings" - "testing" -) - -const ( - // theHarnessContainerPort is the container-side port postgres.Run exposes. Never a host port. - theHarnessContainerPort = "5432/tcp" - // aFixedHostPort and aFixedContainerName are what the reader's control plants in a synthetic - // request. Neither is written anywhere the harness reads. - aFixedHostPort = "5432" - aFixedContainerName = "pgnoty-source-harness" -) - -// TestTheHarnessContainerRequestFixesNoHostPortAndNoContainerName is SC-4's authority. It reads the -// container request testcontainers-go was actually handed by the sole postgres.Run call -- -// recorded live by recordingTheRequest in testmain_integration_test.go -- rather than the source -// text that built it, so a name or a port reaching the request through a const, through a -// ContainerRequest literal, through testcontainers.CustomizeRequest or through a -// HostConfigModifier is answered by the same assertion as the spelling anyone thought of. -// -// The reason the criterion exists is a collision between processes, not a matter of style. Slot S7 -// runs three of these container-backed harnesses concurrently and slot S8 runs two. Docker refuses -// to create a second container under a name that is already taken, and refuses to bind a host port -// another process holds, so either would turn concurrent steps into a failure that reads as a -// flaky daemon rather than as a harness that asked for something it cannot have. -func TestTheHarnessContainerRequestFixesNoHostPortAndNoContainerName(t *testing.T) { - skipIfShort(t) - facts := readContainerRequest(theRecordedHarnessRequest(t)) - - // The request read has to be the one that started the container. A value whose every field - // came back zero fixes nothing by definition, so the assertion below would pass over an empty - // recording, over a recording taken before postgres.Run's own customizers ran, and over a - // reader that stopped finding any field at all - // (.claude/rules/count-the-population-a-vacuity-guard-guards.md). - switch { - case facts.image != harnessImage: - t.Fatalf("the recorded request carries image %q, want the harness's %q", facts.image, harnessImage) - case len(facts.exposedPorts) == 0: - t.Fatal("the recorded request exposes no port, so it is not the request postgres.Run built") - case !facts.waits: - t.Fatal("the recorded request carries no wait strategy, so it was recorded before the " + - "harness's own customizers ran") - } - - if fixed := fixedContainerSettings(facts); len(fixed) != 0 { - t.Fatalf("the harness container request fixes %v; three of these harnesses run concurrently "+ - "in slot S7 and two in S8, and docker cannot give any of them twice", fixed) - } -} - -// TestTheContainerRequestReaderReadsAFixedNameAndAFixedHostPortBackOut gives the reader its own -// falsifiability, over the type it actually reads. The predicate's controls in -// containerrequestcontrols_test.go run on hand-built facts and would all pass if -// readContainerRequest returned an empty value for every request it was handed, which is precisely -// the failure that would make the authority test above green while the harness fixed both -// (.claude/rules/falsify-the-assertion-not-a-copy-of-it.md). -// -// The synthetic request is built from the recorded request's own type, so it is -// testcontainers-go's struct rather than a local imitation of it, and the type is still never named -// here. -func TestTheContainerRequestReaderReadsAFixedNameAndAFixedHostPortBackOut(t *testing.T) { - skipIfShort(t) - facts := readContainerRequest(aRequestFixing(t, aFixedContainerName, aFixedHostPort)) - - if len(facts.unreadable) != 0 { - t.Fatalf("the reader could not read %v out of testcontainers-go's own request type", facts.unreadable) - } - if facts.name != aFixedContainerName { - t.Errorf("the reader read the container name %q, want the planted %q", facts.name, aFixedContainerName) - } - if len(facts.hostPortBindings) != 1 || !strings.Contains(facts.hostPortBindings[0], aFixedHostPort) { - t.Fatalf("the reader read the host port bindings %v, want one naming the planted %q", - facts.hostPortBindings, aFixedHostPort) - } - // Both halves of the binding have to be named. The key of PortBindings is a struct in this moby - // version: reflect.Value.String answers a "" placeholder for one, and a key - // aPortKey failed to parse renders as "invalid port". Either would send whoever reads the - // diagnostic looking for a binding no port names, so the container side is asserted too. - if !strings.Contains(facts.hostPortBindings[0], theHarnessContainerPort) { - t.Errorf("the reader rendered the binding as %q, which names no container port; want the "+ - "planted %q", facts.hostPortBindings[0], theHarnessContainerPort) - } - if fixed := fixedContainerSettings(facts); len(fixed) != 2 { - t.Fatalf("fixedContainerSettings = %v, want one clause for the planted name and one for the "+ - "planted host port", fixed) - } -} - -// theRecordedHarnessRequest is the request the harness handed testcontainers-go, refused rather -// than defaulted when nothing was recorded: an absent recording must not read as a request that -// fixes nothing. -func theRecordedHarnessRequest(t *testing.T) any { - t.Helper() - if harnessContainerRequest == nil { - t.Fatal("the harness recorded no container request, so SC-4 is asserted against nothing; " + - "recordingTheRequest is no longer wrapping an option postgres.Run applies") - } - return harnessContainerRequest -} - -// aRequestFixing is a container request of the library's own type that fixes both things SC-4 -// forbids -- a container name, and a host port bound through a HostConfigModifier, which is the -// route the source-text heuristic cannot see at all. -func aRequestFixing(t *testing.T, name, hostPort string) any { - t.Helper() - held := reflect.New(reflect.TypeOf(theRecordedHarnessRequest(t)).Elem()).Elem() - settableField(t, held, "Name").SetString(name) - - modifier := settableField(t, held, "HostConfigModifier") - modifier.Set(reflect.MakeFunc(modifier.Type(), func(arguments []reflect.Value) []reflect.Value { - bindOneHostPort(arguments[0].Elem().FieldByName("PortBindings"), hostPort) - return nil - })) - return held.Addr().Interface() -} - -// settableField refuses a field this control can no longer plant into, so a renamed field is a -// sentence rather than a panic from inside reflect. -func settableField(t *testing.T, held reflect.Value, name string) reflect.Value { - t.Helper() - field := held.FieldByName(name) - if !field.IsValid() || !field.CanSet() { - t.Fatalf("the request type has no settable %s, so this control cannot plant one into it", name) - } - return field -} - -// bindOneHostPort writes `{theHarnessContainerPort: [{HostPort: hostPort}]}` into a host config's -// PortBindings, building the map, the slice and the binding from the field's own types. -func bindOneHostPort(bindings reflect.Value, hostPort string) { - binding := reflect.New(bindings.Type().Elem().Elem()).Elem() - binding.FieldByName("HostPort").SetString(hostPort) - - written := reflect.MakeMap(bindings.Type()) - written.SetMapIndex(aPortKey(bindings.Type().Key(), theHarnessContainerPort), - reflect.Append(reflect.MakeSlice(bindings.Type().Elem(), 0, 1), binding)) - bindings.Set(written) -} - -// aPortKey builds one PortBindings key of the map's own key type. The vendored moby API spells a -// port as a struct whose fields are unexported and whose only constructor parses text, so the key -// cannot be converted from a string and is unmarshalled instead; an older spelling of the same -// field is a named string type, which converts. -func aPortKey(keyType reflect.Type, port string) reflect.Value { - if keyType.Kind() == reflect.String { - return reflect.ValueOf(port).Convert(keyType) - } - key := reflect.New(keyType) - if unmarshal := key.MethodByName("UnmarshalText"); unmarshal.IsValid() { - unmarshal.Call([]reflect.Value{reflect.ValueOf([]byte(port))}) - } - return key.Elem() -} diff --git a/internal/source/containerrequest_test.go b/internal/source/containerrequest_test.go deleted file mode 100644 index 9233ebf..0000000 --- a/internal/source/containerrequest_test.go +++ /dev/null @@ -1,173 +0,0 @@ -package source - -import ( - "fmt" - "reflect" - "slices" - "strconv" - "strings" -) - -// This file is SC-4's authority: the integration harness must bind no fixed host port and no fixed -// container name, and the question is settled here by reading the request testcontainers-go was -// actually handed rather than the source text that built it. The reason it matters is a collision -// between processes rather than a matter of style -- slot S7 runs three of these container-backed -// harnesses concurrently and S8 runs two, docker refuses a second container under a name already -// taken, and a second bind of a held host port fails outright. -// -// containersettingscan_test.go holds the cheap second line, whose enumeration is its own rather -// than the library's; the assertions that drive what is here are -// TestTheHarnessContainerRequestFixesNoHostPortAndNoContainerName and -// TestTheContainerRequestReaderReadsAFixedNameAndAFixedHostPortBackOut. - -// containerRequestFacts is the part of a testcontainers container request SC-4 ranges over, lifted -// out of the live request so the predicate below is ordinary Go and its controls can run in the -// untagged tier. image and waits carry no policy: they are what the authority test reads to prove -// the value it was handed is the request that started the container rather than a zero one. -// -// unreadable names every field the reader could not find or found with another shape. A request -// whose fields were renamed has to fail loudly rather than answer "nothing is fixed" -// (.claude/rules/scan-result-sentinels.md). -type containerRequestFacts struct { - image string - name string - reuse bool - exposedPorts []string - hostPortBindings []string - waits bool - unreadable []string -} - -// readContainerRequest reads one *testcontainers.GenericContainerRequest without naming its type. -// Reflection rather than an import, for the reason recordingTheRequest records: importing -// testcontainers-go directly promotes it from an indirect to a direct requirement of go.mod, which -// internal/config/releasehygiene_test.go refuses. -// -// Every field is taken by name from the library's own struct, so this reader's authority is the -// request rather than a list of option spellings kept here. It is driven over a request of that -// real type by TestTheContainerRequestReaderReadsAFixedNameAndAFixedHostPortBackOut. -func readContainerRequest(request any) containerRequestFacts { - var facts containerRequestFacts - pointer := reflect.ValueOf(request) - if pointer.Kind() != reflect.Pointer || pointer.IsNil() || pointer.Elem().Kind() != reflect.Struct { - return containerRequestFacts{unreadable: []string{"the recorded request is not a pointer to a struct"}} - } - - held := pointer.Elem() - if field, ok := fieldOf(held, "Image", reflect.String, &facts.unreadable); ok { - facts.image = field.String() - } - if field, ok := fieldOf(held, "Name", reflect.String, &facts.unreadable); ok { - facts.name = field.String() - } - if field, ok := fieldOf(held, "Reuse", reflect.Bool, &facts.unreadable); ok { - facts.reuse = field.Bool() - } - if field, ok := fieldOf(held, "ExposedPorts", reflect.Slice, &facts.unreadable); ok { - for index := range field.Len() { - facts.exposedPorts = append(facts.exposedPorts, field.Index(index).String()) - } - } - if field, ok := fieldOf(held, "WaitingFor", reflect.Interface, &facts.unreadable); ok { - facts.waits = !field.IsNil() - } - if field, ok := fieldOf(held, "HostConfigModifier", reflect.Func, &facts.unreadable); ok { - facts.hostPortBindings = hostPortBindingsOf(field, &facts.unreadable) - } - return facts -} - -// fieldOf reads one named field of the request. A field that is absent, or present with another -// kind, is recorded rather than skipped: either way the reader can no longer answer the question it -// was written for, and an empty answer here reads as "nothing was fixed". -func fieldOf(held reflect.Value, name string, kind reflect.Kind, unreadable *[]string) (reflect.Value, bool) { - field := held.FieldByName(name) - switch { - case !field.IsValid(): - *unreadable = append(*unreadable, name+" is no longer a field of the request") - case field.Kind() != kind: - *unreadable = append(*unreadable, name+" is a "+field.Kind().String()+", not a "+kind.String()) - default: - return field, true - } - return reflect.Value{}, false -} - -// hostPortBindingsOf applies a HostConfigModifier to a host config docker has not touched and -// reports every port binding it writes. A fresh host config binds nothing, so any entry at all is a -// host port this harness asked for by name -- which is why the criterion reads "nil, or leaves -// PortBindings empty" rather than "binds no particular port". -func hostPortBindingsOf(modifier reflect.Value, unreadable *[]string) []string { - if modifier.IsNil() { - return nil - } - shape := modifier.Type() - if shape.NumIn() != 1 || shape.In(0).Kind() != reflect.Pointer || shape.In(0).Elem().Kind() != reflect.Struct { - *unreadable = append(*unreadable, "HostConfigModifier no longer takes one pointer to a struct") - return nil - } - - fresh := reflect.New(shape.In(0).Elem()) - modifier.Call([]reflect.Value{fresh}) - bindings, ok := fieldOf(fresh.Elem(), "PortBindings", reflect.Map, unreadable) - if !ok { - return nil - } - - var written []string - for _, port := range bindings.MapKeys() { - written = append(written, boundHostPorts(port, bindings.MapIndex(port), unreadable)...) - } - slices.Sort(written) - return written -} - -// boundHostPorts names every host port one PortBindings entry writes. The key is rendered through -// fmt rather than through reflect.Value.String, because the vendored moby API spells a port as a -// struct with unexported fields and its own Stringer -- reflect.Value.String answers -// "" for that, which would name no port at all in a diagnostic. -func boundHostPorts(port, bound reflect.Value, unreadable *[]string) []string { - if bound.Kind() != reflect.Slice { - *unreadable = append(*unreadable, "PortBindings no longer maps a port to a slice") - return nil - } - - var written []string - for index := range bound.Len() { - host, ok := fieldOf(bound.Index(index), "HostPort", reflect.String, unreadable) - if !ok { - continue - } - written = append(written, fmt.Sprint(port.Interface())+" to host port "+strconv.Quote(host.String())) - } - return written -} - -// fixedContainerSettings is every setting in one container request that two concurrent harnesses -// cannot share, one clause per reason so a control can name which one fired rather than only that -// something did (.claude/rules/isolate-each-clause-of-a-multi-clause-guard.md). -// -// The exposed-port clause tests for a colon because docker spells a host binding -// `:` or `::`; a bare `5432/tcp` names a container port only -// and lets docker choose the host side. -func fixedContainerSettings(facts containerRequestFacts) []string { - var fixed []string - for _, field := range facts.unreadable { - fixed = append(fixed, "an unreadable request: "+field) - } - if facts.name != "" { - fixed = append(fixed, "a fixed container name "+strconv.Quote(facts.name)) - } - if facts.reuse { - fixed = append(fixed, "container reuse, which docker can only honour for a named container") - } - for _, exposed := range facts.exposedPorts { - if strings.Contains(exposed, ":") { - fixed = append(fixed, "a fixed host port in the exposed port "+strconv.Quote(exposed)) - } - } - for _, binding := range facts.hostPortBindings { - fixed = append(fixed, "a host port bound by HostConfigModifier: "+binding) - } - return fixed -} diff --git a/internal/source/generationscan_test.go b/internal/source/generationscan_test.go index 88dedfc..eb2a532 100644 --- a/internal/source/generationscan_test.go +++ b/internal/source/generationscan_test.go @@ -11,16 +11,6 @@ import ( // scan is defined as what it reaches. const generationEntryPoint = "Generate" -// theGenerationChainFloor is the smallest set of files Generate has ever reached. The chain is -// derived, not transcribed, so a file joining it is scanned without anyone remembering to extend a -// list; the floor exists so a derivation that silently stopped reaching most of the package fails -// here rather than reporting a clean scan of two files -// (.claude/rules/count-the-population-a-vacuity-guard-guards.md). -var theGenerationChainFloor = []string{ - "body.go", "dollarquote.go", "generate.go", "literal.go", "marker.go", "payload.go", - "statements.go", "whenclause.go", -} - func productionRoutingFiles(t *testing.T) []routingFile { t.Helper() files := make([]routingFile, 0, len(productionSourceNames(t))) @@ -66,71 +56,6 @@ func generationChainSources(t *testing.T) []string { return slices.Sorted(maps.Keys(within)) } -func TestTheGenerationChainStillReachesEveryFileTheGatesWereWrittenFor(t *testing.T) { - chain := generationChainSources(t) - for _, want := range theGenerationChainFloor { - if !slices.Contains(chain, want) { - t.Errorf("Generate no longer reaches %s, so the determinism and purity gates below no "+ - "longer scan it; chain = %v", want, chain) - } - } - t.Logf("the generation chain gates examined %d production files: %v", len(chain), chain) -} - -// TestTheGenerationChainDeclaresNoMapAndCallsNoOrderingRoutine is the determinism gate. It does not -// claim to recognise a range over a map -- that is a question about types, which this scan cannot -// answer -- so it forbids the precondition instead: a chain that declares no map type and calls -// nothing that orders a list or iterates a map has no non-deterministic iteration to perform. -func TestTheGenerationChainDeclaresNoMapAndCallsNoOrderingRoutine(t *testing.T) { - for _, name := range generationChainSources(t) { - for _, issue := range orderingHazards(parsedSource(t, name, sourceBytes(t, name))) { - t.Errorf("%s: %s", name, issue) - } - } -} - -// orderingRoutines are the qualified names whose result order is not the caller's. maps.Keys and -// maps.Values head the list because they are how this codebase's own scans iterate a map -// (quotingscan_test.go), and slices.Sort* because that is the spelling a chain file would reach for -// long before it reached for the sort package. -var orderingRoutines = map[string][]string{ - "sort": nil, // every exported name in it orders something - "slices": {"Sort", "SortFunc", "SortStableFunc", "Sorted", "SortedFunc", "SortedStableFunc"}, - "maps": {"Keys", "Values", "All"}, -} - -func orderingHazards(file *goast.File) []string { - var issues []string - goast.Inspect(file, func(node goast.Node) bool { - switch found := node.(type) { - case *goast.MapType: - issues = append(issues, "declares a map type, whose iteration order Go randomises") - case *goast.CallExpr: - if named, ordering := orderingCallName(found); ordering { - issues = append(issues, "calls "+named+", which does not preserve the caller's order") - } - } - return true - }) - return issues -} - -func orderingCallName(call *goast.CallExpr) (string, bool) { - selector, isSelector := call.Fun.(*goast.SelectorExpr) - if !isSelector { - return "", false - } - packageName, isIdent := selector.X.(*goast.Ident) - if !isIdent { - return "", false - } - routines, watched := orderingRoutines[packageName.Name] - if !watched || (routines != nil && !slices.Contains(routines, selector.Sel.Name)) { - return "", false - } - return packageName.Name + "." + selector.Sel.Name, true -} - // TestGenerationPurityHasNoPoolCallOrContextParameter keeps the chain offline: criterion 1 makes // generation a pure function of its request, so no chain file may reach the pool or take a context. func TestGenerationPurityHasNoPoolCallOrContextParameter(t *testing.T) { diff --git a/internal/source/golden_test.go b/internal/source/golden_test.go index fd67cde..efe0cd6 100644 --- a/internal/source/golden_test.go +++ b/internal/source/golden_test.go @@ -32,28 +32,6 @@ var generationModes = []goldenMode{ } var generationIncludeOld = []bool{false, true} -// The corpus axes, as literals: operation {insert, update, delete} = 3, mode -// {full, full + exclude, columns, keys_only} = 4 and include_old {false, true} = 2, so the grid is -// 3 x 4 x 2 = 24 cells, beside the 6 named goldens the axes do not reach. The pin reads the axis -// values gridCases ranges over and the files committed under testdata/ against these numbers, so -// dropping a mode shrinks one side of a comparison and not the other -- unlike a product computed -// from the very slices the rows are built from, which moves together with any contents at all. -const ( - declaredOperations = 3 - declaredModes = 4 - declaredIncludeOld = 2 - declaredGridCells = declaredOperations * declaredModes * declaredIncludeOld - declaredNamedGoldens = 6 -) - -// goldenPopulation holds the three populations the corpus pin reconciles. They move independently: -// the axis sizes are the declarations, the asked-for names are what the crossing builds, and the -// committed names are what is on disk. -type goldenPopulation struct { - operations, modes, includeOld int - rows, named, committed []string -} - // gridGoldenName spells one cell's golden. The crossed rows and the include_old pair assertions in // goldenpairs_test.go both derive their file names through it, so no assertion can read a // hand-listed set of names that has drifted from the corpus. @@ -159,55 +137,8 @@ func checkOrUpdateGolden(t *testing.T, testCase goldenCase) { } } -// reportGoldenPopulationIssues drives goldenPopulationIssues -- the same function -// TestTheCorpusPinFailsOnADroppedCellOrAxisValue falsifies, rather than a second expression of the -// pin. -func reportGoldenPopulationIssues(t *testing.T) { - t.Helper() - for _, issue := range goldenPopulationIssues(observedGoldenPopulation(t)) { - t.Error(issue) - } -} - -func TestGoldenCorpusIsTheCrossedProduct(t *testing.T) { - if !*updateGoldens { - reportGoldenPopulationIssues(t) - } - for _, testCase := range allGoldenCases() { - checkOrUpdateGolden(t, testCase) - } - if *updateGoldens { - // A -update run is held to the same shape it just wrote, so a cell the crossing stopped - // asking for is left behind on disk rather than silently leaving the corpus. - reportGoldenPopulationIssues(t) - } -} - -func TestGoldenCorpusDoesNotWriteWithoutUpdate(t *testing.T) { - if *updateGoldens { - t.Skip("mtime proof applies to the non-update run") - } - before := goldenMtimes(t) +func TestGeneratedSQLMatchesGoldens(t *testing.T) { for _, testCase := range allGoldenCases() { checkOrUpdateGolden(t, testCase) } - after := goldenMtimes(t) - for path, stamp := range before { - if after[path] != stamp { - t.Errorf("%s changed without -update", path) - } - } -} - -func goldenMtimes(t *testing.T) map[string]int64 { - t.Helper() - stamps := make(map[string]int64) - for _, testCase := range allGoldenCases() { - info, err := os.Stat(goldenPath(testCase.name)) - if err != nil { - t.Fatalf("stat %s: %v", testCase.name, err) - } - stamps[testCase.name] = info.ModTime().UnixNano() - } - return stamps } diff --git a/internal/source/goldenpairs_test.go b/internal/source/goldenpairs_test.go index cacf3fa..3f7affd 100644 --- a/internal/source/goldenpairs_test.go +++ b/internal/source/goldenpairs_test.go @@ -1,132 +1,12 @@ package source -// The assertions here read the committed corpus as data -- against the axes it is meant to be the -// crossing of, and against itself -- rather than against freshly generated text, which `go test -// -update` rewrites: a regressed grid_insert_*_old_true.golden matches a regressed generator and -// the suite stays green. Split from golden_test.go for the 200-line budget, not by subject. +// These assertions check how include_old affects the committed SQL across operations and payload +// modes, independently of the generator used to update the goldens. import ( - "fmt" - "path/filepath" - "slices" - "strings" "testing" ) -// observedGoldenPopulation reads the three populations the pin reconciles: the axis sizes gridCases -// ranges over, the goldens the crossed rows and the named cases ask for, and the files on disk. -func observedGoldenPopulation(t *testing.T) goldenPopulation { - t.Helper() - paths, err := filepath.Glob(filepath.Join("testdata", "*.golden")) - if err != nil { - t.Fatalf("glob the golden corpus: %v", err) - } - found := goldenPopulation{operations: len(generationOperations), modes: len(generationModes), includeOld: len(generationIncludeOld)} - for _, testCase := range gridCases() { - found.rows = append(found.rows, testCase.name) - } - for _, testCase := range namedGoldenCases() { - found.named = append(found.named, testCase.name) - } - for _, path := range paths { - found.committed = append(found.committed, filepath.Base(path)) - } - return found -} - -// countIssue is the one wording for a population that has stopped matching its declaration. -func countIssue(subject string, got, want int) string { - if got == want { - return "" - } - return fmt.Sprintf("%s is %d, want the declared %d", subject, got, want) -} - -// goldenPopulationIssues reports every way the corpus stops being the crossed product its axes -// declare. Each clause reads two populations that move independently, so a dropped mode, operation, -// include_old spelling or cell fails by name here rather than in production. -func goldenPopulationIssues(found goldenPopulation) []string { - var issues []string - for _, issue := range []string{ - countIssue("the operation axis", found.operations, declaredOperations), - countIssue("the mode axis", found.modes, declaredModes), - countIssue("the include_old axis", found.includeOld, declaredIncludeOld), - countIssue(fmt.Sprintf("the crossing's row count (%d x %d x %d)", declaredOperations, - declaredModes, declaredIncludeOld), len(found.rows), declaredGridCells), - countIssue("the named case count", len(found.named), declaredNamedGoldens), - countIssue(fmt.Sprintf("the committed corpus (%d + %d)", declaredGridCells, declaredNamedGoldens), - len(found.committed), declaredGridCells+declaredNamedGoldens), - } { - if issue != "" { - issues = append(issues, issue) - } - } - asked := slices.Concat(found.rows, found.named) - for _, name := range asked { - if !slices.Contains(found.committed, name) { - issues = append(issues, name+" is asked for and is committed nowhere under testdata/") - } - } - for _, name := range found.committed { - if !slices.Contains(asked, name) { - issues = append(issues, name+" is committed under testdata/ and no crossed row or named case asks for it") - } - } - return issues -} - -// droppedGoldenCell is the cell one control removes, derived from the axes so that it names a real -// committed golden however they are later ordered; unaskedGolden is one no crossing produces. -var droppedGoldenCell = gridGoldenName(generationOperations[0], generationModes[0].name, - generationIncludeOld[len(generationIncludeOld)-1]) - -const unaskedGolden = "grid_insert_full_old_perhaps.golden" - -// Each row is the observed population with one thing changed, fed to goldenPopulationIssues -- the -// function TestGoldenCorpusIsTheCrossedProduct itself calls, not a second expression of the pin. One -// row per clause, because a population tripping two of them cannot say which fired. The guard's -// other side -- that the corpus as committed is refused for nothing -- is that same test, over the -// unmutated population. -var theCorpusPopulationMutations = []struct { - name string - mutate func(goldenPopulation) goldenPopulation - want string -}{ - {"a declared cell committed nowhere", func(f goldenPopulation) goldenPopulation { - f.committed = slices.DeleteFunc(slices.Clone(f.committed), - func(name string) bool { return name == droppedGoldenCell }) - return f - }, droppedGoldenCell + " is asked for"}, - {"a golden no crossed row asks for", func(f goldenPopulation) goldenPopulation { - f.committed = slices.Concat(f.committed, []string{unaskedGolden}) - return f - }, unaskedGolden + " is committed under testdata/"}, - {"a mode dropped from the axis", func(f goldenPopulation) goldenPopulation { f.modes--; return f }, - "the mode axis is 3, want the declared 4"}, - {"an operation dropped from the axis", func(f goldenPopulation) goldenPopulation { f.operations--; return f }, - "the operation axis is 2, want the declared 3"}, - {"an include_old spelling dropped from the axis", func(f goldenPopulation) goldenPopulation { f.includeOld--; return f }, - "the include_old axis is 1, want the declared 2"}, - {"a crossed row nobody wrote", func(f goldenPopulation) goldenPopulation { - f.rows = f.rows[:len(f.rows)-1] - return f - }, "the crossing's row count (3 x 4 x 2) is 23, want the declared 24"}, -} - -func TestTheCorpusPinFailsOnADroppedCellOrAxisValue(t *testing.T) { - whole := observedGoldenPopulation(t) - for _, mutation := range theCorpusPopulationMutations { - t.Run(mutation.name, func(t *testing.T) { - issues := goldenPopulationIssues(mutation.mutate(whole)) - if !slices.ContainsFunc(issues, func(issue string) bool { - return strings.Contains(issue, mutation.want) - }) { - t.Fatalf("goldenPopulationIssues reported %v, want an issue containing %q", issues, mutation.want) - } - }) - } -} - // theOperationIncludeOldMeansSomethingFor states the include_old rule once, and both directions of // TestIncludeOldMovesTheCommittedDDLOnlyWhereItIsNotInert read it here: an update is the only // operation with a pre-change row the flag can add or withhold, because a delete always carries old @@ -160,8 +40,6 @@ func goldenPairsAcrossIncludeOld(t *testing.T) []goldenPair { pair := goldenPair{operation: operation, firstName: gridGoldenName(operation, mode.name, generationIncludeOld[0]), secondName: gridGoldenName(operation, mode.name, generationIncludeOld[1])} - // Unreachable while gridGoldenName spells the flag: a builder dropping it fails - // TestGoldenCorpusIsTheCrossedProduct first, on twelve goldens asked for by nobody. if pair.firstName == pair.secondName { t.Fatalf("%s names both include_old spellings of the %s %s cell", pair.firstName, operation, mode.name) diff --git a/internal/source/harness_integration_test.go b/internal/source/harness_integration_test.go index 4e11588..6f11382 100644 --- a/internal/source/harness_integration_test.go +++ b/internal/source/harness_integration_test.go @@ -5,9 +5,6 @@ package source import ( "context" "net/url" - "os" - "path/filepath" - "slices" "testing" "github.com/cpouldev/pg_noty/internal/config" @@ -66,25 +63,6 @@ func openPoolAs(t *testing.T, cfg config.Config, role string) *pgxpool.Pool { return pool } -// Copy of internal/schema/runner_integration_test.go:mustMigrate. The source side accepts SQL text -// from internal/schema's migration directory because schema's private migration types cannot cross -// packages. -func applySchemaMigrations(t *testing.T, pool *pgxpool.Pool) { - t.Helper() - paths, err := filepath.Glob(filepath.Join("..", "schema", "migrations", "*.sql")) - if err != nil || len(paths) == 0 { - t.Fatalf("read internal/schema migration corpus: %v", err) - } - slices.Sort(paths) - for _, path := range paths { - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read migration %s: %v", path, err) - } - mustExecOn(t, pool, string(data)) - } -} - // Copy of internal/schema/bootstrapprivilege_integration_test.go:createTheLimitedRole. func createTheLimitedRole(t *testing.T, pool *pgxpool.Pool, role, password string) { t.Helper() @@ -94,13 +72,3 @@ func createTheLimitedRole(t *testing.T, pool *pgxpool.Pool, role, password strin } mustExecOn(t, pool, "CREATE ROLE "+quoted+" LOGIN PASSWORD "+quoteLiteral(password)) } - -func TestExactlyOneContainerServesTheWholePackage(t *testing.T) { - skipIfShort(t) - if got := containersStarted.Load(); got != 1 { - t.Fatalf("containers started = %d, want 1", got) - } - if containerStartup <= 0 { - t.Fatal("container startup was not measured") - } -} diff --git a/internal/source/hostileroutes_test.go b/internal/source/hostileroutes_test.go deleted file mode 100644 index 4cd62cf..0000000 --- a/internal/source/hostileroutes_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package source - -// hostileRoute is how one hostile-input case gets its value in front of this generator, and why -// that route is the reachable one for the position it exercises. -// -// Criterion 14 names exactly two routes for a byte **phase 1 refuses**: the resolved metadata, and -// direct construction at the generator's boundary. A third value is declared below because -// criterion 13 also names a class phase 1 *accepts* — a column whose real name is `Status` — and -// calling that one "the boundary route" would say a live class is guarded, which is the same -// mistake as the reverse. Reading a fixture's row therefore answers both questions a reviewer has: -// which route the value took, and whether the class behind it is live or closed. -type hostileRoute struct { - name string - why string - needsPin bool - assertedAt string -} - -// theCeilingPin is step 10's R29/R32/R33 routing pin. Every guarded case cites it by name, so the -// citation is checkable in one grep and a rename breaks a search rather than rotting -// (.claude/rules/name-the-test-a-comment-claims-exists.md). -const theCeilingPin = "TestRoutingPinExaminesAllThreeRules" - -var ( - // Route one. The catalog supplies the position, so no phase-1 rule stands between the byte and - // the generator: phase 4 reads the target table and the primary-key columns during OID - // resolution and rename detection. A live class, asserted end to end against a real server. - routeResolvedMetadata = hostileRoute{ - name: "resolved metadata (SD-2)", - why: "the catalog supplies this position, so no phase-1 rule stands between the byte and the generator", - assertedAt: "end to end against a real server", - } - // Route two. A position configuration supplies, carrying a byte R29, R32 and R33 refuse through - // identifierDefect's charset rule. The case exists to assert what the generator *does* with the - // value, not to claim a live route, which is why it names the pin that fails first if that - // ceiling ever moves. - routeGeneratorBoundary = hostileRoute{ - name: "generator boundary", - why: "configuration supplies this position and R29/R32/R33 refuse the byte, so the route is guarded rather than live; " + theCeilingPin + " is what fails first if that ceiling moves", - needsPin: true, - assertedAt: "at the generator's boundary, and executed where the position reaches a server", - } - // Not one of criterion 14's two, and deliberately so. `Status` is a name phase 1 accepts — - // internal/config/ident.go names the class itself — so the value is written straight into the - // request for determinism while the class behind it stays live, and it is asserted end to end. - // Declaring it as the boundary route would claim a guarded class where there is none. - routeConfiguredUppercase = hostileRoute{ - name: "configuration, live class", - why: "phase 1 accepts `Status`, so this configuration position is reachable in production as written and needs no ceiling pin", - assertedAt: "end to end against a table carrying both spellings", - } -) - -// theHostileFiles are the sources carrying this package's injection proof. The population is -// declared rather than globbed so that adding a hostile suite is a visible edit here. -var theHostileFiles = []string{ - "boundaryexec_integration_test.go", - "hostileboundary_test.go", - "hostilecolumns_integration_test.go", - "hostileuppercase_integration_test.go", - "injection_integration_test.go", - "injectioncontrols_integration_test.go", - "literalroundtrip_integration_test.go", - "onestatement_integration_test.go", -} - -// theHostileCases is the route every hostile-input assertion declares. Criterion 14 is scored on -// it: a reader must be able to tell a live class from a guarded one without reconstructing phase -// 1's rules. Where one assertion spans positions of different routes, the row names the route that -// *governs* — the guarded one, because that is the one owing a citation. -var theHostileCases = map[string]hostileRoute{ - "TestCatalogHostileTableIsQuotedAndInert": routeResolvedMetadata, - "TestWithoutTheQuotingAuthorityTheHostileTargetIsRefused": routeResolvedMetadata, - "TestWithoutTheQuotingAuthorityAnInjectingTableNameExecutesItsInjection": routeResolvedMetadata, - "TestCatalogPrimaryKeyQuoteAndExcludeSubtraction": routeResolvedMetadata, - "TestUppercaseConfiguredColumnSelectsExactColumn": routeConfiguredUppercase, - "TestUppercaseUpdateOfColumnFiltersOnTheExactColumn": routeConfiguredUppercase, - "TestWithoutTheQuotingAuthorityTheUppercaseUpdateFilterSelectsTheWrongColumn": routeConfiguredUppercase, - "TestUppercaseExcludedColumnIsSubtractedByItsExactKey": routeConfiguredUppercase, - "TestWithoutTheQuotingAuthorityTheUppercaseExcludeSubtractionMissesItsColumn": routeConfiguredUppercase, - "TestBoundaryExcludeNamesAreAbsentAndOtherColumnsRemain": routeGeneratorBoundary, - "TestBoundaryHostileNamesUseTheGeneratorRoute": routeGeneratorBoundary, - "TestEveryHostileBoundaryPositionSurvivesTheServer": routeGeneratorBoundary, - "TestTheHostileUpdateOfFilterDoesNotFireOnAnotherColumn": routeGeneratorBoundary, - "TestGeneratedLiteralAndMarkerValuesRoundTrip": routeGeneratorBoundary, - "TestTheGeneratedChannelAndMarkerRoundTripThroughTheServer": routeGeneratorBoundary, -} - -// theHostileMetaAssertions police the case list rather than exercising a byte of their own. They -// are named so the partition over theHostileFiles is closed: an assertion there joins this set or -// theHostileCases, and one joining neither fails by name rather than shipping with no route. -var theHostileMetaAssertions = []string{ - "TestEveryHostileBoundaryPositionCarriesAnExpectation", - "TestTheOneStatementCounterCountsWhatTheServerRan", -} diff --git a/internal/source/injection_integration_test.go b/internal/source/injection_integration_test.go index 5ba981e..2419edf 100644 --- a/internal/source/injection_integration_test.go +++ b/internal/source/injection_integration_test.go @@ -85,8 +85,7 @@ func refusalCodeOf(err error) string { // Route: resolved metadata. The target table reaches Generate as the catalog spells it and // passes through no configuration rule -- internal/reconcile reads it out of pg_class during OID // resolution and rename detection -- so this is a live class, asserted end to end against a real server rather than -// a guarded one asserted at the boundary. theHostileCases records the same declaration in a form a -// test can read. +// a guarded one asserted at the boundary. func TestCatalogHostileTableIsQuotedAndInert(t *testing.T) { skipIfShort(t) pool := freshDatabase(t) diff --git a/internal/source/packagesources_test.go b/internal/source/packagesources_test.go index 0ba47b2..142b7db 100644 --- a/internal/source/packagesources_test.go +++ b/internal/source/packagesources_test.go @@ -7,33 +7,10 @@ import ( "os" "path/filepath" "slices" - "strconv" "strings" "testing" ) -// A floor, not an equality: the invariant worth guarding is that the reader still sees this -// package's sources, and an equality answers "did anyone add a file" instead -- churn that costs an -// edit and a re-derived sentence every time, and has never once caught a defect. -const productionPopulationRead = 24 - -// packageSourceNames is the one guarded population reader for this package's source-level gates. -// It fails on an empty glob and on a missing doc.go anchor, so a gate pointed at the wrong tree -// cannot pass over no files or over another directory's Go sources. -func packageSourceNames(t *testing.T) []string { - t.Helper() - - paths, err := filepath.Glob("*.go") - if err != nil { - t.Fatalf("glob internal/source sources: %v", err) - } - names, err := guardedSourceNames(paths, "doc.go") - if err != nil { - t.Fatal(err) - } - return names -} - func guardedSourceNames(paths []string, anchor string) ([]string, error) { if len(paths) == 0 { return nil, &sourcePopulationError{message: "source population is empty"} @@ -88,48 +65,3 @@ func parsedSource(t *testing.T, name string, data []byte) *goast.File { } return file } - -// importedPaths returns every import path in one parsed source, including aliased and blank imports. -func importedPaths(file *goast.File) []string { - paths := make([]string, 0, len(file.Imports)) - for _, imported := range file.Imports { - path, err := strconv.Unquote(imported.Path.Value) - if err != nil { - continue - } - paths = append(paths, path) - } - return paths -} - -func withinModule(imported, module string) bool { - return imported == module || len(imported) > len(module) && imported[:len(module)] == module && imported[len(module)] == '/' -} - -func TestTheSourcePopulationReaderRejectsAnEmptyGlob(t *testing.T) { - if _, err := guardedSourceNames(nil, "doc.go"); err == nil { - t.Fatal("an empty source population was accepted") - } -} - -func TestTheSourcePopulationReaderRejectsAMissingAnchor(t *testing.T) { - if _, err := guardedSourceNames([]string{"other.go"}, "doc.go"); err == nil { - t.Fatal("a source population without doc.go was accepted") - } -} - -func productionPopulationIssue(count int) string { - if count < productionPopulationRead { - return "production source count is below the floor the source scans need" - } - return "" -} - -func TestTheProductionPopulationIsRead(t *testing.T) { - if issue := productionPopulationIssue(len(productionSourceNames(t))); issue != "" { - t.Fatal(issue) - } - if productionPopulationIssue(productionPopulationRead-1) == "" { - t.Fatal("a population below the floor was accepted") - } -} diff --git a/internal/source/testmain_integration_test.go b/internal/source/testmain_integration_test.go index cb151ee..6d1f5f6 100644 --- a/internal/source/testmain_integration_test.go +++ b/internal/source/testmain_integration_test.go @@ -7,10 +7,8 @@ import ( "flag" "fmt" "os" - "reflect" "sync/atomic" "testing" - "time" "github.com/cpouldev/pg_noty/internal/config" "github.com/cpouldev/pg_noty/internal/testpostgres" @@ -31,35 +29,8 @@ const ( var ( sharedContainer *postgres.PostgresContainer containersStarted atomic.Int64 - containerUses atomic.Int64 - containerStartup time.Duration - - // harnessContainerRequest is the *testcontainers.GenericContainerRequest the sole postgres.Run - // call below handed the library, recorded by recordingTheRequest and read back by - // TestTheHarnessContainerRequestFixesNoHostPortAndNoContainerName. It is a live pointer, so it - // holds the request as every customizer left it; testcontainers passes the request on by value, - // so nothing after the customize loop can rewrite what this names. Written once from TestMain - // before m.Run and only read afterwards. - harnessContainerRequest any ) -// recordingTheRequest returns a customizer of option's own type that records the container request -// it is handed and then delegates to option. -// -// The type parameter is what keeps this file from naming testcontainers-go's types: importing that -// module directly would promote it from an indirect to a direct requirement of go.mod, which -// internal/config/releasehygiene_test.go refuses. The request therefore leaves as an any and is -// read by reflection in readContainerRequest. -func recordingTheRequest[Option any](option Option) Option { - recorded := reflect.MakeFunc( - reflect.TypeOf(option), func(arguments []reflect.Value) []reflect.Value { - harnessContainerRequest = arguments[0].Interface() - return reflect.ValueOf(option).Call(arguments) - }, - ) - return recorded.Interface().(Option) -} - func TestMain(m *testing.M) { os.Exit(runSourceHarness(m)) } func runSourceHarness(m *testing.M) int { @@ -91,18 +62,15 @@ func runSourceHarness(m *testing.M) int { func startSourceContainer(ctx context.Context) (*postgres.PostgresContainer, error) { containersStarted.Add(1) - started := time.Now() - container, err := postgres.Run( + return postgres.Run( ctx, harnessImage, postgres.WithDatabase(harnessDatabase), postgres.WithUsername(harnessUser), postgres.WithPassword(harnessPassword), postgres.WithSQLDriver(harnessSQLDriver), - recordingTheRequest(postgres.BasicWaitStrategies()), + postgres.BasicWaitStrategies(), ) - containerStartup = time.Since(started) - return container, err } // reportToHarnessStderr says something about this run where a reader will see it without -v. @@ -127,7 +95,6 @@ func skipIfShort(t *testing.T) { func harnessConfig(t *testing.T) config.Config { t.Helper() skipIfShort(t) - containerUses.Add(1) dsn, err := sharedContainer.ConnectionString(t.Context(), "sslmode=disable") if err != nil { t.Fatalf("read container connection string: %v", err) @@ -138,7 +105,6 @@ func harnessConfig(t *testing.T) config.Config { func restoreToSnapshot(t *testing.T) { t.Helper() skipIfShort(t) - containerUses.Add(1) if err := testpostgres.RestoreSnapshot(t.Context(), sharedContainer); err != nil { t.Fatalf("restore snapshot: %v", err) }