kbs 0.3.0 → 0.4.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4b6c4a01ce43cb0e03e62c3a2c3408eee1ea1926be20e3153174323a7cf1df5c
4
- data.tar.gz: fb3f9f2ef51558bf292397a6c27fd53772456f46298b637e0908d502cfb01e2b
3
+ metadata.gz: 481d313c3b2209c082586165c521c611ef365a76c00aadbd00c29fa5713380d8
4
+ data.tar.gz: 818ee36d1b51568683a3953905417a4e098d1cebfd69c8a0f97b764557c31efe
5
5
  SHA512:
6
- metadata.gz: 862649575330472c4466b8159e7788b50f6ee2a3aaac4e7210ed91c4e437bf7715749646b9e48d7b6056ad38b4fed37a20177645be8e2e7b8c14c9b941d435b5
7
- data.tar.gz: 4dad7e5d1333bae4c1c9c9bcb38e984dc2f08d23b19b44994de620bb09a9430859c65c0202709f38e84768430a60b0d5fde1d41b515266b64ff2c328ce1e293f
6
+ metadata.gz: '0386b6fedbc7c781e5ac99b805899b655091bc3b043bde464fb6717451f015879a2047b1807f7d5bb13bb88b7400fd8040ebc844a7e787305fa808f83daad58a'
7
+ data.tar.gz: b88d4baba525d8aec2ccd086de8817ef612c32a243b08a71a95b920fcd1bc900d1cdf39edb1572818d96c5b48a4d9362d28a892cfd31ea23e0deb21f56578b29
data/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.4.0] - Unreleased
4
+
5
+ Faster matching and rule firing. What matches and the order rules fire in are unchanged for every strategy.
6
+
7
+ ### Breaking changes
8
+ - The facts an action receives (`Token#facts`) are frozen; copy them with `dup` before changing them.
9
+ - `Token#children` for a token with a single child returns a frozen one-element Set; change children through `add_child` / `remove_child` as before.
10
+ - `Activation#sort_key` is computed when called, from the new `Activation#strategy` the agenda sets; `Activation#sort_key=` is gone.
11
+ - `MemoryIndex.fact_key` and `MemoryIndex.token_key` return the value itself for a single field, and `MemoryIndex#lookup` may return an Array.
12
+
13
+ ### Changed
14
+ - **Agenda grouped by salience, as in CLIPS.** Activations are filed by salience and, under `:definition`, by rule; within a group `:depth` takes the newest first and `:breadth` / `:definition` the oldest first. Adding and popping no longer compare sort keys, which took about 40% of CPU in an assert-and-`run` profile. Firing 3n activations from three rules runs about 3 to 3.7 times faster (see `docs/advanced/performance.md`).
15
+ - **Fewer allocations per fact and per match.** A join index keys a single field by its value instead of an Array, and a bucket holds a lone fact or token without a `Set`. Each alpha memory prepares its pattern's tests once and skips the `?variables`. `Fact#matches?` no longer builds a pair per pattern entry, joins hand on their candidates without copying them, and the alpha network builds a candidate list only when more than one applies. A token with one child keeps it without a `Set`, and the Sets that hold tokens compare by identity. Joins, negation and retraction run about 15% to 45% faster at n=2000 (25% to 70% with YJIT).
16
+
17
+ ### Added
18
+ - `benchmarks/rete_scaling.rb` measures firing (`run`) under the `:definition` and `:depth` strategies.
19
+ - Fasterer is in the development bundle, so the `asgard quality` Fasterer gate runs instead of being skipped; `.fasterer.yml` records the one speedup turned off.
20
+ - README and the performance guide recommend running with YJIT (`ruby --yjit` or `RUBY_YJIT_ENABLE=1`), which is roughly 1.5 to 2.5 times faster on these benchmarks.
21
+
3
22
  ## [0.3.0] - 2026-11-20
4
23
 
5
24
  The engine now works like CLIPS: an agenda with conflict resolution, truth maintenance, `exists`, `modify`, and joins on shared `?variables`. Matching and retraction use indexes instead of scans.
data/README.md CHANGED
@@ -332,6 +332,20 @@ Facts → Alpha Network → Beta Network → Production Nodes
332
332
 
333
333
  ## ⚡ Performance
334
334
 
335
+ ### Run with YJIT
336
+
337
+ Turn on YJIT, the JIT compiler built into CRuby. It makes KBS roughly 1.5 to 2.5 times faster with no code changes:
338
+
339
+ ```bash
340
+ ruby --yjit app.rb # or set RUBY_YJIT_ENABLE=1
341
+ ```
342
+
343
+ ```ruby
344
+ RubyVM::YJIT.enable # or from code, early in boot
345
+ ```
346
+
347
+ `benchmarks/rete_scaling.rb` measures the network with and without it; see [Performance Tuning](docs/advanced/performance.md#running-with-yjit).
348
+
335
349
  ### Benchmarks
336
350
  - **Rule Compilation**: ~1ms per rule for typical patterns
337
351
  - **Fact Addition**: ~0.1ms per fact (warm network)
data/lib/kbs/agenda.rb CHANGED
@@ -4,7 +4,10 @@ module KBS
4
4
  # A rule matched by a token, waiting on the agenda to fire.
5
5
  class Activation
6
6
  attr_reader :node, :token, :salience, :rule_order, :timetag
7
- attr_accessor :sort_key
7
+
8
+ # The conflict resolution strategy of the agenda the activation is on,
9
+ # which #sort_key follows. Set by the agenda; :definition until then.
10
+ attr_accessor :strategy
8
11
 
9
12
  def initialize(node, token, rule_order:, timetag:)
10
13
  @node = node
@@ -13,6 +16,13 @@ module KBS
13
16
  @rule_order = rule_order
14
17
  @timetag = timetag
15
18
  @cancelled = false
19
+ @strategy = :definition
20
+ end
21
+
22
+ # Where the activation sorts on its agenda, lowest first. Built when
23
+ # asked for: the agenda orders activations without it.
24
+ def sort_key
25
+ key_for(@strategy)
16
26
  end
17
27
 
18
28
  def rule
@@ -67,12 +77,123 @@ module KBS
67
77
  # :depth newest activation first
68
78
  # :breadth oldest activation first
69
79
  #
70
- # Activations sit in a binary heap. Removing one marks it cancelled and
71
- # it is dropped when it reaches the top, so add, remove and pop are
72
- # O(log n).
80
+ # Activations are grouped the way CLIPS groups them: by salience, and
81
+ # under :definition also by rule. Groups are kept in firing order, and
82
+ # within a group the order follows from where an activation is put:
83
+ # :depth takes the newest first (a stack), the others the oldest first
84
+ # (a queue). Nothing is compared to add or pop an activation; only an
85
+ # add that opens a new group finds its place, by binary search on a
86
+ # number. Removing an activation marks it cancelled, and it is dropped
87
+ # when it reaches the front of its group.
73
88
  class Agenda
89
+ # Activations taken oldest first.
90
+ class Fifo
91
+ def initialize
92
+ @items = []
93
+ end
94
+
95
+ def <<(activation)
96
+ @items << activation
97
+ self
98
+ end
99
+
100
+ # self when an activation is pending, after dropping the cancelled
101
+ # ones in front of it; nil otherwise.
102
+ def front
103
+ @items.shift while @items.first&.cancelled?
104
+ self unless @items.empty?
105
+ end
106
+
107
+ # The activation to take next. Call #front first.
108
+ def next
109
+ @items.first
110
+ end
111
+
112
+ def take
113
+ @items.shift
114
+ end
115
+
116
+ def each_activation(&)
117
+ @items.each(&)
118
+ end
119
+
120
+ private
121
+
122
+ attr_reader :items
123
+ end
124
+
125
+ # Activations taken newest first.
126
+ class Lifo < Fifo
127
+ def front
128
+ items.pop while items.last&.cancelled?
129
+ self unless items.empty?
130
+ end
131
+
132
+ def next
133
+ items.last
134
+ end
135
+
136
+ def take
137
+ items.pop
138
+ end
139
+ end
140
+
141
+ # Members filed under numeric keys and kept in key order: the salience
142
+ # levels of an agenda, or the rules within one level. A member is
143
+ # made by the block when its key is first used, and is a Fifo, a Lifo
144
+ # or another Groups.
145
+ class Groups
146
+ def initialize(&make)
147
+ @make = make
148
+ @members = {}
149
+ @keys = []
150
+ end
151
+
152
+ # The member for `key`, made and filed in order if it is new.
153
+ def fetch(key)
154
+ @members[key] || file(key)
155
+ end
156
+
157
+ # The first queue with an activation pending, found through the
158
+ # members in key order. Members left with nothing pending are
159
+ # dropped on the way. nil when nothing is pending.
160
+ def front
161
+ until @keys.empty?
162
+ queue = @members[@keys.first].front
163
+ return queue if queue
164
+
165
+ @members.delete(@keys.shift)
166
+ end
167
+ nil
168
+ end
169
+
170
+ def each_activation(&)
171
+ @members.each_value { |member| member.each_activation(&) }
172
+ end
173
+
174
+ private
175
+
176
+ # Activations mostly arrive for keys after the existing ones, so
177
+ # the last key is checked before searching.
178
+ def file(key)
179
+ last = @keys.last
180
+ position = last.nil? || last < key ? @keys.size : @keys.bsearch_index { |other| other >= key }
181
+ @keys.insert(position, key)
182
+ @members[key] = @make.call
183
+ end
184
+ end
185
+
74
186
  STRATEGIES = %i[definition depth breadth].freeze
75
187
 
188
+ # For each strategy: the queue its groups use, and the key that files
189
+ # an activation into a group within its salience level (the position
190
+ # of its rule under :definition, one key for all otherwise).
191
+ LAYOUTS = {
192
+ definition: [Fifo, :rule_order.to_proc],
193
+ depth: [Lifo, proc { 0 }],
194
+ breadth: [Fifo, proc { 0 }]
195
+ }.freeze
196
+
76
197
  attr_reader :strategy, :size
77
198
 
78
199
  # An object told about each activation that is added, and each one
@@ -84,16 +205,20 @@ module KBS
84
205
  @listener = nil
85
206
  validate_strategy(strategy)
86
207
  @strategy = strategy
87
- @heap = []
88
208
  @size = 0
89
209
  @timetag = 0
210
+ @levels = self.class.levels_for(strategy)
211
+ @rule_key = LAYOUTS.fetch(strategy).last
90
212
  end
91
213
 
214
+ # Regroups the pending activations, oldest first, so each new group
215
+ # is in timetag order whatever the old strategy was.
92
216
  def strategy=(strategy)
93
217
  validate_strategy(strategy)
218
+ pending = to_a.sort_by(&:timetag)
94
219
  @strategy = strategy
95
- pending = to_a
96
- @heap = []
220
+ @levels = self.class.levels_for(strategy)
221
+ @rule_key = LAYOUTS.fetch(strategy).last
97
222
  pending.each { |activation| push(activation) }
98
223
  end
99
224
 
@@ -115,18 +240,16 @@ module KBS
115
240
 
116
241
  # Removes and returns the next activation to fire, or nil when empty.
117
242
  def pop
118
- drop_cancelled
119
- return nil if @heap.empty?
243
+ activation = @levels.front&.take
244
+ return nil unless activation
120
245
 
121
- activation = pop_top
122
246
  activation.cancel!
123
247
  @size -= 1
124
248
  activation
125
249
  end
126
250
 
127
251
  def peek
128
- drop_cancelled
129
- @heap.first
252
+ @levels.front&.next
130
253
  end
131
254
 
132
255
  def empty?
@@ -134,20 +257,34 @@ module KBS
134
257
  end
135
258
 
136
259
  def clear
137
- @heap.each(&:cancel!)
138
- @heap = []
260
+ @levels.each_activation(&:cancel!)
261
+ @levels = self.class.levels_for(@strategy)
139
262
  @size = 0
140
263
  end
141
264
 
142
265
  # Pending activations in firing order.
143
266
  def to_a
144
- @heap.reject(&:cancelled?).sort_by(&:sort_key)
267
+ @levels.enum_for(:each_activation).reject(&:cancelled?).sort_by(&:sort_key)
145
268
  end
146
269
 
147
270
  def sort_key_for(activation)
148
271
  activation.key_for(@strategy)
149
272
  end
150
273
 
274
+ # Empty salience levels for `strategy`. Each level holds one group per
275
+ # rule under :definition, and a single group otherwise.
276
+ def self.levels_for(strategy)
277
+ queue = LAYOUTS.fetch(strategy).first
278
+ Groups.new { Groups.new { queue.new } }
279
+ end
280
+
281
+ # The key of the salience level an activation is filed under: its
282
+ # salience negated, so that higher salience sorts first, and
283
+ # normalized, so that 1 and 1.0 share a level.
284
+ def self.level_key(activation)
285
+ -MemoryIndex.normalize(activation.salience)
286
+ end
287
+
151
288
  private
152
289
 
153
290
  def validate_strategy(strategy)
@@ -156,53 +293,9 @@ module KBS
156
293
  raise ArgumentError, "unknown strategy #{strategy.inspect}; use one of #{STRATEGIES.inspect}"
157
294
  end
158
295
 
159
- def drop_cancelled
160
- pop_top while @heap.first&.cancelled?
161
- end
162
-
163
296
  def push(activation)
164
- activation.sort_key = sort_key_for(activation)
165
- @heap << activation
166
- sift_up(@heap.size - 1)
167
- end
168
-
169
- def pop_top
170
- top = @heap.first
171
- last = @heap.pop
172
- unless @heap.empty?
173
- @heap[0] = last
174
- sift_down(0)
175
- end
176
- top
177
- end
178
-
179
- # Whether the activation at heap position `index` sorts before the one
180
- # at `other`.
181
- def before?(index, other)
182
- (@heap[index].sort_key <=> @heap[other].sort_key).negative?
183
- end
184
-
185
- def sift_up(index)
186
- while index.positive?
187
- parent = (index - 1) / 2
188
- break unless before?(index, parent)
189
-
190
- @heap[index], @heap[parent] = @heap[parent], @heap[index]
191
- index = parent
192
- end
193
- end
194
-
195
- def sift_down(index)
196
- loop do
197
- smallest = index
198
- [(2 * index) + 1, (2 * index) + 2].each do |child|
199
- smallest = child if child < @heap.size && before?(child, smallest)
200
- end
201
- break if smallest == index
202
-
203
- @heap[index], @heap[smallest] = @heap[smallest], @heap[index]
204
- index = smallest
205
- end
297
+ activation.strategy = @strategy
298
+ @levels.fetch(self.class.level_key(activation)).fetch(@rule_key.call(activation)) << activation
206
299
  end
207
300
  end
208
301
  end
@@ -4,15 +4,38 @@ module KBS
4
4
  # The facts that fit one condition pattern. Shared by every rule that
5
5
  # uses the pattern; tells its join nodes when a fact arrives or leaves.
6
6
  class AlphaMemory
7
- attr_accessor :successors, :pattern
8
- attr_reader :linked
7
+ attr_accessor :successors
8
+ attr_reader :pattern, :linked
9
9
 
10
10
  def initialize(pattern = {})
11
11
  @items = Set.new
12
12
  @successors = []
13
- @pattern = pattern
14
13
  @linked = true
15
14
  @indexes = {}
15
+ @pattern = pattern
16
+ @fact_type, @tests = self.class.compile(pattern)
17
+ end
18
+
19
+ # Sets the pattern and prepares the tests #admits? runs.
20
+ def pattern=(pattern)
21
+ @pattern = pattern
22
+ @fact_type, @tests = self.class.compile(pattern)
23
+ end
24
+
25
+ # The fact type a pattern requires (nil for any) and the tests from
26
+ # PatternMatching.tests_for.
27
+ def self.compile(pattern)
28
+ [pattern[:type], PatternMatching.tests_for(pattern)]
29
+ end
30
+
31
+ # Whether `fact` fits the pattern: the answer of
32
+ # fact.matches?(pattern), found without looking at the pattern's
33
+ # ?variables, which fit anything.
34
+ def admits?(fact)
35
+ fact_type = @fact_type
36
+ return false if fact_type && fact_type != fact.type
37
+
38
+ PatternMatching.passes?(@tests, fact.attributes)
16
39
  end
17
40
 
18
41
  # @return [Array] the facts in this memory, in the order they arrived.
@@ -33,24 +33,36 @@ module KBS
33
33
  # @return [Array<KBS::AlphaMemory>] the memories whose pattern `fact`
34
34
  # matches, in the order they were created
35
35
  def memories_for(fact)
36
- matches = candidates_for(fact).select { |memory| fact.matches?(memory.pattern) }
36
+ matches = candidates_for(fact).select { |memory| memory.admits?(fact) }
37
37
  matches.size > 1 ? matches.sort_by { |memory| @sequence[memory] } : matches
38
38
  end
39
39
 
40
40
  # @return [Array<KBS::AlphaMemory>] the memories that have to be
41
- # checked for `fact`
41
+ # checked for `fact`. It may be one of the network's own lists, so
42
+ # do not modify it: a new Array is built only when more than one
43
+ # list applies.
42
44
  def candidates_for(fact)
43
45
  type = @types[fact.type]
44
- return @untyped.dup unless type
46
+ return @untyped unless type
45
47
 
46
- candidates = @untyped + type[:unselected]
47
- type[:selectors].each do |attribute, table|
48
- selected = table[MemoryIndex.normalize(fact.attributes[attribute])]
49
- candidates.concat(selected) if selected
48
+ candidates = self.class.join_lists(@untyped, type[:unselected])
49
+ attributes = fact.attributes
50
+ type[:selectors].each_pair do |attribute, table|
51
+ selected = table[MemoryIndex.normalize(attributes[attribute])]
52
+ candidates = self.class.join_lists(candidates, selected) if selected
50
53
  end
51
54
  candidates
52
55
  end
53
56
 
57
+ # `first` followed by `second`: one of them as it is when the other is
58
+ # empty, a new Array otherwise.
59
+ def self.join_lists(first, second)
60
+ return second if first.empty?
61
+ return first if second.empty?
62
+
63
+ first + second
64
+ end
65
+
54
66
  # The attribute and constant a pattern is filed under: its first
55
67
  # attribute tested against a plain value. nil when it has none.
56
68
  #
@@ -12,7 +12,7 @@ module KBS
12
12
  attr_accessor :listener
13
13
 
14
14
  def initialize
15
- @tokens = Set.new
15
+ @tokens = Set.new.compare_by_identity
16
16
  @successors = []
17
17
  @linked = true
18
18
  @indexes = {}
data/lib/kbs/condition.rb CHANGED
@@ -6,6 +6,9 @@ module KBS
6
6
  class Condition
7
7
  attr_reader :type, :pattern, :variable_bindings, :negated, :exists, :logical
8
8
 
9
+ # What #summary puts before a negated or exists condition.
10
+ SUMMARY_PREFIXES = { "without" => "NOT ", "exists" => "EXISTS " }.freeze
11
+
9
12
  # @param negated [Boolean] match when no fact fits the pattern
10
13
  # @param exists [Boolean] match once when at least one fact fits the
11
14
  # pattern, instead of once for each fact
@@ -24,7 +27,7 @@ module KBS
24
27
 
25
28
  # One line for listings: the type and pattern, marked NOT or EXISTS.
26
29
  def summary
27
- prefix = { "without" => "NOT ", "exists" => "EXISTS " }.fetch(keyword, "")
30
+ prefix = SUMMARY_PREFIXES[keyword] || ""
28
31
  "#{prefix}#{@type}(#{RuleSource.pattern_source(@pattern)})"
29
32
  end
30
33
 
data/lib/kbs/engine.rb CHANGED
@@ -266,7 +266,7 @@ module KBS
266
266
 
267
267
  # The alpha memories that hold `fact`.
268
268
  def alpha_memories_for(fact)
269
- @fact_memories.fetch(fact, []).dup
269
+ @fact_memories[fact]&.dup || []
270
270
  end
271
271
 
272
272
  # Fires activations from the agenda until it is empty: the highest
@@ -452,12 +452,12 @@ module KBS
452
452
  # Facts go straight into its items: the memory has no successors yet,
453
453
  # and existing alpha memories already hold their facts.
454
454
  def get_or_create_alpha_memory(pattern)
455
- @alpha_network.fetch(pattern) { |memory| seed_alpha_memory(memory, pattern) }
455
+ @alpha_network.fetch(pattern) { |memory| seed_alpha_memory(memory) }
456
456
  end
457
457
 
458
- def seed_alpha_memory(memory, pattern)
458
+ def seed_alpha_memory(memory)
459
459
  @working_memory.facts.each do |fact|
460
- next unless fact.matches?(pattern)
460
+ next unless memory.admits?(fact)
461
461
 
462
462
  memory.add_item(fact)
463
463
  (@fact_memories[fact] ||= []) << memory
@@ -70,10 +70,12 @@ module KBS
70
70
  @left_index.lookup(MemoryIndex.fact_key(fact, @fact_fields))
71
71
  end
72
72
 
73
- # Facts that join with `token`.
73
+ # Facts that join with `token`. Without residual tests the candidates
74
+ # are the matches, handed on without a copy: joining a match never
75
+ # changes the memory it came from.
74
76
  def matching_facts(token)
75
77
  candidates = candidate_facts(token)
76
- matches = @residual_tests.empty? ? candidates.to_a : candidates.select { |fact| join_tests_pass?(@residual_tests, token, fact) }
78
+ matches = @residual_tests.empty? ? candidates : candidates.select { |fact| join_tests_pass?(@residual_tests, token, fact) }
77
79
  @left_activations += 1
78
80
  count(candidates, matches)
79
81
  end
@@ -81,7 +83,7 @@ module KBS
81
83
  # Tokens that join with `fact`.
82
84
  def matching_tokens(fact)
83
85
  candidates = candidate_tokens(fact)
84
- matches = @residual_tests.empty? ? candidates.to_a : candidates.select { |token| join_tests_pass?(@residual_tests, token, fact) }
86
+ matches = @residual_tests.empty? ? candidates : candidates.select { |token| join_tests_pass?(@residual_tests, token, fact) }
85
87
  @right_activations += 1
86
88
  count(candidates, matches)
87
89
  end
data/lib/kbs/join_node.rb CHANGED
@@ -122,7 +122,7 @@ module KBS
122
122
  case entry
123
123
  when nil then @tokens_by_fact[fact] = token
124
124
  when Set then entry << token
125
- else @tokens_by_fact[fact] = Set[entry, token]
125
+ else @tokens_by_fact[fact] = Set.new.compare_by_identity << entry << token
126
126
  end
127
127
  end
128
128
 
@@ -7,8 +7,12 @@ module KBS
7
7
  #
8
8
  # The key is computed once, when the item is added, and remembered:
9
9
  # removing an item finds its bucket even if its attributes changed since.
10
- # Buckets are Sets, so adding and removing an item do not depend on the
11
- # size of the bucket.
10
+ #
11
+ # A join on an id usually files one item per key, so a bucket holds a
12
+ # lone item itself and becomes a Set only for the second. Sets compare
13
+ # with eql?, as the index's own key table does, so a blackboard fact
14
+ # read again from its store is the same item. Adding and removing an
15
+ # item do not depend on the size of the bucket.
12
16
  class MemoryIndex
13
17
  EMPTY = Set.new.freeze
14
18
 
@@ -22,7 +26,12 @@ module KBS
22
26
  def add(item)
23
27
  key = @key_for.call(item)
24
28
  @keys[item] = key
25
- (@buckets[key] ||= Set.new) << item
29
+ bucket = @buckets[key]
30
+ case bucket
31
+ when nil then @buckets[key] = item
32
+ when Set then bucket << item
33
+ else @buckets[key] = Set[bucket, item] unless bucket.eql?(item)
34
+ end
26
35
  end
27
36
 
28
37
  def remove(item)
@@ -30,14 +39,22 @@ module KBS
30
39
 
31
40
  key = @keys.delete(item)
32
41
  bucket = @buckets[key]
33
- bucket.delete(item)
34
- @buckets.delete(key) if bucket.empty?
42
+ if bucket.is_a?(Set)
43
+ bucket.delete(item)
44
+ return unless bucket.empty?
45
+ end
46
+ @buckets.delete(key)
35
47
  end
36
48
 
37
- # @return [Set] the items filed under `key`, in the order they were
38
- # added; do not modify it
49
+ # @return [Enumerable] the items filed under `key`, in the order they
50
+ # were added; do not modify it
39
51
  def lookup(key)
40
- @buckets[key] || EMPTY
52
+ bucket = @buckets[key]
53
+ case bucket
54
+ when nil then EMPTY
55
+ when Set then bucket
56
+ else [bucket]
57
+ end
41
58
  end
42
59
 
43
60
  def clear
@@ -49,15 +66,27 @@ module KBS
49
66
  @keys.size
50
67
  end
51
68
 
52
- # The index key for a fact: its values for `fields`.
69
+ # The index key for a fact: its value for the field, or its values for
70
+ # several fields. A single field is the common case and needs no Array.
53
71
  def self.fact_key(fact, fields)
54
- fields.map { |field| normalize(fact.attributes[field]) }
72
+ attributes = fact.attributes
73
+ return normalize(attributes[fields.first]) if fields.size == 1
74
+
75
+ fields.map { |field| normalize(attributes[field]) }
55
76
  end
56
77
 
57
- # The index key for a token: for each [condition index, field] pair,
58
- # that attribute of the fact the condition matched.
78
+ # The index key for a token, built like #fact_key: for each [condition
79
+ # index, field] pair, that attribute of the fact the condition matched.
59
80
  def self.token_key(token, specs)
60
- specs.map { |index, field| normalize(token.fact_at(index)&.attributes&.[](field)) }
81
+ return token_value(token, *specs.first) if specs.size == 1
82
+
83
+ specs.map { |index, field| token_value(token, index, field) }
84
+ end
85
+
86
+ # The normalized attribute `field` of the fact the condition at
87
+ # `index` matched; nil when that condition matched no fact.
88
+ def self.token_value(token, index, field)
89
+ normalize(token.fact_at(index)&.attributes&.[](field))
61
90
  end
62
91
 
63
92
  # Join tests compare with ==, and a Hash key with eql?. They differ
@@ -6,22 +6,47 @@ module KBS
6
6
  module PatternMatching
7
7
  # Whether the fact's type and attributes fit `pattern`. A Proc is
8
8
  # called with the attribute's value, a ?variable fits anything, and
9
- # any other value has to be equal.
9
+ # any other value has to be equal. Walks the pattern with each_pair,
10
+ # since Hash#all? builds a [key, value] Array for every entry.
10
11
  def matches?(pattern)
11
12
  type = pattern[:type]
12
13
  return false if type && type != @type
13
14
 
14
- pattern.all? { |key, expected| key == :type || PatternMatching.value_matches?(@attributes[key], expected) }
15
+ attributes = @attributes
16
+ pattern.each_pair do |key, expected|
17
+ next if key == :type
18
+ return false unless PatternMatching.value_matches?(attributes[key], expected)
19
+ end
20
+ true
15
21
  end
16
22
 
17
23
  def self.value_matches?(actual, expected)
18
24
  if expected.is_a?(Proc)
19
25
  actual && expected.call(actual)
20
- elsif expected.is_a?(Symbol) && expected.end_with?('?')
26
+ elsif variable?(expected)
21
27
  true
22
28
  else
23
29
  actual == expected
24
30
  end
25
31
  end
32
+
33
+ # A ?variable, which fits any value.
34
+ def self.variable?(expected)
35
+ expected.is_a?(Symbol) && expected.end_with?('?')
36
+ end
37
+
38
+ # The [attribute, expected value] pairs of `pattern` that can fail: all
39
+ # but the type and the ?variables. Frozen.
40
+ def self.tests_for(pattern)
41
+ pattern.reject { |key, expected| key == :type || variable?(expected) }.to_a.freeze
42
+ end
43
+
44
+ # Whether `attributes` pass every test from #tests_for.
45
+ def self.passes?(tests, attributes)
46
+ tests.each do |key, expected|
47
+ return false unless value_matches?(attributes[key], expected)
48
+ end
49
+ true
50
+ end
26
51
  end
27
52
  end
@@ -14,7 +14,7 @@ module KBS
14
14
  # @param order [Integer] the rule's position among the engine's rules
15
15
  def initialize(rule, agenda = nil, order: 0)
16
16
  @rule = rule
17
- @tokens = Set.new
17
+ @tokens = Set.new.compare_by_identity
18
18
  @agenda = agenda
19
19
  @order = order
20
20
  @activations = {}.compare_by_identity
@@ -111,7 +111,7 @@ module KBS
111
111
 
112
112
  def link(token, fact)
113
113
  (@facts_matching[token] ||= Set.new) << fact
114
- (@tokens_matched_by[fact] ||= Set.new) << token
114
+ (@tokens_matched_by[fact] ||= Set.new.compare_by_identity) << token
115
115
  end
116
116
 
117
117
  def unlink_token(fact, token)
data/lib/kbs/token.rb CHANGED
@@ -20,26 +20,42 @@ module KBS
20
20
 
21
21
  # @return [Set<KBS::Token>] the tokens that extend this one, so that
22
22
  # removing this token can remove them without a search. Frozen and
23
- # empty until the first #add_child.
23
+ # empty while there are none. Use #add_child and #remove_child to
24
+ # change them.
24
25
  def children
25
- @children || EMPTY_CHILDREN
26
+ case @children
27
+ when nil then EMPTY_CHILDREN
28
+ when Set then @children
29
+ else Set[@children].freeze
30
+ end
26
31
  end
27
32
 
33
+ # Most tokens have one child or none, so @children holds a lone child
34
+ # itself and becomes a Set only for the second.
28
35
  def add_child(token)
29
- (@children ||= Set.new) << token
36
+ case @children
37
+ when nil then @children = token
38
+ when Set then @children << token
39
+ else @children = Set.new.compare_by_identity << @children << token unless @children.equal?(token)
40
+ end
30
41
  end
31
42
 
32
43
  def remove_child(token)
33
- @children&.delete(token)
44
+ case @children
45
+ when Set then @children.delete(token)
46
+ when token then @children = nil
47
+ end
34
48
  end
35
49
 
36
50
  def clear_children
37
51
  @children = nil
38
52
  end
39
53
 
40
- # The matched facts, one per positive condition.
54
+ # The matched facts, one per positive condition. Frozen: the slots
55
+ # themselves when every condition matched a fact, so that firing a
56
+ # rule allocates nothing for them.
41
57
  def facts
42
- @slots.compact
58
+ @slots.include?(nil) ? @slots.compact.freeze : @slots
43
59
  end
44
60
 
45
61
  # One entry per condition matched so far: the matched fact, or nil
@@ -81,7 +97,7 @@ module KBS
81
97
  def build_slots
82
98
  return (@fact ? [@fact] : []).freeze unless @parent
83
99
 
84
- (@parent.slots + [@fact]).freeze
100
+ [*@parent.slots, @fact].freeze
85
101
  end
86
102
  end
87
103
  end
data/lib/kbs/version.rb CHANGED
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KBS
4
- VERSION = "0.3.0"
4
+ VERSION = "0.4.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kbs
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.3.0
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dewayne VanHoozer