test('all template intervals occur in input array', () => {
    fc.assert(fc.property(
      arbitrary_input_intervals(),
      (intervals) => {
        const template = setupStepScaling(intervals);
        const steps = template.allStepsAbsolute();

        return steps.every(step => {
          return reportFalse(intervals.find(interval => {
            const acceptableLowerBounds = step.MetricIntervalLowerBound === -Infinity ? [undefined, 0] : [undefined, step.MetricIntervalLowerBound];
            // eslint-disable-next-line max-len
            const acceptableUpperBounds = step.MetricIntervalUpperBound === Infinity ? [undefined, Infinity] : [undefined, step.MetricIntervalUpperBound];

            return (acceptableLowerBounds.includes(interval.lower) && acceptableUpperBounds.includes(interval.upper));
          }) !== undefined, step, intervals);
        });
      },
    ));
  })

Summary: The template should include all intervals present in the input array, ensuring that every step in the template corresponds to an interval with matching bounds in the input.


unknown

test('lower alarm uses lower policy', () => {
    fc.assert(fc.property(
      arbitrary_input_intervals(),
      (intervals) => {
        const template = setupStepScaling(intervals);
        const alarm = template.resource(template.lowerAlarm);
        fc.pre(alarm !== undefined);

        return reportFalse(alarm.Properties.AlarmActions[0].Ref === template.lowerPolicy, alarm);
      },
    ));
  })

Summary: Lower alarms should reference the lower scaling policy in the template setup.


test('upper alarm uses upper policy', () => {
    fc.assert(fc.property(
      arbitrary_input_intervals(),
      (intervals) => {
        const template = setupStepScaling(intervals);
        const alarm = template.resource(template.upperAlarm);
        fc.pre(alarm !== undefined);

        return reportFalse(alarm.Properties.AlarmActions[0].Ref === template.upperPolicy, alarm);
      },
    ));
  })

Summary: The test verifies that an upper alarm in a step scaling policy correctly references the upper scaling policy for given intervals.


test('every aspect gets executed at most once on every construct', () =>
    fc.assert(
      fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
        afterSynth((testApp) => {
          forEveryVisitPair(testApp.actionLog, (a, b) => {
            if (sameConstruct(a, b) && sameAspect(a, b)) {
              throw new Error(`Duplicate visit: t=${a.index} and t=${b.index}`);
            }
          });
        }, stabilizeAspects)(app);
      }),
    ),
  )

appWithAspects afterSynth forEveryVisitPair sameConstruct sameAspect

Summary: Each aspect is executed at most once on every construct within the application.


it('returns the correct number of digits', () => {
      fc.assert(
        fc.property(fc.integer(), (n) => {
          const expected = n.toString().replace("-", "").length;
          assert.strictEqual(numDigits(n), expected);
        }),
      );
    })

Summary: `numDigits` returns the correct count of digits in an integer.


test('all aspects that exist at the start of synthesis get invoked on all nodes in its scope at the start of synthesis', () =>
    fc.assert(
      fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
        const originalConstructsOnApp = app.cdkApp.node.findAll();
        const originalAspectApplications = getAllAspectApplications(originalConstructsOnApp);
        afterSynth((testApp) => {
          const visitsMap = getVisitsMap(testApp.actionLog);

          for (const aspectApplication of originalAspectApplications) {
            // Check that each original AspectApplication also visited all child nodes of its original scope:
            for (const construct of originalConstructsOnApp) {
              if (isAncestorOf(aspectApplication.construct, construct)) {
                if (!visitsMap.get(construct)!.includes(aspectApplication.aspect)) {
                  throw new Error(`Aspect ${aspectApplication.aspect} applied on ${aspectApplication.construct.node.path} did not visit construct ${construct.node.path} in its original scope.`);
                }
              }
            }
          }
        }, stabilizeAspects)(app);
      }),
    ),
  )

appWithAspects getAllAspectApplications afterSynth getVisitsMap isAncestorOf

Summary: All aspects present at the start of synthesis must be invoked on all constructs within their scope during synthesis.


test('with stabilization, every aspect applied on the tree eventually executes on all of its nodes in scope', () =>
    fc.assert(
      fc.property(appWithAspects(), (app) => {
        afterSynth((testApp) => {
          const allConstructsOnApp = testApp.cdkApp.node.findAll();
          const allAspectApplications = getAllAspectApplications(allConstructsOnApp);
          const visitsMap = getVisitsMap(testApp.actionLog);

          for (const aspectApplication of allAspectApplications) {
            // Check that each AspectApplication also visited all child nodes of its scope:
            for (const construct of allConstructsOnApp) {
              if (isAncestorOf(aspectApplication.construct, construct)) {
                if (!visitsMap.get(construct)!.includes(aspectApplication.aspect)) {
                  throw new Error(`Aspect ${aspectApplication.aspect.constructor.name} applied on ${aspectApplication.construct.node.path} did not visit construct ${construct.node.path} in its scope.`);
                }
              }
            }
          }
        }, true)(app);
      }),
    ),
  )

appWithAspects afterSynth getAllAspectApplications getVisitsMap isAncestorOf

Summary: Every aspect applied to a tree should execute on all of its nodes within scope when stabilization is enabled.


test('inherited aspects get invoked before locally defined aspects, if both have the same priority', () =>
    fc.assert(
      fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
        afterSynth((testApp) => {
          forEveryVisitPair(testApp.actionLog, (a, b) => {
            if (!sameConstruct(a, b)) return;
            if (aspectAppliedT(testApp, a.aspect, a.construct) !== -1 ||
              aspectAppliedT(testApp, b.aspect, b.construct) !== -1) return;

            const aPrio = lowestAspectPrioFor(a.aspect, a.construct);
            const bPrio = lowestAspectPrioFor(b.aspect, b.construct);

            if (!(aPrio == bPrio)) return;

            const aInherited = allAncestorAspects(a.construct).includes(a.aspect);
            const bInherited = allAncestorAspects(b.construct).includes(b.aspect);

            if (!(aInherited == true && bInherited == false)) return;

            if (!(a.index < b.index)) {
              throw new Error(
                `Aspect ${a.aspect}@${aPrio} at ${a.index} should have been before ${b.aspect}@${bPrio} at ${b.index}, but was after`,
              );
            }
          });
        }, stabilizeAspects)(app);
      }),
    ),
  )

appWithAspects afterSynth forEveryVisitPair sameConstruct aspectAppliedT lowestAspectPrioFor allAncestorAspects

Summary: Inherited aspects should invoke before locally defined aspects if both have the same priority.


test('for every construct, lower priorities go before higher priorities', () =>
    fc.assert(
      fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
        afterSynth((testApp) => {
          forEveryVisitPair(testApp.actionLog, (a, b) => {
            if (!sameConstruct(a, b)) return;
            if (aspectAppliedT(testApp, a.aspect, a.construct) !== -1 ||
              aspectAppliedT(testApp, b.aspect, b.construct) !== -1) return;

            const aPrio = lowestAspectPrioFor(a.aspect, a.construct);
            const bPrio = lowestAspectPrioFor(b.aspect, b.construct);

            // But only if the application of aspect A exists at least as long as the application of aspect B
            const aAppliedT = aspectAppliedT(testApp, a.aspect, a.construct);
            const bAppliedT = aspectAppliedT(testApp, b.aspect, b.construct);

            if (!implies(aPrio < bPrio && aAppliedT <= bAppliedT, a.index < b.index)) {
              throw new Error(
                `Aspect ${a.aspect}@${aPrio} at ${a.index} should have been before ${b.aspect}@${bPrio} at ${b.index}, but was after`,
              );
            }
          });
        }, stabilizeAspects)(app);
      }),
    ),
  )

appWithAspects afterSynth forEveryVisitPair sameConstruct aspectAppliedT lowestAspectPrioFor implies

Summary: For every construct, aspects with lower priorities are applied before those with higher priorities, ensuring the order respects the application's lifetime.


test('for every construct, if a invokes before b that must mean it is of equal or lower priority', () =>
    fc.assert(
      fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
        afterSynth((testApp) => {
          forEveryVisitPair(testApp.actionLog, (a, b) => {
            if (!sameConstruct(a, b)) return;
            if (aspectAppliedT(testApp, a.aspect, a.construct) !== -1 ||
              aspectAppliedT(testApp, b.aspect, b.construct) !== -1) return;

            const aPrio = lowestAspectPrioFor(a.aspect, a.construct);
            const bPrio = lowestAspectPrioFor(b.aspect, b.construct);

            if (!implies(a.index < b.index, aPrio <= bPrio)) {
              throw new Error(
                `Aspect ${a.aspect}@${aPrio} at ${a.index} should have been before ${b.aspect}@${bPrio} at ${b.index}, but was after`,
              );
            }
          });
        }, stabilizeAspects)(app);
      }),
    ),
  )

Summary: For each construct, if one aspect invokes before another, the first aspect must have equal or lower priority.


test('visitLog is nonempty', () =>
  fc.assert(
    fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
      afterSynth((testApp) => {
        expect(testApp.actionLog).not.toEqual([]);
      }, stabilizeAspects)(app);
    }),
  ),
)

Summary: Ensures that after synthesis, the `visitLog` in a `PrettyApp` is not empty, regardless of aspect stabilization.


test('LinkedQueue behaves the same as array', () => {
  // define the possible commands and their inputs
  const allCommands = [
    fc.string().map((v) => new PushCommand(v)),
    fc.constant(new ShiftCommand()),
  ];

  // run everything
  fc.assert(
    fc.property(fc.commands(allCommands, { size: '+1' }), (cmds) => {
      const s = () => ({
        model: { array: [] } satisfies Model,
        real: new LinkedQueue(),
      });
      fc.modelRun(s, cmds);
    }),
  );
})

Summary: `LinkedQueue` should perform operations consistently with standard array behaviors, verified by executing sequences of push and shift commands.


asyncTest(async () => {
      const stack = new Stack();
      fc.assert(
        fc.property(
          fc.string(), anyValue,
          (delimiter, value) => _.isEqual(stack.resolve(Fn.join(delimiter, [value as string])), value),
        ),
        { verbose: true },
      );
    })

Summary: `Fn.join` with a delimiter and a single value results in the resolved output being equal to the original value.


asyncTest(async () => {
      const stack = new Stack();
      fc.assert(
        fc.property(
          fc.string(), fc.array(nonEmptyString, { minLength: 1, maxLength: 15 }),
          (delimiter, values) => stack.resolve(Fn.join(delimiter, values)) === values.join(delimiter),
        ),
        { verbose: true },
      );
    })

Summary: `Fn.join` should produce the same result as JavaScript's `join` method when joining an array of non-empty strings using a specified delimiter.


asyncTest(async () => {
      const stack = new Stack();
      fc.assert(
        fc.property(
          fc.string(), fc.array(nonEmptyString, { minLength: 1, maxLength: 3 }), tokenish, fc.array(nonEmptyString, { minLength: 1, maxLength: 3 }),
          (delimiter, prefix, obj, suffix) =>
            _.isEqual(stack.resolve(Fn.join(delimiter, [...prefix, stringToken(obj), ...suffix])),
              { 'Fn::Join': [delimiter, [prefix.join(delimiter), obj, suffix.join(delimiter)]] }),
        ),
        { verbose: true },
      );
    })

Summary: The property checks that using `Fn.join` to concatenate a mix of string arrays and a token object with a delimiter results in a resolved structure matching an expected `{ 'Fn::Join': [...] }` format.


it('should return empty array for invalid astra endpoints', () => {
      fc.assert(
        fc.property(fc.webUrl(), (webURL) => {
          assert.deepStrictEqual(extractDbComponentsFromAstraUrl(webURL), []);
        }),
      );

      fc.assert(
        fc.property(fc.string(), (webURL) => {
          assert.deepStrictEqual(extractDbComponentsFromAstraUrl(webURL), []);
        }),
      );
    })


asyncTest(async () => {
      const stack = new Stack();
      fc.assert(
        fc.property(
          fc.string(), fc.array(anyValue),
          fc.array(anyValue, { minLength: 1, maxLength: 3 }),
          fc.array(anyValue),
          (delimiter, prefix, nested, suffix) =>
            // Gonna test
            _.isEqual(stack.resolve(Fn.join(delimiter, [...prefix as string[], Fn.join(delimiter, nested as string[]), ...suffix as string[]])),
              stack.resolve(Fn.join(delimiter, [...prefix as string[], ...nested as string[], ...suffix as string[]]))),
        ),
        { verbose: true },
      );
    })

Summary: The `Fn.join` function should produce the same result when nested joins are resolved with the same delimiter as when flattened into a single join.


asyncTest(async () => {
      const stack = new Stack();
      fc.assert(
        fc.property(
          fc.string(), fc.string(),
          fc.array(anyValue, { minLength: 1, maxLength: 3 }),
          fc.array(tokenish, { minLength: 2, maxLength: 3 }),
          fc.array(anyValue, { minLength: 3 }),
          (delimiter1, delimiter2, prefix, nested, suffix) => {
            fc.pre(delimiter1 !== delimiter2);
            const join = Fn.join(delimiter1, [...prefix as string[], Fn.join(delimiter2, stringListToken(nested)), ...suffix as string[]]);
            const resolved = stack.resolve(join);
            return resolved['Fn::Join'][1].find((e: any) => typeof e === 'object'
                                                        && ('Fn::Join' in e)
                                                        && e['Fn::Join'][0] === delimiter2) != null;
          },
        ),
        { verbose: true },
      );
    })

Summary: `Fn.join` with different delimiters correctly nests string list tokens, ensuring nested joins are present with the expected delimiter in the resolution.


test('lower alarm index is lower than higher alarm index', () => {
    fc.assert(fc.property(
      arbitrary_complete_intervals(),
      (intervals) => {
        const alarms = findAlarmThresholds(intervals);

        return (alarms.lowerAlarmIntervalIndex === undefined
          || alarms.upperAlarmIntervalIndex === undefined
          || alarms.lowerAlarmIntervalIndex < alarms.upperAlarmIntervalIndex);
      },
    ));
  })

Summary: The test checks that in the `findAlarmThresholds` function, the `lowerAlarmIntervalIndex` is less than the `upperAlarmIntervalIndex`, if both are defined.


test('no picking upper bound infinity for lower alarm', () => {
    fc.assert(fc.property(
      arbitrary_complete_intervals(),
      (intervals) => {
        const alarms = findAlarmThresholds(intervals);
        fc.pre(alarms.lowerAlarmIntervalIndex !== undefined);

        return intervals[alarms.lowerAlarmIntervalIndex!].upper !== Infinity;
      },
    ));
  })

Summary: The `findAlarmThresholds` function should not select an interval with an upper bound of infinity for the lower alarm.


it('should maintain immutability for any sequence of operations', () => {
      fc.assert(
        fc.property(
          fc.array(
            fc.oneof(
              fc.tuple(fc.constant('setVar'), varNameArb, typeInfoArb),
              fc.tuple(fc.constant('setImport'), varNameArb, importedClassInfoArb),
              fc.tuple(fc.constant('markExport'), varNameArb)
            ),
            { minLength: 1, maxLength: 100 }
          ),
          (operations) => {
            const original = create_file_type_tracker();
            let current = original;

            for (const [op, name, data] of operations) {
              const previous = current;

              switch (op) {
                case 'setVar':
                  current = set_variable_type(current, name, data as TypeInfo);
                  break;
                case 'setImport':
                  current = set_imported_class(current, name, data as ImportedClassInfo);
                  break;
                case 'markExport':
                  current = mark_as_exported(current, name);
                  break;
              }

              // Previous state unchanged
              expect(current).not.toBe(previous);
              expect(previous.variableTypes).toBe(previous.variableTypes);
            }

            // Original completely unchanged
            expect(original.variableTypes.size).toBe(0);
            expect(original.importedClasses.size).toBe(0);
            expect(original.exportedDefinitions.size).toBe(0);
          }
        )
      );
    })

Summary: The sequence of `setVar`, `setImport`, and `markExport` operations on a file type tracker should not mutate the previous state, ensuring immutability is maintained and the original tracker's state remains unchanged.


it('should be commutative for independent operations', () => {
      fc.assert(
        fc.property(
          varNameArb,
          varNameArb,
          typeInfoArb,
          typeInfoArb,
          (var1, var2, type1, type2) => {
            fc.pre(var1 !== var2); // Ensure different variables

            const tracker = create_file_type_tracker();

            // Apply in order 1->2
            const result1 = set_variable_type(
              set_variable_type(tracker, var1, type1),
              var2, type2
            );

            // Apply in order 2->1
            const result2 = set_variable_type(
              set_variable_type(tracker, var2, type2),
              var1, type1
            );

            // Results should be equivalent
            expect(result1.variableTypes.size).toBe(result2.variableTypes.size);
            expect(result1.variableTypes.get(var1)).toEqual(result2.variableTypes.get(var1));
            expect(result1.variableTypes.get(var2)).toEqual(result2.variableTypes.get(var2));
          }
        )
      );
    })

Summary: Setting variable types in different orders for independent variables should yield results with equivalent sizes and values for each variable.


it('should maintain structural sharing for any update sequence', () => {
      fc.assert(
        fc.property(
          fc.array(
            fc.record({
              filePath: fc.string({ minLength: 1, maxLength: 20 }),
              hasGraph: fc.boolean(),
              hasCache: fc.boolean()
            }),
            { minLength: 1, maxLength: 20 }
          ),
          (updates) => {
            let project = create_project_call_graph();
            const unchangedMaps = new Set<any>();

            for (const update of updates) {
              const prev = project;

              // Track which maps were present before
              if (prev.fileGraphs.size > 0) unchangedMaps.add(prev.fileGraphs);
              if (prev.fileCache.size > 0) unchangedMaps.add(prev.fileCache);
              if (prev.fileTypeTrackers.size > 0) unchangedMaps.add(prev.fileTypeTrackers);

              // Apply update
              if (update.hasGraph) {
                project = add_file_graph(project, update.filePath, {} as any);
              }
              if (update.hasCache) {
                project = add_file_cache(project, update.filePath, {} as any);
              }

              // Verify structural sharing
              if (!update.hasGraph && prev.fileGraphs.size > 0) {
                expect(project.fileGraphs).toBe(prev.fileGraphs);
              }
              if (!update.hasCache && prev.fileCache.size > 0) {
                expect(project.fileCache).toBe(prev.fileCache);
              }
            }
          }
        )
      );
    })

Summary: Structural sharing is maintained for file graphs and caches during any sequence of updates to a project.


it('should correctly merge any two projects', () => {
      fc.assert(
        fc.property(
          fc.array(fc.string({ minLength: 1, maxLength: 10 }), { maxLength: 10 }),
          fc.array(fc.string({ minLength: 1, maxLength: 10 }), { maxLength: 10 }),
          (files1, files2) => {
            let project1 = create_project_call_graph();
            let project2 = create_project_call_graph();

            // Build project1
            for (const file of files1) {
              project1 = add_file_graph(project1, file, {} as any);
            }

            // Build project2
            for (const file of files2) {
              project2 = add_file_graph(project2, file, {} as any);
            }

            // Merge
            const merged = merge_project_graphs(project1, project2);

            // Verify merge properties
            expect(merged).not.toBe(project1);
            expect(merged).not.toBe(project2);

            // All files from both projects should be in merged
            const allFiles = new Set([...files1, ...files2]);
            expect(merged.fileGraphs.size).toBe(allFiles.size);

            // Project2 takes precedence for overlapping files
            for (const file of files2) {
              expect(merged.fileGraphs.has(file)).toBe(true);
            }
          }
        )
      );
    })

Summary: Merging two project call graphs results in a new graph containing all files from both projects, with precedence given to files from the second project if there are overlaps.


it('should handle batch updates efficiently', () => {
      fc.assert(
        fc.property(
          fc.array(
            fc.record({
              filePath: fc.string({ minLength: 1, maxLength: 20 }),
              graph: fc.constant({} as any),
              cache: fc.constant({} as any)
            }),
            { minLength: 1, maxLength: 50 }
          ),
          (updates) => {
            const project = create_project_call_graph();

            // Apply batch
            const batchResult = batch_update_files(project, updates);

            // Apply sequentially
            let seqResult = project;
            for (const update of updates) {
              if (update.graph) {
                seqResult = add_file_graph(seqResult, update.filePath, update.graph);
              }
              if (update.cache) {
                seqResult = add_file_cache(seqResult, update.filePath, update.cache);
              }
            }

            // Results should be equivalent
            expect(batchResult.fileGraphs.size).toBe(seqResult.fileGraphs.size);
            expect(batchResult.fileCache.size).toBe(seqResult.fileCache.size);
          }
        )
      );
    })

Summary: Applying batch file updates should yield the same results as applying them sequentially in terms of file graph and file cache sizes.


it('should never expose mutable internal state', () => {
      fc.assert(
        fc.property(
          fc.array(varNameArb, { minLength: 1, maxLength: 10 }),
          (vars) => {
            let tracker = create_file_type_tracker();

            // Add some data
            for (const v of vars) {
              tracker = set_variable_type(tracker, v, {
                className: 'TestClass',
                classDef: undefined,
                position: { row: 0, column: 0 }
              });
            }

            // Get internal state
            const varTypes = tracker.variableTypes;
            const exports = tracker.exportedDefinitions;

            // Verify they're readonly types (TypeScript enforces at compile time)
            // At runtime, verify immutability through operations
            const originalSize = varTypes.size;
            const originalExportsSize = exports.size;

            // Any mutations would only affect a new instance
            const updated = set_variable_type(tracker, 'newVar', {
              className: 'NewClass',
              classDef: undefined,
              position: { row: 0, column: 0 }
            });

            // Original tracker unchanged
            expect(tracker.variableTypes.size).toBe(originalSize);
            expect(tracker.exportedDefinitions.size).toBe(originalExportsSize);

            // New instance has the changes
            expect(updated.variableTypes.size).toBe(originalSize + 1);
          }
        )
      );
    })

Summary: `create_file_type_tracker` ensures its internal state remains immutable, as evidenced by no changes occurring to the original state after operations that modify a new instance.


it('should support undo/redo through state history', () => {
      fc.assert(
        fc.property(
          fc.array(
            fc.tuple(varNameArb, typeInfoArb),
            { minLength: 1, maxLength: 20 }
          ),
          (operations) => {
            const history: FileTypeTrackerData[] = [];
            let current = create_file_type_tracker();

            history.push(current);

            // Apply operations and track history
            const uniqueVars = new Set<string>();
            for (const [name, type] of operations) {
              current = set_variable_type(current, name, type);
              uniqueVars.add(name);
              history.push(current);
            }

            // Verify we can access any previous state
            // The size is based on unique variable names, not total operations
            for (let i = 0; i < history.length; i++) {
              if (i === 0) {
                expect(history[i].variableTypes.size).toBe(0);
              } else {
                // Size increases only when we see a new variable
                const varsUpToI = new Set(operations.slice(0, i).map(([n]) => n));
                expect(history[i].variableTypes.size).toBe(varsUpToI.size);
              }
            }

            // Simulate undo
            const undoSteps = Math.min(5, operations.length);
            const afterUndo = history[history.length - 1 - undoSteps];
            const varsAfterUndo = new Set(operations.slice(0, operations.length - undoSteps).map(([n]) => n));
            expect(afterUndo.variableTypes.size).toBe(varsAfterUndo.size);
          }
        )
      );
    })

Summary: The state history should correctly track variable type changes to support undo/redo functionality, with the ability to revert to any previous state based on unique variable operations.


test('should parse complete json', () => {
    expect(partialParse('{"__proto__": 0}')).toEqual(JSON.parse('{"__proto__": 0}'));

    fc.assert(
      fc.property(fc.json({ depthSize: 'large', noUnicodeString: false }), (jsonString) => {
        const parsedNormal = JSON.parse(jsonString);
        const parsedPartial = partialParse(jsonString);
        expect(parsedPartial).toEqual(parsedNormal);
      }),
    );
  })

Summary: The function `partialParse` should produce the same result as `JSON.parse` when parsing JSON strings.


test('should only throw errors parsing numbers', () =>
    fc.assert(
      fc.property(fc.json({ depthSize: 'large', noUnicodeString: false }), (jsonString) => {
        for (let i = 1; i < jsonString.length; i++) {
          // speedup
          i += Math.floor(Math.random() * 3);
          const substring = jsonString.substring(0, i);

          // since we don't allow partial parsing for numbers
          if (
            typeof JSON.parse(jsonString) === 'number' &&
            'e-+.'.includes(substring[substring.length - 1]!)
          ) {
            expect(() => partialParse(substring)).toThrow(MalformedJSON);
          } else {
            partialParse(substring);
          }
        }
      }),
    ))

Summary: Partial parsing attempts on JSON strings should only throw errors when dealing with numbers where the substring ends with `'e'`, `'-'`, `'+'`, or `'.'`.


it("deep cloning of LiveStructures", () =>
    fc.assert(
      fc.asyncProperty(
        liveStructure,

        async (data) => {
          const { root } = await prepareStorageUpdateTest([
            createSerializedObject("0:0", {}),
          ]);

          // Clone "a" to "b"
          root.set("a", data);
          root.set("b", data.clone());

          const imm = root.toImmutable();
          expect(imm.a).toEqual(imm.b);
        }
      )
    ))

Summary: Deep cloning `LiveStructures` ensures that cloned objects are equal to their originals when stored within the same parent structure.


it("deep cloning of LiveStructures (twice)", () =>
    fc.assert(
      fc.asyncProperty(
        liveStructure,

        async (data) => {
          const { root } = await prepareStorageUpdateTest([
            createSerializedObject("0:0", {}),
          ]);

          // Clone "a" to "b"
          root.set("a", data);
          root.set("b", data.clone().clone());
          //                        ^^^^^^^^ Deliberately cloning twice in this test

          const imm = root.toImmutable();
          expect(imm.a).toEqual(imm.b);
        }
      )
    ))

Summary: Deep cloning of `LiveStructures` twice should result in equivalent objects, verified by ensuring property `a` equals property `b` after two clones.


it("deep cloning of LSON data (= LiveStructures or JSON)", () =>
    fc.assert(
      fc.asyncProperty(
        lson,

        async (data) => {
          const { root } = await prepareStorageUpdateTest([
            createSerializedObject("0:0", {}),
          ]);

          // Clone "a" to "b"
          root.set("a", data);
          root.set("b", cloneLson(data));
          //            ^^^^^^^^^ Much like data.clone(), but generalized to
          //                      work on _any_ LSON value, even if data is
          //                      a JSON value

          const imm = root.toImmutable();
          expect(imm.a).toEqual(imm.b);
        }
      )
    ))

Summary: Deep cloning of LSON data ensures that cloned data structures, when converted to immutable form, are equal to their source counterparts.


test("normal popping and pushing behaves like a normal array", () => {
    fc.assert(
      fc.property(
        sequenceOfOps(),

        (seq) => {
          const expected = [];
          const deque = new Deque();

          for (const [op, values] of seq) {
            if (op === "add") {
              expected.push(...values);
              deque.push(values);
            } else {
              expect(expected.pop()).toEqual(deque.pop());
            }
          }

          const actual = Array.from(deque);
          expect(actual).toEqual(expected);
        }
      )
    );
  })

Summary: Sequential push and pop operations on `Deque` should produce the same results as a normal array.


test("popping and pushing from the left cannot be distinguished from array shift/unshift ops", () => {
    fc.assert(
      fc.property(
        sequenceOfOps(),

        (seq) => {
          const expected = [];
          const deque = new Deque();

          for (const [op, values] of seq) {
            if (op === "add") {
              expected.unshift(...values);
              deque.pushLeft(values);
            } else {
              expect(expected.shift()).toEqual(deque.popLeft());
            }
          }

          const actual = Array.from(deque);
          expect(actual).toEqual(expected);
        }
      )
    );
  })

Summary: Popping and pushing elements from the left of a `Deque` should produce the same result as using array `shift` and `unshift` operations, ensuring both methods lead to equivalent sequences.


it("asPos is idempotent", () => {
    fc.assert(
      fc.property(
        fc.string(),

        (s) => {
          expect(asPos(s)).toBe(asPos(asPos(s)));
          expect(asPos(s)).toBe(asPos(asPos(asPos(asPos(s)))));
        }
      )
    );
  })

Summary: The `asPos` function, when applied to a string, should be idempotent, meaning repeated applications yield the same result as a single application.


test("after hops to next major digit when possible", () => {
    expect(after(ONE)).toBe(TWO);
    expect(after(TWO)).toBe(THREE);
    expect(after(THREE)).toBe(FOUR);
    expect(after(asPos(ZERO + ZERO + ONE))).toBe(ONE);
    expect(after(ONE)).toBe(TWO);
    expect(after(asPos(ONE + ZERO + ONE))).toBe(TWO);
    expect(after(TWO)).toBe(THREE);
    expect(after(THREE)).toBe(FOUR);
    expect(after(EIGHT)).toBe(NINE);
    expect(after(NINE)).toBe(NINE + ONE);
    expect(after(asPos(NINE + ONE))).toBe(NINE + TWO);
    expect(after(asPos(NINE + ONE + TWO + THREE))).toBe(NINE + TWO);
    expect(after(asPos(NINE + EIGHT))).toBe(NINE + NINE);
    expect(after(asPos(NINE + NINE))).toBe(NINE + NINE + ONE);
    expect(after(asPos(NINE + NINE + NINE + NINE))).toBe(
      NINE + NINE + NINE + NINE + ONE
    );

    // Generically stated, if the first digit isn't a 9, the result is always
    // going to be a single digit position
    fc.assert(
      fc.property(
        genPos(),

        (pos) => {
          if (pos[0] !== NINE) {
            expect(after(pos).length).toBe(1); // Always generates a single-digit
          }
        }
      )
    );
  })

Summary: The `after` function should increment positions by hopping to the next major digit, ensuring single-digit results unless the first digit is a 9.


test("before hops to prior major digit when possible", () => {
    expect(before(NINE)).toBe(EIGHT);
    expect(before(FOUR)).toBe(THREE);
    expect(before(THREE)).toBe(TWO);
    expect(before(TWO)).toBe(ONE);

    // Not possible when reading the "left edge" of .1, .01, .001, .0001, etc.
    expect(before(ONE)).toBe(ZERO + NINE); // e.g. before(.1) => .09

    expect(before(asPos(ONE + ONE))).toBe(ONE);
    expect(before(asPos(ONE + ONE))).toBe(ONE);
    expect(before(TWO)).toBe(ONE);
    expect(before(asPos(TWO + THREE + ONE + ZERO + ONE))).toBe(TWO);
    expect(before(THREE)).toBe(TWO);
    expect(before(NINE)).toBe(EIGHT);
    expect(before(asPos(NINE + ONE))).toBe(NINE);
    expect(before(asPos(NINE + TWO))).toBe(NINE);
    expect(before(asPos(NINE + THREE))).toBe(NINE);
    expect(before(asPos(NINE + EIGHT))).toBe(NINE);
    expect(before(asPos(NINE + NINE))).toBe(NINE);
    expect(before(asPos(ZERO + ONE))).toBe(ZERO + ZERO + NINE);
    expect(before(asPos(ZERO + ZERO + ONE))).toBe(ZERO + ZERO + ZERO + NINE);
    expect(before(asPos(ONE + ZERO + ZERO + ONE))).toBe(ONE); // e.g. before(.1001) => .1

    expect(before(asPos(NINE + THREE))).toBe(NINE); // e.g. before(.93) => .9
    expect(before(asPos(TWO + THREE + ONE + ZERO + ONE))).toBe(TWO); // e.g. before(.23101) => .2

    expect(before(asPos(ZERO + ZERO + TWO))).toBe(ZERO + ZERO + ONE);
    expect(before(asPos(ZERO + ZERO + TWO + EIGHT + THREE))).toBe(
      ZERO + ZERO + TWO
    );
    expect(before(asPos(ZERO + ZERO + TWO + ZERO + THREE))).toBe(
      ZERO + ZERO + TWO
    );

    // Generically stated, if this isn't the "left edge", the result is always
    // going to be a single digit
    fc.assert(
      fc.property(
        genUnverifiedPos(),

        (pos) => {
          if (!(pos === ONE || asPos(pos)[0] === ZERO)) {
            expect(before(pos).length).toBe(1); // Always generates a single-digit
          }
        }
      ),

      {
        // Counter-examples that where found in the past by fast-check
        examples: [["\u0000x"]],
      }
    );
  })

Summary: Verifying that the `before` function returns the correct prior major digit for different positions, ensuring it generates a single-digit when not on the "left edge" of a sequence.


it('before generates alphabetically "lower" values', () => {
    fc.assert(
      fc.property(
        genPos(),

        (pos) => {
          expect(before(pos) < pos).toBe(true);
          expect(pos > before(pos)).toBe(true);
        }
      )
    );
  })

Summary: The `before` function generates values that are alphabetically lower than the given position.


it('should handle to-bignumber coercion properly', () => {
      const desAsserter = mkDesAsserter('bignumber', (n) => BigNumber(n));

      fc.assert(
        fc.property(fc.oneof(fc.double(), arbs.bigNum()), arbs.pathWithObj(), (num, pathWithObj) => {
          desAsserter.ok(pathWithObj, num);
        }),
      );
    })

Summary: `mkDesAsserter` correctly coerces numbers to `BigNumber` across various numeric inputs and paths.


it('should serialize the date into the proper format', () => {
        fc.assert(
          fc.property(arbs.validDate(), (date) => {
            assert.deepStrictEqual(serdes.serialize(date), [{ $date: date.valueOf() }, false]);
          }),
        );
      })

Summary: `serdes.serialize` converts a valid date into an object with a `$date` property holding the date's timestamp value.


it('should deserialize the date properly', () => {
        fc.assert(
          fc.property(arbs.validDate(), (date) => {
            assert.deepStrictEqual(serdes.deserialize({ $date: date.valueOf() }, {}), date);
          }),
        );
      })

Summary: Deserialization of a date object from its serialized form should yield the original date.


it("throws for equal values", () => {
    expect(() => between(asPos("x"), asPos("x"))).toThrow();
    expect(() => between(asPos("x"), asPos("x        "))).toThrow();

    fc.assert(
      fc.property(
        genUnverifiedPos(),

        (pos) => {
          expect(() => between(pos, pos)).toThrow();
        }
      )
    );
  })

Summary: The function `between` throws an exception when called with two identical position values, including those with trailing spaces or unverified positions.


it("arguments are commutative", () => {
    fc.assert(
      fc.property(
        genPos(),
        genPos(),

        (pos1, pos2) => {
          if (pos1 !== pos2) {
            expect(between(pos1, pos2)).toBe(between(pos2, pos1));
          }
        }
      )
    );
  })

Summary: `between` function produces the same result regardless of the order of distinct `pos1` and `pos2`.


it("correct compares output of before/after", () => {
    fc.assert(
      fc.property(
        genPos(),

        (pos) => {
          expect(pos < after(pos)).toBe(true);
          expect(before(pos) < pos).toBe(true);
          expect(after(pos) > pos).toBe(true);
          expect(pos > before(pos)).toBe(true);
        }
      )
    );
  })

Summary: The property ensures that for any generated position `pos`, `before(pos)` produces a position less than `pos`, and `after(pos)` produces a position greater than `pos`.


it("correct compares output of between", () => {
    fc.assert(
      fc.property(
        genPosRange(),

        ([lo, hi]) => {
          const mid = between(lo, hi);
          expect(lo < mid).toBe(true);
          expect(mid < hi).toBe(true);
          expect(mid > lo).toBe(true);
          expect(hi > mid).toBe(true);
        }
      ),

      {
        examples: [
          // Found these as counter examples once, adding them here to prevent regressions in the future
          [["a", "a!"] as Pos[]],
          [["a", "a                             !"] as Pos[]],
        ],
      }
    );
  })

Summary: The `between` function generates a position between two given positions `lo` and `hi`, ensuring `lo < mid < hi` holds true.


it("will only generate syntactically valid queries", () =>
    fc.assert(
      fc.property(
        fc.dictionary(
          fc.string(),
          fc.oneof(
            fc.string(),
            fc.dictionary(fc.string(), fc.string(), { minKeys: 1 })
          ),
          { minKeys: 1 }
        ),
        fc.context(),

        (objValue, ctx) => {
          let query: string;
          try {
            query = objectToQuery(objValue);
          } catch {
            // If there was a parse error, we cannot assert anything reasonable
            // about the result
            return;
          }

          const fields = Object.fromEntries(
            Object.entries(objValue).flatMap(([k, v]) =>
              typeof v === "string" ? [[k, "mixed"] as const] : []
            )
          );
          const indexableFields = Object.fromEntries(
            Object.entries(objValue).flatMap(([k, v]) =>
              typeof v !== "string" ? [[k, "mixed"] as const] : []
            )
          );

          const parser = new QueryParser({
            fields,
            indexableFields,
          });

          ctx.log(`Generated query that did not parse was: →${query}←`);
          expect(() => parser.parse(query)).not.toThrow();
        }
      )
    ))

Summary: `objectToQuery` generates syntactically valid queries from dictionaries, ensuring they can be parsed without errors.


it('should $binary-ify any DataAPIVectorLike and ignore the rest', () => {
        const arb = fc.oneof(
          fc.anything(),
          arbs.vector().map(v => v.asArray()),
          arbs.vector().map(v => v.asFloat32Array()),
          arbs.vector().map(v => ({ $binary: v.asBase64() })),
          arbs.vector(),
        );

        fc.assert(
          fc.property(arb, (anything) => {
            if (DataAPIVector.isVectorLike(anything)) {
              assert.deepStrictEqual(serdes.serialize({ $vector: anything }), [{ $vector: { $binary: vector(anything).asBase64() } }, false]);
            } else {
              assert.deepStrictEqual(serdes.serialize({ $vector: anything }), [{ $vector: anything }, false]);
            }
          }),
        );
      })

Summary: The serialization process should convert `DataAPIVectorLike` objects into a `$binary` format and leave non-vector-like objects unchanged.


it('should deserialize number[]s into DataAPIVectors', () => {
        fc.assert(
          fc.property(arbs.vector(), (vector) => {
            assert.deepStrictEqual(serdes.deserialize({ $vector: vector.asArray() }, {}), { $vector: vector });
          }),
        );
      })

Summary: Deserializes arrays of numbers into `DataAPIVectors` and ensures the deserialized result matches the original vector structure.


it('should deserialize { $binary }s into DataAPIVectors', () => {
        fc.assert(
          fc.property(arbs.vector().map(v => v.asBase64()), (base64) => {
            assert.deepStrictEqual(serdes.deserialize({ $vector: { $binary: base64 } }, {}), { $vector: vector({ $binary: base64 }) });
          }),
        );
      })

Summary: Deserialization of `{ $binary }` inputs should correctly yield `DataAPIVectors`.


it('should serialize uuids properly', () => {
        fc.assert(
          fc.property(arbs.uuid(), (uuid) => {
            assert.deepStrictEqual(serdes.serialize(uuid), [{ $uuid: uuid.toString() }, false]);
          }),
        );
      })

Summary: Serializing a UUID should result in an object with the UUID string under the key `$uuid` and a boolean value `false`.


it('should deserialize uuids properly', () => {
        fc.assert(
          fc.property(arbs.uuid(), (uuid) => {
            assert.deepStrictEqual(serdes.deserialize({ $uuid: uuid.toString() }, {}), uuid);
          }),
        );
      })

Summary: Deserializing an object with a `$uuid` key should return the original UUID.


test("delete behaves just like a normal Map delete", () => {
    fc.assert(
      fc.property(
        fc.array(fc.tuple(fc.string(), fc.anything())),
        fc.array(fc.string()),

        (tuples, keysToDelete) => {
          const expected = new Map(tuples);
          const actual = new DefaultMap(() => 0 as unknown, tuples);

          for (const key of keysToDelete) {
            expected.delete(key);
            actual.delete(key);
          }

          expect(new Map(actual)).toEqual(expected);
        }
      )
    );
  })

Summary: Deleting keys from `DefaultMap` should yield the same result as doing so from a normal `Map`.


test("SortedList.from() will sort the input and keep it sorted automatically (asc)", () => {
    expect(Array.from(SortedList.from([3, 1, 2], asc))).toEqual([1, 2, 3]);
    expect(Array.from(SortedList.from(["world", "hello"], asc))).toEqual([
      "hello",
      "world",
    ]);
    expect(
      Array.from(
        SortedList.from(
          [{ id: 1 }, { id: 2 }, { id: -99 }],
          (a, b) => a.id < b.id
        )
      )
    ).toEqual([{ id: -99 }, { id: 1 }, { id: 2 }]);

    fc.assert(
      fc.property(
        fc.array(fc.nat()),

        (arr) => {
          const sortedArr = [...arr].sort((a, b) => a - b);
          expect(Array.from(SortedList.from(arr, asc))).toEqual(sortedArr);
        }
      )
    );
  })

Summary: `SortedList.from()` sorts the input array automatically in ascending order, preserving the sorted order for numbers, strings, and objects with `id` properties.


test("Static method .fromAlreadySorted won't sort (garbage in, garbage out)", () => {
    expect(Array.from(SortedList.fromAlreadySorted([3, 1, 2], asc))).toEqual([
      3, 1, 2,
    ]);
    expect(
      Array.from(SortedList.fromAlreadySorted(["world", "hello"], asc))
    ).toEqual(["world", "hello"]);

    fc.assert(
      fc.property(
        fc.array(fc.nat()),

        (arr) => {
          expect(Array.from(SortedList.fromAlreadySorted(arr, asc))).toEqual(
            arr
          );
        }
      )
    );
  })

Summary: `SortedList.fromAlreadySorted` returns the input array unchanged, even if it is not sorted.


test("will keep a sorted list sorted, no matter what elements are added (asc)", () => {
    fc.assert(
      fc.property(
        fc.array(fc.nat()),
        fc.array(fc.nat()),

        (input, valuesToAdd) => {
          const sortedList = SortedList.from(input, asc); // Our thing
          const jsSortedArr = [...input].sort((a, b) => a - b); // For comparison

          expect(Array.from(sortedList)).toEqual(jsSortedArr);
          for (const value of valuesToAdd) {
            jsSortedArr.push(value);
            jsSortedArr.sort((a, b) => a - b);

            sortedList.add(value);
            expect(Array.from(sortedList)).toEqual(jsSortedArr);
          }
        }
      )
    );
  })

Summary: A `SortedList` maintains its elements in ascending order, regardless of which elements are added.


test("will keep a sorted list sorted, no matter what elements are added (desc)", () => {
    fc.assert(
      fc.property(
        fc.array(fc.nat()),
        fc.array(fc.nat()),

        (input, valuesToAdd) => {
          const sortedList = SortedList.from(input, desc); // Our thing
          const jsDescSortedArr = [...input].sort((a, b) => b - a); // For comparison

          expect(Array.from(sortedList)).toEqual(jsDescSortedArr);
          for (const value of valuesToAdd) {
            jsDescSortedArr.push(value);
            jsDescSortedArr.sort((a, b) => b - a);

            sortedList.add(value);
            expect(Array.from(sortedList)).toEqual(jsDescSortedArr);
          }
        }
      )
    );
  })

Summary: SortedList maintains a descending order after adding elements, ensuring it matches the order produced by JavaScript's native sort function.


test("test with more complex data structures (asc)", () => {
    const thread = fc.record({ id: fc.nat(), updatedAt: fc.date() });

    fc.assert(
      fc.property(
        fc.array(thread, { maxLength: 10_000 }),
        fc.array(thread, { maxLength: 10_000 }),

        (threads, threadsToAdd) => {
          const sortedList = SortedList.from(
            threads,
            (t1, t2) => t1.updatedAt < t2.updatedAt
          ); // Our thing
          const jsSortedArr = [...threads].sort(
            (t1, t2) => t1.updatedAt.getTime() - t2.updatedAt.getTime()
          ); // For comparison

          expect(Array.from(sortedList)).toEqual(jsSortedArr);
          for (const newThread of threadsToAdd) {
            jsSortedArr.push(newThread);
            jsSortedArr.sort(
              (t1, t2) => t1.updatedAt.getTime() - t2.updatedAt.getTime()
            ); // For comparison

            sortedList.add(newThread);
            expect(Array.from(sortedList)).toEqual(jsSortedArr);
          }
        }
      )
    );
  })

Summary: The `SortedList` maintains ascending order of threads based on `updatedAt` when initially created and after adding new threads, matching JavaScript's array sorting.


test("test with more complex data structures (desc)", () => {
    const thread = fc.record({ id: fc.nat(), updatedAt: fc.date() });

    fc.assert(
      fc.property(
        fc.array(thread, { maxLength: 10_000 }),
        fc.array(thread, { maxLength: 10_000 }),

        (threads, threadsToAdd) => {
          const sortedList = SortedList.from(
            threads,
            (t1, t2) => t2.updatedAt < t1.updatedAt
          ); // Our thing
          const jsDescSortedArr = [...threads].sort(
            (t1, t2) => t2.updatedAt.getTime() - t1.updatedAt.getTime()
          ); // For comparison

          expect(Array.from(sortedList)).toEqual(jsDescSortedArr);
          for (const newThread of threadsToAdd) {
            jsDescSortedArr.push(newThread);
            jsDescSortedArr.sort(
              (t1, t2) => t2.updatedAt.getTime() - t1.updatedAt.getTime()
            ); // For comparison

            sortedList.add(newThread);
            expect(Array.from(sortedList)).toEqual(jsDescSortedArr);
          }
        }
      )
    );
  })

Summary: `SortedList` maintains proper descending order of elements by comparing `updatedAt` dates, even after adding new elements.


it("keys don't change", () => {
    fc.assert(
      fc.property(
        objectWithoutProto(),

        (obj) => {
          const result = mapValues(obj, () => Math.random());
          expect(Object.keys(result)).toStrictEqual(Object.keys(obj));
        }
      )
    );
  })

Summary: `mapValues` returns an object with the same keys as the input object, even when the `__proto__` property is removed.


test('output dimensions match configuration', () => {
    fc.assert(
      fc.property(networkConfig(), (config) => {
        const network = new MockNeuralNetwork(
          config
        ) as any as any as any as any;
        const input = new Array(config?.inputSize).fill(0.5);
        const output = network.predict(input);

        expect(output).toHaveLength(config?.outputSize);
      })
    );
  })

Summary: The output dimensions of a neural network should match the specified output size in the configuration.


it('should create a new cursor with the initial page state unset if undefined', () => {
        fc.assert(
          fc.property(fc.string(), arbs.record(fc.anything()), (garbagePageState, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);
            cursor['_currentPage'] = { nextPageState: 'some-page-state', result: [] };

            CursorDeltaAsserter
              .captureImmutDelta(cursor, () => cursor.initialPageState(garbagePageState).initialPageState(undefined))
              .assertDelta({ _currentPage: undefined });
          }),
        );
      })

Summary: Creating a new cursor with an undefined initial page state results in `_currentPage` being set to undefined.


it('should return a brand new cursor with the same config', () => {
        const allArbs = <const>[
          arbs.record(fc.anything()),
          arbs.record(fc.anything()),
          fc.func(fc.anything()),
          fc.array(fc.anything().map((x) => new RerankedResult(x, {}))),
          arbs.cursorState(),
          fc.nat(),
          fc.string(),
        ];

        fc.assert(
          fc.property(...allArbs, (filter, options, mapping, buffer, state, consumed, qs) => {
            const cursor = new CursorImpl(parent, null!, [filter, false], options, mapping);

            cursor['_currentPage'] = { nextPageState: qs, result: buffer };
            cursor['_state'] = state;
            cursor['_consumed'] = consumed;

            CursorDeltaAsserter
              .captureImmutDelta(cursor, () => {
                return cursor.clone();
              })
              .assertDelta({
                _currentPage: undefined,
                _state: 'idle',
                _consumed: 0,
              });
          }),
        );
      })

Summary: A cloned `Cursor` should return as a new instance with the `_currentPage`, `_state`, and `_consumed` properties reset to specified default values.


test('network info consistency', () => {
    fc.assert(
      fc.property(networkConfig(), (config) => {
        const network = new MockNeuralNetwork(
          config
        ) as any as any as any as any;
        const info = network.getInfo();

        // Input/output sizes should match config
        expect(info.numInputs).toBe(config?.inputSize);
        expect(info.numOutputs).toBe(config?.outputSize);

        // Layer count should be consistent
        expect(info.numLayers).toBe(config?.hiddenLayers.length + 2);

        // Total neurons should be positive
        expect(info.totalNeurons).toBeGreaterThan(0);

        // Memory usage should be reasonable
        expect(info.metrics.memoryUsage).toBeGreaterThan(0);
        expect(info.metrics.memoryUsage).toBeLessThan(1e9); // Less than 1GB
      })
    );
  })

Summary: A neural network's input/output sizes, layer count, total neurons, and memory usage should be consistent with its configuration settings.


it('should create a new cursor with sort vector included', () => {
        fc.assert(
          fc.property(fc.constantFrom(undefined, true, false), arbs.record(fc.anything()), (include, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorInternalDeltaAsserter
              .captureImmutDelta(cursor._internal, () => cursor.includeSortVector(include)._internal)
              .assertDelta({ _options: { ...oldOptions, includeSortVector: include ?? true } });
          }),
        );
      })

Summary: Creating a new cursor should include the sort vector in its options, reflecting whether it is specified as undefined, true, or false.


it('should create a new cursor with the initial page state set if a string', () => {
        fc.assert(
          fc.property(fc.string(), arbs.record(fc.anything()), (pageState, oldOptions) => {
            const cursor = new CursorImpl(parent, null!, [{}, false], oldOptions);

            CursorDeltaAsserter
              .captureImmutDelta(cursor, () => cursor.initialPageState(pageState))
              .assertDelta({ _currentPage: { nextPageState: pageState, result: [] } });
          }),
        );
      })

Summary: A new cursor should be created with the initial page state set when the page state is a string, and this state should reflect in the cursor's current page configuration.


Summary: Creating a new cursor should result in the initial page state being unset when the page state is defined as undefined.


test('parameter bounds validation', () => {
    fc.assert(
      fc.property(
        networkConfig(),
        fc.array(finiteFloat(), { minLength: 100, maxLength: 1000 }),
        (_config, weights) => {
          // All weights should be finite
          const allFinite = weights.every((w) => Number.isFinite(w));
          expect(allFinite).toBe(true);

          // Weights should be in reasonable range for training stability
          const allReasonable = weights.every((w) => Math.abs(w) < 100);
          expect(allReasonable).toBe(true);
        }
      )
    );
  })

Summary: All weights generated for a network configuration must be finite and within a reasonable range for training stability.


test('normalization reversibility', () => {
    fc.assert(
      fc.property(
        fc.array(finiteFloat(), { minLength: 10, maxLength: 100 }),
        (data) => {
          // Skip if all values are the same (stdDev = 0)
          const unique = [...new Set(data)];
          fc.pre(unique.length > 1);

          const mean = data?.reduce((sum, x) => sum + x, 0) / data.length;
          const variance =
            data?.reduce((sum, x) => sum + (x - mean) ** 2, 0) / data.length;
          const stdDev = Math.sqrt(variance);

          const normalized = normalizeData(data);
          const denormalized = denormalizeData(normalized, mean, stdDev);

          // Original data should be approximately restored
          for (let i = 0; i < data.length; i++) {
            expect(denormalized[i]).toBeCloseTo(data?.[i], 5);
          }
        }
      )
    );
  })

Summary: Normalizing and then denormalizing a set of floating-point numbers should approximately restore the original data, assuming the standard deviation is not zero.


test('normalized data properties', () => {
    fc.assert(
      fc.property(
        fc.array(finiteFloat(), { minLength: 10, maxLength: 100 }),
        (data) => {
          const unique = [...new Set(data)];
          fc.pre(unique.length > 1); // Skip constant arrays

          const normalized = normalizeData(data);

          // Mean should be approximately 0
          const mean =
            normalized.reduce((sum, x) => sum + x, 0) / normalized.length;
          expect(Math.abs(mean)).toBeLessThan(1e-10);

          // Standard deviation should be approximately 1
          const variance =
            normalized.reduce((sum, x) => sum + (x - mean) ** 2, 0) /
            normalized.length;
          const stdDev = Math.sqrt(variance);
          expect(Math.abs(stdDev - 1.0)).toBeLessThan(1e-10);

          // All values should be finite
          expect(normalized.every((x) => Number.isFinite(x))).toBe(true);
        }
      )
    );
  })

Summary: Normalized data should have a mean close to 0, a standard deviation close to 1, and all values should be finite.


test('time series window generation correctness', () => {
    fc.assert(
      fc.property(
        fc.array(finiteFloat(), { minLength: 20, maxLength: 100 }),
        fc.integer({ min: 2, max: 10 }),
        fc.integer({ min: 1, max: 5 }),
        (data, windowSize, step) => {
          fc.pre(windowSize <= data.length);

          const windows = createTimeSeriesWindows(data, windowSize, step);

          // Each window should have correct size
          windows.forEach((window) => {
            expect(window).toHaveLength(windowSize);
          });

          // Window count should be correct
          const expectedCount =
            Math.floor((data.length - windowSize) / step) + 1;
          expect(windows.length).toBe(expectedCount);

          // Windows should contain correct subsequences
          for (let i = 0; i < windows.length; i++) {
            const startIndex = i * step;
            for (let j = 0; j < windowSize; j++) {
              expect(windows[i]?.[j]).toBe(data?.[startIndex + j]);
            }
          }
        }
      )
    );
  })

Summary: `createTimeSeriesWindows` correctly generates windows of a specified size and step from input arrays, ensuring that each window contains the appropriate subsequences and matches the expected count.


test('missing value handling consistency', () => {
    fc.assert(
      fc.property(
        fc.array(fc.oneof(finiteFloat(), fc.constant(Number.NaN)), {
          minLength: 5,
          maxLength: 50,
        }),
        fc.constantFrom('mean', 'zero', 'forward_fill'),
        (dataWithNaN, strategy) => {
          const result = handleMissingValues(dataWithNaN, strategy);

          // Result should have same length
          expect(result).toHaveLength(dataWithNaN.length);

          // No NaN values should remain
          expect(result?.every((x) => !Number.isNaN(x))).toBe(true);

          // All values should be finite
          expect(result?.every((x) => Number.isFinite(x))).toBe(true);

          // Non-NaN values should be preserved
          for (let i = 0; i < dataWithNaN.length; i++) {
            if (!Number.isNaN(dataWithNaN?.[i])) {
              expect(result?.[i]).toBe(dataWithNaN?.[i]);
            }
          }
        }
      )
    );
  })

Summary: Handles missing values consistently by replacing NaNs using specified strategies, ensuring the result maintains the same length, contains no NaNs, consists of finite numbers, and preserves original non-NaN values.


test('loss function properties', () => {
    fc.assert(
      fc.property(
        fc.array(smallFloat(), { minLength: 5, maxLength: 20 }),
        fc.array(smallFloat(), { minLength: 5, maxLength: 20 }),
        (predictions, targets) => {
          fc.pre(predictions.length === targets.length);

          // Mean Squared Error
          const mse =
            predictions.reduce(
              (sum, p, i) => sum + (p - targets?.[i]) ** 2,
              0
            ) / predictions.length;

          expect(mse).toBeGreaterThanOrEqual(0);
          expect(Number.isFinite(mse)).toBe(true);

          // MSE should be 0 when predictions equal targets
          const identicalMse =
            predictions.reduce((sum, p) => sum + (p - p) ** 2, 0) /
            predictions.length;
          expect(identicalMse).toBeCloseTo(0, 10);
        }
      )
    );
  })

Summary: The loss function ensures that the Mean Squared Error (MSE) is non-negative and finite, and it is zero when predictions are identical to targets.


it('should return the raw records before any mapping', () => {
        fc.assert(
          fc.property(fc.array(fc.anything()), (buffer) => {
            const cursor = new CursorImpl(parent, null!, [{}, false]).map(() => untouchable());
            cursor['_currentPage'] = { nextPageState: null, result: [...buffer] as SomeDoc[] };
            const consumed = cursor.consumeBuffer();
            assert.deepStrictEqual(consumed, buffer);
          }),
        );
      })

Summary: The `CursorImpl` should return raw records from the buffer before any mapping is applied.


it('should set the state to closed', () => {
        fc.assert(
          fc.property(arbs.cursorState(), (state) => {
            const cursor = new CursorImpl(parent, null!, [{}, false]);
            cursor['_state'] = state;

            DeltaAsserter
              .captureMutDelta(cursor, () => {
                cursor.close();
              })
              .assertDelta({
                _state: 'closed',
              });

            assert.strictEqual(cursor.state, 'closed');
          }),
        );
      })

Summary: The test ensures that calling `close` on a `CursorImpl` sets its state to 'closed'.


test('activation function bounds', () => {
    fc.assert(
      fc.property(finiteFloat(), (x) => {
        // Sigmoid bounds
        const sigmoid = 1 / (1 + Math.exp(-x));
        expect(sigmoid).toBeGreaterThanOrEqual(0);
        expect(sigmoid).toBeLessThanOrEqual(1);
        expect(Number.isFinite(sigmoid)).toBe(true);

        // Tanh bounds
        const tanh = Math.tanh(x);
        expect(tanh).toBeGreaterThanOrEqual(-1);
        expect(tanh).toBeLessThanOrEqual(1);
        expect(Number.isFinite(tanh)).toBe(true);

        // ReLU properties
        const relu = Math.max(0, x);
        expect(relu).toBeGreaterThanOrEqual(0);
        expect(Number.isFinite(relu)).toBe(true);
      })
    );
  })

Summary: The test ensures that for finite float inputs, the sigmoid function output is in [0, 1], the tanh function output is in [-1, 1], and the ReLU function output is non-negative, with all outputs being finite.


test('matrix operations stability', () => {
    fc.assert(
      fc.property(
        fc.array(smallFloat(), { minLength: 4, maxLength: 16 }),
        fc.array(smallFloat(), { minLength: 4, maxLength: 16 }),
        (a, b) => {
          // Simple element-wise operations
          fc.pre(a.length === b.length);

          const sum = a.map((x, i) => x + b[i]);
          const product = a.map((x, i) => x * b[i]);

          // Results should be finite
          expect(sum.every((x) => Number.isFinite(x))).toBe(true);
          expect(product.every((x) => Number.isFinite(x))).toBe(true);

          // Operation properties
          expect(sum).toHaveLength(a.length);
          expect(product).toHaveLength(a.length);
        }
      )
    );
  })

Summary: Element-wise sums and products of two arrays of small floats should be finite and maintain the same length as the input arrays.


test('gradient magnitude bounds', () => {
    fc.assert(
      fc.property(
        fc.array(smallFloat(), { minLength: 10, maxLength: 100 }),
        fc.float({ min: 0.001, max: 0.1 }),
        (weights, learningRate) => {
          // Simulate gradient computation
          const gradients = weights.map((w) => w * 0.1 * (Math.random() - 0.5));

          // Gradients should be finite
          expect(gradients.every((g) => Number.isFinite(g))).toBe(true);

          // Gradient magnitude should be reasonable
          const magnitude = Math.sqrt(
            gradients.reduce((sum, g) => sum + g * g, 0)
          );
          expect(magnitude).toBeLessThan(1000);

          // Weight updates should be stable
          const updatedWeights = weights.map(
            (w, i) => w - learningRate * gradients[i]
          );
          expect(updatedWeights.every((w) => Number.isFinite(w))).toBe(true);
        }
      )
    );
  })

Summary: Tests the generation of finite gradient values, reasonable gradient magnitude, and finite weight updates given arrays of small floats representing weights and a learning rate.


it('should match the root obj when the key is an empty string', () => {
    fc.assert(
      fc.property(arbs.jsonObj(), (obj) => {
        const codec = CodecsClass.forName('', {
          serialize: (v: any, ctx: BaseSerDesCtx) => ctx.done(JSON.stringify(v)),
          deserialize: (v: any, ctx: BaseSerDesCtx) => ctx.done(JSON.stringify(v)),
        });

        const serdes = mkSerDesWithCodecs([codec]);
        const expected = JSON.stringify(obj);

        assert.deepStrictEqual(serdes.serialize(obj), [expected, false]);
        assert.deepStrictEqual(serdes.deserialize(obj, { status: { projectionSchema: {} } }), expected);
      }),
    );
  })

Summary: When using an empty string as the key, the serialized and deserialized output of an object should match its JSON string representation.


test('extreme input values', () => {
    fc.assert(
      fc.property(
        fc.array(
          fc.float({
            min: -1e6,
            max: 1e6,
            noNaN: true,
            noDefaultInfinity: true,
          }),
          {
            minLength: 1,
            maxLength: 10,
          }
        ),
        (extremeInputs) => {
          // Network should handle extreme values gracefully
          const config: NetworkConfig = {
            inputSize: extremeInputs.length,
            hiddenLayers: [{ size: 5, activation: 'sigmoid' }],
            outputSize: 3,
            outputActivation: 'sigmoid',
          };

          const network = new MockNeuralNetwork(config);
          const output = network.predict(extremeInputs);

          // Output should be finite and within bounds for sigmoid
          expect(output.every((x) => Number.isFinite(x))).toBe(true);
          expect(output.every((x) => x >= 0 && x <= 1)).toBe(true);
        }
      )
    );
  })

Summary: The neural network should produce finite outputs within the range [0, 1] for extreme input values without NaN or infinity.


test('malformed data resilience', () => {
    fc.assert(
      fc.property(
        fc.array(
          fc.oneof(
            finiteFloat(),
            fc.constant(Number.NaN),
            fc.constant(Number.POSITIVE_INFINITY),
            fc.constant(Number.NEGATIVE_INFINITY)
          ),
          { minLength: 5, maxLength: 20 }
        ),
        (malformedData) => {
          // Data cleaning should handle malformed inputs
          const cleanedData = malformedData?.map((x) =>
            Number.isFinite(x) ? x : 0
          );

          expect(cleanedData?.every((x) => Number.isFinite(x))).toBe(true);
          expect(cleanedData).toHaveLength(malformedData.length);

          // Missing value handling should work
          const withNaN = malformedData?.map((x) =>
            Number.isFinite(x) ? x : Number.NaN
          );
          const handled = handleMissingValues(withNaN, 'zero');

          expect(handled.every((x) => Number.isFinite(x))).toBe(true);
          expect(handled.every((x) => !Number.isNaN(x))).toBe(true);
        }
      )
    );
  })

Summary: Ensures data cleaning replaces non-finite values with zero and `handleMissingValues` correctly fills missing numeric values, resulting in finite values throughout.


test('distribution preservation in preprocessing', () => {
    fc.assert(
      fc.property(
        fc.array(fc.float({ min: -100, max: 100, noNaN: true }), {
          minLength: 50,
          maxLength: 200,
        }),
        (data) => {
          const unique = [...new Set(data)];
          fc.pre(unique.length > 10); // Ensure sufficient variance

          const normalized = normalizeData(data);

          // Check that relative ordering is preserved
          for (let i = 0; i < data.length - 1; i++) {
            for (let j = i + 1; j < data.length; j++) {
              const originalOrder = data?.[i] <= data?.[j];
              const normalizedOrder = normalized[i] <= normalized[j];
              expect(originalOrder).toBe(normalizedOrder);
            }
          }
        }
      )
    );
  })

Summary: Normalized data maintains the relative ordering of the original data array.


test('correlation preservation', () => {
    fc.assert(
      fc.property(
        fc.array(finiteFloat(), { minLength: 20, maxLength: 50 }),
        fc.float({ min: -2, max: 2 }),
        fc.float({ min: -10, max: 10 }),
        (baseData, correlation, offset) => {
          // Create correlated data
          const correlatedData = baseData?.map(
            (x) => correlation * x + offset + (Math.random() - 0.5) * 0.1
          );

          // Normalize both datasets
          const normalizedBase = normalizeData(baseData);
          const normalizedCorrelated = normalizeData(correlatedData);

          // Calculate correlation coefficients
          const originalCorr = calculateCorrelation(baseData, correlatedData);
          const normalizedCorr = calculateCorrelation(
            normalizedBase,
            normalizedCorrelated
          );

          // Normalization should preserve correlation (within tolerance)
          if (Math.abs(originalCorr) > 0.1) {
            // Only test when correlation is significant
            expect(Math.abs(originalCorr - normalizedCorr)).toBeLessThan(0.1);
          }
        }
      )
    );
  })

Summary: Normalization of datasets should approximately preserve correlation, provided the original correlation is significant.


test('generated', () => {
    fc.assert(
      fc.property(
        fcTsconfig({
          compilerRuleSet: rulesForGenerated,
        }),
        (config) => {
          const validator = new TypeScriptConfigValidator(TypeScriptConfigValidationRuleSet.GENERATED);
          validator.validate(config);
        },
      ),
    );
  })

Summary: The `TypeScriptConfigValidator` validates configurations against the `GENERATED` rule set.


test('alarm thresholds are valid numbers', () => {
    fc.assert(fc.property(
      arbitrary_input_intervals(),
      (intervals) => {
        const template = setupStepScaling(intervals);

        const lowerThreshold = template.lowerThreshold;
        const upperThreshold = template.upperThreshold;

        return reportFalse(
          (lowerThreshold === undefined || (lowerThreshold > 0 && lowerThreshold !== Infinity))
          && (upperThreshold === undefined || (upperThreshold > 0 && upperThreshold !== Infinity)),
          lowerThreshold,
          upperThreshold);
      },
    ));
  })


test('generated step intervals are valid intervals', () => {
    fc.assert(fc.property(
      arbitrary_input_intervals(),
      (intervals) => {
        const template = setupStepScaling(intervals);
        const steps = template.allStepsAbsolute();

        return reportFalse(steps.every(step => {
          return step.MetricIntervalLowerBound! < step.MetricIntervalUpperBound!;
        }), steps, 'template', JSON.stringify(template, undefined, 2));
      },
    ));
  })


test('generated step intervals are nonoverlapping', () => {
    fc.assert(fc.property(
      arbitrary_input_intervals(),
      (intervals) => {
        const template = setupStepScaling(intervals);
        const steps = template.allStepsAbsolute();

        for (let i = 0; i < steps.length; i++) {
          const compareTo = steps.slice(i + 1);
          if (compareTo.some(x => overlaps(steps[i], x))) {
            return reportFalse(false, steps);
          }
        }

        return true;
      },
    ), { verbose: true });
  })


test('all template intervals occur in input array', () => {
    fc.assert(fc.property(
      arbitrary_input_intervals(),
      (intervals) => {
        const template = setupStepScaling(intervals);
        const steps = template.allStepsAbsolute();

        return steps.every(step => {
          return reportFalse(intervals.find(interval => {
            const acceptableLowerBounds = step.MetricIntervalLowerBound === -Infinity ? [undefined, 0] : [undefined, step.MetricIntervalLowerBound];
            // eslint-disable-next-line max-len
            const acceptableUpperBounds = step.MetricIntervalUpperBound === Infinity ? [undefined, Infinity] : [undefined, step.MetricIntervalUpperBound];

            return (acceptableLowerBounds.includes(interval.lower) && acceptableUpperBounds.includes(interval.upper));
          }) !== undefined, step, intervals);
        });
      },
    ));
  })


it("should throw error if private key is not in the prime subgroup l", async () => {
    await fc.assert(
      fc.asyncProperty(fc.bigInt({ min: L, max: r - 1n }), async (privKey: bigint) => {
        const error = await circuit.expectFail({ privKey });

        return error.includes("Assert Failed");
      }),
    );
  })

Summary: Private keys not in the prime subgroup should cause the circuit to throw an error indicating "Assert Failed".


test('lower alarm uses lower policy', () => {
    fc.assert(fc.property(
      arbitrary_input_intervals(),
      (intervals) => {
        const template = setupStepScaling(intervals);
        const alarm = template.resource(template.lowerAlarm);
        fc.pre(alarm !== undefined);

        return reportFalse(alarm.Properties.AlarmActions[0].Ref === template.lowerPolicy, alarm);
      },
    ));
  })


test('upper alarm uses upper policy', () => {
    fc.assert(fc.property(
      arbitrary_input_intervals(),
      (intervals) => {
        const template = setupStepScaling(intervals);
        const alarm = template.resource(template.upperAlarm);
        fc.pre(alarm !== undefined);

        return reportFalse(alarm.Properties.AlarmActions[0].Ref === template.upperPolicy, alarm);
      },
    ));
  })


test('lower alarm index is lower than higher alarm index', () => {
    fc.assert(fc.property(
      arbitrary_complete_intervals(),
      (intervals) => {
        const alarms = findAlarmThresholds(intervals);

        return (alarms.lowerAlarmIntervalIndex === undefined
          || alarms.upperAlarmIntervalIndex === undefined
          || alarms.lowerAlarmIntervalIndex < alarms.upperAlarmIntervalIndex);
      },
    ));
  })


test('never pick undefined intervals for relative alarms', () => {
    fc.assert(fc.property(
      arbitrary_complete_intervals(),
      (intervals) => {
        const alarms = findAlarmThresholds(intervals);

        return (alarms.lowerAlarmIntervalIndex === undefined || intervals[alarms.lowerAlarmIntervalIndex].change !== undefined)
          && (alarms.upperAlarmIntervalIndex === undefined || intervals[alarms.upperAlarmIntervalIndex].change !== undefined);
      },
    ));
  })


test('pick intervals on either side of the undefined interval, if present', () => {
    fc.assert(fc.property(
      arbitrary_complete_intervals(),
      (intervals) => {
        // There must be an undefined interval and it must not be at the edges
        const i = intervals.findIndex(x => x.change === undefined);
        fc.pre(i > 0 && i < intervals.length - 1);

        const alarms = findAlarmThresholds(intervals);
        return (alarms.lowerAlarmIntervalIndex === i - 1 && alarms.upperAlarmIntervalIndex === i + 1);
      },
    ));
  })


test('no picking upper bound infinity for lower alarm', () => {
    fc.assert(fc.property(
      arbitrary_complete_intervals(),
      (intervals) => {
        const alarms = findAlarmThresholds(intervals);
        fc.pre(alarms.lowerAlarmIntervalIndex !== undefined);

        return intervals[alarms.lowerAlarmIntervalIndex!].upper !== Infinity;
      },
    ));
  })


test('no picking lower bound 0 for upper alarm', () => {
    fc.assert(fc.property(
      arbitrary_complete_intervals(),
      (intervals) => {
        const alarms = findAlarmThresholds(intervals);
        fc.pre(alarms.upperAlarmIntervalIndex !== undefined);

        return intervals[alarms.upperAlarmIntervalIndex!].lower !== 0;
      },
    ));
  })


test('every aspect gets executed at most once on every construct', () =>
    fc.assert(
      fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
        afterSynth((testApp) => {
          forEveryVisitPair(testApp.actionLog, (a, b) => {
            if (sameConstruct(a, b) && sameAspect(a, b)) {
              throw new Error(`Duplicate visit: t=${a.index} and t=${b.index}`);
            }
          });
        }, stabilizeAspects)(app);
      }),
    ),
  )


test('all aspects that exist at the start of synthesis get invoked on all nodes in its scope at the start of synthesis', () =>
    fc.assert(
      fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
        const originalConstructsOnApp = app.cdkApp.node.findAll();
        const originalAspectApplications = getAllAspectApplications(originalConstructsOnApp);
        afterSynth((testApp) => {
          const visitsMap = getVisitsMap(testApp.actionLog);

          for (const aspectApplication of originalAspectApplications) {
            // Check that each original AspectApplication also visited all child nodes of its original scope:
            for (const construct of originalConstructsOnApp) {
              if (isAncestorOf(aspectApplication.construct, construct)) {
                if (!visitsMap.get(construct)!.includes(aspectApplication.aspect)) {
                  throw new Error(`Aspect ${aspectApplication.aspect} applied on ${aspectApplication.construct.node.path} did not visit construct ${construct.node.path} in its original scope.`);
                }
              }
            }
          }
        }, stabilizeAspects)(app);
      }),
    ),
  )


test('with stabilization, every aspect applied on the tree eventually executes on all of its nodes in scope', () =>
    fc.assert(
      fc.property(appWithAspects(), (app) => {
        afterSynth((testApp) => {
          const allConstructsOnApp = testApp.cdkApp.node.findAll();
          const allAspectApplications = getAllAspectApplications(allConstructsOnApp);
          const visitsMap = getVisitsMap(testApp.actionLog);

          for (const aspectApplication of allAspectApplications) {
            // Check that each AspectApplication also visited all child nodes of its scope:
            for (const construct of allConstructsOnApp) {
              if (isAncestorOf(aspectApplication.construct, construct)) {
                if (!visitsMap.get(construct)!.includes(aspectApplication.aspect)) {
                  throw new Error(`Aspect ${aspectApplication.aspect.constructor.name} applied on ${aspectApplication.construct.node.path} did not visit construct ${construct.node.path} in its scope.`);
                }
              }
            }
          }
        }, true)(app);
      }),
    ),
  )


test('inherited aspects get invoked before locally defined aspects, if both have the same priority', () =>
    fc.assert(
      fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
        afterSynth((testApp) => {
          forEveryVisitPair(testApp.actionLog, (a, b) => {
            if (!sameConstruct(a, b)) return;
            if (aspectAppliedT(testApp, a.aspect, a.construct) !== -1 ||
              aspectAppliedT(testApp, b.aspect, b.construct) !== -1) return;

            const aPrio = lowestAspectPrioFor(a.aspect, a.construct);
            const bPrio = lowestAspectPrioFor(b.aspect, b.construct);

            if (!(aPrio == bPrio)) return;

            const aInherited = allAncestorAspects(a.construct).includes(a.aspect);
            const bInherited = allAncestorAspects(b.construct).includes(b.aspect);

            if (!(aInherited == true && bInherited == false)) return;

            if (!(a.index < b.index)) {
              throw new Error(
                `Aspect ${a.aspect}@${aPrio} at ${a.index} should have been before ${b.aspect}@${bPrio} at ${b.index}, but was after`,
              );
            }
          });
        }, stabilizeAspects)(app);
      }),
    ),
  )


it(`should check the computation of correct merkle root (level ${level + 1}) [fuzz]`, async () => {
          await fc.assert(
            fc.asyncProperty(generateLeaves(level + 1), async (leaves: bigint[]) => quinCheckRootTest(leaves)),
          );
        })

Summary: The test ensures that generating leaves for a Merkle tree and computing its root verifies the correctness of the root calculation at a specified level.


test('for every construct, lower priorities go before higher priorities', () =>
    fc.assert(
      fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
        afterSynth((testApp) => {
          forEveryVisitPair(testApp.actionLog, (a, b) => {
            if (!sameConstruct(a, b)) return;
            if (aspectAppliedT(testApp, a.aspect, a.construct) !== -1 ||
              aspectAppliedT(testApp, b.aspect, b.construct) !== -1) return;

            const aPrio = lowestAspectPrioFor(a.aspect, a.construct);
            const bPrio = lowestAspectPrioFor(b.aspect, b.construct);

            // But only if the application of aspect A exists at least as long as the application of aspect B
            const aAppliedT = aspectAppliedT(testApp, a.aspect, a.construct);
            const bAppliedT = aspectAppliedT(testApp, b.aspect, b.construct);

            if (!implies(aPrio < bPrio && aAppliedT <= bAppliedT, a.index < b.index)) {
              throw new Error(
                `Aspect ${a.aspect}@${aPrio} at ${a.index} should have been before ${b.aspect}@${bPrio} at ${b.index}, but was after`,
              );
            }
          });
        }, stabilizeAspects)(app);
      }),
    ),
  )


test('for every construct, if a invokes before b that must mean it is of equal or lower priority', () =>
    fc.assert(
      fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
        afterSynth((testApp) => {
          forEveryVisitPair(testApp.actionLog, (a, b) => {
            if (!sameConstruct(a, b)) return;
            if (aspectAppliedT(testApp, a.aspect, a.construct) !== -1 ||
              aspectAppliedT(testApp, b.aspect, b.construct) !== -1) return;

            const aPrio = lowestAspectPrioFor(a.aspect, a.construct);
            const bPrio = lowestAspectPrioFor(b.aspect, b.construct);

            if (!implies(a.index < b.index, aPrio <= bPrio)) {
              throw new Error(
                `Aspect ${a.aspect}@${aPrio} at ${a.index} should have been before ${b.aspect}@${bPrio} at ${b.index}, but was after`,
              );
            }
          });
        }, stabilizeAspects)(app);
      }),
    ),
  )


test('visitLog is nonempty', () =>
  fc.assert(
    fc.property(appWithAspects(), fc.boolean(), (app, stabilizeAspects) => {
      afterSynth((testApp) => {
        expect(testApp.actionLog).not.toEqual([]);
      }, stabilizeAspects)(app);
    }),
  ),
)


test('LinkedQueue behaves the same as array', () => {
  // define the possible commands and their inputs
  const allCommands = [
    fc.string().map((v) => new PushCommand(v)),
    fc.constant(new ShiftCommand()),
  ];

  // run everything
  fc.assert(
    fc.property(fc.commands(allCommands, { size: '+1' }), (cmds) => {
      const s = () => ({
        model: { array: [] } satisfies Model,
        real: new LinkedQueue(),
      });
      fc.modelRun(s, cmds);
    }),
  );
})


asyncTest(async () => {
      const stack = new Stack();
      fc.assert(
        fc.property(
          fc.string(), anyValue,
          (delimiter, value) => _.isEqual(stack.resolve(Fn.join(delimiter, [value as string])), value),
        ),
        { verbose: true },
      );
    })


asyncTest(async () => {
      const stack = new Stack();
      fc.assert(
        fc.property(
          fc.string(), fc.array(nonEmptyString, { minLength: 1, maxLength: 15 }),
          (delimiter, values) => stack.resolve(Fn.join(delimiter, values)) === values.join(delimiter),
        ),
        { verbose: true },
      );
    })


asyncTest(async () => {
      const stack = new Stack();
      fc.assert(
        fc.property(
          fc.string(), fc.array(nonEmptyString, { minLength: 1, maxLength: 3 }), tokenish, fc.array(nonEmptyString, { minLength: 1, maxLength: 3 }),
          (delimiter, prefix, obj, suffix) =>
            _.isEqual(stack.resolve(Fn.join(delimiter, [...prefix, stringToken(obj), ...suffix])),
              { 'Fn::Join': [delimiter, [prefix.join(delimiter), obj, suffix.join(delimiter)]] }),
        ),
        { verbose: true },
      );
    })


asyncTest(async () => {
      const stack = new Stack();
      fc.assert(
        fc.property(
          fc.string(), fc.array(anyValue),
          fc.array(anyValue, { minLength: 1, maxLength: 3 }),
          fc.array(anyValue),
          (delimiter, prefix, nested, suffix) =>
            // Gonna test
            _.isEqual(stack.resolve(Fn.join(delimiter, [...prefix as string[], Fn.join(delimiter, nested as string[]), ...suffix as string[]])),
              stack.resolve(Fn.join(delimiter, [...prefix as string[], ...nested as string[], ...suffix as string[]]))),
        ),
        { verbose: true },
      );
    })


asyncTest(async () => {
      const stack = new Stack();
      fc.assert(
        fc.property(
          fc.string(), fc.string(),
          fc.array(anyValue, { minLength: 1, maxLength: 3 }),
          fc.array(tokenish, { minLength: 2, maxLength: 3 }),
          fc.array(anyValue, { minLength: 3 }),
          (delimiter1, delimiter2, prefix, nested, suffix) => {
            fc.pre(delimiter1 !== delimiter2);
            const join = Fn.join(delimiter1, [...prefix as string[], Fn.join(delimiter2, stringListToken(nested)), ...suffix as string[]]);
            const resolved = stack.resolve(join);
            return resolved['Fn::Join'][1].find((e: any) => typeof e === 'object'
                                                        && ('Fn::Join' in e)
                                                        && e['Fn::Join'][0] === delimiter2) != null;
          },
        ),
        { verbose: true },
      );
    })


test("Property-based testing (fast-check)", () => {
  type Boundaries = {
    min: number;
    max: number;
  };

  const minmax =
    ({ min, max }: Boundaries) =>
    (n: number): number =>
      Math.min(max, Math.max(min, n));

  fc.assert(
    fc.property(fc.integer(), (n): boolean => {
      const result = minmax({ min: 1, max: 10 })(n);
      return 1 <= result && result <= 10;
    })
  );
})


it("return the same value", () => {
      fc.assert(
        fc.property(fc.tuple(fc.integer({ min: 0 }), fc.integer({ min: 0, max: 99999999 })), (v) => {
          const strV = removeTrailingZerosExceptOne(`${v[0]}.${v[1]}`);

          const bv = parseBigInt(strV);
          const r = formatBigInt(bv);
          expect(r).toStrictEqual(strV);
        })
      );
    })


it('Timestamp to DateTime', async () => {
    const dateTimeContract = await loadFixture(fixture)

    await fc.assert(
      fc.asyncProperty(
        fc.integer().filter((x) => x >= 0),
        async (timestamp) => {
          const dateTime = await dateTimeContract.timestampToDateTime(timestamp)
          const date = new Date(timestamp * 1_000)

          expect(dateTime.year.toNumber()).equal(date.getUTCFullYear())
          expect(dateTime.month.toNumber()).equal(date.getUTCMonth() + 1)
          expect(dateTime.day.toNumber()).equal(date.getUTCDate())
          expect(dateTime.hour.toNumber()).equal(date.getUTCHours())
          expect(dateTime.minute.toNumber()).equal(date.getUTCMinutes())
          expect(dateTime.second.toNumber()).equal(date.getUTCSeconds())
        }
      )
    )
  })


it('child transactions should always have a parent_id', async () => {
    await fc.assert(
      fc
        .asyncProperty(fc.array(messageArb, { maxLength: 100 }), async msgs => {
          const tracer = execTracer();
          tracer.start();
          const cleanup = addSyncListener((oldValues, newValues) => {
            const ts = newValues.get('transactions') as Map<
              string,
              { isChild: number; parent_id: string | null; id: string }
            >;
            if (
              ts &&
              [...ts.values()].find(
                t =>
                  t.isChild === 1 && t.parent_id == null && t.id.includes('/'),
              )
            ) {
            } else {
              tracer.event('applied');
            }
          });

          await sendMessages(msgs);
          await tracer.expect('applied');

          const transactions = await db.all<db.DbTransaction>(
            'SELECT * FROM transactions',
            [],
          );
          for (const trans of transactions) {
            const transMsgs = msgs
              .filter(msg => msg.row === trans.id)
              .sort((m1, m2) => {
                const t1 = m1.timestamp.toString();
                const t2 = m2.timestamp.toString();
                if (t1 < t2) {
                  return 1;
                } else if (t1 > t2) {
                  return -1;
                }
                return 0;
              });
            const msg = transMsgs.find(m => m.column === 'parent_id');

            if (
              trans.isChild === 1 &&
              trans.id.includes('/') &&
              (msg == null || msg.value == null)
            ) {
              // This is a child transaction didn't have a `parent_id`
              // set in the messages. It should have gotten set from
              // the `id`
              const [parentId] = trans.id.split('/');
              expect(parentId).not.toBe(null);
              expect(trans.parent_id).toBe(parentId);
            } else if (msg) {
              // At least one message set `parent_id`
              expect(trans.parent_id).toBe(msg.value);
            } else {
              // `parent_id` should never have been set
              expect(trans.parent_id).toBe(null);
            }
          }

          cleanup();
          tracer.end();
        })
        .beforeEach(() => {
          return db.execQuery(`DELETE FROM transactions`);
        }),
    );
  })


it('queries with `splits: inline` returns only non-parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 20,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await aqlQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'inline' })
              .serialize(),
          );

          expect(data.filter(t => t.is_parent).length).toBe(0);
          expect(data.filter(t => t.tombstone).length).toBe(0);

          const { data: defaultData } = await aqlQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .serialize(),
          );

          // inline should be the default
          expect(defaultData).toEqual(data);
        },
      ),
      { numRuns: 50 },
    );
  })


it('queries with `splits: none` returns only parents', async () => {
    await fc.assert(
      fc.asyncProperty(
        arbs.makeTransactionArray({
          splitFreq: 2,
          minLength: 2,
          maxLength: 8,
        }),
        async arr => {
          await insertTransactions(arr);

          const { data } = await aqlQuery(
            q('transactions')
              .filter({ amount: { $lt: 0 } })
              .select('*')
              .options({ splits: 'none' })
              .serialize(),
          );

          expect(data.filter(t => t.is_child).length).toBe(0);
        },
      ),
      { numRuns: 50 },
    );
  })


it('aggregate queries work with `splits: grouped`', async () => {
    const payeeIds = ['payee1', 'payee2', 'payee3', 'payee4', 'payee5'];

    await fc.assert(
      fc
        .asyncProperty(
          arbs.makeTransactionArray({ splitFreq: 2, payeeIds, maxLength: 100 }),
          async arr => {
            await insertTransactions(arr, payeeIds);

            const aggQuery = q('transactions')
              .filter({
                $or: [{ amount: { $lt: -5 } }, { amount: { $gt: -2 } }],
                'payee.name': { $gt: '' },
              })
              .options({ splits: 'grouped' })
              .calculate({ $sum: '$amount' });

            const { data } = await aqlQuery(aggQuery.serialize());

            const sum = aliveTransactions(arr).reduce((sum, trans) => {
              const amount = trans.amount || 0;
              const matched =
                (amount < -5 || amount > -2) && trans.payee != null;
              if (!trans.tombstone && !trans.is_parent && matched) {
                return sum + amount;
              }
              return sum;
            }, 0);

            expect(data).toBe(sum);
          },
        )
        .beforeEach(() => {
          setClock(null);
          setSyncingMode('import');
          return db.execQuery(`
            DELETE FROM transactions;
            DELETE FROM payees;
            DELETE FROM payee_mapping;
          `);
        }),
    );
  }, 20_000)