openassistant: intent extraction now validates primitive field types
- Commit
2d266788bd40e14abe2c0b28088dfe647b658463- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 07:14 UTC (5 days ago)
- Parents
afacc3b
JsonSchemaValidator.validateType only checked object and
array and fell through to 'valid' for string, number,
integer, boolean and null, at top level and recursively for
every property. The validator is the only gate before
InferenceService.runIntentInference sends RESULT_OK with
the extracted JSON (both the streaming early-halt and the
final check), so {"name":123} against a string-typed
schema halted generation early and was delivered to caller
apps over the IPC contract as a successful extraction.
validateType now enforces the five primitive types (quoted
digits are not numbers, booleans are not numbers, only
integral numerics are integers), with path-prefixed error
messages in the existing style; unknown type names keep the
prior ignore behaviour. Two regression tests failed
pre-fix: primitive type enforcement, and the service-level
test asserting the receiver now gets an error rather than
RESULT_OK. Conversation, tool-loop and streaming paths were
audited and cleared. Verified: :openassistant:
testDevUnitTest and :openassistant:lint BUILD SUCCESSFUL.Diff
openassistant/src/main/java/com/vayunmathur/openassistant/domain/JsonSchemaValidator.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/JsonSchemaValidator.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/JsonSchemaValidator.ktindex a6b9f88a63..858c4797f0 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/JsonSchemaValidator.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/JsonSchemaValidator.kt@@ -4,8 +4,12 @@ import com.vayunmathur.library.log.Log import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement+import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.doubleOrNull+import kotlinx.serialization.json.longOrNull /** Singleton holding json schema validator state and operations. */ object JsonSchemaValidator {@@ -104,9 +108,38 @@ object JsonSchemaValidator { if (expectedType == "array" && data !is JsonArray) { return "${pathPrefix}Expected an array but got ${data::class.simpleName}" }+ // Primitive types are enforced too: without this, {"name": 123}+ // satisfied {"name": {"type": "string"}} and the extraction gate+ // handed caller apps wrongly-typed JSON as a successful result.+ val primitiveOk = when (expectedType) {+ "string" -> (data as? JsonPrimitive)?.isString == true+ "boolean" -> (data as? JsonPrimitive)?.let { !it.isString && it.booleanOrNull != null } == true+ "number" -> (data as? JsonPrimitive)?.let { !it.isString && it.doubleOrNull != null } == true+ "integer" -> (data as? JsonPrimitive)?.let { prim ->+ !prim.isString && (prim.longOrNull != null ||+ prim.doubleOrNull?.let { it % 1.0 == 0.0 } == true)+ } == true+ "null" -> data is JsonNull+ else -> return null+ }+ if (!primitiveOk) {+ return "${pathPrefix}Expected $expectedType but got ${jsonKind(data)}"+ } return null } + /** JSON Schema kind name of [data], for type-mismatch messages. */+ private fun jsonKind(data: JsonElement): String = when (data) {+ is JsonObject -> "object"+ is JsonArray -> "array"+ is JsonNull -> "null"+ is JsonPrimitive -> when {+ data.isString -> "string"+ data.booleanOrNull != null -> "boolean"+ else -> "number"+ }+ }+ private fun validateObject(data: JsonObject, schema: JsonObject, path: String): String? { checkUnknownFields(data, schema, path)?.let { return it } checkRequiredFields(data, schema, path)?.let { return it }
openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.ktindex d229a51f1f..7e9d1551cc 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/InferenceServiceFakeEngineTest.kt@@ -300,6 +300,21 @@ class InferenceServiceFakeEngineTest { assertEquals(0, code); assertEquals("""{"name":"Ada"}""", data?.getString("json_result")) } + @Test fun intentInferenceRejectsWronglyTypedFields() {+ // The schema says "name" is a string; a numeric name must not be+ // delivered to the caller as a successful extraction.+ val receiver = CapturingReceiver()+ val schema = """{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}"""+ val fake = FakeEngine(extractBehavior = { _, onText -> onText("""{"name":123}"""); """{"name":123}""" })+ val service = startService(fake)+ val intent = Intent(ctx, InferenceService::class.java).apply {+ putExtra("user_text", "extract"); putExtra("schema", schema); putExtra("RECEIVER", receiver)+ }+ service.onStartCommand(intent, 0, 1)+ assertTrue(receiver.latch.await(15, TimeUnit.SECONDS), "receiver should get an error result")+ assertEquals(-1, synchronized(receiver.results) { receiver.results.first().first })+ }+ @Test fun intentInferenceSchemaMismatchAndNullReplyError() { val receiver = CapturingReceiver() val schema = """{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}"""
openassistant/src/test/java/com/vayunmathur/openassistant/util/JsonValidationTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/JsonValidationTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/JsonValidationTest.ktindex 32eedd35dc..364fd82960 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/JsonValidationTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/JsonValidationTest.kt@@ -41,6 +41,36 @@ class JsonValidationTest { assertTrue(nested!!.contains("at outer.inner"), nested) } + @Test fun primitiveTypesAreEnforced() {+ // A property declared as a string must not accept a number: the+ // extraction gate is the only check before a caller app is handed+ // the JSON as a successful result.+ val nameSchema = """{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}"""+ assertNull(validate("""{"name":"Ada"}""", nameSchema))+ val numName = validate("""{"name":123}""", nameSchema)+ assertTrue(numName!!.contains("name"), numName)+ assertTrue(numName.contains("string"), numName)++ // Top-level primitive types are checked too, not just properties.+ assertNull(validate(""" "hello" """, """{"type":"string"}"""))+ assertNotNull(validate("""123""", """{"type":"string"}"""))+ assertNotNull(validate("""{"a":1}""", """{"type":"string"}"""))++ // Numbers: a quoted digit string is not a number, a boolean is not+ // a number, and only integral numbers satisfy "integer".+ val countSchema = """{"type":"object","properties":{"count":{"type":"integer"},"score":{"type":"number"}}}"""+ assertNull(validate("""{"count":3,"score":1.5}""", countSchema))+ assertNotNull(validate("""{"count":3.5,"score":1.5}""", countSchema))+ assertNotNull(validate("""{"count":"3","score":1.5}""", countSchema))+ assertNotNull(validate("""{"count":3,"score":true}""", countSchema))++ // Booleans and null.+ val flagSchema = """{"type":"object","properties":{"ok":{"type":"boolean"},"note":{"type":"null"}}}"""+ assertNull(validate("""{"ok":true,"note":null}""", flagSchema))+ assertNotNull(validate("""{"ok":"true","note":null}""", flagSchema))+ assertNotNull(validate("""{"ok":false,"note":"x"}""", flagSchema))+ }+ @Test fun unknownAndRequiredFields() { val schema = """{"type":"object","properties":{"name":{}},"required":["name","id"]}""" assertTrue(validate("""{"name":"x","extra":1,"id":2}""", schema)!!.contains("Unexpected field found: 'extra'"))