Repository navigation
perf: reuse ranking relevance and verify documentation flows #18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| name: Deterministic documentation browser flows | ||
| on: | ||
| pull_request: | ||
| push: | ||
| branches: [main] | ||
| permissions: | ||
| contents: read | ||
| concurrency: | ||
| group: browser-${{ github.ref }} | ||
| cancel-in-progress: true | ||
| jobs: | ||
| browser: | ||
| runs-on: ubuntu-latest | ||
| timeout-minutes: 20 | ||
| steps: | ||
| - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 | ||
| with: | ||
| persist-credentials: false | ||
| - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 | ||
| with: | ||
| node-version: 24.8.0 | ||
| - run: npm ci | ||
| - run: npm ci --prefix tests/browser | ||
| - run: npx tsc --project tests/browser/tsconfig.json | ||
| - run: npm run docs:check | ||
| - run: npm run docs:build | ||
| - run: npx --no-install e2e-web install chromium --with-deps | ||
| working-directory: tests/browser | ||
| - run: npm test | ||
| working-directory: tests/browser | ||
| - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 | ||
| if: always() | ||
| with: | ||
| name: documentation-browser-evidence | ||
| path: tests/browser/.e2e/ | ||
| include-hidden-files: true | ||
| retention-days: 7 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,126 @@ | ||
| package rank | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "github.com/microck/moji/internal/provider" | ||
| "math" | ||
| "reflect" | ||
| "sort" | ||
| "strings" | ||
| "testing" | ||
| ) | ||
|
|
||
| // Frozen pre-optimization implementation, retained to compare full ordering, | ||
| // scores, and metadata rather than only the first result. | ||
| func baselineResults(results []provider.Result, query, wantedWeight string, weights Weights) []provider.Result { | ||
| normalizedQuery := strings.ToLower(NormalizeQuery(query)) | ||
| compactQuery := strings.ReplaceAll(normalizedQuery, " ", "") | ||
| ranked := make([]provider.Result, 0, len(results)) | ||
| for _, result := range results { | ||
| if compactQuery == "" || relevance(result, normalizedQuery, compactQuery) > 0 { | ||
| ranked = append(ranked, result) | ||
| } | ||
| } | ||
| familySizes := make(map[string]map[string]struct{}) | ||
| for i := range ranked { | ||
| tags := ParseFilename(ranked[i].Filename) | ||
| if ranked[i].Format == "" { | ||
| ranked[i].Format = tags.Format | ||
| } | ||
| if ranked[i].Weight == "" { | ||
| ranked[i].Weight = tags.Weight | ||
| } | ||
| if tags.Variable { | ||
| ranked[i].Variable = true | ||
| } | ||
| key := tags.Family + "\x00" + familyGroupOf(ranked[i]) | ||
| if familySizes[key] == nil { | ||
| familySizes[key] = make(map[string]struct{}) | ||
| } | ||
| if ranked[i].Weight != "" { | ||
| familySizes[key][ranked[i].Weight] = struct{}{} | ||
| } | ||
| } | ||
| for i := range ranked { | ||
| tags := ParseFilename(ranked[i].Filename) | ||
| formatRank := map[string]float64{"otf": 3, "ttf": 2, "dfont": 1.5, "pfb": 1, "woff2": 0.75, "woff": 0.5, "pfm": 0.1}[ranked[i].Format] | ||
| score := weights.Format * formatRank | ||
| score += weights.FamilySize * math.Log2(1+float64(len(familySizes[tags.Family+"\x00"+familyGroupOf(ranked[i])]))) | ||
| if ranked[i].Trusted { | ||
| score += weights.Trusted | ||
| } | ||
| if wantedWeight != "" && ranked[i].Weight == wantedWeight { | ||
| score += weights.WeightBonus * 3 | ||
| } | ||
| if ranked[i].Variable { | ||
| score += weights.VariableBonus | ||
| } | ||
| if ranked[i].SizeBytes > 0 && ranked[i].SizeBytes < 10_000 { | ||
| score -= weights.SizePenalty | ||
| } | ||
| ranked[i].Score = score | ||
| } | ||
| sort.Slice(ranked, func(i, j int) bool { | ||
| leftRelevance := relevance(ranked[i], normalizedQuery, compactQuery) | ||
| rightRelevance := relevance(ranked[j], normalizedQuery, compactQuery) | ||
| if leftRelevance != rightRelevance { | ||
| return leftRelevance > rightRelevance | ||
| } | ||
| if ranked[i].Score != ranked[j].Score { | ||
| return ranked[i].Score > ranked[j].Score | ||
| } | ||
| leftReliability := sourceReliability(ranked[i]) | ||
| rightReliability := sourceReliability(ranked[j]) | ||
| if leftReliability != rightReliability { | ||
| return leftReliability > rightReliability | ||
| } | ||
| if ranked[i].Filename != ranked[j].Filename { | ||
| return ranked[i].Filename < ranked[j].Filename | ||
| } | ||
| if ranked[i].Source != ranked[j].Source { | ||
| return ranked[i].Source < ranked[j].Source | ||
| } | ||
| return ranked[i].URL < ranked[j].URL | ||
| }) | ||
| return ranked | ||
| } | ||
|
|
||
| func rankingFixture() []provider.Result { | ||
| results := make([]provider.Result, 600) | ||
| families := []string{"Inter", "Inter var", "Example", "Font", "SourceSans", "AvenirNext", "ProximaNova", "HelveticaNeue"} | ||
| weights := []string{"Regular", "Bold", "Light", "SemiBoldItalic"} | ||
| for i := range results { | ||
| results[i] = provider.Result{Name: families[i%len(families)], Filename: fmt.Sprintf("%s-%s.ttf", families[i%len(families)], weights[(i/7)%len(weights)]), Source: fmt.Sprintf("source-%d", i%9), URL: fmt.Sprintf("https://example.test/font-%d.ttf", i), SizeBytes: int64(8000 + i*10), Trusted: i%3 == 0} | ||
| } | ||
| return results | ||
| } | ||
| func TestCachedRankingPreservesCompleteResults(t *testing.T) { | ||
| input := rankingFixture() | ||
| before := append([]provider.Result(nil), input...) | ||
| for _, query := range []string{"", "Inter", "Source Sans", "Avenir", "unmatched", "FONT", "Proxima Nova", "Helvetic"} { | ||
| for _, weight := range []string{"", "bold", "light"} { | ||
| got := Results(input, query, weight, DefaultWeights()) | ||
| want := baselineResults(input, query, weight, DefaultWeights()) | ||
| if !reflect.DeepEqual(got, want) { | ||
| t.Fatalf("ranking changed for %q/%q", query, weight) | ||
| } | ||
| } | ||
| } | ||
| if !reflect.DeepEqual(input, before) { | ||
| t.Fatal("ranking mutated caller results") | ||
| } | ||
| } | ||
| func BenchmarkRankingBaseline(b *testing.B) { | ||
| input := rankingFixture() | ||
| b.ReportAllocs() | ||
| for b.Loop() { | ||
| baselineResults(input, "Inter", "", DefaultWeights()) | ||
| } | ||
| } | ||
| func BenchmarkRankingCached(b *testing.B) { | ||
| input := rankingFixture() | ||
| b.ReportAllocs() | ||
| for b.Loop() { | ||
| Results(input, "Inter", "", DefaultWeights()) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import {readFileSync,readdirSync} from 'node:fs'; | ||
| import {join,relative,sep} from 'node:path'; | ||
| import {parse} from 'yaml'; | ||
| import {test} from '@e2e-dev/web'; | ||
| import {expect} from 'e2e'; | ||
| const root='../../docs/content/docs'; | ||
| function pages(directory=root):{route:string;title:string}[]{ | ||
| return readdirSync(directory,{withFileTypes:true}).flatMap(entry=>{ | ||
| const path=join(directory,entry.name); | ||
| if(entry.isDirectory())return pages(path); | ||
| if(!/\.mdx?$/.test(path))return []; | ||
| const front=readFileSync(path,'utf8').match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1]; | ||
| const data=front===undefined?null:parse(front); | ||
| if(typeof data?.title!=='string'||!data.title.trim())throw new Error(`Missing title: ${path}`); | ||
| return [{title:data.title,route:'/docs/'+relative(root,path).split(sep).join('/').replace(/\.mdx?$/,'').replace(/(^|\/)index$/,'')}]; | ||
| }); | ||
| } | ||
| for(const page of pages())test(`rendered documentation ${page.route}`,async({app,screen,browser})=>{ | ||
| await app.open(page.route); | ||
| await expect(screen.getByRole('heading',{name:page.title,exact:true})).toBeVisible(); | ||
| const markdown=await browser.evaluate(async path=>{const response=await fetch('/llms.mdx'+path+'/content.md');return {status:response.status,text:await response.text()};},page.route.replace(/\/$/,'')); | ||
| expect(markdown.status).toBe(200); | ||
| expect(markdown.text.length).toBeGreaterThan(20); | ||
| expect(markdown.text.startsWith(`# ${page.title} (${page.route.replace(/\/$/,'')})\n`)).toBe(true); | ||
| }); | ||
| test('mobile docs navigation and readable content',async({app,browser,screen})=>{ | ||
| await browser.setViewport({width:390,height:844}); | ||
| await app.open('/docs'); | ||
| await expect(screen.getByRole('heading',{name:pages().find(p=>p.route==='/docs/')!.title,exact:true})).toBeVisible(); | ||
| expect(await browser.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1)).toBe(true); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| import type {E2EConfig} from 'e2e'; | ||
| import {web} from '@e2e-dev/web'; | ||
| export default {tests:'*.e2e.ts',workers:1,retries:0,trace:'on',timeout:30000,targets:[{name:'chromium',engine:web(),app:{url:'http://127.0.0.1:4192',command:{executable:'node',args:['serve.mjs'],log:'.e2e/server.log'}}}]} satisfies E2EConfig; |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.