gortex icon indicating copy to clipboard operation
gortex copied to clipboard

SQLite symbol searches keep running after MCP request cancellation

Open rolldav opened this issue 1 month ago • 2 comments

Describe the bug

A cancelled symbol search can keep its worker blocked on a SQLite connection after the MCP middleware has returned its deadline error. The request context does not reach the query engine/search adapters/store reads, which use context-free SQL APIs.

This is a follow-up to the caller deadline protection in #385: the terminal response is bounded, but the underlying read-only search work need not stop. It is distinct from startup/warmup progress and from the change.detect issue #691. I am not claiming this explains every reported daemon hang.

Reproduction

Reproduced against current main e08a48a5efc35cbe87d06861538f9d07cb746744 and initially against af1438b6d84a2c870572a28ec62a21b94fda98fa (v0.64.8+af1438b). Environment: macOS arm64, Go 1.27.2.

Captured tool outputs (initial installed version, then current test toolchain):

$ gortex version --short
v0.64.8+af1438b
$ go version
go version go1.27.2 darwin/arm64

The self-contained test below uses only a temporary SQLite database. It first proves that normal repository-scoped exact-name and multi-word FTS searches work, holds the only connection, waits for the search to actually queue for that connection, cancels the context, and requires the worker to exit before the connection is released. Cleanup releases the connection even on failure. No shared daemon or real repository is needed.

Save as internal/graph/store_sqlite/search_cancellation_test.go on the baseline, then run:

go test ./internal/graph/store_sqlite -run '^TestSearchCancellationReleasesPoolWait$' -count=1 -timeout=3m
package store_sqlite

import (
	"context"
	"path/filepath"
	"testing"
	"time"

	"github.com/zzet/gortex/internal/graph"
	"github.com/zzet/gortex/internal/query"
	"github.com/zzet/gortex/internal/search"
)

// Use the existing entry point on an unpatched binary so the regression
// demonstrates blocked work, rather than failing to compile on a new API.
func cancellationEngine(e *query.Engine, ctx context.Context) *query.Engine {
	if contextual, ok := any(e).(interface {
		WithContext(context.Context) *query.Engine
	}); ok {
		return contextual.WithContext(ctx)
	}
	return e
}

func TestSearchCancellationReleasesPoolWait(t *testing.T) {
	for _, term := range []string{"WidgetExtensions", "widget extensions"} {
		t.Run(term, func(t *testing.T) {
			s, err := Open(filepath.Join(t.TempDir(), "search.sqlite"))
			if err != nil {
				t.Fatal(err)
			}
			defer s.Close()
			n := &graph.Node{ID: "app/widget.go::WidgetExtensions", Name: "WidgetExtensions", Kind: graph.KindType, RepoPrefix: "app", FilePath: "app/widget.go"}
			s.AddNode(n)
			if err := s.UpsertSymbolFTS(n.ID, "widget extensions"); err != nil {
				t.Fatal(err)
			}
			e := query.NewEngine(s)
			e.SetSearch(search.NewSwappable(search.NewSymbolSearcherBackend(s)))
			opts := query.QueryOptions{RepoAllow: map[string]bool{"app": true}, SkipInnerRerank: true, SkipVectorChannel: true}
			// Positive control proves the scoped production backend is active, and warms
			// its memoised corpus gate before deliberately exhausting the private pool.
			if got := e.GatherSymbolCandidates(term, 5, opts, nil); len(got) != 1 || got[0].Node.ID != n.ID {
				t.Fatalf("positive scoped control: %#v", got)
			}
			s.db.SetMaxOpenConns(1)
			conn, err := s.db.Conn(context.Background())
			if err != nil {
				t.Fatal(err)
			}
			defer conn.Close()
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()
			done := make(chan struct{})
			before := s.db.Stats().WaitCount
			go func() { defer close(done); cancellationEngine(e, ctx).GatherSymbolCandidates(term, 5, opts, nil) }()
			wait := time.NewTimer(time.Second)
			defer wait.Stop()
			for s.db.Stats().WaitCount == before {
				select {
				case <-wait.C:
					conn.Close()
					<-done
					t.Fatal("query never reached held connection")
				default:
					time.Sleep(time.Millisecond)
				}
			}
			cancel()
			select {
			case <-done:
			case <-time.After(300 * time.Millisecond):
				conn.Close()
				<-done
				t.Fatal("cancelled search kept waiting for the private SQLite connection")
			}
			conn.Close()
			if got := e.GatherSymbolCandidates(term, 5, opts, nil); len(got) != 1 {
				t.Fatalf("active context polluted by cancellation: %#v", got)
			}
		})
	}
}

The small optional-interface helper lets the same reproducer exercise both the old API and the proposed request-local context API; it is not production code.

Observed result

Current-main command exit status: 1. Both cases fail after cancellation, before cleanup releases the held connection:

--- FAIL: TestSearchCancellationReleasesPoolWait
    --- FAIL: TestSearchCancellationReleasesPoolWait/WidgetExtensions
        cancelled search kept waiting for the private SQLite connection
    --- FAIL: TestSearchCancellationReleasesPoolWait/widget_extensions
        cancelled search kept waiting for the private SQLite connection
FAIL

Expected behavior

The worker stops waiting for SQLite when its request is cancelled. A subsequent active request can still use the shared engine. Context must remain request-local, and repository/generation scope and complete bundle edge metadata must remain unchanged.

Proposed correction

Preserve engine selection identity and bind the request context to an engine clone at MCP search execution boundaries; forward it through optional contextual search capabilities and composed-view layers down to SQLite QueryContext/QueryRowContext and bundle reads; do not fall back into more searches after cancellation. Keep existing non-context APIs for other callers.

This reproducer establishes cancellation of connection-pool waiting. It does not measure every long-running SQL statement, lock acquisition in the backend wrapper, or all legacy graph/rerank paths. The prepared implementation proposal below includes targeted regression tests and validation details; it is not an open PR.

Prepared PR proposal — issue-first review

This change crosses query, search, MCP and storage boundaries. In accordance with CONTRIBUTING.md, it is presented here for design review before a code submission. The guide's actual PR flow uses a fork; no fork-based PR is requested as part of this proposal.

Suggested title: fix(search): propagate MCP cancellation to SQLite symbol reads

Suggested summary: MCP deadline middleware can return while the underlying symbol-search worker remains blocked on SQLite. Carry the request context from search execution through the existing adapters to context-aware SQLite reads so cancellation releases the worker, while retaining existing non-context APIs and base-engine identity.

Complete patch and tests: self-contained proposed diff. It applies cleanly to the exact base above (git apply --check: exit 0); no contributor-fork reference is needed to retrieve the patch.

Implementation boundaries:

  • Keep engineFor identity/routing unchanged; bind context at search execution boundaries to independent engine clones.
  • Use optional contextual backend capabilities; preserve text/vector channel separation, repository/generation predicates and complete edge metadata.
  • Stop further search fallback once cancelled. Propagate cancellation through composed-view/refill paths and embedding requests.
  • No new dependency, installation, runtime configuration or shared-daemon change.

Recorded validation:

  • Baseline exact-name and multi-word FTS cancellation reproduction: exit 1, expected failure.
  • Targeted regression tests with -race, including the real MCP search handler through deadline middleware: exit 0.
  • Complete MCP package with -race, including the unchanged base-engine identity/allocation oracle: exit 0.
  • Full query/search package tests and channel compatibility tests: exit 0.
  • Plain CLI build: exit 0. Built executable not installed.
  • Upstream-pinned golangci-lint v2.13.1 with module toolchain Go 1.27.0: exit 0, 0 issues.
  • Complete go test -race -p 2 ./... -timeout=20m: exit 1, only TestResolverHelper_RealTsserver_DefinitionAcrossFiles failed. The same assertion fails on an unmodified copy of the exact base and on the proposed patch in focused comparisons. No unrelated LSP test/configuration/time limit was changed. Pyright failed an earlier complete run, then passed both focused comparisons and the final complete run; that initial failure remains unassigned.
  • Local benchmarks not run; no throughput claim. This proposal does not claim that all upstream CI gates pass.

Remaining limits: connection-pool wait cancellation is reproduced; interruption of every long-running SQL statement, backend RLock acquisition, all legacy graph/rerank paths and warmup/retirement are outside the demonstrated scope. This does not establish the sole cause of any historical shared-daemon saturation.

The proposed patch is submitted for maintainer review under the contribution terms in CONTRIBUTING.md. Please assess the design/optional-capability approach before turning it into an upstream branch or PR.

rolldav avatar Oct 18 '26 07:10 rolldav

Self-contained proposed patch for maintainer review

This is an implementation proposal attached to the official issue, not an open pull request or an upstream-approved change. It has no dependency on a contributor fork.

Base: e08a48a5efc35cbe87d06861538f9d07cb746744.

The consolidated diff includes the correction and regression tests. git apply --check against a clean copy of that exact base returned exit 0. A maintainer can save the diff as search-cancellation.patch and review/apply it with the normal Git patch workflow. No installation or shared-daemon mutation was performed.

Validation: focused race tests, complete MCP suite, pinned lint and plain CLI build passed. The complete race suite returned exit 1 only for the real TypeScript definition integration test, which fails identically on the unmodified base. The issue description records details and limits; this is not a claim that every upstream gate is green.

Complete proposed diff, including tests
diff --git a/internal/graph/store_sqlite/search_cancellation_test.go b/internal/graph/store_sqlite/search_cancellation_test.go
new file mode 100644
index 0000000..e6680e0
--- /dev/null
+++ b/internal/graph/store_sqlite/search_cancellation_test.go
@@ -0,0 +1,158 @@
+package store_sqlite
+
+import (
+	"context"
+	"path/filepath"
+	"reflect"
+	"testing"
+	"time"
+
+	"github.com/zzet/gortex/internal/graph"
+	"github.com/zzet/gortex/internal/query"
+	"github.com/zzet/gortex/internal/search"
+)
+
+func TestSearchCancellationReleasesPoolWait(t *testing.T) {
+	for _, term := range []string{"WidgetExtensions", "widget extensions"} {
+		t.Run(term, func(t *testing.T) {
+			s, err := Open(filepath.Join(t.TempDir(), "search.sqlite"))
+			if err != nil {
+				t.Fatal(err)
+			}
+			defer s.Close()
+			n := &graph.Node{ID: "app/widget.go::WidgetExtensions", Name: "WidgetExtensions", Kind: graph.KindType, RepoPrefix: "app", FilePath: "app/widget.go"}
+			s.AddNode(n)
+			if err := s.UpsertSymbolFTS(n.ID, "widget extensions"); err != nil {
+				t.Fatal(err)
+			}
+			e := query.NewEngine(s)
+			e.SetSearch(search.NewSwappable(search.NewSymbolSearcherBackend(s)))
+			opts := query.QueryOptions{RepoAllow: map[string]bool{"app": true}, SkipInnerRerank: true, SkipVectorChannel: true}
+			// Positive control proves the scoped production backend is active, and warms
+			// its memoised corpus gate before deliberately exhausting the private pool.
+			if got := e.GatherSymbolCandidates(term, 5, opts, nil); len(got) != 1 || got[0].Node.ID != n.ID {
+				t.Fatalf("positive scoped control: %#v", got)
+			}
+			s.db.SetMaxOpenConns(1)
+			conn, err := s.db.Conn(context.Background())
+			if err != nil {
+				t.Fatal(err)
+			}
+			defer conn.Close()
+			ctx, cancel := context.WithCancel(context.Background())
+			defer cancel()
+			done := make(chan struct{})
+			before := s.db.Stats().WaitCount
+			go func() { defer close(done); e.WithContext(ctx).GatherSymbolCandidates(term, 5, opts, nil) }()
+			wait := time.NewTimer(time.Second)
+			defer wait.Stop()
+			for s.db.Stats().WaitCount == before {
+				select {
+				case <-wait.C:
+					conn.Close()
+					<-done
+					t.Fatal("query never reached held connection")
+				default:
+					time.Sleep(time.Millisecond)
+				}
+			}
+			cancel()
+			select {
+			case <-done:
+			case <-time.After(300 * time.Millisecond):
+				conn.Close()
+				<-done
+				t.Fatal("cancelled search kept waiting for the private SQLite connection")
+			}
+			conn.Close()
+			if got := e.GatherSymbolCandidates(term, 5, opts, nil); len(got) != 1 {
+				t.Fatalf("active context polluted by cancellation: %#v", got)
+			}
+		})
+	}
+}
+
+// The indexed corpus can be answered immediately while an exact view layer
+// waits on SQLite. This exercises the second FTS hop, not just the base lane.
+type emptyIndexedCorpus struct{}
+
+func (emptyIndexedCorpus) Add(string, ...string)                    {}
+func (emptyIndexedCorpus) Remove(string)                            {}
+func (emptyIndexedCorpus) Close()                                   {}
+func (emptyIndexedCorpus) Count() int                               { return 1 }
+func (emptyIndexedCorpus) Search(string, int) []search.SearchResult { return nil }
+
+func TestViewLayerSearchCancellationReleasesPoolWait(t *testing.T) {
+	base, derived := openGenerationReadPair(t)
+	// Same logical ID, distinct generation payloads: a generation-blind query
+	// cannot pass the positive controls.
+	for _, store := range []*Store{base, derived} {
+		hits, err := store.SearchSymbolBundlesContext(context.Background(), "Shared", 5)
+		if err != nil || len(hits) != 1 {
+			t.Fatalf("generation scoped FTS: %v %v", hits, err)
+		}
+		if hits[0].Node.Name != "Shared"+map[*Store]string{base: genZeroMark, derived: genOneMark}[store] {
+			t.Fatalf("wrong generation payload: %+v", hits[0].Node)
+		}
+	}
+	e := query.NewEngine(derived)
+	e.SetSearch(search.NewSwappable(emptyIndexedCorpus{}))
+	e = e.WithViewLayers(derived, []query.ViewLayerSource{{Search: search.NewSymbolSearcherBackend(derived)}})
+	opts := query.QueryOptions{SkipInnerRerank: true, SkipVectorChannel: true, SkipExactNameSplice: true}
+	if got := e.GatherSymbolCandidates("Shared", 5, opts, nil); len(got) != 1 {
+		t.Fatalf("positive layer control: %#v", got)
+	}
+	base.db.SetMaxOpenConns(1)
+	conn, err := base.db.Conn(context.Background())
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer conn.Close()
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+	done := make(chan struct{})
+	before := base.db.Stats().WaitCount
+	go func() { defer close(done); e.WithContext(ctx).GatherSymbolCandidates("Shared", 5, opts, nil) }()
+	timeout := time.NewTimer(time.Second)
+	defer timeout.Stop()
+	for base.db.Stats().WaitCount == before {
+		select {
+		case <-timeout.C:
+			conn.Close()
+			<-done
+			t.Fatal("layer never reached held connection")
+		default:
+			time.Sleep(time.Millisecond)
+		}
+	}
+	cancel()
+	select {
+	case <-done:
+	case <-time.After(300 * time.Millisecond):
+		conn.Close()
+		<-done
+		t.Fatal("cancelled exact-view layer kept waiting")
+	}
+}
+
+func TestSearchBundlesContextPreservesEdgeMetadata(t *testing.T) {
+	s := floodedScopeStore(t, 0)
+	id := "app/widget.go::WidgetExtensions"
+	other := "app/other.go::Caller"
+	s.AddNode(&graph.Node{ID: other, Name: "Caller", Kind: graph.KindFunction, RepoPrefix: "app", FilePath: "app/other.go"})
+	for _, ends := range [][2]string{{id, other}, {other, id}} {
+		s.AddEdge(&graph.Edge{From: ends[0], To: ends[1], Kind: graph.EdgeCalls, FilePath: "app/widget.go", Line: 1, Meta: map[string]any{"similarity": 0.75, "resolve_terminal": true, "resolve_terminal_reason": "test", "semantic_source": "fixture"}})
+	}
+	expectedOut := s.GetOutEdgesByNodeIDs([]string{id})[id]
+	expectedIn := s.GetInEdgesByNodeIDs([]string{id})[id]
+	if len(expectedOut) != 1 || len(expectedIn) != 1 || expectedOut[0].Meta["similarity"] != 0.75 {
+		t.Fatal("full edge positive control failed")
+	}
+	bundles, err := s.SearchSymbolBundlesRepoScopedContext(context.Background(), "widget extensions", []string{"app"}, 5)
+	if err != nil || len(bundles) != 1 {
+		t.Fatalf("bundle: %v %v", bundles, err)
+	}
+	if !reflect.DeepEqual(bundles[0].OutEdges, expectedOut) || !reflect.DeepEqual(bundles[0].InEdges, expectedIn) {
+		t.Fatalf("bundle metadata lost: out=%+v in=%+v", bundles[0].OutEdges[0].Meta, bundles[0].InEdges[0].Meta)
+	}
+}
diff --git a/internal/graph/store_sqlite/store_fts.go b/internal/graph/store_sqlite/store_fts.go
index 155c719..93ea599 100644
--- a/internal/graph/store_sqlite/store_fts.go
+++ b/internal/graph/store_sqlite/store_fts.go
@@ -89,8 +89,12 @@ func (s *Store) UpsertSymbolFTS(nodeID, tokens string) error {
 // every document. One row per document is the invariant the delete path
 // maintains, so this is the corpus size.
 func (s *Store) SymbolFTSCount() (int, error) {
+	return s.SymbolFTSCountContext(context.Background())
+}
+
+func (s *Store) SymbolFTSCountContext(ctx context.Context) (int, error) {
 	var count int
-	if err := s.db.QueryRow(`SELECT COUNT(*) FROM symbol_fts_rowid WHERE view_gen = ?`, s.viewGen).Scan(&count); err != nil {
+	if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM symbol_fts_rowid WHERE view_gen = ?`, s.viewGen).Scan(&count); err != nil {
 		return 0, err
 	}
 	return count, nil
@@ -634,7 +638,12 @@ func (s *Store) BuildSymbolIndex() error {
 // SQLite's bm25() returns lower-is-better, so the stored Score is its
 // negation (higher-is-better, matching the SymbolHit contract).
 func (s *Store) SearchSymbols(query string, limit int) ([]graph.SymbolHit, error) {
-	return s.SearchSymbolsRepoScoped(query, nil, limit)
+	return s.SearchSymbolsContext(context.Background(), query, limit)
+}
+
+// SearchSymbolsContext propagates request cancellation through exact and FTS tiers.
+func (s *Store) SearchSymbolsContext(ctx context.Context, query string, limit int) ([]graph.SymbolHit, error) {
+	return s.SearchSymbolsRepoScopedContext(ctx, query, nil, limit)
 }
 
 // SearchSymbolsRepoScoped is SearchSymbols narrowed to the repoAllow
@@ -646,6 +655,16 @@ func (s *Store) SearchSymbols(query string, limit int) ([]graph.SymbolHit, error
 // without the IN). A nil / empty repoAllow is the exact unscoped
 // behaviour.
 func (s *Store) SearchSymbolsRepoScoped(query string, repoAllow []string, limit int) ([]graph.SymbolHit, error) {
+	return s.SearchSymbolsRepoScopedContext(context.Background(), query, repoAllow, limit)
+}
+
+// SearchSymbolsRepoScopedContext preserves generation and repository predicates
+// while allowing both connection acquisition and SQLite execution to be cancelled.
+func (s *Store) SearchSymbolsRepoScopedContext(ctx context.Context, query string, repoAllow []string, limit int) ([]graph.SymbolHit, error) {
+	if err := ctx.Err(); err != nil {
+		return nil, err
+	}
+
 	if query == "" {
 		return nil, nil
 	}
@@ -669,7 +688,10 @@ func (s *Store) SearchSymbolsRepoScoped(query string, repoAllow []string, limit
 	// module named "Extensions" would otherwise eclipse every
 	// `*Extensions` class the FTS ranks first.
 	if isIdentifierQuery(query) {
-		ns := s.FindNodesByName(query)
+		ns := s.queryNodesContext(ctx, s.stmtFindByName, query, s.viewGen)
+		if err := ctx.Err(); err != nil {
+			return nil, err
+		}
 		if len(ns) > 0 {
 			out := make([]graph.SymbolHit, 0, minInt(len(ns), limit))
 			for _, n := range ns {
@@ -721,7 +743,7 @@ WHERE symbol_fts MATCH ?`
 	}
 	q += ` ORDER BY bm25(symbol_fts) LIMIT ?`
 	args = append(args, limit)
-	rows, err := s.db.Query(q, args...)
+	rows, err := s.db.QueryContext(ctx, q, args...)
 	if err != nil {
 		return nil, err
 	}
@@ -812,27 +834,31 @@ func escapeFTSQuote(t string) string {
 // through this when the backend implements SymbolBundleSearcher,
 // pre-seeding rerank.Context's edge caches.
 func (s *Store) SearchSymbolBundles(query string, limit int) ([]graph.SymbolBundle, error) {
-	hits, err := s.SearchSymbols(query, limit)
-	if err != nil {
-		return nil, err
-	}
-	return s.bundlesForHits(hits)
+	return s.SearchSymbolBundlesContext(context.Background(), query, limit)
+}
+
+func (s *Store) SearchSymbolBundlesContext(ctx context.Context, query string, limit int) ([]graph.SymbolBundle, error) {
+	return s.SearchSymbolBundlesRepoScopedContext(ctx, query, nil, limit)
 }
 
-// SearchSymbolBundlesRepoScoped is SearchSymbolBundles over the
-// repo-scoped hit query — see SearchSymbolsRepoScoped for why the
-// narrowing must happen inside the FTS query.
 func (s *Store) SearchSymbolBundlesRepoScoped(query string, repoAllow []string, limit int) ([]graph.SymbolBundle, error) {
-	hits, err := s.SearchSymbolsRepoScoped(query, repoAllow, limit)
+	return s.SearchSymbolBundlesRepoScopedContext(context.Background(), query, repoAllow, limit)
+}
+
+func (s *Store) SearchSymbolBundlesRepoScopedContext(ctx context.Context, query string, repoAllow []string, limit int) ([]graph.SymbolBundle, error) {
+	hits, err := s.SearchSymbolsRepoScopedContext(ctx, query, repoAllow, limit)
 	if err != nil {
 		return nil, err
 	}
-	return s.bundlesForHits(hits)
+	return s.bundlesForHitsContext(ctx, hits)
 }
 
-// bundlesForHits materialises ranked hits into SymbolBundles through
-// the content-addressed cache + batched node/edge fetches.
-func (s *Store) bundlesForHits(hits []graph.SymbolHit) ([]graph.SymbolBundle, error) {
+// bundlesForHitsContext materialises ranked hits through the content-addressed
+// cache and cancellable batched node/edge fetches.
+func (s *Store) bundlesForHitsContext(ctx context.Context, hits []graph.SymbolHit) ([]graph.SymbolBundle, error) {
+	if err := ctx.Err(); err != nil {
+		return nil, err
+	}
 	if len(hits) == 0 {
 		return nil, nil
 	}
@@ -877,9 +903,19 @@ func (s *Store) bundlesForHits(hits []graph.SymbolHit) ([]graph.SymbolBundle, er
 	var nodes map[string]*graph.Node
 	var out, in map[string][]*graph.Edge
 	if len(missIDs) > 0 {
-		nodes = s.GetNodesByIDs(missIDs)
-		out = s.GetOutEdgesByNodeIDs(missIDs)
-		in = s.GetInEdgesByNodeIDs(missIDs)
+		var err error
+		nodes, err = s.GetNodesByIDsContext(ctx, missIDs)
+		if err != nil {
+			return nil, err
+		}
+		out, err = s.bundleEdgesByNodeIDsContext(ctx, missIDs, "from_id")
+		if err != nil {
+			return nil, err
+		}
+		in, err = s.bundleEdgesByNodeIDsContext(ctx, missIDs, "to_id")
+		if err != nil {
+			return nil, err
+		}
 	}
 
 	bundles := make([]graph.SymbolBundle, 0, len(ids))
@@ -929,3 +965,52 @@ func isIdentifierQuery(q string) bool {
 	}
 	return true
 }
+
+// FindNodesByNameContext is the optional cancellable exact-name splice used by
+// request-local query engines; legacy graph.Reader remains unchanged.
+func (s *Store) FindNodesByNameContext(ctx context.Context, name string) []*graph.Node {
+	return s.queryNodesContext(ctx, s.stmtFindByName, name, s.viewGen)
+}
+
+// Bundle payloads need the full edge metadata (including similarity and promoted
+// resolve/semantic fields); bounded localization's light projection is not a
+// substitute. Keep the historical batch shape, adding only request lifetime.
+func (s *Store) bundleEdgesByNodeIDsContext(ctx context.Context, ids []string, col string) (map[string][]*graph.Edge, error) {
+	uniq := dedupeNonEmpty(ids)
+	out := make(map[string][]*graph.Edge, len(uniq))
+	for i := 0; i < len(uniq); i += lookupChunkSize {
+		if err := ctx.Err(); err != nil {
+			return nil, err
+		}
+		chunk := uniq[i:minInt(i+lookupChunkSize, len(uniq))]
+		q := `SELECT ` + lookupEdgeCols + ` FROM edges WHERE ` + col + ` IN (` + inPlaceholders(len(chunk)) + `) AND view_gen = ?`
+		rows, err := s.db.QueryContext(ctx, q, append(toAnyArgs(chunk), s.viewGen)...)
+		if err != nil {
+			return nil, err
+		}
+		for rows.Next() {
+			edge, err := s.scanEdgeCursor(rows)
+			if err != nil {
+				rows.Close()
+				return nil, err
+			}
+			if edge == nil {
+				continue
+			}
+			key := edge.From
+			if col == "to_id" {
+				key = edge.To
+			}
+			out[key] = append(out[key], edge)
+		}
+		err = rows.Err()
+		closeErr := rows.Close()
+		if err != nil {
+			return nil, err
+		}
+		if closeErr != nil {
+			return nil, closeErr
+		}
+	}
+	return out, nil
+}
diff --git a/internal/mcp/overlay_view.go b/internal/mcp/overlay_view.go
index 4554b8b..e54c6da 100644
--- a/internal/mcp/overlay_view.go
+++ b/internal/mcp/overlay_view.go
@@ -213,6 +213,12 @@ func (s *Server) engineFor(ctx context.Context) *query.Engine {
 	return s.engine
 }
 
+// requestSearchEngine binds cancellation at search execution, preserving
+// engineFor's zero-allocation identity contract for ordinary graph access.
+func (s *Server) requestSearchEngine(ctx context.Context) *query.Engine {
+	return s.engineFor(ctx).WithContext(ctx)
+}
+
 // overlayLayerCacheEntry is one (sessionID, content-hash sum) bucket
 // in s.overlayLayerCache. The hash is over (sorted) overlay files'
 // (path, content, deleted, base_sha) tuples; identical pushes from a
diff --git a/internal/mcp/search_cancellation_test.go b/internal/mcp/search_cancellation_test.go
new file mode 100644
index 0000000..cfc5e38
--- /dev/null
+++ b/internal/mcp/search_cancellation_test.go
@@ -0,0 +1,108 @@
+package mcp
+
+import (
+	"context"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+
+	mcplib "github.com/mark3labs/mcp-go/mcp"
+	"github.com/zzet/gortex/internal/graph"
+	"github.com/zzet/gortex/internal/graph/store_sqlite"
+	"github.com/zzet/gortex/internal/query"
+	"github.com/zzet/gortex/internal/search"
+)
+
+// A controlled wait at the store boundary lets this test isolate the real
+// middleware -> search handler -> Swappable context chain without private DB access.
+// The storage package separately tests actual exhausted SQLite pool waits.
+type deadlineSearchStore struct {
+	*store_sqlite.Store
+	entered chan struct{}
+	release chan struct{}
+}
+
+func (s *deadlineSearchStore) SearchSymbolBundlesRepoScoped(q string, allow []string, limit int) ([]graph.SymbolBundle, error) {
+	close(s.entered)
+	<-s.release
+	return s.Store.SearchSymbolBundlesRepoScoped(q, allow, limit)
+}
+
+func (s *deadlineSearchStore) SearchSymbolBundlesRepoScopedContext(ctx context.Context, q string, allow []string, limit int) ([]graph.SymbolBundle, error) {
+	close(s.entered)
+	select {
+	case <-ctx.Done():
+		return nil, ctx.Err()
+	case <-s.release:
+	}
+	return s.Store.SearchSymbolBundlesRepoScopedContext(ctx, q, allow, limit)
+}
+
+func (s *deadlineSearchStore) SearchSymbolBundles(q string, limit int) ([]graph.SymbolBundle, error) {
+	close(s.entered)
+	<-s.release
+	return s.Store.SearchSymbolBundles(q, limit)
+}
+
+func (s *deadlineSearchStore) SearchSymbolBundlesContext(ctx context.Context, q string, limit int) ([]graph.SymbolBundle, error) {
+	close(s.entered)
+	select {
+	case <-ctx.Done():
+		return nil, ctx.Err()
+	case <-s.release:
+	}
+	return s.Store.SearchSymbolBundlesContext(ctx, q, limit)
+}
+
+func TestSearchDeadlineReleasesMCPHandler(t *testing.T) {
+	srv, _ := setupTestServer(t)
+	store, err := store_sqlite.Open(filepath.Join(t.TempDir(), "search.sqlite"))
+	if err != nil {
+		t.Fatal(err)
+	}
+	defer store.Close()
+	n := &graph.Node{ID: "app/widget.go::WidgetExtensions", Name: "WidgetExtensions", Kind: graph.KindType, RepoPrefix: "app", FilePath: "app/widget.go"}
+	store.AddNode(n)
+	if err := store.UpsertSymbolFTS(n.ID, "widget extensions"); err != nil {
+		t.Fatal(err)
+	}
+	gated := &deadlineSearchStore{Store: store, entered: make(chan struct{}), release: make(chan struct{})}
+	defer close(gated.release)
+	srv.engine = query.NewEngine(store)
+	srv.engine.SetSearch(search.NewSwappable(search.NewSymbolSearcherBackend(gated)))
+	// Check the real scoped SQL separately before enabling the controlled wait.
+	if hits, err := store.SearchSymbolBundlesRepoScoped("widget extensions", []string{"app"}, 5); err != nil || len(hits) != 1 {
+		t.Fatalf("positive scoped SQL control: %v %v", hits, err)
+	}
+	srv.ToolCallTimeout = time.Second
+	finished := make(chan struct{})
+	srv.addTool(mcplib.NewTool("test_cancellable_sql_search"), func(ctx context.Context, req mcplib.CallToolRequest) (*mcplib.CallToolResult, error) {
+		defer close(finished)
+		return srv.handleSearchSymbols(ctx, req)
+	})
+	result := make(chan *mcplib.CallToolResult, 1)
+	go func() {
+		result <- callToolByName(t, srv, context.Background(), "test_cancellable_sql_search", map[string]any{"query": "WidgetExtensions"})
+	}()
+	select {
+	case <-gated.entered:
+	case res := <-result:
+		t.Fatalf("search returned before controlled store: %s", toolText(res))
+	case <-time.After(2 * time.Second):
+		t.Fatal("MCP handler did not reach scoped store")
+	}
+	select {
+	case res := <-result:
+		if !res.IsError || !strings.Contains(toolText(res), "deadline") {
+			t.Error("expired search returned a successful terminal result")
+		}
+	case <-time.After(2 * time.Second):
+		t.Fatal("deadline middleware did not release transport")
+	}
+	select {
+	case <-finished:
+	case <-time.After(300 * time.Millisecond):
+		t.Fatal("deadline returned while search worker kept running")
+	}
+}
diff --git a/internal/mcp/search_corpus.go b/internal/mcp/search_corpus.go
index dbd2ee1..05174b2 100644
--- a/internal/mcp/search_corpus.go
+++ b/internal/mcp/search_corpus.go
@@ -108,7 +108,7 @@ func (s *Server) mergeDocChannel(ctx context.Context, query string, nodes []*gra
 	}
 
 	start := time.Now()
-	wide := s.engineFor(ctx).SearchSymbolsScoped(query, docLimit, scope)
+	wide := s.requestSearchEngine(ctx).SearchSymbolsScoped(query, docLimit, scope)
 	if timings != nil {
 		timings.BM25ExpansionMS += time.Since(start).Milliseconds()
 	}
diff --git a/internal/mcp/smartctx_config.go b/internal/mcp/smartctx_config.go
index 809e13b..d123818 100644
--- a/internal/mcp/smartctx_config.go
+++ b/internal/mcp/smartctx_config.go
@@ -221,7 +221,7 @@ func addInPackSection(result map[string]any, key string, val any) {
 // (how sharply the top result beats the rest) into a high/medium/low verdict.
 // Returns nil when the search yields nothing.
 func (s *Server) inPackConfidence(ctx context.Context, task string) map[string]any {
-	eng := s.engineFor(ctx)
+	eng := s.requestSearchEngine(ctx)
 	if eng == nil || task == "" {
 		return nil
 	}
@@ -281,7 +281,7 @@ func (s *Server) lowConfidenceRetrievalNote(ctx context.Context, task string, sy
 	if strings.TrimSpace(task) == "" || len(syms) == 0 {
 		return nil
 	}
-	eng := s.engineFor(ctx)
+	eng := s.requestSearchEngine(ctx)
 	if eng == nil {
 		return nil
 	}
diff --git a/internal/mcp/tools_coding.go b/internal/mcp/tools_coding.go
index 803a9ae..22c1ca3 100644
--- a/internal/mcp/tools_coding.go
+++ b/internal/mcp/tools_coding.go
@@ -1776,7 +1776,7 @@ func (s *Server) handleSuggestPattern(ctx context.Context, req mcp.CallToolReque
 	var testPatterns []map[string]any
 	if prefix != "" {
 		// Search for test functions that match the example name.
-		testSearch := s.scopedNodeSlice(ctx, s.engineFor(ctx).SearchSymbols(node.Name, 20))
+		testSearch := s.scopedNodeSlice(ctx, s.requestSearchEngine(ctx).SearchSymbols(node.Name, 20))
 		for _, tn := range testSearch {
 			if !isTestFile(tn.FilePath) {
 				continue
@@ -2050,7 +2050,7 @@ func (s *Server) handleSmartContext(ctx context.Context, req mcp.CallToolRequest
 		if len(kw) < 3 {
 			continue
 		}
-		matches := s.scopedNodeSlice(ctx, s.engineFor(ctx).SearchSymbols(kw, 10))
+		matches := s.scopedNodeSlice(ctx, s.requestSearchEngine(ctx).SearchSymbols(kw, 10))
 		for _, m := range matches {
 			if m.Kind == graph.KindFile || m.Kind == graph.KindImport {
 				continue
diff --git a/internal/mcp/tools_core.go b/internal/mcp/tools_core.go
index 75c422f..0744cba 100644
--- a/internal/mcp/tools_core.go
+++ b/internal/mcp/tools_core.go
@@ -1762,6 +1762,7 @@ func (s *Server) handleSearchSymbols(ctx context.Context, req mcp.CallToolReques
 	limit := req.GetInt("limit", 20)
 	offset := decodeCursor(req.GetString("cursor", ""))
 
+	eng := s.requestSearchEngine(ctx)
 	sess := s.sessionFor(ctx)
 	sess.recordSearch(q)
 
@@ -1964,10 +1965,10 @@ func (s *Server) handleSearchSymbols(ctx context.Context, req mcp.CallToolReques
 	var nodes []*graph.Node
 	var primaryCount int
 	if len(expandedTerms) > 0 {
-		nodes, primaryCount = fetchAndMergeBM25Timed(s.engineFor(ctx), q, expandedTerms, fetchLimit, scope, timings)
+		nodes, primaryCount = fetchAndMergeBM25Timed(eng, q, expandedTerms, fetchLimit, scope, timings)
 	} else {
 		bm25Start := time.Now()
-		nodes = s.engineFor(ctx).SearchSymbolsScoped(q, fetchLimit, scope)
+		nodes = eng.SearchSymbolsScoped(q, fetchLimit, scope)
 		timings.BM25PrimaryMS += time.Since(bm25Start).Milliseconds()
 		primaryCount = len(nodes)
 	}
@@ -2092,9 +2093,9 @@ func (s *Server) handleSearchSymbols(ctx context.Context, req mcp.CallToolReques
 			prevDepth = deepLimit
 			var refetched []*graph.Node
 			if len(expandedTerms) > 0 {
-				refetched, _ = fetchAndMergeBM25Timed(s.engineFor(ctx), q, expandedTerms, deepLimit, scope, timings)
+				refetched, _ = fetchAndMergeBM25Timed(eng, q, expandedTerms, deepLimit, scope, timings)
 			} else {
-				refetched = s.engineFor(ctx).SearchSymbolsScoped(q, deepLimit, scope)
+				refetched = eng.SearchSymbolsScoped(q, deepLimit, scope)
 			}
 			kept := applyAllPostFilters(refetched)
 			if len(kept) > 0 {
@@ -2116,7 +2117,7 @@ func (s *Server) handleSearchSymbols(ctx context.Context, req mcp.CallToolReques
 	// clause degrades to a useful result set instead of an empty one.
 	filtersRelaxed := false
 	if len(nodes) == 0 && q != "" && (kindArg != "" || flavorArg != "" || fq.hasFieldFilters()) {
-		relaxed := filterNodes(s.engineFor(ctx).SearchSymbolsScoped(q, fetchLimit, scope), allowed)
+		relaxed := filterNodes(eng.SearchSymbolsScoped(q, fetchLimit, scope), allowed)
 		if len(relaxed) > 0 {
 			nodes = relaxed
 			filtersRelaxed = true
@@ -2135,7 +2136,7 @@ func (s *Server) handleSearchSymbols(ctx context.Context, req mcp.CallToolReques
 	decomposed := false
 	if len(nodes) == 0 && queryHasDecomposableSeparator(q) {
 		if leaves := decomposeQueryToLeaves(q); len(leaves) > 0 {
-			rescued, _ := fetchAndMergeBM25Timed(s.engineFor(ctx), "", leaves, fetchLimit, scope, timings)
+			rescued, _ := fetchAndMergeBM25Timed(eng, "", leaves, fetchLimit, scope, timings)
 			rescued = applyAllPostFilters(rescued)
 			if len(rescued) > 0 {
 				nodes = rescued
@@ -2238,7 +2239,7 @@ func (s *Server) handleSearchSymbols(ctx context.Context, req mcp.CallToolReques
 	// final rerank order; refining it and rebuilding nodes keeps the
 	// two aligned for the diversification pass below.
 	if !scope.SkipVectorChannel && s.searchConfig().CosineRerankEnabled() && len(rerankBreakdown) > 1 {
-		refined := s.engineFor(ctx).RefineByCosine(q, rerankBreakdown, 0)
+		refined := eng.RefineByCosine(q, rerankBreakdown, 0)
 		rerankBreakdown = refined
 		refinedNodes := make([]*graph.Node, 0, len(refined))
 		for _, c := range refined {
@@ -2360,7 +2361,7 @@ func (s *Server) handleSearchSymbols(ctx context.Context, req mcp.CallToolReques
 	if total == 0 && len(resolved.RepoAllow) > 0 {
 		wide := scope
 		wide.RepoAllow = nil
-		wideNodes, _ := fetchAndMergeBM25Timed(s.engineFor(ctx), q, expandedTerms, offset+limit, wide, timings)
+		wideNodes, _ := fetchAndMergeBM25Timed(eng, q, expandedTerms, offset+limit, wide, timings)
 		resp["scope_note"] = scopeZeroNote(resolved, len(wideNodes))
 	}
 	if fetchEscalated {
@@ -2431,7 +2432,7 @@ func (s *Server) handleSearchSymbols(ctx context.Context, req mcp.CallToolReques
 		if len(pageBreakdown) > limit {
 			pageBreakdown = pageBreakdown[:limit]
 		}
-		resp["rerank"] = encodeRerankBreakdown(pageBreakdown, s.engineFor(ctx).Rerank())
+		resp["rerank"] = encodeRerankBreakdown(pageBreakdown, eng.Rerank())
 	}
 
 	// Per-phase Debug log line — single zap.Debug call carrying every
diff --git a/internal/mcp/tools_enhancements.go b/internal/mcp/tools_enhancements.go
index dce2278..12cafd7 100644
--- a/internal/mcp/tools_enhancements.go
+++ b/internal/mcp/tools_enhancements.go
@@ -576,7 +576,7 @@ func (s *Server) handlePrefetchContext(ctx context.Context, req mcp.CallToolRequ
 
 	// 1. BM25 search on task description (weight 0.4)
 	if task != "" {
-		searchResults := s.scopedNodeSlice(ctx, s.engineFor(ctx).SearchSymbols(task, 30))
+		searchResults := s.scopedNodeSlice(ctx, s.requestSearchEngine(ctx).SearchSymbols(task, 30))
 		maxScore := 1.0
 		for i, n := range searchResults {
 			if n.Kind == graph.KindFile || n.Kind == graph.KindImport {
diff --git a/internal/mcp/tools_explore.go b/internal/mcp/tools_explore.go
index 2f98016..c358ca9 100644
--- a/internal/mcp/tools_explore.go
+++ b/internal/mcp/tools_explore.go
@@ -2742,7 +2742,7 @@ func (s *Server) handleExplore(ctx context.Context, req mcp.CallToolRequest) (*m
 	if errResult != nil {
 		return errResult, nil
 	}
-	eng := s.engineFor(ctx)
+	eng := s.requestSearchEngine(ctx)
 	if eng == nil {
 		return mcp.NewToolResultError("no indexed repository is available; run index_repository first"), nil
 	}
diff --git a/internal/mcp/tools_planning.go b/internal/mcp/tools_planning.go
index 4fe746d..70fbe88 100644
--- a/internal/mcp/tools_planning.go
+++ b/internal/mcp/tools_planning.go
@@ -71,7 +71,7 @@ func (s *Server) handlePlanTurn(ctx context.Context, req mcp.CallToolRequest) (*
 		if len(kw) < 3 {
 			continue
 		}
-		for _, m := range s.scopedNodeSlice(ctx, s.engineFor(ctx).SearchSymbols(kw, 10)) {
+		for _, m := range s.scopedNodeSlice(ctx, s.requestSearchEngine(ctx).SearchSymbols(kw, 10)) {
 			if m.Kind == graph.KindFile || m.Kind == graph.KindImport {
 				continue
 			}
diff --git a/internal/mcp/tools_query_project.go b/internal/mcp/tools_query_project.go
index f372691..4d017bf 100644
--- a/internal/mcp/tools_query_project.go
+++ b/internal/mcp/tools_query_project.go
@@ -64,7 +64,7 @@ func (s *Server) handleQueryProject(ctx context.Context, req mcp.CallToolRequest
 	// Search the base graph unscoped, then confine to the target's
 	// repos. Using s.engine (not engineFor) keeps this off the session
 	// overlay and clamp — query_project is an explicit cross-project read.
-	nodes := s.engine.SearchSymbolsScoped(q, limit*5, query.QueryOptions{})
+	nodes := s.engine.WithContext(ctx).SearchSymbolsScoped(q, limit*5, query.QueryOptions{})
 	nodes = filterNodes(nodes, allowed)
 	if len(nodes) > limit {
 		nodes = nodes[:limit]
diff --git a/internal/mcp/tools_winnow.go b/internal/mcp/tools_winnow.go
index fa19740..837460b 100644
--- a/internal/mcp/tools_winnow.go
+++ b/internal/mcp/tools_winnow.go
@@ -230,7 +230,7 @@ func parseWinnowConstraints(req mcp.CallToolRequest) (winnowConstraints, error)
 // caller's overlay view (when any) so winnow honours editor-buffer state
 // just like search_symbols.
 func (s *Server) winnowSymbols(ctx context.Context, c winnowConstraints, allowed map[string]bool) []winnowResult {
-	eng := s.engineFor(ctx)
+	eng := s.requestSearchEngine(ctx)
 	reader := s.readerFor(ctx)
 	var candidates []*graph.Node
 	textScores := make(map[string]float64)
diff --git a/internal/query/engine.go b/internal/query/engine.go
index 6f7723a..8f6c0f9 100644
--- a/internal/query/engine.go
+++ b/internal/query/engine.go
@@ -30,6 +30,7 @@ type SearchProvider func() search.Backend
 // to scope a tool call to the calling session's shadow view without
 // constructing a fresh Engine per request.
 type Engine struct {
+	requestCtx     context.Context
 	g              graph.Reader
 	searchProvider SearchProvider
 	rerank         *rerank.Pipeline
@@ -54,6 +55,23 @@ type Engine struct {
 	viewLayers []ViewLayerSource
 }
 
+// WithContext returns a request-local clone; it never mutates the shared engine.
+func (e *Engine) WithContext(ctx context.Context) *Engine {
+	if e == nil {
+		return nil
+	}
+	clone := *e
+	clone.requestCtx = ctx
+	return &clone
+}
+
+func (e *Engine) requestContext() context.Context {
+	if e.requestCtx != nil {
+		return e.requestCtx
+	}
+	return context.Background()
+}
+
 // overlayLayered is the view side of the reader swap: a reader that
 // carries a per-request overlay layer exposes it so the engine can
 // tell an overlaid read apart from a base read.
@@ -530,6 +548,9 @@ func (e *Engine) SearchSymbols(query string, limit int) []*graph.Node {
 // Fan-out callers merge multiple retrieval channels through this method and run
 // one final session-aware rerank over the combined slice.
 func (e *Engine) GatherSymbolCandidates(query string, limit int, opts QueryOptions, rctx *rerank.Context) []*rerank.Candidate {
+	if e.requestContext().Err() != nil {
+		return nil
+	}
 	if limit <= 0 {
 		limit = 20
 	}
@@ -558,6 +579,9 @@ func (e *Engine) GatherSymbolCandidates(query string, limit int, opts QueryOptio
 	if s := e.getSearch(); s != nil && e.backendHasCorpus(s) {
 		cands = e.gatherBackendCandidates(query, fetchLimit, opts, gatherCtx)
 	} else {
+		if e.requestContext().Err() != nil {
+			return nil
+		}
 		start := time.Now()
 		nodes := e.searchSubstring(query, fetchLimit)
 		if opts.SearchTimings != nil {
@@ -595,6 +619,9 @@ func (e *Engine) SearchSymbolsRanked(query string, limit int, opts QueryOptions,
 		limit = 20
 	}
 	cands := e.GatherSymbolCandidates(query, limit, opts, rctx)
+	if e.requestContext().Err() != nil {
+		return nil
+	}
 
 	if e.rerank != nil && !opts.SkipInnerRerank {
 		ctx := rctx
@@ -682,7 +709,13 @@ func (e *Engine) backendHasCorpus(s search.Backend) bool {
 		return true
 	}
 	has := false
-	if s.Count() > 0 {
+	if dc, ok := s.(search.ContextDocCounter); ok {
+		n, known := dc.DocCountContext(e.requestContext())
+		has = known && n > 0
+		if !known && e.requestContext().Err() == nil {
+			has = s.Count() > 0
+		}
+	} else if s.Count() > 0 {
 		has = true
 	} else if dc, ok := s.(search.DocCounter); ok {
 		if n, known := dc.DocCount(); known && n > 0 {
@@ -708,6 +741,16 @@ func repoAllowList(allow map[string]bool) []string {
 	return out
 }
 
+func (e *Engine) searchBackendContext(b search.Backend, query string, limit int) []search.SearchResult {
+	if e.requestContext().Err() != nil {
+		return nil
+	}
+	if cb, ok := b.(search.ContextSearcher); ok {
+		return cb.SearchContext(e.requestContext(), query, limit)
+	}
+	return b.Search(query, limit)
+}
+
 // gatherBackendCandidates fetches text + (optional) vector results,
 // dedups them across channels, and supplements with exact-name /
 // substring matches. Each candidate carries its
@@ -791,7 +834,14 @@ func (e *Engine) gatherBackendCandidates(query string, limit int, opts QueryOpti
 		scopedAnswered := false
 		if allow := repoAllowList(opts.RepoAllow); len(allow) > 0 {
 			if sb, ok := backend.(search.ScopedSymbolBundleSearcherBackend); ok {
-				bundles = sb.SearchSymbolBundlesScoped(query, allow, limit*2)
+				if cb, ok := backend.(search.ContextScopedSymbolBundleSearcherBackend); ok {
+					bundles = cb.SearchSymbolBundlesScopedContext(e.requestContext(), query, allow, limit*2)
+				} else {
+					bundles = sb.SearchSymbolBundlesScoped(query, allow, limit*2)
+				}
+				if e.requestContext().Err() != nil {
+					return nil
+				}
 				// nil = no scoped support (or error); anything non-nil —
 				// an empty slice included — is the scoped path's answer.
 				scopedAnswered = bundles != nil
@@ -801,7 +851,14 @@ func (e *Engine) gatherBackendCandidates(query string, limit int, opts QueryOpti
 		// the scoped path's real answer and must NOT trigger the
 		// unscoped flood fetch its emptiness proves useless.
 		if bundles == nil {
-			bundles = bsb.SearchSymbolBundles(query, limit*2)
+			if cb, ok := backend.(search.ContextSymbolBundleSearcherBackend); ok {
+				bundles = cb.SearchSymbolBundlesContext(e.requestContext(), query, limit*2)
+			} else {
+				bundles = bsb.SearchSymbolBundles(query, limit*2)
+			}
+			if e.requestContext().Err() != nil {
+				return nil
+			}
 		}
 		if timings != nil {
 			timings.BundleMS += time.Since(bundleStart).Milliseconds()
@@ -874,7 +931,13 @@ func (e *Engine) gatherBackendCandidates(query string, limit int, opts QueryOpti
 		// zero signal vs the BM25 channel — see classWeightTable in
 		// internal/search/rerank/query_kind.go.
 		if vectorOnlyOK && !skipVectorChannel {
-			vecIDs, stats := vectorOnlyBackend.VectorChannelOnly(query, limit*2)
+			var vecIDs []string
+			var stats search.ChannelTimings
+			if cb, ok := backend.(search.ContextVectorOnly); ok {
+				vecIDs, stats = cb.VectorChannelOnlyContext(e.requestContext(), query, limit*2)
+			} else {
+				vecIDs, stats = vectorOnlyBackend.VectorChannelOnly(query, limit*2)
+			}
 			vectorIDs = vecIDs
 			if timings != nil {
 				timings.EmbedMS += stats.EmbedMS
@@ -892,6 +955,9 @@ func (e *Engine) gatherBackendCandidates(query string, limit int, opts QueryOpti
 	// without double-counting against the post-call GetNodesByIDs /
 	// FindNodesByName / Fallback phases that this function
 	// instruments individually below.
+	if e.requestContext().Err() != nil {
+		return nil
+	}
 	if !bundleHandled {
 		type timedChan interface {
 			SearchChannelsTimed(query string, limit int) ([]search.SearchResult, []string, search.ChannelTimings)
@@ -904,12 +970,20 @@ func (e *Engine) gatherBackendCandidates(query string, limit int, opts QueryOpti
 			// rerank's classWeightTable proves it's not earning its
 			// keep for these query classes.
 			textStart := time.Now()
-			textResults = backend.Search(query, limit*2)
+			textResults = e.searchBackendContext(backend, query, limit*2)
 			if timings != nil {
 				timings.TextBackendMS += time.Since(textStart).Milliseconds()
 			}
 		default:
-			if tc, ok := backend.(timedChan); ok {
+			if tc, ok := backend.(search.ContextChannelSearcher); ok {
+				var stats search.ChannelTimings
+				textResults, vectorIDs, stats = tc.SearchChannelsTimedContext(e.requestContext(), query, limit*2)
+				if timings != nil {
+					timings.TextBackendMS += stats.TextMS
+					timings.EmbedMS += stats.EmbedMS
+					timings.VectorSearchMS += stats.VectorSearchMS
+				}
+			} else if tc, ok := backend.(timedChan); ok {
 				var stats search.ChannelTimings
 				textResults, vectorIDs, stats = tc.SearchChannelsTimed(query, limit*2)
 				if timings != nil {
@@ -925,7 +999,7 @@ func (e *Engine) gatherBackendCandidates(query string, limit int, opts QueryOpti
 				}
 			} else {
 				textStart := time.Now()
-				textResults = backend.Search(query, limit*2)
+				textResults = e.searchBackendContext(backend, query, limit*2)
 				if timings != nil {
 					timings.TextBackendMS += time.Since(textStart).Milliseconds()
 				}
@@ -933,6 +1007,10 @@ func (e *Engine) gatherBackendCandidates(query string, limit int, opts QueryOpti
 		}
 	}
 
+	if e.requestContext().Err() != nil {
+		return nil
+	}
+
 	// Composed view: everything above answered for the indexed corpus
 	// alone. Enumerate the stack's generations, compose the results, and
 	// hand one merged ranked list to the materialisation below — which is
@@ -943,10 +1021,14 @@ func (e *Engine) gatherBackendCandidates(query string, limit int, opts QueryOpti
 			query,
 			limit*2,
 			textResults,
-			viewBaseTextRefill(backend, query, repoAllowList(opts.RepoAllow)),
+			viewBaseTextRefillContext(e.requestContext(), backend, query, repoAllowList(opts.RepoAllow)),
 		)
 	}
 
+	if e.requestContext().Err() != nil {
+		return nil
+	}
+
 	// Collect every ID NOT covered by the bundle path (vector hits +
 	// fallback path's text hits) and materialise them with one
 	// batched fetch. Empty IDs are tolerated — the batch lookup
@@ -1033,7 +1115,18 @@ func (e *Engine) gatherBackendCandidates(query string, limit int, opts QueryOpti
 	// that would unconditionally return zero rows.
 	if !opts.SkipExactNameSplice {
 		findNameStart := time.Now()
-		for _, n := range e.g.FindNodesByName(query) {
+		var exact []*graph.Node
+		if reader, ok := e.g.(interface {
+			FindNodesByNameContext(context.Context, string) []*graph.Node
+		}); ok {
+			exact = reader.FindNodesByNameContext(e.requestContext(), query)
+		} else {
+			exact = e.g.FindNodesByName(query)
+		}
+		if e.requestContext().Err() != nil {
+			return nil
+		}
+		for _, n := range exact {
 			if n.Kind == graph.KindFile || n.Kind == graph.KindImport {
 				continue
 			}
diff --git a/internal/query/engine_context_test.go b/internal/query/engine_context_test.go
new file mode 100644
index 0000000..29e4f74
--- /dev/null
+++ b/internal/query/engine_context_test.go
@@ -0,0 +1,39 @@
+package query
+
+import (
+	"context"
+	"testing"
+
+	"github.com/zzet/gortex/internal/graph"
+)
+
+func TestEngineWithContextKeepsRequestsIndependent(t *testing.T) {
+	e := NewEngine(graph.New())
+	firstCtx, cancelFirst := context.WithCancel(context.Background())
+	defer cancelFirst()
+	secondCtx, cancelSecond := context.WithCancel(context.Background())
+	defer cancelSecond()
+	first, second := e.WithContext(firstCtx), e.WithContext(secondCtx)
+	if first == e || second == e || first == second {
+		t.Fatal("cancellable requests must have independent engines")
+	}
+	if first.requestContext() != firstCtx || second.requestContext() != secondCtx {
+		t.Fatal("caller context not preserved")
+	}
+	cancelFirst()
+	if first.requestContext().Err() != context.Canceled || second.requestContext().Err() != nil || e.requestContext().Err() != nil {
+		t.Fatal("request cancellation leaked to another engine")
+	}
+	// Explicit rebinding must clear a cancelled request context, even when the
+	// replacement cannot be cancelled. Optimising WithContext itself must not
+	// accidentally keep the previous request's cancellation.
+	reset := first.WithContext(context.Background())
+	if reset.requestContext().Err() != nil || first.requestContext().Err() != context.Canceled {
+		t.Fatal("rebinding retained or mutated previous cancellation")
+	}
+	type key struct{}
+	values := context.WithValue(context.Background(), key{}, "request")
+	if got := e.WithContext(values).requestContext().Value(key{}); got != "request" {
+		t.Fatal("non-cancellable context values lost")
+	}
+}
diff --git a/internal/query/view_candidates.go b/internal/query/view_candidates.go
index 8a89629..99b69ae 100644
--- a/internal/query/view_candidates.go
+++ b/internal/query/view_candidates.go
@@ -1,6 +1,7 @@
 package query
 
 import (
+	"context"
 	"sort"
 
 	"github.com/zzet/gortex/internal/graph"
@@ -84,7 +85,10 @@ func (e *Engine) viewTextCandidates(
 			exhausted[i+1] = true
 			continue
 		}
-		raw[i+1] = layer.Search.Search(query, fetch)
+		raw[i+1] = e.searchBackendContext(layer.Search, query, fetch)
+		if e.requestContext().Err() != nil {
+			return nil
+		}
 		exhausted[i+1] = len(raw[i+1]) < fetch
 	}
 
@@ -123,7 +127,10 @@ func (e *Engine) viewTextCandidates(
 			if i == 0 {
 				raw[i] = refillBase(nextFetch)
 			} else {
-				raw[i] = e.viewLayers[i-1].Search.Search(query, nextFetch)
+				raw[i] = e.searchBackendContext(e.viewLayers[i-1].Search, query, nextFetch)
+				if e.requestContext().Err() != nil {
+					return nil
+				}
 			}
 			if len(raw[i]) > previous {
 				grew = true
@@ -143,30 +150,56 @@ func (e *Engine) viewTextCandidates(
 	}
 }
 
-// viewBaseTextRefill repeats only the indexed corpus's text lane at a deeper
+// viewBaseTextRefillContext repeats only the indexed corpus's text lane at a deeper
 // width. Bundle search is preferred because it preserves repository narrowing
 // and never wakes the vector channel merely to refill masked BM25 candidates.
-func viewBaseTextRefill(backend search.Backend, query string, repoAllow []string) func(int) []search.SearchResult {
+func viewBaseTextRefillContext(ctx context.Context, backend search.Backend, query string, repoAllow []string) func(int) []search.SearchResult {
 	return func(limit int) []search.SearchResult {
+		if ctx.Err() != nil {
+			return nil
+		}
 		if backend == nil || limit <= 0 {
 			return nil
 		}
 		if len(repoAllow) > 0 {
-			if scoped, ok := backend.(search.ScopedSymbolBundleSearcherBackend); ok {
+			if scoped, ok := backend.(search.ContextScopedSymbolBundleSearcherBackend); ok {
+				bundles := scoped.SearchSymbolBundlesScopedContext(ctx, query, repoAllow, limit)
+				if ctx.Err() != nil {
+					return nil
+				}
+				if bundles != nil {
+					return viewBundleResults(bundles)
+				}
+			} else if scoped, ok := backend.(search.ScopedSymbolBundleSearcherBackend); ok {
 				if bundles := scoped.SearchSymbolBundlesScoped(query, repoAllow, limit); bundles != nil {
 					return viewBundleResults(bundles)
 				}
 			}
 		}
-		if bundled, ok := backend.(search.SymbolBundleSearcherBackend); ok {
+		if bundled, ok := backend.(search.ContextSymbolBundleSearcherBackend); ok {
+			bundles := bundled.SearchSymbolBundlesContext(ctx, query, limit)
+			if ctx.Err() != nil {
+				return nil
+			}
+			if bundles != nil {
+				return viewBundleResults(bundles)
+			}
+		} else if bundled, ok := backend.(search.SymbolBundleSearcherBackend); ok {
 			if bundles := bundled.SearchSymbolBundles(query, limit); bundles != nil {
 				return viewBundleResults(bundles)
 			}
 		}
+		if channels, ok := backend.(search.ContextChannelSearcher); ok {
+			text, _, _ := channels.SearchChannelsTimedContext(ctx, query, limit)
+			return text
+		}
 		if channels, ok := backend.(search.ChannelSearcher); ok {
 			text, _ := channels.SearchChannels(query, limit)
 			return text
 		}
+		if contextual, ok := backend.(search.ContextSearcher); ok {
+			return contextual.SearchContext(ctx, query, limit)
+		}
 		return backend.Search(query, limit)
 	}
 }
diff --git a/internal/query/view_refill_context_test.go b/internal/query/view_refill_context_test.go
new file mode 100644
index 0000000..a07abdb
--- /dev/null
+++ b/internal/query/view_refill_context_test.go
@@ -0,0 +1,73 @@
+package query
+
+import (
+	"context"
+	"testing"
+
+	"github.com/zzet/gortex/internal/search"
+)
+
+type refillChannelBackend struct{ fusedCalls, channelCalls int }
+
+func (*refillChannelBackend) Add(string, ...string) {}
+func (*refillChannelBackend) Remove(string)         {}
+func (*refillChannelBackend) Close()                {}
+func (*refillChannelBackend) Count() int            { return 1 }
+func (*refillChannelBackend) Search(string, int) []search.SearchResult {
+	return []search.SearchResult{{ID: "legacy-fused"}}
+}
+func (b *refillChannelBackend) SearchContext(context.Context, string, int) []search.SearchResult {
+	b.fusedCalls++
+	return []search.SearchResult{{ID: "fused-vector"}}
+}
+func (b *refillChannelBackend) SearchChannels(string, int) ([]search.SearchResult, []string) {
+	b.channelCalls++
+	return []search.SearchResult{{ID: "text"}}, []string{"vector"}
+}
+
+type refillContextChannelBackend struct {
+	*refillChannelBackend
+	ctx   context.Context
+	calls int
+}
+
+func (b *refillContextChannelBackend) SearchChannelsTimedContext(ctx context.Context, _ string, _ int) ([]search.SearchResult, []string, search.ChannelTimings) {
+	b.ctx = ctx
+	b.calls++
+	return []search.SearchResult{{ID: "context-text"}}, []string{"context-vector"}, search.ChannelTimings{TextMS: 7}
+}
+
+func TestViewBaseTextRefillContextPreservesTextChannel(t *testing.T) {
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+	for _, contextual := range []bool{false, true} {
+		name := "legacy channels"
+		if contextual {
+			name = "context channels"
+		}
+		t.Run(name, func(t *testing.T) {
+			base := &refillChannelBackend{}
+			var backend search.Backend = base
+			contextualBackend := &refillContextChannelBackend{refillChannelBackend: base}
+			want := "text"
+			if contextual {
+				backend = contextualBackend
+				want = "context-text"
+			}
+			got := viewBaseTextRefillContext(ctx, backend, "query", nil)(5)
+			if len(got) != 1 || got[0].ID != want {
+				t.Fatalf("refill = %v, want text channel %s", got, want)
+			}
+			if base.fusedCalls != 0 {
+				t.Fatalf("refill invoked fused search %d times", base.fusedCalls)
+			}
+			if contextual {
+				if contextualBackend.calls != 1 || contextualBackend.ctx != ctx || base.channelCalls != 0 {
+					t.Fatal("context channel priority or caller context lost")
+				}
+			} else if base.channelCalls != 1 {
+				t.Fatal("legacy channel was bypassed")
+			}
+		})
+	}
+}
diff --git a/internal/search/hybrid.go b/internal/search/hybrid.go
index ce71691..acd84e4 100644
--- a/internal/search/hybrid.go
+++ b/internal/search/hybrid.go
@@ -85,11 +85,15 @@ type ChannelTimings struct {
 // re-running text Search would double-pay the FTS cost. Returns
 // nil and a zero ChannelTimings when the vector index is empty.
 func (h *HybridBackend) VectorChannelOnly(query string, limit int) ([]string, ChannelTimings) {
+	return h.VectorChannelOnlyContext(context.Background(), query, limit)
+}
+
+func (h *HybridBackend) VectorChannelOnlyContext(parent context.Context, query string, limit int) ([]string, ChannelTimings) {
 	var stats ChannelTimings
 	if h == nil || h.vector == nil || h.vector.Count() == 0 {
 		return nil, stats
 	}
-	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+	ctx, cancel := context.WithTimeout(parent, 5*time.Second)
 	defer cancel()
 	embedStart := time.Now()
 	queryVec, err := h.embedder.Embed(ctx, query)
@@ -165,14 +169,29 @@ func (h *HybridBackend) SearchSymbolBundlesScoped(query string, repoAllow []stri
 }
 
 func (h *HybridBackend) searchChannels(query string, limit int) ([]SearchResult, []string, ChannelTimings) {
+	return h.SearchChannelsTimedContext(context.Background(), query, limit)
+}
+
+func (h *HybridBackend) SearchChannelsTimedContext(parent context.Context, query string, limit int) ([]SearchResult, []string, ChannelTimings) {
 	var stats ChannelTimings
 	tStart := time.Now()
-	textResults := h.text.Search(query, limit*2)
+	if parent.Err() != nil {
+		return nil, nil, stats
+	}
+	var textResults []SearchResult
+	if b, ok := h.text.(ContextSearcher); ok {
+		textResults = b.SearchContext(parent, query, limit*2)
+	} else {
+		textResults = h.text.Search(query, limit*2)
+	}
+	if parent.Err() != nil {
+		return nil, nil, stats
+	}
 	stats.TextMS = time.Since(tStart).Milliseconds()
 
 	var vecIDs []string
 	if h.vector.Count() > 0 {
-		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+		ctx, cancel := context.WithTimeout(parent, 5*time.Second)
 		defer cancel()
 		embedStart := time.Now()
 		queryVec, err := h.embedder.Embed(ctx, query)
@@ -341,3 +360,74 @@ func alphaFuse(textResults []SearchResult, vecIDs []string, alpha float64, k, li
 	}
 	return out
 }
+
+func (s *HybridBackend) SearchSymbolBundlesContext(ctx context.Context, query string, limit int) []SymbolBundle {
+	if ctx.Err() != nil || s == nil {
+		return nil
+	}
+
+	if b, ok := s.text.(ContextSymbolBundleSearcherBackend); ok {
+		return b.SearchSymbolBundlesContext(ctx, query, limit)
+	}
+	if b, ok := s.text.(SymbolBundleSearcherBackend); ok {
+		return b.SearchSymbolBundles(query, limit)
+	}
+	return nil
+}
+
+func (s *HybridBackend) SearchSymbolBundlesScopedContext(ctx context.Context, query string, allow []string, limit int) []SymbolBundle {
+	if ctx.Err() != nil || s == nil {
+		return nil
+	}
+
+	if b, ok := s.text.(ContextScopedSymbolBundleSearcherBackend); ok {
+		return b.SearchSymbolBundlesScopedContext(ctx, query, allow, limit)
+	}
+	if b, ok := s.text.(ScopedSymbolBundleSearcherBackend); ok {
+		return b.SearchSymbolBundlesScoped(query, allow, limit)
+	}
+	return nil
+}
+
+func (s *HybridBackend) SearchContext(ctx context.Context, query string, limit int) []SearchResult {
+	if s == nil || ctx.Err() != nil {
+		return nil
+	}
+	text, vec, _ := s.SearchChannelsTimedContext(ctx, query, limit)
+	if ctx.Err() != nil {
+		return nil
+	}
+	if len(vec) == 0 {
+		if len(text) > limit {
+			return text[:limit]
+		}
+		return text
+	}
+	return alphaFuse(text, vec, rerank.AlphaFor(query), s.k, limit)
+}
+
+func (s *HybridBackend) DocCountContext(ctx context.Context) (int, bool) {
+	if s == nil || ctx.Err() != nil {
+		return 0, false
+	}
+	var n int
+	var known bool
+	if b, ok := s.text.(ContextDocCounter); ok {
+		n, known = b.DocCountContext(ctx)
+	} else if b, ok := s.text.(DocCounter); ok {
+		n, known = b.DocCount()
+	} else if s.text != nil {
+		n = s.text.Count()
+		known = true
+	}
+	if ctx.Err() != nil {
+		return 0, false
+	}
+	if n > 0 {
+		return n, known
+	}
+	if s.vector != nil && s.vector.Count() > 0 {
+		return s.vector.Count(), true
+	}
+	return n, known
+}
diff --git a/internal/search/swappable.go b/internal/search/swappable.go
index 4882899..3dc9e4b 100644
--- a/internal/search/swappable.go
+++ b/internal/search/swappable.go
@@ -1,6 +1,7 @@
 package search
 
 import (
+	"context"
 	"sync"
 
 	"github.com/zzet/gortex/internal/embedding"
@@ -262,3 +263,102 @@ func (s *Swappable) SizeBytes() uint64 {
 	defer s.mu.RUnlock()
 	return BackendSize(s.inner)
 }
+
+func (s *Swappable) SearchSymbolBundlesContext(ctx context.Context, query string, limit int) []SymbolBundle {
+	if ctx.Err() != nil || s == nil {
+		return nil
+	}
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	if b, ok := s.inner.(ContextSymbolBundleSearcherBackend); ok {
+		return b.SearchSymbolBundlesContext(ctx, query, limit)
+	}
+	if b, ok := s.inner.(SymbolBundleSearcherBackend); ok {
+		return b.SearchSymbolBundles(query, limit)
+	}
+	return nil
+}
+
+func (s *Swappable) SearchSymbolBundlesScopedContext(ctx context.Context, query string, allow []string, limit int) []SymbolBundle {
+	if ctx.Err() != nil || s == nil {
+		return nil
+	}
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	if b, ok := s.inner.(ContextScopedSymbolBundleSearcherBackend); ok {
+		return b.SearchSymbolBundlesScopedContext(ctx, query, allow, limit)
+	}
+	if b, ok := s.inner.(ScopedSymbolBundleSearcherBackend); ok {
+		return b.SearchSymbolBundlesScoped(query, allow, limit)
+	}
+	return nil
+}
+
+func (s *Swappable) SearchContext(ctx context.Context, query string, limit int) []SearchResult {
+	if ctx.Err() != nil || s == nil {
+		return nil
+	}
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	if s.inner == nil {
+		return nil
+	}
+	if b, ok := s.inner.(ContextSearcher); ok {
+		return b.SearchContext(ctx, query, limit)
+	}
+	return s.inner.Search(query, limit)
+}
+
+func (s *Swappable) DocCountContext(ctx context.Context) (int, bool) {
+	if ctx.Err() != nil || s == nil {
+		return 0, false
+	}
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	if s.inner == nil {
+		return 0, false
+	}
+	if b, ok := s.inner.(ContextDocCounter); ok {
+		return b.DocCountContext(ctx)
+	}
+	if b, ok := s.inner.(DocCounter); ok {
+		return b.DocCount()
+	}
+	return s.inner.Count(), true
+}
+
+func (s *Swappable) SearchChannelsTimedContext(ctx context.Context, query string, limit int) ([]SearchResult, []string, ChannelTimings) {
+	if ctx.Err() != nil {
+		return nil, nil, ChannelTimings{}
+	}
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	if b, ok := s.inner.(ContextChannelSearcher); ok {
+		return b.SearchChannelsTimedContext(ctx, query, limit)
+	}
+	if b, ok := s.inner.(ChannelSearcher); ok {
+		t, v := b.SearchChannels(query, limit)
+		return t, v, ChannelTimings{}
+	}
+	if b, ok := s.inner.(ContextSearcher); ok {
+		return b.SearchContext(ctx, query, limit), nil, ChannelTimings{}
+	}
+	return s.inner.Search(query, limit), nil, ChannelTimings{}
+}
+
+func (s *Swappable) VectorChannelOnlyContext(ctx context.Context, query string, limit int) ([]string, ChannelTimings) {
+	if ctx.Err() != nil {
+		return nil, ChannelTimings{}
+	}
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	if b, ok := s.inner.(ContextVectorOnly); ok {
+		return b.VectorChannelOnlyContext(ctx, query, limit)
+	}
+	if b, ok := s.inner.(interface {
+		VectorChannelOnly(string, int) ([]string, ChannelTimings)
+	}); ok {
+		return b.VectorChannelOnly(query, limit)
+	}
+	return nil, ChannelTimings{}
+}
diff --git a/internal/search/swappable_context_channels_test.go b/internal/search/swappable_context_channels_test.go
new file mode 100644
index 0000000..21b5264
--- /dev/null
+++ b/internal/search/swappable_context_channels_test.go
@@ -0,0 +1,71 @@
+package search
+
+import (
+	"context"
+	"testing"
+)
+
+type splitChannelBackend struct{ fusedCalls, channelCalls int }
+
+func (*splitChannelBackend) Add(string, ...string) {}
+func (*splitChannelBackend) Remove(string)         {}
+func (*splitChannelBackend) Close()                {}
+func (*splitChannelBackend) Count() int            { return 1 }
+func (*splitChannelBackend) Search(string, int) []SearchResult {
+	return []SearchResult{{ID: "legacy-fused"}}
+}
+func (b *splitChannelBackend) SearchContext(context.Context, string, int) []SearchResult {
+	b.fusedCalls++
+	return []SearchResult{{ID: "fused"}}
+}
+func (b *splitChannelBackend) SearchChannels(string, int) ([]SearchResult, []string) {
+	b.channelCalls++
+	return []SearchResult{{ID: "text"}}, []string{"vector"}
+}
+
+type contextSplitChannelBackend struct {
+	*splitChannelBackend
+	ctx   context.Context
+	calls int
+}
+
+func (b *contextSplitChannelBackend) SearchChannelsTimedContext(ctx context.Context, _ string, _ int) ([]SearchResult, []string, ChannelTimings) {
+	b.ctx = ctx
+	b.calls++
+	return []SearchResult{{ID: "context-text"}}, []string{"context-vector"}, ChannelTimings{TextMS: 7}
+}
+
+func TestSwappableContextPreservesSeparateChannels(t *testing.T) {
+	ctx, cancel := context.WithCancel(context.Background())
+	defer cancel()
+	for _, contextual := range []bool{false, true} {
+		name := "legacy channels"
+		if contextual {
+			name = "context channels"
+		}
+		t.Run(name, func(t *testing.T) {
+			base := &splitChannelBackend{}
+			var backend Backend = base
+			contextualBackend := &contextSplitChannelBackend{splitChannelBackend: base}
+			wantText, wantVector := "text", "vector"
+			if contextual {
+				backend = contextualBackend
+				wantText, wantVector = "context-text", "context-vector"
+			}
+			text, vector, timings := NewSwappable(backend).SearchChannelsTimedContext(ctx, "query", 5)
+			if len(text) != 1 || text[0].ID != wantText || len(vector) != 1 || vector[0] != wantVector {
+				t.Fatalf("channels = %v %v, want %s %s", text, vector, wantText, wantVector)
+			}
+			if base.fusedCalls != 0 {
+				t.Fatalf("fused search invoked %d times", base.fusedCalls)
+			}
+			if contextual {
+				if contextualBackend.calls != 1 || contextualBackend.ctx != ctx || base.channelCalls != 0 || timings.TextMS != 7 {
+					t.Fatal("context channel priority/context/timing lost")
+				}
+			} else if base.channelCalls != 1 {
+				t.Fatal("legacy channel was bypassed")
+			}
+		})
+	}
+}
diff --git a/internal/search/symbolsearcher_backend.go b/internal/search/symbolsearcher_backend.go
index 51164a1..7cc23a3 100644
--- a/internal/search/symbolsearcher_backend.go
+++ b/internal/search/symbolsearcher_backend.go
@@ -1,6 +1,7 @@
 package search
 
 import (
+	"context"
 	"strings"
 
 	"github.com/zzet/gortex/internal/graph"
@@ -195,3 +196,97 @@ func (b *SymbolSearcherBackend) DocCount() (int, bool) {
 // graph.Store; closing it from the search adapter would race the
 // indexer's own lifecycle.
 func (b *SymbolSearcherBackend) Close() {}
+
+// ContextSymbolBundleSearcherBackend is the optional deadline-aware bundle path.
+type ContextSymbolBundleSearcherBackend interface {
+	SearchSymbolBundlesContext(context.Context, string, int) []SymbolBundle
+}
+
+type ContextScopedSymbolBundleSearcherBackend interface {
+	SearchSymbolBundlesScopedContext(context.Context, string, []string, int) []SymbolBundle
+}
+
+type ContextSearcher interface {
+	SearchContext(context.Context, string, int) []SearchResult
+}
+
+type ContextDocCounter interface {
+	DocCountContext(context.Context) (int, bool)
+}
+
+func (b *SymbolSearcherBackend) SearchSymbolBundlesContext(ctx context.Context, query string, limit int) []SymbolBundle {
+	if ctx.Err() != nil || b == nil || b.s == nil {
+		return nil
+	}
+	if bs, ok := b.s.(interface {
+		SearchSymbolBundlesContext(context.Context, string, int) ([]graph.SymbolBundle, error)
+	}); ok {
+		bundles, err := bs.SearchSymbolBundlesContext(ctx, query, limit)
+		if err != nil {
+			return nil
+		}
+		return bundles
+	}
+	return b.SearchSymbolBundles(query, limit)
+}
+
+func (b *SymbolSearcherBackend) SearchSymbolBundlesScopedContext(ctx context.Context, query string, allow []string, limit int) []SymbolBundle {
+	if ctx.Err() != nil || b == nil || b.s == nil {
+		return nil
+	}
+	if bs, ok := b.s.(interface {
+		SearchSymbolBundlesRepoScopedContext(context.Context, string, []string, int) ([]graph.SymbolBundle, error)
+	}); ok {
+		bundles, err := bs.SearchSymbolBundlesRepoScopedContext(ctx, query, allow, limit)
+		if err != nil {
+			return nil
+		}
+		if bundles == nil {
+			return []SymbolBundle{}
+		}
+		return bundles
+	}
+	return b.SearchSymbolBundlesScoped(query, allow, limit)
+}
+
+func (b *SymbolSearcherBackend) SearchContext(ctx context.Context, query string, limit int) []SearchResult {
+	if ctx.Err() != nil || b == nil || b.s == nil {
+		return nil
+	}
+	if cs, ok := b.s.(interface {
+		SearchSymbolsContext(context.Context, string, int) ([]graph.SymbolHit, error)
+	}); ok {
+		hits, err := cs.SearchSymbolsContext(ctx, query, limit)
+		if err != nil {
+			return nil
+		}
+		out := make([]SearchResult, len(hits))
+		for i, h := range hits {
+			out[i] = SearchResult{ID: h.NodeID, Score: h.Score}
+		}
+		return out
+	}
+	return b.Search(query, limit)
+}
+
+func (b *SymbolSearcherBackend) DocCountContext(ctx context.Context) (int, bool) {
+	if ctx.Err() != nil || b == nil || b.s == nil {
+		return 0, false
+	}
+	if cs, ok := b.s.(interface {
+		SymbolFTSCountContext(context.Context) (int, error)
+	}); ok {
+		n, err := cs.SymbolFTSCountContext(ctx)
+		return n, err == nil && n >= 0
+	}
+	return b.DocCount()
+}
+
+// ContextChannelSearcher keeps request lifetime through text and vector channels.
+type ContextChannelSearcher interface {
+	SearchChannelsTimedContext(context.Context, string, int) ([]SearchResult, []string, ChannelTimings)
+}
+
+type ContextVectorOnly interface {
+	VectorChannelOnlyContext(context.Context, string, int) ([]string, ChannelTimings)
+}

rolldav avatar Oct 18 '26 08:10 rolldav

Hey @rolldav!

Thanks for the detailed report and the self-contained reproduction, and for moving the patch here for an issue-first review.

This issue I faced during the implementation #806, and it is being fixed in #806 (fix/incremental-index-write-amplification), which already carries cancellation through symbol search. It takes the same approach as your patch:

  • Context-aware SQLite reads. SearchSymbolsContext, SearchSymbolsRepoScopedContext, SearchSymbolBundlesContext, SearchSymbolBundlesRepoScopedContext and FindNodesByNameContext use QueryContext, so a cancelled request stops waiting for a pool connection.
  • Context variants on the search wrappers. SymbolSearcherBackend, HybridBackend and Swappable get optional context-taking methods (internal/search/context_backend.go), and the existing APIs stay as they are.
  • A request-scoped engine. Overlay and routed requests get an engine clone bound to the request's context (WithRequestContext / WithComposedView). Base requests keep the shared engine and pass the context explicitly through SearchSymbolsRankedContext, which keeps the base-engine identity and allocation guard you ran into.

One difference from your patch: after each search step, handleSearchSymbols returns ctx.Err(), so a cancelled or timed-out search ends as an error rather than an empty result with total: 0.

While comparing the two, I found two gaps that #806 shares with your patch, and we'll fix them there before merge:

  1. The context-aware bundle path returns SQLite errors instead of calling panicOnFatal, and the backend turns any error into nil. A corrupt store or an I/O error then looks like "no bundle support" and falls back to a wider search. Fatal errors should keep failing loudly.
  2. Swappable.SearchChannelsTimedContext doesn't check for inner == nil, so a search still in flight after Close() can panic on its final s.inner.Search call.

I'll also run your TestSearchCancellationReleasesPoolWait and TestViewLayerSearchCancellationReleasesPoolWait against the #806 branch and keep them as regression tests, with you credited.

I'll leave this issue open until #806 merges and then close it with a link. If you see a case #806 misses (for example a read that still ignores the context), please add it here.

zzet avatar Oct 19 '26 12:10 zzet