Repository navigation
[Server] Log every 5xx with its cause and a request ID - #1999
Conversation
18751d9 to
ff09724
Compare
|
/review |
yili-db
left a comment
There was a problem hiding this comment.
[AI Assisted] Overall the approach looks right: Armeria's own request ID through a Log4j ContextDataProvider adds no API surface, and logging once in BaseExceptionHandler.handleException with each dialect's actual status is clean. Main gaps: the logging behavior has no tests, two description claims don't fully hold (SCIM 5xx, and the root cause on the isolation-restore path), and the bootstrap change could be its own PR. Details inline.
| } catch (BaseException e) { | ||
| // IGNORE - this should be user not found exception. | ||
| // Any other lookup error, such as an unreachable database, fails startup. | ||
| if (e.getErrorCode() != ErrorCode.NOT_FOUND) { |
There was a problem hiding this comment.
[AI Assisted] Good change, but failing startup on any non-NOT_FOUND lookup error is a user-visible behavior change unrelated to logging, and the Compatibility note doesn't mention it. Can this go in its own PR? Its tests also exercise UnityAccessUtil from UserRepositoryTest; a UnityAccessUtilTest in auth/decorator would fit better.
There was a problem hiding this comment.
This change is what makes this failure visible. Before, the catch dropped every admin-lookup error and treated it as "no admin yet", so the real error was never logged anywhere. To log it, the error has to stop being swallowed, so it's now rethrown and startup fails with the real error as its cause. It's a small change (rethrow when the error isn't NOT_FOUND), so I'd like to keep it here, and I've added it to the Compatibility note. If you feel strongly about it, I can move it to its own PR.
| }); | ||
| } catch (Exception e) { | ||
| LOGGER.debug("Could not read the Casbin policy version", e); | ||
| LOGGER.warn( |
There was a problem hiding this comment.
[AI Assisted] nit: A failed deny-path probe doesn't advance lastCompletedProbeAtNanos, so during a DB outage every denied request logs a WARN with a stack trace. Not a blocker, since those requests already log 5xx ERRORs during an outage. Follow-up idea: log the stack trace only when reads go from healthy to failing.
There was a problem hiding this comment.
This is intentional. While the database is down, each failed read logs a WARN, so the log keeps showing that the problem is ongoing and why grants aren't propagating. An operator might be searching the logs for this error long after the outage started; logging only the first failure would leave a single line from when it began. The background refresh also runs on a fixed interval (server.authorization.policy-refresh-interval, 1 minute by default), so it adds at most one WARN per interval.
timothyw553
left a comment
There was a problem hiding this comment.
i have left one comment. please take a look at Yi's comments -- I mostly agree with them.
timothyw553
left a comment
There was a problem hiding this comment.
Generally looks good to me.
|
Local AI review run (the repo's Roles:
Round 1 outcomes:
|
|
/review |
|
Re: AI review (today's run) Thanks. Here's what changed:
|
|
/review |
1 similar comment
|
/review |
|
Re: AI review (b9cab14) None of these findings need a change in this PR:
|
| } | ||
| // Unlike push(), replace() doesn't throw when another request's context is current. | ||
| try (SafeCloseable ignored = ctx.replace()) { | ||
| LOGGER.error("Request failed", cause); |
There was a problem hiding this comment.
[AI Assisted] I ran this branch and forced a 500 (POST /models with an unwritable storage root). The line reads:
02:01:15.814 ip-10-90-28-182 [armeria-common-worker-3-2] ERROR io.unitycatalog.server.exception.BaseExceptionHandler request_id=b69529ce5b4b0d3f - Request failed
io.unitycatalog.server.exception.BaseException: Failed to create directory: ...
Unless the access log is on, nothing in server.log says which endpoint failed. Could the message carry the method, path and status, e.g. LOGGER.error("Request failed: {} {} -> {}", ctx.method(), ctx.path(), status.code(), cause)? ctx.path() leaves out the query string, so query parameters stay out of the log.
There was a problem hiding this comment.
Agreed the endpoint should be in the log, but not on this line. This line's job is to make sure no exception is swallowed: each 5xx is logged once, with its cause and request ID. Which endpoint a request hit is a different concern: it belongs in one line logged when the request starts, for every request, not just the ones that fail. I'll add that as a separate PR. It doesn't depend on anything here, and once it lands this line is tied to its endpoint through request_id, like every other line of that request.
There was a problem hiding this comment.
[AI Assisted] Fair, that's the better place for it. Could you link the follow-up issue here so it's tracked?
deff1f0 to
a1c108d
Compare
| e instanceof TransactionRollbackException | ||
| || (e instanceof BaseException baseException | ||
| && !baseException.getErrorCode().getHttpStatus().isServerError()); | ||
| if (unlogged && e.getSuppressed().length > 0) { |
There was a problem hiding this comment.
[AI Assisted] After the rebase onto #1993 there's a case this misses: when DatabaseErrors maps the error to a 4xx (PostgreSQL 54000 to INVALID_ARGUMENT), rollBack puts the rollback failure on e but throws a new wrapper around it. The wrapper's getSuppressed() is empty, so nothing warns, and the handler doesn't log a 4xx, so a failed rollback leaves no trace. Logging the rollback failure where it's caught would cover this and drop the suppressed-list inspection. Not a blocker.
There was a problem hiding this comment.
Good catch. Fixed in c9a5a40: the check now also looks at the cause, where a wrapped database error carries its rollback failure.
|
Please rebase |
Each log line written while a request is served now carries the ID Armeria generates for that request, so the lines one request writes can be found together, and log lines name the host. The API is unchanged: no request or response header is added. Failures that left no trace in the server log are now logged: - Each 5xx is logged once at ERROR, with its cause, where the error response is built (UC, Iceberg, Delta and SCIM). Token exchange no longer logs a failed user lookup itself, so it is not logged twice. - Database errors keep their cause when wrapped as INTERNAL, and a failed rollback no longer replaces the error that failed the work. - A failed policy-version read during policy refresh is a WARN. - Bootstrap only creates the admin when the lookup says it is missing; any other lookup error fails startup. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
The 5xx log call in BaseExceptionHandler could throw before the error response was built: ctx.push() throws when another request's context is current on the thread, and an appender set not to ignore its errors throws from the log call. Use ctx.replace() for the one log call and catch a failing log call, so the response is always sent. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
The request ID on the line identifies the request, so the 5xx line no longer repeats the method, path and status. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
A failed user lookup during token exchange again names the lookup type and key. The line is a WARN without the stack trace, because the error handler logs the cause once under the same request ID. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
…ly the bootstrap test RequestContextDataProvider (was RequestIdContextDataProvider) now gets the fields it adds to each log line from Armeria's RequestContextExporter, so another request field is one more builtIn entry. It still adds only the request ID. The exporter is built on first use, while a request is served, so it can't initialize Armeria's Flags class during startup logging. Drop the log-capture tests and the TransactionManager additions; they guard regressions that review already catches. UnityAccessUtilTest stays for the bootstrap change. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
Move the two bootstrap tests out of a new UnityAccessUtilTest into the existing UserRepositoryTest. The missing-admin case now runs against the real repository and its NOT_FOUND on H2; the lookup-failure case spies on the repository. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
The Helm chart renders its own log4j2 config, so it now uses the same pattern as etc/conf/server.log4j2.properties: the host name and request_id. Also make RequestContextDataProvider.REQUEST_ID_KEY private; it was public only for tests this PR no longer has. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
A TransactionRollbackException tells the caller the work was rolled back, and the replay path then reports a no-op success. If the rollback itself failed, the guard added the rollback error as suppressed and rethrew the signal, so the caller reported success and the rollback failure was never logged. Throw INTERNAL with the signal and the rollback error attached instead, so it is logged as a 5xx. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
Nothing in the block throws in practice: Log4j rethrows from a log call only for an appender configured with ignoreExceptions=false, and replace() doesn't throw. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
…error Since unitycatalog#974 moved createUser onto TransactionManager, a database error arrives as BaseException(INTERNAL), and the SCIM create catch-all mapped it to BadRequestException, so the error body said 400 and the 5xx was not logged. Map server-side codes to ServerErrorException with the original exception as the cause. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
Cover a failed rollback: the original error stays the cause with the rollback error suppressed, and under a TransactionRollbackException the request fails as INTERNAL instead of passing for a no-op success. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
The init container ran envsubst over the log4j2 template. With no
variable list, envsubst blanks every ${...} reference, so the Log4j
${hostName} lookup became an empty string and Helm log lines had no
host. The template has no environment placeholders, so copy it.
Signed-off-by: Shubham Bansal <[email protected]>
Co-authored-by: Isaac <[email protected]>
- Keep the ContextDataProvider registration in the shaded jar, so servers started from it log request_id. - Include the reason in the token-exchange lookup warning. - Say in configuration.md that host and request_id come with the default log4j2 config, and how to add both to a custom one. - Document the 5xx logging in BaseExceptionHandler. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
Catching a failed rollback kept the original error, but each fix it needed added another case: a replay signal had to become INTERNAL, and the isolation restore in finally could still replace the error. Go back to main's behavior, where a failed rollback fails the request with its own error. Keep only the original cause on the INTERNAL wrapper, and assert it in the existing runtime-exception test. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
…re fails A failed rollback or isolation restore replaced the error that made the transaction fail, so the caller and the log saw only the follow-on failure. Add each later failure as suppressed, so the original error stays the thrown error or its cause: - the isolation restore becomes a try-with-resources resource, so a failed restore is added to the error in flight; after a commit it still throws; - a failed rollback is added to the operation's error; under a replay signal, whose callers act as if its work was undone, it fails the request as INTERNAL. TransactionManagerTest checks the thrown error and its cause at each failure point (isolation set, operation, commit, rollback, restore, session close, also after a commit), and the suppressed failures. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
A failed rollback, isolation restore or session close is kept as suppressed on the error thrown. The error handler logs only a 5xx, and a caller takes a replay signal as a normal outcome, so behind a 4xx or a signal those failures were never logged. TransactionManager now logs them as a WARN in that case. Also moves the set/begin/restore/close behaviour from the @throws tags into the method description, and narrows the token exchange comment to 5xx. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
Checks that Log4j can find RequestContextDataProvider through ServiceLoader, and that it supplies the request's ID inside a request and nothing outside one. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
Hibernate returns the connection to Hikari when the transaction ends, and Hikari resets an isolation level that was changed, so the restore ran on a fresh connection and only added a checkout that could fail after a commit. Drop it and the tests that pinned it; the session-close failure takes its place in the failure matrix. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
Without an isolation level, the matrix rows with no cleanup failure repeat the existing operation-failure tests, and nothing can be suppressed on a close failure after a commit. AGENTS.md and the setup comment now say the pool resets the level. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
…tcome With one pooled connection, the second transaction reuses the connection the first set to REPEATABLE_READ, so the test fails if the pool stops resetting the level. The failure matrix's expected outcome is an enum, like the operation error next to it. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
A database error that DatabaseErrors maps to a 4xx (PostgreSQL 54000) is wrapped in a new BaseException, and its rollback failure stays suppressed on the wrapped cause. The cleanup warning checked only the thrown error, so it missed that case; it now checks the cause too. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
IcebergRestExceptionHandler now overrides handleException (unitycatalog#1984), so it skips the base method that logs each 5xx. Log it there too. Co-authored-by: Isaac <[email protected]> Signed-off-by: Shubham Bansal <[email protected]>
c9a5a40 to
fe3dc9e
Compare
|
Rebased onto main (4626de6); the branch is now at fe3dc9e. One fix came out of it: #1984 gave |
**PR Checklist** - [x] A description of the changes is added to the description of this PR. - [ ] If there is a related issue, make sure it is linked to this PR. - [x] If you've fixed a bug or added code that should be tested, add tests! - [ ] If you've added or modified a feature, documentation in `docs` is updated **Description of changes** `main` fails `AuthServiceTest.testScimCreateUserDatabaseFailureIsAServerError`, and so does every open PR's "All tests" job, because CI tests each PR merged with `main`. #1994 requires `X-Requested-With: XMLHttpRequest` on writes authenticated with the `UC_TOKEN` cookie. This test, added by #1999 before #1994 merged, sends a SCIM create with that cookie and no header, so it gets `403 Forbidden` instead of the `500` it checks. It now sends the header, like the other cookie tests #1994 updated. <details> <summary>📐 Design notes & details</summary> - On the commit just before #1994 (`6ee532c`), which already has #1999's test, `AuthServiceTest` passes (8/8). On `main` (`45320ad`) it fails with `expected: 500 Internal Server Error but was: 403 Forbidden`. With this change it passes on `main` (10/10). - The test still covers what #1999 added it for: a database failure inside the SCIM create is a 500, not a client error. </details> This pull request and its description were written by Isaac. Signed-off-by: Shubham Bansal <[email protected]> Co-authored-by: Isaac <[email protected]>
…2056) **PR Checklist** - [x] A description of the changes is added to the description of this PR. - [x] If there is a related issue, make sure it is linked to this PR. - [ ] If you've fixed a bug or added code that should be tested, add tests! (config-only change, verified by hand as described below) - [x] If you've added or modified a feature, documentation in `docs` is updated **Description of changes** Closes #2055. With the shipped `etc/conf/server.log4j2.properties`, a server that logs steadily keeps only about 5 seconds of history. The archive pattern ends in seconds (`%d{MM-dd-yyyy-HH-mm-ss}`), and `TimeBasedTriggeringPolicy` rolls over on the most specific unit of the date pattern, so `interval = 1` meant one archive per second. `IfAccumulatedFileCount` then kept only the newest 5 archives. Startup lines, and the 5xx `ERROR` line #1999 added, were deleted within seconds. Changes to `etc/conf/server.log4j2.properties`: - The archive pattern is now `server-%d{yyyy-MM-dd-HH}-%i.log.gz`, so the log rolls over hourly. The 10MB size trigger still splits a busy hour into `-1`, `-2`, ... archives, and archive names now sort by date. - Archives are deleted by age and total size, not by count: `IfLastModified` with `P7D`, ORed with `IfAccumulatedFileSize` over `1GB`, replaces `IfAccumulatedFileCount`. The `IfFileName` glob is unchanged, so archives left over in the old naming scheme also age out after 7 days. - `strategy.max` goes from 5 to 20, so an hour that logs more than 50MB no longer overwrites its own oldest archives. `docs/server/configuration.md` now describes the default rolling and retention. Compatibility: only the default config file changes. Archive names change format, and archives are no longer capped at 5 files, so disk use is bounded by 7 days of logs or 1GB of archives, whichever is smaller. The Helm chart renders its own console-only config and is not affected. Validation: I ran a small program against log4j-core 2.26.1, the version the server uses, with the old and the new config file: - One line every 250ms for 8 seconds. With the old config, `etc/logs` ended up with 4 per-second archives, and `server.log` started at line 28. With the new config, no archive was created and `server.log` held every line from line 0. - With the new config, a 25MB burst, starting with an archive last modified 8 days ago, one modified 6 days ago, and an unrelated `other.log` in `etc/logs`. The burst rolled over twice, to `server-2026-10-26-10-1.log.gz` and `-2.log.gz`. The 8-day-old archive was deleted, and the 6-day-old archive and `other.log` were kept. Log4j printed no status warnings for the config. --------- Signed-off-by: NopeCharon <[email protected]>
PR Checklist
docsis updatedDescription of changes
A failed request left no trace in the server log, and the log lines one request wrote could not be told apart from another's. With this change:
request_id=<id>, the ID Armeria generates for that request, and every line names the host (with the shipped log4j2 configs).ERRORwith its cause, where the error response is built (UC, Iceberg, Delta, SCIM).WARN, because revokes from other instances stop arriving until a read succeeds.Compatibility: the API is unchanged; no request or response header is added. The default log line format gains the host name and
request_id=, so log parsers that match the old pattern need updating. The Helm chart copies the log4j2 config template instead of runningenvsubston it, so a${VAR}in it is now a Log4j lookup. A 4xx whose rollback also fails now returns that 4xx; before, it returned 500. A transaction with a custom isolation level no longer checks out a second connection after it commits, so a committed write can no longer come back as a 500 when that checkout fails. Startup now fails if the admin lookup fails with anything other than not-found, instead of treating it as "no admin yet". A SCIM create-user that fails in the database now reports"status":"500"in the SCIM error body instead of"400"; the HTTP status stays 500. Log levels that alerts may match on change: the token-exchange lookup failure moves fromERRORwith a stack trace toWARNwithout one, and the Casbin policy-refresh read failures move fromDEBUGtoWARN.📐 Design notes & details
RequestContextDataProvider, a Log4jContextDataProvider, exports fields of the current Armeria request through Armeria'sRequestContextExporter, the same exporter Armeria's Logback integration uses. Today it exports onlyrequest_id; another field is one morebuiltIn(...)entry. The Armeria context follows the request onto the blocking executor, where a per-thread MDC would not.api/all.yaml/api/delta.yamldefines a request-ID header, so this PR doesn't read one from callers or return one. That would be new API surface, and it can come later through the spec if wanted.BaseExceptionHandler.handleException(and the Iceberg handler's override of it, from [Server] Report a missing namespace as a missing table on table routes of the Iceberg REST catalog #1984), using the status the dialect actually answers with (Delta has its own), so each 5xx is logged once, with only its cause: the request ID on the line identifies the request. Token exchange still names the failed lookup (email or client ID), now as aWARNwithout the stack trace, so the cause isn't logged twice. A rollback or session-close failure behind a 4xx or a replay signal, which the handler doesn't log, is aWARNfromTransactionManager.ERROR.createScimUserlabelled database errors 400 since Clean up code for transaction management and auth #974 wrapped them asBaseException(INTERNAL); they now map toServerErrorExceptionwith the cause, so they are logged.com.linecorp.armeria.*property is set, Armeria logs during startup before its context storage exists. The provider returns no fields for those lines instead of throwing, and builds the exporter only once a request is served, as Armeria's own appender does.DeltaPropertyMapperdropping its cause.AuthServiceTestmakes the database reject a SCIM user insert and checks the 500 status in the body;TransactionManagerTestfails each point in turn (isolation set, operation, commit, rollback, session close) and checks the thrown error, its cause and the suppressed failures; its existing real-database test checks that the level is back to the original after a transaction; two bootstrap tests are inUserRepositoryTest;UnityCatalogServerTest.logLinesCarryTheRequestIdchecks that Log4j finds the provider and that it supplies the request ID inside a request and nothing outside one. There are no log-output tests.build/sbt testpassed at b9cab14, except for one run ofSdkModelCRUDTest.testModelCRUD, a known same-millisecond timing flake in model updates that this PR doesn't touch; it passes on rerun. The later commits, and the rebase onto main at 4626de6, were checked with the test classes they touch.This pull request and its description were written by Isaac.