package ai import ( "strings" "testing" ) // TestGraphMarketIntentsAreRegistered proves the four G1 market traversals are in the closed Registry, so // ValidateRegistry asserts them at boot and ExecuteIntent can run them. A missing intent means the // registration regressed. func TestGraphMarketIntentsAreRegistered(t *testing.T) { cases := map[string]int{ IntentSegmentCompetitorField: 3, // agency, naics, lookback_years IntentIncumbentOfRecord: 1, // opportunity_id IntentRecompetePipeline: 2, // agency, window_months IntentAgencyBuyingPattern: 2, // agency_prefix, naics } for name, wantParams := range cases { it, ok := IntentByName(name) if !ok { t.Fatalf("intent %q must be registered in the closed Registry", name) } if len(it.Params) != wantParams { t.Errorf("intent %q must bind exactly %d params, got %d", name, wantParams, len(it.Params)) } } } // TestGraphMarketIntentsPassTheReadOnlyGuard is the load bearing security assertion: each registered market // intent passes GuardReadOnlyQuery against the real ReadAllowlist. A query that referenced a non allowlisted // table, hid a mutation, or named an eeo marker would fail here, the same gate ValidateRegistry runs at boot // and ExecuteIntent re runs at execution time. func TestGraphMarketIntentsPassTheReadOnlyGuard(t *testing.T) { for _, sql := range []string{ segmentCompetitorFieldSQL, incumbentOfRecordSQL, recompetePipelineSQL, agencyBuyingPatternSQL, } { if err := GuardReadOnlyQuery(sql, ReadAllowlist); err != nil { t.Errorf("a registered market intent must pass the read only guard: %v", err) } } } // TestValidateRegistryWithMarketIntents proves the whole closed Registry, now carrying the four G1 intents // alongside the TAG and G3 intents, validates at boot. This is the assertion the api boot runs. func TestValidateRegistryWithMarketIntents(t *testing.T) { if err := ValidateRegistry(); err != nil { t.Fatalf("ValidateRegistry must pass with the four G1 market intents registered: %v", err) } } // TestAwardsKeyOnlyOnAgencyAndNaics is the honesty mandate, pinned statically: usaspending_awards carries NO // psc, NO set_aside, and NO pop_state column, so neither the competitor field nor the incumbent walk may // select or join on those columns against the award table. The award arms key ONLY on the agency and NAICS // columns the table actually has. A regression that reached for a phantom award column would fail here. func TestAwardsKeyOnlyOnAgencyAndNaics(t *testing.T) { // The two intents that read usaspending_awards. The competitor field aggregates awards; the incumbent // walk joins an opportunity to its predecessor award. awardIntents := map[string]string{ "segment_competitor_field": segmentCompetitorFieldSQL, "incumbent_of_record": incumbentOfRecordSQL, } for name, sql := range awardIntents { lower := strings.ToLower(sql) // The award join and filter keys: the only two columns usaspending_awards carries for the segment. if !strings.Contains(lower, "awarding_agency") { t.Errorf("%s: the award arm must key on awarding_agency", name) } if !strings.Contains(lower, "naics_code") { t.Errorf("%s: the award arm must key on naics_code", name) } // The phantom columns the award table does NOT have. None may appear qualified to the award alias. for _, phantom := range []string{"a.psc", "a.set_aside", "a.pop_state"} { if strings.Contains(lower, phantom) { t.Errorf("%s: usaspending_awards has no %s column; the award arm must not reference it", name, phantom) } } } } // TestIncumbentEdgeLabeledPrimeOfRecord pins that every incumbent edge the graph surfaces carries the // constant prime-of-record label, never the staffing subcontractor: the public award data carries only the // prime recipient, so prime-of-record is the honest statement of what the data supports. The label is a SQL // constant column, so a row can never be unlabeled. func TestIncumbentEdgeLabeledPrimeOfRecord(t *testing.T) { lower := strings.ToLower(incumbentOfRecordSQL) if !strings.Contains(lower, "'prime-of-record'") { t.Error("the incumbent walk must label every incumbent edge with the constant prime-of-record") } if primeOfRecordLabel != "prime-of-record" { t.Errorf("the prime of record label constant drifted, got %q", primeOfRecordLabel) } } // TestAgencyRollupUsesStringSplitNotRecursion pins that the agency hierarchy rollup uses the // full_parent_path string split and a GROUP BY, NOT a recursive CTE: the hierarchy is already a dotted // materialized path, so recursion would add a determinism risk and no value. The determinism mandate // explicitly prefers the string split where the data supports it. func TestAgencyRollupUsesStringSplitNotRecursion(t *testing.T) { lower := strings.ToLower(agencyBuyingPatternSQL) if !strings.Contains(lower, "split_part(s.full_parent_path") { t.Error("the agency rollup must use a full_parent_path string split (split_part)") } if strings.Contains(lower, "with recursive") { t.Error("the agency rollup must NOT use a recursive CTE; the dotted path makes recursion unnecessary") } } // TestNoFloatTouchesADollarOrShare is the decimal mandate, pinned statically across all four market intents: // no ::float8, no ::float, no ::double precision, and no ::real cast may touch a dollar or a share figure. // Every dollar (award_amount, estimated_value) and every share stays Postgres numeric end to end and is // scanned into shopspring/decimal in Go. A cast to a float type would silently lose the bit stable precision // the AEDT compliance asset requires. func TestNoFloatTouchesADollarOrShare(t *testing.T) { intents := map[string]string{ "segment_competitor_field": segmentCompetitorFieldSQL, "incumbent_of_record": incumbentOfRecordSQL, "recompete_pipeline": recompetePipelineSQL, "agency_buying_pattern": agencyBuyingPatternSQL, } for name, sql := range intents { lower := strings.ToLower(sql) for _, floatCast := range []string{"::float8", "::float", "::double precision", "::real"} { if strings.Contains(lower, floatCast) { t.Errorf("%s: a float cast %q must never touch a dollar or share figure (decimal mandate)", name, floatCast) } } // The dollar and share math is positively numeric: the weighted dollars and the share carry the // ::numeric type, so the cast is to the exact type, never a float. if name == "segment_competitor_field" { if !strings.Contains(lower, "::numeric") { t.Errorf("%s: the weighted dollars and share must be cast to numeric, the exact decimal type", name) } } } } // TestEveryListOrderEndsWithAUniqueTiebreaker pins the byte stable mandate: every market intent that returns // a list ends its ORDER BY with a unique id tiebreaker (a recipient UEI, an award generated_internal_id, a // record id, or the full grouped key), so the same inputs yield byte identical rows. func TestEveryListOrderEndsWithAUniqueTiebreaker(t *testing.T) { cases := []struct { name string sql string mustContain string // a fragment proving the ORDER BY ends with the unique tiebreaker }{ // The competitor field is grouped per recipient; the UEI is the unique tiebreaker. {"segment_competitor_field", segmentCompetitorFieldSQL, "w.recipient_uei"}, // The incumbent walk picks the most recent award; the generated_internal_id is the unique tiebreaker. {"incumbent_of_record", incumbentOfRecordSQL, "a.generated_internal_id"}, // The pipeline orders by the end date then the record id, a total order. {"recompete_pipeline", recompetePipelineSQL, "record_id"}, // The buying pattern groups; the grouped keys are the total order. {"agency_buying_pattern", agencyBuyingPatternSQL, "b.value_band"}, } for _, tc := range cases { lower := strings.ToLower(tc.sql) idx := strings.LastIndex(lower, "order by") if idx < 0 { t.Errorf("%s: the list must be ordered for byte stability", tc.name) continue } orderClause := lower[idx:] if !strings.Contains(orderClause, strings.ToLower(tc.mustContain)) { t.Errorf("%s: the ORDER BY must carry the unique tiebreaker %q, got %q", tc.name, tc.mustContain, orderClause) } } } // TestMarketIntentsAreNotRecursiveWhereAvoidable confirms the market intents are aggregates and joins, not // recursive walks: none of the four uses WITH RECURSIVE. The market questions are answered by GROUP BY // rollups and a string split, exactly as the determinism mandate prefers over recursion. func TestMarketIntentsAreNotRecursiveWhereAvoidable(t *testing.T) { for name, sql := range map[string]string{ "segment_competitor_field": segmentCompetitorFieldSQL, "incumbent_of_record": incumbentOfRecordSQL, "recompete_pipeline": recompetePipelineSQL, "agency_buying_pattern": agencyBuyingPatternSQL, } { if strings.Contains(strings.ToLower(sql), "with recursive") { t.Errorf("%s: a market aggregate must not use a recursive CTE; the data already carries the keys", name) } } } // TestClampMarketBounds proves the window and lookback are always normalized into the bounded range, so no // caller bound value (zero, negative, or oversized) can widen a bounded scan into an unbounded one. func TestClampMarketBounds(t *testing.T) { windowCases := map[int]int{ 0: DefaultRecompeteWindowMonths, -5: DefaultRecompeteWindowMonths, 12: 12, 24: 24, 60: maxRecompeteWindowMonths, 120: maxRecompeteWindowMonths, } for in, want := range windowCases { if got := ClampRecompeteWindowMonths(in); got != want { t.Errorf("ClampRecompeteWindowMonths(%d) = %d, want %d", in, got, want) } } lookbackCases := map[int]int{ 0: DefaultCompetitorLookbackYears, -2: DefaultCompetitorLookbackYears, 5: 5, 15: maxCompetitorLookbackYears, 40: maxCompetitorLookbackYears, } for in, want := range lookbackCases { if got := ClampCompetitorLookbackYears(in); got != want { t.Errorf("ClampCompetitorLookbackYears(%d) = %d, want %d", in, got, want) } } }