class DatalogEngine { constructor() { this.facts = {}; this.rules = {};…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
class DatalogEngine { constructor() { this.facts = {}; this.rules = {}; this.resultsCache = {}; }
addFact(predicate, ...args) { if (!this.facts[predicate]) { this.facts[predicate] = []; } this.facts[predicate].push(args); }
addRule(headPredicate, headArgs, body) { if (!this.rules[headPredicate]) { this.rules[headPredicate] = []; } this.rules[headPredicate].push({ headArgs, body }); }
query(queryPredicate, ...queryArgs) { const cacheKey = JSON.stringify([queryPredicate, queryArgs]); if (this.resultsCache[cacheKey]) { return this.resultsCache[cacheKey]; }
let results = [];
// Apply facts
const facts = this.facts[queryPredicate] || [];
for (let factArgs of facts) {
const substitution = this.unify(queryArgs, factArgs);
if (substitution) {
const newResult = this.applySubstitution(substitution, factArgs);
if (
!results.find(
(result) => JSON.stringify(result) === JSON.stringify(newResult),
)
) {
results.push(newResult);
}
}
}
// Apply rules iteratively until no more changes
let changed;
do {
changed = false;
// Use a stack to process rules
const ruleStack = [...(this.rules[queryPredicate] || [])];
console.log(ruleStack);
while (ruleStack.length) {
const { headArgs, body } = ruleStack.pop();
const substitutions = this.evaluateRule(body, {});
for (let substitution of substitutions) {
// Apply the substitution to the head arguments of the rule
const newResult = this.applySubstitution(substitution, headArgs);
// If the result matches the query args (after applying the substitution), add it to the results
if (this.unify(queryArgs, newResult)) {
if (
!results.find(
(result) =>
JSON.stringify(result) === JSON.stringify(newResult),
)
) {
results.push(newResult);
changed = true;
}
}
}
}
} while (changed);
// Deduplicate results
results = Array.from(new Set(results.map(JSON.stringify))).map(JSON.parse);
this.resultsCache[cacheKey] = results;
return results;
}
unify(args1, args2, substitution = {}) { // Check if the arguments match for (let i = 0; i < args1.length; i++) { const arg1 = args1[i]; const arg2 = args2[i]; if (typeof arg1 === "string" && arg1.startsWith("?")) { // arg1 is a variable if (arg1 in substitution) { // Variable is already assigned, check if it matches with arg2 if (substitution[arg1] !== arg2) { return null; } } else { // Assign the variable substitution[arg1] = arg2; } } else if (typeof arg2 === "string" && arg2.startsWith("?")) { // arg2 is a variable if (arg2 in substitution) { // Variable is already assigned, check if it matches with arg1 if (substitution[arg2] !== arg1) { return null; } } else { // Assign the variable substitution[arg2] = arg1; } } else if (arg1 !== arg2) { // Both arguments are constants and they don't match return null; } } return substitution; }
applySubstitution(substitution, args) { return args.map((arg) => substitution[arg] || arg); }
evaluateRule(body, initialSubstitution) { if (body.length === 0) { return [initialSubstitution]; }
const [firstClause, ...restClauses] = body;
const [predicate, ...clauseArgs] = firstClause;
let newSubstitutions = [];
if (predicate === "neg") {
const [negatedPredicate, ...negatedArgs] = clauseArgs.flat();
if (this.rules[negatedPredicate]) {
for (let rule of this.rules[negatedPredicate]) {
const { headArgs, body } = rule;
const factSubstitutions = this.evaluateRule(
body,
initialSubstitution,
);
if (!factSubstitutions.some((substitution) => substitution)) {
// All facts failed, so the negation succeeds
newSubstitutions.push(initialSubstitution);
}
}
} else {
const facts = this.facts[negatedPredicate] || [];
const factSubstitutions = facts.map((factArgs) =>
this.unify(negatedArgs, factArgs, { ...initialSubstitution }),
);
if (!factSubstitutions.some((substitution) => substitution)) {
// All facts failed, so the negation succeeds
newSubstitutions.push(initialSubstitution);
}
}
} else if (predicate in this.rules) {
for (let rule of this.rules[predicate]) {
const { headArgs, body } = rule;
for (let substitution of this.evaluateRule(body, initialSubstitution)) {
// const newResult = this.applySubstitution(substitution, headArgs);
for (let sub of this.evaluateRule(restClauses, substitution)) {
newSubstitutions.push(sub);
}
}
}
} else {
const substitutedArgs = this.applySubstitution(
initialSubstitution,
clauseArgs,
);
const facts = this.facts[predicate] || [];
for (let factArgs of facts) {
const substitution = this.unify(substitutedArgs, factArgs, {
...initialSubstitution,
});
if (substitution) {
for (let sub of this.evaluateRule(restClauses, substitution)) {
newSubstitutions.push(sub);
}
}
}
}
return newSubstitutions;
} }
const datalog = new DatalogEngine(); // Types datalog.addFact("type", "user1", "user"); datalog.addFact("type", "user2", "user"); datalog.addFact("type", "user3", "user"); datalog.addFact("type", "user4", "user"); datalog.addFact("type", "user5", "user"); datalog.addFact("type", "group1", "group"); datalog.addFact("type", "group2", "group"); datalog.addFact("type", "org1", "org"); datalog.addFact("type", "org2", "org"); datalog.addFact("type", "folder1", "folder"); datalog.addFact("type", "doc1", "document"); datalog.addFact("type", "doc2", "document");
//Groups datalog.addFact("group", "group1", "org1"); datalog.addFact("group", "group2", "org1"); datalog.addFact("group", "group3", "org2");
// Orgs datalog.addFact("role", "org1", "owner", "folder"); datalog.addFact("role", "org1", "owner", "document");
// Facts datalog.addFact("role", "user1", "member", "group1"); datalog.addFact("role", "user1", "user", "group1"); datalog.addFact("role", "user1", "administrator", "group1"); datalog.addFact("role", "user2", "user", "group1"); datalog.addFact("role", "user3", "user", "group2"); datalog.addFact("role", "user4", "manager", "group1"); datalog.addFact("role", "user5", "manager", "group2");
datalog.addFact("direct_member", "user1", "org1"); datalog.addFact("direct_member", "user2", "org1"); datalog.addFact("direct_member", "user3", "org1");
datalog.addFact("role", "group1", "administrator", "org1");
// Documents datalog.addFact("document", "doc1", "group2"); datalog.addFact("document", "doc2", "user1");
datalog.addFact("role", "group2", "editor", "doc1"); datalog.addFact("role", "user1", "viewer", "doc2");
//Folder datalog.addFact("folder", "folder1", "user4");
datalog.addFact("role", "folder1", "owner", "doc1"); datalog.addFact("role", "folder1", "owner", "doc2");
// Rule to infer types datalog.addRule( "types", ["?entity", "?type"], [ ["role", "?entity", "?role", "?other"], ["type", "?entity", "?type"], ], );
// Rules to infer admin datalog.addRule( "in_group", ["?user", "?group"], [ ["direct_member", "?user", "?org"], ["group", "?group", "?org"], ], );
datalog.addRule( "admin", ["?user", "?group"], [["role", "?user", "manager", "?group"]], );
datalog.addRule( "admin", ["?user", "?group"], [ ["in_group", "?user", "?group"], ["role", "?user", "administrator", "?group"], ], );
// Rule to infer documents datalog.addRule( "documents", ["?user", "?doc", "?role"], [ ["admin", "?user", "?group"], ["group", "?group", "?org"], ["role", "?org", "?role", "?type"], ["type", "?doc", "?type"], ["document", "?doc", "?other"], ], );
// Group administrator on org datalog.addRule( "documents", ["?group", "?doc", "?role"], [ ["group", "?group", "?org"], ["role", "?group", "administrator", "?org"], ["role", "?org", "?role", "?type"], ["type", "?doc", "?type"], ["document", "?doc", "?other"], ], ); datalog.addRule( "documents", ["?user", "?doc", "?role"], [ ["folder", "?folder", "?user"], ["role", "?folder", "?role", "?doc"], ], );
datalog.addRule( "documents", ["?user", "?doc", "?role"], [ ["document", "?doc", "?user"], ["role", "?user", "?role", "?doc"], ], );
const documents = datalog.query("documents", "?group", "?", "?role"); // const types = datalog.query("types", "?entity", "?type"); const admins = datalog.query("admin", "?"); console.log(documents);
let's modify our fact such that it can be stored as CREATE TABLE tuples ( object_namespace text NOT NULL, object_id text NOT NULL, object_relation text NOT NULL, subject_namespace text, -- nullable because only valid if subject set subject_id text NOT NULL, subject_relation text -- again only applicable for subject sets );
Here's how we can modify the Datalog engine to store facts in a SQL table:
class DatalogEngine {
constructor() {
this.db = new Database(); // SQL database connection
}
addFact(predicate, subjectNamespace, subjectId, objectNamespace, objectId, relation) {
this.db.run(`
INSERT INTO tuples (
object_namespace,
object_id,
object_relation,
subject_namespace,
subject_id,
subject_relation
) VALUES (
?, ?, ?, ?, ?, ?
)
`, [objectNamespace, objectId, predicate, subjectNamespace, subjectId, relation]);
}
// Other methods...
query(queryPredicate, ...queryArgs) {
const sql = `
SELECT * FROM tuples
WHERE object_relation = ?
${queryArgs.map(arg => `AND object_id = ?`).join(' ')}
`;
const results = this.db.all(sql, [queryPredicate, ...queryArgs]);
// Rest of method...
}
}
We make the following changes:
tuples with the specified schemaaddFact() method inserts into this tablequery() method queries this table to get facts matching the predicate and argumentsThis allows us to store the facts persistently in a database, rather than in memory. Let me know if you have any other questions!