A small service builds a short preview of a document selection and caches the result by request parameters. After a recent PR, the preview started behaving unstably: requests with the same meaning may fail to reuse the cache, and an already returned result sometimes changes after external modifications to the input data.
build method accepts keyword arguments:
account_id — an integer;filters — a hash with simple values and arrays of strings;context — a hash with call metadata.filters are passed in a different order.filters and context must not change an already returned result;cache_key, filter_names, filters, and meta.ruby repro.rb
require_relative "query_preview"
service = QueryPreview.new
filters_a = { tags: ["red", "blue"], status: "open" }
context_a = { request_id: "r-1" }
first = service.build(account_id: 7, filters: filters_a, context: context_a)
filters_b = { status: "open", tags: ["red", "blue"] }
second = service.build(account_id: 7, filters: filters_b, context: { request_id: "r-2" })
context_a[:request_id] = "changed-outside"
filters_a[:tags] << "green"
puts first[:cache_key] == second[:cache_key]
puts first[:meta][:context][:request_id]
puts first[:filters][:tags].join(",")
filters should use the same cache key regardless of the order of keys in the input hash.first must not change after mutating context_a and filters_a.3.3.0rubyQueryPreview#build(account_id:, filters:, context:) -> Hashfilters consist of strings, numbers, symbols, and arrays of stringsUse line comments to explain the problem, its impact, the fix and how to test it.