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

model-identity.ts

138 lines4.8 KB

1import { eq, sql } from 'drizzle-orm'
2​
3import type { Db } from '#/db/index.ts'
4import { changes, models } from '#/db/schema.ts'
5import { stableStringify } from '#/server/kv.ts'
6import type { UpstreamModelIdentity } from '#/server/providers/types.ts'
7​
8export interface UpstreamIdentityWrite {
9 id: string
10 identity: UpstreamModelIdentity | null
12​
13/** Whether a row's stored evidence already says what the provider states. */
14export function sameEvidence(
15 row: typeof models.$inferSelect | undefined,
16 identity: UpstreamModelIdentity | null,
17): boolean {
18 return (
19 (row?.upstreamProvider ?? null) === (identity?.providerNamespace ?? null) &&
20 (row?.upstreamRawId ?? null) === (identity?.rawId ?? null) &&
21 stableStringify(row?.upstreamSource ?? null) ===
22 stableStringify(identity?.source ?? null)
23 )
25​
26/** Write identity evidence in batches; reconcileSameAs owns the link. */
27export async function persistUpstreamIdentities(
28 db: Db,
29 identities: readonly UpstreamIdentityWrite[],
30): Promise<void> {
31 for (let i = 0; i < identities.length; i += 30) {
32 const statements = identities.slice(i, i + 30).map(({ id, identity }) =>
33 db
34 .update(models)
35 .set({
36 upstreamProvider: identity?.providerNamespace ?? null,
37 upstreamRawId: identity?.rawId ?? null,
38 upstreamSource: identity?.source ?? null,
39 })
40 .where(eq(models.id, id)),
41 )
42 const [first, ...rest] = statements
43 if (first) await db.batch([first, ...rest])
44 }
46​
47/**
48 * Resolve stored evidence into links, catalog-wide. The stated namespace is
49 * a provider id, or a name exactly one provider claims in
50 * `provider_model_namespaces`. Within that provider an exact id wins, then a documented alias, then the same two with
51 * dots read as hyphens (gateways write `claude-opus-4.5` for Anthropic's
52 * `claude-opus-4-5`). More than one match at the winning tier is ambiguous:
53 * no link. Evidence is never touched here, so a target that arrives later
54 * links without re-polling the reseller.
55 */
56export async function reconcileSameAs(db: Db, now: number): Promise<void> {
57 const diffs = await db.all<{
58 id: string
59 provider_id: string
60 before: string | null
61 after: string | null
62 }>(sql`
63 WITH sources AS (
64 SELECT id, upstream_raw_id AS raw_id,
65 coalesce(
66 (SELECT id FROM providers WHERE id = models.upstream_provider),
67 (SELECT CASE WHEN count(*) = 1 THEN max(provider_id) END
68 FROM provider_model_namespaces
69 WHERE namespace = models.upstream_provider)
70 ) AS provider_id
71 FROM models WHERE upstream_provider IS NOT NULL
72 ), candidates AS (
73 SELECT source.id AS source_id, target.id AS target_id,
74 CASE
75 WHEN target.raw_id = source.raw_id THEN 0
76 WHEN EXISTS (
77 SELECT 1 FROM json_each(target.aliases)
78 WHERE value = source.raw_id
79 ) THEN 1
80 ELSE 2
81 END AS tier
82 FROM sources source
83 JOIN models target ON target.provider_id = source.provider_id
84 AND target.id != source.id
85 WHERE target.raw_id IN (
86 source.raw_id, replace(source.raw_id, '.', '-')
87 ) OR EXISTS (
88 SELECT 1 FROM json_each(target.aliases) WHERE value IN (
89 source.raw_id, replace(source.raw_id, '.', '-')
90 )
91 )
92 ), resolved AS (
93 SELECT source_id,
94 CASE WHEN count(*) = 1 THEN max(target_id) END AS target_id
95 FROM (
96 SELECT *, min(tier) OVER (PARTITION BY source_id) AS best
97 FROM candidates
98 )
99 WHERE tier = best
100 GROUP BY source_id
101 )
102 SELECT models.id, models.provider_id,
103 models.same_as_model_id AS before, resolved.target_id AS after
104 FROM models LEFT JOIN resolved ON resolved.source_id = models.id
105 WHERE (models.upstream_provider IS NOT NULL
106 OR models.same_as_model_id IS NOT NULL)
107 AND models.same_as_model_id IS NOT resolved.target_id
108 `)
109​
110 // A link and its change row commit together: a failed chunk leaves its
111 // rows still differing, so the next run emits them. Ten rows keep the
112 // insert under D1's 100-bound-parameter limit.
113 for (let i = 0; i < diffs.length; i += 10) {
114 const chunk = diffs.slice(i, i + 10)
115 await db.batch([
116 db.insert(changes).values(
117 chunk.map((row) => ({
118 id: crypto.randomUUID(),
119 type: 'model.updated' as const,
120 providerId: row.provider_id,
121 subjectId: row.id,
122 summary: 'Upstream model link updated',
123 payload: {
124 before: { sameAsModelId: row.before },
125 after: { sameAsModelId: row.after },
126 },
127 createdAt: now,
128 })),
129 ),
130 ...chunk.map((row) =>
131 db
132 .update(models)
133 .set({ sameAsModelId: row.after })
134 .where(eq(models.id, row.id)),
135 ),
136 ])
137 }