feat(matching): rank with semantic embeddings and explain matches by evidence

This commit is contained in:
shira committed 2026-10-11 10:39:46 +03:00
1 parent facc1789b1
commit 24b64d698a
215 files changed
+16951 -327

No files matched your search

@@ -1,5 +1,6 @@
// Package policypublish implements the local operator command that adds the
// demo matching section to the product policy. Until an administrative policy
// demo matching section, or the semantic matching section, to the product
// policy. Until an administrative policy
// editor exists, this is how a stand gets the coefficients that the match
// search needs: startup seeds only the first demo version.
package policypublish
@@ -20,24 +21,38 @@ import (
"lincodex/backend/internal/usecase/policy"
)
const usage = "usage: policy-publish matching --actor operator:<handle>"
const usage = "usage: policy-publish matching|semantic --actor operator:<handle>"
// Track names which section a command publishes.
type Track string
const (
// TrackMatching adds the PRD matching section (Sem weight 0.10).
TrackMatching Track = "matching"
// TrackSemantic adds the semantic matching section (Sem weight 0.5, the
// encoder identity, the calibration, and the explanation thresholds).
TrackSemantic Track = "semantic"
)
// Command is a parsed, validated request.
type Command struct {
Track Track
Author domain.PolicyAuthor
}
// Extender publishes the demo matching section.
type Extender interface {
EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
EnsureDemoSemanticMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
}
// Parse validates every argument before Run reads configuration or connects.
func Parse(args []string) (Command, error) {
if len(args) == 0 || args[0] != "matching" {
if len(args) == 0 || (args[0] != string(TrackMatching) && args[0] != string(TrackSemantic)) {
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("policy-publish matching", flag.ContinueOnError)
track := Track(args[0])
flags := flag.NewFlagSet("policy-publish "+args[0], flag.ContinueOnError)
flags.SetOutput(io.Discard)
actor := flags.String("actor", "", "operator handle")
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
@@ -48,7 +63,7 @@ func Parse(args []string) (Command, error) {
if err != nil || !strings.HasPrefix(value, "operator:") {
return Command{}, errors.New("actor must be operator:<handle>")
}
return Command{Author: author}, nil
return Command{Track: track, Author: author}, nil
}
// Run parses the command, loads only DATABASE_URL from the supplied
@@ -81,7 +96,14 @@ func Execute(ctx context.Context, command Command, extender Extender, output io.
if extender == nil || output == nil {
return errors.New("policy publication command dependencies are required")
}
result, err := extender.EnsureDemoMatchingSection(ctx, command.Author)
publish, section, note := extender.EnsureDemoMatchingSection, "the demo matching section",
"note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n"
if command.Track == TrackSemantic {
publish, section, note = extender.EnsureDemoSemanticMatchingSection, "the semantic matching section",
"note: research-calibrated values (LincodexMatch DEV split), not product measurements; searches use them at once,\n"+
"and Sem stays neutral for subjects without vectors until the semantic-backfill command has run\n"
}
result, err := publish(ctx, command.Author)
if err != nil {
return safeOperationError(err)
}
@@ -89,11 +111,7 @@ func Execute(ctx context.Context, command Command, extender Extender, output io.
if result.Created {
status = "published"
}
if _, err := fmt.Fprintf(output,
"%s: product policy version %d carries the demo matching section\n"+
"note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n",
status, result.Version.Version(),
); err != nil {
if _, err := fmt.Fprintf(output, "%s: product policy version %d carries %s\n%s", status, result.Version.Version(), section, note); err != nil {
return errors.New("could not write the result")
}
return nil
@@ -13,9 +13,10 @@ import (
)
type extenderFake struct {
result policy.MatchingResult
err error
author domain.PolicyAuthor
result policy.MatchingResult
err error
author domain.PolicyAuthor
semantic bool
}
func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
@@ -23,11 +24,21 @@ func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, autho
return extender.result, extender.err
}
func (extender *extenderFake) EnsureDemoSemanticMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
extender.author = author
extender.semantic = true
return extender.result, extender.err
}
func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) {
command, err := Parse([]string{"matching", "--actor", "operator:night"})
if err != nil || command.Author != "operator:night" {
if err != nil || command.Author != "operator:night" || command.Track != TrackMatching {
t.Fatalf("Parse(valid) = %+v, %v", command, err)
}
semantic, err := Parse([]string{"semantic", "--actor", "operator:night"})
if err != nil || semantic.Track != TrackSemantic {
t.Fatalf("Parse(semantic) = %+v, %v", semantic, err)
}
for _, args := range [][]string{
nil, {"list"}, {"matching"}, {"matching", "--actor", "alice"}, {"matching", "--actor", "system:demo-seed"},
{"matching", "--actor", "operator:night", "extra"},
@@ -62,3 +73,14 @@ func TestExecutePrintsOnlyTheVersionAndMapsFailuresToSafeMessages(t *testing.T)
}
}
}
func TestExecuteSemanticTrackPublishesTheSemanticSection(t *testing.T) {
var output bytes.Buffer
extender := &extenderFake{}
if err := Execute(context.Background(), Command{Track: TrackSemantic, Author: "operator:night"}, extender, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
if !extender.semantic || !strings.Contains(output.String(), "the semantic matching section") {
t.Fatalf("output = %q, semantic called %v", output.String(), extender.semantic)
}
}
@@ -0,0 +1,120 @@
// Package semanticbackfill implements the operator command that schedules
// vector jobs for existing published candidates and needs, for example after
// semantic matching is enabled, the semantic policy is published, or the ML
// model changes. The jobs run in the backend worker; the command only
// schedules them and prints the resume cursor of every page.
package semanticbackfill
import (
"context"
"errors"
"flag"
"fmt"
"io"
"time"
"github.com/google/uuid"
"lincodex/backend/config"
"lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/usecase/semantic"
)
const usage = "usage: semantic-backfill candidates|needs|all --run <label> [--after <uuid>]"
// Command is a parsed, validated request.
type Command struct {
Scopes []semantic.BackfillScope
Run string
After uuid.UUID
}
// Runner schedules the jobs of one scope.
type Runner interface {
Run(ctx context.Context, scope semantic.BackfillScope, run string, after uuid.UUID, report func(semantic.BackfillProgress) error) error
}
// Parse validates every argument before Run reads configuration or connects.
func Parse(args []string) (Command, error) {
if len(args) == 0 {
return Command{}, errors.New(usage)
}
var scopes []semantic.BackfillScope
switch args[0] {
case string(semantic.BackfillCandidates):
scopes = []semantic.BackfillScope{semantic.BackfillCandidates}
case string(semantic.BackfillNeeds):
scopes = []semantic.BackfillScope{semantic.BackfillNeeds}
case "all":
scopes = []semantic.BackfillScope{semantic.BackfillCandidates, semantic.BackfillNeeds}
default:
return Command{}, errors.New(usage)
}
flags := flag.NewFlagSet("semantic-backfill", flag.ContinueOnError)
flags.SetOutput(io.Discard)
run := flags.String("run", "", "run label; a new label recomputes again")
after := flags.String("after", "", "resume after this identifier")
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 || *run == "" {
return Command{}, errors.New(usage)
}
command := Command{Scopes: scopes, Run: *run}
if *after != "" {
if len(scopes) != 1 {
return Command{}, errors.New("--after needs a single scope")
}
parsed, err := uuid.Parse(*after)
if err != nil {
return Command{}, errors.New("--after must be a UUID")
}
command.After = parsed
}
return command, nil
}
// Run parses the command, loads only DATABASE_URL, and schedules.
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error {
command, err := Parse(args)
if err != nil {
return err
}
if lookup == nil || output == nil || clock == nil {
return errors.New("semantic backfill command dependencies are required")
}
databaseURL := config.DatabaseURLFromEnv(lookup)
if databaseURL == "" {
return errors.New("DATABASE_URL is not set")
}
pool, err := postgres.NewPool(ctx, databaseURL)
if err != nil {
return errors.New("database configuration is invalid")
}
defer pool.Close()
if err := pool.Ping(ctx); err != nil {
return errors.New("database is unavailable")
}
backfill, err := semantic.NewBackfill(postgres.NewTransactor(pool), clock)
if err != nil {
return err
}
return Execute(ctx, command, backfill, output)
}
// Execute runs every scope and prints one line per page.
func Execute(ctx context.Context, command Command, runner Runner, output io.Writer) error {
for _, scope := range command.Scopes {
total := 0
err := runner.Run(ctx, scope, command.Run, command.After, func(progress semantic.BackfillProgress) error {
total += progress.Scheduled
_, err := fmt.Fprintf(output, "%s: scheduled %d (total %d), resume with --after %s\n",
progress.Scope, progress.Scheduled, total, progress.After)
return err
})
if err != nil {
return errors.New("the backfill stopped; run it again with --after of the last printed line")
}
if _, err := fmt.Fprintf(output, "%s: done, %d jobs scheduled; the backend worker computes them\n", scope, total); err != nil {
return errors.New("could not write the result")
}
}
return nil
}
@@ -0,0 +1,63 @@
package semanticbackfill
import (
"bytes"
"context"
"errors"
"strings"
"testing"
"github.com/google/uuid"
"lincodex/backend/internal/usecase/semantic"
)
type runnerFake struct {
scopes []semantic.BackfillScope
err error
}
func (runner *runnerFake) Run(_ context.Context, scope semantic.BackfillScope, _ string, after uuid.UUID, report func(semantic.BackfillProgress) error) error {
runner.scopes = append(runner.scopes, scope)
if runner.err != nil {
return runner.err
}
return report(semantic.BackfillProgress{Scope: scope, Scheduled: 2, After: after, Done: true})
}
func TestParseRequiresAScopeAndARunLabel(t *testing.T) {
command, err := Parse([]string{"all", "--run", "2026-10-11"})
if err != nil || len(command.Scopes) != 2 || command.Run != "2026-10-11" {
t.Fatalf("Parse(all) = %+v, %v", command, err)
}
after := uuid.New()
command, err = Parse([]string{"needs", "--run", "r1", "--after", after.String()})
if err != nil || command.After != after {
t.Fatalf("Parse(needs --after) = %+v, %v", command, err)
}
for _, args := range [][]string{
nil, {"vectors"}, {"candidates"}, {"all", "--run", "r1", "--after", after.String()},
{"needs", "--run", "r1", "--after", "x"}, {"needs", "--run", "r1", "extra"},
} {
if _, err := Parse(args); err == nil {
t.Errorf("Parse(%v) accepted invalid arguments", args)
}
}
}
func TestExecuteReportsEveryScopeAndHidesStorageErrors(t *testing.T) {
var output bytes.Buffer
runner := &runnerFake{}
command := Command{Scopes: []semantic.BackfillScope{semantic.BackfillCandidates, semantic.BackfillNeeds}, Run: "r1"}
if err := Execute(context.Background(), command, runner, &output); err != nil {
t.Fatalf("Execute() error = %v", err)
}
if len(runner.scopes) != 2 || !strings.Contains(output.String(), "needs: done, 2 jobs scheduled") {
t.Fatalf("output = %q", output.String())
}
failing := &runnerFake{err: errors.New("pq: password authentication failed for user x")}
err := Execute(context.Background(), command, failing, &bytes.Buffer{})
if err == nil || strings.Contains(err.Error(), "password") {
t.Fatalf("Execute(failing) error = %v, want a safe message", err)
}
}