Source identity
| Field | Recorded value |
|---|---|
| Source type | GitHub source |
| Original record | Janady13/missionmatch / cmd/teach-aggregate/main.go |
| Date | Not specified in source |
| Repository | Janady13/missionmatch |
| Revision | 1e9249840a4302ec82e123b9c9cb6f75badea3e4 |
| Branch | master |
| Path or archive member | cmd/teach-aggregate/main.go |
| Original SHA-256 | b7e179ae5dd4a1389bf0ccea65556d25ff049843032fe5ab553631267d55d2bf |
| Git blob SHA | 6a2cb5ff339044c6c908ff37cbe6f06e76431e9a |
| Reading-copy SHA-256 | b7e179ae5dd4a1389bf0ccea65556d25ff049843032fe5ab553631267d55d2bf |
Every recorded occurrence
These 25 records contain identical original source bytes. Their paths and revisions remain part of the archive.
| Original record | Branch or archive | Revision / identifier | Original location |
|---|---|---|---|
| Janady13/missionmatch / cmd/teach-aggregate/main.go | master | 1e9249840a4302ec82e123b9c9cb6f75badea3e4 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | feature/aioe-upgrade | 2178e7298d0e5d9af83afa12402fd587f0ba6ed8 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | m5-price-to-win | 41000ad30fff4129fdaf5ec84e15ba14c27d4890 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | collision-deconfliction | 4ee5a09972608ed89f8377c6665542d5f450f0a6 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | graphrag-foundation | b0ddeb9f633fd138d09309d1a17b7d13bc3a67f7 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | time-to-fill-survival | b66e1e505863d4f17741a4b9ede73509e45bd6c6 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | mag-substrate | b82c7100a492dec67dfd1eda6b3f53def859be35 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | capture-readiness | bae6af7cb2997e819174a9e9cfff5e16067a1975 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | ws8-teaching-loop | c823f0fb6bb2aba0f39001eb6de96f4000d9321f | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | phase2-connectors | e038d4c687aec16f8bd9bc4d907eea14d91f8704 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | presentation-readiness | eb574acaa29d71ce4d0f852572e87c275c79fdb7 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | ws9-bench-ingestion | f585a9ef32fa554663ce1fba9a414a54b6e49cf0 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | vendor-intelligence | fe9796a19c261951d3f2565206c0c1b5ac294465 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | collision-deconfliction | 4ee5a09972608ed89f8377c6665542d5f450f0a6 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | m5-price-to-win | 41000ad30fff4129fdaf5ec84e15ba14c27d4890 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | master | 1e9249840a4302ec82e123b9c9cb6f75badea3e4 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | ws8-teaching-loop | c823f0fb6bb2aba0f39001eb6de96f4000d9321f | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | mag-substrate | b82c7100a492dec67dfd1eda6b3f53def859be35 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | time-to-fill-survival | b66e1e505863d4f17741a4b9ede73509e45bd6c6 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | graphrag-foundation | b0ddeb9f633fd138d09309d1a17b7d13bc3a67f7 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | ws9-bench-ingestion | f585a9ef32fa554663ce1fba9a414a54b6e49cf0 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | presentation-readiness | eb574acaa29d71ce4d0f852572e87c275c79fdb7 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | phase2-connectors | e038d4c687aec16f8bd9bc4d907eea14d91f8704 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | feature/aioe-upgrade | 2178e7298d0e5d9af83afa12402fd587f0ba6ed8 | Open original |
| Janady13/missionmatch / cmd/teach-aggregate/main.go | capture-readiness | bae6af7cb2997e819174a9e9cfff5e16067a1975 | Open original |
Recovered source transcript
Download complete source text ↓277 lines · 14.4 KB
// Command teach-aggregate runs the WS8 teaching loop cadence pass. For each organization it runs the in
// tenant teaching producer (folds that tenant's own reviewer craft into the closed scrub.TeachingSignal
// vocabulary of contents free counts and persists the per tenant teaching_signal_aggregates rows) and then
// the deterministic curation proposal generator (turns recurring approved craft into pending
// curation_proposals a human approves, then a SECOND human verifies, before anything affects a future score).
// Both passes are idempotent and safe to rerun: every upsert refreshes in place and every proposal insert is
// deduped on the active pair. It is a one shot job and a cron candidate like tag-missions and mm-opp-sync.
//
// THE HONEST SCORE INVARIANT. This pass never changes a weight, a band cut, the 0.62 semantic threshold, the
// engine ModelVersion math, or any already served and audited score. The producer only COUNTS what the frozen
// engine already wrote, and the generator only emits a SUGGESTION. The only score affecting change anywhere is
// an additive curated resolver edge that two humans must approve then verify, which changes FUTURE scores only,
// recorded as a model input change (ontology.edge.added), never an engine change. Mission tags and craft
// aggregates are reference data, NEVER a scoring input, and the pass never reaches the eeo schema.
//
// TWO POOL PATTERN (the tag-missions precedent). The READS that fold a tenant's craft and scan its evaluations
// run through the NOBYPASSRLS application role inside each org's RunInTenantTx, so Postgres Row Level Security
// is exercised on every row and one tenant can never read another's. Every WRITE to a global migrator owned
// table (teaching_signal_aggregates, curation_proposals) goes through the BYPASSRLS migrator pool, never the
// app role, which has SELECT only on those tables.
//
// THE CROSS TENANT DIFFERENTIAL PRIVACY PATH STAYS OFF. The cross tenant DP aggregation runs ONLY when
// MM_FEDERATED_DP_ENABLED is true AND the contributing live non test tenant count is at least MinTenants. The
// contributing tenant set is defined by an EXPLICIT production org allow list, the env var
// MM_FEDERATED_PRODUCTION_ORGS (comma separated org uuids, default EMPTY). With the default empty allow list
// the contributing count is zero, below MinTenants, so the cross tenant path is skipped and logged, which is
// the correct posture today: a real five tenant cohort does not exist and the flag is off. NOTE the Mission A
// tenant_directory is the future source of this allow list (the durable list of live non test tenants), and the
// Mironov safe noise sampler (federated.activeAggregator.Noise, an activation blocker today) is a HARD blocker
// before the flag is ever set.
//
// Env (server side only): MM_DATABASE_URL (the app DSN, NOBYPASSRLS, required), MM_MIGRATOR_DATABASE_URL (the
// migrator DSN, BYPASSRLS, used for the global aggregate and proposal writes and to enumerate org ids; falls
// back to MM_DATABASE_URL), MM_FEDERATED_DP_ENABLED / MM_FEDERATED_DP_EPSILON / MM_FEDERATED_DP_DELTA (the DP
// config, default off), MM_FEDERATED_PRODUCTION_ORGS (the contributing tenant allow list, default empty).
//
// Build and run FIPS validated: CGO_ENABLED=0 GOFIPS140=v1.0.0 go build, run with GODEBUG=fips140=on.
package main
import (
"context"
"crypto/fips140"
"crypto/pbkdf2"
"crypto/sha256"
"flag"
"log"
"os"
"strings"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/missionworkforce/missionmatch/internal/modules/ai"
"github.com/missionworkforce/missionmatch/internal/modules/matching/engine"
"github.com/missionworkforce/missionmatch/internal/platform/audit"
"github.com/missionworkforce/missionmatch/internal/platform/config"
"github.com/missionworkforce/missionmatch/internal/platform/database"
"github.com/missionworkforce/missionmatch/internal/platform/database/dbgen"
"github.com/missionworkforce/missionmatch/internal/platform/inference"
"github.com/missionworkforce/missionmatch/internal/platform/security"
"github.com/missionworkforce/missionmatch/internal/platform/tenant"
)
func main() {
orgFlag := flag.String("org", "", "limit the pass to a single organization id (default: all orgs)")
flag.Parse()
// FIPS self test: derive one PBKDF2 key at the production cost under the active crypto module and fail
// closed if it errors, so a build that dropped the validated module is caught at boot, not mid run. This is
// the same in build FIPS gate the api, missionclass-sync, and tag-missions binaries use.
if err := fipsSelfTest(); err != nil {
log.Fatalf("teach-aggregate: FIPS self test (PBKDF2 HMAC SHA 256) failed: %v", err)
}
log.Printf("teach-aggregate: fips_enabled=%v module=%s", fips140.Enabled(), fips140.Version())
cfg, err := config.Load()
if err != nil {
log.Fatalf("teach-aggregate: config: %v", err)
}
appDSN := strings.TrimSpace(os.Getenv("MM_DATABASE_URL"))
if appDSN == "" {
log.Fatal("teach-aggregate: MM_DATABASE_URL (the app DSN) is required")
}
migDSN := firstNonEmpty(os.Getenv("MM_MIGRATOR_DATABASE_URL"), appDSN)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
// App pool: the per tenant craft folds and evaluation scans run here, under RLS, never the migrator bypass.
appPool, err := database.NewPool(ctx, appDSN)
if err != nil {
log.Fatalf("teach-aggregate: app pool: %v", err)
}
defer appPool.Close()
// Fail closed unless this is the NOBYPASSRLS app role, so the pass can never bypass tenant RLS.
if err := database.AssertRole(ctx, appPool, "missionmatch_app"); err != nil {
log.Fatalf("teach-aggregate: app pool role check: %v", err)
}
appDB := tenant.New(appPool)
// Migrator pool: the global aggregate and proposal writes plus the org enumeration. No tenant scoped read
// runs here. teaching_signal_aggregates and curation_proposals are global migrator owned tables the app
// role can only SELECT.
migPool, err := pgxpool.New(ctx, migDSN)
if err != nil {
log.Fatalf("teach-aggregate: migrator pool: %v", err)
}
defer migPool.Close()
if err := database.AssertMigratorRole(ctx, migPool); err != nil {
log.Fatalf("teach-aggregate: %v", err)
}
// The teaching client carries TeachingEnabled from config (default false). With it false, the producer's
// per signal Teach call validates the scrub boundary end to end but transmits nothing off the box, the
// correct in tenant LIVE posture. A nil client is also fine (the producer skips Teach), but build a real one
// when a gateway URL is configured so the boundary is exercised exactly as it will be in production.
var teacher *inference.Client
if cfg.Inference.URL != "" {
t, terr := inference.New(inference.Config{
BaseURL: cfg.Inference.URL, EmbedModel: cfg.Inference.EmbedModel, RerankModel: cfg.Inference.RerankModel,
GenerateModel: cfg.Inference.GenerateModel, Dimension: cfg.Inference.Dimension,
Timeout: time.Duration(cfg.Inference.TimeoutSeconds) * time.Second, MaxRetries: cfg.Inference.MaxRetries,
BreakerTrips: cfg.Inference.BreakerTrips, BreakerCool: time.Duration(cfg.Inference.BreakerCoolSec) * time.Second,
TeachingEnabled: cfg.Inference.TeachingEnabled,
})
if terr != nil {
log.Fatalf("teach-aggregate: inference client: %v", terr)
}
teacher = t
}
// The producer's audit is on the APP pool, because the per tenant teaching.signal.aggregated event commits
// on the same tenant tx that read the decisions (invariant 5). The generator's audit is the SAME writer used
// through System for the global teaching.proposal.created event (NULL org).
auditW := audit.New(appDB)
producer := ai.NewTeachingProducer(appDB, ai.NewMigratorAggregateWriter(migPool), auditW, teacher)
generator := ai.NewProposalGenerator(appDB, ai.NewMigratorGovernanceReader(migPool), ai.NewMigratorProposalWriter(migPool), auditW)
orgIDs, err := listOrgs(ctx, migPool, *orgFlag)
if err != nil {
log.Fatalf("teach-aggregate: list orgs: %v", err)
}
if len(orgIDs) == 0 {
log.Print("teach-aggregate: no organizations to process")
return
}
// The model_version is pinned from engine.ModelVersion, never a literal, so the whole pass stamps the live
// scoring contract and a drifted version is refused at the scrub boundary (the producer registers it at
// init). Logged once so the run record names the contract its aggregates sit on.
log.Printf("teach-aggregate: model_version=%s (pinned from engine.ModelVersion)", engine.ModelVersion)
var totalSignals, totalProposals int
for _, orgID := range orgIDs {
orgCtx := tenant.WithOrg(ctx, orgID.String())
// 1. The in tenant producer: fold this tenant's reviewer craft into per tenant aggregates. RLS scoped
// read on the app pool, global write on the migrator pool, audit on the same tenant tx.
pRes, perr := producer.AggregateForOrg(orgCtx)
if perr != nil {
log.Fatalf("teach-aggregate: org %s aggregate: %v", orgID, perr)
}
// 2. The deterministic curation generator: turn recurring approved craft into pending proposals. RLS
// scoped evaluation scan on the app pool, governance read and proposal write on the migrator pool,
// global proposal created audit through System. Idempotent: a rerun never duplicates an active pair.
gRes, gerr := generator.GenerateProposalsForOrg(orgCtx)
if gerr != nil {
log.Fatalf("teach-aggregate: org %s generate proposals: %v", orgID, gerr)
}
log.Printf("teach-aggregate: org %s folded %d decisions into %d signals, scanned %d evaluations, created %d proposals (%d substitution, %d reciprocity, %d recalibration)",
orgID, pRes.DecisionsRead, len(pRes.Signals), gRes.EvaluationsScanned, gRes.Created,
gRes.SubstitutionEdges, gRes.ReciprocityReviews, gRes.RecalibrationRows)
totalSignals += len(pRes.Signals)
totalProposals += gRes.Created
}
// 3. The CROSS TENANT differential privacy aggregation, gated OFF by posture. It runs ONLY when the flag is
// on AND a real contributing cohort of at least MinTenants live non test tenants exists. With the default
// empty allow list the contributing count is zero, so this is skipped and logged today, which is correct.
runCrossTenantDP(cfg.Federated)
log.Printf("teach-aggregate: DONE, %d org(s), persisted %d teaching signals and created %d curation proposals",
len(orgIDs), totalSignals, totalProposals)
}
// runCrossTenantDP runs the cross tenant differential privacy aggregation when, and ONLY when, two conditions
// both hold: MM_FEDERATED_DP_ENABLED is true, and the contributing tenant count (the live non test orgs in the
// explicit MM_FEDERATED_PRODUCTION_ORGS allow list) is at least MinTenants. Today the allow list defaults to
// empty, so the contributing count is zero, below MinTenants, and the path is skipped and logged. This is the
// correct posture: a real five tenant cohort does not exist and the flag is off. When a real cohort eventually
// exists, the Mironov safe noise sampler (federated Noise, an activation blocker today) must be implemented
// FIRST, and the contributing tenant set should be sourced from the Mission A tenant_directory rather than this
// env allow list. The function deliberately does NO emission yet beyond logging the gate decision; the active
// aggregator construction itself refuses while the flag is off (federated.NewActiveAggregator returns
// ErrDisabled), the hard construction guard this function mirrors at the cadence layer.
func runCrossTenantDP(fed config.Federated) {
contributing := contributingTenants()
minTenants := ai.DefaultFederatedConfig().MinTenants
if !fed.DPEnabled {
log.Printf("teach-aggregate: cross tenant DP SKIPPED, MM_FEDERATED_DP_ENABLED is false (the in tenant posture, no federated emission)")
return
}
if len(contributing) < minTenants {
log.Printf("teach-aggregate: cross tenant DP SKIPPED, %d contributing tenant(s) in MM_FEDERATED_PRODUCTION_ORGS is below MinTenants %d (no real cohort exists yet)",
len(contributing), minTenants)
return
}
// Unreachable in tenant LIVE today (the allow list is empty so the count is always below MinTenants). When a
// real cohort exists this is where the gated aggregation would run, AFTER the Mironov safe sampler ships. It
// is a hard fail until then so an operator who flips the flag prematurely gets a legible refusal, never a
// silent naive Gaussian release.
log.Fatalf("teach-aggregate: cross tenant DP requested with %d contributing tenants but the Mironov safe noise sampler is an activation blocker, refusing to release (implement federated.Noise first)",
len(contributing))
}
// contributingTenants parses MM_FEDERATED_PRODUCTION_ORGS into the set of live non test contributing org ids.
// It is EMPTY by default, so the contributing count is zero and the cross tenant path stays off. Only a well
// formed uuid counts; a malformed entry is skipped rather than silently widening the cohort. The roughly 1088
// test orgs are excluded by construction, because they are simply never in this explicit production allow list.
func contributingTenants() []uuid.UUID {
raw := strings.TrimSpace(os.Getenv("MM_FEDERATED_PRODUCTION_ORGS"))
if raw == "" {
return nil
}
var out []uuid.UUID
for _, part := range strings.Split(raw, ",") {
s := strings.TrimSpace(part)
if s == "" {
continue
}
id, err := uuid.Parse(s)
if err != nil {
log.Printf("teach-aggregate: ignoring malformed org id %q in MM_FEDERATED_PRODUCTION_ORGS", s)
continue
}
out = append(out, id)
}
return out
}
// listOrgs returns the organization ids to process. It reads them through the migrator role (which sees every
// org) so one run covers the cluster; the per org folds and scans then run under the app role and RLS. A -org
// value restricts the run to a single org for a targeted pass.
func listOrgs(ctx context.Context, migPool *pgxpool.Pool, only string) ([]uuid.UUID, error) {
if only != "" {
id, err := uuid.Parse(strings.TrimSpace(only))
if err != nil {
return nil, err
}
return []uuid.UUID{id}, nil
}
return dbgen.New(migPool).ListAllOrganizationIDs(ctx)
}
// fipsSelfTest derives one PBKDF2 key at the production iteration count under the active crypto module. It is
// the in build FIPS gate, identical to the api, missionclass-sync, and tag-missions binaries, so this cadence
// binary is held to the same validated crypto posture.
func fipsSelfTest() error {
_, err := pbkdf2.Key(sha256.New, "missionmatch fips self test", []byte("self test salt"), security.PBKDF2Iterations, 32)
return err
}
func firstNonEmpty(vals ...string) string {
for _, v := range vals {
if s := strings.TrimSpace(v); s != "" {
return s
}
}
return ""
}