Repository navigation
Add gorp.Session: ordered async reporting with Flush, breaker and abort; use it in report test2json - #53
Open
DzmitryHumianiuk wants to merge 23 commits into
Open
Add gorp.Session: ordered async reporting with Flush, breaker and abort; use it in report test2json#53DzmitryHumianiuk wants to merge 23 commits into
DzmitryHumianiuk wants to merge 23 commits into
Conversation
ReportPortal writes ErrorRS.errorCode as a number (ErrorTypeSerializer calls writeNumber(error.getCode())), but the upstream spec declares it as a string enum. The generated client therefore failed to decode every error response declared as ErrorRS and returned "json: cannot unmarshal number into Go struct field ...errorCode of type string" instead of the HTTP status and the server's error model. Override the property in scripts/openapi-preprocess.jq (integer/int64, same as the spec's own Error schema) and regenerate the client. The filter now fails if the schema or property disappears upstream. GetErrorCode/SetErrorCode/GetErrorCodeOk of ComEpamReportportalBaseInfrastructureRulesExceptionErrorRS change from string to int64. Fixes #31 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…ents
A failed call through the generated client reported only the HTTP status
("404 Not Found"), or a oneOf decoding error instead of the status for a
rejected API key, while the Resty clients dumped the raw body.
gorp.HTTPError now carries the status, request, ReportPortal error code and
message, OAuth error and the raw body. Both clients build it with the same
tolerant parser: the generated client through Configuration.ResponseMiddleware
(all operations, declared status or not), the Resty clients through their
response handler. Errors of the generated client still unwrap to
*openapi.GenericOpenAPIError. errors.Is works with ErrUnauthorized,
ErrForbidden, ErrNotFound and ErrNotAPIResponse.
The Resty clients now fail on a 2xx text/html response (wrong host or path)
instead of returning an empty result.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
NewClient and NewReportingClient take variadic options after the authentication option. WithResponseMiddleware adds a hook that is called with every response and its body before the client's own error handling; hooks are chained and the first error stops the chain. The same hook serves the Resty-based methods and the generated client. ParseLaunchMode, ParseItemType and ParseStatus convert user input to the typed values. Part of #27 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
A token request of WithPasswordOwnerGrantAuth fails inside the OAuth2 transport, before any API response exists, so neither client's response handling saw it and the caller got the oauth2 package's two-line text. The token source now converts *oauth2.RetrieveError into the same HTTPError as a failed API call: request (the token endpoint), status, OAuth error and description, or ReportPortal's error code and message (ReportPortal 6 answers a wrong password with an ErrorRS body). HTTPError.Unwrap returns the RetrieveError, so errors.As to it keeps working. A token "error" answered with status 200 is not mistaken for an HTML page: the 2xx HTML case moved out of newHTTPError into newNotAPIError. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The generated client has a single ResponseMiddleware slot, read from the Configuration on every call, so a middleware assigned by the user silently replaced OpenAPIErrorMiddleware and brought the generated error texts back. ChainResponseMiddleware combines middlewares into one: they run in the given order, nil entries are skipped, the first error wins. With the user's middleware first it sees failed responses too and the call still returns an HTTPError. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
…tions A wrong host or base path lands on the UI or a login page, which answers 200 with HTML. The Resty clients already report that as ErrNotAPIResponse; the generated client failed with "undefined response type", because its middleware could not tell a JSON operation from one that legitimately returns a file or an HTML report. OpenAPIErrorMiddleware now matches the answered request (method + path template, compared with the end of the path) against nonJSONOperations and returns ErrNotAPIResponse for a 2xx text/html response of any other operation. The list is derived from pkg/openapi/api/openapi.yaml: the 41 operations with no application/json content in a 2xx response, or with that content declared as a binary string. A test recomputes it from the YAML and prints the list to paste when it drifts; another one checks that no JSON operation's path fits an exempt template. go.yaml.in/yaml/v3 becomes a direct (test-only) dependency; it was already in go.sum through testify. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
README "Errors": how to keep OpenAPIErrorMiddleware next to a middleware of your own, which operations are exempt from the HTML check, what a failed password-grant token request looks like. AGENTS.md: file table row for nonjson_operations.go and the rule to update the list after regenerating the client. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
WithRetry(RetryPolicy) repeats requests that failed with a network error, 5xx (except 501) or 429, with exponential backoff and jitter. A Retry-After header is honored up to MaxWait, other 4xx are never retried, retries stop with the context. The hand-written methods use Resty's retry API with the policy's own conditions and delays; the generated client gets a copy of the HTTP client with a retrying transport. GET, PUT and DELETE are retried. Launch and item starts are retried because they carry a client UUID, which the client now generates when the request has none. Rerun starts, raw starts without a uuid and logs are sent once. Part of #27 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
The oauth2 package reads the "error" field of any JSON body into
RetrieveError.ErrorCode. For a wrong token URL answered by Spring's
default handler ({"status":404,"error":"Not Found","path":…}) the
fallback in newTokenError copied it, and the text became
"404 Not Found: Not Found" instead of the "no such endpoint" hint.
The fallback now applies only to a body that is not a JSON object,
the form-encoded case it exists for. README: the status sentinels
match a token failure as well.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Truncate shortens names, descriptions and attributes to the server's limits, counted in UTF-16 code units like the server does and never splitting a character. BoundedID shortens testCaseId/uniqueId to a prefix plus a hash of the whole ID, so long IDs stay unique and stable. The limits are constants taken from the service-api validation rules. Part of #27 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Checked on ReportPortal 6.0.0: a 3000-character key and value are stored as 512/512 (AttributeConverter.MAX_ATTRIBUTE_LENGTH in service-api). The 128 default stays below that, so only the comment and README change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # pkg/gorp/client.go
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # AGENTS.md
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> # Conflicts: # AGENTS.md
A Session reports one launch (started, or attached by UUID) through one worker that sends item starts, finishes and logs in the order of the calls. Item UUIDs are chosen by the client, so StartItem returns at once and children may be queued before their parent's start is answered; they are sent after it. - A failed start skips the item's finish, logs and descendants, each reported as ErrNotStarted wrapping the cause. - Errors go to WithErrorHandler and are returned once by Flush/Close/ Launch.Finish/Launch.Abort (32 kept, the rest counted). - A breaker (default 3 consecutive no-response/5xx results, 4xx resets) stops the session for good; Finish then returns ErrLaunchNotFinished and the owner calls Abort, which finishes the open items innermost first and the launch. - Flush(ctx) and Close(ctx) are bounded by ctx; after Close, Finish or Abort no goroutine of the session is left. - Names, uniqueId, descriptions and attributes are shortened to the server limits on a copy of the request (WithoutTruncation turns it off). LogBatcher gets LogBatcherOptions.OnBatch (the result of every batch) and Sync(ctx) (send the current batch and wait for all requests without closing). The in-flight limit is now a slot channel instead of errgroup.SetLimit, so that Sync does not block on it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The reporter no longer sends starts, finishes and logs itself: it queues them on a session and keeps only the parsing state (open items, parents, retries, pending log). Its maps hold *gorp.Item handles; retryOf is the UUID of the previous run's handle. Fail-fast is rebuilt on the session's error handler: the first reporting error stops reading events, and receive interrupts the run with Launch.Abort (INTERRUPTED: open items innermost first, then the launch unless it is joined) and returns that error. A normal end is Flush, then Launch.Finish (or Close for --launch-uuid); a Finish that could not finish the launch is followed by Abort. Differences in behaviour, all with the same end state: - events queued behind a failed request are dropped by Abort; - a failed log batch interrupts the run when it happens, not at the end; - a container re-opened without a new child keeps its status on abort; - item UUIDs are chosen by the client (test servers echo the request uuid); - over-long names and uniqueIds are shortened instead of failing with 400. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
e2e: a tree queued at once (FAILED leaves and an attachment right before the launch finish), a second session attached to the launch (the launch stays IN_PROGRESS until its owner finishes it), and Abort stopping a launch with open items. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Abort no longer waits out log requests that hang: the batcher is detached (no caller waits for a slot) and the logs get abortLogWait (2 s) before the session context is canceled; unsent logs are counted in one ErrSessionClosed/ErrBreakerOpen error. - Finish and Abort are serialized (endMu). A second Finish, or a Finish after/during Abort, sends nothing and returns ErrSessionClosed. - The request that trips the breaker is reported as its own error and not counted as unsent; a start canceled by the breaker matches ErrBreakerOpen (canceledBySession, classified before the trip). - Close with an ended ctx after the worker stopped returns nil. - Close during StartLaunch: no goroutine is started afterwards, StartLaunch fails with ErrSessionClosed and ErrLaunchNotFinished. - A start that may be stored re-opens its parents for Abort. - Test fake tolerates canceled multipart uploads; chaos test ported. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
receive may sit in an enqueue of the session behind a hanging request and not see the cancel; a context.AfterFunc now interrupts the launch (once), and the Abort releases receive. ErrSessionClosed reported after the cancel is not taken for the failure. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The Ginkgo wrapper stops a launch it cannot finish in two steps, each with its own share of the time: the open items, then the launch. With Abort alone a suite finish that hangs or gets a 5xx used up the budget or ended the abort, and the launch stayed In Progress. AbortItems is Abort without the launch finish; the owner sends it itself. AbortItems follows the rules of Abort: it drops the queue before taking endMu (so it releases a Finish waiting for the drain), gives the logs abortLogWait, and a Finish during or after it sends nothing and returns ErrSessionClosed. Its error never matches ErrLaunchNotFinished. The launch stays unfinished for the session, so a later Abort sends the launch finish: the retry when the owner's own finish failed. Abort behaves as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…waits, Flush errors, attachments Review findings on gorp.Session and LogBatcher: - Launch.Abort/AbortItems go on with the next open item after an item finish that got no answer or a 5xx (the item stays open) and give up after WithBreakerThreshold such failures in a row (3 if the breaker is disabled; also after the breaker opened) or when ctx ends. Otherwise Abort sends the launch finish, so the launch is not left In Progress. - The lock between Finish and Abort is a one-slot channel taken with the caller's ctx: an Abort whose ctx ends while a Finish hangs returns. A Finish whose ctx ends while an Abort runs returns ErrSessionClosed. - Flush returns an error matching ErrSessionClosed/ErrBreakerOpen when its barrier was dropped or logs were dropped while it waited, instead of nil. - LogBatcher loads attachments before the request: a log whose attachment can't be loaded is left out and reported in the LogBatchError; the other logs of the batch are sent. The request still gets the attachment's own reader, so it closes the file of a FileMultipart as before. - LogBatcher starts a new batch when a file name repeats. ReportPortal 6.0.0 hands same-named parts to the logs in order, but a log it rejects in validation does not take its part, and the next log of that name got the rejected log's file (seen live). New e2e test TestLogBatcher_SameNamedAttachmentsKeepTheirContent. - Test fake: a request the client gave up on (still in its handler when the launch finish arrives) is no ordering violation; this flaked under -race -count=20. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Part of #27 (slice L6). Implements #52.
Stacked on #47 (
feat/log-batcher). It also needs #36 (HTTPError), #48 (Option), #49 (truncation helpers) and #50 (WithRetry). The branch merges all of them (base commit c423030), so the diff against #47 shows their changes too until they are merged. Review the three commits on top of c423030.Per #52 this merges only together with its second consumer, the Ginkgo agent migration. That migration is a follow-up stacked on #15.
gorp.Sessionreports one launch. One worker sends item starts, finishes and logs in the order of the calls. Calls that report return at once and never fail. Errors go to a handler and are returned byFlush,Close,Launch.FinishandLaunch.Abort. A terminal breaker stops reporting when the server is down.Abortmakes sure the launch is not left In Progress.gorp report test2jsonnow reports through it.Changes
pkg/gorp: the session (session.go,session_queue.go,session_breaker.go)NewSession(client, opts...)takes these options:WithErrorHandler,WithBreakerThreshold(default 3, below 1 turns it off),WithLogBatchingandWithoutTruncation. A session has one launch, fromStartLaunch(ctx, rq)(synchronous; the UUID is the one in the response, so a rerun works) orAttachLaunch(uuid)(no I/O, never finished).Launchmethods:StartItem(parent, rq),Item(uuid)for a handle of an item started elsewhere,Log,Finish(ctx, rq),Abort(ctx, status, endTime).Itemmethods:Log,Finish,Wait(ctx).ErrLaunchNotFinished,ErrBreakerOpen,ErrSessionClosed,ErrLaunchAttached,ErrNotStarted.LogBatcher, so a log is sent only after its item's start was answered. Requests are serial; log batches run concurrently, up toMaxInFlight.ErrNotStartedwrapping the cause. A start that got no answer, a 5xx, or was canceled may still exist on the server, so it stays in the open set.*url.ErrorthatretryableErroraccepts. Any answer < 500 resets the count, including a rejected log inside a 201. With concurrent batches, a result counts only if its request started after the last counted failure was seen, so one outage that fails 4 batches counts once. This is done with a generation counter that a request takes when it starts.FlushreturnsErrBreakerOpen.FinishreturnsErrLaunchNotFinishedjoined withErrBreakerOpen.Close/Finish("N reporting operations and M logs were not sent").Flush(ctx)puts a barrier into the queue, then callsLogBatcher.Sync(ctx). The session keeps working if ctx ends first.Close(ctx)stops accepting and lets the worker drain the queue. If ctx ends first, it cancels the requests under way and drops the rest. No goroutine of the session is left after it returns.FinishisCloseplusFinishLaunch.Abortdrops the queue, cancels the request under way, sends the logs the batcher holds (for at most 2 s, see Review fixes), then finishes the open items (deepest first, latest first at the same depth) and the launch, unless it is attached or already finished. After an item finish that gets no answer or a 5xx it goes on with the next item, and gives up afterWithBreakerThresholdsuch failures in a row or when ctx ends, withErrLaunchNotFinished(see Review fixes, round 2).Truncate.uniqueId:BoundedID. Description and attributes on start and finish:Truncate/TruncateAttributes.testCaseIdis not touched. Item starts always get a client UUID.pkg/gorp:LogBatcher(additive)LogBatcherOptions.OnBatch func(logs int, err error)reports the result of every batch from the request goroutine.LogBatcher.Sync(ctx)sends the current batch and waits until every batch taken so far has finished. A batch counts as unfinished from the moment it is taken, under the mutex. The batcher stays open.MaxInFlightlimit is now a slot channel instead oferrgroup.SetLimit.Addstill blocks on it.Synchands its batch to an errgroup goroutine that waits for a slot, soSyncnever blocks on one.internal/commands:report test2jsonreporter.gosends nothing itself.tests/suites/openItemshold*gorp.Item.retryOfis the previous run'sUUID(). Logs go toItem.Log/Launch.Log, andpendingLogremembers its item.startLaunch's andstartTest's client calls, theentryIDchecks,finishLaunch,finishLogs,logs *LogBatcher, and the loop overopenItemsininterrupt.reporter.fail) stores the first error and closesreportFailed.nextEventthen stops reading, and the final flush (flushUntilFailed) stops waiting.receivethen callsinterrupt, which is nowLaunch.Abort(INTERRUPTED), and returns that error.Flush, thenLaunch.Finish, orClosefor--launch-uuid. AFinisherror that matchesErrLaunchNotFinishedis followed byAbort.WithRetrystays off.Tests
pkg/gorp/session_test.gouses a fake server (session_helpers_test.go) that checks ordering while serving:itemUuidin a log batch belongs to an answered start;uuidis stored once.-race;ErrNotStarted);Flush/Finisherrors, a singleErrBreakerOpen,Abortagainst a dead server sends one request,Abortafter recovery finishes innermost first + launch STOPPED;WithRetry) is one item and its child is still sent;Flushdeadline (the session keeps working),Closedeadline (goroutines stopped, drop counts),Finishdeadline (ErrLaunchNotFinished, thenAbort);Abortdrops the queue and cancels the request under way;WithoutTruncation, caller's request unchanged;classifyResulttable;requireStopped: worker, batcher timer, unfinished batches). No new dependency.log_batcher_test.go:Sync(bounded by ctx with no free slot; the batcher stays open),OnBatch(ok / failed / rejected).TestSession_FullQueueBlocksCallersUntilClosed. The caller blocks once 1024 operations are queued,Flush(50ms)returnsDeadlineExceeded, and an expiredClosereleases the caller withErrSessionClosed.internal/commands:TestReportLaunch_FailedStartInterruptsLaunch: a 500 on a start mid-stream leads to an error, suite INTERRUPTED and launch INTERRUPTED.TestReporter_FailureAfterInputEndedStopsReporting: the input is closed before TestB's 500 is released, and at most 5 items are sent. WithoutflushUntilFailedit fails with 202 items sent.TestReportLaunch_CancelledContextInterruptsLaunchnow also asserts that it returns in under 3 s. Otherwise it would pass even ifAbortwaited out the mock's 5 s hang.e2e/session_test.go:TestSession_TreeQueuedAtOnce,TestSession_AttachFromSecondSession,TestSession_AbortStopsLaunch. The design'sFailedItemsFinishBeforeLaunchcase is folded intoTreeQueuedAtOnce, which finishes FAILED leaves right before the launch.Review fixes (commits 8ced547, a300bf9 and a test hardening on top)
Launch.Abortno longer waits out hanging log requests. Itdetaches the batcher (unexported: from then on no caller waits for a slot; a batch waits for its slot in its own goroutine, like the one ofSync), so neither the worker nor the flush timer blocks. The log requests under way and the logs the batcher holds getSession.abortLogWait(2 s, unexported field) and thenctxis canceled. Logs that were not sent are counted in one error,N logs were not sent, matchingErrSessionClosed(ErrBreakerOpenwith the breaker open).Launch.FinishandLaunch.Abortare serialized byendMu(wasabortMu). Abort drops the queue before it takes the lock, so it can still stop a Finish that waits for the drain. A secondFinish, or one after or duringAbort, sends nothing and returnsErrSessionClosed(notErrLaunchNotFinished).canceledBySession(ctx, effect), meaning no answer and ctx done, classified before the breaker trips. The request (or log batch) that trips the breaker is reported as its own error and not counted as unsent. A start canceled by the breaker or by Abort wrapsdropReason(), soItem.WaitmatchesErrBreakerOpen/ErrSessionClosed.shutdownreturns nil when the worker is already done, even with an ended ctx.beginchecksclosed, creates the contexts, batcher and worker, and setslaunchunder ones.muhold.CloseduringStartLaunch→StartLaunchreturns an error matchingErrSessionClosedandErrLaunchNotFinished. The launch exists on the server and is left; the UUID is in the message.AttachLaunchreturnsErrSessionClosed.addOpenWithParents), like a successful start does.report test2json:reporter.watch(acontext.AfterFuncon the reporter's ctx) callsinterrupt, now once-only, so a cancel reaches areceivethat is blocked on the full queue.failignoresErrSessionClosedafter the cancel.decodeBodyand the log handler no longerrequirein handler goroutines. They tolerate a body the client abandoned, including Resty's well-formed but truncated JSON part of a canceled upload.ErrSessionClosedresults ofFinishare a behaviour change for callers (the Ginkgo migration).Launch.AbortItems(commit 9aca770)AbortItems(ctx, status, endTime)isAbortwithout the launch finish, for an owner that finishes the launch itself withReportingClient.FinishLaunchand a time budget of its own (the Ginkgo wrapper: suites in 2/3 of its budget, then the launch in the last 1/3).AbortandAbortItemsshare one unexportedabort(…, finishLaunch bool);Abortis unchanged.Abort: it drops the queue before takingendMu(so it releases aFinishthat waits for the drain), detaches the batcher and gives the logsabortLogWait(2 s), then finishes the open items innermost first (since round 2: every one of them, giving up after the threshold of failures in a row, see below).Finishduring or afterAbortItemssends nothing and returnsErrSessionClosed, as afterAbort. If aFinishalready holdsendMu(its launch finish under way),AbortItemswaits for it.ErrLaunchNotFinished: the launch is not its business. It can contain "N logs were not sent" (ErrSessionClosed/ErrBreakerOpen) and the error of the item finish it stopped at.l.finishedstays false), so anAbortafterAbortItemssends the launch finish. That is the retry when the owner's own finish failed; after a successful owner finish, don't callAbort.TestSession_AbortItemsLeavesTheLaunchToItsOwner(from 7377b08: 503 on the suite, no launch finish, the next call finishes the suite, the owner finishes the launch),TestLaunch_FinishAfterAbortItemsSendsNothing(thenAbortsends the STOPPED launch finish, the item is not finished twice),TestLaunch_AbortItemsStopsAFinishWaitingForTheQueue(Finish →ErrSessionClosed, no launch finish, the start under way is finished STOPPED),TestLaunch_AbortItemsDuringFinishWaitsForIt(one PASSED launch finish, then the open item).Review fixes, round 2 (commit 8da3e4d)
WithBreakerThresholdsuch failures in a row (default 3; 3 when the breaker is disabled, so a dead server never costs one timeout per item), or when ctx ends. The same budget applies after the breaker opened: that is the usual path (breaker →FinishreturnsErrLaunchNotFinished→Abort), and a server that is back but fails one more item finish must not stop the abort there. Any answer resets the count. Only a give-up (or a failed launch finish) leaves the launch unfinished withErrLaunchNotFinished; otherwiseAbortsends the launch finish even if some items could not be finished, so the launch is not left In Progress. Those items stay open; a laterAbort/AbortItemstries them again.AbortItemsfollows the same rules and still never matchesErrLaunchNotFinished.endMubecameSession.end, a one-slot channel.lockEnd(ctx)takes it at once when free (an ended ctx changes nothing then), else waits for it or ctx. AnAbortthat gives up there returns ctx's error (plusErrLaunchNotFinishedforAbort); the queue was dropped already.Launch.Finishtakes it the same way; aFinishwhose ctx ends while anAbortholds it returnsErrSessionClosed(the abort's business), notErrLaunchNotFinished, as promised in round 1.dropsetssessionOp.droppedbefore it closes a barrier.Flushthen returnsflush: not everything queued before was sent: <ErrSessionClosed | ErrBreakerOpen>instead of nil. The<-s.workerDonecase was removed from Flush's select: the worker always resolves the queue (reaches or drops the barrier) beforeworkerDonecloses. The second half: a Flush past its barrier that waits inLogBatcher.Syncfor a log request which Abort then cancels also returned nil (the logs only went intodroppedLogs).Session.logsDroppedEver(never reset) is compared before and after; if it grew, Flush returnsflush: logs were dropped: <reason>.SaveLogBatchreturned on the firstLoaderror, so one missing file lost the whole batch, text logs included.LogBatchernow remembers which log each file belongs to (owners) and loads the attachments right before the request (logBatch.load). A log whose attachment can't be loaded is left out and added to the batch's*LogBatchError; the rest is sent with the loaded readers. The request gets each attachment's own reader (loadedMultipart): Resty closes a reader that is anio.Closerafter the request (resty.dev/v3@v3.0.0-rc.4request.go:1600/:1638→util.go:275 closeq), so wrapping it in aReaderMultipartwould have left the*os.Fileof aFileMultipartopen (caught byTestLogBatcher_FileOfAnAttachmentIsClosedAfterTheRequest). A batch with no log left sends nothing and returns a plain error, not aLogBatchError, because the breaker takes aLogBatchErrorfor an answer of the server. A server rejection of the whole request (4xx/5xx, e.g. an upload over the size limit) still loses the batch; that is documented onLogBatcher.LogBatcher.Addcuts the batch when the log'sfile.nameis already in it (fileNames, reset bytake), so two logs with one file name never share a request. This also coversreport test2json.fakeRP's "launch finish with N requests under way" check flaked under-race -count=20(2 of 100 iterations ofTestSession_AbortDoesNotWaitForLogsThatHang/worker): Abort cancels the hung log requests client-side, and the handler notices the cancel a moment later.endingWriternow records whether a request ended with an answer; at the launch finish the fake waits up to 1 s for the requests still in a handler and counts only those that are then answered or still running. A request the client gave up on is no violation. 0 failures in 5 × 20 afterwards.pkg/gorp/session_abort_test.go(new):TestLaunch_AbortTriesEveryItemAfterATransientFailure(3 suites, 503 on the first finish → all 3 tried, launch STOPPED for Abort, none for AbortItems, the failed suite finished by the next call),TestLaunch_AbortStopsAfterTheBreakerThreshold(all 503: 3 requests at threshold 3 / 2 at threshold 2 / 3 with the breaker disabled; no launch finish),TestLaunch_AbortCountsOnlyFailuresInARow(503, 503, 200, 503, 503 → 5 tried, launch finished),TestLaunch_AbortStopsWhenCtxEnds,TestLaunch_AbortWaitingForAFinishRespectsCtx(100 ms ctx behind a hung launch finish: returns in < 1 s; was 30 s),TestSession_FlushDroppedByAbortFails,TestSession_ChaosWithAbortItemsEndsCleanly(ported from the reviewer'sTestReview_ChaosAbortItems),TestSession_FlushWaitingForLogsCanceledByAbortFails,TestLaunch_FinishWaitingForAnAbortSaysSessionClosed,TestLaunch_AbortAfterTheBreakerTriesEveryItem(breaker open, server back, one more 503 on the first item: all 6 open items tried, launch STOPPED; with a budget of 1 it stopped at the first).TestSession_BreakerOpensAfterTransientFailuresnow expects 3 abort requests against a server that is still down (was 1).log_batcher_test.go:TestLogBatcher_UnreadableAttachmentDropsOnlyItsLog,TestLogBatcher_NoRequestWhenNoLogIsLeft,TestLogBatcher_SameFileNameStartsANewBatch,TestLogBatcher_FileOfAnAttachmentIsClosedAfterTheRequest.e2e/log_batcher_test.go:TestLogBatcher_SameNamedAttachmentsKeepTheirContent(two logs withfile.namescreenshot.txt: two requests, and each log's downloaded attachment,GET /api/v1/data/{project}/{id}, helperenv.data, has its own content).endlock, the abort budget, Flush), README "Reporting session", SKILL.md library table.Docs
AGENTS.md(file table and design notes for the session, the batcher's slots andSync, and reporter fail-fast),README.md(a new short "Reporting session" section),.claude/skills/reportportal/SKILL.md(library table).Behaviour change
For library users, everything is additive.
LogBatcherbehaves as before.OnBatchandSyncare new.gorp report test2jsonends in the same state as before: launch, items and statuses are unchanged, and on any failure the open items and then the launch are INTERRUPTED and the exit code is ≠ 0. The accepted differences:Abort, instead of never being read.uuid:hierarchyServerandrecordingServer.TestReportLaunch_InterruptFinishesOpenItemsBeforeLaunchnow asserts on the recorded UUIDs instead oftest-1/suite-1.newTestReporter,sentLogsandTestReporterLog_ItemUUIDuseAttachLaunch+Launch.Itemhandles, and their literal-ID assertions are unchanged.TestReportLaunch_CancelledContextInterruptsLaunchonly gained a time assertion. No other existing test changed. Both "reporting logs" error-text assertions still pass, because the session wraps batch errors asreporting logs: ….Abortstill sends the logs the batcher already holds (the old code lost them on Ctrl-C, because the batcher used the canceled ctx). It waits for them at most 2 s, so a hanging log endpoint delays the INTERRUPTED finishes by at most that much. Logs not sent by then are counted in the error.Abort/AbortItemsno longer stop at the first item finish that gets no answer or a 5xx. They try the other open items and give up after 3 (the breaker threshold) such failures in a row or when ctx ends;Abortthen sends the launch finish unless it gave up. On a dead server this sends up to 3 item finishes instead of 1, also after the breaker opened.Flushreturns an error matchingErrSessionClosedwhen an abort dropped what it waited for (was nil). A log whose attachment can't be read is dropped alone; the other logs of its batch are sent (before, the whole batch was lost). Logs with the same attachment name go in separate requests. AFinishwhose ctx ends while anAbortruns returnsErrSessionClosed.Verification
go build ./... && go vet ./... && go vet -tags e2e ./e2e/: OK.go test -race -count=1 ./...: OK.go test -race -count=20 ./pkg/gorp/ ./internal/commands/also passes, on the final code.go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.15.0 run --build-tags e2e ./...: 0 issues.e2e against a local ReportPortal (docker-compose
gorp-local, not demo):go test -tags e2e -count=1 -v ./e2e/...passed 21 tests, the 18 existing ones plus the 3 new session tests, in 68.9 s, on the final code. One earlier attempt failed with "connection refused" partway through, because the colima VM had stopped under the server. After a restart the suite passed. The suite prints "could not delete leftover launch … 500 TransientObjectException" for launches 24 to 312, which are older than this branch. That is a server-side delete failure on those leftovers, not a test failure.AGENTS.md rule 5: a real
go test -json -count=1 ./...(Go 1.27.4) of a probe package with pass, fail (t.Errorfover two lines), a parallelsize=1/size=2table and a skip, through the migrated binary (gorp report test2json --file events.jsonl --launchName gorp-wave-l6-test2json).example.com/probeFAILED; TestPass/TestTable PASSED, TestFail FAILED, TestSkip SKIPPED under the suite;size=1/size=2under TestTable." p_test.go:6: expected 1\n\n got 2\n".Review fixes:
go build ./... && go vet ./... && go vet -tags e2e ./e2e/OK;go test -race -count=1 ./...OK;go test -race -count=50 ./pkg/gorp/ ./internal/commands/OK (103 s / 56 s);go test -race -count=100 -cpu 1,2,8 -run 'TestSession_ChaosEndsCleanly|TestSession_AbortDoesNot|TestLaunch_' ./pkg/gorp/OK; golangci-lint v2.15.0run --build-tags e2e ./...: 0 issues. e2e was not rerun for the review fixes (the local server was in use); unit tests only.AbortItems (9aca770):
go build ./... && go vet ./... && go vet -tags e2e ./e2e/OK;go test -race -count=1 ./...OK;go test -race -count=20 ./pkg/gorp/ ./internal/commands/OK (41.9 s / 23.0 s) at 9aca770; the four AbortItems/Finish tests-count=30OK; golangci-lint v2.15.0run --build-tags e2e ./...: 0 issues. e2e on the local ReportPortal 6.0.0 (not demo): 21 passed, 70.4 s.Round 2 (8da3e4d):
go build ./... && go vet ./... && go vet -tags e2e ./e2e/OK;go test -race -count=1 ./...OK;go test -race -count=20 ./pkg/gorp/ ./internal/commands/OK (42.0 s / 22.8 s); the new abort/flush/chaos tests-race -count=20OK; golangci-lint v2.15.0run --build-tags e2e ./...: 0 issues. Before the fix the new tests failed: Abort/AbortItems sent 1 item finish where 3 were expected, the threshold cases sent 1 instead of 3/2,AbortWaitingForAFinishRespectsCtxtook 29.99 s,FlushDroppedByAbortFailsgot nil,UnreadableAttachmentDropsOnlyItsLoggot noLogBatchError(whole batch lost).TestLogBatcher_SameFileNameStartsANewBatchsent one request of 7 logs before the split,FlushWaitingForLogsCanceledByAbortFailsgot nil,FinishWaitingForAnAbortSaysSessionClosedgotErrLaunchNotFinished. e2e on the local ReportPortal 6.0.0 (not demo): 22 passed (21 + the same-name test), 57.3 s at 8da3e4d. Each e2e run leaves one…-TestLaunchListAndMerge-mergedlaunch: the server answers 500TransientObjectExceptionto its DELETE (pre-existing, same for all older ones).-race -count=20 ./pkg/gorp/5 times in a row after the fake fix: all ok.Investigation log
The design was read against c423030.
internal/commands/reporter.goreceivecalledclient.Start*/FinishTestsynchronously and usedr.ctxfor requests, so Ctrl-C canceled a hanging request at once. Under the design, worker requests use the session's internal ctx.TestReportLaunch_CancelledContextInterruptsLaunch(report_robustness_test.go,onItemStart = cancel, handler waits up to 5 s for disconnect) would then wait for the in-flight start insideAbort(context.WithoutCancel(ctx)): 5 s in the mock, up to the 30 s HTTP timeout in real use. Design fix: two contexts,Session.ctx(batcher + worker; canceled by the breaker or an expiredClosectx) andSession.opCtx(worker requests; also canceled byAbort).Abortcancels the operation under way and treats a canceled start as possibly stored (open set). It still sends the logs the batcher holds with the livectx. Seeshutdowninsession.go, andrunStart/reportUnlessCanceledinsession_queue.go. The test runs in milliseconds.Breaker rule "counts only if the request started after the last counted failure".
OnBatch(logs, err)as designed fires only when a request ends, so it cannot tell when the request started. Design fix: the batcher has two unexported hooks that the session sets:begin() uint64, called when a request starts, andobserve(token, logs, err), called when it ends. The publicOnBatchstays as designed. The breaker keeps a generation number that every counted failure increments, and only results of the current generation count (breaker.generation/recordinsession_breaker.go). A first version comparedtime.Now()readings. That was replaced because the CI matrix includes Windows (.github/workflows/build.yml), and a coarse clock could make two readings equal. Covered byTestSession_BreakerCountsConcurrentBatchFailuresOnce: 4 batches are held in the handler until all 4 have arrived, then all get 502, with threshold 2 → not open. One more failure → open.Syncrace:Add/Flushcalltake()undermu, then block insendwaiting for a slot. A counter incremented inside the request goroutine would read zero during that gap. Fix: batches are numbered and registered inunfinishedinsidetake()undermu, and removed afterOnBatch.Syncwaits until no batch numbered ≤ its snapshot is unfinished (log_batcher.go). To keepSyncbounded by ctx,errgroup.SetLimitbecame a slot channel:Addacquires a slot beforeGo, whileSyncacquires it inside the goroutine.Classification of "no response".
retryableError(retry.go) returns true for any error whose text is not on its permanent list. That includes non-transport errors such asunable to read multipart: open …. Narrowed: a no-response failure must also be a*url.Error(classifyResult).TestSession_NoResponseCountsForTheBreakerchecks that connection refused is classified as a failure.Response
idof item starts: the session ignores it and uses the client UUID, because children may already be queued with that UUID. ReportPortal echoes theuuid, and retries depend on it (L4). The fakes that answered fixed ids (hierarchyServerinreport_hierarchy_test.go,recordingServerinreport_robustness_test.go) now echo it.reportingMockServerand theOutputTypeErrorLevelsserver keep fixed ids and still pass, because they route by path prefix.Abort order: "latest start first" alone breaks with re-opened containers. A re-opened ancestor is added after its children, so it would be finished first. Changed:
openItems()sorts by depth (deepest first), then by order of entry (latest first). Covered byTestSession_AbortReopensContainers.Finish of an attached launch: the design says "sends nothing and returns
ErrLaunchAttached".Launch.Finishon an attached launch also runsClose(ctx), so the session's goroutines stop on that call as well.A finish of an item that got no answer, a 5xx or was canceled keeps the item in the open set, so
Abortre-finishes it with its status. An answered failure (4xx) removes it from the open set: repeating the finish can't help.TestSession_FinishDeadlineDoesNotFinishLaunchcovers the canceled case.The reporter's
interruptlogs at WARN only whenAbort's error matchesErrLaunchNotFinished.Abortalso returns the errors not taken yet, which include the one that caused the interrupt. Logging those at WARN printed a misleading "unable to finish the interrupted launch" next to a launch that was finished INTERRUPTED (seen in theTestReportLaunch_FailedStartInterruptsLaunchoutput).A drop by
Abortis not reported as an error (decision 8: document it). Drops caused by the breaker or by an expiredClose/Finishctx are summed up in the returned error.Review finding: fail-fast did not cover the final flush. With
--file, the input ends in milliseconds, soreceiveis usually insideFlushwhen the first request fails, and the whole queue would be drained beforeinterruptran. That is not accepted difference (a), and with a hanging server it costs three timeouts instead of one. Fix:flushUntilFailedcancels the flush context whenreportFailedcloses (reporter.go).TestReporter_FailureAfterInputEndedStopsReportingreproduces the race deterministically: the input is closed before the 500 is released. It sent 202 starts without the fix and at most 5 with it.Launch.Abortreads and changes the open set. ConcurrentAbortcalls are serialized withSession.abortMu(renamedendMuin the review fixes, which also serializeLaunch.Finishwith it, see 16), so the "safe for concurrent use" claim holds.The bound on requests: the 30 s timeout is
defaultHTTPTimeoutinpkg/gorp/client.go:14, thehttp.Client.TimeoutofWithApiKeyAuth. A client built with a custom*http.Clientthat has no timeout makesAbort(context.WithoutCancel(ctx))in the CLI unbounded per request. The CLI usesWithApiKeyAuth.Test fakes must read request bodies to EOF (
io.ReadAll, and drain afterFormValue). Otherwisenet/httpdoesn't notice the client went away and<-r.Context().Done()handlers hang; this was found as a hang inTestSession_CloseDeadlineStopsEverything.Review: Abort with
/loghanging. Reproduced with the reviewer's experiment: 20 logs,MaxEntries: 1, 4 in flight, client timeout 2 s.Abort(Background)took 3.9 s, waited for the client timeouts, and a 5th request was sent after Abort began. Fix: detach plus theabortLogWaitbound (see Changes).TestSession_AbortDoesNotWaitForLogsThatHanghas aworkervariant (the worker is parked inAdd) and atimervariant (the flush timer is parked insend,MaxInFlight: 1). With a 1 min client timeout and a 200 ms bound, Abort takes < 2 s, exactlyMaxInFlightlog requests are seen, and the item and launch are INTERRUPTED. The old behaviour is measured by the experiment above.Review: Finish. The old code sent a second launch finish on a second
Finishand returned nil. WithFinishblocked in the drain whileAbortran, the launch was finished PASSED while Abort was still finishing items, and Abort skipped its own launch finish. Fixed and covered byTestLaunch_FinishTwiceSendsOneFinish,TestLaunch_FinishAfterAbortSendsNothing(Abort fails with a 503, Finish sends nothing, a second Abort finishes INTERRUPTED),TestLaunch_FinishWaitingForTheQueueIsStoppedByAbort(one launch finish, INTERRUPTED, after the items), andTestLaunch_AbortDuringFinishWaitsForIt(Abort waits for the launch finish under way and then finishes only the open item). All four fail on 3c4f01a.Review: trip accounting. Old: 3 × 503 sent
r0,r1andr2, the handler got onlyr0andr1, andClosesaid "1 reporting operations … not sent". Old: a start in flight when a log batch tripped the breaker gavecontext canceled, which does not matchErrBreakerOpen. Cause:opCtx.Err()/s.ctx.Err()was read afterrecordhad tripped and canceled. Covered byTestSession_RequestThatTripsTheBreakerIsReportedandTestSession_LogBatchThatTripsTheBreaker.Review:
Close(canceledCtx)after the worker stopped returned an error in 113 of 200 calls, becauseselectpicks a ready case at random.TestSession_CloseAgainWithEndedContextruns it 200 times.Review 4a, confirmed.
TestReportLaunch_CancelWithAFullQueueInterruptsAtOnce: 1500runevents, the first start hangs for 20 s, cancel after 300 ms. The old code returned after 20.0 s. The fix returns in < 5 s with the launch INTERRUPTED. The session part already worked, sinceAbortclosesspaceand setsclosed.TestSession_AbortReleasesCallersOfAFullQueuepins that. What was missing is that nobody called Abort whilereceivewas blocked.Review 4b, confirmed.
CloseduringStartLaunchreturned nil, and thenbeginstarted the worker and the timer.TestSession_CloseWhileTheLaunchStartsfails on 3c4f01a. With the fix, the launch is left on the server and documented in the error. A best-effort finish was rejected: it would be a request nobody asked for, with a status the caller didn't choose.Review 4c, confirmed. A 502 on a new child of a finished suite: the old Abort finished the child and not the suite.
TestSession_AbortFinishesTheParentsOfAStartThatMayBeStoredcovers it.Review 4d, a fake problem, not a product bug. In the reviewer's chaos test,
require.NoErroratsession_helpers_test.go:168failed with "unexpected end of JSON input". Thatrequireran in a handler goroutine. Resty (resty.dev/v3@v3.0.0-rc.4,middleware.gohandleMultipart) streams parts through a pipe with agracefulStopReaderthat stops at the cancel. The deferredmw.Close()still writes the closing boundary, so a canceled upload arrives well-formed with a truncated JSON part. The client has given up on such a request, and the fake now answers it 400 without asserting. The same chaos run also showed "launch finish with 1 requests under way" in variant 2 (Abort, Close and Finish at once). That was finding 2, not the fake. It is gone after the fix: 0 in 3 × 300 runs. Ported asTestSession_ChaosEndsCleanly.AbortItems. 7377b08 (on
feat/session-ginkgo) split the oldAbort(abortMu) and conflicts with 8ced547 insession.go/AGENTS.md, so it was re-implemented on the newAbortinstead of cherry-picked. Decisions: drop beforeendMuandaborted = trueas inAbort, soFinishcannot finish a launch the owner is stopping; noErrLaunchNotFinished(the 7377b08 test assertsNotErrorIs);l.finishednot set, because the session never sees the owner's finish. The wrapper's use (pkg/ginkgo/cmd/ginkgo-rp/main.go,rpLaunch.abort) callsAbortItemswithstopLaunchTimeout*2/3, thenr.client.FinishLaunchdirectly (not through the session) withstopLaunchTimeout/3.B1, same-named attachments in one request. service-api
ControllerUtils.findByFileName(src/main/java/com/epam/reportportal/base/util/ControllerUtils.java:52-61) takes the first part of the name and removes it from theMultiValuedMap(files.get(filename).remove(multipartFile)), since commit 5193f58945 "EPMRPP-87421 fixed attachments handling" (2023-11-22, released in 5.11.0).LogAsyncController.createLog(batch,:125-170) walks the logs in order, so on the happy path the n-th log of a name gets the n-th part of that name. Live check on the local server (reportportal/service-api:6.0.0), 9aca770 (no batcher change): two logs "shot BEFORE"/"shot AFTER", bothfile.namescreenshot.txt, in one request, contents downloaded withGET /api/v1/data/{project}/{binaryContent.id}: each log had its own content. ButcreateLogcallsvalidateSaveRQbeforefindByFileName(:148-152), so a log rejected in validation never takes its part. Second live probe (a throwaway e2e test, not kept), one rawSaveLogBatch: log 1 level"x"(@Size(min = 3)onSaveLogRQ.level) with partshot.txt=CONTENT-OF-FIRST, log 2 levelinfowith partshot.txt=CONTENT-OF-SECOND. Answer: entry 0 failedIncorrect value in save log request 'x' in field 'level', entry 1 ok; the stored log "second-valid" has contentCONTENT-OF-FIRST. So the finding is real whenever an earlier same-named log of the batch is rejected; the split was implemented. (The first try put the logs on the launch;GET log?filter.eq.launchIdlists item logs only, so the test uses an item.)B2. (Final rule: the threshold also applies with the breaker open; a first version used 1 there, which reproduced the finding on the usual path, see
TestLaunch_AbortAfterTheBreakerTriesEveryItem.)abort(session.go, before::702-722) returned at the firstbreakerFailure. Reviewer'sTestReview_AbortStopsAtFirstSuiteFailure(Ginkgo wrapper): with 3 suites and a 503 on the first finish, the other 2 were never sent. Decision: a separate per-call counter of failures in a row (not the session breaker, which is terminal and may be open already), budget = breaker threshold, 3 if disabled, 1 if the breaker is open (keepsTestSession_BreakerOpensAfterTransientFailures' "Abort against a dead server: one request"). A give-up skips the launch finish (the server is not answering; the launch finish would add one more timeout) and returnsErrLaunchNotFinished; below the budget the launch finish is sent, which satisfies "launch never left In Progress".A1. Reviewer's
TestReview_AbortItemsWaitsBehindHungFinish:AbortItems(ctx=100ms)blocked > 2 s onendMu.Lock()behind a Finish in its launch finish. Ported asTestLaunch_AbortWaitingForAFinishRespectsCtx; on 9aca770 it returned after 29.99 s (the fake answers the launch finish only when the client gives up: the 30 s HTTP timeout). Fix: channel lock with a non-blocking first try, so an uncontended call with an ended ctx behaves as before.A2. Reviewer's
TestReview_FlushDuringAbortItems: Flush blocked behind a hanging start, then AbortItems → Flush returned nil. Cause:dropcloses barriers like a reached one (session_queue.godrop). Ported asTestSession_FlushDroppedByAbortFails(nil before the fix). The same is true after the barrier: Flush inbatcher.Sync, a hung log request,abortLogWait20 ms, AbortItems → the batch is canceled and counted indroppedLogs,Syncreturns nil, Flush returned nil (TestSession_FlushWaitingForLogsCanceledByAbortFails).Finish during Abort with an ended ctx. With the channel lock a
Finishwhose ctx ends whileAbortholdsendfirst returnedErrLaunchNotFinished; round 1 documentedErrSessionClosedfor a Finish during Abort. ThelockEndfailure path ofFinishnow checkss.aborted(TestLaunch_FinishWaitingForAnAbortSaysSessionClosed).Unreadable attachment.
ReportingClient.SaveLogBatch(reporting_client.go:380-384) returnsunable to read multipartbefore sending anything, so the batch's other logs were lost (TestLogBatcher_UnreadableAttachmentDropsOnlyItsLogfailed: noLogBatchError, 0 requests). The fix is in the batcher, not inSaveLogBatch, whose contract (one request or an error) stays. OnlyLoaderrors are handled; an I/O error while the body streams still fails the request.Not verified
Multipart.Load), e.g. the Ginkgo agent'sstagedFile, which opens its file at the firstRead, still fails the whole request: onlyLoaderrors are separated per log.Abort→ STOPPED path is unit-tested only.WithRetry+ session against a live server (the CLI keeps retries off).Flushpolicy is out of scope.🤖 Generated with Claude Code