Skip to content
Merged
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: 9 additions & 0 deletions docs/architecture/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,7 @@ does not grant consent or start provider work.
"mode": "lexical",
"profile": "private",
"limit": 50,
"content_first": true,
"fence": {
"vault_uid": "22222222-2222-4222-8222-222222222222",
"content_version_ids": ["11111111-1111-4111-8111-111111111111"]
Expand All @@ -512,6 +513,14 @@ several are configured. The CLI requires that choice. `auto` uses lexical
retrieval. See [processing consent](#processing-consent) before choosing a mode
that embeds query text.

Set optional `content_first: true` to prefer retained content matches, including
transcripts, before filename-only matches. Selection applies the exact source
fence before cutoff and keeps content evidence when a filename also matches.
Omission and false keep filename priority. Auto and lexical use this order;
hybrid uses these lexical ranks alongside semantic ranks. Pure semantic accepts
the option without changing vector results. Optional reranking can reorder
the selected candidates. `POST /search/validate` accepts the same preference.

The response includes `requested_mode`, `actual_mode`, `coverage`,
`degradations`, `results`, `truncated`, and `trace` (`explain: true` populates
the trace). An opted-in request also returns a `reranking` receipt with
Expand Down
3 changes: 3 additions & 0 deletions docs/embedding.md
Original file line number Diff line number Diff line change
Expand Up @@ -253,6 +253,9 @@ for provider construction and [Document processing](usage/document-processing.md
for planning, consent, retained results, and the private-deployment acceptance
runner.

Set `DocumentSearchRequest.ContentFirst` to prefer content matches, following the
[HTTP search ordering contract](architecture/http-api.md#coverage-and-source-fenced-search).

## Retain and process a remote recording

Embedded callers can keep the recording identity separate from the protected
Expand Down
3 changes: 3 additions & 0 deletions docs/internal/daemon-api-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,9 @@ branch on the code, not human detail. Adding a store error normally requires:
4. documenting the public code; and
5. testing the non-2xx response envelope.

Document search forwards `content_first` through `retrieval.Query` to the store's
lexical search, following the [HTTP search ordering contract](../architecture/http-api.md#coverage-and-source-fenced-search).

Document search accepts `rerank: true` as an explicit opt-in. The daemon checks
the separate provider grant for `query_text_and_excerpt` before it sends the
query and bounded excerpts to ZeroEntropy or Cohere. The searcher revalidates
Expand Down
3 changes: 3 additions & 0 deletions docs/usage/search.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,9 @@ for receipt fields and degradation causes.
- **`hybrid`** combines lexical and semantic candidates.
- **`auto`** uses lexical retrieval and reports `lexical` as the actual mode.

HTTP and embedded callers can [prefer content matches over filenames](../architecture/http-api.md#coverage-and-source-fenced-search)
with `content_first: true` or `ContentFirst: true`.

Each search response reports the actual mode, degradation, and the number of
complete documents in the supplied source set. The coverage API separately
reports rendition and embedding state, including complete, unavailable, stale,
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/generated/docbank.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions internal/api/media_artifact_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func TestMediaArtifactImportReusesImmutableInputBeforeCreatingNodes(t *testing.T
{name: "changed MIME", filename: "call.srt", mediaType: "text/vtt", newOperation: true, conflict: true},
} {
t.Run(test.name, func(t *testing.T) {
ts, catalog := newTestServer(t, configureMediaTestService(t))
ts, catalog := newTestServer(t, configureMediaTestService(t, 0))
c := daemonconn.New(ts.URL, testAPIKey)
wav := mediatest.WAV()
source, err := c.SubmitSuppliedMedia(t.Context(), api.MediaSuppliedMetadata{
Expand Down Expand Up @@ -77,7 +77,7 @@ func TestMediaArtifactImportReusesImmutableInputBeforeCreatingNodes(t *testing.T

func TestMediaArtifactConcurrentConflictsDoNotCreateExtraNodes(t *testing.T) {
t.Parallel()
ts, catalog := newTestServer(t, configureMediaTestService(t))
ts, catalog := newTestServer(t, configureMediaTestService(t, 0))
c := daemonconn.New(ts.URL, testAPIKey)
wav := mediatest.WAV()
source, err := c.SubmitSuppliedMedia(t.Context(), api.MediaSuppliedMetadata{
Expand Down
4 changes: 2 additions & 2 deletions internal/api/media_remote_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ func TestRemoteRecordingManualHTTPRejectsExtraArtifactPart(t *testing.T) {

func TestMediaAcquisitionPlanRejectsOversizedCanonicalURLWithoutEcho(t *testing.T) {
t.Parallel()
ts, _ := newTestServer(t, configureMediaTestService(t))
ts, _ := newTestServer(t, configureMediaTestService(t, 0))
secret := strings.Repeat("c", 8193)
body := `{"operation_id":"00000000-0000-0000-0000-000000000460","reference_url":"https://recordings.invalid/call","canonical_url":"` + secret + `"}`
response, responseBody := rawJSONRequest(t, ts.URL, http.MethodPost, "/api/v1/media/acquisition-plan",
Expand All @@ -212,7 +212,7 @@ func TestMediaAcquisitionPlanRejectsOversizedCanonicalURLWithoutEcho(t *testing.

func TestMediaAcquisitionPlanRejectsOversizedReferenceURLWithoutEcho(t *testing.T) {
t.Parallel()
ts, _ := newTestServer(t, configureMediaTestService(t))
ts, _ := newTestServer(t, configureMediaTestService(t, 0))
secret := strings.Repeat("r", 8193)
body := `{"operation_id":"00000000-0000-0000-0000-000000000461","reference_url":"` + secret + `","canonical_url":"https://recordings.invalid/call"}`
response, responseBody := rawJSONRequest(t, ts.URL, http.MethodPost, "/api/v1/media/acquisition-plan",
Expand Down
12 changes: 12 additions & 0 deletions internal/api/openapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -732,3 +732,15 @@ func TestOpenAPIProvenanceMTimeUsesDateTimeFormat(t *testing.T) {
assert.Equal(t, "date-time", mtime.Format)
}
}

func TestDocumentSearchContentFirstSchema(t *testing.T) {
t.Parallel()
doc := api.NewOfflineServer().API().OpenAPI()
for _, name := range []string{"DocumentSearchRequest", "DocumentSearchValidationRequest"} {
schema := doc.Components.Schemas.Map()[name]
require.NotNil(t, schema)
require.NotNil(t, schema.Properties["content_first"])
assert.Equal(t, "boolean", schema.Properties["content_first"].Type)
assert.NotContains(t, schema.Required, "content_first")
}
}
99 changes: 90 additions & 9 deletions internal/api/routes_media_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import (

func TestMediaRoutesAreAuthenticatedAndCoverTheTwelveContracts(t *testing.T) {
t.Parallel()
ts, catalog := newTestServer(t, configureMediaTestService(t))
ts, catalog := newTestServer(t, configureMediaTestService(t, 0))
unauthorized, body := get(t, ts, "/api/v1/media/sources?limit=10",
map[string]string{"X-Api-Key": ""})
require.Equal(t, 401, unauthorized.StatusCode, body)
Expand Down Expand Up @@ -212,6 +212,84 @@ func TestMediaRoutesAreAuthenticatedAndCoverTheTwelveContracts(t *testing.T) {
require.NotContains(t, body, catalog.BlobsDir)
}

func TestDocumentSearchContentFirstTranscript(t *testing.T) {
t.Parallel()
ts, catalog := newTestServer(t, configureMediaTestService(t, 1))
c := daemonconn.New(ts.URL, testAPIKey)
wav := mediatest.WAV()
receipt, err := c.SubmitSuppliedMedia(t.Context(), api.MediaSuppliedMetadata{
OperationID: "00000000-0000-4000-8000-000000000801", Filename: "mercury.wav",
MediaType: "audio/wav", SHA256: processingTestHash(string(wav)), ByteLength: int64(len(wav)),
Occurrence: api.MediaOccurrenceBody{Ref: "synthetic-mercury", Revision: "1", Filename: "mercury.wav"},
}, bytes.NewReader(wav))
require.NoError(t, err)
transcript := "mercury retained transcript evidence\n"
artifact, err := c.ImportMediaArtifact(t.Context(), receipt.SourceID, api.MediaArtifactMetadata{
OperationID: "00000000-0000-4000-8000-000000000802", OccurrenceID: receipt.OccurrenceID,
Kind: "transcript", Filename: "captions.txt", MediaType: "text/plain",
SHA256: processingTestHash(transcript), ByteLength: int64(len(transcript)),
}, strings.NewReader(transcript))
require.NoError(t, err)
version, err := catalog.ContentVersionByID(t.Context(), receipt.ContentVersionID)
require.NoError(t, err)
recording, err := catalog.NodeByID(t.Context(), version.NodeID)
require.NoError(t, err)
_, _, err = catalog.Move(t.Context(), recording.ID, *recording.ParentID, "mercury-recording.wav", recording.Revision)
require.NoError(t, err)
selector := api.ProcessingSelector{NodeID: version.NodeID, ContentVersionID: version.ID, Profile: processing.SuppliedMediaProfileName}
plan, err := c.API().PlanDocumentProcessing(t.Context(), &apiclient.PlanDocumentProcessingRequestOptions{Body: &api.ProcessingPlanRequest{Selector: selector}})
require.NoError(t, err)
_, err = c.API().GrantDocumentProcessingConsent(t.Context(), &apiclient.GrantDocumentProcessingConsentRequestOptions{Body: &api.ProcessingConsentGrantRequest{Selector: selector, PlanFingerprint: plan.Fingerprint}})
require.NoError(t, err)
queued, err := c.RetryMedia(t.Context(), receipt.SourceID, api.MediaRetryBody{
OperationID: "00000000-0000-4000-8000-000000000803",
Processing: &api.MediaProcessingBody{Profile: processing.SuppliedMediaProfileName, SuppliedInputID: artifact.SuppliedInputID},
})
require.NoError(t, err)
require.Eventually(t, func() bool {
status, statusErr := c.MediaStatus(t.Context(), receipt.SourceID)
return statusErr == nil && status.OperationID == queued.OperationID && status.OperationState == "succeeded"
}, 30*time.Second, 20*time.Millisecond)
fence := []string{version.ID}
for _, name := range []string{"mercury-a.txt", "mercury-b.txt"} {
node := createFileWithContent(t, ts, catalog, "/"+name, "unrelated synthetic text "+name)
fence = append(fence, node.CurrentVersionID)
}
request := api.DocumentSearchRequest{
Query: "mercury", Mode: "lexical", Profile: processing.SuppliedMediaProfileName, Limit: 1,
Fence: api.DocumentSourceFence{VaultUID: catalog.VaultID(), ContentVersionIDs: fence},
}
control, controlBody := do(t, ts, http.MethodPost, "/api/v1/search", nil, request)
require.Equal(t, http.StatusOK, control.StatusCode, controlBody)
var controlReport api.DocumentSearchReport
require.NoError(t, json.Unmarshal([]byte(controlBody), &controlReport))
require.Len(t, controlReport.Results, 1)
require.Equal(t, "node_name", controlReport.Results[0].Evidence[0].Kind)
require.True(t, controlReport.Truncated)
falseResponse, falseBody := do(t, ts, http.MethodPost, "/api/v1/search", nil, map[string]any{
"query": request.Query, "mode": request.Mode, "profile": request.Profile,
"limit": request.Limit, "fence": request.Fence, "content_first": false,
})
request.ContentFirst = true
response, body := do(t, ts, http.MethodPost, "/api/v1/search", nil, request)
require.Equal(t, http.StatusOK, response.StatusCode, body)
require.Equal(t, http.StatusOK, falseResponse.StatusCode, falseBody)
var falseReport api.DocumentSearchReport
require.NoError(t, json.Unmarshal([]byte(falseBody), &falseReport))
require.Equal(t, controlReport.Results, falseReport.Results)
require.Equal(t, controlReport.Truncated, falseReport.Truncated)
var report api.DocumentSearchReport
require.NoError(t, json.Unmarshal([]byte(body), &report))
require.Len(t, report.Results, 1)
require.Equal(t, version.ID, report.Results[0].ContentVersionID)
require.Equal(t, "rendition_segment", report.Results[0].Evidence[0].Kind)
require.NotEmpty(t, report.Results[0].Evidence[0].BuildID)
require.Contains(t, report.Results[0].Excerpt, "mercury retained transcript evidence")
typedReport, err := c.SearchDocuments(t.Context(), request)
require.NoError(t, err)
require.Equal(t, report.Results, typedReport.Results)
}

func TestMediaTranscriptHTTPReturnsUnavailableWithoutProcessing(t *testing.T) {
t.Parallel()
ts, _ := newTestServer(t, nil)
Expand All @@ -226,7 +304,7 @@ func TestMediaUploadsOutliveRequestTimeout(t *testing.T) {
t.Parallel()
for _, artifact := range []bool{false, true} {
t.Run(fmt.Sprintf("artifact=%t", artifact), func(t *testing.T) {
ts, catalog := newTestServer(t, configureMediaTestService(t))
ts, catalog := newTestServer(t, configureMediaTestService(t, 0))
wav := mediatest.WAV()
supplied := api.MediaSuppliedMetadata{
OperationID: "00000000-0000-4000-8000-000000000601", Filename: "slow.wav",
Expand Down Expand Up @@ -291,7 +369,7 @@ func TestMediaMultipartRejectsIncompleteEnvelopeBeforeRetention(t *testing.T) {
{name: "oversized metadata", oversized: true},
} {
t.Run(test.name, func(t *testing.T) {
ts, catalog := newTestServer(t, configureMediaTestService(t))
ts, catalog := newTestServer(t, configureMediaTestService(t, 0))
wav := mediatest.WAV()
metadata := api.MediaSuppliedMetadata{OperationID: "00000000-0000-4000-8000-000000000391",
Filename: "bounded.wav", MediaType: "audio/wav", SHA256: processingTestHash(string(wav)),
Expand Down Expand Up @@ -342,7 +420,7 @@ func TestMediaMultipartRejectsIncompleteEnvelopeBeforeRetention(t *testing.T) {
}

func TestMediaRetryClassifiesProcessingErrors(t *testing.T) { //nolint:paralleltest // the two-second consent expiry is measured on the real clock
ts, catalog := newTestServer(t, configureMediaTestService(t))
ts, catalog := newTestServer(t, configureMediaTestService(t, 0))
c := daemonconn.New(ts.URL, testAPIKey)
wav := mediatest.WAV()
receipt, err := c.SubmitSuppliedMedia(t.Context(), api.MediaSuppliedMetadata{
Expand Down Expand Up @@ -408,7 +486,7 @@ func TestMediaRetryClassifiesProcessingErrors(t *testing.T) { //nolint:parallelt

func TestMediaReferenceRejectsUnsupportedProcessing(t *testing.T) {
t.Parallel()
ts, _ := newTestServer(t, configureMediaTestService(t))
ts, _ := newTestServer(t, configureMediaTestService(t, 0))
response, body := do(t, ts, http.MethodPost, "/api/v1/media/sources", nil, api.MediaReferenceBody{
OperationID: "00000000-0000-4000-8000-000000000404", ReferenceURL: "https://recordings.invalid/call",
Occurrence: api.MediaOccurrenceBody{Ref: "call", Revision: "1"},
Expand All @@ -422,7 +500,7 @@ func TestMediaReferenceRejectsUnsupportedProcessing(t *testing.T) {

func TestMediaHTTPMP3OrdinaryProcessingFreezesRevokedInput(t *testing.T) {
t.Parallel()
ts, catalog := newTestServer(t, configureMediaTestService(t))
ts, catalog := newTestServer(t, configureMediaTestService(t, 0))
c := daemonconn.New(ts.URL, testAPIKey)
mp3 := mediatest.MP3()
receipt, err := c.SubmitSuppliedMedia(t.Context(), api.MediaSuppliedMetadata{
Expand Down Expand Up @@ -471,7 +549,7 @@ func TestMediaHTTPMP3OrdinaryProcessingFreezesRevokedInput(t *testing.T) {

func TestMediaRouteRejectsCursorOwnedByAnotherPrincipal(t *testing.T) {
t.Parallel()
ts, catalog := newTestServer(t, configureMediaTestService(t))
ts, catalog := newTestServer(t, configureMediaTestService(t, 0))
c := daemonconn.New(ts.URL, testAPIKey)
for index, operationID := range []string{
"00000000-0000-4000-8000-000000000361",
Expand Down Expand Up @@ -500,7 +578,7 @@ func TestMediaRouteRejectsCursorOwnedByAnotherPrincipal(t *testing.T) {

func TestMediaOperationReceiptRecoversLostRemoteSubmission(t *testing.T) {
t.Parallel()
ts, catalog := newTestServer(t, configureMediaTestService(t))
ts, catalog := newTestServer(t, configureMediaTestService(t, 0))
c := daemonconn.New(ts.URL, testAPIKey)
operationID := "00000000-0000-4000-8000-000000000371"
path := "/api/v1/media/operations/" + operationID
Expand Down Expand Up @@ -575,13 +653,16 @@ func newOtherPrincipalMediaServer(t *testing.T, catalog *testStore) *httptest.Se
return otherHTTP
}

func configureMediaTestService(t *testing.T) func(*api.Deps) {
func configureMediaTestService(t *testing.T, lexicalLimit int) func(*api.Deps) {
t.Helper()
return func(deps *api.Deps) {
gate := api.NewOperationGate()
deps.Gate = gate
name, profile, err := processing.NewSuppliedMediaProfile(deps.Store, deps.Blobs, "daemon:operator")
require.NoError(t, err)
if lexicalLimit != 0 {
profile.Profile.Retrieval.LexicalLimit = lexicalLimit
}
var key [32]byte
key[0] = 7
service, err := processing.NewService(processing.ServiceConfig{Catalog: deps.Store,
Expand Down
6 changes: 4 additions & 2 deletions internal/api/routes_processing.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,8 @@ func registerProcessingRoutes(api huma.API, d Deps) {
return nil, processingUnavailable()
}
err := d.Processing.ValidateSearch(ctx, processing.SearchRequest{Query: input.Body.Query,
Mode: input.Body.Mode, Limit: input.Body.Limit, Profile: input.Body.Profile,
ContentFirst: input.Body.ContentFirst,
Mode: input.Body.Mode, Limit: input.Body.Limit, Profile: input.Body.Profile,
BindingID: input.Body.BindingID, Explain: input.Body.Explain, Rerank: input.Body.Rerank})
if err != nil {
return nil, fromProcessingError(err)
Expand All @@ -440,7 +441,8 @@ func registerProcessingRoutes(api huma.API, d Deps) {
return nil, processingUnavailable()
}
report, err := d.Processing.Search(ctx, processing.SearchRequest{Query: input.Body.Query,
Mode: input.Body.Mode, Limit: input.Body.Limit, Profile: input.Body.Profile,
ContentFirst: input.Body.ContentFirst,
Mode: input.Body.Mode, Limit: input.Body.Limit, Profile: input.Body.Profile,
BindingID: input.Body.BindingID, Explain: input.Body.Explain,
Rerank: input.Body.Rerank,
Fence: processing.SourceFence{VaultUID: input.Body.Fence.VaultUID,
Expand Down
8 changes: 7 additions & 1 deletion internal/api/routes_processing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,11 @@ func TestProcessingSearchValidationMatchesSearchQueryAndProfileErrors(t *testing
t.Parallel()
ts, catalog := newTestServer(t, configureProcessingTestService(t))
node := createFileWithContent(t, ts, catalog, "/search-validation.txt", "synthetic search evidence\n")
for _, mode := range []string{"auto", "lexical", "semantic", "hybrid"} {
response, body := do(t, ts, http.MethodPost, "/api/v1/search/validate", nil,
map[string]any{"query": "synthetic", "mode": mode, "profile": "private", "content_first": true})
require.Equal(t, http.StatusOK, response.StatusCode, body)
}

for _, test := range []struct {
name, query, profile string
Expand All @@ -342,9 +347,10 @@ func TestProcessingSearchValidationMatchesSearchQueryAndProfileErrors(t *testing
} {
t.Run(test.name, func(t *testing.T) {
validationResponse, validationBody := do(t, ts, http.MethodPost, "/api/v1/search/validate", nil,
map[string]any{"query": test.query, "mode": "lexical", "limit": 1, "profile": test.profile})
map[string]any{"query": test.query, "mode": "lexical", "limit": 1, "profile": test.profile, "content_first": true})
searchResponse, searchBody := do(t, ts, http.MethodPost, "/api/v1/search", nil,
map[string]any{"query": test.query, "mode": "lexical", "limit": 1, "profile": test.profile,
"content_first": true,
"fence": map[string]any{"vault_uid": catalog.VaultID(),
"content_version_ids": []string{node.CurrentVersionID}}})
assert.Equal(t, searchResponse.StatusCode, validationResponse.StatusCode)
Expand Down
12 changes: 8 additions & 4 deletions internal/api/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,8 +236,10 @@ type DocumentSearchRequest struct {
Profile string `json:"profile" minLength:"1" maxLength:"128" pattern:"^[a-z][a-z0-9_-]*$"`
BindingID string `json:"binding_id,omitzero" maxLength:"128"`
Fence DocumentSourceFence `json:"fence"`
Explain bool `json:"explain,omitzero"`
Rerank bool `json:"rerank,omitzero"`

Explain bool `json:"explain,omitzero"`
Rerank bool `json:"rerank,omitzero"`
ContentFirst bool `json:"content_first,omitzero"`
}

type DocumentSimilarRequest struct {
Expand Down Expand Up @@ -295,8 +297,10 @@ type DocumentSearchValidationRequest struct {
Limit int `json:"limit,omitzero" minimum:"1" maximum:"100"`
Profile string `json:"profile" minLength:"1" maxLength:"128" pattern:"^[a-z][a-z0-9_-]*$"`
BindingID string `json:"binding_id,omitzero" maxLength:"128"`
Explain bool `json:"explain,omitzero"`
Rerank bool `json:"rerank,omitzero"`

Explain bool `json:"explain,omitzero"`
Rerank bool `json:"rerank,omitzero"`
ContentFirst bool `json:"content_first,omitzero"`
}

type DocumentSearchValidation struct {
Expand Down
Loading
Loading