mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-12-03 18:43:38 +01:00
Parallelize slow internal/api race subtests and speed up fixtures (#5366)
**Parallelize slow internal/api race subtests and speed up fixtures** Backend tests (api-0..4) finished last on post-#5350 Pulse Build and Test runs (46109093360, ~1,726 runner-seconds across 5 shards), with the slowest unclaimed internal/api tests executing isolated subtest matrices sequentially, seeding the full default public demo estate where compact mock topologies suffice, or bypassing TestMain's PULSE_TEST_BCRYPT_COST via direct bcrypt.DefaultCost calls. - Parallelize isolated subtest matrices across 14 unclaimed internal/api test files (host_agent_credential_handoff_test.go, agent_snapshot_authority_test.go, resource_read_authority_test.go, token_stream_lifetime_test.go, token_stream_shutdown_test.go, assistant_stream_lifetime_test.go, assistant_json_lifetime_test.go, agent_events_auth_test.go, reporting_boundary_test.go, docker_agents_report_size_test.go, security_setup_fixture_isolation_test.go, websocket_auth_test.go, security_token_withdrawal_test.go, and log_stream_auth_test.go), lifting shared env/session setup out of per-subtest helpers, serializing only the temporary AI alert-analysis binder swap during router construction, and caching read-only source file bytes once in reporting_boundary_test.go. - Use the existing compact 2-node mock integration fixture (newIntegrationServer) for TestStateEndpointReturnsMockData, TestConfigNodesUsesMockTopology, and TestMockModeToggleEndpoint in router_integration_test.go, while preserving newFleetIntegrationServer for multi-page recovery rollup/point tests. - Route four test fixtures (change_password_session_admin_test.go, oidc_only_admin_parity_test.go, platform_admin_session_parity_test.go, and security_status_capability_enforcement_test.go) through pkg/auth.HashPassword so they honor TestMain's PULSE_TEST_BCRYPT_COST instead of bcrypt.DefaultCost. Contract-Neutral: Test-only parallelization and fixture optimization across 19 internal/api test files with zero production code, API behavior, or assertion changes. **Keep global-session-store internal/api subtests sequential** NewRouter calls ensureSessionStore(cfg.DataPath), which replaces and shuts down the package-global session store whenever a router is built with a new data directory. Keep the six subtest suites that create or mutate entries in GetSessionStore() sequential while retaining parallel execution for all token-only and router-free subtest matrices. Contract-Neutral: Test-only adjustment reverting t.Parallel() on six session-store subtest suites; zero production code or assertion changes. **Keep 24 MiB blocked-write cancellation subtests sequential** Each subtest in TestUpdateStreamChainRequestCancellationInterruptsBlockedWrites broadcasts a 24 MiB payload into a stalled socket; running all four concurrently under -race spikes memory pressure on 6 GiB guests without meaningful runtime gain. Keep those four subtests sequential while retaining parallel unit subtests in token_stream_shutdown_test.go. Contract-Neutral: Test-only adjustment reverting t.Parallel() on one 4-subtest blocked-write test to avoid concurrent 24 MiB memory spikes under -race. **Restrict internal/api subtest parallelization to router-free tests** NewRouter mutates three package-global singletons (ensureSessionStore, ensureCSRFStore, and auth.SetManager), and newTestRouter cleanup calls ShutdownRBAC which closes and clears the global RBAC manager. Remove t.Parallel() from all subtest matrices that construct newTestRouter instances while keeping the 11 strictly router-free / sequential-fixture speedups intact. Contract-Neutral: Test-only revert of t.Parallel() on newTestRouter-based subtest matrices to keep package-global RBAC, session, and CSRF singletons strictly serialized. --- Fleet candidate `20261128T052019Z-delivery-trust` from the `delivery-trust` lane. Reviewed tip `69815679f46c571d6492d382884bb7ffb4170186` on `main`. [How Pulse handles triage](https://github.com/rcourtman/Pulse/blob/main/docs/AI_TRANSPARENCY.md)
This commit is contained in:
@@ -132,7 +132,9 @@ func (w *agentEventRefreshWriter) Flush() {
|
||||
// of WithValue's context to prove it cannot retain earlier refresh snapshots.
|
||||
func TestAgentEventTokenRefreshKeepsBoundedContext(t *testing.T) {
|
||||
for _, transport := range []string{"header", "bearer"} {
|
||||
transport := transport
|
||||
t.Run(transport, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
const orgID = "refresh-tenant"
|
||||
token := newTokenRecord(t, agentEventLifecycleToken, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil)
|
||||
token.OrgID = orgID
|
||||
@@ -314,7 +316,9 @@ func TestAgentEventTokenLifecycleClosesIdleStream(t *testing.T) {
|
||||
func TestAgentEventTokenLifecycleResolvesLiveTenantInventory(t *testing.T) {
|
||||
const orgID = "tenant-a"
|
||||
for _, change := range []string{"replaced", "removed", "same_credential_in_new_owner", "changes_during_validation", "no_global_fallback"} {
|
||||
change := change
|
||||
t.Run(change, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
record := newTokenRecord(t, agentEventLifecycleToken, []string{config.ScopeMonitoringRead, config.ScopeAIExecute}, nil)
|
||||
record.OrgID = orgID
|
||||
base := &config.Config{}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
|
||||
)
|
||||
|
||||
const changePasswordProbeCurrent = "correct-admin-password"
|
||||
@@ -18,11 +18,11 @@ const changePasswordProbeCurrent = "correct-admin-password"
|
||||
func newChangePasswordRouter(t *testing.T) (*Router, *config.Config) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte(changePasswordProbeCurrent), bcrypt.DefaultCost)
|
||||
hashed, err := internalauth.HashPassword(changePasswordProbeCurrent)
|
||||
if err != nil {
|
||||
t.Fatalf("bcrypt: %v", err)
|
||||
t.Fatalf("hash password: %v", err)
|
||||
}
|
||||
cfg := &config.Config{DataPath: dir, ConfigPath: dir, AuthUser: "admin", AuthPass: string(hashed)}
|
||||
cfg := &config.Config{DataPath: dir, ConfigPath: dir, AuthUser: "admin", AuthPass: hashed}
|
||||
router := newTestRouter(t, cfg, nil, nil, nil, nil, "1.0.0")
|
||||
cleanupTestRouter(t, router)
|
||||
return router, cfg
|
||||
@@ -93,9 +93,9 @@ func TestChangePasswordBasicAuthPathUnaffected(t *testing.T) {
|
||||
func newChangePasswordRouterWithToken(t *testing.T, rawToken string, scopes []string) (*Router, *config.Config) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte(changePasswordProbeCurrent), bcrypt.DefaultCost)
|
||||
hashed, err := internalauth.HashPassword(changePasswordProbeCurrent)
|
||||
if err != nil {
|
||||
t.Fatalf("bcrypt: %v", err)
|
||||
t.Fatalf("hash password: %v", err)
|
||||
}
|
||||
record, err := config.NewAPITokenRecord(rawToken, "change-password-caller", scopes)
|
||||
if err != nil {
|
||||
@@ -103,7 +103,7 @@ func newChangePasswordRouterWithToken(t *testing.T, rawToken string, scopes []st
|
||||
}
|
||||
cfg := &config.Config{
|
||||
DataPath: dir, ConfigPath: dir,
|
||||
AuthUser: "admin", AuthPass: string(hashed),
|
||||
AuthUser: "admin", AuthPass: hashed,
|
||||
APITokens: []config.APITokenRecord{*record},
|
||||
}
|
||||
cfg.SortAPITokens()
|
||||
|
||||
@@ -27,7 +27,9 @@ func TestDockerAgentReportSizeContractAcceptsOrdinaryAndLargeFleets(t *testing.T
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
test := test
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
handler, _ := newDockerAgentHandlers(t, nil)
|
||||
body := dockerFleetReportBody(t, test.runtime, test.containers)
|
||||
if test.compressed {
|
||||
@@ -50,6 +52,7 @@ func TestDockerAgentReportSizeContractAcceptsOrdinaryAndLargeFleets(t *testing.T
|
||||
|
||||
func TestDockerAgentReportSizeContractBoundaries(t *testing.T) {
|
||||
t.Run("uncompressed exact encoded limit accepted", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
handler, _ := newDockerAgentHandlers(t, nil)
|
||||
body := padDockerReportBody(t, dockerFleetReportBody(t, "docker", 1), agentsdocker.ReportEncodedBodyLimitBytes)
|
||||
rec := postDockerReport(handler, body, "")
|
||||
@@ -59,6 +62,7 @@ func TestDockerAgentReportSizeContractBoundaries(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("uncompressed byte over encoded limit rejected", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
handler := &DockerAgentHandlers{}
|
||||
body := padDockerReportBody(t, dockerFleetReportBody(t, "docker", 1), agentsdocker.ReportEncodedBodyLimitBytes+1)
|
||||
rec := postDockerReport(handler, body, "")
|
||||
@@ -66,6 +70,7 @@ func TestDockerAgentReportSizeContractBoundaries(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("gzip exact encoded limit accepted", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
handler, _ := newDockerAgentHandlers(t, nil)
|
||||
body := gzipAPIReportBodyWithEncodedSize(
|
||||
t,
|
||||
@@ -79,6 +84,7 @@ func TestDockerAgentReportSizeContractBoundaries(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("gzip byte over encoded limit rejected before decompression", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
handler := &DockerAgentHandlers{}
|
||||
body := gzipAPIReportBodyWithEncodedSize(
|
||||
t,
|
||||
@@ -90,6 +96,7 @@ func TestDockerAgentReportSizeContractBoundaries(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("gzip exact decoded limit accepted", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
handler, _ := newDockerAgentHandlers(t, nil)
|
||||
decoded := padDockerReportBody(t, dockerFleetReportBody(t, "podman", 1), agentsdocker.ReportDecodedBodyLimitBytes)
|
||||
rec := postDockerReport(handler, gzipAPIReportBody(t, decoded), "gzip")
|
||||
@@ -99,6 +106,7 @@ func TestDockerAgentReportSizeContractBoundaries(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("gzip byte over decoded limit rejected", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
handler := &DockerAgentHandlers{}
|
||||
decoded := padDockerReportBody(t, dockerFleetReportBody(t, "podman", 1), agentsdocker.ReportDecodedBodyLimitBytes+1)
|
||||
rec := postDockerReport(handler, gzipAPIReportBody(t, decoded), "gzip")
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
||||
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func adminParitySession(t *testing.T, user string) *http.Cookie {
|
||||
@@ -31,12 +30,12 @@ func adminParityConfig(t *testing.T, adminUser string) *config.Config {
|
||||
}
|
||||
cfg := &config.Config{DataPath: dir, ConfigPath: dir, APITokens: []config.APITokenRecord{*record}}
|
||||
if adminUser != "" {
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte("admin-parity-password"), bcrypt.DefaultCost)
|
||||
hashed, err := auth.HashPassword("admin-parity-password")
|
||||
if err != nil {
|
||||
t.Fatalf("bcrypt: %v", err)
|
||||
t.Fatalf("hash password: %v", err)
|
||||
}
|
||||
cfg.AuthUser = adminUser
|
||||
cfg.AuthPass = string(hashed)
|
||||
cfg.AuthPass = hashed
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/models"
|
||||
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func platformAdminSession(t *testing.T, user string) *http.Cookie {
|
||||
@@ -27,12 +26,12 @@ func platformAdminConfig(t *testing.T, adminUser string) *config.Config {
|
||||
dir := t.TempDir()
|
||||
cfg := &config.Config{DataPath: dir, ConfigPath: dir}
|
||||
if adminUser != "" {
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte("platform-admin-password"), bcrypt.DefaultCost)
|
||||
hashed, err := auth.HashPassword("platform-admin-password")
|
||||
if err != nil {
|
||||
t.Fatalf("bcrypt: %v", err)
|
||||
t.Fatalf("hash password: %v", err)
|
||||
}
|
||||
cfg.AuthUser = adminUser
|
||||
cfg.AuthPass = string(hashed)
|
||||
cfg.AuthPass = hashed
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
@@ -112,27 +112,37 @@ func TestReportingSubjectBoundaryExemptionIsExact(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
sourceFiles := make(map[string][]byte)
|
||||
for _, dir := range []string{"internal/api"} {
|
||||
err := filepath.WalkDir(filepath.Join(repo, dir), func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
rel, err := filepath.Rel(repo, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sourceFiles[rel] = data
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, tc := range variants {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
for _, dir := range []string{"internal/api"} {
|
||||
err := filepath.WalkDir(filepath.Join(repo, dir), func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
|
||||
return nil
|
||||
}
|
||||
rel, err := filepath.Rel(repo, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
copyReportingBoundaryFile(t, path, filepath.Join(root, rel))
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for rel, data := range sourceFiles {
|
||||
writeReportingBoundaryFile(t, filepath.Join(root, rel), data)
|
||||
}
|
||||
apiDir := filepath.Join(root, "internal/api")
|
||||
if tc.file != "" {
|
||||
@@ -148,12 +158,8 @@ func TestReportingSubjectBoundaryExemptionIsExact(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func copyReportingBoundaryFile(t *testing.T, source, target string) {
|
||||
func writeReportingBoundaryFile(t *testing.T, target string, data []byte) {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(source)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -913,7 +913,7 @@ func TestAlertAcknowledge_AllowsPrintableAlertIDs(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestStateEndpointReturnsMockData(t *testing.T) {
|
||||
srv := newFleetIntegrationServer(t)
|
||||
srv := newIntegrationServer(t)
|
||||
|
||||
res, err := http.Get(srv.server.URL + "/api/state")
|
||||
if err != nil {
|
||||
@@ -1277,7 +1277,7 @@ func TestHealthEndpointHeadAllowed(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestConfigNodesUsesMockTopology(t *testing.T) {
|
||||
srv := newFleetIntegrationServer(t)
|
||||
srv := newIntegrationServer(t)
|
||||
|
||||
res, err := http.Get(srv.server.URL + "/api/config/nodes")
|
||||
if err != nil {
|
||||
@@ -1300,7 +1300,7 @@ func TestConfigNodesUsesMockTopology(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestMockModeToggleEndpoint(t *testing.T) {
|
||||
srv := newFleetIntegrationServer(t)
|
||||
srv := newIntegrationServer(t)
|
||||
|
||||
if !mock.IsMockEnabled() {
|
||||
t.Fatalf("mock mode should be enabled at start of test")
|
||||
|
||||
@@ -24,7 +24,9 @@ func TestQuickSecuritySetupFixturesInFreshProcesses(t *testing.T) {
|
||||
"TestQuickSecuritySetupRotatesWithBasicAuth",
|
||||
"TestQuickSecuritySetupAllowsRecoveryTokenRotation",
|
||||
} {
|
||||
name := name
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, executable,
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/rcourtman/pulse-go-rewrite/internal/config"
|
||||
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func newCapabilityConfig(t *testing.T, adminUser string) *config.Config {
|
||||
@@ -18,12 +17,12 @@ func newCapabilityConfig(t *testing.T, adminUser string) *config.Config {
|
||||
tempDir := t.TempDir()
|
||||
cfg := &config.Config{DataPath: tempDir, ConfigPath: tempDir}
|
||||
if adminUser != "" {
|
||||
hashed, err := bcrypt.GenerateFromPassword([]byte("capability-password"), bcrypt.DefaultCost)
|
||||
hashed, err := auth.HashPassword("capability-password")
|
||||
if err != nil {
|
||||
t.Fatalf("bcrypt: %v", err)
|
||||
t.Fatalf("hash password: %v", err)
|
||||
}
|
||||
cfg.AuthUser = adminUser
|
||||
cfg.AuthPass = string(hashed)
|
||||
cfg.AuthPass = hashed
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
@@ -31,7 +31,9 @@ func TestTokenStreamWriterNativeMedia(t *testing.T) {
|
||||
responseMediaCase{"sse_parameters", "Text/Event-Stream; charset=iso-8859-1", "text/event-stream; charset=utf-8"})
|
||||
for _, media := range cases {
|
||||
for _, commit := range []string{"write", "header", "flush", "informational"} {
|
||||
media, commit := media, commit
|
||||
t.Run(media.name+"/"+commit, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
writer := &tokenStreamWriter{writer: w, flusher: w.(http.Flusher), ctx: ctx, cancel: cancel, allowed: func() bool { return true }}
|
||||
@@ -447,7 +449,9 @@ func TestProtectedReadStreamsKeepOrgAndInstanceSplit(t *testing.T) {
|
||||
|
||||
func TestTokenStreamWriterChecksReplayQueueAndFinalClosure(t *testing.T) {
|
||||
for _, stage := range []string{"before_replay", "between_replay", "queued_write", "flush", "after_handler"} {
|
||||
stage := stage
|
||||
t.Run(stage, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
cfg := newTestConfigWithTokens(t, newTokenRecord(t, scopedReadToken, []string{config.ScopeSettingsRead}, nil))
|
||||
revoke := func() { config.Mu.Lock(); cfg.RemoveAPIToken(cfg.APITokens[0].ID); config.Mu.Unlock() }
|
||||
var retained http.ResponseWriter
|
||||
|
||||
@@ -366,6 +366,7 @@ func requireWithin(t *testing.T, label string, done <-chan struct{}) {
|
||||
// withdrawal expire it, and nothing is written afterwards.
|
||||
func TestTokenStreamWriterInterruptsStalledTransport(t *testing.T) {
|
||||
t.Run("close", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
writer, base, wrote := guardOverStalledTransport(func() bool { return true })
|
||||
closed := make(chan struct{})
|
||||
go func() { writer.close(); close(closed) }()
|
||||
@@ -380,6 +381,7 @@ func TestTokenStreamWriterInterruptsStalledTransport(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("withdrawal", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
var allowed atomic.Bool
|
||||
allowed.Store(true)
|
||||
writer, _, wrote := guardOverStalledTransport(allowed.Load)
|
||||
@@ -397,6 +399,7 @@ func TestTokenStreamWriterInterruptsStalledTransport(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("deadline control", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
writer, base, wrote := guardOverStalledTransport(func() bool { return true })
|
||||
set := make(chan struct{})
|
||||
go func() {
|
||||
@@ -533,7 +536,9 @@ func (p *panickingTransport) SetWriteDeadline(time.Time) error {
|
||||
// write that no longer exists.
|
||||
func TestTokenStreamWriterClearsIOStateOnTransportPanic(t *testing.T) {
|
||||
for _, op := range []string{"write", "header", "flush"} {
|
||||
op := op
|
||||
t.Run(op, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
base := &panickingTransport{ResponseRecorder: httptest.NewRecorder(), op: op}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
Reference in New Issue
Block a user