Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | /** |
| 2 | * Property tests for `dereferenceJsonSchema`. |
| 3 | * |
| 4 | * The example-based suite in `jsonSchema.test.ts` pins specific shapes. These |
| 5 | * tests pin *invariants* over a generated space of schemas, which is where the |
| 6 | * gaps were: sentinel-mode cycles, external refs surviving, `$ref`-shaped data |
| 7 | * sitting inside instance-value keywords, idempotence, and — the failure that |
| 8 | * originally motivated the helper — output that cannot be serialized. |
| 9 | * |
| 10 | * The generator is a small seeded PRNG rather than a property-testing library. |
| 11 | * Neither SDK has one today, and the Python counterpart |
| 12 | * (`python/tests/test_json_schema_properties.py`) mirrors this file's generator |
| 13 | * and invariants exactly; a library in one ecosystem and not the other would |
| 14 | * break that symmetry. Swapping in fast-check/hypothesis later is mechanical — |
| 15 | * the invariants below are the durable part. |
| 16 | * |
| 17 | * Failures are reproducible: every case prints its seed. |
| 18 | * |
| 19 | * Regenerated 2026-08-28 from the Python counterpart after the original was |
| 20 | * lost in a session handoff. |
| 21 | */ |
| 22 | import { describe, it, expect } from 'vitest'; |
| 23 | import { dereferenceJsonSchema } from '../../src/utils/jsonSchema'; |
| 24 | import { JsonSchemaRefResolutionError } from '../../src/errors'; |
| 25 | |
| 26 | /** Deterministic PRNG so a failing case can be replayed from its seed. */ |
| 27 | function mulberry32(seed: number): () => number { |
| 28 | let a = seed >>> 0; |
| 29 | return () => { |
| 30 | a = (a + 0x6d2b79f5) >>> 0; |
| 31 | let t = Math.imul(a ^ (a >>> 15), 1 | a); |
| 32 | t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; |
| 33 | return ((t ^ (t >>> 14)) >>> 0) / 4294967296; |
| 34 | }; |
| 35 | } |
| 36 | |
| 37 | type Json = Record<string, unknown>; |
| 38 | |
| 39 | /** Keywords whose values are instance data — a `$ref` there is not a reference. */ |
| 40 | const INSTANCE_VALUE_KEYWORDS = new Set(['const', 'default', 'enum', 'examples']); |
| 41 | |
| 42 | const CASES = 300; |
| 43 | const SEEDS = Array.from({ length: CASES }, (_, i) => 0x5eed + i * 7919); |
| 44 | |
| 45 | interface GeneratedDoc { |
| 46 | schema: Json; |
| 47 | /** True when the document contains at least one ref that cannot resolve. */ |
| 48 | hasUnresolvable: boolean; |
| 49 | } |
| 50 | |
| 51 | const pick = <T>(rng: () => number, items: readonly T[]): T => |
| 52 | items[Math.floor(rng() * items.length)]; |
| 53 | |
| 54 | /** |
| 55 | * Build a schema exercising every branch the dereferencer has: resolvable refs, |
| 56 | * chains, self-recursion, dangling pointers, external refs, legacy |
| 57 | * `definitions`, Draft 2020-12 siblings next to `$ref`, and `$ref`-shaped data |
| 58 | * parked inside instance-value keywords. |
| 59 | */ |
| 60 | function generateDoc(rng: () => number, withInstanceValueRefs = false): GeneratedDoc { |
| 61 | const chance = (p: number) => rng() < p; |
| 62 | |
| 63 | // Definition names include JSON-Pointer escapes (`~0`/`~1`) and prototype |
| 64 | // keys; the clone step filters the latter (prototype pollution), so refs to |
| 65 | // them degrade to sentinels — a documented divergence from Python, which has |
| 66 | // no prototype to pollute. |
| 67 | const defNames = ['Alpha', 'Beta', 'Gamma', 'a/b', 'c~d', '__proto__', 'constructor'].slice( |
| 68 | 0, |
| 69 | 1 + Math.floor(rng() * 7) |
| 70 | ); |
| 71 | |
| 72 | const escapePointer = (name: string) => name.replace(/~/g, '~0').replace(/\//g, '~1'); |
| 73 | |
| 74 | const defsKey = chance(0.25) ? 'definitions' : '$defs'; |
| 75 | |
| 76 | const state = { hasUnresolvable: false }; |
| 77 | |
| 78 | // Mirrors `POLLUTING_KEYS` in `jsonSchema.ts`. A definition under one of |
| 79 | // these names is never an own `$defs` entry (assigning `__proto__` sets the |
| 80 | // prototype; the clone step drops the rest), so any pointer to it is |
| 81 | // unresolvable exactly like a dangling one and must set the flag too — |
| 82 | // otherwise the throw-mode ratchet below could stay red for a reason |
| 83 | // unrelated to the instance-value bug it documents. |
| 84 | const POLLUTING_DEF_NAMES = new Set(['__proto__', 'constructor', 'prototype']); |
| 85 | const pointerTo = (name: string) => { |
| 86 | if (POLLUTING_DEF_NAMES.has(name)) state.hasUnresolvable = true; |
| 87 | return `#/${defsKey}/${escapePointer(name)}`; |
| 88 | }; |
| 89 | |
| 90 | const leaf = (): Json => { |
| 91 | const node: Json = { type: pick(rng, ['string', 'number', 'integer', 'boolean']) }; |
| 92 | // `$ref`-shaped *data*. Only injected for the dedicated test block, so the |
| 93 | // other properties stay independent of the instance-value bug this module |
| 94 | // documents. |
| 95 | if (withInstanceValueRefs) { |
| 96 | if (chance(0.4)) node.default = { $ref: '#/$defs/NotARealReference' }; |
| 97 | if (chance(0.4)) node.enum = [{ $ref: '#/$defs/AlsoNotOne' }]; |
| 98 | } |
| 99 | return node; |
| 100 | }; |
| 101 | |
| 102 | const refNode = (): Json => { |
| 103 | const kind = pick(rng, [ |
| 104 | 'resolvable', |
| 105 | 'resolvable', |
| 106 | 'resolvable', |
| 107 | 'dangling', |
| 108 | 'external', |
| 109 | 'whole-document', |
| 110 | 'deep', |
| 111 | ]); |
| 112 | let node: Json; |
| 113 | if (kind === 'whole-document') { |
| 114 | // `#` resolves to the root, always an ancestor, so this must come back |
| 115 | // as a cycle sentinel rather than diverging. |
| 116 | node = { $ref: '#' }; |
| 117 | } else if (kind === 'deep') { |
| 118 | // Pointers are generic JSON Pointers, not `$defs`-only. |
| 119 | node = { $ref: `#/${defsKey}/${escapePointer(defNames[0])}/properties/value` }; |
| 120 | } else if (kind === 'external') { |
| 121 | node = { |
| 122 | $ref: pick(rng, ['https://example.com/s.json', 'file:///tmp/s.json', 'other.json#/A']), |
| 123 | }; |
| 124 | } else if (kind === 'dangling') { |
| 125 | state.hasUnresolvable = true; |
| 126 | node = { $ref: pointerTo('MissingDefinition') }; |
| 127 | } else { |
| 128 | node = { $ref: pointerTo(pick(rng, defNames)) }; |
| 129 | } |
| 130 | if (chance(0.3)) node.description = 'sibling description'; |
| 131 | return node; |
| 132 | }; |
| 133 | |
| 134 | const subschema = (depth: number): Json => { |
| 135 | if (depth <= 0) return leaf(); |
| 136 | const kind = pick(rng, ['object', 'array', 'ref', 'combinator', 'leaf']); |
| 137 | if (kind === 'object') { |
| 138 | const properties: Record<string, Json> = {}; |
| 139 | const count = 1 + Math.floor(rng() * 3); |
| 140 | for (let i = 0; i < count; i++) properties[`p${i}`] = subschema(depth - 1); |
| 141 | const node: Json = { type: 'object', properties }; |
| 142 | // A `$defs` block below the root is not stripped — only the root. |
| 143 | if (chance(0.2)) node.$defs = { Local: { type: 'string' } }; |
| 144 | if (chance(0.4)) node.required = Object.keys(properties).slice(0, 1); |
| 145 | if (chance(0.3)) node.additionalProperties = subschema(depth - 1); |
| 146 | return node; |
| 147 | } |
| 148 | if (kind === 'array') return { type: 'array', items: subschema(depth - 1) }; |
| 149 | if (kind === 'ref') return refNode(); |
| 150 | if (kind === 'combinator') { |
| 151 | return { [pick(rng, ['anyOf', 'oneOf', 'allOf'])]: [subschema(depth - 1), leaf()] }; |
| 152 | } |
| 153 | return leaf(); |
| 154 | }; |
| 155 | |
| 156 | const defs: Record<string, Json> = {}; |
| 157 | for (const name of defNames) { |
| 158 | const body: Json = { type: 'object', properties: { value: leaf() } }; |
| 159 | // Self-recursion and cross-definition chains: neither has a finite inlined |
| 160 | // form, so the dereferencer must break them rather than diverge. |
| 161 | if (chance(0.35)) body.properties = { ...body.properties, self: { $ref: pointerTo(name) } }; |
| 162 | if (chance(0.3)) { |
| 163 | body.properties = { ...body.properties, other: { $ref: pointerTo(pick(rng, defNames)) } }; |
| 164 | } |
| 165 | defs[name] = body; |
| 166 | } |
| 167 | |
| 168 | const rootProperties: Record<string, Json> = {}; |
| 169 | const rootCount = 1 + Math.floor(rng() * 4); |
| 170 | for (let i = 0; i < rootCount; i++) rootProperties[`f${i}`] = subschema(3); |
| 171 | |
| 172 | return { |
| 173 | schema: { |
| 174 | type: 'object', |
| 175 | properties: rootProperties, |
| 176 | required: Object.keys(rootProperties).slice(0, 2), |
| 177 | [defsKey]: defs, |
| 178 | }, |
| 179 | hasUnresolvable: state.hasUnresolvable, |
| 180 | }; |
| 181 | } |
| 182 | |
| 183 | /** Yield every object reachable through *schema* positions only. */ |
| 184 | function* walkSchemaPositions(value: unknown): Generator<Json> { |
| 185 | if (Array.isArray(value)) { |
| 186 | for (const item of value) yield* walkSchemaPositions(item); |
| 187 | return; |
| 188 | } |
| 189 | if (value === null || typeof value !== 'object') return; |
| 190 | const node = value as Json; |
| 191 | yield node; |
| 192 | for (const [key, child] of Object.entries(node)) { |
| 193 | if (INSTANCE_VALUE_KEYWORDS.has(key)) continue; |
| 194 | yield* walkSchemaPositions(child); |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | const internalRefs = (value: unknown): string[] => |
| 199 | [...walkSchemaPositions(value)] |
| 200 | .map(node => node.$ref) |
| 201 | .filter((ref): ref is string => typeof ref === 'string' && ref.startsWith('#')); |
| 202 | |
| 203 | const externalRefs = (value: unknown): string[] => |
| 204 | [...walkSchemaPositions(value)] |
| 205 | .map(node => node.$ref) |
| 206 | .filter((ref): ref is string => typeof ref === 'string' && !ref.startsWith('#')); |
| 207 | |
| 208 | const instanceValues = (value: unknown): unknown[] => { |
| 209 | const found: unknown[] = []; |
| 210 | for (const node of walkSchemaPositions(value)) { |
| 211 | for (const [key, child] of Object.entries(node)) { |
| 212 | if (INSTANCE_VALUE_KEYWORDS.has(key)) found.push(child); |
| 213 | } |
| 214 | } |
| 215 | return found; |
| 216 | }; |
| 217 | |
| 218 | function forEachDoc(check: (doc: GeneratedDoc) => void, withInstanceValueRefs = false): void { |
| 219 | /** Run *check* over every generated document, reporting the failing seed. */ |
| 220 | for (const seed of SEEDS) { |
| 221 | const doc = generateDoc(mulberry32(seed), withInstanceValueRefs); |
| 222 | try { |
| 223 | check(doc); |
| 224 | } catch (error) { |
| 225 | throw new Error( |
| 226 | `property failed for seed ${seed}\nschema: ${JSON.stringify(doc.schema, null, 2)}\n\n${String(error)}` |
| 227 | ); |
| 228 | } |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | describe('dereferenceJsonSchema — sentinel-mode properties', () => { |
| 233 | it('never raises', () => { |
| 234 | forEachDoc(doc => { |
| 235 | dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' }); |
| 236 | }); |
| 237 | }); |
| 238 | |
| 239 | it('leaves no internal ref', () => { |
| 240 | forEachDoc(doc => { |
| 241 | const out = dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' }); |
| 242 | expect(internalRefs(out)).toEqual([]); |
| 243 | }); |
| 244 | }); |
| 245 | |
| 246 | it('strips root definition blocks', () => { |
| 247 | forEachDoc(doc => { |
| 248 | const out = dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' }) as Json; |
| 249 | expect('$defs' in out).toBe(false); |
| 250 | expect('definitions' in out).toBe(false); |
| 251 | }); |
| 252 | }); |
| 253 | |
| 254 | it('preserves external refs', () => { |
| 255 | forEachDoc(doc => { |
| 256 | const before = new Set(externalRefs(doc.schema)); |
| 257 | const out = dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' }); |
| 258 | // Counts may grow (a def inlined at N sites carries its refs along), |
| 259 | // but nothing reachable in the source may disappear. |
| 260 | const after = new Set(externalRefs(out)); |
| 261 | for (const ref of before) |
| 262 | expect(after.has(ref), `external ref disappeared: ${ref}`).toBe(true); |
| 263 | }); |
| 264 | }); |
| 265 | |
| 266 | it('never mutates its input', () => { |
| 267 | forEachDoc(doc => { |
| 268 | const snapshot = structuredClone(doc.schema); |
| 269 | dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' }); |
| 270 | expect(doc.schema).toEqual(snapshot); |
| 271 | }); |
| 272 | }); |
| 273 | |
| 274 | it('returns serializable output', () => { |
| 275 | // The failure this helper exists to prevent: a dereferencer that keeps |
| 276 | // object identity on a recursive schema builds a real cycle, and |
| 277 | // serializing it for the vendor raises. |
| 278 | forEachDoc(doc => { |
| 279 | JSON.stringify(dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' })); |
| 280 | }); |
| 281 | }); |
| 282 | |
| 283 | it('keeps definition blocks that are not at the root', () => { |
| 284 | forEachDoc(doc => { |
| 285 | // Only the root block is stripped. If a nested one was generated it |
| 286 | // survives — the docs claim this and nothing else pins it. |
| 287 | const input = JSON.stringify(doc.schema); |
| 288 | if (!input.includes('"Local"')) return; |
| 289 | const out = JSON.stringify(dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' })); |
| 290 | expect(out.includes('"Local"')).toBe(true); |
| 291 | }); |
| 292 | }); |
| 293 | |
| 294 | it('does not blow up output size without bound', () => { |
| 295 | // Inlining is depth-bounded but breadth-unbounded: a def referenced N |
| 296 | // times is inlined N times. This does not assert a cap exists — it pins |
| 297 | // the growth factor for the shapes we generate, so a change that makes |
| 298 | // expansion dramatically worse is visible rather than silent. |
| 299 | forEachDoc(doc => { |
| 300 | const before = JSON.stringify(doc.schema).length; |
| 301 | const after = JSON.stringify( |
| 302 | dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' }) |
| 303 | ).length; |
| 304 | expect(after).toBeLessThan(before * 50); |
| 305 | }); |
| 306 | }); |
| 307 | |
| 308 | it('is idempotent', () => { |
| 309 | forEachDoc(doc => { |
| 310 | const once = dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' }); |
| 311 | const twice = dereferenceJsonSchema(once, { onUnresolved: 'sentinel' }); |
| 312 | expect(twice).toEqual(once); |
| 313 | }); |
| 314 | }); |
| 315 | }); |
| 316 | |
| 317 | /** Number of unresolvable refs sentinel mode had to replace. */ |
| 318 | function countReplacements(schema: Json): number { |
| 319 | let replacements = 0; |
| 320 | dereferenceJsonSchema(schema, { |
| 321 | onUnresolved: 'sentinel', |
| 322 | onReplace: () => { |
| 323 | replacements += 1; |
| 324 | }, |
| 325 | }); |
| 326 | return replacements; |
| 327 | } |
| 328 | |
| 329 | describe('dereferenceJsonSchema — throw-mode properties', () => { |
| 330 | it('agrees with sentinel mode when everything resolves', () => { |
| 331 | forEachDoc(doc => { |
| 332 | if (countReplacements(doc.schema) > 0) return; |
| 333 | const strict = dereferenceJsonSchema(doc.schema); |
| 334 | const lenient = dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' }); |
| 335 | expect(strict).toEqual(lenient); |
| 336 | }); |
| 337 | }); |
| 338 | |
| 339 | it('raises exactly when sentinel mode replaced something', () => { |
| 340 | forEachDoc(doc => { |
| 341 | if (countReplacements(doc.schema) > 0) { |
| 342 | expect(() => dereferenceJsonSchema(doc.schema)).toThrow(JsonSchemaRefResolutionError); |
| 343 | } else { |
| 344 | dereferenceJsonSchema(doc.schema); |
| 345 | } |
| 346 | }); |
| 347 | }); |
| 348 | }); |
| 349 | |
| 350 | describe('dereferenceJsonSchema — instance-value keywords', () => { |
| 351 | // KNOWN BROKEN — ratchets, do not delete. |
| 352 | // |
| 353 | // `const`, `default`, `enum` and `examples` hold *instance data*, not |
| 354 | // subschemas, so a `{"$ref": ...}` inside one is an ordinary object that |
| 355 | // happens to have a `$ref` key — not a reference to resolve. |
| 356 | // |
| 357 | // `dereferenceJsonSchema` walks containers with no keyword check, so a tool |
| 358 | // whose schema carries `default: {"$ref": ...}` has that *value* rewritten |
| 359 | // into the unresolved sentinel. `INSTANCE_VALUE_KEYWORDS` exists |
| 360 | // (`jsonSchema.ts:36`) and is honored by `deduplicateJsonSchemaRequiredArrays` |
| 361 | // and `toStrictJsonSchema`, but not by the dereferencer. The Python port has |
| 362 | // the identical gap (`python/tests/test_json_schema_properties.py`). |
| 363 | // |
| 364 | // `it.fails` means these pass the suite while the bug exists; once the |
| 365 | // dereferencer stops walking instance-value keywords they start failing with |
| 366 | // "expected to fail but passed", forcing the marker's removal. A fix cannot |
| 367 | // land silently. |
| 368 | it.fails('does not rewrite $ref-shaped data', () => { |
| 369 | forEachDoc(doc => { |
| 370 | const out = dereferenceJsonSchema(doc.schema, { onUnresolved: 'sentinel' }); |
| 371 | for (const value of instanceValues(out)) { |
| 372 | expect(JSON.stringify(value)).not.toContain('Schema shape unresolved at the source'); |
| 373 | } |
| 374 | }, true); |
| 375 | }); |
| 376 | |
| 377 | it.fails('does not raise on $ref-shaped data', () => { |
| 378 | forEachDoc(doc => { |
| 379 | // Every pointer under the definitions block resolves; the only |
| 380 | // unresolvable strings live in `default`/`enum`, which are data. |
| 381 | if (doc.hasUnresolvable) return; |
| 382 | dereferenceJsonSchema(doc.schema); |
| 383 | }, true); |
| 384 | }); |
| 385 | }); |