[Flash Report] Fast sorting & canonical deduplication for rational trees via C foreign predicate (tcoa_sort/2)

I would like to share an experimental C-based foreign predicate, tcoa_sort/2, designed to sort and deduplicate lists of terms (including rational trees/cyclic terms) up to bisimilarity on a 1,000,000-term scale.

  1. Approach Overview
    Based on term_automaton/2: Each term is converted to an automaton representation.
    No automaton_minimal/3: Explicit automaton minimization (e.g., Hopcroft-style partition refinement) is omitted.
    Bisimilarity-driven serialization:
    During serialization into binary canonical keys, the serializer frequently queries a bisimilarity checker (check_bisimilar_states/3) against ancestor nodes to detect cycles and encode back-references.
    Open question: There appears to be a clear design trade-off between “minimizing upfront then trivially serializing” versus “interleaving local bisimilarity queries on the fly during serialization.” Further discussion on this architectural choice is welcome.
  2. Benchmark (1,000,000 Random Terms)
    Comparison with SWI-Prolog’s built-in syntactic sort/2:

(iMac Intele 2020 macOS 26)

?- N = 1000000, length(_Ns, N), maplist(random_term, _Ns),
   time(tcoa_sort(_Ns, _Sorted)),
   time(sort(_Ns, _Sorted0)),
   time(tcoa_sort(_Sorted, _Sorted1)),
   length(_Sorted, L1), length(_Sorted0, L2), length(_Sorted1, C),
   writeln(L1:L2:C).
% 999,999 inferences, 5.650 CPU in 6.244 seconds (1st tcoa_sort)
% -1 inferences,      1.694 CPU in 1.701 seconds (built-in sort)
% 342,675 inferences, 3.661 CPU in 3.788 seconds (2nd tcoa_sort)
342676 : 545461 : 342676

Throughput: Runs at roughly 1/3 the speed of the built-in syntactic sort/2 (~3.3× CPU time), despite performing automaton generation and bisimilarity equivalence checking.
Deduplication power:
Built-in sort/2 (syntactic identity): 545,461 items
tcoa_sort/2 (bisimilarity equivalence): 342,676 items
Cyclic terms with identical unwinding behaviors but differing syntactic unrollings are consolidated into single equivalence classes.
Idempotence:
Running tcoa_sort/2 on the already sorted output yields L1
=C=342,676, verifying idempotence (f(f(X))=f(X)).
Current profiling aims to optimize the implementation further to reach around 1/2 the runtime of built-in sort/2.
3. Open Question: Potential Applications
This project originated as a personal exploratory experiment investigating the limits of C-Prolog interfacing and rational tree representations, without a predetermined target application.
If anyone sees concrete use cases for fast sorting and canonical deduplication of rational trees / automata (e.g., in type systems, model checking, coalgebraic logic programming, or term rewriting), or has perspectives on the on-the-fly bisimilarity-serialization trade-off, comments and insights are welcome.

Promising result! Some questions

  • Is the comparison the same as compare/3 for every pair of terms that can be safely compared?
  • Is it possible to interleave the automaton generation and comparison, i.e., can we decide early or do we have to create both automaton representations first?
  • For sorting, to you first create all automaton instances?

Hi Jan,

Thank you for the thoughtful questions. Here are the details regarding the current implementation:

  • Is the comparison the same as compare/3 for every pair of terms that can be safely compared?

    • Not necessarily identical to standard standard order of terms (@< / @>). Because tcoa_sort/2 sorts based on a canonical binary serialization key (which embeds internal tags, arities, functor atom IDs, and relative cycle distances), the relative ordering between non-identical terms is a consistent total order, but it does not strictly follow standard compare/3. However, for equivalent terms under bisimilarity (e.g., syntactically unrolled variants of the same rational tree), they collapse to identical keys / equivalence classes, yielding =.
  • Is it possible to interleave the automaton generation and comparison, i.e., can we decide early or do we have to create both automaton representations first?

    • In principle, yes (lazy/on-demand construction), but currently no. In the present implementation, term_automaton/2 is invoked upfront per element to produce the full state graph before serialization. Deciding early without constructing the full automaton is feasible if we drive bisimilarity checking on-the-fly directly from the term structure (or explore transitions lazily), which is an interesting direction for reducing overhead on large acyclic subterms.
  • For sorting, do you first create all automaton instances?

    • Yes, in the current pipeline. The input list is traversed sequentially: for each element, term_automaton/2builds the automaton instance, which is immediately serialized into a compact binary buffer within an isolated foreign frame (so temporary terms and string stacks are discarded per element). The array of keys is then sorted via qsort, and the deduplicated result list is constructed at the end.

Am I right that the serialization basically results in a breath-first walk? If I recall well, we already knew that we can resolve the cyclic terms ordering problem using breath-first traversal, no?

If we can implement an efficient complete order, the second question is whether and how to expose this. Possibly as alternative to compare/3, such that binary trees can use it? That would make them safe, but no longer enumerating in ISO standard order.

Actually, it is not a breadth-first walk, but rather a depth-first, left-to-right traversal.

Conceptually, this is closer to a Naish index (or de Bruijn-like indexing for cycles). The primary idea is to reduce the ordering of rational trees to the standard order of finite terms.

Specifically, if we let H be the set of standard finite (Herbrand) terms and R be the rational trees (H \subseteq R), we consider a natural conservative extension H' of H (augmented with cycle/back-reference index tags) and a canonical mapping:

\phi : R \to H'

Because this mapping associates each rational tree with a canonical, finite representative in H', comparing any two rational trees in R simply reduces to the standard total order on H'.

Regarding your second question: exposing an alternative to compare/3 that operates on this total order would indeed make associative containers (like AVL/red-black trees) safe for cyclic terms, even if the ordering departs from the strict ISO standard order for non-equivalent cyclic structures.

Great! Can you share the code, so I can ask Claude to see whether it can merge this with the automaton code?

I have sent in .tar.gz.c. as private mail attachment.
Good luck.

Subject: Follow-up on tg_sort/2: Strict O(mlog⁥n)O(mlogn) Paige-Tarjan Engine

Here is a quick follow-up to my previous flash report.

Rather than resorting to heuristic shortcuts or repeated sorting within refinement steps, I chose to strictly adhere to theoretical principles. The latest tg_sort/2 directly incorporates the true Paige-Tarjan partition refinement algorithm, maintaining the theoretical worst-case bound of O(m \log⁡ n) for term graphs by exploiting ordered transitions (arities) and the “process the smaller half” rule with an explicit predecessor list.

Here is the benchmark for 1,000,000 generated terms:

?- N = 1000000, length(_Ns, N), maplist(random_term, _Ns),
   time(tg_sort(_Ns, _Sorted)),
   time(tg_sort(_Sorted, _Sorted1)),
   time(sort(_Ns, _Sorted0)),
   time(tg_sort(_Sorted0, _Sorted2)),
   length(_Sorted, L1), length(_Sorted0, L2),
   length(_Sorted1, L3), length(_Sorted2, L4).
% 0 inferences, 3.113 CPU in 3.932 seconds (79% CPU, 0 Lips)
% -1 inferences, 0.083 CPU in 0.089 seconds (93% CPU, -12 Lips)
% -1 inferences, 1.672 CPU in 1.677 seconds (100% CPU, -1 Lips)
% -1 inferences, 0.920 CPU in 0.944 seconds (98% CPU, -1 Lips)
N = 1000000,
L1 = L3, L3 = L4, L4 = 73030,
L2 = 545758.

The execution time (3.113 s) is well within twice that of the built-in sort/2 (1.672 s), while reducing 1,000,000 terms down to 73,030 true equivalence classes under maximal bisimulation (idempotence confirmed: L_1 =L_3=L_4 )

I look forward to seeing further refinements and improvements from Jan in the near future.