{"record":{"id":"fdf0463410e50e7a","repo":"prestodb/presto","slug":"invalid-function-argument-fdf046","errorCode":"INVALID_FUNCTION_ARGUMENT","errorMessage":"Error applying key function to element at position %d","messagePattern":"Error applying key function to element at position (.+?)","errorType":"error_code","errorClass":"PrestoException","httpStatus":null,"severity":"error","filePath":"presto-main-base/src/main/java/com/facebook/presto/operator/scalar/AbstractArraySortByKeyFunction.java","lineNumber":174,"sourceCode":"        }\n\n        // Create array of indices and extracted keys\n        int[] indices = new int[arrayLength];\n        BlockBuilder keyBlockBuilder = keyType.createBlockBuilder(null, arrayLength);\n\n        // Extract keys for all elements\n        for (int i = 0; i < arrayLength; i++) {\n            indices[i] = i;\n            if (array.isNull(i)) {\n                keyBlockBuilder.appendNull();\n            }\n            else {\n                try {\n                    // Use the generated KeyExtractor implementation (direct virtual call)\n                    keyExtractor.extract(properties, array, i, keyFunction, keyBlockBuilder);\n                }\n                catch (Throwable t) {\n                    throw new PrestoException(INVALID_FUNCTION_ARGUMENT, String.format(\"Error applying key function to element at position %d\", i), t);\n                }\n            }\n        }\n\n        Block keysBlock = keyBlockBuilder.build();\n\n        // Sort indices based on extracted keys using Type's compareTo\n        try {\n            if (array.mayHaveNull() || keysBlock.mayHaveNull()) {\n                quickSort(indices, new NullableComparator(array, keysBlock, keyType, function));\n            }\n            else {\n                quickSort(indices, new NonNullableComparator(keysBlock, keyType, function));\n            }\n        }\n        catch (NotSupportedException | UnsupportedOperationException e) {\n            throw new PrestoException(INVALID_FUNCTION_ARGUMENT, \"Key type does not support comparison\", e);\n        }","sourceCodeStart":156,"sourceCodeEnd":192,"githubUrl":"https://github.com/prestodb/presto/blob/55bb57d202de3b926896fa966c2c4a44c779634e/presto-main-base/src/main/java/com/facebook/presto/operator/scalar/AbstractArraySortByKeyFunction.java#L156-L192","documentation":"array_sort_by's key function is invoked per element via the generated KeyExtractor (keyExtractor.extract). If the lambda throws for any element, the wrapper rethrows as INVALID_FUNCTION_ARGUMENT with the offending element position so the caller knows which array entry broke the key function. This is a guard around user-supplied lambdas that Presto cannot validate at bind time.","triggerScenarios":"Calling array_sort_by(arr, k -> ...) where the key lambda throws for element i — e.g. element_at on an out-of-range index, arithmetic overflow, a map lookup missing the key with a failing accessor, or a division by zero inside the lambda.","commonSituations":"Sorting arrays of maps/rows where some elements lack the key the lambda extracts; null-handling mistakes in the key expression; malformed data rows in nested collections.","solutions":["Inspect element at the reported position in the input array; fix or filter out the value the key function cannot handle.","Make the key lambda null-safe and total (use COALESCE/IF/try() style logic inside the lambda).","Filter the array first: array_sort_by(filter(arr, x -> key is valid), k).","If using map element access, provide defaults instead of assuming the key exists."],"exampleFix":"// before\narray_sort_by(a, x -> element_at(x, 'k')) -- throws if 'k' missing\n// after\narray_sort_by(a, x -> coalesce(element_at(x, 'k'), 0))","handlingStrategy":"validation","validationCode":"-- verify the key lambda is total over all elements\nSELECT array_position(transform(a, x -> key(x)), NULL) IS NULL AS key_safe FROM t","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Make key lambdas null-safe with COALESCE/IF","Filter invalid elements before sorting","Test key lambdas on production-shaped data including NULLs"],"tags":["array","lambda","invalid-argument"],"backgroundTag":"key-function-threw","analyzedSha":"55bb57d202de3b926896fa966c2c4a44c779634e","analyzedAt":"2026-09-04T12:50:26.162Z","contentChangedAt":"2026-09-04T12:50:26.162Z","schemaVersion":2},"datasetVersion":"2026-09-11T21:17:09.523Z"}