Skip to content

fix: classify agent errors by type, not by words in the message - #896

Merged
discostu105 merged 1 commit into
mainfrom
fix/typed-agent-errors
Dec 5, 2026
Merged

discostu105 merged 1 commit into
mainfrom
fix/typed-agent-errors

Conversation

@discostu105

@discostu105 discostu105 commented Dec 4, 2026 •

Copy link
Copy Markdown
Member

What broke

Approach

Errors now carry their type from where they are created, and are classified with errors.Is / errors.As:

  • Config: config load/save errors are wrapped as configError. A config that loads but cannot be used is a session.ConfigError: an unresolved ${VAR} environment, a local environment that is not a Dynatrace origin, or a token missing from a sealed config.
  • Contexts and tokens: new session.ErrNoCurrentContext, session.ContextNotFoundError and session.TokenRefreshError.
  • Timeouts: new httpclient.TimeoutError (implements Timeout() bool) for dtctl's own waits. Deadlines and network timeouts are recognised by type in every invocation mode.
  • Malformed input: *json.SyntaxError, *json.UnmarshalTypeError, *yaml.TypeError and yaml.v3's own syntax errors are recognised anywhere in the error chain. Invalid embedding Session options become invalidInputError.
  • Wrong-URL hints: only for 401/403 or DNS / connection-refused errors. Extension 403 errors now wrap the APIError instead of dropping it.
  • Command-line errors: cobra's unknown-command error is recognised by its exact form plus the command path it names. Unknown flags are recognised as *pflag.NotExistError.
  • Text fallback: validation_error keeps one, for messages dtctl wrote itself that start with invalid or validation failed.

Apart from the changes listed below, error messages are unchanged.

Breaking (agent-visible)

The set of error codes and the envelope schema are unchanged. Some errors now get a different code:

  • A missing or unselected context is now context_error (it used to be error).
  • A client-side deadline in the CLI is now timeout (it used to be error).
  • An extension 403 is now permission_denied with exit code 3, and its message gains the API error.
  • dtctl get without a resource is now error (it used to be config_error).
  • Errors that only quote config/timeout/invalid/context, or 401/403, inside a name or server text now fall back to error, and they no longer get the wrong-URL hints.

Message change: in dtctl usage, the text now reads "no current context set; …" instead of "no current context; …".

#819 (an invalid flag value followed by --agent) was already fixed on main by #864. This PR adds a regression test for it.

Verification

  • go build ./..., go vet, golangci-lint (new code): clean.
  • Unit tests pass for cmd, the touched pkg/ packages, and sdk/{session,httpclient,api/...}.
  • Table tests in cmd/error_class_test.go and sdk/session/client_test.go cover the cases from the issues and from the review.
  • sdk/CHANGELOG.md updated.

Agent error codes change as listed above. Per AGENTS.md this is not a breaking change (agent output may change in any minor release).

Fixes #818
Fixes #829
Fixes #819

@discostu105
discostu105 requested a review from a team as a code owner December 4, 2026 22:35

@discostu105 discostu105 left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: the approach is sound, and the cobra/pflag detection and the timeout/context/refresh typing hold up. Two config and validation failures that used to be classified correctly now fall through to error, and the SDK changelog was not updated.

  1. sdk/session/client.go:85 and :94, sdk/session/config.go:991: should-fix. These are real config-file failures that are never wrapped as configError: a project .dtctl.yaml whose ${DT_ENVIRONMENT_URL} did not resolve, a local environment that is not a Dynatrace origin, and a token missing from a sealed config. They come from NewClientFromConfig after Load has succeeded, so configFile() never sees them.
    Scenario: in a fresh clone with DT_ENVIRONMENT_URL unset, dtctl get workflows --agent gives error. On main it gives config_error, which per AGENT_MODE.md means "needs human repair".
    Fix: give these errors a type in the SDK (for example a LocalConfigError), or wrap newClientFromConfig errors that are not ContextNotFoundError/ErrNoCurrentContext and that come from config resolution. Add a test for the unresolved-variable case.

  2. cmd/error_class.go:96 (isDtctlValidationMessage): should-fix. Narrowing the rule to a message prefix also drops malformed input that dtctl wraps.
    Scenario: dtctl exec analyzer X --input '{bad' --agent returns failed to parse input JSON: invalid character 'b' … (cmd/exec_analyzers.go:208). On main that is validation_error; it is now error. The same applies to the other failed to parse …: %w wrappers around encoding/json in pkg/apply and cmd/create_*. It also affects session: invalid safety level (cmd/session.go:150).
    Fix: classify *json.SyntaxError / *json.UnmarshalTypeError (and the YAML decoder's error type) as validation_error with errors.As. This is the same idea as the rest of the PR. Add a table case for a wrapped *json.SyntaxError.

  3. sdk/CHANGELOG.md: should-fix (convention). The PR adds exported SDK API: session.ErrNoCurrentContext, session.ContextNotFoundError, session.TokenRefreshError, httpclient.TimeoutError/Timeoutf. It also changes what SDK callers can see: sdk/api/extension 403 errors now wrap the *APIError and their text gains a : <api error> suffix. None of this is under [Unreleased], while comparable additions (ErrConfigNotFound) were recorded there.

  4. cmd/usage.go:168, :274: nit. The text changes from no current context; select one… to no current context set; select one…. That is harmless, but the PR body says "all messages stay the same". Either reword the body or keep the old text with a small wrapper type.

Checked and fine: the cobra unknown-command regex and command-path check (including noArgs groups and plugin dispatch); GetSpecifiedName against the old UnknownFlagName for the shorthand form; auth refresh wrapping (the old substring also matched failed to refresh tokens); and that no remaining 401/403 path drops its APIError. CI: 22/22 checks green.

@discostu105
discostu105 force-pushed the fix/typed-agent-errors branch from cc8ecc7 to 66075f1 Compare December 5, 2026 03:38
@discostu105 discostu105 changed the title fix: classify agent errors by type, not by words in the message fix!: classify agent errors by type, not by words in the message Dec 5, 2026
@discostu105

Copy link
Copy Markdown
Member Author

Thanks for the review. All four points are fixed in 66075f1 (amended, one push):

  1. Config failures after load. These now return a new session.ConfigError: an unresolved ${VAR} environment, a local environment that is not a Dynatrace origin, a token missing from a sealed config, and the local-config inline/redirected/unbound token refusals. cmd classifies the error as config_error. Tests cover these cases in sdk/session/client_test.go, and there is a table row in cmd/error_class_test.go.
  2. Malformed input. *json.SyntaxError, *json.UnmarshalTypeError and *yaml.TypeError are recognised anywhere in the error chain. So are yaml.v3 syntax errors, matched by the library's yaml: prefix, and only on the decoder's own leaf error. All of these give validation_error. An invalid embedding Session (including session: invalid safety level) becomes an invalidInputError. Table cases cover wrapped JSON and YAML syntax and type errors.
  3. SDK changelog. sdk/CHANGELOG.md [Unreleased] now lists the new SDK types (ConfigError, ErrNoCurrentContext, ContextNotFoundError, TokenRefreshError, TimeoutError/Timeoutf) and the extension 403 change.
  4. PR body. It now names the dtctl usage message change. The title is now fix!:, and the commit and PR carry a BREAKING CHANGE: footer that lists the agent-visible code changes.

CI: 22/22 checks green. The first run hit a data race in sdk/api/query TestExecuteAndPoll_CancelDuringStalledExecuteReturnsAfterGrace on macOS; this PR doesn't touch that package. The Windows SDK job was cancelled alongside it, and both passed on rerun.

The agent error code, the wrong-URL hints and the re-login hint were picked
by substring of the error message, so a quoted name decided them: a missing
dashboard "timeout-overview" reported `timeout`, a workflow
"team-config-sync" `config_error`, an entity "HOST-403" earned wrong-URL
hints. classifyCommandLineError likewise rewrote any error quoting
"unknown command"/"unknown flag" as a cobra usage error, dropping its type,
exit code and suggestions.

Errors are now typed where they originate and classified with errors.Is/As:
- config load/save failures (configError) and session.ConfigError for a
  config that loaded but cannot be used (unresolved ${VAR} environment,
  non-Dynatrace local origin, token missing from a sealed config);
  session.ErrNoCurrentContext, session.ContextNotFoundError,
  session.TokenRefreshError
- httpclient.TimeoutError (Timeout() bool) for dtctl's own waits; deadlines
  and network timeouts are recognised by type in every invocation mode
- malformed input: *json.SyntaxError, *json.UnmarshalTypeError,
  *yaml.TypeError and yaml.v3's own syntax errors, anywhere in the chain;
  invalid embedding Session options are invalidInputError
- wrong-URL hints only for 401/403 and DNS/connection-refused errors;
  extension 403s now wrap the APIError instead of dropping it
- cobra's unknown command error is recognised by its exact shape and the
  command path it names; unknown flags by *pflag.NotExistError
- validation_error keeps one text fallback: a message dtctl wrote that starts
  with "invalid " or "validation failed"

The invalid-flag-value case of #819 was already fixed on main; this adds a
regression test for it.

Agent-visible changes (not breaking per AGENTS.md: agent output may change in any minor release): A missing or unselected
context is `context_error` (was `error`); a client-side deadline in the CLI
is `timeout` (was `error`); an extension 403 is `permission_denied` with
exit code 3 (was `error`, exit 1) and its message gains the API error;
errors that merely mention config/timeout/invalid/context or 401/403 in a
quoted name or server text are `error` and no longer get wrong-URL hints;
`dtctl get` without a resource is `error` (was `config_error`). The `dtctl
usage` message reads "no current context set; ..." (was "no current
context; ...").

Fixes #818
Fixes #829
Fixes #819
@discostu105
discostu105 force-pushed the fix/typed-agent-errors branch from 66075f1 to f0b69f9 Compare December 5, 2026 03:53
@discostu105 discostu105 changed the title fix!: classify agent errors by type, not by words in the message fix: classify agent errors by type, not by words in the message Dec 5, 2026
@discostu105
discostu105 merged commit 49034ac into main Dec 5, 2026
22 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant