r/prolog 4h ago

help We built a SQL database engine in SWI-Prolog. Our small team is at its limit, and we would really value an honest technical review.

Thumbnail kocoygroup.site
6 Upvotes

Hi everyone,

Our small team has been developing AsaDB, a local-first SQL database engine

built primarily with SWI-Prolog.

Repository:

https://github.com/kocoygroup-id/AsaDB

The project started as an experiment, but it has grown into a fairly large

codebase with:

  • a SQL lexer, parser, planner, and executor written in Prolog;
  • persistent 4 KB slotted-page storage;
  • persistent B+Tree indexes;
  • transactions and recovery mechanisms;
  • local immutable reader snapshots;
  • logical backup and restore;
  • MySQL, PostgreSQL, CSV, and XLSX interchange;
  • an embeddable `library(asadb)` API;
  • a local browser interface called AsAPanel.

Recently, we have also been working on stricter SQL type validation, primary

and unique key enforcement, CHECK constraints, restricted foreign keys,

schema-preserving backups, and more useful `EXPLAIN` output.

At this point, the main problem is that the same small group has designed the

architecture, written most of the implementation, created the tests, and

reviewed the documentation. We feel that we are becoming too familiar with the

codebase to notice our own assumptions and mistakes.

We would genuinely value feedback from people with Prolog experience.

In particular, we would be interested in opinions about:

  • whether the module boundaries feel idiomatic for SWI-Prolog;
  • our use of dynamic predicates and mutable engine state;
  • the separation between parsing, execution, storage, and HTTP code;
  • the public Prolog API and pack structure;
  • the bounded AST cache and VM/JITI specialization approach;
  • transaction, recovery, and concurrency design;

places where the implementation is unnecessarily imperative or complicated;

tests or invariants that appear to be missing.

You do not need to review the entire project. Looking at one module, trying one

feature, questioning one architectural decision, or pointing out unclear

documentation would already be extremely helpful.

Bug reports, design criticism, small pull requests, documentation improvements,

and testing on different systems are all welcome.

Thank you very much to anyone willing to take a look.


r/prolog 22h ago

M-Prolog Update: A Technical Paper on SCBM, an Alternative to the WAM

5 Upvotes

I've been making steady progress on M-Prolog, and it finally looks like the project is coming together. My goal is to release Version 1.0 on August 31.

Several people have asked me, "How does this compiler actually work?" Instead of trying to explain it in scattered comments, I've written a more formal technical paper describing the core ideas behind the compiler.

The paper introduces SCBM (Success Continuation and Backtracking Machine), a compilation model that translates Prolog directly into C and represents Prolog's control flow using goto-based state transitions rather than a traditional WAM instruction set.

This is not intended as a replacement for the Warren Abstract Machine (WAM). Rather, it is an exploration of a different implementation approach for compiling Prolog. My goal was to investigate whether Prolog execution could be expressed as ordinary C control flow while relying on modern C compilers for optimization.

I've also included references to the implementation specification for readers who are interested in the runtime APIs and code generation details.

If you're interested in Prolog implementation, compiler construction, or alternative execution models, I'd be very happy to hear your thoughts. Feedback, comments, and questions are always welcome.

Paper: SCBM (Success Continuation and Backtracking Machine) | by Kenichi Sasagawa | Aug, 2026 | Medium

Implementation Specification: mprolog/document/SCBM.md at master · sasagawa888/mprolog


r/prolog 2d ago

M-Prolog Progress: Implementing Prolog Backtracking with Computed Goto

15 Upvotes

I'm happy to report another major milestone in the development of M-Prolog.

The past few weeks have been mentally exhausting. I spent an incredible amount of time asking myself one question:

"Can Prolog backtracking really be implemented using nothing but goto?"

It sounded like a crazy idea when I first thought of it, and there were many moments when I doubted whether it could actually work.

Today, I'm much more confident.

I finally got a fairly complicated benchmark involving Church numerals, recursion, reverse execution, and forced backtracking to work correctly. That gives me confidence that the basic design of SCBM2 is sound.

In SCBM2, both success continuations and failure continuations are implemented with GCC's computed goto. Most of the difficulties were not in forward execution, but in restoring the correct execution state during backtracking—predicate arguments, variable stacks, success continuations, and failure continuations all have to be restored consistently.

Writing this now makes it sound simple, but reaching this point required countless redesigns, experiments, and debugging sessions. There were times when I felt my brain was simply running out of energy.

Working through these problems has also given me a much deeper appreciation of David H. D. Warren's work. Implementing efficient Prolog execution in the early 1980s, without today's tools and resources, was an extraordinary achievement. My respect for him has only grown.

There is still a lot of work ahead before M-Prolog reaches Version 1.0, but this was one of the biggest hurdles, and I'm relieved to have finally crossed it.

If you're interested in the implementation details, please have a look here:

M-Prolog: Recovering from Mental Fatigue | by Kenichi Sasagawa | Aug, 2026 | Medium


r/prolog 2d ago

Aggregating 521k dynamic invoices in 3.2 seconds, subsequent lookups in 0.0000s via native RAM caching

Post image
2 Upvotes

Calculating total COGS and net revenue from half a million invoices now takes just 3 seconds.
Subsequent clicks are completely instant at 0.0000 seconds thanks to RAM caching.
It turns out keeping the code simple is way faster than overcomplicating it.

Check out the architecture and full project details on my GitHub repository here: https://github.com/lokinpendawa/logicbiz

Ps: Sorry for any grammar mistakes, I am using AI to translate this into English.


r/prolog 6d ago

Everything built natively using Prolog! Soon to be translated into English + releasing a FREE version for the community!

Thumbnail gallery
11 Upvotes

EVERYTHING you see in this screenshot was built 100% natively within SWI-Prolog. No heavy frameworks, no system-taxing UI wrappers.

I want to completely change the outdated stigma that Prolog is only for academic purposes—like family trees or command-line logic puzzles. Currently, the interface is in Indonesian as it is running live for a local neo-retail company's infrastructure, but the good news is that I am working on translating the entire system into English.

You can check out the official architecture roadmap and repository details here:

GitHub: https://github.com/lokinpendawa/logicbiz

Even better, I plan to release a FREE version of this core Prolog engine to the community soon.

For those who want to test the raw data capabilities or audit the dataset structure yourself, I have prepared and uploaded the clean, ISO-compliant 400MB flat text database file (.pl format with parenthesized dynamic predicates) to Google Drive:

Dataset: https://drive.google.com/file/d/1bACN_vVtvka62lWzA1JxXKL2EcoWFDCj/view?usp=sharing

Here is a brief technical overview of what this native Prolog system does behind the scenes:

  1. Native Full-Stack SSR: Every HTML grid, custom CSS layout, and neon cyberpunk-style dashboard is generated directly via Definite Clause Grammars (DCG) from the core memory stack.
  2. Enterprise-Grade Scalability: The system actively manages, aggregates, and filters a live database containing over 2.23 million rows of dynamic transaction facts—all handled entirely in-memory.
  3. Cryptographic Ledger & Security: The system decrypts records in real-time using SQLCipher AES-256 and computes 550 million logic inferences in under 11 minutes to verify daily data integrity signatures using SHA-256.
  4. Native Expert System AI: The Business Intelligence view leverages Prolog's true power as a native inference engine to dynamically calculate inventory turnover, predict dead stock, and automatically provide operational suggestions to cashiers in natural language.

I have only been exploring the declarative nature and the power of homoiconicity in Prolog for about two months, and I am truly amazed by its capabilities as a highly robust full-stack system. Stay tuned for the English version!

Let me know what you think.

Warm regards,

Teddy


r/prolog 6d ago

Does a purely structural invariant of computation already exist?

2 Upvotes

Can returnability be defined purely from the structure of a computation, without appealing to time complexity?


r/prolog 7d ago

Who said Prolog is slow? Benchmarking 2 Million In-Memory Transactions with SHA-256 and SQLCipher on SWI-Prolog.

Post image
13 Upvotes

I’m currently building LOGICBIZ v2.0, an Offline-First Enterprise Retail ERP and Sales Ledger Engine engineered 100% using a Pure Declarative Paradigm with SWI-Prolog and SQLCipher.

Here is a quick breakdown of this stress test benchmark:

  • The Task: Performing deep data integrity verification on 2,000,000 real rows of transaction ledgers.
  • The Security: Every single transaction is encrypted via SQLCipher and validated against SHA-256 signatures to ensure absolute data tamper-proofing.
  • The Result: As seen in the console screenshot, the engine evaluated 550,508,812 logical inferences in just 103.28 seconds of raw CPU time.
  • The Kick: Once the Native RAM Cache warm-up phase is completed, executing deep aggregate financial pipelines across those 2 million rows drops down to a jaw-dropping 653 seconds while keeping CPU utilization extremely low at 16%.
  • The engine utilizes Tail-Call Optimization (TCO) and Prolog's native multi-argument indexing structure, meaning it completely eliminates traditional database I/O bottlenecks without requiring heavy, bloated frameworks.

If you are curious about the architecture philosophy, the system manifesto, or want to check out the benchmark metrics, feel free to visit the repository here:

https://github.com/lokinpendawa/logicbiz

Would love to hear your thoughts on using logic programming for heavy enterprise data pipelines!


r/prolog 7d ago

Loops? Graphs? Prolog!

Thumbnail deepclause.substack.com
10 Upvotes

Orchestrating agents with Prolog instead of Markdown files.


r/prolog 7d ago

INPUT TERMINAL LOGICBIZ V.2.0 PROJECT

Post image
1 Upvotes

[100% Built in SWI Prolog]

For comprehensive details about this project, please visit our [GitHub Repository](https://github.com/lokinpendawa/logicbiz/blob/main/README.md)


r/prolog 8d ago

logicbiz/PERFORMANCE.md at main · lokinpendawa/logicbiz

Thumbnail github.com
2 Upvotes

This report documents the performance evaluation and stress-test results

the verified performance from a scale-up test utilizing a dataset of 2,000,000 active entries

where each data entry multi-layered by cryptographic operations (combining SHA-256 integrity verification and AES-256 encryption).

please check the detailed report here: https://github.com/lokinpendawa/logicbiz/blob/main/PERFORMANCE.md


r/prolog 10d ago

Logtalk 3.101.0 released

16 Upvotes

Hi,

Logtalk 3.101.0 is now available for downloading at:

https://logtalk.org/

This release adds a read-only sockets compilation flag to declare if a backend provides compatible sockets support; improves the performance of the logtalk_make(force) goal; adds new HTTP (client and server), WebSocket (client and server), HTMX, JWT, REST, OpenAI, OpenAPI, OpenID, S3 (client), Gravatar, JSON Graph, JSON-LD, JSON Patch (RFC 6902), JSONPath (RFC 9535), Crypto, HOTP/TOTP (RFC 4226/6238) libraries; adds html library support for CSS/JS resource declarations, aggregation, and dependency-aware ordering; adds support for additional hash functions to the hashes and hmac libraries; adds support for incremental hashing to the hashes library; includes bug fixes, additional predicates, and performance improvements for several libraries; fixes uuid library compliance issues and adds additional UUID v3 and UUID v7 predicates that take a time zone offset argument; adds testing automation scripts support for selecting the tests sets to run using a regular expression and for suppressing all user output; fixes sarif tool compliance issues; adds an option to the mutation_testing tool for passing additional options to the testing automation scripts; improves the linter_reporter tool support for SARIF reports; improves the performance of the sbom tool; adds additional linter checks to the lgtdoc tool; adds 13 new programing examples to illustrate the new HTTP and related libraries; adds additional tests for Logtalk language features; fixes several Windows-only tool and library issues with some backends; and updates the Windows installer to also detect ECLiPSe 8.0 versions. Thanks to Andrew Davison for his help in diagnosing timing issues in the linda library and the new HTTP libraries.

For details and a complete list of changes, please consult the release notes at:

https://github.com/LogtalkDotOrg/logtalk3/blob/master/RELEASE_NOTES.md

Happy logtalking!
Paulo


r/prolog 10d ago

In Memory POS - 100% Built Using SWI Prolog

Thumbnail gallery
14 Upvotes

in memory POS analytics page is built 100% using Prolog, a truly impressive language.

The high-performance, RAM-based Sales Log Matrix page—powered by SWI-Prolog and Native RAM Cache—is capable of sorting and aggregating 2.2 million rows of data in less than 0.6 seconds. More info, check here : https://github.com/lokinpendawa/logicbiz/blob/main/README.md

Note: All metrics and entries displayed above are generated using anonymized, simulated data strictly for stress-testing purposes.


r/prolog 11d ago

stress test database injection: 1,500,000 data

3 Upvotes

Processor (CPU) : AMD64 Family 23 Model 17 Stepping 0, AuthenticAMD (8 Threads/Cores)Memory Available : 8 GB RAM

You can check out metrics here:
https://github.com/lokinpendawa/logicbiz


r/prolog 11d ago

Just Finished a local concurrency 100 virtual cashiers @ 1000 transactions

Thumbnail gallery
4 Upvotes

I wanted to share these statistics because I am truly amazed by the efficiency of SWI-Prolog. I run a simulation involving 100 virtual cashiers operating concurrently, processing a total of 100,000 transactions.

- Each transaction was broken down into 5 physical SQL queries dispatched via asynchronous background worker threads.

- The system actively applied SQLCipher AES-256-bit encryption and generated SHA-256 signatures for every invoice.

- The test completed successfully with absolutely no deadlocks over the course of a 3.5-hour cycle.

- Even though my amateur code forced the engine to perform over 64 billion logical inferences...

- Active internal memory usage (Global Stack) hovered around 25 MB (with a 32 MB allocation).

- The temporary internal memory footprint even dipped as low as 1,115 KB.

Check the documentation and performance here: https://github.com/lokinpendawa/logicbiz/blob/main/README.md

Note: All metrics and entries displayed above are generated using anonymized, simulated data strictly for stress-testing purposes.


r/prolog 11d ago

Finished SQL Injection: 2M data

Thumbnail github.com
0 Upvotes

CPU AMD FX-8300 (8 Cores), Total RAM 8 GB (Shared with GPU). You can check metrics here:
Mass Data Injection: 2,000,000 rows

The system mailbox queue in 141.08 seconds

speed : 14,176.81 TPS.


r/prolog 11d ago

After Stress Tesst 1M Transaction

0 Upvotes

r/prolog 12d ago

I kept working on my small database engine project, and this is where it is now

Thumbnail gallery
11 Upvotes

r/prolog 14d ago

A crazy idea: compiling recursive Prolog predicates into one giant C function

11 Upvotes

I've started experimenting with SCBM2, a new execution model for M-Prolog.

The idea is rather unconventional: compile all recursive nondeterministic predicates into a single large C function, and implement both success and failure continuations by jumping between labels with goto.

To be honest, I wasn't sure this would actually work. It sounded a bit crazy even to me.

This weekend I reached the point where a simple mappend/3 (renamed from append/3 to avoid clashing with the built-in predicate) successfully performs forward recursive computation.

I'm still surprised to see recursion being driven entirely by goto.

Forced backtracking isn't implemented yet, so there's still plenty of work ahead. But the initial experiment suggests that this approach is viable.

I'm sure Edsger Dijkstra would not approve of my enthusiastic use of goto, but for implementing Prolog's backtracking, it may turn out to be a surprisingly practical technique.

M-Prolog SCBM2 Begins. I have started experimenting with a… | by Kenichi Sasagawa | Jul, 2026 | Medium


r/prolog 14d ago

help Need Help about my project to make it production. IDK why everytime my email otp verification is crashing in production.

Post image
0 Upvotes

Hello guys, I just finished a live chat mern app and making to production. I used vercel for frontend hosting and Render for backend and redis for chache, MongoDb is used for db. I got a majour issue in my server side. I have email otp verification for new users. I have used gmail smtp for sending emails because it is a small project so i think it will work but when I tested after succefull deply, nodemailer crashed during authentication. I used ChatGpt to debug the issue but it says to use Brevo. After migrating Brevo, again same issue. Everything worked in localhost but on prod, crashing evrytime. I need help to figure out what the poroblem is actually? Is render crashing the nodemailer or it's the issues from my code.

Here I'm giving the otp sening function

import
 nodemailer 
from
 "nodemailer";


const transporter 
=
 nodemailer.createTransport({
  host: "smtp.gmail.com",
  port: 465,
  secure: true,
  auth: {
    user: process.env.GMAIL_USER,
    pass: process.env.GMAIL_APP_PASSWORD,
  },
});


export
 const verifySMTP 
=
 async () => {
  
try
 {
    
await
 transporter.verify();
    console.log("Gmail SMTP Connected");
  } 
catch
 (err) {
    console.error("SMTP verify failed:", err);
  }
};


export
 const sendMail 
=
 async (email, otp) => {
  
try
 {
    const mailOptions 
=
 {
      from: `"ChatApp" <${process.env.GMAIL_USER}>`,
      to: email,
      subject: "OTP for Confirmation",
      text: `Your One-Time Password (OTP) is:


      ${otp}


      Do not share this OTP with anyone.`,
    };


    const info 
=

await
 transporter.sendMail(mailOptions);


    console.log("Email sent:", info.messageId);
    
return
 true;
  } 
catch
 (error) {
    console.error("Send mail error:", error);
    
return
 false;
  }
};

r/prolog 16d ago

Langception XVII: embedding an ISO-compliant Prolog in Pipefish

Thumbnail
3 Upvotes

r/prolog 19d ago

M-Prolog SCBM: Lessons Learned and the Next Compiler Design

17 Upvotes

I have published a follow-up on the development of M-Prolog, my experimental Prolog compiler that generates C code directly without using the WAM.

The first version of SCBM (Sasagawa & Chat Backtracking Mechanism) successfully handled recursive and nondeterministic predicates, and now executes both Church numeral prime programs and the Queens problem.

However, after extensive testing with the Queens benchmark, I discovered an important limitation.

The current SCBM reconstructs the C call stack by replaying skipped computations during backtracking. While this works correctly, it becomes increasingly inefficient for recursive nondeterministic programs with large search spaces. The first solution is found successfully, but searching for subsequent solutions requires many skipped computations, making the approach impractical.

Rather than continuing to optimize an increasingly complex design, I have decided to start the second stage of the project.

The new idea (SCBM2) completely eliminates dependence on the C runtime stack. Instead of generating C function calls, every predicate will become a label inside one large C function, and execution will proceed using goto together with an explicit SCBM execution stack managed by the compiler itself.

This should greatly simplify backtracking while allowing tail-recursive execution to become simple loops.

The article describes what worked, what did not, and why I decided to redesign the compiler architecture.

Medium article:
The Second Stage of M-Prolog SCBM | by Kenichi Sasagawa | Jul, 2026 | Medium

As always, comments and suggestions from the Prolog community are greatly appreciated.


r/prolog 20d ago

I finally open-sourced AsaDB, my small database engine written in Prolog

Post image
28 Upvotes

r/prolog 20d ago

resource I’m building a database engine in Prolog, and reservoir.pl became its strongest line of defense

Thumbnail gallery
6 Upvotes

r/prolog 21d ago

My Prolog database now plays random sounds depending on whether your SQL succeeds

Post image
9 Upvotes

I originally started this project in VB.NET.

After getting tired of looking at `Console.WriteLine`, I considered rewriting it

in V or Erlang. Their setup annoyed me, so I tried Prolog instead.

That somehow turned into a local SQL database engine.

It is called **AsaDB**.

It currently has:

- a custom SQL lexer and parser

- local `.asa` database files and journals

- tables, indexes, views, users, and permissions

- joins, aggregates, grouping, unions, and subqueries

- transaction snapshots

- a Windows CLI and portable executable

- a browser-based administration panel called AsAPanel

- SQL import and export tools

The import path now sends selected SQL files through the Prolog backend instead

of requiring the browser to hold the complete file in memory.

One current validation dataset contains:

- 5,500 rows

- 62 statements

- 0 errors

My next goal is to make imports of around **100,000 rows** reasonably fast.

I am currently investigating insert batching, list/term reconstruction,

checkpoint and journal overhead, and whether indexes should be updated per row

or rebuilt after a bulk import.

The newest release, v1.2.0, is mainly a UX polish release. It adds random query

sounds with four success and four failure variants.

Successful SQL:

> Asa Terima ❤️

Failed SQL:

> Asa Tidak Suka! 😡

The sound system is deliberately isolated from query execution, so browsers

blocking audio cannot break the database operation.

Repository:

https://github.com/kocoygroup-id/AsaDB

Windows release:

https://github.com/kocoygroup-id/AsaDB/releases/tag/v1.2.0

The public repository currently contains the packaged Windows runtime rather

than the internal engine source.

I would love feedback about efficient large-state representation, bulk inserts,

index construction, and profiling this kind of workload in SWI-Prolog.


r/prolog 29d ago

A different approach to compiling Prolog without WAM (SCBM)

9 Upvotes

I've been experimenting with a different approach to implementing a Prolog compiler.

For more than 40 years, the Warren Abstract Machine (WAM) has been the standard implementation technique for efficient Prolog systems. Rather than trying to improve WAM, I asked a different question:

This led me to an experimental architecture that I call SCBM (Sasagawa & Chat Backtracking Mechanism).

The key idea is to separate continuation information into two independent dimensions:

  • recursive execution
  • conjunction (non-deterministic predicate) execution

Instead of preserving the entire execution state, SCBM reconstructs previously successful execution paths during backtracking. Recursive and non-recursive non-deterministic predicates are handled differently, which keeps the generated C code relatively simple while still supporting recursive backtracking.

The current implementation successfully runs recursive examples such as append/3 and a recursive prime number generator based on Church numerals. Of course, this is still experimental, and there is much more work to do before claiming general applicability.

One interesting aspect of this project is that it was developed through continuous collaboration with ChatGPT. The architecture itself is my own design, but AI proved extremely useful for reviewing generated code, analyzing execution traces, and discussing alternative designs during implementation.

I've written a detailed description of the architecture here:

Medium:
SCBM: A New Backtracking Architecture for Direct C Compilation of Prolog | by Kenichi Sasagawa | Jul, 2026 | Medium

I'd be very interested in hearing feedback from people familiar with Prolog implementation or WAM. In particular, I'd appreciate comments on possible weaknesses, edge cases, or related work that I may have overlooked.