kbs 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/README.md +52 -25
  4. data/lib/kbs/agenda.rb +208 -0
  5. data/lib/kbs/alpha_memory.rb +55 -7
  6. data/lib/kbs/alpha_network.rb +83 -0
  7. data/lib/kbs/beta_memory.rb +54 -19
  8. data/lib/kbs/blackboard/audit_log.rb +26 -25
  9. data/lib/kbs/blackboard/engine.rb +49 -40
  10. data/lib/kbs/blackboard/fact.rb +17 -21
  11. data/lib/kbs/blackboard/memory.rb +116 -40
  12. data/lib/kbs/blackboard/message_queue.rb +39 -28
  13. data/lib/kbs/blackboard/persistence/hybrid_store.rb +20 -9
  14. data/lib/kbs/blackboard/persistence/redis_store.rb +59 -51
  15. data/lib/kbs/blackboard/persistence/sqlite_store.rb +29 -32
  16. data/lib/kbs/blackboard/persistence/store.rb +11 -1
  17. data/lib/kbs/blackboard/redis_message_queue.rb +16 -7
  18. data/lib/kbs/condition.rb +39 -2
  19. data/lib/kbs/decompiler.rb +300 -124
  20. data/lib/kbs/dsl/condition_helpers.rb +8 -6
  21. data/lib/kbs/dsl/knowledge_base.rb +73 -93
  22. data/lib/kbs/dsl/pattern_evaluator.rb +38 -15
  23. data/lib/kbs/dsl/rule_builder.rb +118 -40
  24. data/lib/kbs/dsl/variable.rb +51 -6
  25. data/lib/kbs/dsl.rb +10 -3
  26. data/lib/kbs/engine.rb +395 -77
  27. data/lib/kbs/errors.rb +38 -0
  28. data/lib/kbs/exists_node.rb +12 -0
  29. data/lib/kbs/fact.rb +5 -19
  30. data/lib/kbs/fact_registry.rb +51 -0
  31. data/lib/kbs/introspection.rb +93 -0
  32. data/lib/kbs/join_indexing.rb +104 -0
  33. data/lib/kbs/join_node.rb +93 -57
  34. data/lib/kbs/join_test_builder.rb +80 -0
  35. data/lib/kbs/join_tests.rb +66 -0
  36. data/lib/kbs/memory_index.rb +75 -0
  37. data/lib/kbs/negation_node.rb +6 -82
  38. data/lib/kbs/network_node.rb +31 -0
  39. data/lib/kbs/pattern_matching.rb +27 -0
  40. data/lib/kbs/production_node.rb +50 -6
  41. data/lib/kbs/quantifier_node.rb +140 -0
  42. data/lib/kbs/rule.rb +26 -13
  43. data/lib/kbs/rule_source.rb +74 -0
  44. data/lib/kbs/rule_step.rb +27 -0
  45. data/lib/kbs/token.rb +60 -10
  46. data/lib/kbs/tracer.rb +80 -0
  47. data/lib/kbs/truth_maintenance.rb +82 -0
  48. data/lib/kbs/version.rb +1 -1
  49. data/lib/kbs/working_memory.rb +25 -3
  50. data/lib/kbs.rb +17 -4
  51. metadata +22 -129
  52. data/.envrc +0 -3
  53. data/.github/workflows/deploy-github-pages.yml +0 -52
  54. data/COMMITS.md +0 -196
  55. data/Rakefile +0 -8
  56. data/docs/advanced/custom-persistence.md +0 -775
  57. data/docs/advanced/debugging.md +0 -726
  58. data/docs/advanced/index.md +0 -8
  59. data/docs/advanced/performance.md +0 -865
  60. data/docs/advanced/testing.md +0 -827
  61. data/docs/api/blackboard.md +0 -1157
  62. data/docs/api/engine.md +0 -1047
  63. data/docs/api/facts.md +0 -1212
  64. data/docs/api/index.md +0 -12
  65. data/docs/api/rules.md +0 -1104
  66. data/docs/architecture/blackboard.md +0 -544
  67. data/docs/architecture/index.md +0 -277
  68. data/docs/architecture/network-structure.md +0 -343
  69. data/docs/architecture/rete-algorithm.md +0 -737
  70. data/docs/assets/css/custom.css +0 -83
  71. data/docs/assets/images/blackboard-architecture.svg +0 -136
  72. data/docs/assets/images/compiled-network.svg +0 -101
  73. data/docs/assets/images/fact-assertion-flow.svg +0 -117
  74. data/docs/assets/images/fact-rule-relationship.svg +0 -65
  75. data/docs/assets/images/fact-structure.svg +0 -42
  76. data/docs/assets/images/inference-cycle.svg +0 -47
  77. data/docs/assets/images/kb-components.svg +0 -43
  78. data/docs/assets/images/kbs.jpg +0 -0
  79. data/docs/assets/images/pattern-matching-trace.svg +0 -136
  80. data/docs/assets/images/rete-network-layers.svg +0 -96
  81. data/docs/assets/images/rule-structure.svg +0 -44
  82. data/docs/assets/images/system-layers.svg +0 -69
  83. data/docs/assets/images/trading-signal-network.svg +0 -139
  84. data/docs/assets/js/mathjax.js +0 -17
  85. data/docs/examples/index.md +0 -223
  86. data/docs/guides/blackboard-memory.md +0 -589
  87. data/docs/guides/dsl.md +0 -1321
  88. data/docs/guides/facts.md +0 -652
  89. data/docs/guides/getting-started.md +0 -385
  90. data/docs/guides/index.md +0 -23
  91. data/docs/guides/negation.md +0 -529
  92. data/docs/guides/pattern-matching.md +0 -561
  93. data/docs/guides/persistence.md +0 -451
  94. data/docs/guides/variable-binding.md +0 -491
  95. data/docs/guides/writing-rules.md +0 -914
  96. data/docs/index.md +0 -155
  97. data/docs/installation.md +0 -156
  98. data/docs/quick-start.md +0 -221
  99. data/docs/what-is-a-fact.md +0 -694
  100. data/docs/what-is-a-knowledge-base.md +0 -350
  101. data/docs/what-is-a-rule.md +0 -833
  102. data/examples/.gitignore +0 -1
  103. data/examples/README.md +0 -531
  104. data/examples/advanced_example.rb +0 -270
  105. data/examples/advanced_example_dsl.rb +0 -224
  106. data/examples/ai_enhanced_kbs.rb +0 -523
  107. data/examples/ai_enhanced_kbs_dsl.rb +0 -538
  108. data/examples/blackboard_demo.rb +0 -50
  109. data/examples/blackboard_demo_dsl.rb +0 -50
  110. data/examples/car_diagnostic.rb +0 -64
  111. data/examples/car_diagnostic_dsl.rb +0 -54
  112. data/examples/concurrent_inference_demo.rb +0 -362
  113. data/examples/concurrent_inference_demo_dsl.rb +0 -362
  114. data/examples/csv_trading_system.rb +0 -559
  115. data/examples/csv_trading_system_dsl.rb +0 -525
  116. data/examples/iot_demo_using_dsl.rb +0 -83
  117. data/examples/portfolio_rebalancing_system.rb +0 -651
  118. data/examples/portfolio_rebalancing_system_dsl.rb +0 -613
  119. data/examples/redis_trading_demo.rb +0 -177
  120. data/examples/redis_trading_demo_dsl.rb +0 -177
  121. data/examples/rule_source_demo.rb +0 -123
  122. data/examples/run_all.rb +0 -50
  123. data/examples/run_all_dsl.rb +0 -49
  124. data/examples/sample_stock_data.csv +0 -46
  125. data/examples/stock_trading_advanced.rb +0 -469
  126. data/examples/stock_trading_advanced_dsl.rb +0 -404
  127. data/examples/temp_dsl.txt +0 -9392
  128. data/examples/timestamped_trading.rb +0 -286
  129. data/examples/timestamped_trading_dsl.rb +0 -258
  130. data/examples/trading_demo.rb +0 -334
  131. data/examples/trading_demo_dsl.rb +0 -322
  132. data/examples/working_demo.rb +0 -176
  133. data/examples/working_demo_dsl.rb +0 -160
  134. data/mkdocs.yml +0 -181
@@ -1,57 +1,92 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KBS
4
+ # The partial matches (tokens) of a rule up to one condition. Passes each
5
+ # new token on to the nodes for the next condition.
4
6
  class BetaMemory
5
- attr_accessor :tokens, :successors
7
+ attr_accessor :successors
6
8
  attr_reader :linked
7
9
 
10
+ # An object told, through token_removed(token), about each token
11
+ # that leaves this memory.
12
+ attr_accessor :listener
13
+
8
14
  def initialize
9
- @tokens = []
15
+ @tokens = Set.new
10
16
  @successors = []
11
17
  @linked = true
18
+ @indexes = {}
19
+ @listener = nil
20
+ end
21
+
22
+ # @return [Array<KBS::Token>] the tokens in this memory, in the order
23
+ # they arrived. A copy: use #add_token and #remove_token to change
24
+ # the memory.
25
+ def tokens
26
+ @tokens.to_a
27
+ end
28
+
29
+ def each_token(&)
30
+ @tokens.each(&)
31
+ end
32
+
33
+ def size
34
+ @tokens.size
35
+ end
36
+
37
+ def include?(token)
38
+ @tokens.include?(token)
12
39
  end
13
40
 
14
41
  def unlink!
15
42
  @linked = false
16
- @successors.each { |s| s.left_unlink! if s.respond_to?(:left_unlink!) }
43
+ @successors.each(&:left_unlink!)
17
44
  end
18
45
 
19
46
  def relink!
20
47
  @linked = true
21
- @successors.each { |s| s.left_relink! if s.respond_to?(:left_relink!) }
48
+ @successors.each(&:left_relink!)
22
49
  end
23
50
 
24
51
  def activate(token)
25
52
  add_token(token)
26
- @successors.each do |s|
27
- if s.respond_to?(:left_activate)
28
- s.left_activate(token)
29
- elsif s.respond_to?(:activate)
30
- s.activate(token)
31
- end
32
- end
53
+ @successors.each { |successor| successor.left_activate(token) }
33
54
  end
34
55
 
35
56
  def deactivate(token)
36
57
  remove_token(token)
37
- @successors.each do |s|
38
- if s.respond_to?(:left_deactivate)
39
- s.left_deactivate(token)
40
- elsif s.respond_to?(:deactivate)
41
- s.deactivate(token)
42
- end
43
- end
58
+ @successors.each { |successor| successor.left_deactivate(token) }
44
59
  end
45
60
 
46
61
  def add_token(token)
47
62
  @tokens << token
48
- unlink! if @tokens.empty?
63
+ @indexes.each_value { |index| index.add(token) }
49
64
  relink! if @tokens.size == 1
50
65
  end
51
66
 
52
67
  def remove_token(token)
53
68
  @tokens.delete(token)
69
+ @indexes.each_value { |index| index.remove(token) }
70
+ @listener&.token_removed(token)
54
71
  unlink! if @tokens.empty?
55
72
  end
73
+
74
+ # Forgets every token without telling the successors.
75
+ def clear
76
+ @tokens.clear
77
+ @indexes.each_value(&:clear)
78
+ end
79
+
80
+ # A hash index of the tokens, kept up to date as tokens come and go.
81
+ # Joins with the same specs share one index.
82
+ #
83
+ # @param specs [Array<Array(Integer, Symbol)>] [condition index, field]
84
+ # pairs whose values make up the key
85
+ # @return [KBS::MemoryIndex]
86
+ def index_on(specs)
87
+ @indexes[specs] ||= MemoryIndex.new { |token| MemoryIndex.token_key(token, specs) }.tap do |index|
88
+ @tokens.each { |token| index.add(token) }
89
+ end
90
+ end
56
91
  end
57
92
  end
@@ -5,6 +5,7 @@ require 'time'
5
5
 
6
6
  module KBS
7
7
  module Blackboard
8
+ # Records every fact change and rule firing of a blackboard in SQLite.
8
9
  class AuditLog
9
10
  def initialize(db, session_id)
10
11
  @db = db
@@ -52,22 +53,22 @@ module KBS
52
53
  def log_rule_firing(rule_name, fact_uuids, bindings = {})
53
54
  @db.execute(
54
55
  "INSERT INTO rules_fired (rule_name, fact_uuids, bindings, session_id) VALUES (?, ?, ?, ?)",
55
- [rule_name, JSON.generate(fact_uuids), JSON.generate(bindings), @session_id]
56
+ [rule_name.to_s, JSON.generate(fact_uuids), JSON.generate(bindings), @session_id]
56
57
  )
57
58
  end
58
59
 
59
60
  def fact_history(fact_uuid = nil, limit: 100)
60
- if fact_uuid
61
- results = @db.execute(
62
- "SELECT * FROM fact_history WHERE fact_uuid = ? ORDER BY timestamp DESC, id DESC LIMIT ?",
63
- [fact_uuid, limit]
64
- )
65
- else
66
- results = @db.execute(
67
- "SELECT * FROM fact_history ORDER BY timestamp DESC, id DESC LIMIT ?",
68
- [limit]
69
- )
70
- end
61
+ results = if fact_uuid
62
+ @db.execute(
63
+ "SELECT * FROM fact_history WHERE fact_uuid = ? ORDER BY timestamp DESC, id DESC LIMIT ?",
64
+ [fact_uuid, limit]
65
+ )
66
+ else
67
+ @db.execute(
68
+ "SELECT * FROM fact_history ORDER BY timestamp DESC, id DESC LIMIT ?",
69
+ [limit]
70
+ )
71
+ end
71
72
 
72
73
  results.map do |row|
73
74
  {
@@ -75,31 +76,31 @@ module KBS
75
76
  fact_type: row['fact_type'].to_sym,
76
77
  attributes: JSON.parse(row['attributes'], symbolize_names: true),
77
78
  action: row['action'],
78
- timestamp: Time.parse(row['timestamp']),
79
+ timestamp: Time.parse("#{row['timestamp']} UTC").localtime,
79
80
  session_id: row['session_id']
80
81
  }
81
82
  end
82
83
  end
83
84
 
84
85
  def rule_firings(rule_name = nil, limit: 100)
85
- if rule_name
86
- results = @db.execute(
87
- "SELECT * FROM rules_fired WHERE rule_name = ? ORDER BY fired_at DESC LIMIT ?",
88
- [rule_name, limit]
89
- )
90
- else
91
- results = @db.execute(
92
- "SELECT * FROM rules_fired ORDER BY fired_at DESC LIMIT ?",
93
- [limit]
94
- )
95
- end
86
+ results = if rule_name
87
+ @db.execute(
88
+ "SELECT * FROM rules_fired WHERE rule_name = ? ORDER BY fired_at DESC LIMIT ?",
89
+ [rule_name.to_s, limit]
90
+ )
91
+ else
92
+ @db.execute(
93
+ "SELECT * FROM rules_fired ORDER BY fired_at DESC LIMIT ?",
94
+ [limit]
95
+ )
96
+ end
96
97
 
97
98
  results.map do |row|
98
99
  {
99
100
  rule_name: row['rule_name'],
100
101
  fact_uuids: JSON.parse(row['fact_uuids']),
101
102
  bindings: row['bindings'] ? JSON.parse(row['bindings'], symbolize_names: true) : {},
102
- fired_at: Time.parse(row['fired_at']),
103
+ fired_at: Time.parse("#{row['fired_at']} UTC").localtime,
103
104
  session_id: row['session_id']
104
105
  }
105
106
  end
@@ -9,48 +9,69 @@ module KBS
9
9
  class Engine < KBS::Engine
10
10
  attr_reader :blackboard
11
11
 
12
- def initialize(db_path: ':memory:', store: nil)
13
- super()
12
+ def initialize(db_path: ':memory:', store: nil, strategy: :definition, fact_duplication: true)
13
+ super(strategy: strategy, fact_duplication: fact_duplication)
14
14
  @blackboard = Memory.new(db_path: db_path, store: store)
15
15
  @working_memory = @blackboard
16
16
  @blackboard.add_observer(self)
17
+ # Files the facts already stored, so duplicates of them are refused.
18
+ self.fact_duplication = fact_duplication
17
19
  end
18
20
 
19
- def add_fact(type, attributes = {})
21
+ # Writes the fact to the blackboard, which tells this engine to
22
+ # match it.
23
+ def create_fact(type, attributes)
20
24
  @blackboard.add_fact(type, attributes)
21
25
  end
22
26
 
23
- def remove_fact(fact)
24
- @blackboard.remove_fact(fact)
25
- end
27
+ # Changes a fact's attributes in the store and matches it again. The
28
+ # fact keeps its uuid, and the audit log records an UPDATE.
29
+ #
30
+ # Fact#update and Fact#[]= write to the store but do not match the
31
+ # fact again.
32
+ #
33
+ # @return [KBS::Blackboard::Fact, nil] the fact with its new
34
+ # attributes; the existing equal fact when duplication is off and
35
+ # the change makes this fact a duplicate (this fact is then
36
+ # removed); nil when the fact is not on the blackboard
37
+ def modify(fact, changes)
38
+ ensure_not_matching!
39
+ current = @blackboard.find_fact(fact)
40
+ return nil unless current
26
41
 
27
- def update(action, fact)
28
- if action == :add
29
- @alpha_memories.each do |pattern, memory|
30
- memory.activate(fact) if fact.matches?(pattern)
31
- end
32
- elsif action == :remove
33
- @alpha_memories.each do |pattern, memory|
34
- memory.deactivate(fact) if fact.matches?(pattern)
35
- end
42
+ attributes = fact.is_a?(Fact) ? fact.attributes : current.attributes
43
+ existing = duplicate_of(current.type, attributes.merge(changes))
44
+ if existing && existing != current
45
+ @blackboard.remove_fact(current)
46
+ return existing
36
47
  end
48
+
49
+ @blackboard.modify_fact(fact, changes)
37
50
  end
38
51
 
39
- def run
40
- @production_nodes.values.each do |node|
41
- node.tokens.each do |token|
42
- # Only fire if not already fired
43
- next if token.fired?
52
+ # Records the firing in the audit log, then fires the rule.
53
+ def fire_activation(activation)
54
+ log_firing(activation)
55
+ super
56
+ end
44
57
 
45
- fact_uuids = token.facts.map { |f| f.respond_to?(:uuid) ? f.uuid : f.object_id.to_s }
46
- bindings = extract_bindings_from_token(token, node.rule)
58
+ # Writes the activation's firing to the audit log, unless its rule
59
+ # has fired for that token already. Rules that share join nodes
60
+ # share tokens, so whether a rule fired is asked of its production
61
+ # node, not of the token.
62
+ def log_firing(activation)
63
+ token = activation.token
64
+ return if activation.node.fired?(token)
47
65
 
48
- @blackboard.log_rule_firing(node.rule.name, fact_uuids, bindings)
49
- node.fire_rule(token)
50
- end
51
- end
66
+ rule = activation.rule
67
+ facts = token.facts
68
+ @blackboard.log_rule_firing(rule.name, facts.map(&:uuid), rule.bindings_for(facts))
52
69
  end
53
70
 
71
+ # A reset empties the network, not the store: the persisted facts
72
+ # stay on the blackboard.
73
+ def clear_working_memory; end
74
+
54
75
  def post_message(sender, topic, content, priority: 0)
55
76
  @blackboard.post_message(sender, topic, content, priority: priority)
56
77
  end
@@ -63,20 +84,8 @@ module KBS
63
84
  @blackboard.stats
64
85
  end
65
86
 
66
- private
67
-
68
- def extract_bindings_from_token(token, rule)
69
- bindings = {}
70
- rule.conditions.each_with_index do |condition, index|
71
- next if condition.negated
72
- fact = token.facts[index]
73
- if fact && condition.respond_to?(:variable_bindings)
74
- condition.variable_bindings.each do |var, field|
75
- bindings[var] = fact.attributes[field] if fact.respond_to?(:attributes)
76
- end
77
- end
78
- end
79
- bindings
87
+ def close
88
+ @blackboard.close
80
89
  end
81
90
  end
82
91
  end
@@ -4,6 +4,8 @@ module KBS
4
4
  module Blackboard
5
5
  # A fact in the blackboard with persistence capabilities
6
6
  class Fact
7
+ include PatternMatching
8
+
7
9
  attr_reader :uuid, :type, :attributes
8
10
 
9
11
  def initialize(uuid, type, attributes, blackboard = nil)
@@ -13,40 +15,34 @@ module KBS
13
15
  @blackboard = blackboard
14
16
  end
15
17
 
18
+ # Facts are identified by uuid. The blackboard builds a new Fact
19
+ # object each time it reads or removes one, so the Rete network
20
+ # must find the object it holds by uuid, not by identity.
21
+ def ==(other)
22
+ other.is_a?(Fact) && other.uuid == @uuid
23
+ end
24
+ alias eql? ==
25
+
26
+ def hash
27
+ [Fact, @uuid].hash
28
+ end
29
+
16
30
  def [](key)
17
31
  @attributes[key]
18
32
  end
19
33
 
20
34
  def []=(key, value)
21
35
  @attributes[key] = value
22
- @blackboard.update_fact(self, @attributes) if @blackboard
36
+ @blackboard&.update_fact(self, @attributes)
23
37
  end
24
38
 
25
39
  def update(new_attributes)
26
40
  @attributes.merge!(new_attributes)
27
- @blackboard.update_fact(self, @attributes) if @blackboard
41
+ @blackboard&.update_fact(self, @attributes)
28
42
  end
29
43
 
30
44
  def retract
31
- @blackboard.remove_fact(self) if @blackboard
32
- end
33
-
34
- def matches?(pattern)
35
- return false if pattern[:type] && pattern[:type] != @type
36
-
37
- pattern.each do |key, value|
38
- next if key == :type
39
-
40
- if value.is_a?(Proc)
41
- return false unless @attributes[key] && value.call(@attributes[key])
42
- elsif value.is_a?(Symbol) && value.to_s.end_with?('?')
43
- next
44
- else
45
- return false unless @attributes[key] == value
46
- end
47
- end
48
-
49
- true
45
+ @blackboard&.remove_fact(self)
50
46
  end
51
47
 
52
48
  def to_s
@@ -14,43 +14,65 @@ module KBS
14
14
  attr_reader :session_id, :store, :message_queue, :audit_log
15
15
 
16
16
  def initialize(db_path: ':memory:', store: nil)
17
- @session_id = SecureRandom.uuid
17
+ self.class.check_store(store) if store
18
+ @session_id = store&.session_id || SecureRandom.uuid
18
19
  @observers = []
20
+ @added_in_transaction = nil
21
+ @store = store || Persistence::SqliteStore.new(db_path: db_path, session_id: @session_id)
22
+ @message_queue, @audit_log = build_components
23
+ end
19
24
 
20
- # Use provided store or create default SqliteStore
21
- @store = store || Persistence::SqliteStore.new(
22
- db_path: db_path,
23
- session_id: @session_id
24
- )
25
+ # Raises ArgumentError unless the memory can build its message queue
26
+ # and audit log on `store`.
27
+ def self.check_store(store)
28
+ return if store.respond_to?(:connection) || store.respond_to?(:db)
25
29
 
26
- # Initialize composed components based on store type
27
- setup_components
30
+ raise ArgumentError, "Store must respond to either :connection (Redis) or :db (SQLite)"
28
31
  end
29
32
 
30
33
  private
31
34
 
32
- def setup_components
33
- # Detect store type and create appropriate MessageQueue and AuditLog
35
+ # The message queue and audit log that go with the store. A store is
36
+ # told apart by what it offers: a hybrid store keeps messages in
37
+ # Redis and the audit log in SQLite, a store with a connection is
38
+ # Redis, and one with a db is SQLite.
39
+ def build_components
34
40
  if @store.respond_to?(:hybrid?) && @store.hybrid?
35
- # Hybrid store: Redis for messages, SQLite for audit
36
- require_relative 'redis_message_queue'
37
- @message_queue = RedisMessageQueue.new(@store.connection)
38
- @audit_log = AuditLog.new(@store.db, @session_id)
41
+ hybrid_components
39
42
  elsif @store.respond_to?(:connection)
40
- # Pure Redis store
41
- require_relative 'redis_message_queue'
42
- require_relative 'redis_audit_log'
43
- @message_queue = RedisMessageQueue.new(@store.connection)
44
- @audit_log = RedisAuditLog.new(@store.connection, @session_id)
45
- elsif @store.respond_to?(:db)
46
- # Pure SQLite store
47
- @message_queue = MessageQueue.new(@store.db)
48
- @audit_log = AuditLog.new(@store.db, @session_id)
43
+ redis_components
49
44
  else
50
- raise ArgumentError, "Store must respond to either :connection (Redis) or :db (SQLite)"
45
+ sqlite_components
51
46
  end
52
47
  end
53
48
 
49
+ def hybrid_components
50
+ require_relative 'redis_message_queue'
51
+ [RedisMessageQueue.new(@store.connection), AuditLog.new(@store.db, @session_id)]
52
+ end
53
+
54
+ def redis_components
55
+ require_relative 'redis_message_queue'
56
+ require_relative 'redis_audit_log'
57
+ connection = @store.connection
58
+ [RedisMessageQueue.new(connection), RedisAuditLog.new(connection, @session_id)]
59
+ end
60
+
61
+ def sqlite_components
62
+ database = @store.db
63
+ [MessageQueue.new(database), AuditLog.new(database, @session_id)]
64
+ end
65
+
66
+ # A fact's uuid, given the fact or the uuid itself.
67
+ def uuid_of(fact)
68
+ fact.is_a?(Fact) ? fact.uuid : fact
69
+ end
70
+
71
+ # The Fact for a row the store returned.
72
+ def fact_from(data)
73
+ Fact.new(*data.values_at(:uuid, :type, :attributes), self)
74
+ end
75
+
54
76
  public
55
77
 
56
78
  # Fact Management
@@ -63,27 +85,31 @@ module KBS
63
85
  end
64
86
 
65
87
  fact = Fact.new(uuid, type, attributes, self)
88
+ @added_in_transaction[uuid] = fact if @added_in_transaction
66
89
  notify_observers(:add, fact)
67
90
  fact
68
91
  end
69
92
 
93
+ # @return [KBS::Blackboard::Fact, nil] the removed fact, or nil when
94
+ # it was not active
70
95
  def remove_fact(fact)
71
- uuid = fact.is_a?(Fact) ? fact.uuid : fact
96
+ uuid = uuid_of(fact)
72
97
 
73
98
  @store.transaction do
74
99
  result = @store.remove_fact(uuid)
100
+ next unless result
75
101
 
76
- if result
77
- @audit_log.log_fact_change(uuid, result[:type], result[:attributes], 'REMOVE')
102
+ @audit_log.log_fact_change(uuid, result[:type], result[:attributes], 'REMOVE')
78
103
 
79
- fact_obj = Fact.new(uuid, result[:type], result[:attributes], self)
80
- notify_observers(:remove, fact_obj)
81
- end
104
+ fact_obj = Fact.new(uuid, result[:type], result[:attributes], self)
105
+ @added_in_transaction&.delete(uuid)
106
+ notify_observers(:remove, fact_obj)
107
+ fact_obj
82
108
  end
83
109
  end
84
110
 
85
111
  def update_fact(fact, new_attributes)
86
- uuid = fact.is_a?(Fact) ? fact.uuid : fact
112
+ uuid = uuid_of(fact)
87
113
 
88
114
  @store.transaction do
89
115
  fact_type = @store.update_fact(uuid, new_attributes)
@@ -94,12 +120,41 @@ module KBS
94
120
  end
95
121
  end
96
122
 
123
+ # The fact with this uuid as the store holds it now, or nil.
124
+ #
125
+ # @param fact [KBS::Blackboard::Fact, String] a fact or its uuid
126
+ def find_fact(fact)
127
+ uuid = uuid_of(fact)
128
+ data = @store.get_fact(uuid)
129
+ data && Fact.new(uuid, data[:type], data[:attributes], self)
130
+ end
131
+
132
+ # Merges `changes` into a fact's attributes and tells the observers
133
+ # it was removed and added again, so an engine matches the new
134
+ # values. The uuid is kept.
135
+ #
136
+ # @return [KBS::Blackboard::Fact, nil] the fact with its new
137
+ # attributes, or nil when it is not in the store
138
+ def modify_fact(fact, changes)
139
+ current = find_fact(fact)
140
+ return nil unless current
141
+
142
+ # A Fact passed in still has its attributes as they were given;
143
+ # the store's copy has been through JSON, which turns Symbol
144
+ # values into Strings.
145
+ attributes = (fact.is_a?(Fact) ? fact : current).attributes.merge(changes)
146
+ update_fact(current, attributes)
147
+
148
+ notify_observers(:remove, current)
149
+ modified = Fact.new(current.uuid, current.type, attributes, self)
150
+ notify_observers(:add, modified)
151
+ modified
152
+ end
153
+
97
154
  def get_facts(type = nil, pattern = {})
98
155
  fact_data = @store.get_facts(type, pattern)
99
156
 
100
- fact_data.map do |data|
101
- Fact.new(data[:uuid], data[:type], data[:attributes], self)
102
- end
157
+ fact_data.map { |data| fact_from(data) }
103
158
  end
104
159
 
105
160
  # Alias for compatibility with WorkingMemory interface
@@ -110,9 +165,7 @@ module KBS
110
165
  def query_facts(sql_conditions = nil, params = [])
111
166
  fact_data = @store.query_facts(sql_conditions, params)
112
167
 
113
- fact_data.map do |data|
114
- Fact.new(data[:uuid], data[:type], data[:attributes], self)
115
- end
168
+ fact_data.map { |data| fact_from(data) }
116
169
  end
117
170
 
118
171
  # Message Queue delegation
@@ -162,8 +215,31 @@ module KBS
162
215
  @store.clear_session(@session_id)
163
216
  end
164
217
 
165
- def transaction(&block)
166
- @store.transaction(&block)
218
+ # Runs the block in a store transaction. When the block raises, the
219
+ # facts it added that the store rolled back are removed from the
220
+ # observers (an engine) as well. A store that cannot roll back, such
221
+ # as Redis, keeps them, and so do the observers. Facts the block
222
+ # removed or modified are not restored in the observers.
223
+ def transaction(&)
224
+ return @store.transaction(&) if @added_in_transaction
225
+
226
+ @added_in_transaction = {}
227
+ begin
228
+ @store.transaction(&)
229
+ rescue StandardError
230
+ withdraw_rolled_back(@added_in_transaction.values)
231
+ raise
232
+ ensure
233
+ @added_in_transaction = nil
234
+ end
235
+ end
236
+
237
+ # Tells the observers each fact the store no longer holds was
238
+ # removed, newest first.
239
+ def withdraw_rolled_back(facts)
240
+ facts.reverse_each do |fact|
241
+ notify_observers(:remove, fact) unless @store.get_fact(fact.uuid)
242
+ end
167
243
  end
168
244
 
169
245
  # Statistics
@@ -185,7 +261,7 @@ module KBS
185
261
  end
186
262
 
187
263
  # For backward compatibility with ReteEngine
188
- alias_method :db, :store
264
+ alias db store
189
265
  end
190
266
  end
191
267
  end