json_schema icon indicating copy to clipboard operation
json_schema copied to clipboard

Creating a schema asynchronously does not await loading of all sub-schemata and causes validation to spuriously fail

Open bnord01 opened this issue 10 months ago • 1 comments

I have a schema with several (shared) sub-schemata. I've loaded the schema using createAsync and a custom provider that loads the schemata from disk.

The issue I'm facing is that createAsync does not seem to await the loading of all sub-schemata and throws spurious validation errors.

When placing a 1 second delay between creating the schema and using it for validation, validation is successful, which indicates that createAsync spawns some futures which it doesn't await.

Moreover logging when a schema is resolved by the provider indicates, that the required schema was not yet loaded when the validation failed.

Setup

  final schema = await JsonSchema.createAsync(mainSchemaContent,
      schemaVersion: SchemaVersion.draft7, refProvider: RefProvider.async(
    (String ref) async {
      final resolvedPath = ref.replaceFirst(remotePath, localPath);
      print("DEBUG: Resolved $resolvedPath");
      return jsonDecode(await File(resolvedPath).readAsString());
    },
  ));

  // await Future.delayed(Duration(seconds: 1)); // With this validation is successful 

  final result = schema.validate(jsonData);
  
  if (result.isValid) {
    print('JSON is valid');
  } else {
    print('JSON is invalid:');
    for (final error in result.errors) {
      print('VALIDATION ERROR: [${error.instancePath}] ${error.message}');
    }
  }

Output indicating that the sub-schema is only loaded after the validation spuriously failed.

DEBUG: Resolved jsonschema/properties.schema.json
DEBUG: Resolved jsonschema/property.schema.json
DEBUG: Resolved jsonschema/values/value.schema.json
....

JSON is invalid:
VALIDATION ERROR: [/properties/title] unallowed additional property defaultValue
...

DEBUG: Resolved jsonschema/values/property-value.schema.json <- referenced by value.schema.json, defines defaultValue
... 

bnord01 avatar Mar 07 '25 14:03 bnord01

Thanks for bringing this one to our attention!

michaelcarter-wf avatar Mar 07 '25 14:03 michaelcarter-wf