aggregator

package
v0.0.0-...-e2f4ec3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 12, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

README

Aggregator Package

Package aggregator provides snapshot publishing functionality for the commitgraph leaderboard.

Purpose

The aggregator runs every 15 minutes and publishes a full ranked list as a Parquet snapshot to ARMOR. This package handles the metadata construction for the snapshot, including corpus stats, percentile distributions, window information, and histogram invariant assertions.

Integration Points

1. BuildSnapshotMetadata

The core integration point is BuildSnapshotMetadata(ctx, db). This function:

  1. Establishes when stats are read: Called after DB connection is available, before snapshot construction
  2. Reads the three corpus stat values: Calls pg.ReadCorpusStats(ctx, db) to get totals
  3. Makes stats available in scope: Returns metadata struct ready for snapshot construction
2. RunHistogramAssertion

The histogram invariant assertion verifies that for every user, the sum of the 30-element daily_ai_commits histogram array equals the ai_commits_30d scalar field. This catches bugs where the ranking query and histogram query disagree about window boundaries, exclusion filters, or alias merge logic.

Publish Cycle Flow

// 1. Establish database connection
db, err := sql.Open("postgres", dsn)
if err != nil {
    return fmt.Errorf("failed to connect: %w", err)
}
defer db.Close()

ctx := context.Background()

// 2. *** INTEGRATION POINT 1 *** - Read stats into metadata
metadata, err := aggregator.BuildSnapshotMetadata(ctx, db)
if err != nil {
    return fmt.Errorf("failed to build metadata: %w", err)
}

// 3. Stats are now available in scope
fmt.Printf("Total commits: %d\n", metadata.Totals.Commits)
fmt.Printf("Total developers: %d\n", metadata.Totals.Developers)
fmt.Printf("Total repositories: %d\n", metadata.Totals.Repositories)

// 4. *** INTEGRATION POINT 2 *** - Run histogram invariant assertion
assertionResult, err := aggregator.RunHistogramAssertion(ctx, db, aggregator.AssertionOptions{})
if err != nil {
    return fmt.Errorf("failed to run histogram assertion: %w", err)
}

if !assertionResult.Passed {
    // Assertion failed - BLOCK PUBLISH
    return fmt.Errorf("histogram assertion failed: %d violations, blocking publish",
        assertionResult.ViolationCount)
}

// 5. Use metadata when constructing the Parquet snapshot
// (In production: query ranking table, write to Parquet with footer metadata)

Metadata Structure

File-Level Metadata (not per-row)
  • WindowStart: Start of 30-day histogram window (current_date - 29 days)
  • Totals: Corpus-wide totals from corpus_stats table
    • Commits: Total AI commits in corpus
    • Developers: Total developers with AI commits
    • Repositories: Total repositories with AI commits
  • Percentiles: Distribution of ai_commits_30d across all ranked users
    • P50: Median (50th percentile)
    • P75: 75th percentile
    • P90: 90th percentile
    • P95: 95th percentile
    • P99: 99th percentile
  • GeneratedAt: When snapshot was created

Acceptance Criteria Met

Stats reader is called at appropriate point: BuildSnapshotMetadata is called after DB is accessible and before snapshot construction

Three stat values available in scope: metadata.Totals.Commits, .Developers, .Repositories are populated and accessible

Integration point is clear and maintainable: Single function call with clear documentation and examples

Histogram assertion runs pre-publish: RunHistogramAssertion is called before snapshot construction to block publishes with data integrity issues

Assertion failure blocks publish: When histogram mismatches are detected, publish is blocked and appropriate error is returned

Bypass mode for emergencies: Assertion can be bypassed with AssertionOptions{Bypass: true, BypassReason: "..."} for emergency situations with audit trail

Failure diagnostics: AssertionResult.FormatViolationLog() provides detailed diagnostic messages including canonical_login, ai_commits_30d, histogram_sum, and difference for each violation

Appropriate error codes: AssertionFailedError is returned for assertion failures (exit code 2), distinct from other errors (exit code 1)

Tested in CI: Unit tests cover assertion logic, bypass mode, violation formatting, and error handling

Usage Example

See example_publish_cycle.go for a complete example of how to integrate this into the publish cycle.

Testing

Run integration tests:

go test ./pkg/aggregator/...

The integration tests verify:

  • TestBuildSnapshotMetadata_Integration: Corpus stats reader is called successfully
  • TestFormatViolationLog: Violation log formatting with truncation
  • TestShouldBlockPublish: Block/publish logic for all assertion states
  • TestRunHistogramAssertion_*: Assertion behavior with passing, failing, and bypass modes

Histogram Invariant Assertion

What it checks

The histogram invariant assertion (Invariant 7) verifies that for every published row:

SUM(daily_ai_commits array) == ai_commits_30d

Both values are derived from the same source data (repo_user_daily_tool rollup) over the same 30-day window, so any divergence indicates a bug in:

  • Window boundary calculation (off-by-one errors)
  • Exclusion filter application (excluded repos leaking in)
  • Alias merge logic (same user appearing under multiple logins)
  • Array aggregation (missing days or wrong ordering)
Failure modes

When the assertion fails, it returns:

  • ViolationCount: Number of users with mismatches
  • Violations: Detailed list with canonical_login, ai_commits_30d, histogram_sum, difference
  • ShouldBlockPublish(): Returns true to block publish

Example violation log:

Histogram assertion violations (3 users):
  [1] alice@example.com: ai_commits_30d=100, histogram_sum=80, diff=20
  [2] bob@example.com: ai_commits_30d=50, histogram_sum=45, diff=5
  [3] charlie@example.com: ai_commits_30d=30, histogram_sum=35, diff=-5
Bypass mode

For emergencies, the assertion can be bypassed with an audit trail:

result, err := aggregator.RunHistogramAssertion(ctx, db, aggregator.AssertionOptions{
    Bypass:       true,
    BypassReason: "Emergency bypass for data investigation - ticket INC-12345",
})

When bypassed:

  • Assertion still runs and records violations
  • ShouldBlockPublish() returns false
  • Bypass reason is logged for audit trail
  • Publish proceeds despite failures
Production usage

In production publish cycle:

  1. Run assertion with RunHistogramAssertion(ctx, db, AssertionOptions{})
  2. Check assertionResult.ShouldBlockPublish()
  3. If true: Block publish, alert operators, log violations, return exit code 2
  4. If false: Proceed with publish
  • SQL implementation: migrations/invariant_7_histogram_reconciles.sql
  • Test fixtures: pkg/pg/invariant_7_integration_test.go
  • Invariant specification: docs/plan/plan.md#L1851-1855
  • Bead tracking: cg-3b5y1

Documentation

Overview

Package aggregator provides an example of how to use BuildSnapshotMetadata in the aggregator's publish cycle.

This example demonstrates the integration point where corpus stats are read and made available for snapshot construction.

Package aggregator provides snapshot publishing functionality for the commitgraph leaderboard.

This file implements the histogram sum invariant assertion that runs during the publish cycle to block publishes with histogram mismatches.

Package aggregator provides a production-ready example of the publish cycle with histogram invariant assertion integration.

This demonstrates the complete flow including: - Database connection setup - Metadata building - Assertion checking - Failure handling with appropriate error codes - Bypass mode for emergencies

Package aggregator provides snapshot publishing functionality for the commitgraph leaderboard.

The aggregator runs every 15 minutes and publishes a full ranked list as a Parquet snapshot. This package handles the metadata construction for the snapshot, including corpus stats, percentile distributions, and window information.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Example_mockPublishCycle

func Example_mockPublishCycle()

Example_mockPublishCycle shows a minimal publish cycle with mocked data for testing the integration point without a database.

func Example_publishCycle

func Example_publishCycle()

Example_publishCycle demonstrates how to integrate BuildSnapshotMetadata and the histogram invariant assertion into the aggregator's 15-minute publish cycle.

This is a conceptual example showing the clear integration point where: 1. Database connection is established 2. BuildSnapshotMetadata is called (reads corpus_stats and percentile_distribution) 3. RunHistogramAssertion is called (blocks publish on histogram mismatches) 4. Metadata is used in snapshot construction (only if assertion passes)

func Example_publishCycleWithBypass

func Example_publishCycleWithBypass()

Example_publishCycleWithBypass demonstrates emergency bypass usage.

func Example_publishCycleWithFailingAssertion

func Example_publishCycleWithFailingAssertion()

Example_publishCycleWithFailingAssertion demonstrates handling assertion failure.

func Example_publishCycleWithPassingAssertion

func Example_publishCycleWithPassingAssertion()

Example_publishCycleWithPassingAssertion demonstrates a successful publish cycle.

func Example_publishExitCodes

func Example_publishExitCodes()

Example_publishExitCodes demonstrates returning appropriate exit codes.

func IsAssertionFailedError

func IsAssertionFailedError(err error) bool

IsAssertionFailedError checks if an error is an AssertionFailedError.

Types

type AssertionFailedError

type AssertionFailedError struct {
	ViolationCount int
	Violations     []HistogramViolation
	Message        string
}

AssertionFailedError is returned when the histogram invariant assertion fails. This is a distinct error type that allows callers to distinguish assertion failures from other errors (like database connection failures).

func (*AssertionFailedError) Error

func (e *AssertionFailedError) Error() string

Error implements the error interface.

type AssertionOptions

type AssertionOptions struct {
	// Bypass allows the assertion to be bypassed for emergencies.
	// When true, the assertion still runs but failures don't block publish.
	Bypass bool
	// BypassReason must be provided when Bypass is true for audit trail.
	BypassReason string
}

AssertionOptions configures how the assertion runs.

type AssertionResult

type AssertionResult struct {
	// Passed indicates whether the assertion passed (no violations)
	Passed bool
	// ViolationCount is the number of users with histogram mismatches
	ViolationCount int
	// Violations contains detailed information about each violation
	Violations []HistogramViolation
	// Bypassed indicates whether the assertion was bypassed
	Bypassed bool
	// BypassReason contains the audit trail for why the assertion was bypassed
	BypassReason string
	// Timestamp when the assertion was run
	Timestamp time.Time
}

AssertionResult represents the result of running the histogram invariant assertion.

func RunHistogramAssertion

func RunHistogramAssertion(ctx context.Context, db *sql.DB, opts AssertionOptions) (*AssertionResult, error)

RunHistogramAssertion executes the histogram sum invariant assertion.

This verifies that for every user, the sum of the 30-element daily_ai_commits histogram array equals the ai_commits_30d scalar field. Both values are derived from the same source data over the same 30-day window, so any divergence indicates a bug in the histogram aggregation or ranking query.

The assertion runs the SQL query from migrations/invariant_7_histogram_reconciles.sql which returns rows where SUM(daily_ai_commits) != ai_commits_30d.

Returns:

  • AssertionResult with detailed results
  • error if the query execution fails (not assertion failure, query error)

Usage in publish cycle:

metadata, err := BuildSnapshotMetadata(ctx, db)
if err != nil {
    return fmt.Errorf("build metadata: %w", err)
}

// Run histogram invariant assertion BEFORE publishing
assertionResult, err := RunHistogramAssertion(ctx, db, AssertionOptions{})
if err != nil {
    return fmt.Errorf("run histogram assertion: %w", err)
}
if !assertionResult.Passed {
    return fmt.Errorf("histogram assertion failed: %d violations, blocking publish",
        assertionResult.ViolationCount)
}

// Assertion passed - proceed with publish

func (*AssertionResult) FormatViolationLog

func (r *AssertionResult) FormatViolationLog() string

FormatViolationLog returns a formatted log message for the violations. This is useful for diagnostic output when the assertion fails.

func (*AssertionResult) ShouldBlockPublish

func (r *AssertionResult) ShouldBlockPublish() bool

ShouldBlockPublish returns true if the assertion result should block publishing. This is true when the assertion failed AND bypass was not enabled.

type CorpusTotals

type CorpusTotals struct {
	// Commits is the total AI commits in corpus
	Commits int64
	// Developers is the total developers with AI commits
	Developers int64
	// Repositories is the total repositories with AI commits
	Repositories int64
}

CorpusTotals contains the three corpus-wide totals from corpus_stats.

type HistogramViolation

type HistogramViolation struct {
	// CanonicalLogin is the user's canonical login (after alias merge)
	CanonicalLogin string
	// AICommits30d is the total commits in the 30-day window from the ranking query
	AICommits30d int
	// HistogramSum is the sum of the 30-element daily_ai_commits array
	HistogramSum int
	// Difference is the discrepancy (ai_commits_30d - histogram_sum)
	Difference int
}

HistogramViolation represents a single row where the histogram sum doesn't match ai_commits_30d.

type PercentileDistribution

type PercentileDistribution struct {
	// P50 is the median (50th percentile) of ai_commits_30d
	P50 float64
	// P75 is the 75th percentile (third quartile)
	P75 float64
	// P90 is the 90th percentile (top 10% threshold)
	P90 float64
	// P95 is the 95th percentile (top 5% threshold)
	P95 float64
	// P99 is the 99th percentile (top 1% threshold)
	P99 float64
}

PercentileDistribution contains the percentile distribution of ai_commits_30d.

type PublishResult

type PublishResult struct {
	// Success indicates whether the publish succeeded
	Success bool
	// Blocked indicates whether the publish was blocked by assertion failure
	Blocked bool
	// AssertionResult contains the histogram assertion results
	AssertionResult *AssertionResult
	// SnapshotMetadata contains the snapshot metadata
	SnapshotMetadata *SnapshotMetadata
	// Error contains any error that occurred
	Error error
}

PublishResult represents the result of a publish cycle.

func RunPublishCycle

func RunPublishCycle(ctx context.Context, dsn string, opts AssertionOptions) *PublishResult

RunPublishCycle executes the complete publish cycle with assertion checking.

This function demonstrates the production flow where: 1. Database connection is established 2. Snapshot metadata is built (corpus stats, percentiles) 3. Histogram invariant assertion is run 4. Publish proceeds only if assertion passes (or bypass is enabled) 5. Appropriate error codes are returned for different failure modes

Returns PublishResult with detailed status.

func RunPublishCycleWithBypass

func RunPublishCycleWithBypass(ctx context.Context, dsn, bypassReason string) *PublishResult

RunPublishCycleWithBypass executes the publish cycle with bypass enabled. This should only be used in emergencies with a clear audit trail.

The bypass reason is logged and included in the assertion result for auditing.

type SnapshotMetadata

type SnapshotMetadata struct {
	// WindowStart is the first day of the 30-day histogram window.
	// All rows in the snapshot share the same window: current_date - 29
	WindowStart time.Time

	// Totals contains corpus-wide scalar totals from corpus_stats table
	Totals CorpusTotals

	// Percentiles contains the percentile distribution of ai_commits_30d
	// across all ranked users
	Percentiles PercentileDistribution

	// GeneratedAt is when this snapshot was created
	GeneratedAt time.Time
}

SnapshotMetadata contains the file-level metadata for a published snapshot.

These fields are stored once per snapshot file (in Parquet metadata/footer), not per row. All rows share the same window_start and totals.

func BuildSnapshotMetadata

func BuildSnapshotMetadata(ctx context.Context, db *sql.DB) (*SnapshotMetadata, error)

BuildSnapshotMetadata constructs the snapshot metadata by reading corpus stats and percentile distribution from the database.

This function implements the integration point for the aggregator's publish cycle. It is called after the database is accessible and before the snapshot is constructed, ensuring the stats are available when we build the snapshot.

Parameters:

  • ctx: Context for database queries
  • db: Database connection (PostgreSQL)

Returns:

  • *SnapshotMetadata: Complete snapshot metadata with totals, percentiles, and window info
  • error: Database error if any query fails

Integration flow: 1. Establish database connection (caller's responsibility) 2. Call BuildSnapshotMetadata to read stats and construct metadata 3. Use metadata when constructing the Parquet snapshot

Example usage:

ctx := context.Background()
db, err := sql.Open("postgres", dsn)
if err != nil {
    return fmt.Errorf("failed to connect to database: %w", err)
}
defer db.Close()

metadata, err := aggregator.BuildSnapshotMetadata(ctx, db)
if err != nil {
    return fmt.Errorf("failed to build snapshot metadata: %w", err)
}

// Use metadata in snapshot construction
fmt.Printf("Publishing snapshot with %d total commits\n", metadata.Totals.Commits)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL