From e85f7df752dae8fe4fa48f64276aefdda4a2d55a Mon Sep 17 00:00:00 2001 From: Thomas Durieux <5577568+tdurieux@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:05:25 +0000 Subject: [PATCH] Complete queue diagnostics and validate current-main Go parity --- backend/README.md | 6 +- backend/cmd/server/lifecycle.go | 2 +- backend/cmd/server/signal_integration_test.go | 11 +- backend/internal/logging/collector_test.go | 6 +- backend/internal/logging/policy.json | 3 +- backend/internal/server/config.go | 3 +- backend/internal/server/error_log.go | 3 + backend/internal/server/error_log_test.go | 13 + backend/internal/server/integration_test.go | 1 + backend/internal/server/jobs.go | 1 + backend/internal/server/providers_test.go | 1 + backend/internal/server/queue_heartbeat.go | 81 ++++++ .../queue_heartbeat_integration_test.go | 91 ++++++ backend/internal/server/resources.go | 2 +- .../current-main-completion-audit.json | 271 ++++++++++++++++++ backend/reports/main-alignment.json | 30 +- 16 files changed, 505 insertions(+), 20 deletions(-) create mode 100644 backend/internal/server/queue_heartbeat.go create mode 100644 backend/internal/server/queue_heartbeat_integration_test.go create mode 100644 backend/reports/current-main-completion-audit.json diff --git a/backend/README.md b/backend/README.md index 85da97d..41ae3ac 100644 --- a/backend/README.md +++ b/backend/README.md @@ -2,10 +2,10 @@ ## Branch alignment status, November 14, 2026 -This branch includes `main` through `511dcd7`. Go now implements the 13 APIs added since the previous migration, along with paid hosting, bibliography preservation, account email preferences, access notifications, direct public GitHub submodules, and the mounted review-service capability endpoint. The current 127-route inventory and Node differential contracts are checked in CI. See [the alignment report](reports/main-alignment.json) for validation and remaining staging checks. Route coverage alone does not establish complete behavioral equivalence. +This branch includes `main` through `511dcd7`. Go now implements the 13 APIs added since the previous migration, along with paid hosting, bibliography preservation, account email preferences, access notifications, direct public GitHub submodules, and the mounted review-service capability endpoint. The current 127-route inventory and Node differential contracts are checked in CI. See [the completion audit](reports/current-main-completion-audit.json) for current evidence and [the alignment report](reports/main-alignment.json) for open-PR impact and staging checks. Route coverage alone does not establish complete behavioral equivalence. -The migration branch also includes PR #953’s expiration emails and admin delivery history, with a Go implementation backed by the same collection. Hosting-quota failures no longer enter automatic retry loops. Go emits structured JSON compatible with PR #956’s collector. The operational logging stack has not been deployed. +The migration branch also includes PR #953’s expiration emails and admin delivery history, with a Go implementation backed by the same collection. Hosting-quota failures no longer enter automatic retry loops. Go emits structured JSON compatible with PR #956’s collector. The operational logging stack has not been deployed. Newly opened PR #957 adds investigation APIs and changes admin log responses; it was reviewed but is not part of current main or this branch. Port its API/UI changes together if adopting it, and replace its fixed four-streamer health expectation for Go. This directory implements the API, authentication, repository processing, file serving, storage adapters and background jobs in Go. The existing browser application remains JavaScript. Node is used to build browser assets, run differential tests and perform offline data migration; it is absent from the runtime image. @@ -88,7 +88,7 @@ The separate `.github/workflows/go-backend.yml` workflow runs formatting, static Go writes JSON to stderr with fixed event names, severity, generated trace IDs, status codes and bounded diagnostic fields. Arbitrary messages, errors, URLs, repository identifiers, payloads and credentials are discarded before serialization. `LOG_LEVEL` keeps its existing behavior; `APP_RELEASE` accepts a 7–40 character lowercase Git SHA. Job trace IDs persist across retries, and originating request IDs propagate through the job record. Process heartbeats include RSS, the container memory limit and active requests. -The collector policy and unmodified Vector sanitizer fixture are pinned to PR #956 commit `f084f5c`. `GO_TEST_VECTOR_IMAGE=timberio/vector:0.61.0-debian go test -race ./internal/logging` checks real Go output through Vector in a network-isolated container. CI uses the image digest from that PR. Updating the collector requires reviewing both the field allowlist and its privacy tests. Fixed Go ZIP stages and reasons remain in local JSON logs; the pinned collector discards those additional fields. The logging stack itself is not installed by this migration change, and aggregate queue-heartbeat output remains a follow-up to the existing admin queue metrics. +The collector policy and unmodified Vector sanitizer fixture are pinned to PR #956 commit `f084f5c`. `GO_TEST_VECTOR_IMAGE=timberio/vector:0.61.0-debian go test -race ./internal/logging` checks real Go output through Vector in a network-isolated container. CI uses the image digest from that PR. Updating the collector requires reviewing both the field allowlist and its privacy tests. Fixed Go ZIP stages and reasons remain in local JSON logs; the pinned collector discards those additional fields. The logging stack itself is not installed by this migration change, and its deployment remains an operator task. Go emits queue counts and oldest-waiting age every 30 seconds, independently of maintenance. Failed samples emit no heartbeat. `LOG_REDIS_MIRROR=off` stops new Redis error history/counters while retaining structured output and access to existing history. ## Configuration diff --git a/backend/cmd/server/lifecycle.go b/backend/cmd/server/lifecycle.go index 5b92803..d14c90e 100644 --- a/backend/cmd/server/lifecycle.go +++ b/backend/cmd/server/lifecycle.go @@ -23,7 +23,7 @@ func serveAndDrain(ctx context.Context, server *http.Server, jobs func(context.C if err != nil { return true, errListen } - slog.Info("Go backend listening", "address", listener.Addr().String()) + slog.Info("server started", "module", "process", "listenPort", listener.Addr().(*net.TCPAddr).Port) workers, cancelWorkers := context.WithCancel(ctx) defer cancelWorkers() jobsDone := make(chan struct{}) diff --git a/backend/cmd/server/signal_integration_test.go b/backend/cmd/server/signal_integration_test.go index 18ccfe6..0866585 100644 --- a/backend/cmd/server/signal_integration_test.go +++ b/backend/cmd/server/signal_integration_test.go @@ -4,10 +4,12 @@ import ( "bufio" "context" "encoding/base64" + "encoding/json" "net" "net/http" "os" "os/exec" + "strconv" "strings" "syscall" "testing" @@ -54,10 +56,13 @@ func TestExecutableSignalsIntegration(t *testing.T) { go func() { scanner := bufio.NewScanner(stderr) for scanner.Scan() { - _, suffix, ok := strings.Cut(scanner.Text(), "address=") - if ok { + var entry struct { + Event string `json:"event"` + Port int `json:"listenPort"` + } + if json.Unmarshal(scanner.Bytes(), &entry) == nil && entry.Event == "server_started" && entry.Port > 0 && entry.Port <= 65535 { select { - case ready <- strings.Trim(suffix, "\""): + case ready <- net.JoinHostPort("127.0.0.1", strconv.Itoa(entry.Port)): default: } } diff --git a/backend/internal/logging/collector_test.go b/backend/internal/logging/collector_test.go index f9d4b92..ea5c970 100644 --- a/backend/internal/logging/collector_test.go +++ b/backend/internal/logging/collector_test.go @@ -22,6 +22,7 @@ func TestVectorCollector(t *testing.T) { logger.Info("request", "requestId", "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "route", "/api/repo/:id/file/:path", "status", 200, "ms", 42, "stages", map[string]float64{"upstream": 12}) logger.With("service", "worker", "jobId", "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb").Error("job failed", "queue", "download", "code", "quota_exceeded", "attempt", 2, "error", "secret-repository") logger.Info("process heartbeat", "rss", 123456, "memoryRatio", 0.25, "uptime", 30) + logger.Info("queue heartbeat", "queue", "download", "waiting", 3, "active", 2, "delayed", 1, "failed", 4, "oldestWaitingMs", 60000) dir := t.TempDir() program, err := os.ReadFile("testdata/collector.vrl") if err != nil { @@ -46,7 +47,7 @@ func TestVectorCollector(t *testing.T) { t.Fatalf("%v: %s", err, output) } decoder := json.NewDecoder(bytes.NewReader(output)) - for i, event := range []string{"request_completed", "job_failed", "process_heartbeat"} { + for i, event := range []string{"request_completed", "job_failed", "process_heartbeat", "queue_heartbeat"} { var row map[string]any var encoded string if err = decoder.Decode(&encoded); err == nil { @@ -64,6 +65,9 @@ func TestVectorCollector(t *testing.T) { if i == 1 && (row["service"] != "worker" || row["errorCode"] != "quota_exceeded" || row["severity"] != "error" || row["jobId"] == nil) { t.Fatal(row) } + if i == 3 && (row["queue"] != "download" || row["waiting"] != float64(3) || row["oldestWaitingMs"] != float64(60000)) { + t.Fatal(row) + } if i == 2 && row["memoryRatio"] != 0.25 { t.Fatal(row) } diff --git a/backend/internal/logging/policy.json b/backend/internal/logging/policy.json index 01487e5..8a07d48 100644 --- a/backend/internal/logging/policy.json +++ b/backend/internal/logging/policy.json @@ -687,6 +687,7 @@ "stage_cache_fill_ms", "stage_worker_wait_ms", "stage_anonymize_ms", - "stage_streamer_headers_ms" + "stage_streamer_headers_ms", + "listenPort" ] } diff --git a/backend/internal/server/config.go b/backend/internal/server/config.go index 994b73e..5366067 100644 --- a/backend/internal/server/config.go +++ b/backend/internal/server/config.go @@ -29,6 +29,7 @@ type Config struct { AppID, AppClientID, AppClientSecret, AppCallback, AppSlug, AppPrivateKey, AppWebhookSecret string AppEnabled, AppNewConnections, OAuthEnabled, Download, SecureCookies bool CacheMonitoring bool + DisableRedisLogMirror bool TrustedHops int RateLimit, Workers int Cipher *security.Cipher @@ -56,7 +57,7 @@ func envInt(key string, fallback int) int { return v } func LoadConfig() (Config, error) { - c := Config{EmailAPIKey: os.Getenv("RESEND_API_KEY"), EmailFrom: os.Getenv("EMAIL_FROM"), CacheMonitoring: envBool("CACHE_MONITORING_ENABLED", true), Storage: env("STORAGE", "filesystem"), S3Bucket: os.Getenv("S3_BUCKET"), S3Region: os.Getenv("S3_REGION"), S3Endpoint: os.Getenv("S3_ENDPOINT"), S3ID: os.Getenv("S3_CLIENT_ID"), S3Secret: os.Getenv("S3_CLIENT_SECRET"), Address: ":" + env("PORT", "5000"), MongoURI: os.Getenv("MONGODB_URI"), Database: env("MONGODB_DATABASE", "production"), RedisAddress: net.JoinHostPort(env("REDIS_HOSTNAME", "redis"), env("REDIS_PORT", "6379")), SessionSecret: os.Getenv("SESSION_SECRET"), Root: env("FOLDER", "repositories"), PublicDir: env("PUBLIC_DIR", "public"), Hostname: env("APP_HOSTNAME", "localhost:5000"), Mask: env("ANONYMIZATION_MASK", "XXXX"), ClientID: os.Getenv("CLIENT_ID"), ClientSecret: os.Getenv("CLIENT_SECRET"), Callback: env("AUTH_CALLBACK", "http://localhost:5000/github/auth"), AppID: os.Getenv("GITHUB_APP_ID"), AppClientID: os.Getenv("GITHUB_APP_CLIENT_ID"), AppClientSecret: os.Getenv("GITHUB_APP_CLIENT_SECRET"), AppCallback: env("GITHUB_APP_CALLBACK", "http://localhost:5000/github/app/callback"), AppSlug: os.Getenv("GITHUB_APP_SLUG"), AppPrivateKey: os.Getenv("GITHUB_APP_PRIVATE_KEY"), AppWebhookSecret: os.Getenv("GITHUB_APP_WEBHOOK_SECRET"), AppEnabled: envBool("GITHUB_APP_ENABLED", false), AppNewConnections: envBool("GITHUB_APP_NEW_CONNECTIONS", true), OAuthEnabled: envBool("GITHUB_OAUTH_ENABLED", true), Download: envBool("ENABLE_DOWNLOAD", true), SecureCookies: envBool("COOKIE_SECURE", os.Getenv("NODE_ENV") == "production"), RateLimit: envInt("RATE_LIMIT", 1000), Workers: envInt("ANONYMIZATION_WORKERS", 1)} + c := Config{DisableRedisLogMirror: os.Getenv("LOG_REDIS_MIRROR") == "off", EmailAPIKey: os.Getenv("RESEND_API_KEY"), EmailFrom: os.Getenv("EMAIL_FROM"), CacheMonitoring: envBool("CACHE_MONITORING_ENABLED", true), Storage: env("STORAGE", "filesystem"), S3Bucket: os.Getenv("S3_BUCKET"), S3Region: os.Getenv("S3_REGION"), S3Endpoint: os.Getenv("S3_ENDPOINT"), S3ID: os.Getenv("S3_CLIENT_ID"), S3Secret: os.Getenv("S3_CLIENT_SECRET"), Address: ":" + env("PORT", "5000"), MongoURI: os.Getenv("MONGODB_URI"), Database: env("MONGODB_DATABASE", "production"), RedisAddress: net.JoinHostPort(env("REDIS_HOSTNAME", "redis"), env("REDIS_PORT", "6379")), SessionSecret: os.Getenv("SESSION_SECRET"), Root: env("FOLDER", "repositories"), PublicDir: env("PUBLIC_DIR", "public"), Hostname: env("APP_HOSTNAME", "localhost:5000"), Mask: env("ANONYMIZATION_MASK", "XXXX"), ClientID: os.Getenv("CLIENT_ID"), ClientSecret: os.Getenv("CLIENT_SECRET"), Callback: env("AUTH_CALLBACK", "http://localhost:5000/github/auth"), AppID: os.Getenv("GITHUB_APP_ID"), AppClientID: os.Getenv("GITHUB_APP_CLIENT_ID"), AppClientSecret: os.Getenv("GITHUB_APP_CLIENT_SECRET"), AppCallback: env("GITHUB_APP_CALLBACK", "http://localhost:5000/github/app/callback"), AppSlug: os.Getenv("GITHUB_APP_SLUG"), AppPrivateKey: os.Getenv("GITHUB_APP_PRIVATE_KEY"), AppWebhookSecret: os.Getenv("GITHUB_APP_WEBHOOK_SECRET"), AppEnabled: envBool("GITHUB_APP_ENABLED", false), AppNewConnections: envBool("GITHUB_APP_NEW_CONNECTIONS", true), OAuthEnabled: envBool("GITHUB_OAUTH_ENABLED", true), Download: envBool("ENABLE_DOWNLOAD", true), SecureCookies: envBool("COOKIE_SECURE", os.Getenv("NODE_ENV") == "production"), RateLimit: envInt("RATE_LIMIT", 1000), Workers: envInt("ANONYMIZATION_WORKERS", 1)} if raw, ok := os.LookupEnv("REVIEW_SERVICE_KEYS"); ok { c.ReviewKeys = &raw } diff --git a/backend/internal/server/error_log.go b/backend/internal/server/error_log.go index faadd74..d889c4f 100644 --- a/backend/internal/server/error_log.go +++ b/backend/internal/server/error_log.go @@ -85,6 +85,9 @@ func (s *Server) enqueueError(level, module, message, code string, status int, d if module != "requests" { slog.Log(context.Background(), severity, message, "module", module, "code", code, "httpStatus", status, "requestId", str(detail["requestId"])) } + if s.Config.DisableRedisLogMirror { + return + } at := time.Now().UTC() bucket := errorBucket(status, level) data, err := json.Marshal(M{"ts": at, "module": module, "level": level, "message": message, "raw": []any{message, detail}}) diff --git a/backend/internal/server/error_log_test.go b/backend/internal/server/error_log_test.go index 4b6693a..d4bff31 100644 --- a/backend/internal/server/error_log_test.go +++ b/backend/internal/server/error_log_test.go @@ -139,6 +139,19 @@ func runErrorLogIntegration(t *testing.T, base *Server) { if ttl := client.TTL(ctx, hourly).Val(); ttl < 47*time.Hour || ttl > 48*time.Hour { t.Fatal(ttl) } + // Disabling collection must retain previously recorded history and stop + // both new entries and counters, while structured output remains independent. + s.Config.DisableRedisLogMirror = true + s.recordError(ctx, fail("upstream_error", 502)) + report, err = s.adminErrors(query("GET", "/api/admin/errors")) + if err != nil || number(obj(report)["total"]) != 3 { + t.Fatal("mirror opt-out erased or appended history", report, err) + } + stats, err = s.errorStats(query("GET", "/api/admin/errors/stats")) + if err != nil || number(obj(stats)["last24h"]) != 5 { + t.Fatal("disabled mirror changed counters", stats, err) + } + s.Config.DisableRedisLogMirror = false // Malformed legacy entries retain the TypeScript fallback shape. client.LPush(ctx, "admin:errors", "malformed legacy entry") report, err = s.adminErrors(query("GET", "/api/admin/errors?limit=1")) diff --git a/backend/internal/server/integration_test.go b/backend/internal/server/integration_test.go index ea75619..61d927a 100644 --- a/backend/internal/server/integration_test.go +++ b/backend/internal/server/integration_test.go @@ -131,6 +131,7 @@ func TestBackendIntegration(t *testing.T) { } t.Run("owner notification lifecycle", func(t *testing.T) { runOwnerAlertsIntegration(t, server) }) t.Run("email delivery history", func(t *testing.T) { runEmailHistoryIntegration(t, server) }) + t.Run("queue heartbeat logging", func(t *testing.T) { runQueueHeartbeatIntegration(t, server) }) t.Run("job structured logging", func(t *testing.T) { runJobLoggingIntegration(t, server) }) t.Run("hosting quota jobs", func(t *testing.T) { runQuotaJobIntegration(t, server) }) t.Run("billing lifecycle", func(t *testing.T) { runBillingIntegration(t, server) }) diff --git a/backend/internal/server/jobs.go b/backend/internal/server/jobs.go index c34f8b0..168cfc8 100644 --- a/backend/internal/server/jobs.go +++ b/backend/internal/server/jobs.go @@ -55,6 +55,7 @@ func (s *Server) RunJobs(ctx context.Context) { s.removalRecoveryPending.Store(true) s.recoverImportedRemovalJobs(ctx) var workers sync.WaitGroup + workers.Go(func() { s.runQueueHeartbeats(ctx) }) if s.Config.Billing.Enabled { workers.Go(func() { s.runBillingMaintenance(ctx) }) } diff --git a/backend/internal/server/providers_test.go b/backend/internal/server/providers_test.go index 8155305..39ed032 100644 --- a/backend/internal/server/providers_test.go +++ b/backend/internal/server/providers_test.go @@ -32,6 +32,7 @@ func TestResourceStatusErrors(t *testing.T) { http int }{ {"repo", "queue", "rate_limited:1790000000000", "rate_limited", 425}, + {"repo", "error", "", "repository_not_accessible", 500}, {"repo", "error", "repository_access_revoked", "repository_access_revoked", 500}, {"repo", "error", "repo_not_found", "repo_not_found", 404}, {"repo", "error", "branch_not_found", "branch_not_found", 404}, diff --git a/backend/internal/server/queue_heartbeat.go b/backend/internal/server/queue_heartbeat.go new file mode 100644 index 0000000..bafc9fe --- /dev/null +++ b/backend/internal/server/queue_heartbeat.go @@ -0,0 +1,81 @@ +package server + +import ( + "context" + "log/slog" + "time" +) + +// Sample independently of maintenance; a slow maintenance pass must not look +// like a dead queue. Each sample is bounded and samples cannot overlap. +func (s *Server) runQueueHeartbeats(ctx context.Context) { + ticker := time.NewTicker(30 * time.Second) + defer ticker.Stop() + for { + s.logQueueHeartbeat(ctx, time.Now()) + select { + case <-ctx.Done(): + return + case <-ticker.C: + } + } +} + +func (s *Server) logQueueHeartbeat(ctx context.Context, now time.Time) { + rows, err := s.queueHeartbeat(ctx, now) + if err != nil { + return + } // Missing heartbeats report an unavailable queue store. + for _, row := range rows { + slog.InfoContext(ctx, "queue heartbeat", "module", "queue", "queue", row["queue"], "waiting", row["waiting"], "active", row["active"], "delayed", row["delayed"], "failed", row["failed"], "oldestWaitingMs", row["oldestWaitingMs"]) + } +} + +func (s *Server) queueHeartbeat(ctx context.Context, now time.Time) ([]M, error) { + ctx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + // Go represents timed retries as waiting with a future availableAt. Report + // those as delayed, matching the Node queue dashboard and alert semantics. + state := M{"$cond": []any{M{"$and": []any{M{"$eq": []any{"$state", "waiting"}}, M{"$gt": []any{"$availableAt", now}}}}, "delayed", "$state"}} + cursor, err := s.Store.DB.Collection("gojobs").Aggregate(ctx, []M{ + {"$match": M{"state": M{"$in": []string{"waiting", "active", "delayed", "failed"}}, "action": M{"$in": []string{"prepare", "cache", "remove", "expire"}}}}, + {"$group": M{"_id": M{"action": "$action", "state": state}, "count": M{"$sum": 1}, "oldest": M{"$min": "$createdAt"}}}, + }) + if err != nil { + return nil, err + } + defer cursor.Close(ctx) + groups := []M{} + if err = cursor.All(ctx, &groups); err != nil { + return nil, err + } + rows := []M{} + byName := map[string]M{} + for _, queue := range workerQueues { + row := M{"queue": queue.name, "waiting": int64(0), "active": int64(0), "delayed": int64(0), "failed": int64(0), "oldestWaitingMs": int64(0)} + rows = append(rows, row) + byName[queue.name] = row + } + for _, group := range groups { + id := obj(group["_id"]) + queue := "download" + switch str(id["action"]) { + case "cache": + queue = "cache" + case "remove", "expire": + queue = "remove" + } + row := byName[queue] + state := str(id["state"]) + row[state] = number(row[state]) + number(group["count"]) + if state == "waiting" { + if oldest, ok := storedDate(group["oldest"]); ok { + age := now.Sub(oldest).Milliseconds() + if age > number(row["oldestWaitingMs"]) { + row["oldestWaitingMs"] = age + } + } + } + } + return rows, nil +} diff --git a/backend/internal/server/queue_heartbeat_integration_test.go b/backend/internal/server/queue_heartbeat_integration_test.go new file mode 100644 index 0000000..a3c1bc8 --- /dev/null +++ b/backend/internal/server/queue_heartbeat_integration_test.go @@ -0,0 +1,91 @@ +package server + +import ( + "bytes" + "context" + "encoding/json" + "log/slog" + "strings" + "testing" + "time" + + "github.com/tdurieux/anonymous_github/backend/internal/logging" + "go.mongodb.org/mongo-driver/v2/bson" +) + +func runQueueHeartbeatIntegration(t *testing.T, base *Server) { + ctx := t.Context() + db := base.Store.DB.Client().Database("queue_heartbeat_test_" + bson.NewObjectID().Hex()) + defer db.Drop(ctx) + s := &Server{Store: &Store{DB: db, Redis: base.Store.Redis}} + now := time.Now().Truncate(time.Millisecond) + rows := []any{ + M{"action": "prepare", "state": "waiting", "createdAt": now.Add(-time.Minute), "availableAt": now, "resourceId": "private-repository"}, + M{"action": "prepare", "state": "waiting", "createdAt": now.Add(-time.Hour), "availableAt": now.Add(time.Minute)}, + M{"action": "prepare", "state": "active"}, M{"action": "prepare", "state": "failed"}, M{"action": "prepare", "state": "completed"}, + M{"action": "remove", "state": "waiting", "createdAt": now.Add(-time.Second)}, + M{"action": "expire", "state": "waiting", "createdAt": now.Add(-2 * time.Second)}, + M{"action": "cache", "state": "delayed"}, M{"action": "unknown", "state": "waiting"}, + } + if _, err := db.Collection("gojobs").InsertMany(ctx, rows); err != nil { + t.Fatal(err) + } + previous := slog.Default() + defer slog.SetDefault(previous) + var output bytes.Buffer + slog.SetDefault(slog.New(logging.New(&output, slog.LevelInfo, ""))) + s.logQueueHeartbeat(ctx, now) + lines := strings.Split(strings.TrimSpace(output.String()), "\n") + if len(lines) != 3 { + t.Fatal(output.String()) + } + counts := map[string]M{} + for _, line := range lines { + row := M{} + if err := json.Unmarshal([]byte(line), &row); err != nil { + t.Fatal(err) + } + counts[str(row["queue"])] = row + if row["event"] != "queue_heartbeat" { + t.Fatal(row) + } + } + download := counts["download"] + for _, key := range []string{"waiting", "active", "delayed", "failed"} { + if number(download[key]) != 1 { + t.Fatal(download) + } + } + if number(download["oldestWaitingMs"]) != 60000 || number(counts["remove"]["oldestWaitingMs"]) != 2000 || number(counts["remove"]["waiting"]) != 2 || number(counts["cache"]["delayed"]) != 1 { + t.Fatal(counts) + } + if strings.Contains(output.String(), "private") { + t.Fatal(output.String()) + } + output.Reset() + cancelled, cancel := context.WithCancel(ctx) + cancel() + s.logQueueHeartbeat(cancelled, now) + if output.Len() != 0 { + t.Fatal("database failure emitted a healthy heartbeat", output.String()) + } + if _, err := db.Collection("gojobs").DeleteMany(ctx, M{}); err != nil { + t.Fatal(err) + } + s.logQueueHeartbeat(ctx, now) + lines = strings.Split(strings.TrimSpace(output.String()), "\n") + if len(lines) != 3 { + t.Fatal("empty queues must still report heartbeats", output.String()) + } + for _, line := range lines { + row := M{} + if err := json.Unmarshal([]byte(line), &row); err != nil { + t.Fatal(err) + } + for _, key := range []string{"waiting", "active", "delayed", "failed", "oldestWaitingMs"} { + if number(row[key]) != 0 { + t.Fatal(row) + } + } + } +} diff --git a/backend/internal/server/resources.go b/backend/internal/server/resources.go index 1d3c6af..0e6f3b5 100644 --- a/backend/internal/server/resources.go +++ b/backend/internal/server/resources.go @@ -90,7 +90,7 @@ func (s *Server) checkResource(ctx context.Context, kind string, r M) error { } } if kind == "repo" { - return fail(code, repositoryFailureStatus(code)) + return fail(code, repositoryFailureStatus(str(r["statusMessage"]))) } return fail(code, 500) } diff --git a/backend/reports/current-main-completion-audit.json b/backend/reports/current-main-completion-audit.json new file mode 100644 index 0000000..1156b64 --- /dev/null +++ b/backend/reports/current-main-completion-audit.json @@ -0,0 +1,271 @@ +{ + "objective": "Bring Go to current committed Node feature parity, preserve provider extensibility and review open PR migration/security/cutover impact.", + "status": "implementation_and_review_verified", + "reference": { + "nodeMain": "511dcd706791e551243fd2682765825f82473afc", + "branch": "feat/go-backend-migration", + "goCheckpoint": "116cbba", + "additionalIntegratedFeature": "PR #953 expiration emails and delivery history", + "routeCount": 127, + "contractScripts": 65 + }, + "requirements": [ + { + "id": "runtime", + "requirement": "Run the backend in Go, retaining the browser application and a Node rollback path", + "sourceEvidence": [ + "Dockerfile", + "Dockerfile.node", + "backend/cmd/server/main.go", + "backend/scripts/test-deployment.py" + ], + "validation": [ + "dockerBuild", + "deploymentSmoke", + "runtimeIsolation", + "nodeRollback" + ], + "status": "verified" + }, + { + "id": "currentNodeFeatures", + "requirement": "Preserve supported features and outputs of committed Node main, including billing/conferences, previews, preservation, notifications, submodules and review capabilities", + "sourceEvidence": [ + "backend/contracts/routes.cjs", + "backend/internal/server/routes_test.go", + "backend/internal/server/billing_integration_test.go", + "backend/internal/server/new_features_test.go", + "backend/internal/server/provider_preview_integration_test.go", + "backend/internal/server/email_history_integration_test.go" + ], + "validation": [ + "contracts", + "race", + "nodeRegression" + ], + "status": "verified" + }, + { + "id": "security", + "requirement": "Retain authentication, scopes, owner isolation, revocation, signed webhooks, safe redirects and bounded transformations", + "sourceEvidence": [ + "backend/internal/security/security_test.go", + "backend/internal/server/webhook_integration_test.go", + "backend/internal/server/provider_github_archive_test.go", + "backend/internal/server/provider_github_content_test.go", + "backend/internal/server/provider_identity_integration_test.go", + "backend/internal/anonymize/anonymize_test.go", + "backend/internal/logging/handler_test.go" + ], + "validation": [ + "race", + "vulnerabilities", + "collector" + ], + "status": "verified" + }, + { + "id": "streaming", + "requirement": "Retain streaming file/archive processing, cancellation, content verification and bounded cache/worker behavior", + "sourceEvidence": [ + "backend/internal/server/zip_archive_integration_test.go", + "backend/internal/server/zip_transfer_test.go", + "backend/internal/server/shared_http_test.go", + "backend/internal/anonymize/process_cache_test.go" + ], + "validation": [ + "race", + "contracts" + ], + "status": "verified" + }, + { + "id": "providers", + "requirement": "Allow additional providers through shared interfaces without rewriting lifecycle/content handlers", + "sourceEvidence": [ + "backend/internal/provider/provider.go", + "backend/internal/server/http.go", + "backend/internal/server/provider_integration_test.go", + "backend/internal/server/document_identity_integration_test.go", + "backend/README.md" + ], + "validation": [ + "race" + ], + "status": "verified" + }, + { + "id": "cutoverReview", + "requirement": "Review data/queue handoff and rollback needs without asserting a production rehearsal", + "sourceEvidence": [ + "backend/scripts/migrate-bullmq.cjs", + "backend/internal/server/bullmq_handoff_integration_test.go", + "backend/internal/server/cache_telemetry_import_integration_test.go", + "backend/README.md" + ], + "validation": [ + "race", + "deploymentSmoke", + "nodeRollback" + ], + "status": "verified" + }, + { + "id": "prReview", + "requirement": "Review open PRs for migration, security and cutover impact", + "sourceEvidence": [ + "backend/reports/main-alignment.json", + "backend/internal/logging/testdata/collector.vrl" + ], + "validation": [ + "openPRs" + ], + "status": "verified" + } + ], + "validation": { + "race": { + "result": "passed", + "log": "/tmp/go-completion-race-clean.log", + "sha256": "e76afe243f58b3b86de1c9f6bda8badf76e3fb37649752f78beb40eeb06bfda0", + "packages": [ + "ok \tgithub.com/tdurieux/anonymous_github/backend/cmd/server\t2.212s", + "ok \tgithub.com/tdurieux/anonymous_github/backend/internal/anonymize\t5.134s", + "ok \tgithub.com/tdurieux/anonymous_github/backend/internal/blobcache\t103.871s", + "ok \tgithub.com/tdurieux/anonymous_github/backend/internal/logging\t1.070s", + "ok \tgithub.com/tdurieux/anonymous_github/backend/internal/provider\t1.043s", + "ok \tgithub.com/tdurieux/anonymous_github/backend/internal/quotagate\t1.326s", + "ok \tgithub.com/tdurieux/anonymous_github/backend/internal/security\t1.044s", + "ok \tgithub.com/tdurieux/anonymous_github/backend/internal/server\t398.107s", + "ok \tgithub.com/tdurieux/anonymous_github/backend/internal/storage\t1.333s" + ] + }, + "contracts": { + "result": "passed", + "log": "/tmp/go-completion-contracts.log", + "sha256": "2eb8599a165363a0afdb1f0db53c03f3499f8f750049837df79c1666f1b8b46d", + "scripts": 65, + "routes": 127, + "anonymizationCases": 499, + "fileTypeCases": 7876 + }, + "vulnerabilities": { + "result": "passed", + "log": "/tmp/go-completion-vulnerabilities.log", + "sha256": "cd603802373c0ab24cb1e859ec21635183b92cc81aeb083b21f3061103e3822f", + "reachable": 0, + "importedPackages": 0, + "unusedModuleAdvisories": 4 + }, + "dockerBuild": { + "result": "passed", + "log": "/tmp/go-final-image.log", + "sha256": "8fbc5daccb9c2cbbd262340d70f8214eb89983db3050482cb021128d76737a6b", + "image": "sha256:416b628b5ae3fe333ffc5102c9159afb24d3da6b1168b0f64af59f102796e8e4" + }, + "deploymentSmoke": { + "result": "passed", + "log": "/tmp/go-final-smoke.log", + "sha256": "d877fbd4de0ed9bd212ba3f783582721f340ada74ef92bab5b632adefc7af718", + "scope": "Disposable MongoDB/Redis/storage, startup, non-root writes, static routes, graceful shutdown and rollback Compose model" + }, + "runtimeIsolation": { + "result": "passed", + "uid": 10001, + "nodeExecutablePresent": false, + "image": "sha256:416b628b5ae3fe333ffc5102c9159afb24d3da6b1168b0f64af59f102796e8e4" + }, + "nodeRollback": { + "result": "passed", + "log": "/tmp/go-final-node-native.log", + "sha256": "55e9566a48851f0f435edfb0e6c0b61967650f0052426b94d84bf7780ca5f982", + "build": { + "result": "passed", + "log": "/tmp/go-final-node-image.log", + "sha256": "1fb003955de60157771bae8ef105fef7b7a78592383648cd529e68ea3c0b7cc7" + }, + "image": "sha256:f8bdd4052f103c102a16c39af2fa8ca99f306f257a9009e3de50c03114629649" + }, + "collector": { + "result": "passed", + "log": "/tmp/go-final-collector.log", + "sha256": "5a6859a6830c8584af3166de86e21df43e0a833f0900b09ec9b49d3574a276e7", + "scope": "Actual request, job, process and queue records through pinned Vector sanitizer; privacy and concurrency race tests" + }, + "nodeRegression": { + "result": "passed_after_targeted_fixes", + "broadRun": { + "result": "1676 passed, 436 skipped, 5 failures", + "log": "/tmp/go-pr-node-full.log", + "sha256": "387add4974fcb2dfa0e1b41e8fcb1d771da9744c90228756d9f5168618d6ad92" + }, + "fixedFailures": { + "result": "25 passed", + "log": "/tmp/go-pr-final-node-regressions.log", + "sha256": "a3873d5978f257e5a53c0db63fe6fc7174550dc3b6e523a7437ae3e80921151b" + }, + "emailFeature": { + "result": "42 passed", + "log": "/tmp/go-pr953-node-tests.log", + "sha256": "06fd89e336fab5a4cea65772727b09bbfd46c93e9eec059dcd7d07783af48af9" + }, + "limitation": "The broad Node suite was not repeated after repairing its five failures; every failing case passed the targeted rerun. Optional external-service skips are not claimed as executed." + }, + "static": { + "result": "passed", + "commands": [ + "go vet ./...", + "gofmt -l cmd internal", + "git diff --check" + ], + "typescript": "Passed directly and in freshly rebuilt Node rollback image" + }, + "openPRs": { + "result": "reviewed", + "numbers": [ + 953, + 954, + 955, + 956, + 957 + ], + "details": "backend/reports/main-alignment.json", + "ci": "Open PR jobs could not start under the previously confirmed account billing block; local results provide validation. No CI-green claim.", + "reviewThreads": "953-956 have no review threads. 957 has three unresolved/outdated threads; fixes were inspected in 88d696c/20621c0." + } + }, + "scopeAndLimits": [ + "Current Node means committed main 511dcd7, re-fetched during this audit. Uncommitted work in other checkouts was not modified.", + "Open PR #957 is a reviewed, unmerged feature rather than a current-main requirement. Its two new APIs and Redis/UI response changes must be ported together if adopted; its fixed four-streamer health rule is unsuitable for the Go deployment.", + "The optional Vector/VictoriaLogs/Grafana stack was reviewed and collector compatibility tested, not deployed.", + "Live Stripe test-mode checkout/webhooks, real Resend delivery, OAuth/App callbacks with copied data, and sanitized production restore/queue/rollback rehearsal remain deployment gates. Mocked protocol tests do not prove these live workflows.", + "No production or beta deployment, production data change, email delivery, PR merge or external provider adapter release was performed.", + "Earlier speed/memory reports are dated workload measurements. This audit makes no new production speedup or live memory claim." + ], + "intentionalDifferences": [ + "Preserve supported behavior without reintroducing Node bugs; unknown stored failures remain 500, explicit quota denials 402, and explicit credential/access errors retain their status.", + "Submodule ZIP entries use bounded per-file reads after the parent archive stream.", + "Owner notification history is conservatively rescanned at startup.", + "Stripe display prices and admin billing summaries are not cached.", + "No GitLab/Bitbucket implementation is shipped; the tested provider extension interface and documented credential obligations are supplied." + ], + "source": { + "sha256": "4b89fce7c930f971015d2f15a27123d0ff03e97ad198623dfbc3fd823af9c2a2", + "files": 397, + "algorithm": "Sorted backend-relative path, NUL, bytes, NUL; Go sources/tests, go.mod, go.sum and embedded logging policy." + }, + "updatedAtUTC": "2026-11-14T17:04:39.695978+00:00", + "correctedFailures": { + "firstAuditRace": { + "result": "failed", + "log": "/tmp/go-final-parity-race.log", + "sha256": "940a66f81926417a9aeda386cb721fd2d9ddd5b3846b8c9ab85de78cf1fe37a6" + }, + "fixes": [ + "Signal integration now reads the numeric JSON startup port instead of the removed text address field.", + "Unknown stored failures remain HTTP 500; only explicit permission failure codes map to HTTP 403." + ], + "verification": "All packages passed the subsequent full race/database run, including signal shutdown and repository recovery." + }, + "conclusion": "Supported committed-main behavior, runtime migration and provider extensibility are verified under the documented no-bug-parity policy. Open PR migration/security/cutover impact is reviewed, including new unmerged #957. Production deployment and future unmerged feature ports are not represented as completed." +} diff --git a/backend/reports/main-alignment.json b/backend/reports/main-alignment.json index dcbdd28..4f906d8 100644 --- a/backend/reports/main-alignment.json +++ b/backend/reports/main-alignment.json @@ -1,7 +1,7 @@ { "mainCommit": "511dcd706791e551243fd2682765825f82473afc", "restoredGoFrom": "bff2e343fdc6fc09ff0f373a34bef9716b06bc00^", - "status": "Current-main feature implementation complete; isolated validation recorded below, live cutover checks pending", + "status": "Current-main implementation and open-PR review verified; production deployment gates remain separate", "removedTypeScriptRoutes": [], "notes": [ "Node reference is committed main 511dcd706791e551243fd2682765825f82473afc, not uncommitted work in another checkout.", @@ -10,12 +10,12 @@ "No production or beta deployment was performed." ], "validation": { - "goIntegrationRace": "passed with disposable MongoDB/Redis including quota-job, owner-notification and email-history lifecycle tests; server package 389.481s. Final stored-error mapping additionally passed focused resource/status race tests.", + "goIntegrationRace": "Final clean full run passed on Go 1.27.4 with disposable MongoDB/Redis, including executable signals, queue heartbeats, provider lifecycle, BullMQ handoff, cache compatibility and repository recovery. Server package: 398.107s.", "goVet": "passed on Go 1.27.4", "nodeContracts": "65 scripts passed after PR #953 source integration", "routeInventory": "127 TypeScript routes verified, including the two email-history routes from PR #953", - "goDockerBuild": "passed with Go 1.27.4 and klauspost/compress v1.20.2", - "deploymentSmoke": "passed: isolated startup, non-root writes, static routes, graceful shutdown, Node rollback compose model", + "goDockerBuild": "Fresh final Go image build passed: sha256:416b628b5ae3fe333ffc5102c9159afb24d3da6b1168b0f64af59f102796e8e4", + "deploymentSmoke": "Fresh final image passed isolated startup, non-root writes, static routes, graceful shutdown and rollback Compose-model checks; no Node executable in Go runtime.", "reachableVulnerabilities": "none reported by govulncheck v1.9.0; four advisories remain in required modules without reachable calls", "existingNodeIndexes": "passed with race detector: pre-existing named submodule index and repeated Go startup", "openPRFocusedNodeTests": "42 email-history, expiration and admin UI tests passed; final 25-test activity/error-code/preview regression set passed", @@ -23,7 +23,8 @@ "nodeSuite": "Broad run: 1676 passed, 436 skipped, five failures. Fixed missing cache_miss translation, three stale Mongoose query mocks and one stale preview-button selector; all five failures passed in a 25-test focused rerun. Full suite not repeated after these fixes.", "typescript": "tsc --noEmit passed", "structuredLogging": "Passed race tests for private-data filtering, concurrent output, request traces, process samples, webhook failure diagnostics and persistent job traces. Actual Go records passed the unmodified Vector 0.61.0 sanitizer using the PR-pinned image digest. Final focused regression run and go vet passed.", - "oauthDiscoveryDenial": "Disposable database race test passed for OAuth/App discovery, OAuth 401, permission 403 and App reconnect semantics." + "oauthDiscoveryDenial": "Disposable database race test passed for OAuth/App discovery, OAuth 401, permission 403 and App reconnect semantics.", + "nodeRollback": "Fresh rollback image build and native SQLite/Zstandard round trips passed." }, "changes": [ "Restore Go backend and Go deployment on top of current main", @@ -45,7 +46,10 @@ "Recognize named Express Router imports in route inventory generation", "Repair current Node activity-test query mocks and preview-button selector; add the missing cache_miss translation", "Emit safe structured JSON logs, persist job/request trace correlation, add process memory heartbeats and webhook failure phases", - "Normalize confirmed legacy OAuth discovery credential denial without changing App reconnect errors" + "Normalize confirmed legacy OAuth discovery credential denial without changing App reconnect errors", + "Emit bounded periodic queue diagnostics with delayed-retry classification and no false healthy samples on database failure", + "Support Redis error-mirror opt-out and preserve historical reads", + "Use a numeric JSON startup port for executable signal/shutdown validation" ], "implementedTypeScriptRoutes": [ { @@ -131,8 +135,16 @@ }, "956": { "head": "f084f5cbfc7b328a04b4e7e859ce9fa224c605c4", - "result": "Go JSON logging implemented and tested against its pinned, unmodified Vector sanitizer. Request timings, job traces, errors and memory heartbeats retained. Aggregate queue-heartbeat output and deployment of the logging stack remain outstanding; fixed Go ZIP stage/reason fields remain local only." + "result": "Safe Go JSON logs and queue/process heartbeats implemented; LOG_REDIS_MIRROR=off supported without deleting history. Actual Go records validated against the pinned Vector sanitizer. Stack deployment remains an operator task; fixed Go ZIP stage/reason fields remain local only." }, - "checks": "GitHub Actions jobs did not start because the account is locked due to a billing issue. This is not a test failure." - } + "checks": "GitHub Actions jobs did not start because the account is locked due to a billing issue. This is not a test failure.", + "957": { + "head": "20621c0660ec68ab2b7090f9faec5ba42b737717", + "base": "f084f5cbfc7b328a04b4e7e859ce9fa224c605c4", + "result": "Reviewed as a new, unmerged feature. Its two investigation/correlation routes, new Redis projection/pagination fields and admin UI are not part of current main or this migration branch. Port those together if adopting #957. Its hard-coded four-streamer health expectation must be adapted for the single Go process; existing Go UUID request/job traces are compatible.", + "securityReview": "Admin middleware precedes both routes; query inputs are allowlisted, operator endpoints are fixed configuration, redirects rejected, concurrency limited to two, deadline four seconds and response cap 2 MiB. Responses use safe field projection.", + "reviewThreads": "Three formally unresolved, outdated threads. Inspected fixes for Redis transaction queue capacity, absent/unknown releases and info-severity edge 5xx in 88d696c/20621c0; author replies describe real Redis/Vector/VictoriaLogs validation. No review comments or resolutions posted by this migration task." + } + }, + "completionAudit": "backend/reports/current-main-completion-audit.json" }