Skip to content

Add Ginkgo v2 agent and ginkgo-rp wrapper (pkg/ginkgo) - #15

Open
That-geeky-shree wants to merge 11 commits into
reportportal:masterfrom
That-geeky-shree:feat/ginkgo-agent
Open

That-geeky-shree wants to merge 11 commits into
reportportal:masterfrom
That-geeky-shree:feat/ginkgo-agent

Conversation

@That-geeky-shree

Copy link
Copy Markdown

Adds a ReportPortal agent for Ginkgo v2, as discussed in reportportal/reportportal#2706.

  • Real-time spec reporting: priorities, test reference IDs, By() steps, logs, attachments, DescribeTable parameters.
  • ginkgo-rp wrapper creates and finalizes the launch; works with -r and -p.
  • Built on pkg/gorp's ReportingClient. Lives in its own Go module (pkg/ginkgo), so goRP's main go.mod is unchanged.
  • Sanity examples in pkg/ginkgo/examples, behind the sanity build tag.

Tested: build, vet, race tests and repo lint config pass. Ran the examples in parallel against a local ReportPortal 5.15.

Open points:

  1. pkg/ginkgo/go.mod has a temporary replace to ../..; it needs removing after a goRP release.
  2. Root task test/task lint don't cover this module. Happy to add CI steps or move the code if you prefer.

@coderabbitai

coderabbitai Bot commented Oct 10, 2026

Copy link
Copy Markdown

Important

  • 🔍 Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

⚙️ Run configuration
  • Configuration used: Repository: reportportal/goRP/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 1d014435-5c02-41b0-be72-594c0754c1a2

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@DzmitryHumianiuk

Copy link
Copy Markdown
Member

Thanks for the contribution — the overall design (wrapper creates/finishes the launch, workers report via ReportBeforeEach/ReportAfterEach, file-based coordination for -p) fits Ginkgo well. I went through the code; a few things need to be addressed before we can merge.

Reporting correctness

  1. testCaseId / codeRef are built from parentUUID + "/" + name and uniqueId is a random UUID (test_listener.go:161-178). The parent UUID changes every launch, so item history, retries and auto-analysis won't work. Please derive them from stable data (package path + container hierarchy + leaf text; codeRef from the leaf node location), and consider mapping TestReference(...) to testCaseId.
  2. By() steps, logs and attachments are created after the spec finishes, all stamped with time.Now() (reporting_node.go:393-403). Steps get zero duration and logs lose their real time. Please use the timeline timestamps from the spec events / report entries and spec.EndTime.
  3. Every By() step is finished with the spec's final status (reporting_node.go:464-469), so one failing step marks all steps as failed.
  4. CapturedGinkgoWriterOutput / CapturedStdOutErr are copied but never sent, so GinkgoWriter output doesn't reach ReportPortal.
  5. Describe/Context items are never finished explicitly — finishSuitesFromResults only finishes top-level suites, although the comments say otherwise.
  6. BeforeSuite/AfterSuite failures: as far as I can see they only flip the launch to FAILED via the exit code, with no item or log. Could you confirm and report them from ReportAfterSuite?

Configuration
7. Config is read only from reportportal.properties. Please support environment variables (at least endpoint, project, API key, launch name) for CI, plus launch attributes, description and mode. Plain Ginkgo labels should be reported as item attributes.

Robustness
8. Cleanup globs in main.go:274-284 (rp_cache_<session>_*, rp-agent-attachments-*<session>*) don't match the real names (rp_cache_<sha256>, rp-agent-attachments-<random>), so these files leak. With -p, CleanupAttachments only runs from ReportAfterSuite, i.e. not in every worker.
9. Suite discovery re-implements Ginkgo's: it requires *_suite_test.go and a string literal in RunSpecs, and rejects paths outside cwd. On a mismatch the worker goes dormant with only a warning. Please fail loudly, and take the suite name from Ginkgo's report rather than parsing sources.
10. Library code calls log.Fatal (NewLaunchCoordinator, InitializeAttachments), which contradicts "reporting must never kill the test process".

Tests / CI / release
11. The root task test / task lint don't cover this module, so the green check doesn't exercise it. Please add CI steps, and tests for the container cache/locking and hierarchy building.
12. The replace directive breaks go install ...@latest; go.mod should require a released goRP version (currently v5.0.0 vs latest v5.2.2).

Smaller notes: string-matching in isRetriableError, --skip-package=rpagent skipping any user package with that substring, flake attempts not reported as RP retries.

Address review feedback on reportportal#15:

- Stable testCaseId, codeRef and uniqueId so History and retries work
- Real timestamps for By() steps, logs and attachments
- Per-step status instead of the spec's final status
- Send GinkgoWriter and stdout output to ReportPortal
- Finish Describe/Context containers explicitly with the right status
- Report BeforeSuite/AfterSuite failures as their own items
- Env-var configuration, launch attributes, description and mode, and Ginkgo labels as item attributes
- Fix temp-file leaks and per-worker cleanup
- Suite discovery follows Ginkgo (any *_test.go calling RunSpecs, paths outside cwd), and a worker whose package was not registered logs an ERROR
- Never kill the test process from library code
- Skip only the agent's own rpagent package instead of any path containing the word
- Mark suites that received no specs as skipped, not failed
- Tests for container cache locking (including across processes) and hierarchy building
@That-geeky-shree

Copy link
Copy Markdown
Author

@DzmitryHumianiuk Thanks for the review. All 12 points are addressed and pushed, checked against a local ReportPortal (including a -p run compared item by item with a sequential one).

  1. Stable identity: testCaseId and codeRef come from package path, container hierarchy, leaf text and location. uniqueId is a deterministic UUID. History now links runs. TestReference stays a testReferenceId attribute: a reference can be shared or edited, identity must not change.
  2. Timestamps: steps, logs and attachments use the real timeline times.
  3. Step status: each By() step has its own status.
  4. Output: GinkgoWriter and stdout are sent.
  5. Containers: Describe/Context items are finished with the right status and end time.
  6. BeforeSuite/AfterSuite: failures are their own items. ReportPortal doesn't count them in launch stats (documented in the README).
  7. Config: RP_* env vars, launch description, attributes and mode, and Ginkgo labels as item attributes.
  8. Leaks: temp files are cleaned up (56 leaked in a test run, now 0).
  9. Suite discovery: it now follows Ginkgo's rule: any *_test.go calling RunSpecs counts, not only *_suite_test.go. Paths outside the working directory are accepted, and symlinks are resolved. The suite name comes from the RunSpecs argument, parsed with go/parser; it handles string literals and package-level constants, even ones defined in another file of the package, and a computed name falls back to the directory name. I didn't take the name from Ginkgo's report: the wrapper creates the launch and suites before any worker starts, and Ginkgo's types.Report only exists inside a worker, after the run has begun. If you'd prefer lazy creation of the suite in the worker from report.SuiteDescription, I can do that, but it costs a more complex race between parallel workers. A package that wasn't registered by the wrapper logs an ERROR … will NOT be reported line from the worker. It doesn't abort the run, in line with point 10 (reporting must never kill the test process).
  10. No log.Fatal in library code.
  11. CI and tests: ginkgo:* Task targets wired into root test, vet, lint and fmt, plus CI steps. New tests cover container-cache locking across real processes and hierarchy building.
  12. replace removed, go.mod requires goRP v5.2.2.

The --skip-package substring bug is fixed too. Two smaller notes are left out of this PR on purpose: typed-error retry detection in isRetriableError, and reporting flake attempts as ReportPortal retries. Neither affects the correctness fixes above. The retry change needs its own design, because attempts have to be linked as retries of one item, and I'd rather not grow an already large PR. Happy to do both as a follow-up, or here if you prefer.

@DzmitryHumianiuk

Copy link
Copy Markdown
Member

Thanks for the quick turnaround — I went through the new head. All 12 points are addressed in code, and build, vet and go test -race pass locally. I haven't run it against a live ReportPortal. Keeping TestReference as an attribute and parsing the suite name from sources are both fine.

This is a large addition to an official client, so I'd like it to be complete before merge rather than followed up later. That includes the two items you proposed to defer.

Previously deferred — please include in this PR

  1. Flake attempts as ReportPortal retries. With --flake-attempts / FlakeAttempts(n) / MustPassRepeatedly(n) the agent reports one item with the final state, so a spec that passed on the third attempt looks like a clean pass. Each attempt should be reported and linked as a retry of the same item (retry / retryOf), using the per-attempt data Ginkgo records in the spec report.
  2. Typed retry detection. isRetriableError still matches substrings of err.Error() ("timeout", "EOF", "connection refused", …). Please classify with errors.Is / errors.As (net.Error with Timeout(), io.EOF / io.ErrUnexpectedEOF, syscall.ECONNREFUSED / ECONNRESET, *net.DNSError, context.DeadlineExceeded) plus the existing *gorp.HTTPError check.

New findings on this pass

  1. Abort path doesn't stop the launch. abortLaunch and the deferred cleanup in createRPLaunchAndSaveState call StopLaunch, which in goRP v5.2.2 hits a non-existent /launch/{id}/stop endpoint. The fix is on master but not in any tag yet. Until a release, please finish the launch via FinishLaunch with status STOPPED.
  2. The wrapper has no signal handling. As far as I can see, on Ctrl-C or a cancelled CI job it exits before finalizing, leaving the launch in progress and temp files behind. Please handle SIGINT/SIGTERM, wait for ginkgo, then finalize and clean up.
  3. ginkgoValueFlags is incomplete (main.go:489-502): --compilers, --ldflags, --coverpkg, single-dash -tags, -label-filter and others are missing, so their values are treated as package paths and the wrapper exits 1 before any test runs. A hand-maintained flag table will keep drifting; please don't fail the run on an unresolvable path.
  4. ReportPortal being down blocks the tests. If the launch can't be created the wrapper returns 1 without running ginkgo, and a failed finalization returns 2 even when tests passed. Tests must still run and the exit code must be ginkgo's (a strict mode can be opt-in).
  5. Suites outside cwd go dormant. Workers look for reportportal.properties upwards from the suite directory, not from where the wrapper found it, so ginkgo-rp ../other/pkg creates the launch and suite but reports nothing. Pass the resolved config to the workers via environment.
  6. Discovery vs Ginkgo. Ginkgo detects a suite by a ginkgo import in *_test.go, not by a RunSpecs call, so the "same rule as Ginkgo" statement isn't accurate. Discovery also ignores --tags and --skip-package, so excluded packages show up as empty SKIPPED suites.
  7. Interrupted specs lose their data. The worker's signal handler finishes active items and deletes them from activeHierarchies; ReportAfterEach then finds no hierarchy, so the interrupted spec's logs, steps and output are dropped and its containers are missing from the wrapper's aggregation.
  8. Test coverage. cmd/ginkgo-rp is at 17.6% and rpagent at 56.1%. With no coverage at all: run, createRPLaunchAndSaveState, aggregateAndFinalizeLaunch, finishSuitesFromResults, parseTargetPathsAndRecursiveFlag, setupExitHandlers, AddAttachment, SendAttachmentLog, LoadRPConfig. Please add an httptest-based test of the full wrapper flow (launch → suites → results → containers → finish, including the abort and RP-down paths) and tests for attachments and config lookup.
  9. Log delivery. Every log line and every By() step is a separate synchronous HTTP request inside the test process. Please batch logs per spec (SaveLogMultipart accepts several entries).
  10. Cleanups. rpagent.Log entries (RP_LOG#…) are still visible in Ginkgo's own report — use ReportEntryVisibilityNever. verboseMode and suiteCache in run() are assigned and unused. The commit "adds integration-guide.html" only removes two README lines; please squash or reword the history.

Questions

  • The README says a retried start request with the same UUID is deduplicated by ReportPortal. Did you verify that against a real instance?
  • Do you truncate testCaseId and item names for very long hierarchies / table entries?

@That-geeky-shree

Copy link
Copy Markdown
Author

@DzmitryHumianiuk Thanks for the review again. All pointers and both deferred items are now in the PR.

  1. Flake attempts: each attempt is now its own item, linked with retry/retryOf to the previous one. A spec that passes on the third try shows PASSED with 2 FAILED retries and counts once. Each attempt keeps its own failure message, output and By() steps. (retryOf must point at the previous attempt. Pointing at the first one double-counted the spec.)
  2. Typed retry detection: isRetriableError now uses errors.Is/errors.As on the types you listed.
  3. Abort: now uses FinishLaunch with STOPPED. ReportPortal turns STOPPED into FAILED while a suite is still open, so the suites are finished first.
  4. Signals: the wrapper handles SIGINT, SIGTERM and SIGHUP. It passes the signal to ginkgo's whole process group, waits, finalizes the launch, cleans up, and exits 130, 143 or 129. A second signal kills it.
  5. Flags: the hand-kept table is gone. Flags are split with Ginkgo's own flag definitions, and an unresolvable path never fails the run.
  6. RP down: the tests always run and the exit code is Ginkgo's. RP_STRICT=true makes reporting failures fail the run.
  7. Suites outside cwd: the wrapper passes the config file it used to the workers via RP_CONFIG_FILE.
  8. Discovery: it now follows Ginkgo's real rule and respects --tags and --skip-package. The README is corrected.
  9. Interrupted specs: the signal handler no longer deletes the spec's data. The interrupted spec now shows as INTERRUPTED with its message, logs and steps.
  10. Coverage: cmd/ginkgo-rp 17.6% → 62%, rpagent 56.1% → 73%. There is a full wrapper-flow test against a fake RP server and a real Ginkgo suite. It covers the normal run, a failing run, abort, RP down, strict mode, a failing finalization, signals, and attachments.
  11. Logs: one batch per spec. By() steps and attachments are still separate requests.
  12. Cleanups: RP_LOG# entries are hidden with ReportEntryVisibilityNever, and the unused variables are removed. I'll squash and reword the history once you confirm there are no more changes, so I don't rewrite it under your review.

Your questions

  • Same-UUID dedupe: yes, I checked it on a real instance. A repeated start request returns the same ID and one item is stored.
  • Truncation: not before, now yes. ReportPortal rejects item names over 1024 characters (HTTP 400), so longer names are cut and end in .... It silently cuts a testCaseId at 1024, so a longer one is cut and gets ~ plus a short hash of the full ID, keeping it unique and stable.

@DzmitryHumianiuk

Copy link
Copy Markdown
Member

Thanks, this is a big step forward. I reviewed f79ab09:

  • build, vet and go mod tidy -diff are clean;
  • go test -race passes, with 62.2% coverage for cmd/ginkgo-rp and 73.1% for rpagent;
  • all TestWrapper* e2e tests actually run.

I also ran it against a live ReportPortal (API 6.0.0) in three modes: sequential, -p --procs=4, and a run interrupted with SIGINT.

What works on a live instance

  • Hierarchy, By() steps as nested no-stats steps with their own status and logs, stable testCaseId/codeRef/uniqueId, attachments, Log(), Skip/Pending, DescribeTable, launch attributes.
  • -p produces the same tree and statistics as a sequential run, and containers are not duplicated.
  • FlakeAttempts with the failure in the It: two FAILED retries and a PASSED final item. Each attempt has its own GinkgoWriter output, By() step and failure message, and the spec counts once.
  • SIGINT: exit code 130, the running spec is INTERRUPTED with its logs, the launch is closed, and no processes are left behind.
  • Names over 1024 characters and the ~hash testCaseId suffix behave as described.

Where the agent stands against the Java agents

I compared the agent with client-java + agent-java-testng and with the ReportPortal server code. Legend: ✅ done · ❌ must fix in this PR (numbered items below) · ➡️ follow-up PR.

Capability Java (client-java + TestNG agent) Ginkgo agent (f79ab09) Status
Stable identity (testCaseId / codeRef / uniqueId) codeRef[params], no uniqueId pkg > containers > It, file:line, UUIDv5 uniqueId ✅; ❌ #7 pin uniqueId in a test
Nested steps @Step, hasStats=false By() as nested steps, own status and logs ✅
Retries retry=true + NOT_ISSUE on the failed attempt explicit retry / retryOf chain ✅ for It failures; ❌ #1 failures in AfterEach/DeferCleanup; ❌ #2 MustPassRepeatedly
Skipped issue rp.skipped.issue, skippedIssue system attribute none: SKIPPED and pending become To Investigate ❌ #6
Launch attributes, description, mode rp.attributes, rp.description, rp.mode same keys; mode is validated ✅
Logs, levels, attachments batched multipart, emitLog from any thread batch per spec, Log(), AddAttachment() ✅; ❌ #3 RP_ATTACHMENT# printed in the console
Item attributes @Attributes labels, rp.ref, priority ❌ #4 priority:P1 on every spec; ➡️ map key:value labels to key/value attributes
Parallel processes rp.client.join (file lock) wrapper owns the launch, -p workers share it ✅
Error isolation reporting never fails tests same, RP_STRICT opt-in ✅
HTTP retries and idempotency effectively none worker: 3 attempts, same item UUID on retry ✅, better than Java
Interrupt / abort shutdown hook finishes the launch signals forwarded, launch finalized ✅; ❌ #5 finalization deadline; ➡️ #11 job control
Name / testCaseId limits client-side truncation name 1024, testCaseId with hash ✅
Launch link UUID only dead code on 6.x ❌ #8
Docs per-attempt stdout, discovery wording ❌ #9, #10
Join an existing launch (multi-job) rp.launch.uuid + rp.launch.uuid.creation.skip none ➡️
Rerun rp.rerun, rp.rerun.of none ➡️
System attributes agent, os, jvm none ➡️ agent, os, go (skippedIssue is part of #6)
NOT_ISSUE on non-final failed attempts yes no ➡️
Real table parameters data provider values parsed from key='value' in the Entry text ➡️ explicit rpagent.Param(k, v) label
codeRef Class.method, no line file:line ➡️ drop the line number (not part of identity)
Config parity all rp.* keys, -D > env > file 8 keys, env > file ➡️ rp.batch.size.logs, rp.http.timeout.*, rp.enable, …
Reporting off the spec's wall time async (Rx) synchronous in the hooks ➡️

The items below still need fixing in this PR.

1. A failure in AfterEach / DeferCleanup / AfterAll is lost for earlier attempts (confirmed live)
With FlakeAttempts(2) and an AfterEach that fails on attempt 1, the retry item shows Location: :0 … attempt failed (details were not captured). The JustAfterEach in rpagent/reporting_node.go:169 runs before those nodes, so it cannot see their failure.

The README premise is also wrong: "Ginkgo does not keep the failure message of an earlier attempt". It does. In ginkgo/v2/internal/group.go (v2.26.0, the attempt loop in run), every failed attempt except the last is appended to SpecReport.AdditionalFailures as "Failure recorded during attempt N:\n…", with its State, full Failure and TimelineLocation.

How to fix:

  • Remove attemptFailures, recordAttemptFailure and takeAttemptFailures (rpagent/attempts.go:10-33), and the global JustAfterEach (reporting_node.go:169-173). A library should not inject a node into every user suite.
  • In splitAttempts, collect the spec.AdditionalFailures whose Failure.TimelineLocation.Order falls inside the attempt's (lo, hi) window.
    • One window can hold more than one entry. A cleanup failure after the primary one is recorded too (group.go:294).
    • The entry prefixed Failure recorded during attempt N is that attempt's failure. Strip the prefix and use its State.
    • Log the remaining entries as ERROR logs on the same attempt.
    • The "details were not captured" fallback should then become unreachable.
  • Related: the agent does not use AdditionalFailures anywhere. Even without retries, Ginkgo records secondary failures there (e.g. a DeferCleanup that fails after the It already failed), and today they never reach ReportPortal. Please log them on the final item too.
  • Test: extend cmd/ginkgo-rp/testdata/fixture with a flaky spec whose AfterEach fails on attempt 1. In e2e_test.go, assert the retry/retryOf chain and that the retry item carries the AfterEach failure message. There is currently no wrapper-level test for retries at all.

2. MustPassRepeatedly must not be reported as retries (confirmed live)
MustPassRepeatedly(3) shows up as a PASSED item with two PASSED retries. In ReportPortal a retry means "an earlier attempt failed": the item gets the has-retries mark and reads as flaky although nothing failed.

How to fix: in splitAttempts (rpagent/attempts.go:44-45), split only on SpecEventSpecRetry. For SpecEventSpecRepeat, keep one item. Per repetition, add either an INFO log or, if you prefer, a nested no-stats step ("Repeat 1 of 3") carrying its output. If a repetition fails, the item is FAILED with that repetition's failure. Please update the README section "Flaky Specs".

3. RP_ATTACHMENT#… entries are printed in the Ginkgo console
Running a spec with AddAttachment prints RP_ATTACHMENT#{"tmpPath":"/var/folders/…","origName":…} under "Report Entries". RP_LOG# is hidden correctly.

Please pass ginkgo.ReportEntryVisibilityNever in rpagent/attachment.go:145, as label_helpers.go:60 does. Do the same for the error entries at :101, :120 and :130.

4. Every spec gets a priority: P1 attribute even when no priority was set
ExtractPriorityFromReportEntry returns DefaultPriority, and the attribute is always emitted in rpagent/test_listener.go:180-184. As a result every item in the launch carries priority:P1, which makes the attribute useless for filtering. Please return (int, bool) and send the attribute only when a rp.priority: label is present. The P0–P4 stats in the wrapper summary can keep counting unlabelled specs as the default if you want.

5. Finalization cannot be interrupted and has no overall deadline
After ginkgo exits, signal.Notify (cmd/ginkgo-rp/main.go:87) stays active until run() returns, so Ctrl-C is swallowed. At the same time, finalization uses context.Background() (main.go:1067, :1077, :1393 and rpagent/launch_coordinator.go:237), bounded only by the 30 s client timeout per request. If ReportPortal hangs mid-run, finalizing a few hundred containers takes up to hours, and only kill -9 stops it.

How to fix:

  • Create one ctx for finalization:

    • give it an overall deadline (e.g. RP_FINALIZE_TIMEOUT, default 2–5 min);
    • cancel it when a signal arrives after ginkgo has exited;
    • pass it through aggregateAndFinalizeLaunch → finishContainers / finishSuitesFromResults → FinalizeLaunch.

    This is also the repo convention: ctx goes first and is forwarded.

  • After a few consecutive failures, stop finishing items one by one and fall back to stopLaunch.

6. Skipped and pending specs become "To Investigate" (confirmed live)
In the live launch, Skip("…") and PIt specs were finished as SKIPPED with issue ti001, so 2 of the 4 To Investigate items were not failures at all. The server assigns To Investigate to every SKIPPED item that has statistics and no issue (FinishTestItemHandlerImpl.java:344-374 in service-api).

The agent also starts an item for every spec in ReportBeforeEach, with no state check. So on --focus / --label-filter runs every filtered-out spec should end up as SKIPPED too. That follows from the code; I did not run it live.

How to fix:

  • Property: add rp.skipped.issue / RP_SKIPPED_ISSUE with default true, as in the Java agents (ListenerParameters.java:47). When it is false, finish user-skipped specs with Issue{IssueType: "NOT_ISSUE"}.

  • Attribute: send the system launch attribute skippedIssue=<bool> at launch start, as TestNGService.java:602-606 does.

  • Skips nobody needs to investigate: always send NOT_ISSUE, whatever the property says, for:

    • pending specs;
    • specs skipped without a failure message (filtered out, skipAll);
    • Ginkgo's cascade skips in ordered containers ("Spec skipped because…").

    Then only the culprit stays To Investigate, as Java does for skips after a failed configuration method. Nobody has to triage these.

  • Better, as a follow-up: do not create items at all for specs that were filtered out.

7. Pin uniqueId in a test
testCaseId is the history key, and uniqueId is the key the flaky and most-failed widgets group by. If either changes after release, every user's history splits and cannot be repaired.

identity_test.go already pins a literal testCaseId, and the README documents the format. No test pins a literal uniqueId, though. Please add literal expected uniqueId values next to the testCaseId ones, and cover a DescribeTable entry, a By() step and an over-long name. The over-long name matters because uniqueId is derived from the full ID, not the cut one.

8. The launch link is never printed on ReportPortal 6.x
rpagent/launch_coordinator.go:251-255 builds the URL from rs.Number, but the v2 finish response contains only id and link. So nothing is printed, and the hand-built path is not the 6.x route anyway. Please delete the hand-built URL and print rs.Link whenever it is non-empty, not only with rp.debug.

9. README: per-attempt stdout under -p
splitAttempts clears CapturedStdOutErr on earlier attempts, and the last attempt receives the stdout/stderr of all attempts. GinkgoWriter output is split correctly. Stdout has no offsets, so it cannot be split exactly. Please say so in the "Flaky Specs" section, or label that log on the final item as covering all attempts.

10. README wording on discovery
README.md:419 says suites are found "the way Ginkgo does". That is not quite true:

  • Ginkgo's filesHaveGinkgoSuite (ginkgo/internal/test_suite.go) runs a regex over every _test.go file and ignores build tags and GOOS/GOARCH.
  • The agent uses go/build with --tags.

The agent's behaviour is reasonable. Please just describe it as it is, and mention the edge case: a package whose Ginkgo files are all excluded by tags is still picked up by Ginkgo but is not registered in ReportPortal.

11. Follow-up: job control with the separate process group
Setpgid (cmd/ginkgo-rp/proc_unix.go:15) is needed for the group-wide forwarding, so keep it. But it moves ginkgo out of the terminal's foreground group. I'd expect Ctrl-Z to stop only the wrapper and a test that reads stdin to get SIGTTIN. I have not verified either. Please check both. If they are confirmed, forward SIGTSTP/SIGCONT to the group and note the stdin limitation in the README. This can be a follow-up.

Squashing and rewording the history after the review is fine. Please also make sure CI passes on the new head once it is approved to run.

@That-geeky-shree

Copy link
Copy Markdown
Author

@DzmitryHumianiuk, Thanks for the live run and the detailed review. All 11 items are fixed and pushed (two new commits on top of f79ab09). I Build, vet, go mod tidy -diff, golangci-lint v2.15.0 and go test -race pass. Coverage is now 88.8% for cmd/ginkgo-rp and 88.2% for rpagent.

  1. AfterEach / DeferCleanup failures in retries: the JustAfterEach hook and the attemptFailures helpers are gone. An earlier attempt's failure now comes from AdditionalFailures, taken by timeline window with the prefix stripped. Other failures are logged as ERROR on their attempt, and also for specs that were not retried. The fixture has a flaky spec whose AfterEach fails on attempt 1, and the e2e test checks the retry chain and the message. The README premise is corrected.
  2. MustPassRepeatedly: now one plain item with an INFO log "Repetition k of n". A failing repetition makes the item FAILED with its failure. README updated.
  3. RP_ATTACHMENT# entries: hidden with ReportEntryVisibilityNever at all four places. The attachment error logs now read "Attachment not uploaded: file (message): reason".
  4. Priority: (int, bool). The attribute is sent only when a rp.priority: label exists. The wrapper summary still counts unlabeled specs as P1(default).
  5. Finalization: one context with a deadline (RP_FINALIZE_TIMEOUT, default 3 min), passed down to FinalizeLaunch. Ctrl-C cancels it, a second Ctrl-C gives up at once, and after 3 failed finish requests in a row it falls back to stopLaunch.
  6. Skips: rp.skipped.issue / RP_SKIPPED_ISSUE (default true) and the skippedIssue system attribute. Pending, filtered-out and cascade skips are always NOT_ISSUE. On a launch with a user Skip, a pending spec, a filtered-out spec and an ordered-group failure.
  7. uniqueId: literal expected values for a spec, container, table entry, By() step, second step with the same text, fixture, slash name, non-ASCII name and an over-long ID, plus the namespace.
  8. Launch link: the hand-built URL is deleted. rs.Link is printed whenever it is non-empty.
  9. Stdout under retries: the README says so, and the final item's stdout log is labeled [stdout/stderr of all N attempts].
  10. Discovery wording: the README now describes the agent's rule (compiled files, imports) and the edge case. I confirmed Ginkgo's own behaviour by running it. I kept skipping testdata, which Ginkgo does not skip, and documented that.
  11. Job control:
    • Ctrl-Z was confirmed: it stopped only the wrapper, and the tests kept running.
    • Now SIGTSTP and SIGCONT are forwarded to ginkgo's group. I checked Ctrl-Z, fg, bg and Ctrl-C in a real terminal.
    • The stdin concern is not an issue: test processes get EOF under plain ginkgo too. README updated.

Also tested against the real instance:

  • RP stopped mid-run: the spec passes, exit 0, or 2 with RP_STRICT.
  • RP frozen at finalization: the deadline ends it after 50 s with a warning, and the launch is STOPPED.
  • -p and sequential runs give identical trees.

Left for a follow-up, as in your java-testNg vs ginkgo table: key:value labels, joining an existing launch, rerun, system attributes, NOT_ISSUE on non-final failed attempts, explicit table parameters, dropping the line from codeRef, config parity, and async reporting. Also not creating items for filtered-out specs.
One note: if ReportPortal freezes (not dies) while a spec runs, the worker waits on each call (30 s × 3 attempts). That is the "synchronous in the hooks" follow-up.

@DzmitryHumianiuk

Copy link
Copy Markdown
Member

Thanks, this round closes almost everything. I reviewed 07ad5c4:

  • build, vet, go mod tidy -diff and go test -race are clean (88.8% / 88.2%); GOOS=windows builds and vets clean;
  • I ran it against ReportPortal 6.0.0 again. Retry chains carry the right per-attempt failure (in the attempt's By() step), the AfterEach failure lands on attempt 1, MustPassRepeatedly is one item with "Repetition k of 3" logs, Skip("reason") is To Investigate by default, and the pending spec is NOT_ISSUE with no defect. The printed link comes from rs.Link.

All 11 items are fixed. A few things are left, mostly in the new signal and finalization code. Please fix all of them, including the minor ones, so the next round can be the last:

  1. Ctrl-Z can freeze the run when nothing can resume it (cmd/ginkgo-rp/proc_unix.go:52-54, :75-77). Under ssh -t host ginkgo-rp …, docker run -it … or a CI pty, the wrapper's process group is orphaned. Before, the kernel discarded SIGTSTP there. Now the handler stops ginkgo's group and SIGSTOPs the wrapper, and nobody ever sends SIGCONT. Suggested fix: skip both the forward and stopSelf when the wrapper can't be resumed (for example os.Getpid() == 1, or the parent is in another session: unix.Getsid(os.Getppid()) != unix.Getsid(0)).

  2. A launch can still stay In Progress after a finalize error (cmd/ginkgo-rp/main.go:305). abortLaunch runs only when the context is done or the failure streak reaches 3. If the containers and suites finish and the single FinishLaunch returns a 5xx, or a small run (one container, one suite) hits a dead server, there are fewer than 3 failures and the launch is left In Progress. This contradicts the comment at main.go:277-279. Please call abortLaunch on any error from aggregateAndFinalizeLaunch, and extend TestWrapperFinalizeFailureKeepsGinkgoExitCode to assert the STOPPED attempt. That test would also cover the streak branch at main.go:311, which no test executes right now.

  3. The failure streak counts every error, including 4xx (main.go:409-419). Three consecutive rejected container finishes now stop the launch and say "ReportPortal is not responding". Count only transport errors and 5xx.

  4. The agent doesn't build against current goRP master. pkg/ginkgo pins goRP/v5 v5.2.2, so CI never compiles it against the code in the same repository. Built against master (with a go.work that uses . and ./pkg/ginkgo), it fails:

  5. Minor

    • After ginkgo exits, Ctrl-Z is silently ignored during finalization (Go keeps the handler after signal.Stop). Either document it or keep SIGSTOP-ing the wrapper itself until finalizeRun ends.
    • reporting_node.go:367-369: the single-attempt path passes spec instead of attempts[0], so the filtering in attempts.go:38-42 is dead code.
    • Stale comments: reporting_node.go:365-366 (MustPassRepeatedly is no longer one item per attempt) and main.go:477 ("as FAILED", but the code sends STOPPED).
    • An invalid rp.skipped.issue value is ignored silently (rpagent/config.go:99-102). A warning would match RP_FINALIZE_TIMEOUT.
    • proc_unix_test.go:40 stubs stopSelf, so the real SIGSTOP isn't tested. Please add one test that runs the wrapper logic in a child process and checks that it really stops and resumes.

I'd like all of the above fixed in this PR. I also re-ran all our goRP examples together with this build (master + #29 + #30 + this PR): the results match the earlier runs, except one expected change: To Investigate drops by one because pending specs are now NOT_ISSUE. The follow-up list in your comment looks right to me.

@That-geeky-shree

Copy link
Copy Markdown
Author

Thanks @DzmitryHumianiuk. All the points are fixed and pushed. I tested them on ReportPortal 6.0.0, on the released goRP v5.2.2 and, through a go.work, against master + #29 + #30. Lint, go test -race and go mod tidy -diff are clean (89.2% / 88.4% coverage).

  1. Ctrl-Z in an orphaned group: the wrapper now acts on Ctrl-Z only when something can resume it. It checks when the signal arrives, and treats process 1, a parent that is process 1, a parent in another session, and an unreadable session as "cannot resume". Then it does nothing, as before my job-control code. I reproduced the freeze in a pty with no shell above the wrapper (everything stopped for good) and checked the fix there. A helper-process test checks the real SIGSTOP and resume, and that nothing happens in a new session. unix.Getsid is used because syscall.Getsid doesn't exist on Linux, so golang.org/x/sys is now a direct dependency.
  2. Launch left In Progress: abortLaunch now runs after any error from aggregateAndFinalizeLaunch. TestWrapperFinalizeFailureKeepsGinkgoExitCode asserts [PASSED, STOPPED] (also in strict mode), and a new nested-container fixture covers the 3-failure branch.
  3. Streak and 4xx: only transport errors, timeouts and 5xx count. A 4xx ends the streak. I checked this on 6.0.0 by revoking an API key mid-run: before, "not responding" after the third 401. Now every container and the suite are tried, then the stop fallback runs.
  4. Master build: I reproduced the four errors. The agent no longer names ParameterResource or Issue; it fills them through JSON, so it compiles against both v5.2.2 and master. I did that rather than using the generated names, which don't exist in v5.2.2 and would break the build against the released module that go.mod requires. The log tests now accept both the JSON and the multipart json_request_part forms (I fixed two more tests with the same problem). New CI step and task ginkgo:workspace build, vet and test pkg/ginkgo against this repository's pkg/gorp.
  5. Minor:
    • Ctrl-Z during finalization now stops the wrapper too.
    • The single-attempt path passes attempts[0].
    • Both stale comments are fixed.
    • An unreadable rp.skipped.issue or rp.debug (file or environment) now prints a warning.
    • The real-SIGSTOP test is in (see 1).

I'll squash and reword the history once you confirm there are no more changes.

@DzmitryHumianiuk

Copy link
Copy Markdown
Member

Thanks, I reviewed 923718e. Items 2–5 are fixed. Item 1 is fixed only for some setups. We're close to the end: after this round I expect no more changes.

What I ran:

Verified fixed:

  • Item 2: abortLaunch(hardCtx, …) runs after any finalize error (main.go:308-318). The launch is never stopped after a successful finish, and the tests assert [PASSED, STOPPED].
  • Item 3: only transport errors, timeouts and 5xx count, and a 4xx ends the streak (main.go:419-431). This works with the *gorp.HTTPError of both v5.2.2 and master + Return one HTTPError with the server's code and message from both clients #36.
  • Item 4: parameters and the issue go through JSON. A wrong field name would fail, not be dropped: both versions use DisallowUnknownFields. Thanks for fixing the other two tests and for the CI step.
  • Item 5: all minor points are done, and the real SIGSTOP tests are real.

Please fix the following, then I think we're done:

  1. Ctrl-Z still freezes the run when the parent is in the same session but doesn't do job control (cmd/ginkgo-rp/proc_unix.go:72-83).

    • canBeResumed compares the parent's session with the wrapper's own. It doesn't check whether the wrapper's process group is orphaned. The kernel's rule is the one that matters: a group can be resumed only if some member has a parent in the same session but a different process group, which is the job-control shell.

    • Same session, no job control: ssh -t host 'cd proj && ginkgo-rp ./...', ssh -t host make test, or a script on a CI pty. The parent is a non-interactive sh in the same session and the same process group, so the check passes, the wrapper stops itself, and nothing sends SIGCONT. Reproduced with a real ^Z on a pty: sh -c 'ginkgo-rp …; echo AFTER' stayed stopped for good.

    • docker exec -it / kubectl exec -it: the parent is outside the PID namespace, so getppid() is 0, and getsid(0) returns the wrapper's own session. The sessions compare equal, so the check returns true. Reproduced in golang:1.27.4-alpine with kill -TSTP.

    • The other direction: ppid == 1 is too broad. In docker run -it img bash, the interactive shell is PID 1 and does job control, and Ctrl-Z is now ignored there.

    • Suggested check, closer to the kernel's own: walk up from the wrapper while the ancestors are in the wrapper's process group. Look at the first ancestor outside the group:

      • If it is in the same session, a job-control shell can resume the group, so act on Ctrl-Z.
      • If its pid is 0, it is in another session, or it can't be read, do nothing.

      Reading the parent of an arbitrary pid takes /proc/<pid>/stat on Linux and unix.SysctlKinfoProc("kern.proc.pid", pid) on macOS/BSD. That also removes the ppid == 1 special case.

    • I tried restoring the default action and sending SIGTSTP to the wrapper itself, so that the kernel would decide. With Go's runtime the wrapper doesn't stop even under an interactive bash, so I don't recommend that route.

    • Please add test cases for ppid == 0 and for a parent in the same process group. TestJobControlDoesNothingWhereNothingCanResume covers only the case where the wrapper is its own session leader.

  2. Signals can go to a reaped process group during finalization (proc_unix.go:111,114, main.go:221). The handler now outlives cmd.Wait, so Ctrl-Z or SIGCONT during finalization sends kill(-pid) to a pgid that may already be reused by another group of the same user. Skip the forward once ginkgo has exited.

  3. Suspending during finalization can turn the launch STOPPED. The finalize deadline and the HTTP timeouts keep counting while the wrapper is stopped. Ctrl-Z during finalization followed by fg more than 3 minutes later gives "finalizing took longer…" and a STOPPED launch. One sentence in the README is enough.

  4. Two tests depend on the real environment (proc_unix_test.go:43, :245). They stub stopSelf but not getppid/getsid. When go test runs as the container's PID 1 (docker run golang go test ./...), canBeResumed() is false and proc_unix_test.go:262 fails with "Ctrl-Z was ignored after ginkgo had exited". Also, procState (:21) uses ps -o stat= -p, which busybox ps doesn't support: on Alpine every state reads "gone". GitHub runners are not affected, but please stub the session lookups and read /proc/<pid>/stat where it exists.

  5. Minor

    • The new boolean warning repeats. LoadRPConfig isn't cached, so one typo in rp.debug prints the warning many times per run (rpagent/config.go:158). Warn once.
    • task ginkgo:workspace:
      • It doesn't remove its mktemp -d directory. Add a trap.
      • It doesn't vet -tags sanity ./examples/... the way ginkgo:vet does, so drift in the examples isn't caught.

After these, please squash and reword as you suggested. We're close to merging. Next on our side is a shared reporting session in pkg/gorp (#52), with ordering, Flush(ctx) and an outage breaker. Once it lands, the agent can drop its own queue, failure streak and finalize logic, but that will be a follow-up and doesn't block this PR.

@DzmitryHumianiuk

DzmitryHumianiuk commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Two notes while you work on the items from my last review. Neither one adds to that list.

  1. A test fails when it is repeated. TestCleanupRemovesExactlyOneSessionsFiles (cmd/ginkgo-rp/main_test.go:417) fails at 923718e with go test -count=2 ./cmd/ginkgo-rp/. The second iteration fails at the final t.Fatalf. The process-wide inMemoryContainerCache (rpagent/launch_coordinator.go:30) survives between iterations, so the cache file isn't created again. CI runs with -count=1, so it passes there. If it's easy, please reset the cache in the test, for example with t.Cleanup. If not, it can wait.
  2. The shared session is up for review. Add gorp.Session: ordered async reporting with Flush, breaker and abort; use it in report test2json #53 adds gorp.Session (Design: a reporting session for Go agents (ordering, Flush(ctx), breaker) #52), and ginkgo: report through gorp.Session #54 (draft) is the follow-up that moves this agent onto it. ginkgo: report through gorp.Session #54 is stacked on this PR, so it doesn't block it. It removes failureStreak, abortLaunch/stopLaunch and the log retry, and it doesn't touch proc_unix.go. You don't need to do anything for it now. Once this PR is merged, I'll rebase ginkgo: report through gorp.Session #54.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants