diff --git a/SECURITY.rst b/SECURITY.rst index 88a716ae..57f9a89c 100644 --- a/SECURITY.rst +++ b/SECURITY.rst @@ -55,7 +55,7 @@ Installation token limited to the test repository and to the permissions the bot uses: - Actions: read and write (reading runs, reruns, dispatching); - - Checks: read (warning annotations); + - Checks: read (warning and error annotations); - Contents: read and write (test branches and recovery refs); - Workflows: read and write (patches may change workflow files); - Metadata: read (always granted). diff --git a/SETUP.rst b/SETUP.rst index 1e591ee6..84fd885a 100644 --- a/SETUP.rst +++ b/SETUP.rst @@ -136,7 +136,7 @@ Fill in the form: - **Repository permissions**: - Actions: read and write (reading runs, reruns, dispatching); - - Checks: read-only (warning annotations, see + - Checks: read-only (warning and error annotations, see ``workflows.warning_annotation`` in ``examples/reference.yaml``); - Contents: read and write (pushing test branches); - Workflows: read and write (patches may change workflow files); diff --git a/examples/ovn.yaml b/examples/ovn.yaml index 11cd7ce2..fb9b3532 100644 --- a/examples/ovn.yaml +++ b/examples/ovn.yaml @@ -34,6 +34,10 @@ report: # Answers from submitters go to ovs-dev. reply_to: ovs-dev@openvswitch.org pending: check + # List the failed tests of these workflows in reports. + workflow_logs_format: + ovn-kubernetes: ginkgo + Build and Test: autotest archive: reports_url: https://mail.openvswitch.org/pipermail/ovs-build/ diff --git a/examples/reference.yaml b/examples/reference.yaml index 0fdaf56f..d3ba84de 100644 --- a/examples/reference.yaml +++ b/examples/reference.yaml @@ -133,10 +133,119 @@ report: # Email a report for every patch that applied, not only for failures. apply_success: true - # Reports of failed runs include the last log_lines lines of up to - # max_log_jobs failed jobs. + # Format of the job logs of each workflow, by workflow name (as in + # the Test-Label, ignoring case), used to list the failed tests and + # show their logs in reports of failed runs. The jobs of a workflow + # that is not listed, or whose log has no failed tests in its format + # (for example when the build failed), get the last log_lines lines of + # their log instead. Leave it empty, the default, to always report + # the last log_lines lines of every job. For example: + # + # workflow_logs_format: + # ovn-kubernetes: ginkgo + # Build and Test: autotest + # + # The formats are: + # + # - autotest: Autotest test suites, like "make check" of OVS and OVN, + # when the job prints tests/testsuite.log after the tests fail. The + # failed tests are those of its "Summary of the failures" (failed + # tests and unexpected passes), from every test suite the job ran, + # and the log of each is its part of "Detailed failed tests". The + # error is at the end of those logs, so a long one keeps its last + # max_test_lines lines, after a note on how many lines came before. + # + # - ginkgo: Ginkgo test suites, like the e2e tests of ovn-kubernetes. + # The failed specs are those of the "Summarizing N Failures:" list at + # the end of the suite, and the log of each is the report Ginkgo + # printed when it failed, with its error. Go unit tests that run in + # the same job are not looked at. + workflow_logs_format: {} + + # Limits on the logs in reports of failed runs. All of them are + # optional; the values below are the defaults. Each must be at least + # 1. Wherever a limit cuts something, the report says how much was + # left out and to see the workflow run: + # + # ... 12 more failed tests, see the workflow run. + # ... 40 more lines, see the workflow run. + # + # A report starts with the list of all failed jobs, from GitHub, with + # the step each failed at. Then come the logs of the first + # max_log_jobs failed jobs, each in one of three ways: + # + # - When the job has error annotations titled + # workflows.warning_annotation, like the checkpatch workflows: + # + # Errors of "": + # + # + # - Otherwise, when workflow_logs_format gives the workflow a format + # and failed tests are found in the job's log: + # + # Failed tests in "": + # <- up to max_listed_tests names + # ... + # ... N more failed tests, see the workflow run. + # + # <- up to max_tests tests, each with + # up to max_test_lines log lines + # ... + # ... N more failed tests, see the workflow run. + # + # Only whole tests are shown: each test shown gets its log up to + # max_test_lines lines, never less to make room for others. So a job shows at + # most max_tests x max_test_lines log lines, plus the list of names, + # the test names and the notes. With the defaults, that is at most + # 4 x 25 = 100 log lines, and about 160 lines in all with a full list + # of 50 names. + # + # A test's log is shown only once per report: when the same test + # fails in several jobs, the later jobs list its name, say its log + # is skipped, and don't count it toward their max_tests. + # + # - Otherwise (no format, or no failed tests found in the log, as when + # the build fails before the tests run): + # + # Last log lines of "": + # + # + # These lines end with the line that ends the step that failed (the + # "##[error]Process completed with exit code" line), so the cleanup + # steps after it do not hide the error. + # + # The logs of the jobs after the first max_log_jobs are left out, with + # a note saying how many. + # + # max_lines is a ceiling on the whole report. It counts every line: + # the list of failed jobs, blank lines, headings, lists of failed + # tests, test names, log lines and notes. Once the report reaches it, + # no more jobs are added, and the report is cut after max_lines lines, + # even in the middle of a test. The report is also always cut after + # 20000 characters, in case of very long lines. Reports with a few + # failed tests stay well under max_lines; it only cuts reports of runs + # with many failures in several jobs. To get shorter reports, lower + # max_log_jobs, max_tests, max_test_lines and max_listed_tests first. + # The warnings in reports of runs that passed with warnings, and + # reports of patches that fail to apply, with the git am output and the + # diff of the conflicts, are cut the same way. + # + # So not every limit applies to every job: + # + # - max_log_jobs and max_lines apply to every report. + # - The errors of annotations, like those of checkpatch, are only cut + # by max_lines. + # - Reports of patches that fail to apply are only cut by max_lines. + # - max_listed_tests, max_tests and max_test_lines only apply to the + # workflows given a format in workflow_logs_format. + # - log_lines only applies to the jobs reported with the last lines of + # their log. + max_log_jobs: 3 + max_listed_tests: 50 + max_tests: 4 + max_test_lines: 25 log_lines: 25 - max_log_jobs: 5 + max_lines: 300 # Right-hand side of generated Message-IDs. Empty means the domain # of the LEADTEST_SMTP_USERNAME address. @@ -370,9 +479,14 @@ workflows: # annotations with this title, e.g. from # echo "::warning title=leadtest::2 lines are too long" # Their messages are included in the report. This lets a workflow - # pass with warnings, like checkpatch in fork-workflows/. Reading the + # pass with warnings, like checkpatch in fork-workflows/. The report of + # a failed job carries the messages of its error annotations with this + # title, e.g. from + # echo "::error title=leadtest::ERROR: Line is too long" + # instead of its log. Either way the messages are cut to + # report.max_lines lines and 20000 characters. Reading the # annotations needs the Checks permission of the GitHub App (see - # SETUP.rst). Empty disables it. + # SETUP.rst). Empty disables both. warning_annotation: leadtest rechecks: diff --git a/fork-workflows/leadtest-checkpatch-dpdk.yml b/fork-workflows/leadtest-checkpatch-dpdk.yml index db81c57d..a6fa7c14 100644 --- a/fork-workflows/leadtest-checkpatch-dpdk.yml +++ b/fork-workflows/leadtest-checkpatch-dpdk.yml @@ -64,8 +64,23 @@ jobs: done chmod +x linux/checkpatch.pl + # On failure the output goes in an error annotation titled like + # workflows.warning_annotation, which LeadTestKit reports instead of + # the end of the log. - name: Run checkpatches.sh run: | cd dpdk + status=0 DPDK_CHECKPATCH_PATH="$GITHUB_WORKSPACE/linux/checkpatch.pl" \ - devtools/checkpatches.sh "$GITHUB_WORKSPACE/patch.mbox" + devtools/checkpatches.sh "$GITHUB_WORKSPACE/patch.mbox" \ + > ../checkpatch.log 2>&1 || status=$? + cat ../checkpatch.log + [ "$status" -eq 0 ] && exit 0 + python3 - ../checkpatch.log <<'EOF' + import sys + text = open(sys.argv[1]).read().strip() + for c, e in (("%", "%25"), ("\r", "%0D"), ("\n", "%0A")): + text = text.replace(c, e) + print("::error title=leadtest::" + text) + EOF + exit "$status" diff --git a/fork-workflows/leadtest-checkpatch-ovs.yml b/fork-workflows/leadtest-checkpatch-ovs.yml index fed34915..d854760a 100644 --- a/fork-workflows/leadtest-checkpatch-ovs.yml +++ b/fork-workflows/leadtest-checkpatch-ovs.yml @@ -59,23 +59,27 @@ jobs: cp upstream/utilities/checkpatch.py checkpatch.py fi - # Errors fail the job. With only warnings the job passes with a - # warning annotation titled like workflows.warning_annotation, and - # LeadTestKit reports a warning with its text. + # The output of checkpatch goes in an annotation titled like + # workflows.warning_annotation, which LeadTestKit reports instead of + # the end of the log. Errors fail the job with an error annotation. + # With only warnings the job passes with a warning annotation, and + # LeadTestKit reports a warning. - name: Run checkpatch run: | status=0 python3 checkpatch.py patch.mbox > checkpatch.log 2>&1 || status=$? cat checkpatch.log - if [ "$status" -ne 0 ] && ! grep -q '^ERROR' checkpatch.log && - grep -q '^WARNING' checkpatch.log; then - python3 - checkpatch.log <<'EOF' + [ "$status" -eq 0 ] && exit 0 + level=error + if ! grep -q '^ERROR' checkpatch.log && grep -q '^WARNING' checkpatch.log; then + level=warning + fi + python3 - "$level" checkpatch.log <<'EOF' import sys - text = open(sys.argv[1]).read().strip() + text = open(sys.argv[2]).read().strip() for c, e in (("%", "%25"), ("\r", "%0D"), ("\n", "%0A")): text = text.replace(c, e) - print("::warning title=leadtest::" + text) + print("::%s title=leadtest::%s" % (sys.argv[1], text)) EOF - exit 0 - fi + [ "$level" = warning ] && exit 0 exit "$status" diff --git a/internal/config/config.go b/internal/config/config.go index ec8b0c36..88c9bfcd 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -11,6 +11,7 @@ import ( "net/url" "os" "regexp" + "slices" "strconv" "strings" "time" @@ -107,6 +108,10 @@ type TestRepo struct { GitHost string `yaml:"git_host"` } +// LogFormats are the job log formats that can be given in +// report.workflow_logs_format. +var LogFormats = []string{"ginkgo", "autotest"} + type Report struct { // Style is "ovs" (patchwork state names) or "dpdk" (upper case). Style string `yaml:"style"` @@ -122,8 +127,16 @@ type Report struct { // "both" or "off". Pending string `yaml:"pending"` ApplySuccess bool `yaml:"apply_success"` - LogLines int `yaml:"log_lines"` - MaxLogJobs int `yaml:"max_log_jobs"` + // WorkflowLogsFormat maps workflow names to the format of their job + // logs, one of LogFormats, to find the failed tests in them. + WorkflowLogsFormat map[string]string `yaml:"workflow_logs_format"` + // Limits on the logs in reports of failed runs. + MaxLogJobs int `yaml:"max_log_jobs"` + MaxListedTests int `yaml:"max_listed_tests"` + MaxTests int `yaml:"max_tests"` + MaxTestLines int `yaml:"max_test_lines"` + LogLines int `yaml:"log_lines"` + MaxLines int `yaml:"max_lines"` // MessageIDDomain is the right-hand side of generated Message-IDs. MessageIDDomain string `yaml:"message_id_domain"` } @@ -268,7 +281,8 @@ type Workflows struct { // RerunJobs is "failed" (GitHub's "Re-run failed jobs") or "all". RerunJobs string `yaml:"rerun_jobs"` // WarningAnnotation is the title of the warning annotations that - // make a successful run a warning. Empty disables the check. + // make a successful run a warning, and of the error annotations + // reported instead of the log of a failed job. Empty disables both. WarningAnnotation string `yaml:"warning_annotation"` } @@ -323,16 +337,21 @@ func defaults() Config { GitHost: "github.com", }, Report: Report{ - Style: "ovs", - Label: "github-robot", - ApplyLabel: "apply-robot", - FromName: "LeadTestKit Robot", - BuildPrefix: "github build", - Reply: Reply{Mode: "on-failure"}, - Pending: "both", - ApplySuccess: true, - LogLines: 25, - MaxLogJobs: 5, + Style: "ovs", + Label: "github-robot", + ApplyLabel: "apply-robot", + FromName: "LeadTestKit Robot", + BuildPrefix: "github build", + Reply: Reply{Mode: "on-failure"}, + Pending: "both", + ApplySuccess: true, + WorkflowLogsFormat: map[string]string{}, + MaxLogJobs: 3, + MaxListedTests: 50, + MaxLines: 300, + MaxTests: 4, + MaxTestLines: 25, + LogLines: 25, }, Archive: Archive{ MinDelay: Duration(time.Second), @@ -744,6 +763,17 @@ func (c *Config) validate() error { if l.PerAuthorMaxShare <= 0 || l.PerAuthorMaxShare > 1 { add("limits.per_author_max_share must be in (0, 1]") } + rp := c.Report + if rp.MaxLogJobs < 1 || rp.MaxListedTests < 1 || rp.MaxLines < 1 || + rp.MaxTests < 1 || rp.MaxTestLines < 1 || rp.LogLines < 1 { + add("report: max_log_jobs, max_listed_tests, max_lines, max_tests, " + + "max_test_lines and log_lines must be >= 1") + } + for wf, f := range rp.WorkflowLogsFormat { + if !slices.Contains(LogFormats, f) { + add("report: workflow_logs_format: unknown format %q for %q", f, wf) + } + } if c.Runner.LoopInterval <= 0 || c.Runner.LoopDuration < 0 { add("runner: loop_interval must be positive") } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index a6828ec3..831426f7 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -98,6 +98,8 @@ func TestValidationErrors(t *testing.T) { "stale 1s": minimal + "\npages:\n stale_after: 1s\n", "bad pending": strings.Replace(minimal, "report:\n", "report:\n pending: yes\n", 1), + "unknown log format": strings.Replace(minimal, "report:\n", + "report:\n workflow_logs_format:\n lorem: ipsum\n", 1), "no dev archive for rechecks": strings.Replace(minimal, "archive:\n dev_url: https://lists.example.org/pipermail/lorem-dev/\n", "", 1), diff --git a/internal/gitrepo/work.go b/internal/gitrepo/work.go index 1d1d3463..6aaa7bb9 100644 --- a/internal/gitrepo/work.go +++ b/internal/gitrepo/work.go @@ -149,7 +149,8 @@ func (w *WorkRepo) ReadFile(ctx context.Context, rev, path string) ([]byte, erro // Apply applies the emails on top of base one by one. It returns the // commit of every applied patch, or "" for a patch whose change is // already there, which git am applies without a commit; on a failure it -// also returns the index of the failing patch and the git am output. +// also returns the index of the failing patch and the git am output, +// followed by the diff of any conflicts. func (w *WorkRepo) Apply( ctx context.Context, base string, mboxes [][]byte, ) ([]string, int, string, error) { @@ -182,13 +183,24 @@ func (w *WorkRepo) Apply( if err != nil { return shas, -1, "", err } - if _, err := g.Run(ctx, "am", "-q", "-3", "--no-gpg-sign", file); err != nil { + // Without -q, git am names the files with conflicts. + if _, err := g.Run(ctx, "-c", "advice.mergeConflict=false", "-c", + "advice.amWorkDir=false", "am", "-3", + "--no-gpg-sign", file); err != nil { var gerr *Error if !errors.As(err, &gerr) { return shas, -1, "", err } + out := strings.TrimSpace(gerr.Stdout + "\n" + gerr.Stderr) + diff, err := w.Git.Out(ctx, "diff", "--no-color", "--no-ext-diff") w.abortAm(ctx) - return shas, i, strings.TrimSpace(gerr.Stdout + "\n" + gerr.Stderr), nil + if err != nil { + return shas, -1, "", err + } + if diff != "" { + out += "\n\n" + diffHeading + "\n" + diff + } + return shas, i, out, nil } sha, err := w.Git.Out(ctx, "rev-parse", "HEAD") if err != nil { @@ -204,6 +216,8 @@ func (w *WorkRepo) Apply( return shas, -1, "", nil } +const diffHeading = "Diff of the conflicts:" + // SameChange reports whether a commit makes the change of an email, // comparing stable patch IDs, which ignore whitespace and line numbers. func (w *WorkRepo) SameChange(ctx context.Context, sha string, mbox []byte) (bool, error) { diff --git a/internal/gitrepo/work_test.go b/internal/gitrepo/work_test.go index 31b789f8..c435d448 100644 --- a/internal/gitrepo/work_test.go +++ b/internal/gitrepo/work_test.go @@ -136,6 +136,10 @@ func TestApplyFailure(t *testing.T) { if err != nil || failed != 0 || len(shas) != 0 || out == "" { t.Fatalf("shas=%v failed=%d out=%q err=%v", shas, failed, out, err) } + // Without a three-way merge there are no conflicts to show. + if strings.Contains(out, diffHeading) { + t.Errorf("out=%q", out) + } // The repository must be usable again after a failure. shas, failed, out, err = w.Apply(ctx, base, patches[:2]) if err != nil || failed != -1 || len(shas) != 2 { @@ -143,6 +147,38 @@ func TestApplyFailure(t *testing.T) { } } +func TestApplyConflict(t *testing.T) { + upstream, test, patches := setup(t) + ctx := context.Background() + w := newWork(t, test) + // Settings of the operator must not change the diff in reports. + config := filepath.Join(t.TempDir(), "gitconfig") + write(t, config, "[color]\n\tui = always\n[diff]\n\texternal = false\n") + w.Git.Env = []string{"GIT_CONFIG_GLOBAL=" + config} + old, _ := w.Resolve(ctx, upstream, "main") + clone := filepath.Join(t.TempDir(), "clone") + run(t, "", "clone", "-q", upstream, clone) + write(t, filepath.Join(clone, "lorem.txt"), "lorem\nipsum\namet\n") + run(t, clone, "commit", "-qam", "lorem: Add amet.") + run(t, clone, "push", "-q", "origin", "main") + base, _ := w.Resolve(ctx, upstream, "main") + shas, failed, out, err := w.Apply(ctx, base, patches[:1]) + if err != nil || failed != 0 || len(shas) != 0 { + t.Fatalf("shas=%v failed=%d out=%q err=%v", shas, failed, out, err) + } + conflict := strings.Index(out, "CONFLICT (content): Merge conflict in lorem.txt") + heading := strings.Index(out, diffHeading) + if conflict < 0 || heading < conflict || !strings.Contains(out[heading:], "<<<<<<<") || + strings.Contains(out, "hint:") || strings.Contains(out, "\x1b[") { + t.Errorf("out=%q", out) + } + // The repository must be usable again after a conflict. + if shas, failed, out, err = w.Apply(ctx, old, patches[:1]); err != nil || + failed != -1 || len(shas) != 1 { + t.Fatalf("second apply: shas=%v failed=%d out=%q err=%v", shas, failed, out, err) + } +} + // git am applies a patch whose change is already there without a // commit, and without an error. func TestApplyAlreadyApplied(t *testing.T) { diff --git a/internal/pipeline/annotations.go b/internal/pipeline/annotations.go index dca927df..751b1d12 100644 --- a/internal/pipeline/annotations.go +++ b/internal/pipeline/annotations.go @@ -5,7 +5,6 @@ package pipeline import ( "context" - "fmt" "net/http" "strings" @@ -66,7 +65,7 @@ func (p *Pipeline) successResult(ctx context.Context, pt *state.Patch, r *state. if len(msgs) == 0 { return state.ResultSuccess, true } - warnings := headLines(strings.Join(msgs, "\n"), p.Cfg.Report.LogLines) + warnings := capLog(strings.Join(msgs, "\n"), p.Cfg.Report.MaxLines, maxReportChars) r.Details = "Warnings:\n" + warnings p.noteRun(pt, wr.HTMLURL, wr.RunAttempt, "workflow-warnings", "%s run %d, attempt %d passed with %s:\n%s", r.Workflow, wr.ID, wr.RunAttempt, @@ -100,11 +99,33 @@ func (p *Pipeline) warningAnnotations(ctx context.Context, suiteID int64, return msgs, nil } -func headLines(text string, n int) string { - lines := strings.Split(text, "\n") - if len(lines) <= n { - return text +// errorAnnotations returns the messages of the error annotations of a +// failed job titled workflows.warning_annotation; a workflow uses them to +// report only what matters, like the output of checkpatch, instead of the +// end of its log. It returns "" when the job has none or they cannot be +// read for lack of permission. +func (p *Pipeline) errorAnnotations(ctx context.Context, runID int64, + j gh.Job) (string, error) { + title := p.Cfg.Workflows.WarningAnnotation + if title == "" { + return "", nil + } + // The check run of a job has the ID of the job. + notes, err := p.gh().Annotations(ctx, j.ID) + if code := httpx.StatusCode(err); code == http.StatusForbidden || + code == http.StatusNotFound { + p.warnf("Run %d: cannot read the annotations of job %d (%s); reporting its "+ + "log (the GitHub App needs Checks: read-only): %v", runID, j.ID, j.Name, err) + return "", nil + } + if err != nil { + return "", err + } + var msgs []string + for _, a := range notes { + if a.Level == "failure" && a.Title == title { + msgs = append(msgs, strings.TrimRight(a.Message, "\n")) + } } - return strings.Join(lines[:n], "\n") + - fmt.Sprintf("\n... %d more lines, see the workflow run.", len(lines)-n) + return strings.Join(msgs, "\n"), nil } diff --git a/internal/pipeline/annotations_test.go b/internal/pipeline/annotations_test.go index 48eb8670..b3b33d64 100644 --- a/internal/pipeline/annotations_test.go +++ b/internal/pipeline/annotations_test.go @@ -4,6 +4,7 @@ package pipeline import ( + "fmt" "strings" "testing" "time" @@ -86,6 +87,161 @@ func TestWarningAnnotationsDisabled(t *testing.T) { } } +func TestWarningAnnotationIsCapped(t *testing.T) { + var lines []string + for i := range 150 { + lines = append(lines, fmt.Sprintf("WARNING: line %d", i)) + } + e, _ := annotatedRun(t, gh.Annotation{Level: "warning", Title: "leadtest", + Message: strings.Join(lines, "\n")}) + e.cfg.Report.MaxLines = 100 + e.step() + r := checkpatchRun(e) + if !strings.HasSuffix(r.Details, "WARNING: line 99\n... 50 more lines, see the workflow run.") { + t.Fatalf("details:\n%s", r.Details) + } + + // Each line has 201 characters with its newline, so 99 of them fit in + // maxReportChars. + long := strings.Repeat("WARNING: "+strings.Repeat("x", 191)+"\n", 120) + e, _ = annotatedRun(t, gh.Annotation{Level: "warning", Title: "leadtest", + Message: long}) + e.step() + r = checkpatchRun(e) + if !strings.HasSuffix(r.Details, "x\n... 21 more lines, see the workflow run.") || + strings.Count(r.Details, "WARNING: x") != 99 { + t.Fatalf("details (%d warnings): ends %q", strings.Count(r.Details, "WARNING: x"), + r.Details[max(0, len(r.Details)-80):]) + } +} + +// failedCheckpatch finishes a failed Checkpatch run of patch 6001 whose +// job has the given log and annotations. +func failedCheckpatch(t *testing.T, log string, notes ...gh.Annotation) *env { + e := newEnv(t, "") + e.pw.addSeries(60, 1, "lorem", e.now) + e.step() + id := e.gh.startRuns("series_60", "sha-6001", "Checkpatch")[0] + e.gh.jobs[id] = []gh.Job{{ID: 61, Name: "checkpatch", Conclusion: "failure", + Steps: []gh.Step{{Name: "Run checkpatch", Conclusion: "failure"}}}} + e.gh.logs[61] = log + e.gh.annotations[61] = notes + e.gh.finishRun(id, "failure") + return e +} + +const checkpatchLog = "2026-03-10T12:00:00.1Z \x1b[36;1mexit \"$status\"\x1b[0m\n" + + "2026-03-10T12:00:00.2Z ERROR: Author should not be mailing list.\n" + + "2026-03-10T12:00:00.3Z ##[error]Process completed with exit code 1.\n" + +func TestErrorAnnotationReplacesLog(t *testing.T) { + e := failedCheckpatch(t, checkpatchLog, + gh.Annotation{Level: "failure", Title: "leadtest", + Message: "== Checking \"patch.mbox\" ==\nERROR: Author should not be mailing " + + "list.\nLines checked: 121, Warnings: 0, Errors: 1\n"}, + gh.Annotation{Level: "failure", Message: "Process completed with exit code 1."}, + gh.Annotation{Level: "warning", Title: "leadtest", Message: "WARNING: ipsum"}) + e.step() + report := string(e.mail.sent[len(e.mail.sent)-2].Data) + reply := string(e.mail.sent[len(e.mail.sent)-1].Data) + for name, mail := range map[string]string{"report": report, "reply": reply} { + if !strings.Contains(mail, "|fail| pw6001") && name == "report" || + !strings.Contains(mail, "checkpatch: failed at step \"Run checkpatch\"") || + !strings.Contains(mail, "Errors of \"checkpatch\":\r\n== Checking \"patch.mbox\""+ + " ==\r\nERROR: Author should not be mailing list.\r\nLines checked: 121, "+ + "Warnings: 0, Errors: 1\r\n") || + strings.Contains(mail, "log lines") || strings.Contains(mail, "exit code") || + strings.Contains(mail, "\x1b") || strings.Contains(mail, "WARNING: ipsum") { + t.Errorf("%s:\n%s", name, mail) + } + } +} + +func TestErrorAnnotationsOfAJobAreJoined(t *testing.T) { + e := failedCheckpatch(t, checkpatchLog, + gh.Annotation{Level: "failure", Title: "leadtest", Message: "ERROR: lorem\n"}, + gh.Annotation{Level: "failure", Title: "leadtest", Message: "ERROR: ipsum"}) + e.step() + report := string(e.mail.sent[len(e.mail.sent)-2].Data) + if !strings.Contains(report, "Errors of \"checkpatch\":\r\nERROR: lorem\r\n"+ + "ERROR: ipsum\r\n") { + t.Errorf("report:\n%s", report) + } +} + +// Errors are cut by the limits of the whole report. +func TestErrorAnnotationIsCapped(t *testing.T) { + var lines []string + for i := range 150 { + lines = append(lines, fmt.Sprintf("ERROR: line %d", i)) + } + e := failedCheckpatch(t, checkpatchLog, gh.Annotation{Level: "failure", + Title: "leadtest", Message: strings.Join(lines, "\n")}) + e.cfg.Report.MaxLines = 100 + e.step() + // The report starts with 4 lines before the errors. + report := string(e.mail.sent[len(e.mail.sent)-2].Data) + if !strings.Contains(report, "ERROR: line 95\r\n... 54 more lines, see the workflow run.") || + strings.Contains(report, "ERROR: line 96") { + t.Errorf("report:\n%s", report) + } + + long := strings.Repeat("ERROR: "+strings.Repeat("x", 193)+"\n", 120) + e = failedCheckpatch(t, checkpatchLog, gh.Annotation{Level: "failure", + Title: "leadtest", Message: long}) + e.step() + report = string(e.mail.sent[len(e.mail.sent)-2].Data) + n := strings.Count(report, "ERROR: x") + if !strings.Contains(report, "x\r\n... "+fmt.Sprint(120-n)+" more lines, see the "+ + "workflow run.") || n < 90 || n*201 > maxReportChars { + t.Errorf("report (%d errors):\n%s", n, report) + } +} + +func TestErrorAnnotationFallsBackToLog(t *testing.T) { + note := gh.Annotation{Level: "failure", Title: "leadtest", Message: "ERROR: lorem"} + cases := map[string]func(e *env){ + "no annotation": func(e *env) { e.gh.annotations[61] = nil }, + "no permission": func(e *env) { e.gh.annotationErr = &httpx.StatusError{Code: 403} }, + "not found": func(e *env) { e.gh.annotationErr = &httpx.StatusError{Code: 404} }, + "empty message": func(e *env) { + e.gh.annotations[61] = []gh.Annotation{{Level: "failure", Title: "leadtest"}} + }, + "disabled": func(e *env) { e.cfg.Workflows.WarningAnnotation = "" }, + } + for name, setup := range cases { + e := failedCheckpatch(t, checkpatchLog, note) + setup(e) + e.step() + report := string(e.mail.sent[len(e.mail.sent)-2].Data) + if !strings.Contains(report, "Last 25 log lines of \"checkpatch\":") || + strings.Contains(report, "Errors of") { + t.Errorf("%s: report:\n%s", name, report) + } + if name == "disabled" && e.gh.annotationCalls != 0 { + t.Errorf("disabled: %d annotation calls", e.gh.annotationCalls) + } + } +} + +func TestErrorAnnotationRetry(t *testing.T) { + e := failedCheckpatch(t, checkpatchLog, + gh.Annotation{Level: "failure", Title: "leadtest", Message: "ERROR: lorem"}) + e.gh.fail["annotations"] = 1 + e.step() + r := e.series(60).Patches[0].Run(state.RunPush, "Checkpatch") + if r.Final.Email != "" || r.Failure == nil || r.Failure.Op != "logs" { + t.Fatalf("a transient error must delay the report: %+v", r) + } + e.advance(10 * time.Minute) + e.step() + report := string(e.mail.sent[len(e.mail.sent)-2].Data) + if r.Final.Email == "" || !strings.Contains(report, "Errors of \"checkpatch\":\r\n"+ + "ERROR: lorem\r\n") { + t.Errorf("run = %+v, report:\n%s", r, report) + } +} + func TestAnnotationErrors(t *testing.T) { notes := gh.Annotation{Level: "warning", Title: "leadtest", Message: "WARNING: lorem"} e, _ := annotatedRun(t, notes) diff --git a/internal/pipeline/autotest.go b/internal/pipeline/autotest.go new file mode 100644 index 00000000..8cd73195 --- /dev/null +++ b/internal/pipeline/autotest.go @@ -0,0 +1,108 @@ +package pipeline + +import ( + "regexp" + "strings" +) + +const autotestSummary = "## Summary of the failures. ##" + +// autotestEntryRe matches a test in the lists of a summary: +// +// 977: ovn-northd.at:22477 lr_in_admission cr-port guard ... +var autotestEntryRe = regexp.MustCompile(`^\s*(\d+): (\S+)\s+(.*\S)\s*$`) + +// autotestTests finds the failed tests in the testsuite.log files of +// Autotest test suites, as printed in a job log when the tests fail. +// A job can run several test suites, so it reads every testsuite.log. +// The log of each test is its part of "Detailed failed tests", which +// ends with the check that failed. +func autotestTests(log string) []failedTest { + var tests []failedTest + seen := map[string]bool{} + for i := 0; ; { + k := strings.Index(log[i:], autotestSummary) + if k < 0 { + return tests + } + i = lineEnd(log, i+k) + end := len(log) + if k := strings.Index(log[i:], autotestSummary); k >= 0 { + end = i + k + } + for _, t := range autotestFailures(log[i:end]) { + if !seen[t.Name] { + seen[t.Name] = true + tests = append(tests, t) + } + } + } +} + +// autotestFailures reads the failed tests and unexpected passes in log, +// which starts after the heading of a summary of the failures: +// +// Failed tests: +// ovn 26.09.90 test suite test groups: +// +// NUM: FILE-NAME:LINE TEST-GROUP-NAME +// KEYWORDS +// +// 977: ovn-northd.at:22477 lr_in_admission cr-port guard ... +// 1168: ovn-controller.at:732 features -- parallelization=yes +// features +// +// Skipped tests: +// ... +// +// ## ---------------------- ## +// ## Detailed failed tests. ## +// ## ---------------------- ## +func autotestFailures(log string) []failedTest { + var tests []failedTest + var starts, stops []string + listing := false + i := 0 + for i < len(log) { + end := lineEnd(log, i) + line := cleanLines(log[i:end]) + i = end + if strings.HasPrefix(line, "## ") && !strings.HasPrefix(line, "## -") { + break + } + switch line { + case "Failed tests:", "Unexpected passes:": + listing = true + continue + case "Skipped tests:": + listing = false + continue + } + if m := autotestEntryRe.FindStringSubmatch(line); listing && m != nil { + tests = append(tests, failedTest{ + Name: m[1] + ": " + m[3] + " (" + m[2] + ")", + Tail: true, + }) + starts = append(starts, m[1]+". "+m[2]+": testing ") + stops = append(stops, m[1]+". "+m[2]+": "+m[1]+". ") + } + } + // A test's details run from its "testing" line to its result line: + // + // 977. ovn-northd.at:22477: testing lr_in_admission ... + // ... + // 977. ovn-northd.at:22477: 977. lr_in_admission ... FAILED (...) + details := log[i:] + for k := range tests { + start := strings.Index(details, starts[k]) + if start < 0 { + continue + } + stop := strings.Index(details[start:], stops[k]) + if stop < 0 { + continue + } + tests[k].Log = cleanLines(details[lineStart(details, start):lineEnd(details, start+stop)]) + } + return tests +} diff --git a/internal/pipeline/autotest_test.go b/internal/pipeline/autotest_test.go new file mode 100644 index 00000000..5b1299b1 --- /dev/null +++ b/internal/pipeline/autotest_test.go @@ -0,0 +1,178 @@ +package pipeline + +import ( + "context" + "reflect" + "strings" + "testing" + + "leadtestkit/internal/gh" + "leadtestkit/internal/state" +) + +// autotestLog is trimmed from the log of an OVN "Build and Test" job. +var autotestLog = strings.ReplaceAll(`T 977: lr_in_admission guard -- parallelization=yes FAILED (ovn-northd.at:22477) +T + cat tests/testsuite.log +T ## ------------- ## +T ## Test results. ## +T ## ------------- ## +T +T ERROR: 823 tests were run, +T 2 failed unexpectedly. +T ## ------------------------ ## +T ## Summary of the failures. ## +T ## ------------------------ ## +T Failed tests: +T ovn 26.09.90 test suite test groups: +T +T NUM: FILE-NAME:LINE TEST-GROUP-NAME +T KEYWORDS +T +T 977: ovn-northd.at:22477 lr_in_admission guard -- parallelization=yes +T 1168: ovn-controller.at:732 features -- parallelization=yes +T features +T +T Skipped tests: +T ovn 26.09.90 test suite test groups: +T +T NUM: FILE-NAME:LINE TEST-GROUP-NAME +T KEYWORDS +T +T 610: ovn.at:42444 gratuitous arp max timeout +T slowtest unstable +T +T ## ---------------------- ## +T ## Detailed failed tests. ## +T ## ---------------------- ## +T +T # -*- compilation -*- +T 977. ovn-northd.at:22477: testing lr_in_admission guard -- parallelization=yes ... +T ovn-nbctl lr-add lr1 +T ./ovn-northd.at:22477: grep lr_in_admission lr1_lflows +T --- - +T +++ /workspace/ovn-tmp/tests/testsuite.dir/at-groups/977/stdout +T - table=??(lr_in_admission ), priority=55 +T +T 977. ovn-northd.at:22477: 977. lr_in_admission guard -- parallelization=yes (ovn-northd.at:22477): FAILED (ovn-northd.at:22477) +T +T ## ------------- ## +T ## ../config.log ## +T ## ------------- ## +T + timeout -k 5m -v 2h make check 'TESTSUITEFLAGS=-j4 -k unstable' RECHECK=yes +T ## ------------------------ ## +T ## Summary of the failures. ## +T ## ------------------------ ## +T Failed tests: +T ovn 26.09.90 test suite test groups: +T +T NUM: FILE-NAME:LINE TEST-GROUP-NAME +T KEYWORDS +T +T 977: ovn-northd.at:22477 lr_in_admission guard -- parallelization=yes +T +T Unexpected passes: +T ovn 26.09.90 test suite test groups: +T +T NUM: FILE-NAME:LINE TEST-GROUP-NAME +T KEYWORDS +T +T 722: ovn-performance.at:227 ovn-controller incremental processing +T unstable +T +T ## ---------------------- ## +T ## Detailed failed tests. ## +T ## ---------------------- ## +T +T # -*- compilation -*- +T 722. ovn-performance.at:227: testing ovn-controller incremental processing ... +T 722. ovn-performance.at:227: 722. ovn-controller incremental processing (ovn-performance.at:227): UNEXPECTED PASS +`, "T ", "2026-11-25T14:00:01.8555287Z ") + +func TestAutotestTests(t *testing.T) { + want := []failedTest{ + { + Name: "977: lr_in_admission guard -- parallelization=yes (ovn-northd.at:22477)", + Log: `977. ovn-northd.at:22477: testing lr_in_admission guard -- parallelization=yes ... +ovn-nbctl lr-add lr1 +./ovn-northd.at:22477: grep lr_in_admission lr1_lflows +--- - ++++ /workspace/ovn-tmp/tests/testsuite.dir/at-groups/977/stdout +- table=??(lr_in_admission ), priority=55 + +977. ovn-northd.at:22477: 977. lr_in_admission guard -- parallelization=yes (ovn-northd.at:22477): FAILED (ovn-northd.at:22477)`, + Tail: true, + }, + { + Name: "1168: features -- parallelization=yes (ovn-controller.at:732)", + Tail: true, + }, + { + Name: "722: ovn-controller incremental processing (ovn-performance.at:227)", + Log: `722. ovn-performance.at:227: testing ovn-controller incremental processing ... +722. ovn-performance.at:227: 722. ovn-controller incremental processing (ovn-performance.at:227): UNEXPECTED PASS`, + Tail: true, + }, + } + for _, log := range []string{autotestLog, strings.ReplaceAll(autotestLog, "\n", "\r\n")} { + if got := autotestTests(log); !reflect.DeepEqual(got, want) { + t.Errorf("autotestTests =\n%#v\nwant\n%#v", got, want) + } + } + + all := strings.Index(autotestLog, "## Summary") + for _, log := range []string{"", autotestLog[:all]} { + if got := autotestTests(log); got != nil { + t.Errorf("autotestTests(%q) = %#v, want none", log, got) + } + } +} + +func TestCapLogEnd(t *testing.T) { + text := "lorem\nipsum\ndolor\nsit\n" + for _, tc := range []struct { + maxLines int + want string + }{ + {4, "lorem\nipsum\ndolor\nsit"}, + {9, "lorem\nipsum\ndolor\nsit"}, + {2, "... 2 earlier lines, see the workflow run.\ndolor\nsit"}, + {1, "... 3 earlier lines, see the workflow run.\nsit"}, + } { + if got := capLogEnd(text, tc.maxLines); got != tc.want { + t.Errorf("capLogEnd(%d) = %q, want %q", tc.maxLines, got, tc.want) + } + } +} + +func TestFailureLogsAutotest(t *testing.T) { + e := newEnv(t, "") + e.cfg.Report.WorkflowLogsFormat = map[string]string{"Build and Test": "autotest"} + e.cfg.Report.MaxTestLines = 3 + e.cfg.Report.MaxTests = 1 + e.gh.jobs[77] = []gh.Job{{ID: 100, Name: "linux", Conclusion: "failure"}} + e.gh.logs[100] = autotestLog + + "2026-11-25T14:01:39.0962814Z ##[error]Process completed with exit code 1.\n" + got, err := e.p.failureLogs(context.Background(), + &state.Run{ID: 77, Workflow: "build and test"}) + if err != nil { + t.Fatal(err) + } + want := `Failed jobs: + linux: failure + +Failed tests in "linux": + 977: lr_in_admission guard -- parallelization=yes (ovn-northd.at:22477) + 1168: features -- parallelization=yes (ovn-controller.at:732) + 722: ovn-controller incremental processing (ovn-performance.at:227) + +977: lr_in_admission guard -- parallelization=yes (ovn-northd.at:22477) +... 5 earlier lines, see the workflow run. +- table=??(lr_in_admission ), priority=55 + +977. ovn-northd.at:22477: 977. lr_in_admission guard -- parallelization=yes (ovn-northd.at:22477): FAILED (ovn-northd.at:22477) +... 1 more failed test, see the workflow run. +` + if got != want { + t.Errorf("failureLogs =\n%s\nwant\n%s", got, want) + } +} diff --git a/internal/pipeline/ginkgo.go b/internal/pipeline/ginkgo.go new file mode 100644 index 00000000..bf6a8ae4 --- /dev/null +++ b/internal/pipeline/ginkgo.go @@ -0,0 +1,107 @@ +package pipeline + +import ( + "regexp" + "strings" +) + +var ( + ginkgoSummaryRe = regexp.MustCompile(`^Summarizing \d+ Failures?:$`) + ansiPrefixRe = regexp.MustCompile(`^(\x1b\[[0-9;]*m)+`) +) + +// ginkgoStates start the lines of the failed specs in a Ginkgo summary. +var ginkgoStates = []string{"[FAIL]", "[PANICKED!]", "[TIMEDOUT]", "[ABORTED]", "[INTERRUPTED]"} + +// ginkgoTests finds the failed specs in the summaries that Ginkgo prints +// at the end of a test suite: +// +// Summarizing 1 Failure: +// [FAIL] Network Segmentation UDN Pod [It] should react to ... +// /home/runner/.../test/e2e/network_segmentation.go:2388 +// +// The log of each spec is the report that Ginkgo printed when it +// failed, with its error. +func ginkgoTests(log string) []failedTest { + var tests []failedTest + for i := 0; ; { + k := strings.Index(log[i:], "Summarizing ") + if k < 0 { + return tests + } + at := lineStart(log, i+k) + i = lineEnd(log, i+k) + if ginkgoSummaryRe.MatchString(strings.TrimSpace(cleanLines(log[at:i]))) { + tests = append(tests, ginkgoSummary(log, at, i)...) + } + } +} + +// ginkgoSummary reads the failed specs of the summary at log[at:], whose +// lines start at log[i:]. +func ginkgoSummary(log string, at, i int) []failedTest { + var tests []failedTest + for i < len(log) { + end := lineEnd(log, i) + line := strings.TrimSpace(cleanLines(log[i:end])) + if line == "" { + break + } + for _, s := range ginkgoStates { + if !strings.HasPrefix(line, s+" ") { + continue + } + t := failedTest{Name: strings.TrimPrefix(line, s+" ")} + // The name as in the log, with its color codes. + raw := strings.TrimRight(log[i:end], "\r\n") + raw = raw[strings.Index(raw, s)+len(s):] + raw = strings.TrimPrefix(ansiPrefixRe.ReplaceAllString(raw, ""), " ") + t.Log = ginkgoReport(log[:at], raw, t.Name) + if t.Log == "" && end < len(log) { + t.Log = strings.TrimSpace(cleanLines(log[end:lineEnd(log, end)])) + } + tests = append(tests, t) + break + } + i = end + } + return tests +} + +// ginkgoReport finds in log the report that Ginkgo printed when the spec +// failed, which starts with its state and name, as raw in the summary: +// +// - [FAILED] [70.239 seconds] +// Network Segmentation UDN Pod [It] should react to ... +// /home/runner/.../test/e2e/network_segmentation.go:2277 +// +// [FAILED] Timed out after 5.000s. +// ... +// ------------------------------ +// +// It returns the report after the name, or "" if there is none. +func ginkgoReport(log, raw, name string) string { + if raw == "" { + return "" + } + for end := len(log); ; { + k := strings.LastIndex(log[:end], raw) + if k < 0 { + return "" + } + end = k + start, next := lineStart(log, k), lineEnd(log, k) + if strings.TrimSpace(cleanLines(log[start:next])) != name || start == 0 { + continue + } + prev := strings.TrimSpace(cleanLines(log[lineStart(log, start-1):start])) + if !strings.HasPrefix(prev, "• [") { + continue + } + stop := strings.Index(log[next:], "------------------------------") + if stop < 0 { + stop = len(log) - next + } + return strings.TrimRight(cleanLines(log[next:lineStart(log, next+stop)]), "\n") + } +} diff --git a/internal/pipeline/ginkgo_test.go b/internal/pipeline/ginkgo_test.go new file mode 100644 index 00000000..1d3a1ba1 --- /dev/null +++ b/internal/pipeline/ginkgo_test.go @@ -0,0 +1,117 @@ +package pipeline + +import ( + "context" + "reflect" + "strings" + "testing" + + "leadtestkit/internal/gh" + "leadtestkit/internal/state" +) + +// ginkgoLog is trimmed from the log of an ovn-kubernetes e2e job, with +// a second failed spec added. +var ginkgoLog = strings.ReplaceAll(strings.ReplaceAll(`T Running Suite: E2e Suite +T ^[[0mNetwork Segmentation ^[[38;5;243mUDN Pod ^[[38;5;9m^[[1m[It] should react to annotations changes^[[0m ^[[38;5;204m[Feature:NetworkSegmentation]^[[0m +T ^[[38;5;243m/src/test/e2e/network_segmentation.go:2277^[[0m +T ^[[1mSTEP:^[[0m Creating a kubernetes client ^[[38;5;243m@ 11/30/26 09:42:30.961^[[0m +T ^[[38;5;9m[FAILED]^[[0m in [It] - /src/test/e2e/network_segmentation.go:2388 ^[[38;5;243m@ 11/30/26 09:43:40.249^[[0m +T ^[[38;5;9m• [FAILED] [70.239 seconds]^[[0m +T ^[[0mNetwork Segmentation ^[[38;5;243mUDN Pod ^[[38;5;9m^[[1m[It] should react to annotations changes^[[0m ^[[38;5;204m[Feature:NetworkSegmentation]^[[0m +T ^[[38;5;243m/src/test/e2e/network_segmentation.go:2277^[[0m +T +T ^[[38;5;9m[FAILED] Timed out after 5.000s. +T Expected +T : false +T to be true^[[0m +T ^[[38;5;9mIn ^[[1m[It]^[[0m^[[38;5;9m at: ^[[1m/src/test/e2e/network_segmentation.go:2388^[[0m ^[[38;5;243m@ 11/30/26 09:43:40.249^[[0m +T +T ^[[38;5;243m------------------------------^[[0m +T ^[[38;5;10m•^[[0m +T +T ^[[38;5;9m^[[1mSummarizing 2 Failures:^[[0m +T ^[[38;5;9m[FAIL]^[[0m ^[[0mNetwork Segmentation ^[[38;5;243mUDN Pod ^[[38;5;9m^[[1m[It] should react to annotations changes^[[0m ^[[38;5;204m[Feature:NetworkSegmentation]^[[0m +T ^[[38;5;243m/src/test/e2e/network_segmentation.go:2388^[[0m +T ^[[38;5;208m[TIMEDOUT]^[[0m ^[[0mLoad Balancer ^[[38;5;208m^[[1m[It] should work^[[0m +T ^[[38;5;243m/src/test/e2e/service.go:42^[[0m +T +T ^[[38;5;9m^[[1mRan 166 of 1120 Specs in 4377.014 seconds^[[0m +T ^[[38;5;9m^[[1mFAIL!^[[0m -- ^[[38;5;10m^[[1m164 Passed^[[0m | ^[[38;5;9m^[[1m2 Failed^[[0m +`, "T ", "2026-11-30T10:18:37.2717875Z "), "^[", "\x1b") + +func TestFailureLogsGinkgo(t *testing.T) { + e := newEnv(t, "") + e.cfg.Report.WorkflowLogsFormat = map[string]string{"ovn-kubernetes": "ginkgo"} + e.cfg.Report.MaxTestLines = 4 + e.gh.jobs[77] = []gh.Job{{ID: 100, Name: "e2e", Conclusion: "failure"}} + e.gh.logs[100] = ginkgoLog + + "2026-11-30T10:18:37.2717875Z ##[error]Process completed with exit code 2.\n" + got, err := e.p.failureLogs(context.Background(), + &state.Run{ID: 77, Workflow: "ovn-kubernetes"}) + if err != nil { + t.Fatal(err) + } + want := `Failed jobs: + e2e: failure + +Failed tests in "e2e": + Network Segmentation UDN Pod [It] should react to annotations changes [Feature:NetworkSegmentation] + Load Balancer [It] should work + +Network Segmentation UDN Pod [It] should react to annotations changes [Feature:NetworkSegmentation] +/src/test/e2e/network_segmentation.go:2277 + + [FAILED] Timed out after 5.000s. + Expected +... 3 more lines, see the workflow run. +Load Balancer [It] should work +/src/test/e2e/service.go:42 +` + if got != want { + t.Errorf("failureLogs =\n%s\nwant\n%s", got, want) + } +} + +func TestGinkgoTests(t *testing.T) { + want := []failedTest{ + { + Name: "Network Segmentation UDN Pod [It] should react to annotations changes [Feature:NetworkSegmentation]", + Log: `/src/test/e2e/network_segmentation.go:2277 + + [FAILED] Timed out after 5.000s. + Expected + : false + to be true + In [It] at: /src/test/e2e/network_segmentation.go:2388 @ 11/30/26 09:43:40.249`, + }, + { + Name: "Load Balancer [It] should work", + Log: "/src/test/e2e/service.go:42", + }, + } + for _, log := range []string{ginkgoLog, strings.ReplaceAll(ginkgoLog, "\n", "\r\n")} { + if got := ginkgoTests(log); !reflect.DeepEqual(got, want) { + t.Errorf("ginkgoTests =\n%#v\nwant\n%#v", got, want) + } + } + + plain := ansiRe.ReplaceAllString(ginkgoLog, "") + if got := ginkgoTests(plain); !reflect.DeepEqual(got, want) { + t.Errorf("ginkgoTests without colors =\n%#v\nwant\n%#v", got, want) + } + + if got := ginkgoTests(ginkgoLog + ginkgoLog); len(got) != 4 { + t.Errorf("ginkgoTests of two suites found %d failed specs, want 4", len(got)) + } + + for _, log := range []string{ + "", + "Summarizing the results\n [FAIL] lorem\n", + strings.ReplaceAll(ginkgoLog, "Summarizing", "Summary of"), + } { + if got := ginkgoTests(log); got != nil { + t.Errorf("ginkgoTests(%q) = %#v, want none", log, got) + } + } +} diff --git a/internal/pipeline/pipeline_test.go b/internal/pipeline/pipeline_test.go index eb2d860a..8885cb0e 100644 --- a/internal/pipeline/pipeline_test.go +++ b/internal/pipeline/pipeline_test.go @@ -141,6 +141,21 @@ func TestApplyFailure(t *testing.T) { } } +func TestApplyFailureIsCapped(t *testing.T) { + e := newEnv(t, "") + e.p.Cfg.Report.MaxLines = 2 + base := &state.Base{Branch: "main", SHA: "0123456789abcdef"} + got := e.p.applyFailure(base, "lorem\nipsum\ndolor\nsit") + want := "Failed to apply on top of main (0123456789ab):\n\n" + + "lorem\nipsum\n... 2 more lines." + if got != want { + t.Errorf("got %q, want %q", got, want) + } + if got := e.p.applyFailure(base, "lorem\nipsum"); !strings.HasSuffix(got, "\n\nlorem\nipsum") { + t.Errorf("got %q", got) + } +} + func TestTransientErrorsAreRetried(t *testing.T) { e := newEnv(t, "") e.pw.addSeries(9, 1, "lorem", e.now) diff --git a/internal/pipeline/reports.go b/internal/pipeline/reports.go index 13041782..b7a12d46 100644 --- a/internal/pipeline/reports.go +++ b/internal/pipeline/reports.go @@ -210,7 +210,7 @@ func (p *Pipeline) reportFinal(ctx context.Context, s *state.Series, } extra := r.Details if hasLogs(r) { - logs, err := p.failureLogs(ctx, r.ID) + logs, err := p.failureLogs(ctx, r) if err != nil { attempts := 0 if r.Failure != nil && r.Failure.Op == "logs" { @@ -328,7 +328,7 @@ func (p *Pipeline) reply(ctx context.Context, s *state.Series, pt *state.Patch, if !ok { extra = r.Details if hasLogs(r) { - logs, err := p.failureLogs(ctx, r.ID) + logs, err := p.failureLogs(ctx, r) if err != nil { p.warnf("%s: replying without build logs: %v", patchName(pt), err) logs = "Build logs are not available: " + err.Error() @@ -527,7 +527,12 @@ func (a *mailAddress) String() string { var logTimestampRe = regexp.MustCompile(`^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z `) -func (p *Pipeline) failureLogs(ctx context.Context, runID int64) (string, error) { +// maxReportChars limits the logs in a report in case of very long lines. +const maxReportChars = 20000 + +func (p *Pipeline) failureLogs(ctx context.Context, r *state.Run) (string, error) { + runID := r.ID + parse := p.logParser(r.Workflow) p.infof("Fetching failed-job details and log excerpts for GitHub run %d.", runID) jobs, err := p.gh().Jobs(ctx, runID) if err != nil { @@ -559,34 +564,227 @@ func (p *Pipeline) failureLogs(ctx context.Context, runID int64) (string, error) fmt.Fprintf(&b, " %s: %s\n", j.Name, j.Conclusion) } } - maxJobs := p.Cfg.Report.MaxLogJobs + rp := p.Cfg.Report + omitted := 0 + shown := map[string]bool{} for i, j := range failed { - if i >= maxJobs { + if i >= rp.MaxLogJobs { + omitted = len(failed) - i p.infof("Run %d: logs limited to %d failed jobs; omitting %d more.", - runID, maxJobs, len(failed)-maxJobs) - fmt.Fprintf(&b, "\nLogs of %d more failed jobs are not included.\n", - len(failed)-maxJobs) + runID, rp.MaxLogJobs, omitted) + break + } + if len(splitLines(b.String())) >= rp.MaxLines || b.Len() >= maxReportChars { + omitted = len(failed) - i + p.infof("Run %d: report is full; omitting the logs of %d more failed jobs.", + runID, omitted) break } - p.infof("Fetching log tail for failed job %d (%s) in run %d.", j.ID, j.Name, runID) + errors, err := p.errorAnnotations(ctx, runID, j) + if err != nil { + return "", err + } + if errors != "" { + fmt.Fprintf(&b, "\nErrors of %q:\n%s\n", j.Name, errors) + continue + } + p.infof("Fetching log for failed job %d (%s) in run %d.", j.ID, j.Name, runID) log, err := p.gh().JobLog(ctx, j.ID) if err != nil { return "", err } - fmt.Fprintf(&b, "\nLast %d log lines of %q:\n", p.Cfg.Report.LogLines, j.Name) - b.WriteString(logTail(log, p.Cfg.Report.LogLines)) - b.WriteString("\n") + log = failedStep(log) + var tests []failedTest + if parse != nil { + tests = parse(log) + } + if len(tests) == 0 { + fmt.Fprintf(&b, "\nLast %d log lines of %q:\n", rp.LogLines, j.Name) + b.WriteString(logTail(log, rp.LogLines) + "\n") + continue + } + fmt.Fprintf(&b, "\nFailed tests in %q:\n", j.Name) + for k, t := range tests { + if k >= rp.MaxListedTests { + fmt.Fprintf(&b, " ... %s, see the workflow run.\n", + plural(len(tests)-k, "more failed test")) + break + } + b.WriteString(" " + t.Name + "\n") + } + var withLogs []failedTest + var skipped []string + for _, t := range tests { + if t.Log != "" && shown[t.Name] { + skipped = append(skipped, t.Name) + } else if t.Log != "" { + withLogs = append(withLogs, t) + } + } + switch { + case len(skipped) == 1: + fmt.Fprintf(&b, "\nSkipping the log of already shown test %s.\n", skipped[0]) + case len(skipped) > 3: + fmt.Fprintf(&b, "\nSkipping the logs of %d already shown tests.\n", len(skipped)) + case len(skipped) > 1: + fmt.Fprintf(&b, "\nSkipping the logs of already shown tests %s.\n", + strings.Join(skipped, ", ")) + } + for k, t := range withLogs { + if k == 0 { + b.WriteString("\n") + } + if k >= rp.MaxTests { + fmt.Fprintf(&b, "... %s, see the workflow run.\n", + plural(len(withLogs)-k, "more failed test")) + break + } + lg := capLog(t.Log, rp.MaxTestLines, 0) + if t.Tail { + lg = capLogEnd(t.Log, rp.MaxTestLines) + } + b.WriteString(t.Name + "\n" + lg + "\n") + shown[t.Name] = true + } + } + report := capLog(b.String(), rp.MaxLines, maxReportChars) + "\n" + if omitted > 0 { + report += fmt.Sprintf("\nThe logs of %s are not included.\n", + plural(omitted, "more failed job")) } - return b.String(), nil + return report, nil } -func logTail(log string, n int) string { - lines := strings.Split(strings.TrimRight(strings.ReplaceAll(log, "\r\n", "\n"), "\n"), "\n") - if len(lines) > n { - lines = lines[len(lines)-n:] +// A failedTest is a failed test found in a job log, with the part of +// the log that tells why it failed, if any. +type failedTest struct { + Name string + Log string + // Tail keeps the end of a long Log, where it has the error, instead + // of its beginning. + Tail bool +} + +// logParsers find the failed tests in a job log, cut by failedStep, for +// each format in config.LogFormats. +var logParsers = map[string]func(log string) []failedTest{ + "ginkgo": ginkgoTests, + "autotest": autotestTests, +} + +// logParser returns the parser of the logs of workflow, or nil if +// report.workflow_logs_format gives it none. +func (p *Pipeline) logParser(workflow string) func(log string) []failedTest { + for wf, f := range p.Cfg.Report.WorkflowLogsFormat { + if strings.EqualFold(wf, workflow) { + return logParsers[f] + } } + return nil +} + +func splitLines(text string) []string { + return strings.Split(strings.TrimSuffix(text, "\n"), "\n") +} + +// capLog keeps the first maxLines lines of text, and the first maxChars +// characters if maxChars is positive, without cutting a line, and notes +// how many lines it left out. The result has no final newline. +func capLog(text string, maxLines, maxChars int) string { + kept, more := capLines(text, maxLines, maxChars) + if more == 0 { + return kept + } + if kept != "" { + kept += "\n" + } + return kept + fmt.Sprintf("... %s, see the workflow run.", + plural(more, "more line")) +} + +// capLines is capLog without the note: it returns the lines kept and +// how many it left out. +func capLines(text string, maxLines, maxChars int) (string, int) { + ls := splitLines(text) + keep, size := 0, 0 + for keep < len(ls) && keep < maxLines { + size += len(ls[keep]) + 1 + if maxChars > 0 && size > maxChars { + break + } + keep++ + } + return strings.Join(ls[:keep], "\n"), len(ls) - keep +} + +// stepEnds start the line that GitHub adds to a job log when a step +// fails. +var stepEnds = []string{ + "##[error]Process completed with exit code", + "##[error]The operation was canceled", +} + +// failedStep returns log up to and including the line that ends the +// first failed step, leaving out the cleanup steps after it, or all of +// log if no step failed. +func failedStep(log string) string { + end := len(log) + for _, s := range stepEnds { + if i := strings.Index(log[:end], s); i >= 0 { + end = i + } + } + if i := strings.IndexByte(log[end:], '\n'); i >= 0 { + return log[:end+i+1] + } + return log +} + +// lineStart returns the start of the line of text that has text[i]. +func lineStart(text string, i int) int { + return strings.LastIndexByte(text[:i], '\n') + 1 +} + +// lineEnd returns the end of the line of text that has text[i], after +// its newline. +func lineEnd(text string, i int) int { + if k := strings.IndexByte(text[i:], '\n'); k >= 0 { + return i + k + 1 + } + return len(text) +} + +var ansiRe = regexp.MustCompile(`\x1b\[[0-9;]*m`) + +// cleanLines removes the carriage returns, timestamps and color codes +// of the lines of a job log. The result has no final newline. +func cleanLines(text string) string { + lines := strings.Split(strings.TrimRight(text, "\r\n"), "\n") for i, l := range lines { - lines[i] = logTimestampRe.ReplaceAllString(l, "") + l = logTimestampRe.ReplaceAllString(strings.TrimSuffix(l, "\r"), "") + lines[i] = ansiRe.ReplaceAllString(l, "") } return strings.Join(lines, "\n") } + +// logTail returns the last n lines of log, cleaned. +// capLogEnd keeps the last maxLines lines of text and notes how many +// lines it left out before them. The result has no final newline. +func capLogEnd(text string, maxLines int) string { + ls := splitLines(text) + if len(ls) <= maxLines { + return strings.Join(ls, "\n") + } + return fmt.Sprintf("... %s, see the workflow run.\n", + plural(len(ls)-maxLines, "earlier line")) + + strings.Join(ls[len(ls)-maxLines:], "\n") +} + +func logTail(log string, n int) string { + log = strings.TrimRight(log, "\r\n") + start := len(log) + for k := 0; k < n && start > 0; k++ { + start = strings.LastIndexByte(log[:start-1], '\n') + 1 + } + return cleanLines(log[start:]) +} diff --git a/internal/pipeline/reports_test.go b/internal/pipeline/reports_test.go new file mode 100644 index 00000000..8f6556de --- /dev/null +++ b/internal/pipeline/reports_test.go @@ -0,0 +1,297 @@ +package pipeline + +import ( + "context" + "fmt" + "slices" + "strings" + "testing" + + "leadtestkit/internal/config" + "leadtestkit/internal/gh" + "leadtestkit/internal/state" +) + +func numbered(prefix string, n int) string { + var b strings.Builder + for i := 1; i <= n; i++ { + fmt.Fprintf(&b, "%s %d\n", prefix, i) + } + return b.String() +} + +func TestCapLog(t *testing.T) { + text := "lorem\nipsum\ndolor\nsit\n" + for _, tc := range []struct { + maxLines, maxChars int + want string + }{ + {4, 0, "lorem\nipsum\ndolor\nsit"}, + {9, 0, "lorem\nipsum\ndolor\nsit"}, + {2, 0, "lorem\nipsum\n... 2 more lines, see the workflow run."}, + {9, 12, "lorem\nipsum\n... 2 more lines, see the workflow run."}, + {9, 11, "lorem\n... 3 more lines, see the workflow run."}, + {9, 3, "... 4 more lines, see the workflow run."}, + } { + if got := capLog(text, tc.maxLines, tc.maxChars); got != tc.want { + t.Errorf("capLog(%d, %d) = %q, want %q", tc.maxLines, tc.maxChars, got, tc.want) + } + } +} + +func TestFailedStep(t *testing.T) { + for _, tc := range []struct{ log, want string }{ + {"lorem\nipsum\n", "lorem\nipsum\n"}, + {"lorem\r\nZ ##[error]Process completed with exit code 1.\r\nipsum\r\n", + "lorem\r\nZ ##[error]Process completed with exit code 1.\r\n"}, + {"##[error]Process completed with exit code 1.\nipsum\n", + "##[error]Process completed with exit code 1.\n"}, + {"lorem\n##[error]The operation was canceled.\nipsum\n" + + "##[error]Process completed with exit code 1.\n", + "lorem\n##[error]The operation was canceled.\n"}, + {"lorem\n##[error]Process completed with exit code 1.", + "lorem\n##[error]Process completed with exit code 1."}, + } { + if got := failedStep(tc.log); got != tc.want { + t.Errorf("failedStep(%q) = %q, want %q", tc.log, got, tc.want) + } + } +} + +func TestLogTail(t *testing.T) { + log := "2026-03-10T12:00:00.1234567Z lorem\r\n" + + "2026-03-10T12:00:00Z \x1b[38;5;9m\x1b[1mipsum\x1b[0m\r\n" + + "dolor\r\n\r\n" + for _, tc := range []struct { + n int + want string + }{ + {1, "dolor"}, + {2, "ipsum\ndolor"}, + {3, "lorem\nipsum\ndolor"}, + {9, "lorem\nipsum\ndolor"}, + } { + if got := logTail(log, tc.n); got != tc.want { + t.Errorf("logTail(%d) = %q, want %q", tc.n, got, tc.want) + } + } + if got := logTail("", 3); got != "" { + t.Errorf("logTail of an empty log = %q", got) + } +} + +// setLogParser makes parse the parser of the logs of workflow. +func setLogParser(t *testing.T, e *env, workflow string, + parse func(string) []failedTest) { + logParsers["lorem-format"] = parse + t.Cleanup(func() { delete(logParsers, "lorem-format") }) + e.cfg.Report.WorkflowLogsFormat = map[string]string{workflow: "lorem-format"} +} + +func TestLogParsers(t *testing.T) { + for _, f := range config.LogFormats { + if logParsers[f] == nil { + t.Errorf("no parser for log format %q", f) + } + } + for f := range logParsers { + if !slices.Contains(config.LogFormats, f) { + t.Errorf("log format %q is missing from config.LogFormats", f) + } + } +} + +func TestFailureLogsLimits(t *testing.T) { + ctx := context.Background() + e := newEnv(t, "") + e.cfg.Report.MaxTestLines = 3 + e.cfg.Report.MaxTests = 2 + e.cfg.Report.MaxListedTests = 2 + e.cfg.Report.LogLines = 4 + e.gh.jobs[77] = []gh.Job{ + {ID: 100, Name: "tests", Conclusion: "failure"}, + {ID: 101, Name: "build", Conclusion: "failure"}, + } + run := &state.Run{ID: 77, Workflow: "lorem tests"} + e.gh.logs[100] = "TESTS\n" + e.gh.logs[101] = numbered("2026-03-10T12:00:00.1234567Z build", 10) + + "2026-03-10T12:00:00.1234567Z ##[error]Process completed with exit code 2.\n" + + numbered("2026-03-10T12:00:00.1234567Z cleanup", 3) + setLogParser(t, e, "Lorem Tests", func(log string) []failedTest { + if log != "TESTS\n" { + return nil + } + return []failedTest{ + {Name: "lorem", Log: numbered("lorem", 5)}, + {Name: "ipsum", Log: numbered("ipsum", 2)}, + {Name: "dolor", Log: numbered("dolor", 2)}, + } + }) + got, err := e.p.failureLogs(ctx, run) + if err != nil { + t.Fatal(err) + } + want := `Failed jobs: + tests: failure + build: failure + +Failed tests in "tests": + lorem + ipsum + ... 1 more failed test, see the workflow run. + +lorem +lorem 1 +lorem 2 +lorem 3 +... 2 more lines, see the workflow run. +ipsum +ipsum 1 +ipsum 2 +... 1 more failed test, see the workflow run. + +Last 4 log lines of "build": +build 8 +build 9 +build 10 +##[error]Process completed with exit code 2. +` + if got != want { + t.Errorf("failureLogs =\n%s\nwant\n%s", got, want) + } + + e.cfg.Report.MaxLines = 12 + got, err = e.p.failureLogs(ctx, run) + if err != nil { + t.Fatal(err) + } + want = `Failed jobs: + tests: failure + build: failure + +Failed tests in "tests": + lorem + ipsum + ... 1 more failed test, see the workflow run. + +lorem +lorem 1 +lorem 2 +... 6 more lines, see the workflow run. + +The logs of 1 more failed job are not included. +` + if got != want { + t.Errorf("failureLogs with max_lines 12 =\n%s\nwant\n%s", got, want) + } + + e.cfg.Report.MaxLines = 300 + e.cfg.Report.MaxLogJobs = 1 + got, err = e.p.failureLogs(ctx, run) + if err != nil { + t.Fatal(err) + } + want = `Failed jobs: + tests: failure + build: failure + +Failed tests in "tests": + lorem + ipsum + ... 1 more failed test, see the workflow run. + +lorem +lorem 1 +lorem 2 +lorem 3 +... 2 more lines, see the workflow run. +ipsum +ipsum 1 +ipsum 2 +... 1 more failed test, see the workflow run. + +The logs of 1 more failed job are not included. +` + if got != want { + t.Errorf("failureLogs with max_log_jobs 1 =\n%s\nwant\n%s", got, want) + } + + e.cfg.Report.MaxLogJobs = 5 + run.Workflow = "ipsum" + got, err = e.p.failureLogs(ctx, run) + if err != nil { + t.Fatal(err) + } + want = `Failed jobs: + tests: failure + build: failure + +Last 4 log lines of "tests": +TESTS + +Last 4 log lines of "build": +build 8 +build 9 +build 10 +##[error]Process completed with exit code 2. +` + if got != want { + t.Errorf("failureLogs of a workflow without a format =\n%s\nwant\n%s", got, want) + } +} + +func TestFailureLogsShowsTestLogsOnce(t *testing.T) { + ctx := context.Background() + e := newEnv(t, "") + e.gh.jobs[77] = []gh.Job{ + {ID: 100, Name: "lorem job", Conclusion: "failure"}, + {ID: 101, Name: "ipsum job", Conclusion: "failure"}, + {ID: 102, Name: "dolor job", Conclusion: "failure"}, + } + e.gh.logs[100] = "lorem ipsum" + e.gh.logs[101] = "lorem ipsum dolor" + e.gh.logs[102] = "lorem" + setLogParser(t, e, "lorem tests", func(log string) []failedTest { + var tests []failedTest + for _, name := range strings.Fields(log) { + tests = append(tests, failedTest{Name: name, Log: name + " log"}) + } + return tests + }) + got, err := e.p.failureLogs(ctx, &state.Run{ID: 77, Workflow: "lorem tests"}) + if err != nil { + t.Fatal(err) + } + want := `Failed jobs: + lorem job: failure + ipsum job: failure + dolor job: failure + +Failed tests in "lorem job": + lorem + ipsum + +lorem +lorem log +ipsum +ipsum log + +Failed tests in "ipsum job": + lorem + ipsum + dolor + +Skipping the logs of already shown tests lorem, ipsum. + +dolor +dolor log + +Failed tests in "dolor job": + lorem + +Skipping the log of already shown test lorem. +` + if got != want { + t.Errorf("failureLogs =\n%s\nwant\n%s", got, want) + } +} diff --git a/internal/pipeline/schedule.go b/internal/pipeline/schedule.go index aa13354e..49d5f543 100644 --- a/internal/pipeline/schedule.go +++ b/internal/pipeline/schedule.go @@ -573,9 +573,9 @@ func (p *Pipeline) prepare(ctx context.Context, s *state.Series) { p.warnf("%s: failed to apply on %s at %s:\n%s", patchName(pt), base.Branch, short(base.SHA), output) pt.Status = state.PatchApplyFailed - p.notePatch(pt, "apply-failed", "%s", applyFailure(base, output)) + p.notePatch(pt, "apply-failed", "%s", p.applyFailure(base, output)) pt.Runs = append(pt.Runs, - p.applyRun(state.ResultFail, applyFailure(base, output))) + p.applyRun(state.ResultFail, p.applyFailure(base, output))) default: p.infof("%s: not applied because an earlier patch failed.", patchName(pt)) pt.Status = state.PatchNotApplied @@ -668,10 +668,12 @@ func short(sha string) string { return sha } -func applyFailure(base *state.Base, output string) string { - const maxDetails = 4000 - if len(output) > maxDetails { - output = "...\n" + output[len(output)-maxDetails:] +// applyFailure reports a patch that failed to apply, with the git am +// output cut like the logs of failed runs. +func (p *Pipeline) applyFailure(base *state.Base, output string) string { + output, more := capLines(output, p.Cfg.Report.MaxLines, maxReportChars) + if more > 0 { + output += fmt.Sprintf("\n... %s.", plural(more, "more line")) } return fmt.Sprintf("Failed to apply on top of %s (%s):\n\n%s", base.Branch, short(base.SHA), output)