mirror of
https://github.com/MeshCore-Beacon/beacon-server.git
synced 2026-12-06 05:04:31 +00:00
* Seek region and message pages from their window, drop the slow pool * Bound typed and scoped region pages and message since pages, migration 059 * Count the late rows in the zero-hit type pair read bound * Cap typed window ranges, broader bounded cmi verification
614 lines
21 KiB
Go
614 lines
21 KiB
Go
// Copyright 2026 Beacon Contributors
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// Command planguard checks that the planner keeps choosing the plans Beacon's statements were designed for.
|
|
//
|
|
// planguard run --tier fixture|local|prod [--corpus db/planguard/corpus.yaml] [--dsn $PLANGUARD_DSN]
|
|
// [--out planguard-out] [--only RE] [--skip RE] [--modes m,..] [--include-pending] [--search-path P]
|
|
// [--baseline check|write|off] [--emit resolvers|plans --params FILE] [--plans FILE --params FILE]
|
|
// [--fidelity-against results.jsonl]
|
|
// planguard gen-policy [--corpus FILE] [--out FILE] (defaults and db/sqlc are under the module root)
|
|
// planguard diff --cases db/planguard/diff/NAME.yaml [--old-ref origin/dev] [--walk 1,2,3,web] [--dsn $PLANGUARD_DSN]
|
|
// [--out planguard-out] [--files db/planguard]
|
|
// planguard storediff --old URL --new URL --cases db/planguard/storediff/NAME.yaml [--walk 1,2,3,web] [--out DIR]
|
|
//
|
|
// diff runs each batch of a case file in one READ ONLY snapshot and compares every pair's full results. old:
|
|
// statements are read from db/sqlc at --old-ref through git (the checkout is never switched), new: from the working
|
|
// tree's db/sqlc, file: from --files.
|
|
//
|
|
// storediff walks each case of a case file page by page on two running servers (normally both read-only on one
|
|
// database) and compares the whole JSON of every page.
|
|
//
|
|
// --tier fixture first builds the synthetic fixture on --dsn through the migrations (or finds it built from the same
|
|
// files); it refuses a database that holds data and was not built that way, and one whose collation is not C
|
|
// (create it with CREATE DATABASE <name> TEMPLATE template0 LC_COLLATE 'C' LC_CTYPE 'C' ENCODING 'UTF8').
|
|
//
|
|
// Exit status: 0 when no run fails, 1 when one does (or the run cannot be made), 2 on usage errors.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/MeshCore-Beacon/beacon-server/db/planpolicy"
|
|
"github.com/MeshCore-Beacon/beacon-server/internal/planguard"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
const usage = "usage: planguard run --tier fixture|local|prod [flags] (planguard run -h for the flags)\n" +
|
|
" planguard gen-policy [--corpus FILE] [--out FILE] (paths default to the module root's db/)\n" +
|
|
" planguard diff --cases FILE [--old-ref REF] [--walk 1,2,3,web] [--dsn DSN] [--out DIR] [--files DIR]\n" +
|
|
" planguard storediff --old URL --new URL --cases FILE [--walk 1,2,3,web] [--out DIR]"
|
|
|
|
func main() {
|
|
os.Exit(run(os.Args[1:], os.Stdout, os.Stderr))
|
|
}
|
|
|
|
func run(args []string, stdout, stderr io.Writer) int {
|
|
if len(args) == 0 {
|
|
fmt.Fprintln(stderr, usage)
|
|
return 2
|
|
}
|
|
switch args[0] {
|
|
case "run":
|
|
return runCmd(args[1:], stdout, stderr)
|
|
case "gen-policy":
|
|
return genPolicyCmd(args[1:], stdout, stderr)
|
|
case "diff":
|
|
return diffCmd(args[1:], stderr)
|
|
case "storediff":
|
|
return storeDiffCmd(args[1:], stderr)
|
|
case "-h", "-help", "--help", "help":
|
|
fmt.Fprintln(stderr, usage)
|
|
return 2
|
|
}
|
|
fmt.Fprintf(stderr, "planguard: unknown subcommand %q\n%s\n", args[0], usage)
|
|
return 2
|
|
}
|
|
|
|
// genPolicyCmd writes db/planpolicy/cached_gen.go from the corpus: the cached statements whose entries prove
|
|
// every shape and mode of their admission profile. Statement texts come from db/sqlc of the module that holds the
|
|
// working directory (found by walking up to go.mod), so it runs from any directory of the checkout.
|
|
func genPolicyCmd(args []string, stdout, stderr io.Writer) int {
|
|
fs := flag.NewFlagSet("gen-policy", flag.ContinueOnError)
|
|
fs.SetOutput(stderr)
|
|
corpus := fs.String("corpus", "", "corpus file (default <module root>/db/planguard/corpus.yaml)")
|
|
out := fs.String("out", "", "generated Go file (default <module root>/db/planpolicy/cached_gen.go)")
|
|
if err := fs.Parse(args); err != nil {
|
|
return 2
|
|
}
|
|
if fs.NArg() > 0 {
|
|
fmt.Fprintf(stderr, "planguard gen-policy: unexpected argument %q\n", fs.Arg(0))
|
|
return 2
|
|
}
|
|
root, err := moduleRoot()
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard gen-policy:", err)
|
|
return 1
|
|
}
|
|
if *corpus == "" {
|
|
*corpus = filepath.Join(root, "db", "planguard", "corpus.yaml")
|
|
}
|
|
if *out == "" {
|
|
*out = filepath.Join(root, "db", "planpolicy", "cached_gen.go")
|
|
}
|
|
sqlc, err := planguard.LoadStatements(filepath.Join(root, "db", "sqlc"))
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard:", err)
|
|
return 1
|
|
}
|
|
c, err := planguard.LoadCorpus(os.DirFS(filepath.Dir(*corpus)), filepath.Base(*corpus), sqlc)
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard:", err)
|
|
return 1
|
|
}
|
|
src, err := planguard.GenPolicy(c, planpolicy.VerificationOnly)
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard gen-policy:", err)
|
|
return 1
|
|
}
|
|
if old, err := os.ReadFile(*out); err == nil && string(old) == string(src) {
|
|
fmt.Fprintf(stdout, "%s is up to date\n", *out)
|
|
return 0
|
|
}
|
|
if err := os.WriteFile(*out, src, 0o644); err != nil {
|
|
fmt.Fprintln(stderr, "planguard:", err)
|
|
return 1
|
|
}
|
|
fmt.Fprintf(stdout, "wrote %s\n", *out)
|
|
return 0
|
|
}
|
|
|
|
// diffCmd compares old and new statement results on one snapshot per batch.
|
|
func diffCmd(args []string, stderr io.Writer) int {
|
|
fs := flag.NewFlagSet("diff", flag.ContinueOnError)
|
|
fs.SetOutput(stderr)
|
|
cases := fs.String("cases", "", "diff case file, e.g. db/planguard/diff/planted_readmodels.yaml (required)")
|
|
oldRef := fs.String("old-ref", "", "git ref whose db/sqlc gives the old: statements (required when the cases use old:)")
|
|
walk := fs.String("walk", "", "comma list of page sizes to walk the pairs that have a walk at; web = each walk's web_limit")
|
|
dsn := fs.String("dsn", os.Getenv("PLANGUARD_DSN"), "PostgreSQL DSN (default $PLANGUARD_DSN)")
|
|
out := fs.String("out", "planguard-out", "output directory")
|
|
files := fs.String("files", "", "directory file: statements are relative to (default <module root>/db/planguard)")
|
|
if err := fs.Parse(args); err != nil {
|
|
return 2
|
|
}
|
|
usageErr := func(format string, a ...any) int {
|
|
fmt.Fprintf(stderr, "planguard diff: "+format+"\n", a...)
|
|
return 2
|
|
}
|
|
if fs.NArg() > 0 {
|
|
return usageErr("unexpected argument %q", fs.Arg(0))
|
|
}
|
|
if *cases == "" {
|
|
return usageErr("--cases is required")
|
|
}
|
|
limits, err := parseWalk(*walk)
|
|
if err != nil {
|
|
return usageErr("--walk: %v", err)
|
|
}
|
|
if *dsn == "" {
|
|
return usageErr("--dsn (or $PLANGUARD_DSN) is required")
|
|
}
|
|
root, err := moduleRoot()
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard diff:", err)
|
|
return 1
|
|
}
|
|
if *files == "" {
|
|
*files = filepath.Join(root, "db", "planguard")
|
|
}
|
|
raw, err := os.ReadFile(*cases)
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard diff:", err)
|
|
return 1
|
|
}
|
|
fsys := os.DirFS(*files)
|
|
spec, err := planguard.ParseDiffSpec(raw, *cases, fsys)
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard diff:", err)
|
|
return 1
|
|
}
|
|
needOld := false
|
|
for _, b := range spec.Batches {
|
|
for _, src := range b.Statements {
|
|
needOld = needOld || strings.HasPrefix(src, "old:")
|
|
}
|
|
}
|
|
var oldSQL map[string]string
|
|
if needOld {
|
|
if *oldRef == "" {
|
|
return usageErr("--old-ref is required: %s uses old: statements", *cases)
|
|
}
|
|
if oldSQL, err = planguard.LoadStatementsAtRef(root, *oldRef); err != nil {
|
|
fmt.Fprintln(stderr, "planguard diff:", err)
|
|
return 1
|
|
}
|
|
}
|
|
newSQL, err := planguard.LoadStatements(filepath.Join(root, "db", "sqlc"))
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard diff:", err)
|
|
return 1
|
|
}
|
|
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
pc, err := pgconn.Connect(ctx, *dsn)
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard diff: connect:", err)
|
|
return 1
|
|
}
|
|
defer pc.Close(context.Background())
|
|
rep, runErr := planguard.RunDiff(ctx, planguard.NewSession(pc), spec, oldSQL, newSQL, fsys, *out, limits)
|
|
code := 0
|
|
if rep != nil {
|
|
for _, b := range rep.Batches {
|
|
for _, p := range b.Pairs {
|
|
fmt.Fprintln(stderr, p.Line())
|
|
}
|
|
}
|
|
fmt.Fprintf(stderr, "report: %s\n", filepath.Join(*out, "diff_report.md"))
|
|
if n := len(rep.Failed()); n > 0 {
|
|
fmt.Fprintf(stderr, "%d pairs missed their expectation\n", n)
|
|
code = 1
|
|
}
|
|
if n := len(rep.Skipped()); n > 0 {
|
|
fmt.Fprintf(stderr, "%d pairs were skipped: their {sql: …} params found no value on this snapshot, so they prove nothing\n", n)
|
|
code = 1
|
|
}
|
|
}
|
|
if runErr != nil {
|
|
fmt.Fprintln(stderr, "planguard diff:", runErr)
|
|
code = 1
|
|
}
|
|
return code
|
|
}
|
|
|
|
// storeDiffCmd compares the pages of two servers' API.
|
|
func storeDiffCmd(args []string, stderr io.Writer) int {
|
|
fs := flag.NewFlagSet("storediff", flag.ContinueOnError)
|
|
fs.SetOutput(stderr)
|
|
oldBase := fs.String("old", "", "base URL of the old server, e.g. http://127.0.0.1:8481 (required)")
|
|
newBase := fs.String("new", "", "base URL of the new server, e.g. http://127.0.0.1:8482 (required)")
|
|
cases := fs.String("cases", "", "storediff case file, e.g. db/planguard/storediff/smoke.yaml (required)")
|
|
walk := fs.String("walk", "web", "comma list of page sizes; web = each case's web_limit")
|
|
out := fs.String("out", "", "directory for storediff_report.md (default: no file)")
|
|
if err := fs.Parse(args); err != nil {
|
|
return 2
|
|
}
|
|
usageErr := func(format string, a ...any) int {
|
|
fmt.Fprintf(stderr, "planguard storediff: "+format+"\n", a...)
|
|
return 2
|
|
}
|
|
if fs.NArg() > 0 {
|
|
return usageErr("unexpected argument %q", fs.Arg(0))
|
|
}
|
|
if *oldBase == "" || *newBase == "" || *cases == "" {
|
|
return usageErr("--old, --new and --cases are required")
|
|
}
|
|
for _, base := range []string{*oldBase, *newBase} {
|
|
if u, err := url.Parse(base); err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
|
return usageErr("%q is not an http(s) base URL", base)
|
|
}
|
|
}
|
|
if _, err := parseWalk(*walk); err != nil {
|
|
return usageErr("--walk: %v", err)
|
|
}
|
|
spec, err := planguard.LoadStoreDiffSpec(*cases)
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard storediff:", err)
|
|
return 1
|
|
}
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
hc := &http.Client{Timeout: 2 * time.Minute}
|
|
rep, runErr := planguard.RunStoreDiff(ctx, hc, *oldBase, *newBase, spec, strings.Split(*walk, ","))
|
|
code := 0
|
|
if rep != nil {
|
|
for _, c := range rep.Cases {
|
|
fmt.Fprintln(stderr, c.Line())
|
|
}
|
|
if *out != "" {
|
|
path := filepath.Join(*out, "storediff_report.md")
|
|
if err := os.MkdirAll(*out, 0o755); err != nil {
|
|
fmt.Fprintln(stderr, "planguard storediff:", err)
|
|
code = 1
|
|
} else if err := os.WriteFile(path, []byte(rep.Markdown()), 0o644); err != nil {
|
|
fmt.Fprintln(stderr, "planguard storediff:", err)
|
|
code = 1
|
|
} else {
|
|
fmt.Fprintf(stderr, "report: %s\n", path)
|
|
}
|
|
}
|
|
if n := len(rep.Failed()); n > 0 {
|
|
fmt.Fprintf(stderr, "%d results differ\n", n)
|
|
code = 1
|
|
}
|
|
if n := len(rep.Skipped()); n > 0 {
|
|
fmt.Fprintf(stderr, "%d results were skipped: a path var found no value, so they prove nothing\n", n)
|
|
code = 1
|
|
}
|
|
}
|
|
if runErr != nil {
|
|
fmt.Fprintln(stderr, "planguard storediff:", runErr)
|
|
code = 1
|
|
}
|
|
return code
|
|
}
|
|
|
|
// parseWalk reads "1,2,3,web" (web → 0, each walk's web_limit).
|
|
func parseWalk(s string) ([]int, error) {
|
|
if s == "" {
|
|
return nil, nil
|
|
}
|
|
var out []int
|
|
for _, part := range strings.Split(s, ",") {
|
|
part = strings.TrimSpace(part)
|
|
if part == "web" {
|
|
out = append(out, 0)
|
|
continue
|
|
}
|
|
n, err := strconv.Atoi(part)
|
|
if err != nil || n < 1 {
|
|
return nil, fmt.Errorf("%q is not a page size ≥ 1 or web", part)
|
|
}
|
|
out = append(out, n)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// moduleRoot returns the nearest directory at or above the working directory that holds go.mod.
|
|
func moduleRoot() (string, error) {
|
|
dir, err := os.Getwd()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
for {
|
|
if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil {
|
|
return dir, nil
|
|
}
|
|
parent := filepath.Dir(dir)
|
|
if parent == dir {
|
|
return "", errors.New("no go.mod at or above the working directory; run it inside the beacon-server checkout")
|
|
}
|
|
dir = parent
|
|
}
|
|
}
|
|
|
|
type runFlags struct {
|
|
tier, corpus, dsn, out, only, skip, modes, searchPath, baseline, emit, params, plans, fidelity string
|
|
includePending bool
|
|
}
|
|
|
|
func usageErr(stderr io.Writer, format string, a ...any) int {
|
|
fmt.Fprintf(stderr, "planguard run: "+format+"\n", a...)
|
|
return 2
|
|
}
|
|
|
|
func runCmd(args []string, stdout, stderr io.Writer) int {
|
|
var f runFlags
|
|
fs := flag.NewFlagSet("run", flag.ContinueOnError)
|
|
fs.SetOutput(stderr)
|
|
fs.StringVar(&f.tier, "tier", "", "fixture | local | prod (required)")
|
|
fs.StringVar(&f.corpus, "corpus", "db/planguard/corpus.yaml", "corpus file; baselines live in its baseline/<tier> directory")
|
|
fs.StringVar(&f.dsn, "dsn", os.Getenv("PLANGUARD_DSN"), "PostgreSQL DSN (default $PLANGUARD_DSN)")
|
|
fs.StringVar(&f.out, "out", "planguard-out", "output directory")
|
|
fs.StringVar(&f.only, "only", "", "regexp: run only entries whose id matches")
|
|
fs.StringVar(&f.skip, "skip", "", "regexp: leave out entries whose id matches")
|
|
fs.StringVar(&f.modes, "modes", "", "comma list of plan modes overriding every entry's")
|
|
fs.BoolVar(&f.includePending, "include-pending", false, "run pending statements too (local overlays only)")
|
|
fs.StringVar(&f.searchPath, "search-path", "", "override every group's search_path")
|
|
fs.StringVar(&f.baseline, "baseline", "", "check | write | off (default check; prod is always off)")
|
|
fs.StringVar(&f.emit, "emit", "", "resolvers | plans: write a read-only psql script to stdout instead of running")
|
|
fs.StringVar(&f.params, "params", "", "psql output of the --emit resolvers script")
|
|
fs.StringVar(&f.plans, "plans", "", "psql output of the --emit plans script: check it instead of running")
|
|
fs.StringVar(&f.fidelity, "fidelity-against", "", "results.<tier>.jsonl of another run to compare drivers with")
|
|
if err := fs.Parse(args); err != nil {
|
|
return 2
|
|
}
|
|
if fs.NArg() > 0 {
|
|
return usageErr(stderr, "unexpected argument %q", fs.Arg(0))
|
|
}
|
|
o, code := f.options(stderr)
|
|
if code != 0 {
|
|
return code
|
|
}
|
|
|
|
sqlc, err := planguard.LoadStatements("db/sqlc")
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard:", err)
|
|
return 1
|
|
}
|
|
c, err := planguard.LoadCorpus(os.DirFS(filepath.Dir(f.corpus)), filepath.Base(f.corpus), sqlc)
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard:", err)
|
|
return 1
|
|
}
|
|
if f.params != "" {
|
|
if o.Params, err = readResolverOutput(f.params); err != nil {
|
|
fmt.Fprintln(stderr, "planguard:", err)
|
|
return 1
|
|
}
|
|
}
|
|
|
|
switch {
|
|
case f.emit == "resolvers":
|
|
return emit(stderr, func(nonce string) error { return planguard.EmitResolvers(stdout, c, o, nonce) })
|
|
case f.emit == "plans":
|
|
return emit(stderr, func(nonce string) error { return planguard.EmitPlans(stdout, c, o, o.Params, nonce) })
|
|
case f.plans != "":
|
|
raw, err := os.ReadFile(f.plans)
|
|
if err == nil {
|
|
var nonce string
|
|
if nonce, err = planguard.ScriptNonce(raw); err == nil {
|
|
var plans map[string][]byte
|
|
if plans, err = planguard.ParsePlanOutput(strings.NewReader(string(raw)), nonce); err == nil {
|
|
var rep *planguard.Report
|
|
rep, err = planguard.CheckPlans(c, o, plans)
|
|
if err == nil {
|
|
for _, r := range rep.Results {
|
|
fmt.Fprintln(stderr, r.Line())
|
|
}
|
|
return finish(rep, nil, f, stderr)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
fmt.Fprintf(stderr, "planguard: %s: %v\n", f.plans, err)
|
|
return 1
|
|
}
|
|
|
|
if f.dsn == "" {
|
|
return usageErr(stderr, "--dsn (or $PLANGUARD_DSN) is required to run")
|
|
}
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
if f.tier == "fixture" {
|
|
if err := buildFixture(ctx, f, stderr); err != nil {
|
|
fmt.Fprintln(stderr, "planguard:", err)
|
|
return 1
|
|
}
|
|
}
|
|
pc, err := pgconn.Connect(ctx, f.dsn)
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard: connect:", err)
|
|
return 1
|
|
}
|
|
defer pc.Close(context.Background())
|
|
o.Progress = func(r planguard.Result) { fmt.Fprintln(stderr, r.Line()) }
|
|
rep, err := planguard.Run(ctx, c, planguard.NewSession(pc), o)
|
|
if rep == nil {
|
|
fmt.Fprintln(stderr, "planguard:", err)
|
|
return 1
|
|
}
|
|
return finish(rep, err, f, stderr)
|
|
}
|
|
|
|
// buildFixture builds the fixture tier's database on --dsn from the fixture/ directory beside the corpus, or finds
|
|
// it built from the same files.
|
|
func buildFixture(ctx context.Context, f runFlags, stderr io.Writer) error {
|
|
pool, err := pgxpool.New(ctx, f.dsn)
|
|
if err != nil {
|
|
return fmt.Errorf("connect: %w", err)
|
|
}
|
|
defer pool.Close()
|
|
t0 := time.Now()
|
|
if err := planguard.BuildFixture(ctx, pool, os.DirFS(filepath.Dir(f.corpus))); err != nil {
|
|
return err
|
|
}
|
|
fmt.Fprintf(stderr, "fixture ready in %.1f s\n", time.Since(t0).Seconds())
|
|
return nil
|
|
}
|
|
|
|
// options checks the flags and builds the run options; code is 2 on a usage error.
|
|
func (f runFlags) options(stderr io.Writer) (planguard.RunOptions, int) {
|
|
o := planguard.RunOptions{Tier: f.tier, IncludePending: f.includePending, SearchPath: f.searchPath}
|
|
switch f.tier {
|
|
case "":
|
|
return o, usageErr(stderr, "--tier is required (fixture, local or prod)")
|
|
case "fixture", "local", "prod":
|
|
default:
|
|
return o, usageErr(stderr, "unknown --tier %q (want fixture, local or prod)", f.tier)
|
|
}
|
|
switch f.baseline {
|
|
case "":
|
|
o.Baseline = planguard.BaselineCheck
|
|
case "check", "write", "off":
|
|
o.Baseline = planguard.BaselineMode(f.baseline)
|
|
default:
|
|
return o, usageErr(stderr, "unknown --baseline %q (want check, write or off)", f.baseline)
|
|
}
|
|
if f.tier == "prod" {
|
|
o.Baseline = planguard.BaselineOff
|
|
}
|
|
o.BaselineDir = filepath.Join(filepath.Dir(f.corpus), "baseline", f.tier)
|
|
var err error
|
|
if f.only != "" {
|
|
if o.Only, err = regexp.Compile(f.only); err != nil {
|
|
return o, usageErr(stderr, "--only: %v", err)
|
|
}
|
|
}
|
|
if f.skip != "" {
|
|
if o.Skip, err = regexp.Compile(f.skip); err != nil {
|
|
return o, usageErr(stderr, "--skip: %v", err)
|
|
}
|
|
}
|
|
if f.modes != "" {
|
|
for _, m := range strings.Split(f.modes, ",") {
|
|
switch m = strings.TrimSpace(m); m {
|
|
case "custom", "generic", "auto":
|
|
o.Modes = append(o.Modes, m)
|
|
default:
|
|
return o, usageErr(stderr, "--modes: unknown mode %q (want custom, generic or auto)", m)
|
|
}
|
|
}
|
|
}
|
|
if (f.emit != "" || f.plans != "") && f.tier != "prod" {
|
|
return o, usageErr(stderr, "--emit and --plans are the prod tier's psql path; use them with --tier prod")
|
|
}
|
|
switch f.emit {
|
|
case "", "resolvers":
|
|
case "plans":
|
|
if f.params == "" {
|
|
return o, usageErr(stderr, "--emit plans needs --params (the psql output of --emit resolvers)")
|
|
}
|
|
default:
|
|
return o, usageErr(stderr, "unknown --emit %q (want resolvers or plans)", f.emit)
|
|
}
|
|
if f.plans != "" {
|
|
if f.emit != "" {
|
|
return o, usageErr(stderr, "--plans and --emit are exclusive")
|
|
}
|
|
if f.params == "" {
|
|
return o, usageErr(stderr, "--plans needs --params (the psql output of --emit resolvers)")
|
|
}
|
|
}
|
|
return o, 0
|
|
}
|
|
|
|
func emit(stderr io.Writer, write func(nonce string) error) int {
|
|
nonce, err := planguard.NewNonce()
|
|
if err == nil {
|
|
err = write(nonce)
|
|
}
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard:", err)
|
|
return 1
|
|
}
|
|
return 0
|
|
}
|
|
|
|
func readResolverOutput(path string) (map[string]*string, error) {
|
|
raw, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
nonce, err := planguard.ScriptNonce(raw)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s: %w", path, err)
|
|
}
|
|
res, err := planguard.ParseResolverOutput(strings.NewReader(string(raw)), nonce)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s: %w", path, err)
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// finish writes the report files, prints the totals and the fidelity, and returns the exit status.
|
|
func finish(rep *planguard.Report, runErr error, f runFlags, stderr io.Writer) int {
|
|
code := 0
|
|
if err := rep.WriteFiles(f.out); err != nil {
|
|
fmt.Fprintln(stderr, "planguard: write report:", err)
|
|
code = 1
|
|
}
|
|
fmt.Fprintf(stderr, "%d runs in %.1f s: %s\n", len(rep.Results), rep.DurationMs/1000, rep.CountsString())
|
|
if f.fidelity != "" {
|
|
other, err := planguard.ReadResults(f.fidelity)
|
|
if err != nil {
|
|
fmt.Fprintln(stderr, "planguard: fidelity:", err)
|
|
code = 1
|
|
} else {
|
|
var otherIx []string
|
|
if meta, err := planguard.ReadReportMeta(f.fidelity); err == nil {
|
|
otherIx = meta.Indexes
|
|
} else if errors.Is(err, os.ErrNotExist) {
|
|
fmt.Fprintf(stderr, "planguard: fidelity: no report file beside %s; its index set is unknown, so nothing is excluded for it\n", f.fidelity)
|
|
} else {
|
|
fmt.Fprintln(stderr, "planguard: fidelity:", err)
|
|
code = 1
|
|
}
|
|
fr := planguard.Fidelity(rep.Results, other, rep.Indexes, otherIx)
|
|
pct := 0.0
|
|
if fr.Total > 0 {
|
|
pct = 100 * float64(fr.Match) / float64(fr.Total)
|
|
}
|
|
fmt.Fprintf(stderr, "fidelity: %d of %d driver sets match (%.1f %%), %d excluded for index-set differences\n", fr.Match, fr.Total, pct, fr.Excluded)
|
|
for _, m := range fr.Mismatches {
|
|
fmt.Fprintln(stderr, " differs:", m)
|
|
}
|
|
}
|
|
}
|
|
if runErr != nil {
|
|
fmt.Fprintln(stderr, "planguard: run stopped:", runErr)
|
|
code = 1
|
|
}
|
|
if n := len(rep.Failures()); n > 0 {
|
|
fmt.Fprintf(stderr, "%d failing runs\n", n)
|
|
code = 1
|
|
}
|
|
return code
|
|
}
|