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

model-identity.ts

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