Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions agent/stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package agent

import (
"context"
"maps"
"sync"
"time"

Expand Down Expand Up @@ -32,7 +33,7 @@ type statsDest interface {
// statsDest (agent API in prod)
type statsReporter struct {
*sync.Cond
networkStats *map[netlogtype.Connection]netlogtype.Counts
networkStats map[netlogtype.Connection]netlogtype.Counts
unreported bool
lastInterval time.Duration

Expand All @@ -54,8 +55,18 @@ func (s *statsReporter) callback(_, _ time.Time, virtual, _ map[netlogtype.Conne
s.L.Lock()
defer s.L.Unlock()
s.logger.Debug(context.Background(), "got stats callback")
s.networkStats = &virtual
s.unreported = true
// Accumulate stats until they've been reported.
if s.unreported {
if s.networkStats == nil && virtual != nil {
s.networkStats = make(map[netlogtype.Connection]netlogtype.Counts)
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: let's save some allocations.

Suggested change
s.networkStats = make(map[netlogtype.Connection]netlogtype.Counts)
s.networkStats = make(map[netlogtype.Connection]netlogtype.Counts, len(virtual))

Copy link
Member Author

Choose a reason for hiding this comment

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

I've never actually benchmarked how much a difference a size hint gives for maps, especially ones that don't have a lot of data. Is there a significant difference?

Your suggestion made me realize this had a better fix 😄.

}
for k, v := range virtual {
s.networkStats[k] = s.networkStats[k].Add(v)
}
} else {
s.networkStats = maps.Clone(virtual)
s.unreported = true
}
Copy link
Member Author

@mafredri mafredri Dec 11, 2024

Choose a reason for hiding this comment

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

Review: If the callback was called multiple times before reporting, we lost data as each update is a snapshot since the last.

This can happen if:

  1. The interval is short (tests)
  2. Report takes a long time

I believe the assumption is that the "ConnStatsCallback" reports a realistic count for "now", however, what it actually returns is closer to an additive diff between this and the previous report. Thus, if two callbacks happen in quick succession we're effectively zeroing the actual data.

Copy link
Contributor

Choose a reason for hiding this comment

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

Great catch!

s.Broadcast()
}

Expand Down Expand Up @@ -96,9 +107,8 @@ func (s *statsReporter) reportLoop(ctx context.Context, dest statsDest) error {
if ctxDone {
return nil
}
networkStats := *s.networkStats
s.unreported = false
if err = s.reportLocked(ctx, dest, networkStats); err != nil {
if err = s.reportLocked(ctx, dest, s.networkStats); err != nil {
return xerrors.Errorf("report stats: %w", err)
}
}
Expand Down
2 changes: 1 addition & 1 deletion coderd/insights.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ func (api *API) returnDAUsInternal(rw http.ResponseWriter, r *http.Request, temp
}
for _, row := range rows {
resp.Entries = append(resp.Entries, codersdk.DAUEntry{
Date: row.StartTime.Format(time.DateOnly),
Date: row.StartTime.In(loc).Format(time.DateOnly),
Copy link
Member Author

Choose a reason for hiding this comment

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

Review: Drive-by fix, the date was off-by-one depending on timezone.

Amount: int(row.ActiveUsers),
})
}
Expand Down
24 changes: 21 additions & 3 deletions coderd/insights_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,26 @@ func TestDeploymentInsights(t *testing.T) {
db, ps := dbtestutil.NewDB(t, dbtestutil.WithDumpOnFailure())
logger := testutil.Logger(t)
rollupEvents := make(chan dbrollup.Event)
statsInterval := 500 * time.Millisecond
batcher, closeBatcher, err := workspacestats.NewBatcher(context.Background(),
workspacestats.BatcherWithLogger(logger.Named("batcher").Leveled(slog.LevelDebug)),
workspacestats.BatcherWithStore(db),
workspacestats.BatcherWithBatchSize(1),
workspacestats.BatcherWithInterval(statsInterval),
)
require.NoError(t, err)
defer closeBatcher()
client := coderdtest.New(t, &coderdtest.Options{
Database: db,
Pubsub: ps,
Logger: &logger,
IncludeProvisionerDaemon: true,
AgentStatsRefreshInterval: time.Millisecond * 100,
AgentStatsRefreshInterval: statsInterval,
StatsBatcher: batcher,
DatabaseRolluper: dbrollup.New(
logger.Named("dbrollup").Leveled(slog.LevelDebug),
db,
dbrollup.WithInterval(time.Millisecond*100),
dbrollup.WithInterval(statsInterval/2),
dbrollup.WithEventChannel(rollupEvents),
),
})
Expand All @@ -76,7 +86,7 @@ func TestDeploymentInsights(t *testing.T) {
workspace := coderdtest.CreateWorkspace(t, client, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, workspace.LatestBuild.ID)

ctx := testutil.Context(t, testutil.WaitLong)
ctx := testutil.Context(t, testutil.WaitSuperLong)
Copy link
Member Author

@mafredri mafredri Dec 11, 2024

Choose a reason for hiding this comment

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

Review: In race mode, propagating the agent connection stats can take a while.


// Pre-check, no permission issues.
daus, err := client.DeploymentDAUs(ctx, codersdk.TimezoneOffsetHour(clientTz))
Expand Down Expand Up @@ -108,6 +118,13 @@ func TestDeploymentInsights(t *testing.T) {
err = sess.Start("cat")
require.NoError(t, err)

select {
case <-ctx.Done():
require.Fail(t, "timed out waiting for initial rollup event")
case ev := <-rollupEvents:
require.True(t, ev.Init, "want init event")
}

for {
select {
case <-ctx.Done():
Expand All @@ -120,6 +137,7 @@ func TestDeploymentInsights(t *testing.T) {
if len(daus.Entries) > 0 && daus.Entries[len(daus.Entries)-1].Amount > 0 {
break
}
t.Logf("waiting for deployment daus to update: %+v", daus)
}
}

Expand Down
Loading