Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

first-party.ts

142 lines4.9 KB

1/**
2 * `firstParty` (issue #719): is this provider the maker of this model?
3 * Derived at read time from the provider's maker declaration
4 * (`providers.makes_own_models`), the row's links, its `maker` and the
5 * namespace table. Never stored per row.
6 */
7import { isNotNull, sql } from 'drizzle-orm'
8​
9import type { Db } from '#/db/index.ts'
10import { models, providerModelNamespaces, providers } from '#/db/schema.ts'
11import type { FactSource, FirstPartySource } from '#/server/providers/types.ts'
12​
13export interface ProviderMaker {
14 declared: boolean
15 /** The provider id and its claimed namespaces, lowercased letters and digits. */
16 names: Set<string>
17 /** Some row here names a maker that is not this provider. */
18 hostsOthers: boolean
20​
21export type MakerContext = Map<string, ProviderMaker>
22​
23const squash = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, '')
24​
25/**
26 * Whether a maker name, as a host writes it, names the provider itself:
27 * the whole name or its first word is the provider id or a namespace it
28 * claims (`Google DeepMind` → `google` → gemini; `ByteDance` → bytedance).
29 */
30export function makerNamesProvider(
31 maker: string,
32 names: ReadonlySet<string>,
33): boolean {
34 const first = maker.trim().split(/[^A-Za-z0-9]+/)[0] ?? ''
35 return names.has(squash(maker)) || names.has(squash(first))
37​
38/** One read per request: the declarations, namespaces and stated makers. */
39export async function loadMakerContext(db: Db): Promise<MakerContext> {
40 const [declared, namespaces, makers] = await Promise.all([
41 db
42 .select({ id: providers.id, declared: providers.makesOwnModels })
43 .from(providers),
44 db.select().from(providerModelNamespaces),
45 db
46 .selectDistinct({ providerId: models.providerId, maker: models.maker })
47 .from(models)
48 .where(isNotNull(models.maker)),
49 ])
50 const context: MakerContext = new Map(
51 declared.map((row) => [
52 row.id,
53 {
54 declared: row.declared,
55 names: new Set([squash(row.id)]),
56 hostsOthers: false,
57 },
58 ]),
59 )
60 for (const row of namespaces) {
61 context.get(row.providerId)?.names.add(squash(row.namespace))
62 }
63 for (const row of makers) {
64 const provider = context.get(row.providerId)
65 if (provider && row.maker && !makerNamesProvider(row.maker, provider.names))
66 provider.hostsOthers = true
67 }
68 return context
70​
71/** `(rows whose sameAs chain ends at this row)`, for a catalog select. */
72export const linkedFromCount = sql<number>`(
73 (SELECT count(*) FROM models AS linked WHERE linked.root_model_id = ${models.id})
74 + (SELECT count(*) FROM models AS linked
75 WHERE linked.same_as_model_id = ${models.id}
76 AND linked.root_model_id IS NULL)
77)`
78​
79export interface FirstPartyInput {
80 providerId: string
81 maker: string | null
82 makerSource: FactSource | undefined
83 /** The served sameAs target's provider; null when none is served. */
84 sameAsProvider: string | null
85 linkedFrom: number
87​
88/**
89 * Whether a row is the declared maker's own model: its provider is
90 * declared, its `maker` (if any) names the provider itself, and, on a
91 * maker that also hosts other makers' models, its maker source was read
92 * for this row. The one predicate for `firstParty` and for the name tier's
93 * candidate roots (`inferLinks`).
94 */
95export function isOwnRow(
96 provider: ProviderMaker | undefined,
97 maker: string | null,
98 makerSource: FactSource | undefined,
99): boolean {
100 if (!provider?.declared) return false
101 if (maker !== null && !makerNamesProvider(maker, provider.names)) return false
102 return !provider.hostsOthers || makerSource !== undefined
104​
105/**
106 * Evidence first: a served link to another provider's row, or a `maker`
107 * naming someone else, is `false`. Then only the declared maker's own row
108 * (`isOwnRow`) can be `true`: from other rows' links ending here, from its
109 * maker source on a maker that hosts others, or from the declaration.
110 * Otherwise null: a host's row that others link to is not the maker's.
111 */
112export function firstParty(
113 input: FirstPartyInput,
114 context: MakerContext,
115): { value: boolean | null; source?: FirstPartySource } {
116 const provider = context.get(input.providerId)
117 if (
118 input.sameAsProvider !== null &&
119 input.sameAsProvider !== input.providerId
120 )
121 return { value: false, source: { decidedBy: 'same-as' } }
122 if (
123 input.maker !== null &&
124 provider &&
125 input.makerSource &&
126 !makerNamesProvider(input.maker, provider.names)
127 )
128 return {
129 value: false,
130 source: { decidedBy: 'maker', source: input.makerSource },
131 }
132 if (!provider || !isOwnRow(provider, input.maker, input.makerSource))
133 return { value: null }
134 if (input.linkedFrom > 0)
135 return {
136 value: true,
137 source: { decidedBy: 'linked-from', count: input.linkedFrom },
138 }
139 return provider.hostsOthers && input.makerSource
140 ? { value: true, source: { decidedBy: 'maker', source: input.makerSource } }
141 : { value: true, source: { decidedBy: 'provider-declared' } }