Repository navigation
chore: Add test helpers to improve coverage - #166
Conversation
Version more accurately represents version storage. This forks from the WorkspaceHistory name, but I think it's easier to understand Workspace history.
Codecov Report
@@ Coverage Diff @@
## main #166 +/- ##
==========================================
+ Coverage 65.44% 67.45% +2.01%
==========================================
Files 106 106
Lines 5580 5636 +56
Branches 68 68
==========================================
+ Hits 3652 3802 +150
+ Misses 1572 1475 -97
- Partials 356 359 +3
Continue to review full report at Codecov.
|
a703482 to
b2d6337
Compare
b2d6337 to
57efae2
Compare
13ef836 to
16449d8
Compare
16449d8 to
0fb2a5a
Compare
| }) | ||
| client := coderdtest.New(t) | ||
| _ = coderdtest.CreateInitialUser(t, client) | ||
| projects, err := client.Projects(context.Background(), "") |
There was a problem hiding this comment.
I really like how much simpler this is 🎉
| if logs == nil { | ||
| logs = []database.WorkspaceHistoryLog{} | ||
| } |
There was a problem hiding this comment.
I wonder if this is the same issue I saw with projects? Sometimes, I'd get nil for projects returned - even in the case where was no error (and had to do something similar): https://github.com/coder/coder/pull/140/files#r797267887
I didn't get a chance to dive deeper yet (I'll look at it next week) - but wondering if its the same issue here? And maybe a bug with our query or sqlc integration?
There was a problem hiding this comment.
Yup, it is! Not an issue with our sqlc implementation, just a false assumption on my part! We now test for this!
There was a problem hiding this comment.
Cool, good to know! I didn't realize that there could be a case where those functions could return nil (I thought they'd always return an empty array) - but something I'll watch out for now.
| // Use xerrors everywhere! It provides additional stacktrace info! | ||
| //nolint:unused,deadcode,varnamelen | ||
| func xerrors(m dsl.Matcher) { |
There was a problem hiding this comment.
Thanks for adding this 👍
| }) | ||
| if err != nil { | ||
| go p.cancelActiveJobf("send periodic update: %s", err) | ||
| p.cancelActiveJobf("send periodic update: %s", err) |
There was a problem hiding this comment.
Was this intentional to remove all these? It might make sense to split this out to a separate change, if possible - just in case there is flakiness or a race condition introduced, it'll be easier to track down.
There was a problem hiding this comment.
It was intentional! The job was hitting a finished state even though it was supposed to cancel itself.
We can separate it out if you feel strongly. It was a logical lapse when creating provisionerd for sure.
Co-authored-by: Bryan <[email protected]>
| provisionerState := []byte{} | ||
| // If workspace history exists before this entry, use that state. | ||
| // We can't use the before state everytime, because if a job fails | ||
| // for some random reason, the workspace shouldn't be reset. | ||
| // | ||
| // Maybe we should make state global on a workspace? | ||
| if workspaceHistory.BeforeID.Valid { | ||
| beforeHistory, err := server.Database.GetWorkspaceHistoryByID(ctx, workspaceHistory.BeforeID.UUID) | ||
| if err != nil { | ||
| return nil, failJob(fmt.Sprintf("get workspace history: %s", err)) | ||
| } | ||
| provisionerState = beforeHistory.ProvisionerState | ||
| } |
There was a problem hiding this comment.
Is this not needed, or is it handled elsewhere? Wasn't clear to me why this could be removed
There was a problem hiding this comment.
Not needed. This wasn't tested before, and wasn't actually necessary.
bryphe-coder
left a comment
There was a problem hiding this comment.
Just some minor nits, but overall looks like a really nice improvement to our tests 🎉 Thanks for doing this cleanup @kylecarbs !
| settings: | ||
| ruleguard: | ||
| failOn: all | ||
| rules: rules.go |
There was a problem hiding this comment.
suggest using separate files for ruleguard like we do in the monorepo (and using a wildcard here), it helps keep each rule organized, and gives us a way to group related rules
There was a problem hiding this comment.
I'd prefer for us to wait until this becomes more unruly.
| err := os.MkdirAll(p.opts.WorkDirectory, 0700) | ||
| if err != nil { | ||
| go p.cancelActiveJobf("create work directory %q: %s", p.opts.WorkDirectory, err) | ||
| p.cancelActiveJobf("create work directory %q: %s", p.opts.WorkDirectory, err) |
There was a problem hiding this comment.
nice, doing this sync seems like it'll be easier to follow
|
|
||
| jobRunning: make(chan struct{}), | ||
| jobRunning: make(chan struct{}), | ||
| jobCancelled: *atomic.NewBool(true), |
There was a problem hiding this comment.
how come we need to use this atomic class if we're already using locks to protect things?
There was a problem hiding this comment.
Job cancel and completion need to be grouped separately. I tried to make them one before this, but it became more difficult to manage.
If two cancels come immediately after one another, it's not good to lock on a mutex and wait for the other to complete, because a job may cancel itself at the same time provisionerd is canceling it, and lock forever.
| }, | ||
| }} | ||
| data, err := echo.Tar(responses, nil) | ||
| data, err := echo.Tar(&echo.Responses{responses, nil}) |
There was a problem hiding this comment.
personally I find this way of defining structs to be less readable, and prefer the variant that lists fields. this is also order-dependent.
There was a problem hiding this comment.
I agree. I'll adjust this!
| id uuid NOT NULL, | ||
| created_at timestamp with time zone NOT NULL, | ||
| project_version_id uuid NOT NULL, | ||
| name character varying(64) NOT NULL, |
There was a problem hiding this comment.
just curious, are there benefits to defining columns as varchar vs text? or is it just cosmetic?
There was a problem hiding this comment.
Just a nice restriction to prevent someone from making a 10MB name accidentally.
| } | ||
|
|
||
| t.Run("CreateMultiple", func(t *testing.T) { | ||
| func TestUserOrganizations(t *testing.T) { |
There was a problem hiding this comment.
do these functions handle context cancellation? might be nice to add tests to check that the server won't do anything if the context has been cancelled and/or that it can abandon in-progress requests and return early in that case
There was a problem hiding this comment.
The t.Cleanup on coderdtest.New will close all connections, so shouldn't be possible.
I'm adding goleak now though so human error can't exist here. Good suggestion!
|
|
||
| func (e *Error) Error() string { | ||
| return fmt.Sprintf("status code %d: %s", e.statusCode, e.Message) | ||
| msg := fmt.Sprintf("status code %d: %s", e.statusCode, e.Message) |
There was a problem hiding this comment.
it doesn't really matter unless this is a hot path, but using strings.Builder and Fprintf to construct these will reduce allocations
There was a problem hiding this comment.
Good suggestion regardless! Updated it.
| return | ||
| } | ||
| if logs == nil { | ||
| logs = []database.WorkspaceHistoryLog{} |
There was a problem hiding this comment.
I guess this is just to get the JSON to return an empty array instead of nil?
| return | ||
| } | ||
| default: | ||
| tarReader := tar.NewReader(bytes.NewReader(createProjectVersion.StorageSource)) |
There was a problem hiding this comment.
should there be a content negotiation check here? i.e. client should use a Content-Type: application/x-tar on the upload, and server can return 415 Unsupported Media Type - that would allow us to accept other content types in the future
There was a problem hiding this comment.
I suppose the answer is maybe. Right now, the archive is sent as base64 encoded bytes in JSON. That's not ideal, and we'll probably swap it to a file-upload format like mentioned.
b900f18 to
479397d
Compare
95c711e to
b900f18
Compare
ad31063 to
a8a0531
Compare
Updates the Agent Relay docs for general availability and for agent-relay v0.17.0, and adds the version requirements table from RELAY-61. - **Beta to GA:** the sidebar state goes from `[premium, beta]` to `[premium]`, and every page drops its beta callout. The monitoring and SIEM notes now say metric names, log messages, and fields can change between releases, and tell readers to review alerts when they upgrade. Anthropic's own "public beta" line for self-hosted environments stays, because Anthropic's docs still say public beta. - **Version requirements:** `setup.md` gets one table of minimum versions for Coder, Agent Relay, the Terraform provider, both modules, and the Claude Code CLI. The "v0.16.0 or later" qualifiers across the pages are removed, because the table sets a single GA baseline. Module examples move to 1.0.1, the latest tag. Its only change from 1.0.0 is in the README. - **v0.17.0, Claude Code poll loop** ([agent-relay#189](coder/agent-relay#189)): after it handles a session, a pool claims the next one right away and waits 5 seconds only after an empty or failed poll. The "one session every 5 seconds" claim and the provisioner sizing formula that depended on it are replaced in `claude-code.md`. `siem.md` lists the renamed `backoff` log field, which replaces `interval`. - **v0.17.0, redelivery** ([agent-relay#165](coder/agent-relay#165)): if Anthropic redelivers a session while its previous workspace still has a start build or a delete in progress, Agent Relay fails the session instead of building again. This is covered in the build budget, setup failure, and reap delay text, plus a new troubleshooting entry. - **`install_cli`:** the docs no longer say `install_cli = true` removes the Claude Code CLI minimum. The modules skip the install when a CLI is already on `PATH` and never upgrade it. ## Open questions - **GA versions (Steven Masley, per RELAY-61):** the table uses the latest versions as of today: Coder 2.39, Agent Relay v0.17.0, Terraform provider v2.20.0, and modules 1.0.0. If GA ships with newer releases, the table, the early access upgrade steps, and the `claude-code.md`/`cursor.md` module notes need the new numbers. - **Stability at GA:** should the monitoring and SIEM pages promise anything about metric and log stability, or does "can change between releases" stay? - **Backport:** the v0.16.0 docs were backported to `release/2.39` (#32122). This PR probably needs the same once the GA versions are settled. Related: #32519 adds a section to `claude-code.md` in a different part of the page. It shouldn't conflict. <details> <summary>Verification notes and decision log</summary> Verified against agent-relay `v0.16.0...v0.17.0`: - `serviceclaudecoderunners/poller.go` `pollLoop`: `drain` polls again right after each handled hint (`maxHintsPerPoll = 1`). `pollIntervalDefault` (5s) is the startup delay and the backoff after `ErrEmptyPoll`, a retryable poll error, or a license lapse. The relay sets no limit on concurrent builds (README, Claude Code pools). - `workspacedispatcher/dispatcher.go` `reconcile`: with `TerminalOnUnfinishedBuild` (set to `redelivered(hint.Attempt)` in `serviceclaudecoderunners/dispatch.go`), `blocksRedelivery` (START or DELETE pending, starting, or canceling, or deleting) sends the non-retryable nack `agent-relay: the previous workspace was not ready for this session; send a new message to retry` and logs `redelivery found a predecessor build or delete in progress, failing current work order`. `retirePredecessorLocked` runs only for a START that isn't deleting. It cancels the build through `settleBuild`, then deletes the workspace. A running delete is left alone. - A new message is a first delivery, and `AwaitDeleting: true` makes it wait for the delete and then build fresh. - `poller.go`: the `poll loop started` record's field is now `backoff`. No other code emits `interval`. - No CLI flags, environment variables, Helm values, or metric names changed between v0.16.0 and v0.17.0. - Registry `agent-relay-{claude-code,cursor}` v1.0.1 `main.tf` `install_cli`: "A CLI already in the image is used as is and never upgraded." Decisions: - The table states one GA baseline instead of a matrix with one row per relay release. RELAY-61 narrowed the scope to "latest versions as of GA", and the relay doesn't check module pairing at runtime, so older rows couldn't be verified. - The Claude Code CLI minimum of 2.1.224 is kept. Neither the relay nor the module checks it, so it's left as stated policy. - Not documented: the example image bumps (#156, #181, #183), the mock-clock refactor (#166), and the test-only PRs, because users see no change. Checks: `make lint/emdash`, `make lint/docs-manifest`, `make lint/docs-html`, markdownlint, and Vale (no new alerts compared with `main`). A `doc-check` self-check found 3 blocking accuracy findings: the `install_cli` wording twice, and the redelivery cleanup wording. All 3 are fixed. </details> Refs DOCS-1797, RELAY-61 > Generated by Coder Agents on behalf of @nickvigilante.
This removes the
Serverstruct fromcoderdtest. I don't believe we should ever need anything but an API client to test all functionality againstcoderd. If we do, there's probably a bad abstraction in play.I've adopted a naming scheme of
Test<HTTP handler>for each route. I'll be creating a custom linter for it inrules.go.