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7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
diff --git a/datafusion/core/tests/extension_types/mod.rs b/datafusion/core/tests/extension_types/mod.rs
--- a/datafusion/core/tests/extension_types/mod.rs
+++ b/datafusion/core/tests/extension_types/mod.rs
@@ -15,4 +15,5 @@
 // specific language governing permissions and limitations
 // under the License.
 
+mod lolbench_aug;
 mod pretty_printing;
diff --git a/datafusion/core/tests/extension_types/lolbench_aug.rs b/datafusion/core/tests/extension_types/lolbench_aug.rs
new file mode 100644
index 000000000..8f23e1ab9
--- /dev/null
+++ b/datafusion/core/tests/extension_types/lolbench_aug.rs
@@ -0,0 +1,462 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use arrow::array::{Array, FixedSizeBinaryArray, Int32Array, RecordBatch, StringArray};
+use arrow::util::display::{ArrayFormatter, DisplayIndex, FormatOptions, FormatResult};
+use arrow_schema::extension::{ExtensionType, Uuid};
+use arrow_schema::{ArrowError, DataType, Field, Schema};
+use datafusion::error::Result;
+use datafusion::execution::SessionStateBuilder;
+use datafusion::prelude::SessionContext;
+use datafusion_common::HashMap as DFHashMap;
+use datafusion_common::types::DFExtensionType;
+use datafusion_expr::registry::{
+    DefaultExtensionTypeRegistration, ExtensionTypeRegistration, ExtensionTypeRegistry, ExtensionTypeRegistryRef,
+    MemoryExtensionTypeRegistry,
+};
+use insta::assert_snapshot;
+use std::collections::HashMap;
+use std::fmt::{Debug, Write};
+use std::sync::Arc;
+
+const EXTENSION_NAME_KEY: &str = "ARROW:extension:name";
+const EXTENSION_METADATA_KEY: &str = "ARROW:extension:metadata";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum ScoreStyle {
+    Raw,
+    Bracketed,
+}
+
+#[derive(Debug, Clone, Copy)]
+struct ScoreExtensionType {
+    style: ScoreStyle,
+}
+
+impl ScoreExtensionType {
+    const NAME_VALUE: &'static str = "lolbench.score";
+
+    fn new(style: ScoreStyle) -> Self {
+        Self { style }
+    }
+}
+
+impl ExtensionType for ScoreExtensionType {
+    const NAME: &'static str = Self::NAME_VALUE;
+    type Metadata = ScoreStyle;
+
+    fn metadata(&self) -> &Self::Metadata {
+        &self.style
+    }
+
+    fn serialize_metadata(&self) -> Option<String> {
+        Some(
+            match self.style {
+                ScoreStyle::Raw => "raw",
+                ScoreStyle::Bracketed => "bracketed",
+            }
+            .to_string(),
+        )
+    }
+
+    fn deserialize_metadata(
+        metadata: Option<&str>,
+    ) -> std::result::Result<Self::Metadata, ArrowError> {
+        match metadata {
+            Some("raw") => Ok(ScoreStyle::Raw),
+            Some("bracketed") => Ok(ScoreStyle::Bracketed),
+            Some(other) => Err(ArrowError::InvalidArgumentError(format!(
+                "invalid score metadata: {other}"
+            ))),
+            None => Ok(ScoreStyle::Raw),
+        }
+    }
+
+    fn supports_data_type(
+        &self,
+        data_type: &DataType,
+    ) -> std::result::Result<(), ArrowError> {
+        if data_type == &DataType::Int32 {
+            Ok(())
+        } else {
+            Err(ArrowError::InvalidArgumentError(format!(
+                "score extension requires Int32 storage, got {data_type}"
+            )))
+        }
+    }
+
+    fn try_new(
+        data_type: &DataType,
+        metadata: Self::Metadata,
+    ) -> std::result::Result<Self, ArrowError> {
+        let instance = Self::new(metadata);
+        instance.supports_data_type(data_type)?;
+        Ok(instance)
+    }
+}
+
+impl DFExtensionType for ScoreExtensionType {
+    fn storage_type(&self) -> DataType {
+        DataType::Int32
+    }
+
+    fn serialize_metadata(&self) -> Option<String> {
+        ExtensionType::serialize_metadata(self)
+    }
+
+    fn create_array_formatter<'fmt>(
+        &self,
+        array: &'fmt dyn Array,
+        options: &FormatOptions<'fmt>,
+    ) -> Result<Option<ArrayFormatter<'fmt>>> {
+        let Some(values) = array.as_any().downcast_ref::<Int32Array>() else {
+            return Ok(None);
+        };
+        let display_index = ScoreDisplayIndex {
+            values,
+            null_str: options.null(),
+            style: self.style,
+        };
+        Ok(Some(ArrayFormatter::new(
+            Box::new(display_index),
+            options.safe(),
+        )))
+    }
+}
+
+#[derive(Debug)]
+struct ScoreDisplayIndex<'a> {
+    values: &'a Int32Array,
+    null_str: &'a str,
+    style: ScoreStyle,
+}
+
+impl DisplayIndex for ScoreDisplayIndex<'_> {
+    fn write(&self, idx: usize, f: &mut dyn Write) -> FormatResult {
+        if self.values.is_null(idx) {
+            write!(f, "{}", self.null_str)?;
+            return Ok(());
+        }
+
+        match self.style {
+            ScoreStyle::Raw => write!(f, "score={}", self.values.value(idx))?,
+            ScoreStyle::Bracketed => write!(f, "[{}]", self.values.value(idx))?,
+        }
+        Ok(())
+    }
+}
+
+#[derive(Debug, Clone, Copy)]
+struct UnknownScoreExtensionType;
+
+impl ExtensionType for UnknownScoreExtensionType {
+    const NAME: &'static str = "lolbench.unknown_score";
+    type Metadata = ();
+
+    fn metadata(&self) -> &Self::Metadata {
+        &()
+    }
+
+    fn serialize_metadata(&self) -> Option<String> {
+        None
+    }
+
+    fn deserialize_metadata(
+        _metadata: Option<&str>,
+    ) -> std::result::Result<Self::Metadata, ArrowError> {
+        Ok(())
+    }
+
+    fn supports_data_type(
+        &self,
+        data_type: &DataType,
+    ) -> std::result::Result<(), ArrowError> {
+        if data_type == &DataType::Int32 {
+            Ok(())
+        } else {
+            Err(ArrowError::InvalidArgumentError(format!(
+                "unknown score extension requires Int32 storage, got {data_type}"
+            )))
+        }
+    }
+
+    fn try_new(
+        data_type: &DataType,
+        metadata: Self::Metadata,
+    ) -> std::result::Result<Self, ArrowError> {
+        let instance = Self;
+        let _ = metadata;
+        instance.supports_data_type(data_type)?;
+        Ok(instance)
+    }
+}
+
+#[derive(Debug)]
+struct NoFormatterExtensionType;
+
+impl DFExtensionType for NoFormatterExtensionType {
+    fn storage_type(&self) -> DataType {
+        DataType::Int32
+    }
+
+    fn serialize_metadata(&self) -> Option<String> {
+        None
+    }
+}
+
+fn score_registration() -> datafusion_expr::registry::ExtensionTypeRegistrationRef {
+    DefaultExtensionTypeRegistration::new_arc(|_storage_type, metadata| {
+        Ok(ScoreExtensionType::new(metadata))
+    })
+}
+
+fn registry_with_score_type() -> Result<ExtensionTypeRegistryRef> {
+    let registry = MemoryExtensionTypeRegistry::new_empty();
+    registry.add_extension_type_registration(score_registration())?;
+    Ok(Arc::new(registry))
+}
+
+fn context_with_registry(registry: ExtensionTypeRegistryRef) -> SessionContext {
+    let state = SessionStateBuilder::default()
+        .with_extension_type_registry(registry)
+        .build();
+    SessionContext::new_with_state(state)
+}
+
+fn score_field(name: &str, style: ScoreStyle) -> Field {
+    Field::new(name, DataType::Int32, true)
+        .with_extension_type(ScoreExtensionType::new(style))
+}
+
+fn manual_extension_field(name: &str, data_type: DataType, type_name: &str, metadata: &str) -> Field {
+    Field::new(name, data_type, false).with_metadata(HashMap::from([
+        (EXTENSION_NAME_KEY.to_string(), type_name.to_string()),
+        (EXTENSION_METADATA_KEY.to_string(), metadata.to_string()),
+    ]))
+}
+
+async fn table_string(
+    ctx: &SessionContext,
+    table_name: &str,
+    batch: RecordBatch,
+) -> Result<String> {
+    ctx.register_batch(table_name, batch)?;
+    ctx.table(table_name).await?.to_string().await
+}
+
+#[tokio::test]
+async fn lolbench_aug_canonical_uuid_uses_default_registry() -> Result<()> {
+    let ctx = context_with_registry(Arc::new(
+        MemoryExtensionTypeRegistry::new_with_canonical_extension_types(),
+    ));
+    let schema = Arc::new(Schema::new(vec![
+        Field::new("uuid_value", DataType::FixedSizeBinary(16), false)
+            .with_extension_type(Uuid),
+    ]));
+    let batch = RecordBatch::try_new(
+        schema,
+        vec![Arc::new(FixedSizeBinaryArray::from(vec![&[
+            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
+        ][..]]))],
+    )?;
+    let result = table_string(&ctx, "uuid_defaults", batch).await?;
+
+    assert_snapshot!(
+        result,
+        @r"
+    +--------------------------------------+
+    | uuid_value                           |
+    +--------------------------------------+
+    | 00010203-0405-0607-0809-0a0b0c0d0e0f |
+    +--------------------------------------+
+    "
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn lolbench_aug_unknown_extension_falls_back_to_default_display() -> Result<()> {
+    let schema = Arc::new(Schema::new(vec![
+        Field::new("plain_value", DataType::Int32, false)
+            .with_extension_type(UnknownScoreExtensionType),
+    ]));
+    let batch = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![42]))])?;
+    let result = table_string(&SessionContext::new(), "unknown_extension", batch).await?;
+
+    assert_snapshot!(
+        result,
+        @r"
+    +-------------+
+    | plain_value |
+    +-------------+
+    | 42          |
+    +-------------+
+    "
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn lolbench_aug_metadata_drives_registered_formatter() -> Result<()> {
+    let ctx = context_with_registry(registry_with_score_type()?);
+    let schema = Arc::new(Schema::new(vec![
+        score_field("raw_score", ScoreStyle::Raw),
+        score_field("bracketed_score", ScoreStyle::Bracketed),
+    ]));
+    let batch = RecordBatch::try_new(
+        schema,
+        vec![
+            Arc::new(Int32Array::from(vec![7, 9])),
+            Arc::new(Int32Array::from(vec![7, 9])),
+        ],
+    )?;
+    let result = table_string(&ctx, "score_metadata", batch).await?;
+
+    assert_snapshot!(
+        result,
+        @r"
+    +-----------+-----------------+
+    | raw_score | bracketed_score |
+    +-----------+-----------------+
+    | score=7   | [7]             |
+    | score=9   | [9]             |
+    +-----------+-----------------+
+    "
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn lolbench_aug_storage_type_mismatch_is_rejected() -> Result<()> {
+    let ctx = context_with_registry(registry_with_score_type()?);
+    let schema = Arc::new(Schema::new(vec![manual_extension_field(
+        "bad_score",
+        DataType::Utf8,
+        ScoreExtensionType::NAME,
+        "bracketed",
+    )]));
+    let batch = RecordBatch::try_new(
+        schema,
+        vec![Arc::new(StringArray::from(vec!["not-an-int"]))],
+    )?;
+    ctx.register_batch("bad_score_storage", batch)?;
+    let err = ctx
+        .table("bad_score_storage")
+        .await?
+        .to_string()
+        .await
+        .expect_err("mismatched extension storage must be rejected");
+    assert!(
+        err.to_string()
+            .contains(""),
+        "unexpected error: {err}"
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn lolbench_aug_dynamic_registration_can_be_removed() -> Result<()> {
+    let registry = Arc::new(MemoryExtensionTypeRegistry::new_empty());
+    registry.add_extension_type_registration(score_registration())?;
+
+    let ctx = context_with_registry(registry.clone());
+    let schema = Arc::new(Schema::new(vec![score_field(
+        "score",
+        ScoreStyle::Bracketed,
+    )]));
+    let batch = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![11]))])?;
+    let result = table_string(&ctx, "registered_scores", batch).await?;
+    assert!(result.contains("[11]"), "registered formatter was not used: {result}");
+
+    let removed = registry.remove_extension_type_registration(ScoreExtensionType::NAME)?;
+    assert!(removed.is_some(), "expected score registration to be removed");
+
+    let ctx = context_with_registry(registry);
+    let schema = Arc::new(Schema::new(vec![score_field(
+        "score",
+        ScoreStyle::Bracketed,
+    )]));
+    let batch = RecordBatch::try_new(schema, vec![Arc::new(Int32Array::from(vec![11]))])?;
+    let result = table_string(&ctx, "removed_scores", batch).await?;
+    assert!(
+        result.contains("| 11    |"),
+        "removed registration should use default formatting: {result}"
+    );
+    assert!(
+        !result.contains("[11]"),
+        "removed registration still used custom formatting: {result}"
+    );
+    Ok(())
+}
+
+#[tokio::test]
+async fn lolbench_aug_registry_api_round_trips_registered_fields() -> Result<()> {
+    let registration = score_registration();
+    assert!(
+        registration.type_name() == ScoreExtensionType::NAME,
+        "registration should name the extension type via type_name()"
+    );
+
+    let registry = MemoryExtensionTypeRegistry::new_with_types([registration])?;
+    assert_eq!(registry.all_extension_types().len(), 1);
+    assert_eq!(registry.extension_type_registrations().len(), 1);
+    assert!(
+        registry
+            .create_extension_type_for_field(&Field::new("plain", DataType::Int32, false))?
+            .is_none(),
+        "plain fields should not resolve to a DataFusion extension type"
+    );
+
+    let extension_type = registry
+        .create_extension_type_for_field(&score_field("score", ScoreStyle::Bracketed))?
+        .expect("registered score field should resolve to an extension type");
+    assert_eq!(extension_type.storage_type(), DataType::Int32);
+    assert_eq!(
+        extension_type.serialize_metadata().as_deref(),
+        Some("bracketed")
+    );
+
+    let empty_registry = MemoryExtensionTypeRegistry::new_empty();
+    empty_registry.extend(&[score_registration()])?;
+    assert_eq!(empty_registry.all_extension_types().len(), 1);
+
+    let mut registrations = DFHashMap::new();
+    registrations.insert(ScoreExtensionType::NAME.to_string(), score_registration());
+    let from_map = MemoryExtensionTypeRegistry::from(registrations);
+    assert_eq!(from_map.extension_type_registrations().len(), 1);
+    Ok(())
+}
+
+#[tokio::test]
+async fn lolbench_aug_default_formatter_hook_falls_back() -> Result<()> {
+    let values = Int32Array::from(vec![1]);
+    let no_formatter = NoFormatterExtensionType;
+    assert!(
+        no_formatter
+            .create_array_formatter(&values, &FormatOptions::default())?
+            .is_none(),
+        "extension types without a formatter should fall back to Arrow formatting"
+    );
+
+    let uuid = Uuid;
+    assert_eq!(
+        <Uuid as DFExtensionType>::storage_type(&uuid),
+        DataType::FixedSizeBinary(16)
+    );
+    assert_eq!(<Uuid as DFExtensionType>::serialize_metadata(&uuid), None);
+    Ok(())
+}
diff --git a/datafusion/expr-common/src/type_coercion/binary/tests/comparison.rs b/datafusion/expr-common/src/type_coercion/binary/tests/comparison.rs
--- a/datafusion/expr-common/src/type_coercion/binary/tests/comparison.rs
+++ b/datafusion/expr-common/src/type_coercion/binary/tests/comparison.rs
@@ -95,6 +95,16 @@ fn test_like_coercion() {
         Some(DataType::LargeUtf8)
     );
 }
+
+#[test]
+fn lolbench_aug_like_binary_utf8_stays_unchanged() {
+    test_like_rule!(DataType::Binary, DataType::Utf8, Some(DataType::Utf8));
+    test_like_rule!(DataType::LargeBinary, DataType::Utf8, Some(DataType::LargeUtf8));
+    assert_eq!(
+        like_coercion(&DataType::Utf8, &DataType::LargeUtf8),
+        Some(DataType::LargeUtf8)
+    );
+}
 
 #[test]
 fn test_type_coercion() -> Result<()> {