<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dogelog Player on Medium]]></title>
        <description><![CDATA[Stories by Dogelog Player on Medium]]></description>
        <link>https://medium.com/@janburse_2989?source=rss-fb70175bc0bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Av1qxZ2EwG1mse6MFnAL1g.jpeg</url>
            <title>Stories by Dogelog Player on Medium</title>
            <link>https://medium.com/@janburse_2989?source=rss-fb70175bc0bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:42:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@janburse_2989/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Tao’s EQT on a Budget Laptop]]></title>
            <link>https://medium.com/@janburse_2989/alepotrypa-lovers-taos-eqt-on-a-budget-laptop-7ee8c9631d9f?source=rss-fb70175bc0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ee8c9631d9f</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[prolog]]></category>
            <category><![CDATA[eqt]]></category>
            <dc:creator><![CDATA[Dogelog Player]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 11:07:33 GMT</pubDate>
            <atom:updated>2026-11-07T14:05:02.311Z</atom:updated>
            <content:encoded><![CDATA[<p>Like complementing lovers, Mace4 can show non-existence of a proof by a counter example, while Prover9 can exhibit a specimen of a proof for a formalizable problem. We wrote small 100% Prolog versions that can attack a majority of Tao’s EQT problems on a budget laptop.</p><h4>Backtracking Hashtables</h4><p>Although both problems are theoretical hopeless, the minimum known results is that proofs in FOL are semi-decidable, while existence of a FOL counter model is even not semi-deciable. Nevertheless, just like zombies, Mace4 and Prover9 regularly reemerge from their tombs.</p><p>The appeal of Mace4 derives from the fact, that finite counter models are nevertheless enumerable, making the subproblem of finite satisfiablility of FOL formulas semi-decidable. Our 100% Prolog implementation is stripped down to only deal with universally quantified equations.</p><p>Our mainloop does mainly guesses entries of a Cayley table:</p><pre>/* without hash table */<br>find([], _, R, R) :- !.<br>find(L, N, R, S) :-<br>   cell(L, C, N, X),<br>   T = [C-X|R],<br>   foldl(reduce_axiom(T), L, H, []),<br>   find(H, N, T, S).</pre><p>The reduce then applies what is currently known for the Cayley table to the already expanded axioms. The xpansion depends on the chosen domain size k, it replaces the universal quantifer ∀x E(x) by the conjunction E(0) .. E(k-1). The method succeeds when all can be reduced to true.</p><p>To speed up the Cayley table we use our backtrackable hashtable:</p><pre>/* with hash table */<br>find([], _, R, R) :- !.<br>find(L, N, R, S) :-<br>   cell(L, C, N, X),<br>   hash_add(R, C, X, T),<br>   foldl(reduce_axiom(T), L, H, []),<br>   find(H, N, T, S).</pre><p>A backtrackable hashtable is a data structure that always preserves the previous version of itself when it is modified. Our hashtable is from Dogelog Players library(util/hash). It works with open lists and relies on fast built-ins such as term_hash/2 and (==)/2.</p><h4>Complaining via Models</h4><p>The Terrence Tao’s EQT challenge is a list of equations over a function signature (*)/2. No associativity or commutativity is assumed, and the thus completely unrestrained model structure related to the signature is called a magma in relation to the Terrence Tao’s EQT challenge.</p><p>The list of equations and their numbering serves as a reference point, and for two equations E1 and E2, the challenge is to decide the implication E1 =&gt; E2, i.e. that every model of E1 is also a model of E2. A counter model shows the impossibility by a model that satisfies E1 &amp; ~E2.</p><p>Such challenges were also offered by SAIR, and we found:</p><pre>/* https://competition.sair.foundation/competitions */<br>data(4164-3927, x*y = y*y*x*x, x*y = x*(y*y)*x, 0).</pre><p>While many corners of the world are currently busy to give their systems an option to generate certificates that show the facts and rules used in a derivation of a statement, which is then called an explanation. We can go on and call a counter model a complaint, a different kind of certificate.</p><p>For finite models the complaint is just a Cayley table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*DkBrZvh8aBLibQvo6fhJ1A.png" /></figure><h4>Non-Backtracking Hashtables</h4><p>There exists the orthodoxy of Knuth Bendix algorithms. We had problems following the orthodoxy since some of its assumptions might never be satisfied, like for example a finite completion of the given equations, so that one is left with interleaving the completion with normalizing.</p><p>We found Eilenberg-MacLane ideas appealing, since it can viewed normalizing also happening for proof paths, and not only for terms. But still we had no use for it, since our proof paths are relatively short. So that we fell back to IDA*, iterative deepening with a heuristic function:</p><pre>/* without hash table */<br>find(T, T, _, _, []).<br>find(T, S, K, M, [(P,Q)-H|E]) :-<br>   J is K+1,<br>   rewrite(T, H, P, Q),<br>   heuristic(H, S, J, N),<br>   N &lt; M,<br>   find(H, S, J, M, E).</pre><p>It does implicitly proof normalization by finding shortest proofs. While the benefit of using iterative deepening is a very small memory footprint, the drawback is a lot of redundant work, and thus long compute time. So one will typically look into methods related to SOS from Prover9.</p><p>We used non-backtrackable hashtable for a simple SOS cache:</p><pre>/* with hash table */<br>find(T, T, _, _, [], _).<br>find(T, S, K, M, [(P,Q)-H|E], Hash) :-<br>   J is K+1,<br>   rewrite(T, H, P, Q),<br>   heuristic(H, S, J, N),<br>   N &lt; M,<br>   \+ (numbervars(H, -1, _),<br>       used(Hash, H, N)),<br>   find(H, S, J, M, E, Hash).</pre><p>A non-backtrackable hashtable is what one is usually comfortable with from imperative programming languages. In the present case it is implemented via change_arg/3, a feature that is available in Dogelog Player and that can imperatively change a Prolog compound.</p><h4>Explaining via Proofs</h4><p>The presence of SOS can reduce the search time in favor of more memory consumption. Nevertheless our method clearly hits a wall. For example we currently cannot prove the famous 650–448, inside a constraint of a minute. While an online WASM version of Prover9 can do it easily.</p><p>But as the previous code snippets show, we also produce a list element [(P,Q)-H|E]. The pair (P,Q) records the rewriting that happened, by the term path P and therule Q. So our routine produces a certificate. In as far our method doesn’t need a Prover9 and Vampire combo to extract proofs.</p><p>To probe certificates generation we use data from Tao’s EQT challenge:</p><pre>/* https://arxiv.org/abs/2512.07087v2 */<br>data(3973-4023, x * y = (y * (z * x)) * z, x * y = (z * (z * x)) * y, 1).<br><br>/* https://competition.sair.foundation/competitions */<br>data(4208-3879, x * y = z * y * x * x, x * x = y * (x * x) * z, 1).<br><br>/* https://arxiv.org/abs/2605.21200v1 */<br>data(650-448, x = x * (y * ((z * x) * y)), x = x * (y * (z * (x * z))), 1).</pre><p>The list can be displayed similar to what Lean calls an equivalent proof by small-step equational reasoning. We abstain from showing what Prolog unification exactly did. In particular rule invocation can add new variables which we number ‘$VAR’(1), ‘$VAR’(2), .. and display as A, B, …</p><p>The proof certificates are the lists written as numbered table rows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*sqKSWwiR0ytThTkpjypqkw.png" /></figure><h4>Tao’s EQT</h4><p>Running some toy examples helps in debugging the 100% Prolog code and get a first grip on how it performs. To dig deeper into its performance we compared to some reported results from the SAIR competition, where equations were fed to LLMs. In particular we picked EQT01–000092:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*UxOmzAvMhRqOquDC86BvLA.png" /></figure><p>The SAIR competition also worked with standing prompts to direct the LLMs towards certain thought patterns. The above data is from the combo_jack entry by Reza Jamei. We computed the time and accuracy via the sizes of the sets hard2 (200) and hard3 (400).</p><p>Our little Prolog system massively excels in accuracy and time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*oRTz5C-L3wZSd_moGN4I6w.png" /></figure><p>Since (255+252)/(255+40+252+53) = 0.845 we left handedly reach an accuracy of 84.5%, that is ca. 20% more than the LLMs could do. Further since (8136.361+66601.298)/600 = 124.5, the average time for each case was 124.5 ms. That’s a 200–400x faster speed than the LLMs.</p><p>The comparison we did, was clearly David against Goliath, since we run on a budget laptop, with a memory constraint of -Xmx2g for the Java VM. While the LLMs had cheap price measured in token. Its per time energy consumption is much higher, and multiplies into the longer runtime.</p><p>But there is a warning. For simplicity we used the answer=”true” and answer=”false” field from the JSON data of the test cases as additional problem information, in that we direct the benchmark directly to either Mace4 or Prover9, and didn’t do a double search.</p><h4>Conclusions</h4><p>Our 100% Prolog code makes heavy use of hashtables, in their backtracking and non-backtracking form. The final David against Goliath benchmark, where we compare with LLM results from SAIR, is in favor of our David with an average of 20% more accuracy and 200–400x more speed.</p><p>See also:</p><p><strong>GitHub Repository — Tao’s EQT</strong><br><a href="https://github.com/Jean-Luc-Picard-2021/eqtlovers/tree/main">https://github.com/Jean-Luc-Picard-2021/eqtlovers/tree/main</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ee8c9631d9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dogelog Player: Dining Philosophers with when/2]]></title>
            <link>https://medium.com/@janburse_2989/dogelog-player-dining-philosophers-with-when-2-bc3103c2d544?source=rss-fb70175bc0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc3103c2d544</guid>
            <category><![CDATA[dining]]></category>
            <category><![CDATA[when]]></category>
            <category><![CDATA[prolog]]></category>
            <dc:creator><![CDATA[Dogelog Player]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 23:34:33 GMT</pubDate>
            <atom:updated>2026-10-22T23:35:31.702Z</atom:updated>
            <content:encoded><![CDATA[<p>Prolog systems with attribute variables saw growing use cases for constraint logic programming with implementations such as CLP(FD), CLP(B), etc.. for example in SWI-Prolog. But one might wonder why they are also associated with concurrent logic programming.</p><h4>Lazy Lists</h4><p>Dogelog Player is a Prolog system for the JavaScript, Python and Java target, mostly written in 100% Prolog. The library(edge/attrvars) realizes attributed variables in 100% Prolog as well, and intially came with freeze/2 for suspension, bind/2 for wakeup and deref/2 for access.</p><p>Meanwhile bind/2, which could only deal with var-term events, has been repaced by unify/2, which can also deal with var-var events. There is a also dif/2 available. The suspension and wakeup mechanism has been migrated from open lists to the open trees with lower append complexity.</p><p>Unlike dif/2 which wakes up on var-var events, freeze/2 only wakes up the given goal when the given term observes a var-term event. The principle of lazy lists is then simply, that a consumer can trigger the production of a list element H, by simply unifying with a cons cell [H|_].</p><pre>takedrop(0, L, [], L) :- !.<br>takedrop(N, L, [H|R], S) :- N &gt; 0,<br>   advance(L, H, T),<br>   M is N-1,<br>   takedrop(M, T, R, S).<br><br>advance(X, H, T) :-<br>   unify(X, [H|T]).</pre><p>Besides an explicit unify/2 above, Fibonnacci needs an explicit deref/2:</p><pre>fib(L, X, Y) :-<br>    freeze(L, (deref(L, R), fib2(R, X, Y))).<br><br>fib2([Y|L], X, Y) :-<br>   Z is X+Y,<br>   fib(L, Z, X).</pre><p>Seems to work fine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*xuYmSUv_b5eyw3IPUit6iw.png" /></figure><h4>‘$LATCH’/2 Gadget</h4><p>Lazy lists were among the means to provide channels in the Fifth Generation Computer Systems (FGCS) project in the early 1980s. After burning $340M, there were sequential machines arriving at 1.4 MLips, and parallel machines arriving at 200 MLips.</p><p>While freeze/2 triggers on a single given term, one might want to trigger on more complex conditions. Already our dif/2 implemetation does that. To avoid double firing a little gadget is described in a SICStus Prolog paper by Mats Carlsson. For our dif/2 we got away with a single latch variable:</p><pre>% &#39;$LATCH&#39;(+Var, +Goal)<br>&#39;$LATCH&#39;(V, G) :- var(V), !, V = 1, G.<br>&#39;$LATCH&#39;(_, _).</pre><p>So for more complex conditions all we have to do is select some guard variables and suspend with the help of ‘$LATCH’/2 gadget. This gives us more headroom, since the wakeup mechanism of library(edge/attrvars) schedules in a FIFO manner without goal deduplication.</p><p>Missing guard variables bear the cost of inaction. For example if occurs_check=false, then dif(X, f(Y)), Y = g(X) can suspend with dif(X, f(g(X))), no need to guard the variable Y. With occurs_check=true and guarding the variable Y, we can trigger and remove dif(X, f(g(X))).</p><h4>Disjunctive Suspension</h4><p>We currently find different implementions of selecting guard variables. While SWI-Prolog and formerly Jekejeke Prolog compute a front, newer Prolog systems from the Scryer Prolog family are not as sophisticated yet. But the front calculation can be done in a few lines of Prolog code:</p><pre>front((A,B), C, L) :- front(A, X, L), !,<br>   C = (X,B).<br>front((_,B), Y, R) :- !,<br>   front(B, Y, R).<br>front((A;B), C, M) :- !,<br>   front(A, X, L),<br>   front(B, Y, R),<br>   append(L, R, M),<br>   C = (X;Y).<br>front(nonvar(T), C, M) :- !,<br>   front_nonvar(T, C, M).</pre><p>The above implementation assumes that front_nonvar/3 succeeds with a nonvar(T) goal in C and a front [T] in M, if a nonvar(V) needs suspension, and otherwise fails. The rest of front/3 implementation resembles computing the front terminal of a grammer. It is then used for:</p><pre>% when(+Goal, +Goal)<br>when(C, G) :-<br>   front(C, D, L), !,<br>   attach(L, when(D, G)).<br>when(_, G) :- G.</pre><p>In practice append/2 in front/3 should be replaced by an attributed variables deduplicating predicate. The attach/2 predicate is an utility that does a simple freeze when the list L is a singleton. Otherwise does a multiple freeze of a ‘$LATCH’/2 compound if the list is a multiton.</p><h4>Round Robin</h4><p>The remaining sections are devoted to the Dining Philosopher problem, an example problem often used in concurrent algorithm design to illustrate synchronization issues and techniques for resolving them. Only we will use coroutining via when/2 and discrete simulation.</p><p>The discrete simulation will advance a state space of 5 forks S1,..,S5:</p><pre>table(T) :-<br>   T = [S1,S2,S3,S4,S5],<br>   philo(1, S1, S2),<br>   philo(2, S2, S3),<br>   philo(3, S3, S4),<br>   philo(4, S4, S5),<br>   philo(5, S5, S1).</pre><p>Each fork is as lazy stream, and each philosopher focuses on two of them:</p><pre>philo(N, L, R) :-<br>   when((nonvar(L), nonvar(R)),<br>   (deref(L, L2), deref(R, R2), philo2(N, L2, R2))).<br><br>philo2(N, [N|L], [N|R]) :- !,<br>   philo(N, L, R).<br>philo2(N, [_|L], [_|R]) :-<br>   philo(N, L, R).</pre><p>Since the philosophers are numbered 1..5, we can use these numbers as an exclusion and reservation mechanism. That a philosopher takes two forks and eats for a while, is modelled as a discrete step, where a philosopher can simultaneously put his label on two forks.</p><p>The round robin scheduler simply triggers each fork in input order:</p><pre>% run(+List)<br>run(T) :-<br>   maplist(advance, T, H, R),<br>   write(H), nl,<br>   sleep(1),<br>   run(R).</pre><p>Sadly, the result is more than half of the philosophers will starve to death:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*Vj8ewwrRhskRLZ9xz_rQjg.png" /></figure><h4>Alternate Schedulers</h4><p>The round robin scheduler results in starvation. In particular the input order makes it that philosopher 1 and 3 always get a pair of forks, while the philosopher 2, 4 and 5 never get a pair of forks. An algorithmic solution to avoid starvation is seen below, we just added a rotation step:</p><pre>?- table(T), run_rotate(T).<br>[1, 1, 3, 3, _0]<br>[5, 5, 2, 2, _1]<br>[4, 4, 1, 1, _2]<br>🚨 Fehler: Ausführung auf Benutzerwunsch abgebrochen.<br> user auf 2</pre><p>“Planwirtschaft” algorithmic solutions can provide equal share fairness, but they might require some additional instrumentation and incure bureau- cratic costs. If we bet on randomness, we are heading towards “Invisble Hand” solutions. Now fairness is viewed as equal chance:</p><pre>?- table(T), run_random(T).<br>[1, 1, 3, 3, _3]<br>[2, 4, 2, 4, _4]<br>[2, 5, 5, 2, _5]<br>🚨 Fehler: Ausführung auf Benutzerwunsch abgebrochen.<br> user auf 5</pre><p>Similar starvation can lead to global suspension. The query ?- freeze(X, between(1,2,X)), dif(X,1), it will not show X = 2, instead it will suspend the two subgoals. Remedies are constraint logic programming libraries such as CLP(Z), etc.. and/or custom attribute variable programming.</p><h4>Epoche Reclamation</h4><p>The reclamation of attributed variables consitutes a resembling problem. The Prolog system is embedded into a compute environment, and has to deal with other Dining Philosophers sitting at the same table, such as a operating system, a database management systems, etc...</p><p>The dispute is about shares in processing, memory, etc.. We already could test the reclamation of attributed variables in the case of dif/2 in a previous blog. We successfully replicated some test cases in Ulrich Neumerkel paper from 2008 about Precise Garbage Collection in Prolog.</p><p>To probe the reclamation in when/2 we consider the infinite loop:</p><pre>% test_random<br>test_random :-<br>   table(T),<br>   loop_random(T).<br><br>% loop_random(+List)<br>loop_random(T) :-<br>   maplist(advance, T, _, R),<br>   random_permutation(R, S),<br>   loop_random(S).</pre><p>Our testing campaign shows these results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*EBmaIylvBo22vwfEOaE5xQ.png" /></figure><p>The loop was run for 120 seconds with a memory limit of 2g. The upcoming Dogelog Player release 2.3.3, as well as the current SWI-Prolog release 10.1.18 reach the time limit without an out of memory abend. What pays off in our case, is the recently introduced heap pressure garbage collector.</p><h4>Conclusions</h4><p>The new when/2 primitive allows scheduling goals on multiple events. By modelling eating forks via lazy lists, we could replicated the Dining Philosopher problem. The lazy lists need to be scheduled by an additional program and we can show that such a scheduler can run forever.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc3103c2d544" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dogelog Player: Heap Pressure for Garbage Collection]]></title>
            <link>https://medium.com/@janburse_2989/dogelog-player-heap-pressure-for-garbage-collection-5791ef8834d5?source=rss-fb70175bc0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5791ef8834d5</guid>
            <category><![CDATA[cg]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[prolog]]></category>
            <dc:creator><![CDATA[Dogelog Player]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 01:16:16 GMT</pubDate>
            <atom:updated>2026-10-15T14:26:30.132Z</atom:updated>
            <content:encoded><![CDATA[<p>Dogelog Player is a Prolog system for the JavaScript, Python and Java targets. It is mostly written in 100% Prolog. Our garbage collector already used GC frequency autotuning via user_time. We added a GC generation choice autotuning feature using user_memory.</p><h4>Metronome Collector</h4><p>A prominent source for advanced garbage collection concerning the WAM are the SICStus Prolog papers by Matt Carlsson et al. from the 80s. Dogelog Player borrowed the trail sweep and compaction. But otherwise delegates to the host programming language garbage collector.</p><p>In its early stage, Dogelog Player had a single generation mark &amp; sweep garbage collector, that was user_time and user_memory agnostic. The heuristic was to measure the trail length, since this is what our garbage collector reduces, before the host programming language takes over.</p><p>Meanwhile Dogelog Player abandoned measuring the trail length, and went for a metronome garbage collector, together with an incremental minor garbage collection phase, which decides which nursery Prolog logical variables are either removed or land in the old generation.</p><pre>###<br># Old policy:<br># - Regular major GC based on metronome tock<br># - Otherwise perform minor GC<br>##<br>def gc_run():<br>    if gc_enter &gt;= gc_tock:<br>        gc_major()<br>        gc_tock += 3600*gc_maxinfs<br>    else:<br>        gc_minor()</pre><p>gc_run() is called from the Prolog solver based on the logical inference counter. Since RAM and CPU speeds varies, logical inferences per second (LIPS) also varies. The current version autotunes the GC frequency via user_time so that gc_run() is called every second.</p><h4>Remembered Sets</h4><p>The GC generation is decided in gc_run(). The current policy is such that a major mark &amp; sweep is called every 60 seconds, otherwise the remaining 59 times, a minor generational mark &amp; sweep is called. Old generation Prolog logical variables that get bound again form a remembered set.</p><p>During the next minor generational mark &amp; sweep, the remembered set will be used as additional marking roots. Unfortunately, this extends the old generation. For certain programs this old generation can indefinitely grow, and will only be reclaimed if there is a major mark &amp; sweep.</p><p>This runaway effect can for example be observed here:</p><pre>test :- <br>   T = [_,_,_,_,_],<br>   loop(T).<br><br>loop(T) :-<br>   maplist(snoc, T, R, _),<br>   loop(R).<br><br>snoc(X, T, H) :-<br>   X = [H|T].</pre><p>For Dogelog Player 2.3.2 all targets fail the test case:</p><pre>/* Java */<br>?- time(call_with_time_limit(120000, test)).<br>% Zeit 75626.377 ms, Benutzer 100 %, Lips 1602 k<br>🚨 Fehler: Ausführung wegen aufgebrauchtem Speicherplatz abgebrochen.<br>    user auf 2<br><br>/* JavaScript */<br>?- time(call_with_time_limit(120000, test)).<br>&lt;--- Last few GCs ---&gt;<br><br>/* Python */<br>?- time(call_with_time_limit(120000, test)).<br>RPython traceback:</pre><p>Ulrich Neumerkel’s paper about Precise Garbage Collection in Prolog from 2008 shows similar test cases. The corresponding stress tests consist of an indefinitely running tail recursive program. In the following we will show how to address the major mark &amp; sweep timing problem.</p><h4>Used Memory</h4><p>The potpourri of the Precise Garbage Collection paper shows examples beyond the major mark &amp; sweep timing problem in loop/1. These extended examples are based on problems with choice points or attributed variables. The SICStus Prolog papers show according refinements.</p><p>To solve the major mark &amp; sweep timing problem we aim at measuring heap pressure and then drop the minor generational mark &amp; sweep in favor of a major mark &amp; sweep. The idea is to measure the used memory and compare it to a soft limit derived from max memory.</p><p>We had a “used” statistics, could extend it to PyPy:</p><pre>def used_memory():<br>    if platform.python_implementation() == &quot;PyPy&quot;:<br>        stats = gc._get_stats()<br>        return (stats.total_gc_memory+<br>                stats.total_memory_pressure+<br>                stats.jit_backend_used)<br>    else:<br>        return 0</pre><p>A new “maxmem“ statistics was introduced, again for PyPy:</p><pre>def max_memory():<br>    if platform.python_implementation() == &quot;PyPy&quot;:<br>        maxstr = os.environ.get(&quot;PYPY_GC_MAX&quot;, None)<br>        if maxstr is None:<br>            return 0<br>        maxstr = maxstr.upper()<br>        if maxstr.endswith(&quot;B&quot;):<br>            maxstr = maxstr[:-1]<br>        i = 0<br>        mult = 1<br>        while i &lt; 3:<br>            if maxstr.endswith(&quot;KMG&quot;[i]):<br>                mult = 1024**(i+1)<br>                maxstr = maxstr[:-1]<br>                break<br>            i += 1<br>        return int(float(maxstr)*mult)<br>    else:<br>        return 0</pre><p>Our code base now offers similar implementations for JavaScript and Java besides the above Python code. In all cases the value 0 means that the corresponding “statistics” is not available. Dogelog Player can still fall back to the metronome collector, use program options or default values.</p><h4>Heap Pressure</h4><p>To avoid repeated CPU-intensive max_memory() we store the value in variable gc_maxmem. The current heuristic is to use 75% of gc_maxmem as a soft limit to trigger an emergency major mark &amp; sweep. The corresponding Python code reads as follows:</p><pre>###<br># New policy:<br># - Regular major GC based on metronome tock<br># - Emergency major GC based on soft limit<br># - Otherwise perform minor GC<br>##<br>def gc_run():<br>    if gc_enter &gt;= gc_tock:<br>        gc_major()<br>        gc_tock += 3600*gc_maxinfs<br>    elif (gc_maxmem != 0 and<br>        used_memory() &gt; gc_maxmem * 3 / 4):<br>        gc_major()<br>        gc_tock += 60*gc_maxinfs<br>    else:<br>        gc_minor()</pre><p>To analyse the problem we used JConsole live view of GC from JDK 26 and tapped into the running Dogelog Player 2.3.2 for Java. We saw that the Java old generation continuously grew, mirroring the old generation of Prolog logical variables and Prolog compounds that were clogging.</p><p>With the regular-only policy the timing was indeed the culprit:</p><pre>/* regular-only */<br>?- time(call_with_time_limit(120000, test)).<br> min min min min min min min min min min<br>% Zeit 76844.937 ms, Benutzer 100 %, Lips 1570 k<br>🚨 Fehler: Ausführung wegen aufgebrauchtem Speicherplatz abgebrochen.<br>    user auf 2<br><br></pre><p>With the regular-and-emergency policy the problem disappears:</p><pre>/* regular-and-emergency */<br>?- time(call_with_time_limit(120000, test)).<br> min min<br>maj min<br>maj<br>maj min min<br>maj<br>maj min min min Etc..</pre><h4>Benchmark Results</h4><p>We implemented the new policy for all targets JavaScript, Python and Java. On the upside the test case now passes, the Prolog system can run loop/1 indefinitely. On the downside the logical inferences per second (LIPS) drop considerably, since major mark &amp; sweep is costly.</p><p>The downside is well known, it has a couple of negative side effects such as noticeable pauses and/or memory thrashing. More disturbingly, repeated major mark &amp; sweep do traverse the same roots redundantly. Remedies are additional generations and/or incremental major mark &amp; sweep.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*shd_0HYH-Mq49XlQSh1LtA.png" /></figure><p>The above diagram shows a LIPS comparison, higher is better. The testing campaign included all of our budget AI laptops, with CPUs such as a Ryzen AI 7 350 (Ryzen), Intel(R) Core(TM) Ultra 7 258V (Yoga), Snapdragon(R) X — X126100 (Think) and Apple A18 Pro (Neo), without virtual memory.</p><p>The degradation is not observed for SWI-Prolog, even with set_prolog_flag( stack_limit, 2147483648) it stays around 45 MLips for the Ryzen CPU without and with pressure. While our own Prolog system drops from 30 to 10 MLips for the Ryzen CPU and the Java target.</p><p>The results for Think show a problem in the availability of host language compilers resp. virtual machines. SWI-Prolog suffers in that their Windows cross-compilation for ARM64 drops the baseline from 45 to 20 MLips. We are similarly unlucky with the Microsoft JDK for ARM64.</p><h4>Conclusions</h4><p>The heuristic is to use 75% of max_memory as a limit for user_memory to trigger an emergency major mark &amp; sweep. The Dogelog Player can now run loop/1 indefinitely. Less welcome is the performance drop from 30 to 10 MLips. SWI-Prolog does not show the same degradation.</p><p>See also:</p><p><strong>Precise Garbage Collection in Prolog</strong><br><a href="https://www.complang.tuwien.ac.at/ulrich/papers/PDF/2008-ciclops.pdf">https://www.complang.tuwien.ac.at/ulrich/papers/PDF/2008-ciclops.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5791ef8834d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The implementation of dif/2 with Open Trees]]></title>
            <link>https://medium.com/@janburse_2989/dogelog-player-the-implementation-of-dif-2-with-open-trees-6e2914596a0f?source=rss-fb70175bc0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e2914596a0f</guid>
            <category><![CDATA[prolog]]></category>
            <category><![CDATA[reclamation]]></category>
            <category><![CDATA[dif]]></category>
            <dc:creator><![CDATA[Dogelog Player]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 08:03:24 GMT</pubDate>
            <atom:updated>2026-10-07T10:37:21.151Z</atom:updated>
            <content:encoded><![CDATA[<p>In the following we show that P(purity) has currently almost zero probability, i.e that a Prolog system will provide the first pillar of purity, i.e. the dif/2 constraint. Even if a Prolog system can deal with a large number of dif/2 constraints, it might still fail the reclamation test.</p><h4>Attributed Variables</h4><p>In the first iteration of library(edge/attrvars) we provided modelling constraints explicitly by ‘$ATTR’/2 compounds. The idea is not new, was already present in Ulrich Neumerkel’s Extensible Unification by Metastructures, 1990. Less than a year ago we used ‘$ATTR’/2 for CLP(Z).</p><p>The motivation to use ‘$ATTR’/2 compounds was mainly the progression of our Prolog system Dogelog Player. The system had matured that it could deal with cyclic terms, and the Metastructures would be naturally cyclic for the simple case of freeze/2. Moreover we had bind/2 for var=term events.</p><pre>/* append another list to an open list */<br>% sys_attr_conc(+List, +List)<br>sys_attr_conc(V, R) :- var(V), !, <br>   V = R.<br>sys_attr_conc([_|L], R) :- <br>   sys_attr_conc(L, R).</pre><p>The ‘$ATTR’/2 compounds itself used open lists to hold a multitude of suspended goals. The realization of open lists is pretty much Prolog folklore. We went with the above primitive to extend the 2nd argument of ‘$ATTR’/2 by a given other list, either open or closed.</p><h4>Open Trees</h4><p>It recently emerged that open lists are not extremely suitable for frequent adding of constraints. The problem is the sys_attr_conc/2 has to reach the end of the list, before it can use ordinary unification to extend the list. So recently we step over open trees, with a similar API:</p><pre>/* append another tree to an open tree */<br>% sys_attr_conc(+Tree, +Integer, +Tree).<br>sys_attr_conc(V, _, N) :- var(V), !,<br>   V = N.<br>sys_attr_conc(node(L, _, R), D, N) :- var(R),<br>   E is D-2, E &gt;= 0,<br>   sys_attr_conc(L, E, N), !.<br>sys_attr_conc(node(_, _, R), D, N) :-<br>   E is D-1, E &gt;= 0,<br>   sys_attr_conc(R, E, N).</pre><p>The above implementation is loosely motivated by the trees of bounded balance as found in Nievergelt &amp; Reingold from 1972. The Prolog code profits from the var(R) check as a signpost, by using asymmetric decrement we give the resulting tree a progressive shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*yR7wnzQDzbge4s_dCOrg8w.png" /></figure><p>We do currently no rebalancing, so if we hit the given limit the open tree is considered to be full, and a buffer overflow is thrown. Open trees obviously are backtracking datastructure just like open lists. The above empirically shows O(log N) performance of trees versus the O(N) of lists.</p><h4>Implementing dif/2</h4><p>While Ulrich Neumerkel’s sketches resemble rather a when/2 implementation of dif/2, where a when/2 uses some frontier suspension strategy, ignoring the instantiation of later variables. We think this doesn’t lead to a early firing dif/2. So we went with the solved form approach.</p><p>A unification problem of the form s = t of two terms s and t can be viewed as turning the problem into a solved form v1 = t1, .., vn=tn where v1, .., vn are variables and t1, .., tn are terms not necessarily disjoint from the variables. The SWI-Prolog predicate unifiable/3 yields such a list.</p><p>To implement dif/2 we realized the same via 100% Prolog:</p><pre>% sys_unifiable(+Term, +Term, +Map, -Map)<br>sys_unifiable(X, Y, P, Q) :- var(X), var(Y), X == Y, !,<br>   Q = P.<br>sys_unifiable(X, Y, P, Q) :- var(Y), !,<br>   Q = [Y-X|P].<br>sys_unifiable(X, Y, P, Q) :- var(X), !,<br>   Q = [X-Y|P].<br>sys_unifiable(X, Y, P, Q) :- compound(X), compound(Y), !,<br>   functor(X,F,N), functor(Y,G,M),<br>   F/N == G/M,<br>   X =.. [_|L], Y =.. [_|R],<br>   foldl(unifiable, L, R, P, Q).<br>sys_unifiable(X, Y, P, Q) :- X == Y,<br>   Q = P.</pre><p>The predicate sys_unifiable threads an accumulator with the solved form. The solve form is also used inside deref/2, a 100% Prolog implementation for the usual dereferencing of Prolog logical variables, but doing a lookup in the solved form. A dif/2 reduction is then readily implemented as:</p><pre>% reduce(+Goal, -Goal)<br>reduce(dif(S, T), M) :-<br>   unifiable(S, T, [], Q), !,<br>   Q \== [],<br>   triage(Q, L, R),<br>   M = dif(L,R).<br>reduce(dif(_, _), true).</pre><p>The above implementation has everything that is needed to reduce a dif/2 constraint. It has the success result returning a new goal true, if the two terms are not unifiable. It has the failure result, if they are unifiable and there is nothing to suspend. And it has the maybe result with dif(L, R).</p><h4>Performance Results</h4><p>To put our solution into perspective, we then went on a testing campaign. By using a similar approach like unifiable/4 we also implemented unify/2 for our new development branch of library(edge/attrvars). The later can be used where (=)/2 is suspected to involve attributed variables. We tested:</p><pre>test(N) :-<br>   length(Xs, N),<br>   dif(V, X), dif(V, Xs),<br>   maplist(dif(X), Xs),<br>   fail.<br>test(_).</pre><p>It’s a test case that currently bogs down Scryer Prolog. By our survey, we could reveal that it is also enemy to Prolog systems such as Trealla Prolog and EyeProlog. Prolog systems that were unimpressed were SWI-Prolog and our Dogelog Player development branch, as this cactus plot shows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*VlIehL6wLHokPoexgpKYFA.png" /></figure><p>The methodology in our testing was to use a logarithmic scale on the y-axis and progressively test N=2,4,8,etc.. At the same time measuring the milliseconds to execute test/1. We then stopped testing when 1000 ms were reached. The result gives a good overview of the current limitations.</p><h4>Space Reclamation</h4><p>We used the previous data to devise a memory consumption test. Prolog systems that can trim the Prolog variable trail are able to garbage collect open lists and open trees. So attributed variables that make use of such ordinary Prolog terms can reclaim constraint space.</p><p>The alternative technique to ordinary Prolog terms are value trails that are then accessed via setarg/3 or put_attr/2. That these implementations might nevertheless have space reclamation issues was already addressed by Ulrich Neumerkel’s Precise Garbage Collection in Prolog paper from 2008.</p><p>Our development branch should reclaim garbage created by tidy/1:</p><pre>tidy(N) :-<br>   length(Xs, N),<br>   dif(V, X), dif(V, Xs),<br>   maplist(dif(X), Xs).<br><br>loop(N) :- tidy(N), loop(N)</pre><p>For testing we used SWI-Prolog 10.1.15 , Dogelog Player 2.3.3, Trealla Prolog 3.9.60, EyeProlog 1.6.30 and Scryer Prolog 0.10.0. We couldn’t find a call_with_time_limit/2 in EyeProlog nor in Scryer Prolog. The testing was carried out on a Ryzen AI 7 350 budget AI laptop with Windows 11.</p><p>We used procgov to limit the memory to 2GB and run the loop for 60 seconds. To be able to run the Scryer Prolog test at all, we had to remove the dif(V, X), dif(V, Xs) constraint. The Length column shows the used N, and the Count column shows the reached loop/1 iterations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*mBkVSewvvf-8YTxAs-qzSg.png" /></figure><p>A “No” shows that the Prolog system didn’t pass. Either it hit the procgov limit, or run out of some of its own limits, indicating it had a reclamation problem there. Amazingly Dogelog Player was the only Prolog system that survived this additional testing.</p><h4>Conclusions</h4><p>Testing Ulrich Neumerkels maplist(dif) problem with a time limit of 1000 ms, we found Trealla Prolog, EyeProlog and Scryer Prolog only approached N=1000. While SWI-Prolog and Dogelog Player climbed above N=1000000. Further a garbage collection test was only survived by Dogelog Player.</p><p>See also:</p><p><strong>Implementing dif/2 with Open Trees</strong><br><a href="https://www.herbrand.ai/izytab/doclet/home/09_paper/75_2026/paper_221334.html">https://www.herbrand.ai/izytab/doclet/home/09_paper/75_2026/paper_221334.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e2914596a0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dogelog in the Park: A Barriered Statechart Simulator]]></title>
            <link>https://medium.com/@janburse_2989/dogelog-in-the-park-a-barriered-statechart-simulator-a50682d1fde8?source=rss-fb70175bc0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/a50682d1fde8</guid>
            <category><![CDATA[statecharts]]></category>
            <category><![CDATA[dogs]]></category>
            <category><![CDATA[prolog]]></category>
            <dc:creator><![CDATA[Dogelog Player]]></dc:creator>
            <pubDate>Fri, 04 Sep 2026 14:31:12 GMT</pubDate>
            <atom:updated>2026-09-04T15:04:42.374Z</atom:updated>
            <content:encoded><![CDATA[<p>In 1984 David Harel wrote a charming paper about statecharts to visualize complex system state and behaviour. After a $80 million acquisition and the expiry of patents. The 2015 W3C XML standard for statecharts has an appendix D showing a reference implementation.</p><h4>State Space</h4><p>We wondered whether there is an easy Prolog implementation of a statechart simulator. We surely will not be able to use our channel objects since they are not for broadcasting. But the concept of parallel state clearly has a broadcasting nature, in event production and consumption.</p><p>The original paper by David Harel does not exclude that a system has ovelapping parallel regions. But the simple model of statecharts is a evolution of an active state tree, that does a bifurcation when a parallel region is entered. We modelled the active state therefor as:</p><pre>States are either:<br>- single state: atom<br>- parallel state: compound</pre><p>The above modelling gives single states and parallel states a name, for parallel states the name is found in the compound functor. In our running example of a Dogelog in the park, we will have multiple single states and one compound state, namely when Dogelog is in the park:</p><pre>/* Dogelog in the Park */<br>single states: waiting, walking, running, etc…<br>compound state: on_a_walk(_,_). </pre><h4>State Transitions</h4><p>We do not really catalog the single states and compound states. Further following the spirit of typeless Prolog, we also don’t validate what the end-user codes as state transitions. But we give the end-user guidance how he can code not only single transtitions, but also parallel spawn and cancel:</p><pre>Transitions are defined:<br>- single transitions: next(+event, +atom, -atom)<br>- parallel spawn: next(+event, +atom, -compound)<br>- parallel cancel: next(+event, +compound, -atom)</pre><p>In our Dogelog in the Park example, we were not very creative. We borrowed it from Stately AI. They have recurring examples featuring a little dog, not a squirrel and not some traffic light. A dog matches better Dogelog Player, so its perfect fit. The parallel examples has two subboxes:</p><pre>% Box 1.1<br>next(speed_up, walking, running).<br>next(slow_down, running, walking).<br><br>% Box 1.2<br>next(wagging_starts, not_wagging, wagging).<br>next(wagging_stops, wagging, not_wagging).</pre><h4>Parallel Simulator</h4><p>The parallel simulator will have to deal the transitions when the little dog is on a walk. He then enters the conjoined boxes Box 1.1 and Box 1.2 forming a parallel box. The Stately AI example has name the parallel box on a walk, so the example will also have this parallel spawn and parallel cancel:</p><pre>% Box 1<br>next(leave_home, waiting, on_a_walk(walking,not_wagging)).<br>next(arrive_home, on_a_walk(_,_), walk_complete).</pre><p>The simulator is a homomorphism of next/3, with an intercept. The intercept happens when the first rule of step/3 does fire for a compound. Otherwise the first rule is part of the homomorphism, computing a single transition from a partial function. The step/3 predicate reads:</p><pre>% step(+Event, +State, -State)<br>step(E, X, Y) :- next(E, X, Y), !.<br>step(E, C, D) :- compound(C), !,<br>    C =.. [F|L],<br>    maplist(step(E), L, R),<br>    D =.. [F|R].<br>step(_, X, X).</pre><p>By using maplist/3 and not concurrent_maplist/3 we added a barrier. Events do not only arrive round robin simultaneously, they are also awaited to complete round robin simultaneously. So the user might add conditions and actions to next/3, but will not get complete chaos.</p><h4>Example Runs</h4><p>We can now walk the little dog. The interested reader might use the interactive simulator on the Stately AI page. We can supply a list of events as a Prolog list. And glue together multiple steps via DCG. This is done as follows by using the (- - &gt;)/2 rule operator form DCG:</p><pre>% steps(+List, +State, -State)<br>steps([]) --&gt; [].<br>steps([X|L]) --&gt; step(X), steps(L).</pre><p>This DCG usage completely bypass difference lists under the hood. And it also doesn’t make use of any non-terminals. The trick is, its a hybrid between ordinary Prolog step/3 and DCG steps//1. We can now let the little dog play fetch in some nature park:</p><pre>/* leave home */<br>?- steps([leave_home, wagging_starts], waiting, S).<br>S = on_a_walk(walking, wagging).<br><br>/* play fetch */<br>?- steps([leave_home, wagging_starts, wagging_stops, <br>   speed_up], waiting, S).<br>S = on_a_walk(running, not_wagging).<br><br>/* return home */<br>?- steps([leave_home, wagging_starts, wagging_stops, <br>   speed_up, slow_down, arrive_home], waiting, S).<br>S = walk_complete.</pre><p>Statecharts already made it into UML in 1995, as part of the behavioral diagrams, although desribing both state and behaviour. One might like the idea of using statecharts, often the non-chaotic variants, for documentation and/or implementation as a simple form of business rules.</p><h4>Conclusions</h4><p>Unlike the W3C appendix D take, the simulator is a homomorphism of next/3, with an intercept for cancellations. By using maplist/3 and not concurrent_maplist/3 we added a barrier. We can now let the little dog play fetch in some nature park, just like in the Stately AI demo page.</p><p>See also:</p><p><strong>Stately AI — Parallel States</strong><br><a href="https://stately.ai/docs/state-machines-and-statecharts#parallel-states">https://stately.ai/docs/state-machines-and-statecharts#parallel-states</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a50682d1fde8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grothendieck-Group Rewriting in Dogelog Player]]></title>
            <link>https://medium.com/@janburse_2989/grothendieck-group-rewriting-in-dogelog-player-51cccc82e3de?source=rss-fb70175bc0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/51cccc82e3de</guid>
            <category><![CDATA[lawvere]]></category>
            <category><![CDATA[grothendieck]]></category>
            <category><![CDATA[prolog]]></category>
            <dc:creator><![CDATA[Dogelog Player]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 16:16:38 GMT</pubDate>
            <atom:updated>2026-08-25T21:10:43.592Z</atom:updated>
            <content:encoded><![CDATA[<p>Since Prologers have their head full of DCG and difference lists, using pairs to measure the Earth’s circumference. They might also like the idea to use difference pairs in rewriting. We attack the commutative semiring N[x] where additive inverse is missing, Grothendieck-Groups come handy.</p><h4>Representing</h4><p>The notation N[x] indicates a polynomial ring where polynomials have coefficients from the natural numbers N, i.e. the positive integers. And where there is a single variable x. It is important to see that we treat x as fixture, i.e. an atom, and not as a variable.</p><p>On the surface we might just use usual Prolog terms over the predefined operators (+)/2 and (*)/2. The first problem we will be facing, that similar functions, that would always give the same evaluation result if we would substitute x with a value, might be syntactically different:</p><pre>f(x) = (x+1)*(x+1)<br><br>g(x) = x*x+x*2+1</pre><p>The idea here is while reading a Prolog term, one would also expand the Prolog term, and produce a representation, so that similar functions have similar representations. The usual way to do this in Prolog, is to assume some representation functions nx_mul/3 and nx_add/3 and define:</p><pre>% nx_expr(+Expr, -List)<br>nx_expr(X*Y, S) :- !,<br>   nx_expr(X, L),<br>   nx_expr(Y, R),<br>   nx_mul(L, R, S).<br>nx_expr(X+Y, S) :- !,<br>   nx_expr(X, L),<br>   nx_expr(Y, R),<br>   nx_add(L, R, S).<br>nx_expr(x, [0,1]) :- !.<br>nx_expr(0, []) :- !.<br>nx_expr(N, [N]).</pre><p>The represention of our choice are lists [n_0,..,n_m] to represent a polynomial n_m*x^m+…+n_0. Addition of polynomials is then addition of these lists, basically multiset addition. And multiplication of polynomials is the manual school algorithm, done with lists:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*yIr8Jv-leMJa-2UsqnSKMg.png" /></figure><h4><strong>Pseudodivision</strong></h4><p>To do rewriting with polynomials, one usually doesn’t approach it from the syntactic substitution approach, as found in Knuth-Bendix algorithm. Instead one uses pseudo division approaches, as found in Gröbner-Bases algorithms. Given a polynomial f and s, one wants to find f = a*s + b.</p><p>We apprach the problem naively in that we first implement a partial subtraction operation. This is again taken from the school algorithm for polynomial divison, only we do not position the divisor, only check balantly whether we can find a polynomial b, such that f = s + b:</p><pre>% nx_sub(+List, +List, -List)<br>nx_sub(L, [], L) :- !.<br>nx_sub([], _, _) :- !, fail.<br>nx_sub([X|L], [Y|R], T) :- X &gt;= Y, !,<br>   Z is X-Y,<br>   nx_sub(L, R, S),<br>   (Z = 0, S = [] -&gt; T = []; T = [Z|S]).</pre><p>The shifting to find a step f = a*s+b is done as follows:</p><pre>% nx_div(+List, +List, -List, -List)<br>nx_div([X|L], R, [0|H], [X|J]) :-<br>   nx_div(L, R, H, J).<br>nx_div(L, R, [1], S) :-<br>   nx_sub(L, R, S).</pre><p>This is not a long division, only a short division. A long division could find a1, a2, .., ak such that f = a1*s+a2*s+..+ak*s+b. But for our purpose and demonstration a short division is enough. So for our running example with f=x*x+x*2+1 and choosing s=x+1, we only get f=x*s+x+1:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*GV-FDmGSV86cuQ1KdYnpRg.png" /></figure><h4>Rewriting</h4><p>If we have a rewriting rule s |-&gt; t, we can apply it via pseudo division. Given a polynomial f , if we find f = a*s+b, we can replace it by f’ = a*t+b. This is the tranditional approach of rewriting, and an equation f = g would be attacked by either rewriting f or g in a single step.</p><pre>Traditional Rule: s |-&gt; t<br><br>if f = a*s+b <br><br>then f&#39; = a*t+b</pre><p>By acting in the spirit of Alexander Grothendieck, who was a master in generalizing, we can also approach rewriting under a different premisse. Namely that the subject are not terms but equations, and that we are asked to use the congruence axioms from equality as well:</p><pre>/* Congruence for Functions Axiom */<br>x1=y1 &amp; … &amp; xn=yn =&gt; f(x1,..,xn) = f(y1,..,yn)<br><br>/* Congruence for Relations Axiom */<br>x1=y1 &amp; … &amp; xn=yn =&gt; R(x1,..,xn) &lt;=&gt; R(y1,..,yn)</pre><p>Together with reflexivity, the above axioms can justify the school manner of going from f = g to f+c = g+c. We dont need the additive inverse for this movement. In Grothendieck-Group rewriting we use pairs of terms for rewriting, and we use the above school movement as well:</p><pre>Grothendieck Rule: s1,s2 |-&gt; t1,t2<br><br>if f = a*s1+b1 and g = a*s2+b2<br><br>then f&#39; = a*t1+b1 and g&#39; = a*t2+b2</pre><p>To implement such a rewriting we have to first obtain a pseudo divison for f, i.e. f = a*s1+b1. We will then compute a*s2 , and check whether we can subtract it from g, to get b2. The backtracking mechanism of Prolog is the perfect programming language here to this little search.</p><h4>Seven Trees in One</h4><p>It is attributed to Lawvere that x⁷ = x can be demonstrated in N[x] under the equality assumption x = x² + 1. We tried the problem with the Grothendieck rule x²,0 |- x,1 . Amazingly nothing Knuth Bendix and Critical Pairs is needed for this derivation and the last step is justified by reflexivity:</p><pre>x*x*x*x*x*x*x = x<br>x*x*x*x*x*x = x*x*x*x*x+x<br>x*x*x*x*x = x*x*x*x*x+x*x*x*x+x<br>x*x*x*x = x*x*x*x*x+x*x*x*x+x*x*x+x<br>x*x*x = x*x*x*x*x+x*x*x*x+x*x*x+x*x+x<br>x*x = x*x*x*x*x+x*x*x*x+x*x*x+x*x+x*2<br>x = x*x*x*x*x+x*x*x*x+x*x*x+x*x+x*2+1<br>x*x*x+x = x*x*x*x*2+x*x*x+x*x+x*2+1<br>x*x+x = x*x*x*x*2+x*x*x+x*x+x*3+1<br>x*2 = x*x*x*x*2+x*x*x+x*x+x*3+2<br>x*x+x*2 = x*x*x*x+x*x*x*2+x*x+x*3+2<br>x*3 = x*x*x*x+x*x*x*2+x*x+x*3+3<br>x*x+x*3 = x*x*x*3+x*x+x*3+3<br>x*4 = x*x*x*3+x*x+x*3+4<br>x*5 = x*x*x*2+x*x*2+x*3+4<br>x*6 = x*x*x+x*x*3+x*3+4<br>x*7 = x*x*4+x*3+4<br>x*7+1 = x*x*3+x*4+4<br>x*7+2 = x*x*2+x*5+4<br>x*7+3 = x*x+x*6+4<br>x*7+4 = x*7+4</pre><p>The below screenshot shows that the method is ultra fast. We can prove the Lawvere example in less than 1 ms. Unlike paramodulation theorem provers, reported by Phil Zucker, crunching the example in the range of 1 sec to 1/2 sec. Other reported attempts fail one way or the other as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*TGsI6rs6Syr_-d702PiGkw.png" /></figure><p>But here comes the crux, usually it is not sound to deduce f = g from f+c = g+c, so on first sight going back to x⁷ = x from 7x+4=7x+4 seems dubious. Unless we accept that the rewriting was only oriented equations. Can we demostrate going back from 7x+4=7x+4 to x⁷ = x?</p><h4>Geniuses</h4><p>Among the school math arsenal is of course not only going from f = g to f+c = g+c. The real school math geniuses would go from f = g to f+0 = g+0, i.e. choose c = 0. This becomes then reversible. Lets first analyse Grothendieck rules and what kind of c they use under the hood. One can verify:</p><pre>Traditional+School Rule: s1+t2 |-&gt; t1+s2<br><br>if f = g where f = a*s1+b1 and g = a*s2+b2<br><br>then f&#39;&#39; = g&#39;&#39; where f&#39;&#39; = a*t1+b1+a*s2 and g&#39;&#39; = a*t2+b2+a*s2</pre><p>So the added c was c = a*s2 and the relation ship to Grothendieck rule is:</p><pre>f’’ = f’ + a*s2 and g’’ = g’ + a*s2</pre><p>The rewriting was implicitly carrying along additional summands c = a*s2. Doing the Alexander Grothedieck zoom out, by not only focusing on f’ and g’, but also by adding an extra c. But for the x = x² + 1 problem it was s2 = 0, so nothing was added that could not be removed.</p><h4>Conclusions</h4><p>The backtracking of Prolog is perfect to search rewrite locations. Following Alexander Grothendieck before category theory, a master in generalizing, we apply rewriting on equations f = g and not only individual terms f and g. The Lawvere example of x⁷ = x from x = x² + 1 runs in less than 1 ms.</p><p>See also:</p><p><strong>The Generalist </strong><br><a href="https://www.thebigquestions.com/2014/11/17/the-generalist/">https://www.thebigquestions.com/2014/11/17/the-generalist/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51cccc82e3de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[π-WAM Assembly: Jump and Link for Tseytin Transform]]></title>
            <link>https://medium.com/@janburse_2989/%CF%80-wam-assembly-jump-and-link-for-tseytin-transformation-d81abe7cceb7?source=rss-fb70175bc0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d81abe7cceb7</guid>
            <category><![CDATA[risc]]></category>
            <category><![CDATA[tseytin]]></category>
            <category><![CDATA[prolog]]></category>
            <dc:creator><![CDATA[Dogelog Player]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 21:20:52 GMT</pubDate>
            <atom:updated>2026-10-07T15:27:05.096Z</atom:updated>
            <content:encoded><![CDATA[<p>We can report some progress in the π-WAM compilation using the recently introduced assembly with labels. While we already showed disjunction (;)/2 without resorting into TRY_ME_ELSE, RETRY_ME_ELSE or TRUST_ME. In this take we show how to do if-then-else (-&gt;)/2 .</p><h4>Binary Disjunction</h4><p>It all began with some ideas how to compile disjunction (A; B) in the presence of a continuation C. Distributivity of conjunction over disjunctions allows us to state ((A; B), C) = ((A, C); (B, C)). The compilation scheme itself is based on a exhaustive reading of continuations:</p><pre>/* Binary disjunction with duplicate continuation */<br>sys_comp_goal((GOAL; GOAL2), REGS, BUFS, LABEL, CONT) --&gt; !,<br>   sys_comp_goal(GOAL, REGS, BUFS, LABEL, CONT),<br>   sys_comp_goal(GOAL2, REGS, BUFS, LABEL, CONT).</pre><p>The exhaustive reading of a continuation C says that we compile it as if it were (C, fail; true). So reaching the end of a compilation of a continuation C, indicates the completion of an exhaustive enmeration of C. This explains the above compilation, but has the defect that the C code is duplicated.</p><p>A solution to avoid this duplication, is to pack the continuation into a subroutine by performing a Tseytin transform. We basically compile ((A; B), C) = (p &lt;- C, (A, p; B, p)) where p is a fresh propositional variable. In compilation a fresh propositional introduction is a new label ENTRY:</p><pre>/* Binary disjunction without duplicate continuation */<br>sys_comp_goal((GOAL; GOAL2), [TEMP|REGS], BUFS, LABEL, CONT) --&gt; !,<br>   sys_comp_goal(GOAL, [TEMP|REGS], BUFS, LABEL, [&#39;$JSR&#39;(ENTRY)]),<br>   sys_comp_goal(GOAL2, [TEMP|REGS], BUFS, LABEL, [&#39;$JSR&#39;(ENTRY)]),<br>   sys_instr((bra,mov,EXIT)),<br>   sys_label(ENTRY),<br>   sys_instr((set,nop,TEMP)),<br>   sys_comp_cont(CONT, REGS, BUFS, LABEL),<br>   sys_instr((jmp,mov,TEMP)),<br>   sys_label(EXIT).</pre><p>The propositional introduction p &lt;- C has a opening and a closing. In the opening the accumulator is stored in a register TEMP. In the closing we jump to what was stored in TEMP. This allows simple subroutine calls without the need for a stack. The ‘$JSR’/1 call deploys a jump and link:</p><pre>/* Calling the Tseytsin transform */<br> sys_comp_goal(&#39;$JSR&#39;(ENTRY), REGS, BUFS, CONT) --&gt; !,<br>   sys_instr((bra,mov,ENTRY)),<br>   sys_comp_cont(CONT, REGS, BUFS).</pre><p>Our bra and jmp instructions are RISC (ARM / RISC-V) inspired. They jump to the argument address to run a block of code, and they save a return address in the accumulator so the called subroutine knows how to get back. This is unlike CISC (x64) where a runtime stack is needed.</p><h4>Global Cuts</h4><p>For simplicity in the Hack VM the jump instructions always have the condition “branch if zero” on them and always perform linking. Unconditioned jumps are realized by zero. The argument can then be an immediate address, like 7, or an indirect address, like [3]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*1dbhZzongmMAGKCyMfYArA.png" /></figure><p>The global cut !/0, is then conceived as jump out of whatever backtracking created by disjunction or between for-loops. It is implemented as a defered break LABEL, where the label LABEL marks the main block. And since it is a break, the jumps goes after the main block:</p><pre>sys_comp_body(GOAL, REGS, BUFS, CONT) --&gt;<br>   sys_comp_goal(GOAL, REGS, BUFS, LABEL, CONT),<br>   sys_label(LABEL).<br><br>sys_comp_goal(!, REGS, BUFS, LABEL, CONT) --&gt; !,<br>   sys_comp_cont(CONT, REGS, BUFS, LABEL),<br>   sys_instr((bra,mov,LABEL)).</pre><p>The global cut works fine, even for nested backtracking cases:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*cNo6nH-gdFg1p-GpzcApFg.png" /></figure><h4>Multiway Disjunction</h4><p>Only compiling binary disjunction would blow up the code. Since the N-th disjunction in a multiway disjunction would have (N-1)-many Tseytin transforms and equally many ‘$JSR’/1 calls for N&gt;1. To arrive at a better compilation schema we tap into the front Dogelog VM transform:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*CmA0ZoraaxfoVtHJ1G6Hkw.png" /></figure><p>The transform replaces multiway disjunction by an ‘$ALT’/1 call with a list argument of the alternatives in the form of ‘$SEQ’/2. We can readily compile this list by iterating through it, and only use a single ‘$JSR’/1 call for either if-then-else (-&gt;)/2 alternatives or ordinary alternatives:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*mgK09v7y913A_glE3jlLLA.png" /></figure><p>But multiway disjunction is not the only things we get for free in the new setting. The compilation also emits ‘$CUT’/1 goals and we didn’t need to reinvent the wheel to compile alternatives that are if-then-else (-&gt;)/2. The later is now a byproduct of using the front Dogelog VM transform.</p><h4>Local Cuts</h4><p>The front Dogelog VM transform pairs ‘$CUT’/1 calls with either ‘$SEQ’/2 elements or ‘$MARK’/1 calls. We can use the first argument of both to carry our break LABEL. The ‘$CUT’/1 then invokes this LABEL, only the LABEL is now an argument of ‘$CUT’/1 itself, and not a compilation parameter:</p><pre>sys_comp_goal(&#39;$MARK&#39;(LABEL), REGS, BUFS, CONT) --&gt; !,<br>   sys_comp_cont(CONT, REGS, BUFS),<br>   sys_label(LABEL).<br><br>sys_comp_goal(&#39;$CUT&#39;(LABEL), REGS, BUFS, CONT) --&gt; !,<br>   sys_comp_cont(CONT, REGS, BUFS),<br>   sys_instr((bra,mov,LABEL)).</pre><p>So far this means we could completely abstain from the classic WAM approach that sees a disjunction leaving a choice point at the its entrance. On the other hand our approch from the π-WAM focuses on the dual end, namely the exit. It leads to a similarly correct behaviour:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*oHT-fbHpi0c8qtlzKrzXPw.png" /></figure><p>Some Prolog systems erroreously make the if-condition cut transparent:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*jUnJdcxPqfHJiztGrIVFMg.png" /></figure><p>We could rejoice don’t need choice points, and hence have a different take than C_OR from SWI-Prolog. But while SWI-Prologs light weight choice points store a link address, we need to do the same to call the fresh Tseytin proposition. But we do so with Jump and Link from RISC.</p><h4>Conclusions</h4><p>To aid in the compilation of (-&gt;)/2 we use the front Dogelog VM transform that introduces ‘$MARK’/1 and ‘$CUT’/1. While SWI-Prologs light weight choice points store a link address, we need also to do the same to call the fresh Tseytin proposition. But we do so with Jump and Link from RISC.</p><p>See also:</p><p><strong>Introduction to π-WAM Assembly</strong><br><a href="https://www.herbrand.ai/izytab/doclet/home/09_paper/75_2026/paper_221654.html">https://www.herbrand.ai/izytab/doclet/home/09_paper/75_2026/paper_221654.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d81abe7cceb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blum’s Speed-Up Theorem and Sudoku]]></title>
            <link>https://medium.com/@janburse_2989/blums-speed-up-theorem-and-sudoku-bb8acd0c3284?source=rss-fb70175bc0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb8acd0c3284</guid>
            <category><![CDATA[dogelog]]></category>
            <category><![CDATA[eyeprolog]]></category>
            <category><![CDATA[speed-up]]></category>
            <dc:creator><![CDATA[Dogelog Player]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 19:55:57 GMT</pubDate>
            <atom:updated>2026-08-15T13:17:00.000Z</atom:updated>
            <content:encoded><![CDATA[<p>Years ago Sam Altman said to have no idea how to generate revenue, but when the generally intelligent system is in place, he might ask it. We take Sudoku as the drosophila how different schools deal with “generality”, in this particular instance attacking NP problems with constraint solvers.</p><h4>Deterministic Time</h4><p>Blum’s Speed-Up theorem from 1967 is hard to grasp, since its formulated with measure theoretic jargon. More approachable ideas are for example from 1965, when people took a closer look at deterministic time. Every non-determinstic NP problem has a solution verifiable in deterministic P.</p><p>All schools honor the shortening of search efforts in constraint solvers. To set the stage for a particular discussion, we first show that every deterministic turing machine can trivially be speed-up, if time is the number of steps f(n) to terminate on an input of length n.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*cKxKD3T20daTgkJpt020dw.png" /></figure><p>The architecture of a such Turing machine T is seen above. A simple construction can now create a Turing machine T’, by combining two single cells into a new cell. And precomputing the finite automata FA’, that simulates FA on two cells. Obviously it is now f’(n) =&lt; f(n)/2.</p><h4>Constraint Propagation</h4><p>Constraint solving algorithms that use constraint propagation in essence combine turing machine cells, from the viewpoint of a constraint variable as a turing machine cell. The method is often combined with a dynamic selection of a not yet triggered variable.</p><p>There do exist a couple of variations, concerning what gets propagated and when propagation stops. Like for example single value assignments can be propagated as well as domain changes can happen. These ideas are seen in GNU Prologs clp(FD), here some hypothetical runs:</p><pre>/* value propagation */<br>X = 3, X+Y = 5 ~~&gt;  Y = 2<br><br>/* domain propagation */<br>X \= 3, X in 1..5 ~~&gt; X in 1..2\/4..5</pre><p>The particular discussion here is, contrasting the method with speed-up theorems. Since combination of cells is done during constraint solving, there is no proper use of a single speed-up function f’(n). Somehow this flexibility is wanted, and even fixpoint computations are suggested.</p><h4>EyeProlog Sudoku</h4><p>We now bat an eye on EyeProlog. We didn’t have time to study it thoroughly, but it seems it deverts from Markus Triska style CLP(Z) implementations that do a great deal in Prolog itself. For example judging from the GitHub source the dynamic variable choice is coded in JavaScript itself:</p><pre>function* enumerate(variables, env, options) {<br>  variables = unresolvedLabelVariables(variables, env);<br>  if (variables.length === 0) {<br>    if (clpzStateConsistent(env)) yield env;<br>    return;<br>  }<br>  const selected = chooseVariable(variables, env, options.variableOrder);<br>  if (selected.values == null) throw new PrologError(&#39;instantiation_error&#39;);<br>  const values = options.valueOrder === &#39;down&#39; ? [...selected.values].reverse() : selected.values;<br>  const variableTerm = variables[selected.index];<br>  const rest = [...variables.slice(0, selected.index), ...variables.slice(selected.index + 1)];<br>  for (const value of values) {<br>    const next = env.clone();<br>    if (!unify(variableTerm, numberTerm(value.toString()), next) ||<br>        !propagate(next) || !clpzStateConsistent(next)) continue;<br>    yield* enumerate(rest, next, options);<br>  }<br>}</pre><p>We also see a propagate() routine, which is also used by postTo(). So it shares a lot of traits with Markus Triska style CLP(Z), where constraints can immediately fire. EyeProlog was announcement in the Scryer community, demonstraiting better performance than Scryer and Trealla.</p><p>We examined the Prolog code of the performance announcements , and found a Sudoku solver. The solved problem was an AI Escargot, and the Prolog code was not unusual, except it didn’t use term_variables/1 for labeling, but instead called the following routine:</p><pre>/* Variant 1 */<br>sudoku9_flatten([], []).<br>sudoku9_flatten([Row|Rows], Cells) :-<br>  sudoku9_append(Row, Rest, Cells),<br>  sudoku9_flatten(Rows, Rest).</pre><p>To add to the particular discussion here, we also tried:</p><pre>/* Variant 2 */<br>sudoku9_flatten([], []).<br>sudoku9_flatten([Row|Rows], Cells) :-<br>  sudoku9_flatten(Rows, Rest),<br>  sudoku9_append(Rest, Row, Cells).</pre><p>The two benchmark results are seen here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*ePV7qATCpVU6pRuh0dfYbQ.png" /><figcaption><strong>Variant 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*H0LDbhy1DHUblYsPvfSxiA.png" /><figcaption><strong>Variant 2</strong></figcaption></figure><h4>Static Ordering</h4><p>Another approach to constraint solving is to adopt a variant of Rina Dechters Bouqet Elimination algorithm. In our take of the library(edge/railgun), the bouquets have a non-deterministic and a deterministic part. But the most important aspect is their genesis.</p><p>The bouquets are stricktly precomputed before the bouqet elimination starts. This puts us much closer to a speed-up theorem setting. If the computation of the bouquets has polynomial complexity, doing it before solving doesn’t destroy their polynomial preprocessing complexity.</p><p>The bouquets are result of reordering the original constraint problem, and can also transform or expand the original constraint problem, resulting in a new time step complexity f’(n). Since the bouqet elimination is still exponential, the preprocessing complexity becomes negligible.</p><h4>Dogelog Sudoku</h4><p>The library(edge/railgun) is available for the target platforms JavaScript, Python and Java. We are currently working on a marriage with π-WAM. What we can already demonstrate is the AI Escargot example from EyeProlog. We also tested two variable orderings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*2PSE-Aqp9NcgZ1x7IWCL6A.png" /><figcaption><strong>Variant 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/717/1*y6nxfq1ZqOYyJgH3U0u6xA.png" /><figcaption>Variant 2</figcaption></figure><p>The results are very close to EyeProlog, although we use different means. Not only do we not use the dynamic constraint propagation approach, but bouquet elimination instead. Further our solution is still 100% Prolog, but nevertheless runs in the browser. The results side by side:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*hjOnt-Hy1qDsAOYuOGduIg.png" /></figure><h4>Conclusions</h4><p>Every turing machine T has a turing machine T’ that can do multiple steps at once. In propagation methods repeated goal reconstructions happens, while static methods construct goals once. The later is applied in Dogelog Player and looking at AI Escargot it can beat EyeProlog in the browser.</p><p>See also:</p><p><strong>Sam Altman on his Business Model<br></strong><a href="https://www.youtube.com/shorts/pLnyjxgFxew">https://www.youtube.com/shorts/pLnyjxgFxew</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb8acd0c3284" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[π-WAM Contest: 1 Million Packets with Prolog]]></title>
            <link>https://medium.com/@janburse_2989/%CF%80-wam-contest-1-million-packets-with-prolog-ec3e91551773?source=rss-fb70175bc0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec3e91551773</guid>
            <category><![CDATA[million]]></category>
            <category><![CDATA[packet]]></category>
            <category><![CDATA[prolog]]></category>
            <dc:creator><![CDATA[Dogelog Player]]></dc:creator>
            <pubDate>Fri, 07 Aug 2026 15:41:46 GMT</pubDate>
            <atom:updated>2026-08-07T16:16:08.780Z</atom:updated>
            <content:encoded><![CDATA[<p>We recently demonstrated a Prolog emulator for ADA RendezVous without ACK and NACK. This is basically a bounded buffer with max_size=1. We now went on and implemented this kind of fire and forget channel object natively for JavaScript, Java and Python. Some results.</p><h4>Native RendezVous</h4><p>Our native channel object uses two semaphores. We found such classes in Java and Python and could use them in our realization. For JavaScript we had to juggle with Atomics, but could also implement native blocking and non-blocking variations using wait() and notify().</p><p>We will briefly review the Java realization, to show the difference between the blocking and non-blocking variants. Both the blocking and non-block variants use the same semaphores. The realization is based on the fact that semaphores can also be operated blocking and non-blocking.</p><pre>public final static class RendezVous {<br>    private final Semaphore head = new Semaphore(0);<br>    private final Semaphore tail = new Semaphore(1);<br>    [...]<br>}</pre><p>The tail semaphore indicates an empty while the head semaphore indicates a full. Two semaphores allow a transition time, where the leading task can store the data, before the recipient load the data. The skeleton of the blocking channel object API put/take reads:</p><pre>public static void cpu_chan_put(RendezVous chan, /* more */)<br>        throws InterruptedException {<br>    chan.tail.acquire();<br>    /* store */<br>    chan.head.release();<br>}<br><br>public static void cpu_chan_take(RendezVous chan, /* more */)<br>          throws InterruptedException {<br>    chan.head.acquire();<br>    /* load*/<br>    chan.tail.release();<br>}</pre><p>To arrive at the channel object API offer/poll that would be non-blocking, one has to simply replace the semaphore calls acquire(), by tryAcquire(). Some APIs lump sum the behaviour blocking and non-blocking via a timeout parameter, that can be zero or infinite.</p><h4>Static Buffers</h4><p>In some of our tests, we observed that a JavaScript worker run out of memory. This was an early propotype of our channel objects, that was very Java stylish, namely each ADA Redezvous created a new int[] object, since the data inside the RendezVous was only a object pointer.</p><p>To adress this problem of memory pressure and subsequent consequences for host language native and parallel garbage collection, we decided to postulate a maximum buffer size, and provide the exchange buffer inside the RendezVous object itself:</p><pre>private static final int MAX_DATA = 128;<br><br>public final static class RendezVous {<br>   [...]<br>   private final int[] data = new int[1+MAX_DATA];<br>}</pre><p>The π-WAM generated already exchange buffer friendly code, we only had to utilize it when adding channel object support inside the π-WAM. Since packets can nevertheless have varying sizes, and we want packets to be transfered atomically, we simply store the size in data[0]:</p><pre>private static void cpu_data_store(int[] data, int max, <br>                                   int[] state, int base) {<br>    data[0] = max;<br>    for (int i = 0; i &lt; max; i++)<br>        data[1+i] = state[base+i];<br>}<br><br>private static void cpu_data_load(int[] data, int max, int[] state, int base) {<br>    int len = data[0];<br>    for (int i = 0; i &lt; max; i++)<br>        state[base+i] = (i &lt; len ? data[1+i] : 0);<br>}</pre><p>For the load we decided on a compromise. Since a π-WAM receive expects a certain size, but the arrived data might have a different size. The error free approach here is to either crop the arrived data, or to pad the arrived data with additional zeros. As shown above this logic is straight forward.</p><h4>SWI-Prolog Million</h4><p>As an early benchmark and showcase we exchanged 1 Million = 10⁶ Packets with Prolog. And to make it more interesting we used the threads and message queues from SWI-Prolog, with all their default settings. Means we used queues that were blocking and unbounded.</p><p>The SWI-Prolog code has first a π-WAM execute/2 polyfill:</p><pre>execute(G, [size(N)]) :-<br>   length(T, N),<br>   maplist(thread_create(G), T),<br>   maplist(thread_join, T).</pre><p>The above polyfill is then used in a producer consumer scenario. Each producer/consumer puts/takes 10000 = 1⁴ packets. By invoking 100 producers and 100 consumers, we exchange 100*10000 = 10²*10⁴ = 10⁶ packets, that is 1 million packets.</p><pre>producer(C) :-<br>   execute(<br>      (between(1,100,_),<br>      between(1,100,_),<br>      thread_send_message(C,[0]),<br>      fail; true), [size(100)]<br>   ).<br><br>consumer(C) :-<br>   execute(<br>      (between(1,100,_),<br>      between(1,100,_),<br>      thread_get_message(C,[0]),<br>      fail; true), [size(100)]<br>   ).<br><br>test :-<br>   message_queue_create(C),<br>   thread_create(producer(C), _),<br>   consumer(C),<br>   message_queue_destroy(C).</pre><p>On our AI Laptop, SWI-Prolog 10.1.13 can do that in less than 1 second:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*ed57o2hfKtuNbLFZJ2MYig.png" /></figure><h4>π-WAM Million</h4><p>We run the same test with π-WAM in Dogelog Player. This time the queue is non-blocking and has a bounded buffer with max_size=1. The code looks similar to SWI-Prolog, except the channel objects have a different factory, are garbage collected and are adressed by numbers:</p><pre>:- ensure_loaded(library(misc/brainfog)).<br><br>producer(C) :-<br>   execute(<br>      (between(1,100,_),<br>      between(1,100,_),<br>      send(3,[0])), [size(100), comm([C])]<br>   ).<br><br>consumer(C) :-<br>   execute(<br>      (between(1,100,_),<br>      between(1,100,_),<br>      recv(3,[0])), [size(100), comm([C])]<br>   ).<br><br>test :-<br>   cpu_chan_new(C), create_task(producer(C)), consumer(C).</pre><p>To have multiple π-WAM running inside the multithreaded part of Java, we use create_task/1 from our Dogelog Player cooperative multitasking arsenal. The π-WAM channels apply a polling round robin on the Hack VM instraction level among a groups of logical threads:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*R1V5yKoWN8IfwWafGfY_qA.png" /></figure><p>π-WAM beats SWI-Prolog here by a factor of ca. 1.5x (2762 / 1893 = 1.459)</p><h4>Conclusions</h4><p>Our 100 producers and 100 consumers, that communicate 10000 packets through a single channel, is the camel to go through the eye of a needle test case. Both π-WAM and SWI-Prolog can do it below a second using different means, but π-WAM beats SWI-Prolog here by a factor of ca. 1.5x.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec3e91551773" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Emulating ADA RendezVous in π-WAM]]></title>
            <link>https://medium.com/@janburse_2989/emulating-ada-rendezvous-channels-in-%CF%80-wam-11ad1908dbcf?source=rss-fb70175bc0bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/11ad1908dbcf</guid>
            <category><![CDATA[prolog]]></category>
            <category><![CDATA[rendezvous]]></category>
            <category><![CDATA[ada]]></category>
            <dc:creator><![CDATA[Dogelog Player]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 11:37:14 GMT</pubDate>
            <atom:updated>2026-08-05T12:27:10.528Z</atom:updated>
            <content:encoded><![CDATA[<p>While ADA RendezVous is often depicted as tied to a leading task that initiate the exchange and responder task that completes the exchange. The exchange mechanism itself can be extracted into a channel object. We do so using busy-wait in 100% Prolog to extend the π-WAM emulator.</p><h4>Channel Object</h4><p>We didn’t need long to find a template to implement the channel object. The Java concurrency library, with its engineering efforts lead by Doug Lea, offers a rich zoo of all kind of locks and queues. We find there a non busy-wait realization by the name SynchronousQueue.</p><p>While we cannot afford to realize a non busy-wait in 100% Prolog, since the ISO core standard doesn’t offer some concepts of tasks and/or synchronization. We can adopt that SynchronousQueue implements the usual BlockingQueue protocol, consiting of put/take and offer/poll.</p><p>We store the channel state in the dynamic database:</p><pre>:- dynamic(sys_chan/2).<br><br>chan(N) :-<br>   retractall(sys_chan(N,_)),<br>   assertz(sys_chan(N,nothing)).</pre><p>And then implement only the offer/poll protocol:</p><pre>offer(N, T) :-<br>   retract(sys_chan(N,nothing)),<br>   assertz(sys_chan(N,just(T))).<br><br>poll(N, T) :-<br>   retract(sys_chan(N,just(T))),<br>   assertz(sys_chan(N,nothing)).</pre><p>The implementation works beautifully out of the box:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*tZTbI5VkW_H466jlqM_LEg.png" /></figure><p>While the SynchronousQueue offer/poll interface returns boolean/option, the realization in 100% Prolog works with success and failure. It works best with first argument indexing braught to retract/1, because the calls will leave no spurious choice point, in the advent of a success.</p><h4>Send/Recv π-WAM</h4><p>While our first take of the π-WAM had only out/1 and in/1. We have meanwhile replaced out/1 by send/2, and in/1 by recv/2. The old predicates did implicitly use the current input and current output. The new predicates use the specified file number. For the channel experiment we dispatch.</p><p>The send uses the unix conventions of stdout = 1 and stderr = 2:</p><pre>sys_write_ints(1, LIST) :- !, /* stdout = 1 */<br>   current_output(STREAM),<br>   [..]<br>sys_write_ints(2, LIST) :- !, /* stderr = 2 */<br>   current_error(STREAM),<br>   [..]<br>sys_write_ints(CHAN, LIST) :-<br>   offer(CHAN, LIST).</pre><p>The recv uses the unix conventions of stdin = 0:</p><pre>sys_read_ints(0, RESULT) :- !, /* stdin = 0 */<br>   current_input(STREAM),<br>   [..]<br>sys_read_ints(CHAN, RESULT) :-<br>   poll(CHAN, RESULT).</pre><p>The π-WAM compile now generates Hack code that will loop. We use the relative addressing that is part of every Hack instruction, together with a condition. The out and in instruction set the accumulator to 0 respective -1 depending on success or failure of the offer/poll realization:</p><pre>sys_comp_goal(send(CHAN, LIST), _, [TEMP|BUFFER], CODE) --&gt; !, {length(LIST, LEN)},<br>   [((val,cst,true),LEN,0), ((acc,set,true),TEMP,0)],<br>   sys_comp_out(LIST, BUFFER),<br>   [((val,out,nq),CHAN,-1)], phrase(CODE).<br>sys_comp_goal(recv(CHAN, LIST), _, [TEMP|BUFFER], CODE) --&gt; !, {length(LIST, LEN)},<br>   [((val,cst,true),LEN,0), ((acc,set,true),TEMP,0)],<br>   [((val,in,nq),CHAN,-1)],<br>   sys_comp_in(LIST, BUFFER, CODE).</pre><p>What was a failure before is now a hang, because of infinite looping:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*ZyfyAqHob_9CRp0TzmrIzw.png" /></figure><p>The looping happens in the instruction [((val,out,nq),CHAN,-1)] for send/2 respective in [((val,in,nq),CHAN,-1)] for recv/2. If either the underlying offer or poll fails, the result will be -1. Thus the nq condition, which means non-zero will be fullfilled, and the relative -1 forces a repeat.</p><h4>Producer and Consumer</h4><p>We were currious about the behaviour when we emulate multiple logical threads. Since the emulation will then use round robin, we can keep multiple channels busy. Problem here, we cannot pack two different tasks into an emulate, since neither if-then-else nor disjunction is yet support.</p><p>To allow running different tasks inside Dogelog Player tasks from cooperative multitasking, we have to assure that the channel operations stay atomic. Dogelog Player tasks feature auto-yield, and thus a task switch can happen anywhere. The solution is shield/1, to switch off auto-yield:</p><pre>offer(N, T) :-<br>   shield(<br>      (retract(sys_chan(N,nothing)),<br>       assertz(sys_chan(N,just(T))))<br>   ).<br><br>poll(N, T) :-<br>   shield(<br>      (retract(sys_chan(N,just(T))),<br>       assertz(sys_chan(N,nothing)))<br>   ).</pre><p>To demonstrate that channel objects implement multiple producer multiple consumer (MPMC) queues, we go full monthy, and start two producers and two consumers. The test is also proof that a single emulator can utilize the environment outside of its goal argument:</p><pre>producer(C) :-<br>   emulate(<br>      (between(1,5,X),<br>      Y is X*X,<br>      send(C,[Y])), [size(2)]<br>   ).<br><br>consumer(C) :-<br>   emulate(<br>      (between(1,5,_),<br>      recv(C,[Y]),<br>      send(1,[Y])), [size(2)]<br>   ).</pre><p>The test case with emulated MPMC queues works like a charm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*JRSTZGZL-xDHfUtkzvNE8g.png" /></figure><p>Users will see that the CPU will show spikes, a result of the busy-wait. For a budget AI laptop that has multiple cores, only a few cores will be hitch hiked. We plan further bencharking on CPU and/or GPU when few logical threads are busy-waiting and when they are physically grouped.</p><h4>Conclusions</h4><p>To obtain channel objects, we could straight forward realize the offer/poll from Doug Lea’s SynchronousQueue using the Prolog dynamic database. The test case with emulated MPMC queues worked like a charm. We plan further benchmarking of physically grouped logical threads.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11ad1908dbcf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>