Files
supabase/apps/docs/app/api/graphql/tests/searchDocs.test.ts
Ali WaseemandJeremias Menichelli 20e304a377 feat(kb): add search ingestion and edge function (#51843)
## Problem

We need embeddings for Kb to run a search endpoint in the Content API
and future KB search.

## Solution

This PR adds KB search backed by its own Supabase table, ingested from
the KB markdown export, and aligns the KB and docs search ingest setups.

<!--
## Preview links

If relevant, include links to changed pages for easy review access.

Copy the preview base URL from the Vercel bot comment on this PR. Use
the following table as an example template.

| Site | Live | Preview | Search for |
| -------------- |
-------------------------------------------------------------------------
|
------------------------------------------------------------------------------------------------------------
| ----------------------------- |
| WWW | [/blog/your-post](https://supabase.com/blog/your-post) |
[/blog/your-post](https://zone-www-dot-com-git-branch-name-supabase.vercel.app/blog/your-post)
| unique phrase from the change |
| Docs |
[/docs/guides/your-page](https://supabase.com/docs/guides/your-page) |
[/docs/guides/your-page](https://docs-git-branch-name-supabase.vercel.app/docs/guides/your-page)
| unique phrase from the change |
| Studio | [/dashboard](https://supabase.com/dashboard) |
[/dashboard](https://studio-git-branch-name-supabase.vercel.app/dashboard)
| unique phrase from the change |
| Design system | [/design-system](https://supabase.com/design-system) |
[/design-system](https://design-system-git-branch-name-supabase.vercel.app/design-system)
| unique phrase from the change |
| UI library | [/library](https://supabase.com/library) |
[/library](https://ui-library-git-branch-name-supabase.vercel.app/library)
| unique phrase from the change |
| Knowledge base |
[/kb/guides/your-page](https://supabase.com/kb/guides/your-page) |
[/kb/guides/your-page](https://kb-git-branch-name-supabase.vercel.app/kb/guides/your-page)
| unique phrase from the change |
-->

<!-- ## Additional context

Optionally add any other context or screenshots.

-->

## Test

1. Run the **KB Search Ingest** workflow, or locally run `pnpm --filter
kb search:ingest` with `SUPABASE_URL` and `SUPABASE_SERVICE_ROLE_KEY`
set in `apps/kb/.env.local`.
2. Query the endpoint and check that the results link to
`https://supabase.com/kb/troubleshooting/...`:
   ```
   curl '<kb-url>/kb/api/search?q=connect%20timeout&limit=5'
   ```

## Checklist

Check all before review:

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [x] If I wrote a new docs topic or edited an existing topic, I used
the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs
[style
guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)

---------

Co-authored-by: Jeremias Menichelli <jmenichelli@gmail.com>
2026-10-21 11:24:52 +02:00

245 lines
6.9 KiB
TypeScript

import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
import { Result } from '~/features/helpers.fn'
import { type OpenAIClientInterface } from '~/lib/openAi'
import { ApiError } from '../../utils'
import { POST } from '../route'
const contentEmbeddingMock = vi
.fn()
.mockImplementation(async () => Result.ok({ embedding: [0.1, 0.2, 0.3], tokenCount: 10 }))
const openAIMock: OpenAIClientInterface = {
createContentEmbedding: contentEmbeddingMock,
}
vi.mock(import('~/lib/openAi'), () => ({
openAI: () => openAIMock,
}))
const rpcSpy = vi.fn().mockImplementation((funcName, params) => {
if (funcName === 'search_content_hybrid') {
const limit = params?.max_result || 2
const mockResults = [
{
type: 'markdown',
page_title: 'Test Guide',
href: '/guides/test',
content: params?.include_full_content ? 'Test content' : null,
subsections: [
{ title: 'Introduction', content: 'Introduction content' },
{ title: 'Details', content: 'Details content' },
],
},
{
type: 'markdown',
page_title: 'Another Guide',
href: '/guides/another',
content: params?.include_full_content ? 'Another content' : null,
subsections: [{ title: 'Getting Started', content: 'Getting Started content' }],
},
{
type: 'reference',
page_title: 'Create a SSO provider',
href: 'https://supabase.com/docs/reference/api/v1-create-a-sso-provider',
content: params?.include_full_content ? 'Creates a new SSO provider for a project' : null,
metadata: {
title: 'Create a SSO provider',
subtitle: 'Management API Reference: Create a SSO provider',
},
},
]
return Promise.resolve({ data: mockResults.slice(0, limit), error: null })
}
return Promise.resolve({ data: [], error: null })
})
vi.mock('~/lib/supabase', () => ({
supabase: () => ({
rpc: rpcSpy,
}),
}))
describe('/api/graphql searchDocs', () => {
beforeAll(() => {
vi.spyOn(console, 'error').mockImplementation(() => {})
// KB search is a network call; return no KB results
vi.stubGlobal('fetch', () => Promise.resolve(Response.json([])))
})
afterAll(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
vi.doUnmock('~/lib/openAi')
vi.doUnmock('~/lib/supabase')
})
it('should return search results when given a valid query', async () => {
const searchQuery = `
query {
searchDocs(query: "authentication") {
nodes {
title
href
}
}
}
`
const request = new Request('http://localhost/api/graphql', {
method: 'POST',
body: JSON.stringify({ query: searchQuery }),
})
const response = await POST(request)
const json = await response.json()
expect(json.errors).toBeUndefined()
expect(json.data).toBeDefined()
expect(json.data.searchDocs).toBeDefined()
expect(json.data.searchDocs.nodes).toBeInstanceOf(Array)
expect(json.data.searchDocs.nodes).toHaveLength(3)
expect(json.data.searchDocs.nodes[0]).toMatchObject({
title: 'Test Guide',
href: '/guides/test',
})
})
it('should respect the limit parameter', async () => {
const searchQuery = `
query {
searchDocs(query: "database", limit: 1) {
nodes {
title
}
}
}
`
const request = new Request('http://localhost/api/graphql', {
method: 'POST',
body: JSON.stringify({ query: searchQuery }),
})
const response = await POST(request)
const json = await response.json()
expect(json.errors).toBeUndefined()
expect(json.data.searchDocs.nodes).toHaveLength(1)
expect(json.data.searchDocs.nodes[0].title).toBe('Test Guide')
expect(rpcSpy).toHaveBeenCalledWith(
'search_content_hybrid',
expect.objectContaining({
max_result: 1,
})
)
})
it('should include content field when requested', async () => {
const searchQuery = `
query {
searchDocs(query: "api") {
nodes {
title
content
}
}
}
`
const request = new Request('http://localhost/api/graphql', {
method: 'POST',
body: JSON.stringify({ query: searchQuery }),
})
const response = await POST(request)
const json = await response.json()
expect(json.errors).toBeUndefined()
expect(json.data.searchDocs.nodes[0].content).toBe('Test content')
expect(rpcSpy).toHaveBeenCalledWith(
'search_content_hybrid',
expect.objectContaining({
include_full_content: true,
})
)
})
it('should handle errors from embedding creation', async () => {
contentEmbeddingMock.mockImplementationOnce(() => {
return Result.error(new ApiError('Embedding generation failed'))
})
const searchQuery = `
query {
searchDocs(query: "failed query") {
nodes {
title
}
}
}
`
const request = new Request('http://localhost/api/graphql', {
method: 'POST',
body: JSON.stringify({ query: searchQuery }),
})
const response = await POST(request)
const json = await response.json()
expect(json.errors).toBeDefined()
expect(json.errors[0].message).toBe('Internal Server Error')
})
it('should require a query parameter', async () => {
const searchQuery = `
query {
searchDocs {
nodes {
title
}
}
}
`
const request = new Request('http://localhost/api/graphql', {
method: 'POST',
body: JSON.stringify({ query: searchQuery }),
})
const response = await POST(request)
const json = await response.json()
expect(json.errors).toBeDefined()
expect(json.errors[0].message).toContain('required')
})
it('should return Management API references with proper fields', async () => {
const searchQuery = `
query {
searchDocs(query: "SSO provider", limit: 3) {
nodes {
... on ManagementApiReference {
title
href
content
}
}
}
}
`
const request = new Request('http://localhost/api/graphql', {
method: 'POST',
body: JSON.stringify({ query: searchQuery }),
})
const response = await POST(request)
const json = await response.json()
expect(json.errors).toBeUndefined()
expect(json.data).toBeDefined()
expect(json.data.searchDocs).toBeDefined()
expect(json.data.searchDocs.nodes).toBeInstanceOf(Array)
expect(json.data.searchDocs.nodes).toHaveLength(3)
const managementApiNode = json.data.searchDocs.nodes[2]
expect(managementApiNode).toMatchObject({
title: 'Create a SSO provider',
href: 'https://supabase.com/docs/reference/api/v1-create-a-sso-provider',
content: 'Creates a new SSO provider for a project',
})
})
})