Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
9 changes: 8 additions & 1 deletion docs/developer/build.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Build

> Last updated: 2026-09-10 · commit `4f29957d2`
> Last updated: 2026-09-12 · commit `9a1fab617`

How to build every component of Darkbloom from a fresh clone: the Go
coordinator, the Rust prompt-contract sidecar, the Swift provider CLI (with its
Expand Down Expand Up @@ -471,6 +471,13 @@ ls -l provider-swift/.build/debug/darkbloom provider-swift/.build/debug/mlx.meta
ls console-ui/.next
```

### Harness assertion checks

The latency and accounting report helpers compile and run with Go alone:
`go test -race ./e2e/testbed/assert -count=1`. These CPU fixtures use synthetic
latency samples and stub query rows; they do not build a provider or require a
Postgres server. See [test.md](test.md#harness-assertion-contracts) for their scope.

## Troubleshooting

| Symptom | Cause | Fix |
Expand Down
21 changes: 20 additions & 1 deletion docs/developer/test.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Test

> Last updated: 2026-09-11 · commit `d22ad0cf3`
> Last updated: 2026-09-12 · commit `9a1fab617`

How to run the unit tests for each component, the end-to-end suite that boots a
real coordinator + Swift provider against ephemeral Postgres, and the docs
Expand Down Expand Up @@ -1172,6 +1172,25 @@ token IDs are accepted.
- The e2e run logs `postgres started`, one `using configured provider binary`
or provider build line per provider, and finishes with `ok github.com/eigeninference/d-inference/e2e`.

### Harness assertion contracts

Run `go test -race ./e2e/testbed/assert -count=1` to check latency evidence and
accounting report handling without a model, provider process or database.
`e2e/testbed/assert/assert.go` (`Asserter.Evaluate`) requires a non-nil sample
with a positive count for every configured segment; missing or empty evidence
fails the segment's presence assertion. A real sample with zero duration remains
valid. Enabled mean, p95, p99 and median bounds keep their order, inclusive
comparison and existing report labels.

`e2e/testbed/assert/accounting_test.go` (`TestAccountingSQLResultContracts`) checks query-row scan failures, zero and
nonzero results, report ordering and sticky failure. It does not execute SQL or
prove ledger integrity. The existing `payment_earnings_parity_sql` and
`earnings_matches_payments_sql` results are informational fee-account counts and
net-charge sums: successful queries pass regardless of the returned number.
The other four SQL assertions require zero violations. Live database checks
still use `PostgresAccountingAsserter.EvaluateAll` in
`e2e/testbed/assert/accounting.go`.

## Troubleshooting

| Symptom | Cause | Fix |
Expand Down
221 changes: 62 additions & 159 deletions e2e/testbed/assert/accounting.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"time"

"github.com/eigeninference/d-inference/coordinator/store"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)

Expand Down Expand Up @@ -114,82 +115,43 @@ func (pa *PostgresAccountingAsserter) EvaluateAll(ctx context.Context) *Assertio
return report
}

pa.assertBalanceIntegritySQL(ctx, report)
pa.assertNoNegativeBalancesSQL(ctx, report)
pa.assertLedgerContinuitySQL(ctx, report)
pa.assertPaymentEarningsParitySQL(ctx, report)
pa.assertEarningsMatchesPaymentsSQL(ctx, report)
pa.assertBillingSessionConsistencySQL(ctx, report)
for _, check := range accountingSQLChecks() {
check.evaluate(report, pa.pool.QueryRow(ctx, check.query))
}

return report
}

func (pa *PostgresAccountingAsserter) assertBalanceIntegritySQL(ctx context.Context, report *AssertionReport) {
name := "balance_integrity_sql"
// observation preserves the two existing informational accounting results: their
// counts are reported, but they do not establish payment/earnings equality.
type accountingSQLCheck struct {
name, query, message string
observation bool
}

row := pa.pool.QueryRow(ctx, `
func accountingSQLChecks() []accountingSQLCheck {
return []accountingSQLCheck{
{
name: "balance_integrity_sql",
query: `
SELECT COUNT(*) FROM balances b
WHERE b.balance_micro_usd != COALESCE((
SELECT SUM(amount_micro_usd) FROM ledger_entries
WHERE account_id = b.account_id
), 0)
`)

var driftCount int
if err := row.Scan(&driftCount); err != nil {
report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: false,
Message: fmt.Sprintf("query failed: %v", err),
})
report.Passed = false
return
}

passed := driftCount == 0
report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: passed,
Message: fmt.Sprintf("%d accounts with balance drift", driftCount),
})
if !passed {
report.Passed = false
}
}

func (pa *PostgresAccountingAsserter) assertNoNegativeBalancesSQL(ctx context.Context, report *AssertionReport) {
name := "no_negative_balances_sql"

row := pa.pool.QueryRow(ctx, `
`,
message: "%d accounts with balance drift",
},
{
name: "no_negative_balances_sql",
query: `
SELECT COUNT(*) FROM balances WHERE balance_micro_usd < 0
`)

var negCount int
if err := row.Scan(&negCount); err != nil {
report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: false,
Message: fmt.Sprintf("query failed: %v", err),
})
report.Passed = false
return
}

passed := negCount == 0
report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: passed,
Message: fmt.Sprintf("%d accounts with negative balance", negCount),
})
if !passed {
report.Passed = false
}
}

func (pa *PostgresAccountingAsserter) assertLedgerContinuitySQL(ctx context.Context, report *AssertionReport) {
name := "ledger_continuity_sql"

row := pa.pool.QueryRow(ctx, `
`,
message: "%d accounts with negative balance",
},
{
name: "ledger_continuity_sql",
query: `
SELECT COUNT(*) FROM (
SELECT le.id,
le.account_id,
Expand All @@ -200,113 +162,54 @@ func (pa *PostgresAccountingAsserter) assertLedgerContinuitySQL(ctx context.Cont
) sub
WHERE prev_balance_after IS NOT NULL
AND prev_balance_after + amount_micro_usd != balance_after
`)

var gapCount int
if err := row.Scan(&gapCount); err != nil {
report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: false,
Message: fmt.Sprintf("query failed: %v", err),
})
report.Passed = false
return
}

passed := gapCount == 0
report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: passed,
Message: fmt.Sprintf("%d ledger continuity gaps found", gapCount),
})
if !passed {
report.Passed = false
}
}

func (pa *PostgresAccountingAsserter) assertPaymentEarningsParitySQL(ctx context.Context, report *AssertionReport) {
name := "payment_earnings_parity_sql"

row := pa.pool.QueryRow(ctx, `
`,
message: "%d ledger continuity gaps found",
},
{
name: "payment_earnings_parity_sql",
query: `
SELECT COUNT(*) FROM (
SELECT le.account_id
FROM ledger_entries le
WHERE le.entry_type = 'platform_fee'
GROUP BY le.account_id
) sub
`)

var feeAccountCount int
if err := row.Scan(&feeAccountCount); err != nil {
report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: false,
Message: fmt.Sprintf("query failed: %v", err),
})
report.Passed = false
return
}

report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: true,
Message: fmt.Sprintf("%d accounts with platform fee entries recorded", feeAccountCount),
})
}

func (pa *PostgresAccountingAsserter) assertEarningsMatchesPaymentsSQL(ctx context.Context, report *AssertionReport) {
name := "earnings_matches_payments_sql"

row := pa.pool.QueryRow(ctx, `
`,
message: "%d accounts with platform fee entries recorded",
observation: true,
},
{
name: "earnings_matches_payments_sql",
query: `
SELECT COALESCE(SUM(le.amount_micro_usd), 0)
FROM ledger_entries le
WHERE le.entry_type IN ('charge', 'refund')
`)

var totalCharges int
if err := row.Scan(&totalCharges); err != nil {
report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: false,
Message: fmt.Sprintf("query failed: %v", err),
})
report.Passed = false
return
}

report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: true,
Message: fmt.Sprintf("net charges across all accounts: %d micro-USD", totalCharges),
})
}

func (pa *PostgresAccountingAsserter) assertBillingSessionConsistencySQL(ctx context.Context, report *AssertionReport) {
name := "billing_session_consistency_sql"

row := pa.pool.QueryRow(ctx, `
`,
message: "net charges across all accounts: %d micro-USD",
observation: true,
},
{
name: "billing_session_consistency_sql",
query: `
SELECT COUNT(*) FROM billing_sessions
WHERE completed_at IS NOT NULL AND status != 'completed'
`)

var inconsistent int
if err := row.Scan(&inconsistent); err != nil {
report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: false,
Message: fmt.Sprintf("query failed: %v", err),
})
report.Passed = false
return
`,
message: "%d billing sessions with completed_at set but status != 'completed'",
},
}
}

passed := inconsistent == 0
report.Results = append(report.Results, AssertionResult{
Name: name,
Passed: passed,
Message: fmt.Sprintf("%d billing sessions with completed_at set but status != 'completed'", inconsistent),
})
if !passed {
func (check accountingSQLCheck) evaluate(report *AssertionReport, row pgx.Row) {
var count int
result := AssertionResult{Name: check.name}
if err := row.Scan(&count); err != nil {
result.Message = fmt.Sprintf("query failed: %v", err)
} else {
result.Passed = check.observation || count == 0
result.Message = fmt.Sprintf(check.message, count)
}
report.Results = append(report.Results, result)
if !result.Passed {
report.Passed = false
}
}
73 changes: 73 additions & 0 deletions e2e/testbed/assert/accounting_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package assert

import (
"context"
"errors"
"fmt"
"testing"

"github.com/stretchr/testify/require"
)

type accountingRow struct {
count int
err error
}

func (row accountingRow) Scan(dest ...any) error {
if row.err != nil {
return row.err
}
if len(dest) != 1 {
return fmt.Errorf("expected one destination, got %d", len(dest))
}
count, ok := dest[0].(*int)
if !ok {
return fmt.Errorf("expected *int destination, got %T", dest[0])
}
*count = row.count
return nil
}

func TestAccountingSQLResultContracts(t *testing.T) {
// These report names and ordering are consumed by existing E2E reports.
checks := accountingSQLChecks()
require.Len(t, checks, 6)
wantNames := []string{
"balance_integrity_sql", "no_negative_balances_sql", "ledger_continuity_sql",
"payment_earnings_parity_sql", "earnings_matches_payments_sql", "billing_session_consistency_sql",
}
wantMessages := []string{
"%d accounts with balance drift", "%d accounts with negative balance", "%d ledger continuity gaps found",
"%d accounts with platform fee entries recorded", "net charges across all accounts: %d micro-USD",
"%d billing sessions with completed_at set but status != 'completed'",
}
for i, check := range checks {
t.Run(wantNames[i], func(t *testing.T) {
require.Equal(t, wantNames[i], check.name)
for _, count := range []int{0, 2, -3} {
report := &AssertionReport{Passed: true}
check.evaluate(report, accountingRow{count: count})
// The fee-count and net-charge observations are intentionally
// informational, including nonzero and negative net charges.
passed := count == 0 || i == 3 || i == 4
require.Equal(t, passed, report.Passed)
require.Equal(t, []AssertionResult{{Name: wantNames[i], Passed: passed, Message: fmt.Sprintf(wantMessages[i], count)}}, report.Results)
}
report := &AssertionReport{Passed: true}
check.evaluate(report, accountingRow{err: errors.New("scan failed")})
require.False(t, report.Passed)
require.Equal(t, []AssertionResult{{Name: wantNames[i], Message: "query failed: scan failed"}}, report.Results)
check.evaluate(report, accountingRow{})
require.False(t, report.Passed, "later passing results cannot clear an earlier failure")
require.Len(t, report.Results, 2)
})
}
}

func TestPostgresAccountingRequiresConnection(t *testing.T) {
report := NewPostgresAccountingAsserter(nil).EvaluateAll(context.Background())
require.False(t, report.Passed)
require.False(t, report.Timestamp.IsZero())
require.Equal(t, []AssertionResult{{Name: "postgres_connection", Message: "no pgxpool.Pool connection provided"}}, report.Results)
}
Loading
Loading