path
stringlengths
26
218
content
stringlengths
0
231k
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasScores.scala
package com.twitter.follow_recommendations.common.models trait HasScores { def scores: Option[Scores] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasSimilarToContext.scala
package com.twitter.follow_recommendations.common.models trait HasSimilarToContext { // user ids that are used to generate similar to recommendations def similarToUserIds: Seq[Long] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasTopicId.scala
package com.twitter.follow_recommendations.common.models trait HasTopicId { def topicId: Long }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasUserCandidateSourceDetails.scala
package com.twitter.follow_recommendations.common.models import com.twitter.hermit.ml.models.Feature import com.twitter.hermit.model.Algorithm import com.twitter.hermit.model.Algorithm.Algorithm import com.twitter.product_mixer.core.model.common.identifier.CandidateSourceIdentifier /** * Used to keep track of a candidate's source not so much as a feature but for filtering candidate * from specific sources (eg. GizmoduckPredicate) */ trait HasUserCandidateSourceDetails { candidateUser: CandidateUser => def userCandidateSourceDetails: Option[UserCandidateSourceDetails] def getAlgorithm: Algorithm = { val algorithm = for { details <- userCandidateSourceDetails identifier <- details.primaryCandidateSource algorithm <- Algorithm.withNameOpt(identifier.name) } yield algorithm algorithm.getOrElse(throw new Exception("Algorithm missing on candidate user!")) } def getAllAlgorithms: Seq[Algorithm] = { getCandidateSources.keys .flatMap(identifier => Algorithm.withNameOpt(identifier.name)).toSeq } def getAddressBookMetadata: Option[AddressBookMetadata] = { userCandidateSourceDetails.flatMap(_.addressBookMetadata) } def getCandidateSources: Map[CandidateSourceIdentifier, Option[Double]] = { userCandidateSourceDetails.map(_.candidateSourceScores).getOrElse(Map.empty) } def getCandidateRanks: Map[CandidateSourceIdentifier, Int] = { userCandidateSourceDetails.map(_.candidateSourceRanks).getOrElse(Map.empty) } def getCandidateFeatures: Map[CandidateSourceIdentifier, Seq[Feature]] = { userCandidateSourceDetails.map(_.candidateSourceFeatures).getOrElse(Map.empty) } def getPrimaryCandidateSource: Option[CandidateSourceIdentifier] = { userCandidateSourceDetails.flatMap(_.primaryCandidateSource) } def withCandidateSource(source: CandidateSourceIdentifier): CandidateUser = { withCandidateSourceAndScore(source, candidateUser.score) } def withCandidateSourceAndScore( source: CandidateSourceIdentifier, score: Option[Double] ): CandidateUser = { withCandidateSourceScoreAndFeatures(source, score, Nil) } def withCandidateSourceAndFeatures( source: CandidateSourceIdentifier, features: Seq[Feature] ): CandidateUser = { withCandidateSourceScoreAndFeatures(source, candidateUser.score, features) } def withCandidateSourceScoreAndFeatures( source: CandidateSourceIdentifier, score: Option[Double], features: Seq[Feature] ): CandidateUser = { val candidateSourceDetails = candidateUser.userCandidateSourceDetails .map { details => details.copy( primaryCandidateSource = Some(source), candidateSourceScores = details.candidateSourceScores + (source -> score), candidateSourceFeatures = details.candidateSourceFeatures + (source -> features) ) }.getOrElse( UserCandidateSourceDetails( Some(source), Map(source -> score), Map.empty, None, Map(source -> features))) candidateUser.copy( userCandidateSourceDetails = Some(candidateSourceDetails) ) } def addCandidateSourceScoresMap( scoreMap: Map[CandidateSourceIdentifier, Option[Double]] ): CandidateUser = { val candidateSourceDetails = candidateUser.userCandidateSourceDetails .map { details => details.copy(candidateSourceScores = details.candidateSourceScores ++ scoreMap) }.getOrElse(UserCandidateSourceDetails(scoreMap.keys.headOption, scoreMap, Map.empty, None)) candidateUser.copy( userCandidateSourceDetails = Some(candidateSourceDetails) ) } def addCandidateSourceRanksMap( rankMap: Map[CandidateSourceIdentifier, Int] ): CandidateUser = { val candidateSourceDetails = candidateUser.userCandidateSourceDetails .map { details => details.copy(candidateSourceRanks = details.candidateSourceRanks ++ rankMap) }.getOrElse(UserCandidateSourceDetails(rankMap.keys.headOption, Map.empty, rankMap, None)) candidateUser.copy( userCandidateSourceDetails = Some(candidateSourceDetails) ) } def addInfoPerRankingStage( rankingStage: String, scores: Option[Scores], rank: Int ): CandidateUser = { val scoresOpt: Option[Scores] = scores.orElse(candidateUser.scores) val originalInfoPerRankingStage = candidateUser.infoPerRankingStage.getOrElse(Map[String, RankingInfo]()) candidateUser.copy( infoPerRankingStage = Some(originalInfoPerRankingStage + (rankingStage -> RankingInfo(scoresOpt, Some(rank)))) ) } def addAddressBookMetadataIfAvailable( candidateSources: Seq[CandidateSourceIdentifier] ): CandidateUser = { val addressBookMetadata = AddressBookMetadata( inForwardPhoneBook = candidateSources.contains(AddressBookMetadata.ForwardPhoneBookCandidateSource), inReversePhoneBook = candidateSources.contains(AddressBookMetadata.ReversePhoneBookCandidateSource), inForwardEmailBook = candidateSources.contains(AddressBookMetadata.ForwardEmailBookCandidateSource), inReverseEmailBook = candidateSources.contains(AddressBookMetadata.ReverseEmailBookCandidateSource) ) val newCandidateSourceDetails = candidateUser.userCandidateSourceDetails .map { details => details.copy(addressBookMetadata = Some(addressBookMetadata)) }.getOrElse( UserCandidateSourceDetails( None, Map.empty, Map.empty, Some(addressBookMetadata), Map.empty)) candidateUser.copy( userCandidateSourceDetails = Some(newCandidateSourceDetails) ) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasUserState.scala
package com.twitter.follow_recommendations.common.models import com.twitter.core_workflows.user_model.thriftscala.UserState trait HasUserState { def userState: Option[UserState] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasWtfImpressions.scala
package com.twitter.follow_recommendations.common.models import com.twitter.util.Time trait HasWtfImpressions { def wtfImpressions: Option[Seq[WtfImpression]] lazy val numWtfImpressions: Int = wtfImpressions.map(_.size).getOrElse(0) lazy val candidateImpressions: Map[Long, WtfImpression] = wtfImpressions .map { imprMap => imprMap.map { i => i.candidateId -> i }.toMap }.getOrElse(Map.empty) lazy val latestImpressionTime: Time = { if (wtfImpressions.exists(_.nonEmpty)) { wtfImpressions.get.map(_.latestTime).max } else Time.Top } def getCandidateImpressionCounts(id: Long): Option[Int] = candidateImpressions.get(id).map(_.counts) def getCandidateLatestTime(id: Long): Option[Time] = { candidateImpressions.get(id).map(_.latestTime) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/OptimusRequest.scala
package com.twitter.follow_recommendations.common.models import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.timelines.configapi.HasParams /** Convenience trait to group together all traits needed for optimus ranking */ trait OptimusRequest extends HasParams with HasClientContext with HasDisplayLocation with HasInterestIds with HasDebugOptions with HasPreviousRecommendationsContext {}
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/Product.scala
package com.twitter.follow_recommendations.common.models import com.twitter.product_mixer.core.model.common.identifier.ProductIdentifier import com.twitter.product_mixer.core.model.marshalling.request.{Product => ProductMixerProduct} object Product { case object MagicRecs extends ProductMixerProduct { override val identifier: ProductIdentifier = ProductIdentifier("MagicRecs") override val stringCenterProject: Option[String] = Some("people-discovery") } case object PlaceholderProductMixerProduct extends ProductMixerProduct { override val identifier: ProductIdentifier = ProductIdentifier("PlaceholderProductMixerProduct") } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/RankingInfo.scala
package com.twitter.follow_recommendations.common.models import com.twitter.follow_recommendations.{thriftscala => t} import com.twitter.follow_recommendations.logging.{thriftscala => offline} case class RankingInfo( scores: Option[Scores], rank: Option[Int]) { def toThrift: t.RankingInfo = { t.RankingInfo(scores.map(_.toThrift), rank) } def toOfflineThrift: offline.RankingInfo = { offline.RankingInfo(scores.map(_.toOfflineThrift), rank) } } object RankingInfo { def fromThrift(rankingInfo: t.RankingInfo): RankingInfo = { RankingInfo( scores = rankingInfo.scores.map(Scores.fromThrift), rank = rankingInfo.rank ) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/Reason.scala
package com.twitter.follow_recommendations.common.models import com.twitter.follow_recommendations.{thriftscala => t} import com.twitter.follow_recommendations.logging.{thriftscala => offline} case class FollowProof(followedBy: Seq[Long], numIds: Int) { def toThrift: t.FollowProof = { t.FollowProof(followedBy, numIds) } def toOfflineThrift: offline.FollowProof = offline.FollowProof(followedBy, numIds) } object FollowProof { def fromThrift(proof: t.FollowProof): FollowProof = { FollowProof(proof.userIds, proof.numIds) } } case class SimilarToProof(similarTo: Seq[Long]) { def toThrift: t.SimilarToProof = { t.SimilarToProof(similarTo) } def toOfflineThrift: offline.SimilarToProof = offline.SimilarToProof(similarTo) } object SimilarToProof { def fromThrift(proof: t.SimilarToProof): SimilarToProof = { SimilarToProof(proof.userIds) } } case class PopularInGeoProof(location: String) { def toThrift: t.PopularInGeoProof = { t.PopularInGeoProof(location) } def toOfflineThrift: offline.PopularInGeoProof = offline.PopularInGeoProof(location) } object PopularInGeoProof { def fromThrift(proof: t.PopularInGeoProof): PopularInGeoProof = { PopularInGeoProof(proof.location) } } case class TttInterestProof(interestId: Long, interestDisplayName: String) { def toThrift: t.TttInterestProof = { t.TttInterestProof(interestId, interestDisplayName) } def toOfflineThrift: offline.TttInterestProof = offline.TttInterestProof(interestId, interestDisplayName) } object TttInterestProof { def fromThrift(proof: t.TttInterestProof): TttInterestProof = { TttInterestProof(proof.interestId, proof.interestDisplayName) } } case class TopicProof(topicId: Long) { def toThrift: t.TopicProof = { t.TopicProof(topicId) } def toOfflineThrift: offline.TopicProof = offline.TopicProof(topicId) } object TopicProof { def fromThrift(proof: t.TopicProof): TopicProof = { TopicProof(proof.topicId) } } case class CustomInterest(query: String) { def toThrift: t.CustomInterestProof = { t.CustomInterestProof(query) } def toOfflineThrift: offline.CustomInterestProof = offline.CustomInterestProof(query) } object CustomInterest { def fromThrift(proof: t.CustomInterestProof): CustomInterest = { CustomInterest(proof.query) } } case class TweetsAuthorProof(tweetIds: Seq[Long]) { def toThrift: t.TweetsAuthorProof = { t.TweetsAuthorProof(tweetIds) } def toOfflineThrift: offline.TweetsAuthorProof = offline.TweetsAuthorProof(tweetIds) } object TweetsAuthorProof { def fromThrift(proof: t.TweetsAuthorProof): TweetsAuthorProof = { TweetsAuthorProof(proof.tweetIds) } } case class DeviceFollowProof(isDeviceFollow: Boolean) { def toThrift: t.DeviceFollowProof = { t.DeviceFollowProof(isDeviceFollow) } def toOfflineThrift: offline.DeviceFollowProof = offline.DeviceFollowProof(isDeviceFollow) } object DeviceFollowProof { def fromThrift(proof: t.DeviceFollowProof): DeviceFollowProof = { DeviceFollowProof(proof.isDeviceFollow) } } case class AccountProof( followProof: Option[FollowProof] = None, similarToProof: Option[SimilarToProof] = None, popularInGeoProof: Option[PopularInGeoProof] = None, tttInterestProof: Option[TttInterestProof] = None, topicProof: Option[TopicProof] = None, customInterestProof: Option[CustomInterest] = None, tweetsAuthorProof: Option[TweetsAuthorProof] = None, deviceFollowProof: Option[DeviceFollowProof] = None) { def toThrift: t.AccountProof = { t.AccountProof( followProof.map(_.toThrift), similarToProof.map(_.toThrift), popularInGeoProof.map(_.toThrift), tttInterestProof.map(_.toThrift), topicProof.map(_.toThrift), customInterestProof.map(_.toThrift), tweetsAuthorProof.map(_.toThrift), deviceFollowProof.map(_.toThrift) ) } def toOfflineThrift: offline.AccountProof = { offline.AccountProof( followProof.map(_.toOfflineThrift), similarToProof.map(_.toOfflineThrift), popularInGeoProof.map(_.toOfflineThrift), tttInterestProof.map(_.toOfflineThrift), topicProof.map(_.toOfflineThrift), customInterestProof.map(_.toOfflineThrift), tweetsAuthorProof.map(_.toOfflineThrift), deviceFollowProof.map(_.toOfflineThrift) ) } } object AccountProof { def fromThrift(proof: t.AccountProof): AccountProof = { AccountProof( proof.followProof.map(FollowProof.fromThrift), proof.similarToProof.map(SimilarToProof.fromThrift), proof.popularInGeoProof.map(PopularInGeoProof.fromThrift), proof.tttInterestProof.map(TttInterestProof.fromThrift), proof.topicProof.map(TopicProof.fromThrift), proof.customInterestProof.map(CustomInterest.fromThrift), proof.tweetsAuthorProof.map(TweetsAuthorProof.fromThrift), proof.deviceFollowProof.map(DeviceFollowProof.fromThrift) ) } } case class Reason(accountProof: Option[AccountProof]) { def toThrift: t.Reason = { t.Reason(accountProof.map(_.toThrift)) } def toOfflineThrift: offline.Reason = { offline.Reason(accountProof.map(_.toOfflineThrift)) } } object Reason { def fromThrift(reason: t.Reason): Reason = { Reason(reason.accountProof.map(AccountProof.fromThrift)) } } trait HasReason { def reason: Option[Reason] // helper methods below def followedBy: Option[Seq[Long]] = { for { reason <- reason accountProof <- reason.accountProof followProof <- accountProof.followProof } yield { followProof.followedBy } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/RecentlyEngagedUserId.scala
package com.twitter.follow_recommendations.common.models import com.twitter.follow_recommendations.logging.{thriftscala => offline} import com.twitter.follow_recommendations.{thriftscala => t} case class RecentlyEngagedUserId(id: Long, engagementType: EngagementType) { def toThrift: t.RecentlyEngagedUserId = t.RecentlyEngagedUserId(id = id, engagementType = engagementType.toThrift) def toOfflineThrift: offline.RecentlyEngagedUserId = offline.RecentlyEngagedUserId(id = id, engagementType = engagementType.toOfflineThrift) } object RecentlyEngagedUserId { def fromThrift(recentlyEngagedUserId: t.RecentlyEngagedUserId): RecentlyEngagedUserId = { RecentlyEngagedUserId( id = recentlyEngagedUserId.id, engagementType = EngagementType.fromThrift(recentlyEngagedUserId.engagementType) ) } def fromOfflineThrift( recentlyEngagedUserId: offline.RecentlyEngagedUserId ): RecentlyEngagedUserId = { RecentlyEngagedUserId( id = recentlyEngagedUserId.id, engagementType = EngagementType.fromOfflineThrift(recentlyEngagedUserId.engagementType) ) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/RecommendationStep.scala
package com.twitter.follow_recommendations.common.models import com.twitter.follow_recommendations.{thriftscala => t} import com.twitter.follow_recommendations.logging.{thriftscala => offline} case class RecommendationStep( recommendations: Seq[FlowRecommendation], followedUserIds: Set[Long]) { def toThrift: t.RecommendationStep = t.RecommendationStep( recommendations = recommendations.map(_.toThrift), followedUserIds = followedUserIds ) def toOfflineThrift: offline.OfflineRecommendationStep = offline.OfflineRecommendationStep( recommendations = recommendations.map(_.toOfflineThrift), followedUserIds = followedUserIds) } object RecommendationStep { def fromThrift(recommendationStep: t.RecommendationStep): RecommendationStep = { RecommendationStep( recommendations = recommendationStep.recommendations.map(FlowRecommendation.fromThrift), followedUserIds = recommendationStep.followedUserIds.toSet) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/STPGraph.scala
package com.twitter.follow_recommendations.common.models import com.twitter.hermit.model.Algorithm.Algorithm import com.twitter.wtf.scalding.jobs.strong_tie_prediction.FirstDegreeEdge import com.twitter.wtf.scalding.jobs.strong_tie_prediction.FirstDegreeEdgeInfo import com.twitter.wtf.scalding.jobs.strong_tie_prediction.SecondDegreeEdge case class PotentialFirstDegreeEdge( userId: Long, connectingId: Long, algorithm: Algorithm, score: Double, edgeInfo: FirstDegreeEdgeInfo) case class IntermediateSecondDegreeEdge( connectingId: Long, candidateId: Long, edgeInfo: FirstDegreeEdgeInfo) case class STPGraph( firstDegreeEdgeInfoList: List[FirstDegreeEdge], secondDegreeEdgeInfoList: List[SecondDegreeEdge])
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/SafetyLevel.scala
package com.twitter.follow_recommendations.common.models import com.twitter.spam.rtf.thriftscala.{SafetyLevel => ThriftSafetyLevel} sealed trait SafetyLevel { def toThrift: ThriftSafetyLevel } object SafetyLevel { case object Recommendations extends SafetyLevel { override val toThrift = ThriftSafetyLevel.Recommendations } case object TopicsLandingPageTopicRecommendations extends SafetyLevel { override val toThrift = ThriftSafetyLevel.TopicsLandingPageTopicRecommendations } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/Score.scala
package com.twitter.follow_recommendations.common.models import com.twitter.follow_recommendations.common.rankers.common.RankerId import com.twitter.follow_recommendations.common.rankers.common.RankerId.RankerId import com.twitter.follow_recommendations.logging.{thriftscala => offline} import com.twitter.follow_recommendations.{thriftscala => t} /** * Type of Score. This is used to differentiate scores. * * Define it as a trait so it is possible to add more information for different score types. */ sealed trait ScoreType { def getName: String } /** * Existing Score Types */ object ScoreType { /** * the score is calculated based on heuristics and most likely not normalized */ case object HeuristicBasedScore extends ScoreType { override def getName: String = "HeuristicBasedScore" } /** * probability of follow after the candidate is recommended to the user */ case object PFollowGivenReco extends ScoreType { override def getName: String = "PFollowGivenReco" } /** * probability of engage after the user follows the candidate */ case object PEngagementGivenFollow extends ScoreType { override def getName: String = "PEngagementGivenFollow" } /** * probability of engage per tweet impression */ case object PEngagementPerImpression extends ScoreType { override def getName: String = "PEngagementPerImpression" } /** * probability of engage per tweet impression */ case object PEngagementGivenReco extends ScoreType { override def getName: String = "PEngagementGivenReco" } def fromScoreTypeString(scoreTypeName: String): ScoreType = scoreTypeName match { case "HeuristicBasedScore" => HeuristicBasedScore case "PFollowGivenReco" => PFollowGivenReco case "PEngagementGivenFollow" => PEngagementGivenFollow case "PEngagementPerImpression" => PEngagementPerImpression case "PEngagementGivenReco" => PEngagementGivenReco } } /** * Represent the output from a certain ranker or scorer. All the fields are optional * * @param value value of the score * @param rankerId ranker id * @param scoreType score type */ final case class Score( value: Double, rankerId: Option[RankerId] = None, scoreType: Option[ScoreType] = None) { def toThrift: t.Score = t.Score( value = value, rankerId = rankerId.map(_.toString), scoreType = scoreType.map(_.getName) ) def toOfflineThrift: offline.Score = offline.Score( value = value, rankerId = rankerId.map(_.toString), scoreType = scoreType.map(_.getName) ) } object Score { val RandomScore = Score(0.0d, Some(RankerId.RandomRanker)) def optimusScore(score: Double, scoreType: ScoreType): Score = { Score(value = score, scoreType = Some(scoreType)) } def predictionScore(score: Double, rankerId: RankerId): Score = { Score(value = score, rankerId = Some(rankerId)) } def fromThrift(thriftScore: t.Score): Score = Score( value = thriftScore.value, rankerId = thriftScore.rankerId.flatMap(RankerId.getRankerByName), scoreType = thriftScore.scoreType.map(ScoreType.fromScoreTypeString) ) } /** * a list of scores */ final case class Scores( scores: Seq[Score], selectedRankerId: Option[RankerId] = None, isInProducerScoringExperiment: Boolean = false) { def toThrift: t.Scores = t.Scores( scores = scores.map(_.toThrift), selectedRankerId = selectedRankerId.map(_.toString), isInProducerScoringExperiment = isInProducerScoringExperiment ) def toOfflineThrift: offline.Scores = offline.Scores( scores = scores.map(_.toOfflineThrift), selectedRankerId = selectedRankerId.map(_.toString), isInProducerScoringExperiment = isInProducerScoringExperiment ) } object Scores { val Empty: Scores = Scores(Nil) def fromThrift(thriftScores: t.Scores): Scores = Scores( scores = thriftScores.scores.map(Score.fromThrift), selectedRankerId = thriftScores.selectedRankerId.flatMap(RankerId.getRankerByName), isInProducerScoringExperiment = thriftScores.isInProducerScoringExperiment ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/Session.scala
package com.twitter.follow_recommendations.common.models import com.twitter.finagle.tracing.Trace object Session { /** * The sessionId in FRS is the finagle trace id which is static within the lifetime of a single * request. * * It is used when generating per-candidate tokens (in TrackingTokenTransform) and is also passed * in to downstream Optimus ranker requests. * */ def getSessionId: Long = Trace.id.traceId.toLong }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/SignalData.scala
package com.twitter.follow_recommendations.common.models import com.twitter.simclusters_v2.thriftscala.InternalId import com.twitter.usersignalservice.thriftscala.SignalType import com.twitter.usersignalservice.thriftscala.Signal trait SignalData { val userId: Long val signalType: SignalType } case class RecentFollowsSignal( override val userId: Long, override val signalType: SignalType, followedUserId: Long, timestamp: Long) extends SignalData object RecentFollowsSignal { def fromUssSignal(targetUserId: Long, signal: Signal): RecentFollowsSignal = { val InternalId.UserId(followedUserId) = signal.targetInternalId.getOrElse( throw new IllegalArgumentException("RecentFollow Signal does not have internalId")) RecentFollowsSignal( userId = targetUserId, followedUserId = followedUserId, timestamp = signal.timestamp, signalType = signal.signalType ) } def getRecentFollowedUserIds( signalDataMap: Option[Map[SignalType, Seq[SignalData]]] ): Option[Seq[Long]] = { signalDataMap.map(_.getOrElse(SignalType.AccountFollow, default = Seq.empty).flatMap { case RecentFollowsSignal(userId, signalType, followedUserId, timestamp) => Some(followedUserId) case _ => None }) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/TrackingToken.scala
package com.twitter.follow_recommendations.common.models import com.twitter.finagle.tracing.Trace import com.twitter.follow_recommendations.logging.{thriftscala => offline} import com.twitter.follow_recommendations.{thriftscala => t} import com.twitter.scrooge.BinaryThriftStructSerializer import com.twitter.suggests.controller_data.thriftscala.ControllerData import com.twitter.util.Base64StringEncoder /** * used for attribution per target-candidate pair * @param sessionId trace-id of the finagle request * @param controllerData 64-bit encoded binary attributes of our recommendation * @param algorithmId id for identifying a candidate source. maintained for backwards compatibility */ case class TrackingToken( sessionId: Long, displayLocation: Option[DisplayLocation], controllerData: Option[ControllerData], algorithmId: Option[Int]) { def toThrift: t.TrackingToken = { Trace.id.traceId.toLong t.TrackingToken( sessionId = sessionId, displayLocation = displayLocation.map(_.toThrift), controllerData = controllerData, algoId = algorithmId ) } def toOfflineThrift: offline.TrackingToken = { offline.TrackingToken( sessionId = sessionId, displayLocation = displayLocation.map(_.toOfflineThrift), controllerData = controllerData, algoId = algorithmId ) } } object TrackingToken { val binaryThriftSerializer = BinaryThriftStructSerializer[t.TrackingToken](t.TrackingToken) def serialize(trackingToken: TrackingToken): String = { Base64StringEncoder.encode(binaryThriftSerializer.toBytes(trackingToken.toThrift)) } def deserialize(trackingTokenStr: String): TrackingToken = { fromThrift(binaryThriftSerializer.fromBytes(Base64StringEncoder.decode(trackingTokenStr))) } def fromThrift(token: t.TrackingToken): TrackingToken = { TrackingToken( sessionId = token.sessionId, displayLocation = token.displayLocation.map(DisplayLocation.fromThrift), controllerData = token.controllerData, algorithmId = token.algoId ) } } trait HasTrackingToken { def trackingToken: Option[TrackingToken] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/TweetCandidate.scala
package com.twitter.follow_recommendations.common.models case class TweetCandidate( tweetId: Long, authorId: Long, score: Option[Double])
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/UserCandidateSourceDetails.scala
package com.twitter.follow_recommendations.common.models import com.twitter.follow_recommendations.logging.{thriftscala => offline} import com.twitter.follow_recommendations.{thriftscala => t} import com.twitter.hermit.constants.AlgorithmFeedbackTokens._ import com.twitter.hermit.ml.models.Feature import com.twitter.hermit.model.Algorithm import com.twitter.product_mixer.core.model.common.identifier.CandidateSourceIdentifier /** * primaryCandidateSource param is showing the candidate source that responsible for generating this * candidate, as the candidate might have gone through multiple candidate sources to get generated * (for example if it has generated by a composite source). WeightedCandidateSourceRanker uses this * field to do the sampling over candidate sources. All the sources used for generating this * candidate (including the primary source) and their corresponding score exist in the * candidateSourceScores field. */ case class UserCandidateSourceDetails( primaryCandidateSource: Option[CandidateSourceIdentifier], candidateSourceScores: Map[CandidateSourceIdentifier, Option[Double]] = Map.empty, candidateSourceRanks: Map[CandidateSourceIdentifier, Int] = Map.empty, addressBookMetadata: Option[AddressBookMetadata] = None, candidateSourceFeatures: Map[CandidateSourceIdentifier, Seq[Feature]] = Map.empty, ) { def toThrift: t.CandidateSourceDetails = { t.CandidateSourceDetails( candidateSourceScores = Some(candidateSourceScores.map { case (identifier, score) => (identifier.name, score.getOrElse(0.0d)) }), primarySource = for { identifier <- primaryCandidateSource algo <- Algorithm.withNameOpt(identifier.name) feedbackToken <- AlgorithmToFeedbackTokenMap.get(algo) } yield feedbackToken ) } def toOfflineThrift: offline.CandidateSourceDetails = { offline.CandidateSourceDetails( candidateSourceScores = Some(candidateSourceScores.map { case (identifier, score) => (identifier.name, score.getOrElse(0.0d)) }), primarySource = for { identifier <- primaryCandidateSource algo <- Algorithm.withNameOpt(identifier.name) feedbackToken <- AlgorithmToFeedbackTokenMap.get(algo) } yield feedbackToken ) } } object UserCandidateSourceDetails { val algorithmNameMap: Map[String, Algorithm.Value] = Algorithm.values.map { algorithmValue: Algorithm.Value => (algorithmValue.toString, algorithmValue) }.toMap /** * This method is used to parse the candidate source of the candidates, which is only passed from * the scoreUserCandidates endpoint. We create custom candidate source identifiers which * CandidateAlgorithmSource will read from to hydrate the algorithm id feature. * candidateSourceScores will not be populated from the endpoint, but we add the conversion for * completeness. Note that the conversion uses the raw string of the Algorithm rather than the * assigned strings that we give to our own candidate sources in the FRS. */ def fromThrift(details: t.CandidateSourceDetails): UserCandidateSourceDetails = { val primaryCandidateSource: Option[CandidateSourceIdentifier] = for { primarySourceToken <- details.primarySource algo <- TokenToAlgorithmMap.get(primarySourceToken) } yield CandidateSourceIdentifier(algo.toString) val candidateSourceScores = for { scoreMap <- details.candidateSourceScores.toSeq (name, score) <- scoreMap algo <- algorithmNameMap.get(name) } yield { CandidateSourceIdentifier(algo.toString) -> Some(score) } val candidateSourceRanks = for { rankMap <- details.candidateSourceRanks.toSeq (name, rank) <- rankMap algo <- algorithmNameMap.get(name) } yield { CandidateSourceIdentifier(algo.toString) -> rank } UserCandidateSourceDetails( primaryCandidateSource = primaryCandidateSource, candidateSourceScores = candidateSourceScores.toMap, candidateSourceRanks = candidateSourceRanks.toMap, addressBookMetadata = None, candidateSourceFeatures = Map.empty ) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/UserIdAndTimestamp.scala
package com.twitter.follow_recommendations.common.models case class UserIdWithTimestamp(userId: Long, timeInMs: Long)
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/WtfImpression.scala
package com.twitter.follow_recommendations.common.models import com.twitter.util.Time /** * Domain model for representing impressions on wtf recommendations in the past 16 days */ case class WtfImpression( candidateId: Long, displayLocation: DisplayLocation, latestTime: Time, counts: Int)
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "escherbird/src/scala/com/twitter/escherbird/util/stitchcache", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/strato", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/user_state", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/features", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/stores", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/CandidateParamPredicate.scala
package com.twitter.follow_recommendations.common.predicates import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.models.FilterReason import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import com.twitter.timelines.configapi.Param class CandidateParamPredicate[A <: HasParams]( param: Param[Boolean], reason: FilterReason) extends Predicate[A] { override def apply(candidate: A): Stitch[PredicateResult] = { if (candidate.params(param)) { Stitch.value(PredicateResult.Valid) } else { Stitch.value(PredicateResult.Invalid(Set(reason))) } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/CandidateSourceParamPredicate.scala
package com.twitter.follow_recommendations.common.predicates import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.FilterReason import com.twitter.product_mixer.core.model.common.identifier.CandidateSourceIdentifier import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.Param /** * This predicate allows us to filter candidates given its source. * To avoid bucket dilution, we only want to evaluate the param (which would implicitly trigger * bucketing for FSParams) only if the candidate source fn yields true. * The param provided should be true when we want to keep the candidate and false otherwise. */ class CandidateSourceParamPredicate( val param: Param[Boolean], val reason: FilterReason, candidateSources: Set[CandidateSourceIdentifier]) extends Predicate[CandidateUser] { override def apply(candidate: CandidateUser): Stitch[PredicateResult] = { // we want to avoid evaluating the param if the candidate source fn yields false if (candidate.getCandidateSources.keys.exists(candidateSources.contains) && !candidate.params( param)) { Stitch.value(PredicateResult.Invalid(Set(reason))) } else { Stitch.value(PredicateResult.Valid) } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/CuratedCompetitorListPredicate.scala
package com.twitter.follow_recommendations.common.predicates import com.google.inject.name.Named import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.constants.GuiceNamedConstants import com.twitter.follow_recommendations.common.models.FilterReason.CuratedAccountsCompetitorList import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.stitch.Stitch import com.twitter.strato.client.Fetcher import javax.inject.Inject import javax.inject.Singleton import com.twitter.conversions.DurationOps._ import com.twitter.escherbird.util.stitchcache.StitchCache @Singleton case class CuratedCompetitorListPredicate @Inject() ( statsReceiver: StatsReceiver, @Named(GuiceNamedConstants.CURATED_COMPETITOR_ACCOUNTS_FETCHER) competitorAccountFetcher: Fetcher[ String, Unit, Seq[Long] ]) extends Predicate[CandidateUser] { private val stats: StatsReceiver = statsReceiver.scope(this.getClass.getName) private val cacheStats = stats.scope("cache") private val cache = StitchCache[String, Set[Long]]( maxCacheSize = CuratedCompetitorListPredicate.CacheNumberOfEntries, ttl = CuratedCompetitorListPredicate.CacheTTL, statsReceiver = cacheStats, underlyingCall = (competitorListPrefix: String) => query(competitorListPrefix) ) private def query(prefix: String): Stitch[Set[Long]] = competitorAccountFetcher.fetch(prefix).map(_.v.getOrElse(Nil).toSet) /** * Caveat here is that though the similarToUserIds allows for a Seq[Long], in practice we would * only return 1 userId. Multiple userId's would result in filtering candidates associated with * a different similarToUserId. For example: * - similarToUser1 -> candidate1, candidate2 * - similarToUser2 -> candidate3 * and in the competitorList store we have: * - similarToUser1 -> candidate3 * we'll be filtering candidate3 on account of similarToUser1, even though it was generated * with similarToUser2. This might still be desirable at a product level (since we don't want * to show these accounts anyway), but might not achieve what you intend to code-wise. */ override def apply(candidate: CandidateUser): Stitch[PredicateResult] = { cache.readThrough(CuratedCompetitorListPredicate.DefaultKey).map { competitorListAccounts => if (competitorListAccounts.contains(candidate.id)) { PredicateResult.Invalid(Set(CuratedAccountsCompetitorList)) } else { PredicateResult.Valid } } } } object CuratedCompetitorListPredicate { val DefaultKey: String = "default_list" val CacheTTL = 5.minutes val CacheNumberOfEntries = 5 }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/ExcludedUserIdPredicate.scala
package com.twitter.follow_recommendations.common.predicates import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.models.FilterReason.ExcludedId import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasExcludedUserIds import com.twitter.stitch.Stitch object ExcludedUserIdPredicate extends Predicate[(HasExcludedUserIds, CandidateUser)] { val ValidStitch: Stitch[PredicateResult.Valid.type] = Stitch.value(PredicateResult.Valid) val ExcludedStitch: Stitch[PredicateResult.Invalid] = Stitch.value(PredicateResult.Invalid(Set(ExcludedId))) override def apply(pair: (HasExcludedUserIds, CandidateUser)): Stitch[PredicateResult] = { val (excludedUserIds, candidate) = pair if (excludedUserIds.excludedUserIds.contains(candidate.id)) { ExcludedStitch } else { ValidStitch } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/InactivePredicate.scala
package com.twitter.follow_recommendations.common.predicates import com.google.inject.name.Named import com.twitter.core_workflows.user_model.thriftscala.UserState import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.constants.GuiceNamedConstants import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.FilterReason import com.twitter.follow_recommendations.common.predicates.InactivePredicateParams._ import com.twitter.service.metastore.gen.thriftscala.UserRecommendabilityFeatures import com.twitter.stitch.Stitch import com.twitter.strato.client.Fetcher import com.twitter.timelines.configapi.HasParams import com.twitter.util.Duration import com.twitter.util.Time import javax.inject.Inject import javax.inject.Singleton import com.twitter.conversions.DurationOps._ import com.twitter.escherbird.util.stitchcache.StitchCache import com.twitter.follow_recommendations.common.models.HasUserState import com.twitter.follow_recommendations.common.predicates.InactivePredicateParams.DefaultInactivityThreshold import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import java.lang.{Long => JLong} @Singleton case class InactivePredicate @Inject() ( statsReceiver: StatsReceiver, @Named(GuiceNamedConstants.USER_RECOMMENDABILITY_FETCHER) userRecommendabilityFetcher: Fetcher[ Long, Unit, UserRecommendabilityFeatures ]) extends Predicate[(HasParams with HasClientContext with HasUserState, CandidateUser)] { private val stats: StatsReceiver = statsReceiver.scope("InactivePredicate") private val cacheStats = stats.scope("cache") private def queryUserRecommendable(userId: Long): Stitch[Option[UserRecommendabilityFeatures]] = userRecommendabilityFetcher.fetch(userId).map(_.v) private val userRecommendableCache = StitchCache[JLong, Option[UserRecommendabilityFeatures]]( maxCacheSize = 100000, ttl = 12.hours, statsReceiver = cacheStats.scope("UserRecommendable"), underlyingCall = (userId: JLong) => queryUserRecommendable(userId) ) override def apply( targetAndCandidate: (HasParams with HasClientContext with HasUserState, CandidateUser) ): Stitch[PredicateResult] = { val (target, candidate) = targetAndCandidate userRecommendableCache .readThrough(candidate.id).map { case recFeaturesFetchResult => recFeaturesFetchResult match { case None => PredicateResult.Invalid(Set(FilterReason.MissingRecommendabilityData)) case Some(recFeatures) => if (disableInactivityPredicate(target, target.userState, recFeatures.userState)) { PredicateResult.Valid } else { val defaultInactivityThreshold = target.params(DefaultInactivityThreshold).days val hasBeenActiveRecently = recFeatures.lastStatusUpdateMs .map(Time.now - Time.fromMilliseconds(_)).getOrElse( Duration.Top) < defaultInactivityThreshold stats .scope(defaultInactivityThreshold.toString).counter( if (hasBeenActiveRecently) "active" else "inactive" ).incr() if (hasBeenActiveRecently && (!target .params(UseEggFilter) || recFeatures.isNotEgg.contains(1))) { PredicateResult.Valid } else { PredicateResult.Invalid(Set(FilterReason.Inactive)) } } } }.rescue { case e: Exception => stats.counter(e.getClass.getSimpleName).incr() Stitch(PredicateResult.Invalid(Set(FilterReason.FailOpen))) } } private[this] def disableInactivityPredicate( target: HasParams, consumerState: Option[UserState], candidateState: Option[UserState] ): Boolean = { target.params(MightBeDisabled) && consumerState.exists(InactivePredicate.ValidConsumerStates.contains) && ( ( candidateState.exists(InactivePredicate.ValidCandidateStates.contains) && !target.params(OnlyDisableForNewUserStateCandidates) ) || ( candidateState.contains(UserState.New) && target.params(OnlyDisableForNewUserStateCandidates) ) ) } } object InactivePredicate { val ValidConsumerStates: Set[UserState] = Set( UserState.HeavyNonTweeter, UserState.MediumNonTweeter, UserState.HeavyTweeter, UserState.MediumTweeter ) val ValidCandidateStates: Set[UserState] = Set(UserState.New, UserState.VeryLight, UserState.Light, UserState.NearZero) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/InactivePredicateParams.scala
package com.twitter.follow_recommendations.common.predicates import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.FSParam import com.twitter.timelines.configapi.Param object InactivePredicateParams { case object DefaultInactivityThreshold extends FSBoundedParam[Int]( name = "inactive_predicate_default_inactivity_threshold", default = 60, min = 1, max = 500 ) case object UseEggFilter extends Param[Boolean](true) case object MightBeDisabled extends FSParam[Boolean]("inactive_predicate_might_be_disabled", true) case object OnlyDisableForNewUserStateCandidates extends FSParam[Boolean]( "inactive_predicate_only_disable_for_new_user_state_candidates", false) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/PreviouslyRecommendedUserIdsPredicate.scala
package com.twitter.follow_recommendations.common.predicates import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.FilterReason import com.twitter.follow_recommendations.common.models.HasPreviousRecommendationsContext import com.twitter.stitch.Stitch import javax.inject.Singleton @Singleton class PreviouslyRecommendedUserIdsPredicate extends Predicate[(HasPreviousRecommendationsContext, CandidateUser)] { override def apply( pair: (HasPreviousRecommendationsContext, CandidateUser) ): Stitch[PredicateResult] = { val (targetUser, candidate) = pair val previouslyRecommendedUserIDs = targetUser.previouslyRecommendedUserIDs if (!previouslyRecommendedUserIDs.contains(candidate.id)) { PreviouslyRecommendedUserIdsPredicate.ValidStitch } else { PreviouslyRecommendedUserIdsPredicate.AlreadyRecommendedStitch } } } object PreviouslyRecommendedUserIdsPredicate { val ValidStitch: Stitch[PredicateResult.Valid.type] = Stitch.value(PredicateResult.Valid) val AlreadyRecommendedStitch: Stitch[PredicateResult.Invalid] = Stitch.value(PredicateResult.Invalid(Set(FilterReason.AlreadyRecommended))) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/dismiss/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/dismiss_store", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/dismiss/DismissedCandidatePredicate.scala
package com.twitter.follow_recommendations.common.predicates.dismiss import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.models.FilterReason.DismissedId import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDismissedUserIds import com.twitter.stitch.Stitch import javax.inject.Singleton @Singleton class DismissedCandidatePredicate extends Predicate[(HasDismissedUserIds, CandidateUser)] { override def apply(pair: (HasDismissedUserIds, CandidateUser)): Stitch[PredicateResult] = { val (targetUser, candidate) = pair targetUser.dismissedUserIds .map { dismissedUserIds => if (!dismissedUserIds.contains(candidate.id)) { DismissedCandidatePredicate.ValidStitch } else { DismissedCandidatePredicate.DismissedStitch } }.getOrElse(DismissedCandidatePredicate.ValidStitch) } } object DismissedCandidatePredicate { val ValidStitch: Stitch[PredicateResult.Valid.type] = Stitch.value(PredicateResult.Valid) val DismissedStitch: Stitch[PredicateResult.Invalid] = Stitch.value(PredicateResult.Invalid(Set(DismissedId))) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/dismiss/DismissedCandidatePredicateParams.scala
package com.twitter.follow_recommendations.common.predicates.dismiss import com.twitter.conversions.DurationOps._ import com.twitter.timelines.configapi.Param import com.twitter.util.Duration object DismissedCandidatePredicateParams { case object LookBackDuration extends Param[Duration](180.days) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/gizmoduck/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "escherbird/src/scala/com/twitter/escherbird/util/stitchcache", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/cache", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/gizmoduck", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/common", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/deciders", "stitch/stitch-gizmoduck", "util/util-slf4j-api/src/main/scala", "util/util-thrift", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/gizmoduck/GizmoduckPredicate.scala
package com.twitter.follow_recommendations.common.predicates.gizmoduck import com.twitter.decider.Decider import com.twitter.decider.RandomRecipient import com.twitter.escherbird.util.stitchcache.StitchCache import com.twitter.finagle.Memcached.Client import com.twitter.finagle.stats.StatsReceiver import com.twitter.finagle.util.DefaultTimer import com.twitter.follow_recommendations.common.base.StatsUtil import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.clients.cache.MemcacheClient import com.twitter.follow_recommendations.common.clients.cache.ThriftBijection import com.twitter.follow_recommendations.common.models.FilterReason._ import com.twitter.follow_recommendations.common.models.AddressBookMetadata import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.FilterReason import com.twitter.follow_recommendations.common.predicates.gizmoduck.GizmoduckPredicate._ import com.twitter.follow_recommendations.common.predicates.gizmoduck.GizmoduckPredicateParams._ import com.twitter.follow_recommendations.configapi.deciders.DeciderKey import com.twitter.gizmoduck.thriftscala.LabelValue.BlinkBad import com.twitter.gizmoduck.thriftscala.LabelValue.BlinkWorst import com.twitter.gizmoduck.thriftscala.LabelValue import com.twitter.gizmoduck.thriftscala.LookupContext import com.twitter.gizmoduck.thriftscala.QueryFields import com.twitter.gizmoduck.thriftscala.User import com.twitter.gizmoduck.thriftscala.UserResult import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.scrooge.CompactThriftSerializer import com.twitter.spam.rtf.thriftscala.SafetyLevel import com.twitter.stitch.Stitch import com.twitter.stitch.gizmoduck.Gizmoduck import com.twitter.timelines.configapi.HasParams import com.twitter.util.Duration import com.twitter.util.logging.Logging import java.lang.{Long => JLong} import javax.inject.Inject import javax.inject.Singleton /** * In this filter, we want to check 4 categories of conditions: * - if candidate is discoverable given that it's from an address-book/phone-book based source * - if candidate is unsuitable based on it's safety sub-fields in gizmoduck * - if candidate is withheld because of country-specific take-down policies * - if candidate is marked as bad/worst based on blink labels * We fail close on the query as this is a product-critical filter */ @Singleton case class GizmoduckPredicate @Inject() ( gizmoduck: Gizmoduck, client: Client, statsReceiver: StatsReceiver, decider: Decider = Decider.False) extends Predicate[(HasClientContext with HasParams, CandidateUser)] with Logging { private val stats: StatsReceiver = statsReceiver.scope(this.getClass.getName) // track # of Gizmoduck predicate queries that yielded valid & invalid predicate results private val validPredicateResultCounter = stats.counter("predicate_valid") private val invalidPredicateResultCounter = stats.counter("predicate_invalid") // track # of cases where no Gizmoduck user was found private val noGizmoduckUserCounter = stats.counter("no_gizmoduck_user_found") private val gizmoduckCache = StitchCache[JLong, UserResult]( maxCacheSize = MaxCacheSize, ttl = CacheTTL, statsReceiver = stats.scope("cache"), underlyingCall = getByUserId ) // Distributed Twemcache to store UserResult objects keyed on user IDs val bijection = new ThriftBijection[UserResult] { override val serializer = CompactThriftSerializer(UserResult) } val memcacheClient = MemcacheClient[UserResult]( client = client, dest = "/s/cache/frs:twemcaches", valueBijection = bijection, ttl = CacheTTL, statsReceiver = stats.scope("twemcache") ) // main method used to apply GizmoduckPredicate to a candidate user override def apply( pair: (HasClientContext with HasParams, CandidateUser) ): Stitch[PredicateResult] = { val (request, candidate) = pair // measure the latency of the getGizmoduckPredicateResult, since this predicate // check is product-critical and relies on querying a core service (Gizmoduck) StatsUtil.profileStitch( getGizmoduckPredicateResult(request, candidate), stats.scope("getGizmoduckPredicateResult") ) } private def getGizmoduckPredicateResult( request: HasClientContext with HasParams, candidate: CandidateUser ): Stitch[PredicateResult] = { val timeout: Duration = request.params(GizmoduckGetTimeout) val deciderKey: String = DeciderKey.EnableGizmoduckCaching.toString val enableDistributedCaching: Boolean = decider.isAvailable(deciderKey, Some(RandomRecipient)) // try getting an existing UserResult from cache if possible val userResultStitch: Stitch[UserResult] = enableDistributedCaching match { // read from memcache case true => memcacheClient.readThrough( // add a key prefix to address cache key collisions key = "GizmoduckPredicate" + candidate.id.toString, underlyingCall = () => getByUserId(candidate.id) ) // read from local cache case false => gizmoduckCache.readThrough(candidate.id) } val predicateResultStitch = userResultStitch.map { userResult => { val predicateResult = getPredicateResult(request, candidate, userResult) if (enableDistributedCaching) { predicateResult match { case PredicateResult.Valid => stats.scope("twemcache").counter("predicate_valid").incr() case PredicateResult.Invalid(reasons) => stats.scope("twemcache").counter("predicate_invalid").incr() } // log metrics to check if local cache value matches distributed cache value logPredicateResultEquality( request, candidate, predicateResult ) } else { predicateResult match { case PredicateResult.Valid => stats.scope("cache").counter("predicate_valid").incr() case PredicateResult.Invalid(reasons) => stats.scope("cache").counter("predicate_invalid").incr() } } predicateResult } } predicateResultStitch .within(timeout)(DefaultTimer) .rescue { // fail-open when timeout or exception case e: Exception => stats.scope("rescued").counter(e.getClass.getSimpleName).incr() invalidPredicateResultCounter.incr() Stitch(PredicateResult.Invalid(Set(FailOpen))) } } private def logPredicateResultEquality( request: HasClientContext with HasParams, candidate: CandidateUser, predicateResult: PredicateResult ): Unit = { val localCachedUserResult = Option(gizmoduckCache.cache.getIfPresent(candidate.id)) if (localCachedUserResult.isDefined) { val localPredicateResult = getPredicateResult(request, candidate, localCachedUserResult.get) localPredicateResult.equals(predicateResult) match { case true => stats.scope("has_equal_predicate_value").counter("true").incr() case false => stats.scope("has_equal_predicate_value").counter("false").incr() } } else { stats.scope("has_equal_predicate_value").counter("undefined").incr() } } // method to get PredicateResult from UserResult def getPredicateResult( request: HasClientContext with HasParams, candidate: CandidateUser, userResult: UserResult, ): PredicateResult = { userResult.user match { case Some(user) => val abPbReasons = getAbPbReason(user, candidate.getAddressBookMetadata) val safetyReasons = getSafetyReasons(user) val countryTakedownReasons = getCountryTakedownReasons(user, request.getCountryCode) val blinkReasons = getBlinkReasons(user) val allReasons = abPbReasons ++ safetyReasons ++ countryTakedownReasons ++ blinkReasons if (allReasons.nonEmpty) { invalidPredicateResultCounter.incr() PredicateResult.Invalid(allReasons) } else { validPredicateResultCounter.incr() PredicateResult.Valid } case None => noGizmoduckUserCounter.incr() invalidPredicateResultCounter.incr() PredicateResult.Invalid(Set(NoUser)) } } private def getByUserId(userId: JLong): Stitch[UserResult] = { StatsUtil.profileStitch( gizmoduck.getById(userId = userId, queryFields = queryFields, context = lookupContext), stats.scope("getByUserId") ) } } object GizmoduckPredicate { private[gizmoduck] val lookupContext: LookupContext = LookupContext(`includeDeactivated` = true, `safetyLevel` = Some(SafetyLevel.Recommendations)) private[gizmoduck] val queryFields: Set[QueryFields] = Set( QueryFields.Discoverability, // needed for Address Book / Phone Book discoverability checks in getAbPbReason QueryFields.Safety, // needed for user state safety checks in getSafetyReasons, getCountryTakedownReasons QueryFields.Labels, // needed for user label checks in getBlinkReasons QueryFields.Takedowns // needed for checking takedown labels for a user in getCountryTakedownReasons ) private[gizmoduck] val BlinkLabels: Set[LabelValue] = Set(BlinkBad, BlinkWorst) private[gizmoduck] def getAbPbReason( user: User, abMetadataOpt: Option[AddressBookMetadata] ): Set[FilterReason] = { (for { discoverability <- user.discoverability abMetadata <- abMetadataOpt } yield { val AddressBookMetadata(fwdPb, rvPb, fwdAb, rvAb) = abMetadata val abReason: Set[FilterReason] = if ((!discoverability.discoverableByEmail) && (fwdAb || rvAb)) Set(AddressBookUndiscoverable) else Set.empty val pbReason: Set[FilterReason] = if ((!discoverability.discoverableByMobilePhone) && (fwdPb || rvPb)) Set(PhoneBookUndiscoverable) else Set.empty abReason ++ pbReason }).getOrElse(Set.empty) } private[gizmoduck] def getSafetyReasons(user: User): Set[FilterReason] = { user.safety .map { s => val deactivatedReason: Set[FilterReason] = if (s.deactivated) Set(Deactivated) else Set.empty val suspendedReason: Set[FilterReason] = if (s.suspended) Set(Suspended) else Set.empty val restrictedReason: Set[FilterReason] = if (s.restricted) Set(Restricted) else Set.empty val nsfwUserReason: Set[FilterReason] = if (s.nsfwUser) Set(NsfwUser) else Set.empty val nsfwAdminReason: Set[FilterReason] = if (s.nsfwAdmin) Set(NsfwAdmin) else Set.empty val isProtectedReason: Set[FilterReason] = if (s.isProtected) Set(IsProtected) else Set.empty deactivatedReason ++ suspendedReason ++ restrictedReason ++ nsfwUserReason ++ nsfwAdminReason ++ isProtectedReason }.getOrElse(Set.empty) } private[gizmoduck] def getCountryTakedownReasons( user: User, countryCodeOpt: Option[String] ): Set[FilterReason] = { (for { safety <- user.safety.toSeq if safety.hasTakedown takedowns <- user.takedowns.toSeq takedownCountry <- takedowns.countryCodes requestingCountry <- countryCodeOpt if takedownCountry.toLowerCase == requestingCountry.toLowerCase } yield Set(CountryTakedown(takedownCountry.toLowerCase))).flatten.toSet } private[gizmoduck] def getBlinkReasons(user: User): Set[FilterReason] = { user.labels .map(_.labels.map(_.labelValue)) .getOrElse(Nil) .exists(BlinkLabels.contains) for { labels <- user.labels.toSeq label <- labels.labels if (BlinkLabels.contains(label.labelValue)) } yield Set(Blink) }.flatten.toSet }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/gizmoduck/GizmoduckPredicateCache.scala
package com.twitter.follow_recommendations.common.predicates.gizmoduck import java.util.concurrent.TimeUnit import com.google.common.base.Ticker import com.google.common.cache.CacheBuilder import com.google.common.cache.Cache import com.twitter.finagle.stats.StatsReceiver import com.twitter.util.Time import com.twitter.util.Duration /** * In-memory cache used for caching GizmoduckPredicate query calls in * com.twitter.follow_recommendations.common.predicates.gizmoduck.GizmoduckPredicate. * * References the cache implementation in com.twitter.escherbird.util.stitchcache, * but without the underlying Stitch call. */ object GizmoduckPredicateCache { private[GizmoduckPredicateCache] class TimeTicker extends Ticker { override def read(): Long = Time.now.inNanoseconds } def apply[K, V]( maxCacheSize: Int, ttl: Duration, statsReceiver: StatsReceiver ): Cache[K, V] = { val cache: Cache[K, V] = CacheBuilder .newBuilder() .maximumSize(maxCacheSize) .asInstanceOf[CacheBuilder[K, V]] .expireAfterWrite(ttl.inSeconds, TimeUnit.SECONDS) .recordStats() .ticker(new TimeTicker()) .build() // metrics for tracking cache usage statsReceiver.provideGauge("cache_size") { cache.size.toFloat } statsReceiver.provideGauge("cache_hits") { cache.stats.hitCount.toFloat } statsReceiver.provideGauge("cache_misses") { cache.stats.missCount.toFloat } statsReceiver.provideGauge("cache_hit_rate") { cache.stats.hitRate.toFloat } statsReceiver.provideGauge("cache_evictions") { cache.stats.evictionCount.toFloat } cache } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/gizmoduck/GizmoduckPredicateFSConfig.scala
package com.twitter.follow_recommendations.common.predicates.gizmoduck import com.twitter.follow_recommendations.common.predicates.gizmoduck.GizmoduckPredicateParams._ import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.HasDurationConversion import com.twitter.util.Duration import javax.inject.Inject import javax.inject.Singleton @Singleton class GizmoduckPredicateFSConfig @Inject() () extends FeatureSwitchConfig { override val durationFSParams: Seq[FSBoundedParam[Duration] with HasDurationConversion] = Seq( GizmoduckGetTimeout ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/gizmoduck/GizmoduckPredicateParams.scala
package com.twitter.follow_recommendations.common.predicates.gizmoduck import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.DurationConversion import com.twitter.timelines.configapi.HasDurationConversion import com.twitter.util.Duration import com.twitter.conversions.DurationOps._ object GizmoduckPredicateParams { case object GizmoduckGetTimeout extends FSBoundedParam[Duration]( name = "gizmoduck_predicate_timeout_in_millis", default = 200.millisecond, min = 1.millisecond, max = 500.millisecond) with HasDurationConversion { override def durationConversion: DurationConversion = DurationConversion.FromMillis } val MaxCacheSize: Int = 250000 val CacheTTL: Duration = Duration.fromHours(6) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/health/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "escherbird/src/scala/com/twitter/escherbird/util/stitchcache", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/cache", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/common", "strato/config/columns/hss/user_signals/api:api-strato-client", "util/util-slf4j-api/src/main/scala", "util/util-thrift", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/health/HssPredicate.scala
package com.twitter.follow_recommendations.common.predicates.hss import com.twitter.finagle.stats.StatsReceiver import com.twitter.finagle.util.DefaultTimer import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.base.StatsUtil import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.FilterReason import com.twitter.follow_recommendations.common.models.FilterReason.FailOpen import com.twitter.hss.api.thriftscala.SignalValue import com.twitter.hss.api.thriftscala.UserHealthSignal.AgathaCseDouble import com.twitter.hss.api.thriftscala.UserHealthSignal.NsfwAgathaUserScoreDouble import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.strato.generated.client.hss.user_signals.api.HealthSignalsOnUserClientColumn import com.twitter.timelines.configapi.HasParams import com.twitter.util.logging.Logging import com.twitter.util.Duration import javax.inject.Inject import javax.inject.Singleton /** * Filter out candidates based on Health Signal Store (HSS) health signals */ @Singleton case class HssPredicate @Inject() ( healthSignalsOnUserClientColumn: HealthSignalsOnUserClientColumn, statsReceiver: StatsReceiver) extends Predicate[(HasClientContext with HasParams, CandidateUser)] with Logging { private val stats: StatsReceiver = statsReceiver.scope(this.getClass.getName) override def apply( pair: (HasClientContext with HasParams, CandidateUser) ): Stitch[PredicateResult] = { val (request, candidate) = pair StatsUtil.profileStitch( getHssPredicateResult(request, candidate), stats.scope("getHssPredicateResult") ) } private def getHssPredicateResult( request: HasClientContext with HasParams, candidate: CandidateUser ): Stitch[PredicateResult] = { val hssCseScoreThreshold: Double = request.params(HssPredicateParams.HssCseScoreThreshold) val hssNsfwScoreThreshold: Double = request.params(HssPredicateParams.HssNsfwScoreThreshold) val timeout: Duration = request.params(HssPredicateParams.HssApiTimeout) healthSignalsOnUserClientColumn.fetcher .fetch(candidate.id, Seq(AgathaCseDouble, NsfwAgathaUserScoreDouble)) .map { fetchResult => fetchResult.v match { case Some(response) => val agathaCseScoreDouble: Double = userHealthSignalValueToDoubleOpt( response.signalValues.get(AgathaCseDouble)).getOrElse(0d) val agathaNsfwScoreDouble: Double = userHealthSignalValueToDoubleOpt( response.signalValues.get(NsfwAgathaUserScoreDouble)).getOrElse(0d) stats.stat("agathaCseScoreDistribution").add(agathaCseScoreDouble.toFloat) stats.stat("agathaNsfwScoreDistribution").add(agathaNsfwScoreDouble.toFloat) /** * Only filter out the candidate when it has both high Agatha CSE score and NSFW score, as the Agatha CSE * model is an old one that may not be precise or have high recall. */ if (agathaCseScoreDouble >= hssCseScoreThreshold && agathaNsfwScoreDouble >= hssNsfwScoreThreshold) { PredicateResult.Invalid(Set(FilterReason.HssSignal)) } else { PredicateResult.Valid } case None => PredicateResult.Valid } } .within(timeout)(DefaultTimer) .rescue { case e: Exception => stats.scope("rescued").counter(e.getClass.getSimpleName).incr() Stitch(PredicateResult.Invalid(Set(FailOpen))) } } private def userHealthSignalValueToDoubleOpt(signalValue: Option[SignalValue]): Option[Double] = { signalValue match { case Some(SignalValue.DoubleValue(value)) => Some(value) case _ => None } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/health/HssPredicateFSConfig.scala
package com.twitter.follow_recommendations.common.predicates.hss import com.twitter.follow_recommendations.common.predicates.hss.HssPredicateParams._ import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.HasDurationConversion import com.twitter.util.Duration import javax.inject.Inject import javax.inject.Singleton @Singleton class HssPredicateFSConfig @Inject() () extends FeatureSwitchConfig { override val doubleFSParams: Seq[FSBoundedParam[Double]] = Seq( HssCseScoreThreshold, HssNsfwScoreThreshold, ) override val durationFSParams: Seq[FSBoundedParam[Duration] with HasDurationConversion] = Seq( HssApiTimeout ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/health/HssPredicateParams.scala
package com.twitter.follow_recommendations.common.predicates.hss import com.twitter.conversions.DurationOps._ import com.twitter.timelines.configapi.DurationConversion import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.HasDurationConversion import com.twitter.util.Duration object HssPredicateParams { object HssCseScoreThreshold extends FSBoundedParam[Double]( "hss_predicate_cse_score_threshold", default = 0.992d, min = 0.0d, max = 1.0d) object HssNsfwScoreThreshold extends FSBoundedParam[Double]( "hss_predicate_nsfw_score_threshold", default = 1.5d, min = -100.0d, max = 100.0d) object HssApiTimeout extends FSBoundedParam[Duration]( name = "hss_predicate_timeout_in_millis", default = 200.millisecond, min = 1.millisecond, max = 500.millisecond) with HasDurationConversion { override def durationConversion: DurationConversion = DurationConversion.FromMillis } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/sgs/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/socialgraph", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/common", "src/thrift/com/twitter/socialgraph:thrift-scala", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/sgs/InvalidRelationshipPredicate.scala
package com.twitter.follow_recommendations.common.predicates.sgs import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.FilterReason import com.twitter.follow_recommendations.common.models.HasInvalidRelationshipUserIds import com.twitter.stitch.Stitch import javax.inject.Singleton @Singleton class InvalidRelationshipPredicate extends Predicate[(HasInvalidRelationshipUserIds, CandidateUser)] { override def apply( pair: (HasInvalidRelationshipUserIds, CandidateUser) ): Stitch[PredicateResult] = { val (targetUser, candidate) = pair targetUser.invalidRelationshipUserIds match { case Some(users) => if (!users.contains(candidate.id)) { InvalidRelationshipPredicate.ValidStitch } else { Stitch.value(InvalidRelationshipPredicate.InvalidRelationshipStitch) } case None => Stitch.value(PredicateResult.Valid) } } } object InvalidRelationshipPredicate { val ValidStitch: Stitch[PredicateResult.Valid.type] = Stitch.value(PredicateResult.Valid) val InvalidRelationshipStitch: PredicateResult.Invalid = PredicateResult.Invalid(Set(FilterReason.InvalidRelationship)) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/sgs/RecentFollowingPredicate.scala
package com.twitter.follow_recommendations.common.predicates.sgs import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.FilterReason import com.twitter.follow_recommendations.common.models.HasRecentFollowedUserIds import com.twitter.stitch.Stitch import javax.inject.Singleton @Singleton class RecentFollowingPredicate extends Predicate[(HasRecentFollowedUserIds, CandidateUser)] { override def apply(pair: (HasRecentFollowedUserIds, CandidateUser)): Stitch[PredicateResult] = { val (targetUser, candidate) = pair targetUser.recentFollowedUserIdsSet match { case Some(users) => if (!users.contains(candidate.id)) { RecentFollowingPredicate.ValidStitch } else { RecentFollowingPredicate.AlreadyFollowedStitch } case None => RecentFollowingPredicate.ValidStitch } } } object RecentFollowingPredicate { val ValidStitch: Stitch[PredicateResult.Valid.type] = Stitch.value(PredicateResult.Valid) val AlreadyFollowedStitch: Stitch[PredicateResult.Invalid] = Stitch.value(PredicateResult.Invalid(Set(FilterReason.AlreadyFollowed))) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/sgs/SgsPredicateFSConfig.scala
package com.twitter.follow_recommendations.common.predicates.sgs import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.HasDurationConversion import com.twitter.util.Duration import javax.inject.Inject import javax.inject.Singleton @Singleton class SgsPredicateFSConfig @Inject() () extends FeatureSwitchConfig { override val durationFSParams: Seq[FSBoundedParam[Duration] with HasDurationConversion] = Seq( SgsPredicateParams.SgsRelationshipsPredicateTimeout ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/sgs/SgsPredicateParams.scala
package com.twitter.follow_recommendations.common.predicates.sgs import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.DurationConversion import com.twitter.timelines.configapi.HasDurationConversion import com.twitter.util.Duration import com.twitter.conversions.DurationOps._ object SgsPredicateParams { case object SgsRelationshipsPredicateTimeout extends FSBoundedParam[Duration]( name = "sgs_predicate_relationships_timeout_in_millis", default = 300.millisecond, min = 1.millisecond, max = 1000.millisecond) with HasDurationConversion { override def durationConversion: DurationConversion = DurationConversion.FromMillis } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/sgs/SgsRelationshipsByUserIdPredicate.scala
package com.twitter.follow_recommendations.common.predicates.sgs import com.google.common.annotations.VisibleForTesting import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.FilterReason.InvalidRelationshipTypes import com.twitter.socialgraph.thriftscala.ExistsRequest import com.twitter.socialgraph.thriftscala.ExistsResult import com.twitter.socialgraph.thriftscala.LookupContext import com.twitter.socialgraph.thriftscala.Relationship import com.twitter.socialgraph.thriftscala.RelationshipType import com.twitter.stitch.Stitch import com.twitter.stitch.socialgraph.SocialGraph import com.twitter.util.logging.Logging import javax.inject.Inject import javax.inject.Singleton class SgsRelationshipsByUserIdPredicate( socialGraph: SocialGraph, relationshipMappings: Seq[RelationshipMapping], statsReceiver: StatsReceiver) extends Predicate[(Option[Long], CandidateUser)] with Logging { private val InvalidFromPrimaryCandidateSourceName = "invalid_from_primary_candidate_source" private val InvalidFromCandidateSourceName = "invalid_from_candidate_source" private val NoPrimaryCandidateSource = "no_primary_candidate_source" private val stats: StatsReceiver = statsReceiver.scope(this.getClass.getName) override def apply( pair: (Option[Long], CandidateUser) ): Stitch[PredicateResult] = { val (idOpt, candidate) = pair val relationships = relationshipMappings.map { relationshipMapping: RelationshipMapping => Relationship( relationshipMapping.relationshipType, relationshipMapping.includeBasedOnRelationship) } idOpt .map { id: Long => val existsRequest = ExistsRequest( id, candidate.id, relationships = relationships, context = SgsRelationshipsByUserIdPredicate.UnionLookupContext ) socialGraph .exists(existsRequest).map { existsResult: ExistsResult => if (existsResult.exists) { candidate.getPrimaryCandidateSource match { case Some(candidateSource) => stats .scope(InvalidFromPrimaryCandidateSourceName).counter( candidateSource.name).incr() case None => stats .scope(InvalidFromPrimaryCandidateSourceName).counter( NoPrimaryCandidateSource).incr() } candidate.getCandidateSources.foreach({ case (candidateSource, _) => stats .scope(InvalidFromCandidateSourceName).counter(candidateSource.name).incr() }) PredicateResult.Invalid(Set(InvalidRelationshipTypes(relationshipMappings .map { relationshipMapping: RelationshipMapping => relationshipMapping.relationshipType }.mkString(", ")))) } else { PredicateResult.Valid } } } // if no user id is present, return true by default .getOrElse(Stitch.value(PredicateResult.Valid)) } } object SgsRelationshipsByUserIdPredicate { // OR Operation @VisibleForTesting private[follow_recommendations] val UnionLookupContext = Some( LookupContext(performUnion = Some(true))) } @Singleton class ExcludeNonFollowersSgsPredicate @Inject() ( socialGraph: SocialGraph, statsReceiver: StatsReceiver) extends SgsRelationshipsByUserIdPredicate( socialGraph, Seq(RelationshipMapping(RelationshipType.FollowedBy, includeBasedOnRelationship = false)), statsReceiver) @Singleton class ExcludeNonFollowingSgsPredicate @Inject() ( socialGraph: SocialGraph, statsReceiver: StatsReceiver) extends SgsRelationshipsByUserIdPredicate( socialGraph, Seq(RelationshipMapping(RelationshipType.Following, includeBasedOnRelationship = false)), statsReceiver) @Singleton class ExcludeFollowingSgsPredicate @Inject() ( socialGraph: SocialGraph, statsReceiver: StatsReceiver) extends SgsRelationshipsByUserIdPredicate( socialGraph, Seq(RelationshipMapping(RelationshipType.Following, includeBasedOnRelationship = true)), statsReceiver)
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/sgs/SgsRelationshipsPredicate.scala
package com.twitter.follow_recommendations.common.predicates.sgs import com.google.common.annotations.VisibleForTesting import com.twitter.finagle.stats.NullStatsReceiver import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasProfileId import com.twitter.follow_recommendations.common.models.FilterReason.FailOpen import com.twitter.follow_recommendations.common.models.FilterReason.InvalidRelationshipTypes import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.socialgraph.thriftscala.ExistsRequest import com.twitter.socialgraph.thriftscala.ExistsResult import com.twitter.socialgraph.thriftscala.LookupContext import com.twitter.socialgraph.thriftscala.Relationship import com.twitter.socialgraph.thriftscala.RelationshipType import com.twitter.stitch.Stitch import com.twitter.stitch.socialgraph.SocialGraph import com.twitter.timelines.configapi.HasParams import com.twitter.util.TimeoutException import com.twitter.util.logging.Logging import javax.inject.Inject import javax.inject.Singleton case class RelationshipMapping( relationshipType: RelationshipType, includeBasedOnRelationship: Boolean) class SgsRelationshipsPredicate( socialGraph: SocialGraph, relationshipMappings: Seq[RelationshipMapping], statsReceiver: StatsReceiver = NullStatsReceiver) extends Predicate[(HasClientContext with HasParams, CandidateUser)] with Logging { private val stats: StatsReceiver = statsReceiver.scope(this.getClass.getSimpleName) override def apply( pair: (HasClientContext with HasParams, CandidateUser) ): Stitch[PredicateResult] = { val (target, candidate) = pair val timeout = target.params(SgsPredicateParams.SgsRelationshipsPredicateTimeout) SgsRelationshipsPredicate .extractUserId(target) .map { id => val relationships = relationshipMappings.map { relationshipMapping: RelationshipMapping => Relationship( relationshipMapping.relationshipType, relationshipMapping.includeBasedOnRelationship) } val existsRequest = ExistsRequest( id, candidate.id, relationships = relationships, context = SgsRelationshipsPredicate.UnionLookupContext ) socialGraph .exists(existsRequest).map { existsResult: ExistsResult => if (existsResult.exists) { PredicateResult.Invalid(Set(InvalidRelationshipTypes(relationshipMappings .map { relationshipMapping: RelationshipMapping => relationshipMapping.relationshipType }.mkString(", ")))) } else { PredicateResult.Valid } } .within(timeout)(com.twitter.finagle.util.DefaultTimer) } // if no user id is present, return true by default .getOrElse(Stitch.value(PredicateResult.Valid)) .rescue { case e: TimeoutException => stats.counter("timeout").incr() Stitch(PredicateResult.Invalid(Set(FailOpen))) case e: Exception => stats.counter(e.getClass.getSimpleName).incr() Stitch(PredicateResult.Invalid(Set(FailOpen))) } } } object SgsRelationshipsPredicate { // OR Operation @VisibleForTesting private[follow_recommendations] val UnionLookupContext = Some( LookupContext(performUnion = Some(true))) private def extractUserId(target: HasClientContext with HasParams): Option[Long] = target match { case profRequest: HasProfileId => Some(profRequest.profileId) case userRequest: HasClientContext with HasParams => userRequest.getOptionalUserId case _ => None } } @Singleton class InvalidTargetCandidateRelationshipTypesPredicate @Inject() ( socialGraph: SocialGraph) extends SgsRelationshipsPredicate( socialGraph, InvalidRelationshipTypesPredicate.InvalidRelationshipTypes) {} @Singleton class NoteworthyAccountsSgsPredicate @Inject() ( socialGraph: SocialGraph) extends SgsRelationshipsPredicate( socialGraph, InvalidRelationshipTypesPredicate.NoteworthyAccountsInvalidRelationshipTypes) object InvalidRelationshipTypesPredicate { val InvalidRelationshipTypesExcludeFollowing: Seq[RelationshipMapping] = Seq( RelationshipMapping(RelationshipType.HideRecommendations, true), RelationshipMapping(RelationshipType.Blocking, true), RelationshipMapping(RelationshipType.BlockedBy, true), RelationshipMapping(RelationshipType.Muting, true), RelationshipMapping(RelationshipType.MutedBy, true), RelationshipMapping(RelationshipType.ReportedAsSpam, true), RelationshipMapping(RelationshipType.ReportedAsSpamBy, true), RelationshipMapping(RelationshipType.ReportedAsAbuse, true), RelationshipMapping(RelationshipType.ReportedAsAbuseBy, true) ) val InvalidRelationshipTypes: Seq[RelationshipMapping] = Seq( RelationshipMapping(RelationshipType.FollowRequestOutgoing, true), RelationshipMapping(RelationshipType.Following, true), RelationshipMapping( RelationshipType.UsedToFollow, true ) // this data is accessible for 90 days. ) ++ InvalidRelationshipTypesExcludeFollowing val NoteworthyAccountsInvalidRelationshipTypes: Seq[RelationshipMapping] = Seq( RelationshipMapping(RelationshipType.Blocking, true), RelationshipMapping(RelationshipType.BlockedBy, true), RelationshipMapping(RelationshipType.Muting, true), RelationshipMapping(RelationshipType.MutedBy, true), RelationshipMapping(RelationshipType.ReportedAsSpam, true), RelationshipMapping(RelationshipType.ReportedAsSpamBy, true), RelationshipMapping(RelationshipType.ReportedAsAbuse, true), RelationshipMapping(RelationshipType.ReportedAsAbuseBy, true) ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/user_activity/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/cache", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/strato", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/deciders", "strato/config/columns/onboarding:onboarding-strato-client", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/user_activity/UserActivityPredicate.scala
package com.twitter.follow_recommendations.common.predicates.user_activity import com.twitter.core_workflows.user_model.thriftscala.UserState import com.twitter.decider.Decider import com.twitter.decider.RandomRecipient import com.twitter.finagle.Memcached.Client import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.Predicate import com.twitter.follow_recommendations.common.base.PredicateResult import com.twitter.follow_recommendations.common.base.StatsUtil import com.twitter.follow_recommendations.common.clients.cache.MemcacheClient import com.twitter.follow_recommendations.common.clients.cache.ThriftEnumOptionBijection import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.FilterReason import com.twitter.follow_recommendations.configapi.deciders.DeciderKey import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.strato.generated.client.onboarding.UserRecommendabilityWithLongKeysOnUserClientColumn import com.twitter.timelines.configapi.HasParams import javax.inject.Inject import javax.inject.Singleton abstract case class UserStateActivityPredicate( userRecommendabilityClient: UserRecommendabilityWithLongKeysOnUserClientColumn, validCandidateStates: Set[UserState], client: Client, statsReceiver: StatsReceiver, decider: Decider = Decider.False) extends Predicate[(HasParams with HasClientContext, CandidateUser)] { private val stats: StatsReceiver = statsReceiver.scope(this.getClass.getSimpleName) // client to memcache cluster val bijection = new ThriftEnumOptionBijection[UserState](UserState.apply) val memcacheClient = MemcacheClient[Option[UserState]]( client = client, dest = "/s/cache/follow_recos_service:twemcaches", valueBijection = bijection, ttl = UserActivityPredicateParams.CacheTTL, statsReceiver = stats.scope("twemcache") ) override def apply( targetAndCandidate: (HasParams with HasClientContext, CandidateUser) ): Stitch[PredicateResult] = { val userRecommendabilityFetcher = userRecommendabilityClient.fetcher val (_, candidate) = targetAndCandidate val deciderKey: String = DeciderKey.EnableExperimentalCaching.toString val enableDistributedCaching: Boolean = decider.isAvailable(deciderKey, Some(RandomRecipient)) val userStateStitch: Stitch[Option[UserState]] = enableDistributedCaching match { case true => { memcacheClient.readThrough( // add a key prefix to address cache key collisions key = "UserActivityPredicate" + candidate.id.toString, underlyingCall = () => queryUserRecommendable(candidate.id) ) } case false => queryUserRecommendable(candidate.id) } val resultStitch: Stitch[PredicateResult] = userStateStitch.map { userStateOpt => userStateOpt match { case Some(userState) => { if (validCandidateStates.contains(userState)) { PredicateResult.Valid } else { PredicateResult.Invalid(Set(FilterReason.MinStateNotMet)) } } case None => { PredicateResult.Invalid(Set(FilterReason.MissingRecommendabilityData)) } } } StatsUtil.profileStitch(resultStitch, stats.scope("apply")) .rescue { case e: Exception => stats.scope("rescued").counter(e.getClass.getSimpleName).incr() Stitch(PredicateResult.Invalid(Set(FilterReason.FailOpen))) } } def queryUserRecommendable( userId: Long ): Stitch[Option[UserState]] = { val userRecommendabilityFetcher = userRecommendabilityClient.fetcher userRecommendabilityFetcher.fetch(userId).map { userCandidate => userCandidate.v.flatMap(_.userState) } } } @Singleton class MinStateUserActivityPredicate @Inject() ( userRecommendabilityClient: UserRecommendabilityWithLongKeysOnUserClientColumn, client: Client, statsReceiver: StatsReceiver) extends UserStateActivityPredicate( userRecommendabilityClient, Set( UserState.Light, UserState.HeavyNonTweeter, UserState.MediumNonTweeter, UserState.HeavyTweeter, UserState.MediumTweeter ), client, statsReceiver ) @Singleton class AllTweeterUserActivityPredicate @Inject() ( userRecommendabilityClient: UserRecommendabilityWithLongKeysOnUserClientColumn, client: Client, statsReceiver: StatsReceiver) extends UserStateActivityPredicate( userRecommendabilityClient, Set( UserState.HeavyTweeter, UserState.MediumTweeter ), client, statsReceiver ) @Singleton class HeavyTweeterUserActivityPredicate @Inject() ( userRecommendabilityClient: UserRecommendabilityWithLongKeysOnUserClientColumn, client: Client, statsReceiver: StatsReceiver) extends UserStateActivityPredicate( userRecommendabilityClient, Set( UserState.HeavyTweeter ), client, statsReceiver ) @Singleton class NonNearZeroUserActivityPredicate @Inject() ( userRecommendabilityClient: UserRecommendabilityWithLongKeysOnUserClientColumn, client: Client, statsReceiver: StatsReceiver) extends UserStateActivityPredicate( userRecommendabilityClient, Set( UserState.New, UserState.VeryLight, UserState.Light, UserState.MediumNonTweeter, UserState.MediumTweeter, UserState.HeavyNonTweeter, UserState.HeavyTweeter ), client, statsReceiver )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/user_activity/UserActivityPredicateParams.scala
package com.twitter.follow_recommendations.common.predicates.user_activity import com.twitter.timelines.configapi.FSParam import com.twitter.util.Duration object UserActivityPredicateParams { case object HeavyTweeterEnabled extends FSParam[Boolean]("user_activity_predicate_heavy_tweeter_enabled", false) val CacheTTL: Duration = Duration.fromHours(6) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common/AdhocScoreModificationType.scala
package com.twitter.follow_recommendations.common.rankers.common /** * To manage the extent of adhoc score modifications, we set a hard limit that from each of the * types below *ONLY ONE* adhoc scorer can be applied to candidates' scores. More details about the * usage is available in [[AdhocRanker]] */ object AdhocScoreModificationType extends Enumeration { type AdhocScoreModificationType = Value // This type of scorer increases the score of a subset of candidates through various policies. val BoostingScorer: AdhocScoreModificationType = Value("boosting") // This type of scorer shuffles candidates randomly according to some distribution. val WeightedRandomSamplingScorer: AdhocScoreModificationType = Value("weighted_random_sampling") // This is added solely for testing purposes and should not be used in production. val InvalidAdhocScorer: AdhocScoreModificationType = Value("invalid_adhoc_scorer") }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/org/slf4j:slf4j-api", "product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/common", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common/DedupCandidates.scala
package com.twitter.follow_recommendations.common.rankers.common import com.twitter.product_mixer.core.model.common.UniversalNoun import scala.collection.mutable object DedupCandidates { def apply[C <: UniversalNoun[Long]](input: Seq[C]): Seq[C] = { val seen = mutable.HashSet[Long]() input.filter { candidate => seen.add(candidate.id) } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common/RankerId.scala
package com.twitter.follow_recommendations.common.rankers.common object RankerId extends Enumeration { type RankerId = Value val RandomRanker: RankerId = Value("random") // The production PostNUX ML warm-start auto-retraining model ranker val PostNuxProdRanker: RankerId = Value("postnux_prod") val None: RankerId = Value("none") // Sampling from the Placket-Luce distribution. Applied after ranker step. Its ranker id is mainly used for logging. val PlacketLuceSamplingTransformer: RankerId = Value("placket_luce_sampling_transformer") def getRankerByName(name: String): Option[RankerId] = RankerId.values.toSeq.find(_.equals(Value(name))) } /** * ML model based heavy ranker ids. */ object ModelBasedHeavyRankerId { import RankerId._ val HeavyRankerIds: Set[String] = Set( PostNuxProdRanker.toString, ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/fatigue_ranker/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/impression_store", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/utils", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/common", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/fatigue_ranker/ImpressionBasedFatigueRanker.scala
package com.twitter.follow_recommendations.common.rankers.fatigue_ranker import com.twitter.finagle.stats.Counter import com.twitter.finagle.stats.Stat import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.Ranker import com.twitter.follow_recommendations.common.base.StatsUtil import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasWtfImpressions import com.twitter.follow_recommendations.common.models.WtfImpression import com.twitter.follow_recommendations.common.rankers.common.RankerId.RankerId import com.twitter.follow_recommendations.common.rankers.utils.Utils import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.servo.util.MemoizingStatsReceiver import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import com.twitter.util.Time /** * Ranks candidates based on the given weights for each algorithm while preserving the ranks inside each algorithm. * Reorders the ranked list based on recent impressions from recentImpressionRepo * * Note that the penalty is added to the rank of each candidate. To make producer-side experiments * with multiple rankers possible, we modify the scores for each candidate and ranker as: * NewScore(C, R) = -(Rank(C, R) + Impression(C, U) x FatigueFactor), * where C is a candidate, R a ranker and U the target user. * Note also that fatigue penalty is independent of any of the rankers. */ class ImpressionBasedFatigueRanker[ Target <: HasClientContext with HasDisplayLocation with HasParams with HasWtfImpressions ]( fatigueFactor: Int, statsReceiver: StatsReceiver) extends Ranker[Target, CandidateUser] { val name: String = this.getClass.getSimpleName val stats = statsReceiver.scope("impression_based_fatigue_ranker") val droppedStats: MemoizingStatsReceiver = new MemoizingStatsReceiver(stats.scope("hard_drops")) val impressionStats: StatsReceiver = stats.scope("wtf_impressions") val noImpressionCounter: Counter = impressionStats.counter("no_impressions") val oldestImpressionStat: Stat = impressionStats.stat("oldest_sec") override def rank(target: Target, candidates: Seq[CandidateUser]): Stitch[Seq[CandidateUser]] = { StatsUtil.profileStitch( Stitch.value(rankCandidates(target, candidates)), stats.scope("rank") ) } private def trackTimeSinceOldestImpression(impressions: Seq[WtfImpression]): Unit = { val timeSinceOldest = Time.now - impressions.map(_.latestTime).min oldestImpressionStat.add(timeSinceOldest.inSeconds) } private def rankCandidates( target: Target, candidates: Seq[CandidateUser] ): Seq[CandidateUser] = { target.wtfImpressions .map { wtfImpressions => if (wtfImpressions.isEmpty) { noImpressionCounter.incr() candidates } else { val rankerIds = candidates.flatMap(_.scores.map(_.scores.flatMap(_.rankerId))).flatten.sorted.distinct /** * In below we create a Map from each CandidateUser's ID to a Map from each Ranker that * the user has a score for, and candidate's corresponding rank when candidates are sorted * by that Ranker (Only candidates who have this Ranker are considered for ranking). */ val candidateRanks: Map[Long, Map[RankerId, Int]] = rankerIds .flatMap { rankerId => // Candidates with no scores from this Ranker is first removed to calculate ranks. val relatedCandidates = candidates.filter(_.scores.exists(_.scores.exists(_.rankerId.contains(rankerId)))) relatedCandidates .sortBy(-_.scores .flatMap(_.scores.find(_.rankerId.contains(rankerId)).map(_.value)).getOrElse( 0.0)).zipWithIndex.map { case (candidate, rank) => (candidate.id, rankerId, rank) } }.groupBy(_._1).map { case (candidate, ranksForAllRankers) => ( candidate, ranksForAllRankers.map { case (_, rankerId, rank) => (rankerId, rank) }.toMap) } val idFatigueCountMap = wtfImpressions.groupBy(_.candidateId).mapValues(_.map(_.counts).sum) trackTimeSinceOldestImpression(wtfImpressions) val rankedCandidates: Seq[CandidateUser] = candidates .map { candidate => val candidateImpressions = idFatigueCountMap.getOrElse(candidate.id, 0) val fatiguedScores = candidate.scores.map { ss => ss.copy(scores = ss.scores.map { s => s.rankerId match { // We set the new score as -rank after fatigue penalty is applied. case Some(rankerId) => // If the candidate's ID is not in the candidate->ranks map, or there is no // rank for this specific ranker and this candidate, we use maximum possible // rank instead. Note that this indicates that there is a problem. s.copy(value = -(candidateRanks .getOrElse(candidate.id, Map()).getOrElse(rankerId, candidates.length) + candidateImpressions * fatigueFactor)) // In case a score exists without a RankerId, we pass on the score as is. case None => s } }) } candidate.copy(scores = fatiguedScores) }.zipWithIndex.map { // We re-rank candidates with their input ordering (which is done by the request-level // ranker) and fatigue penalty. case (candidate, inputRank) => val candidateImpressions = idFatigueCountMap.getOrElse(candidate.id, 0) (candidate, inputRank + candidateImpressions * fatigueFactor) }.sortBy(_._2).map(_._1) // Only populate ranking info when WTF impression info present val scribeRankingInfo: Boolean = target.params(ImpressionBasedFatigueRankerParams.ScribeRankingInfoInFatigueRanker) if (scribeRankingInfo) Utils.addRankingInfo(rankedCandidates, name) else rankedCandidates } }.getOrElse(candidates) // no reranking/filtering when wtf impressions not present } } object ImpressionBasedFatigueRanker { val DefaultFatigueFactor = 5 def build[ Target <: HasClientContext with HasDisplayLocation with HasParams with HasWtfImpressions ]( baseStatsReceiver: StatsReceiver, fatigueFactor: Int = DefaultFatigueFactor ): ImpressionBasedFatigueRanker[Target] = new ImpressionBasedFatigueRanker(fatigueFactor, baseStatsReceiver) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/fatigue_ranker/ImpressionBasedFatigueRankerFSConfig.scala
package com.twitter.follow_recommendations.common.rankers.fatigue_ranker import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig import com.twitter.timelines.configapi.FSParam import javax.inject.Inject import javax.inject.Singleton @Singleton class ImpressionBasedFatigueRankerFSConfig @Inject() extends FeatureSwitchConfig { override val booleanFSParams: Seq[FSParam[Boolean]] = Seq(ImpressionBasedFatigueRankerParams.ScribeRankingInfoInFatigueRanker) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/fatigue_ranker/ImpressionBasedFatigueRankerParams.scala
package com.twitter.follow_recommendations.common.rankers.fatigue_ranker import com.twitter.timelines.configapi.FSParam import com.twitter.timelines.configapi.Param object ImpressionBasedFatigueRankerParams { // Whether to enable hard dropping of impressed candidates object DropImpressedCandidateEnabled extends Param[Boolean](false) // At what # of impressions to hard drop candidates. object DropCandidateImpressionThreshold extends Param[Int](default = 10) // Whether to scribe candidate ranking/scoring info per ranking stage object ScribeRankingInfoInFatigueRanker extends FSParam[Boolean]("fatigue_ranker_scribe_ranking_info", true) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/first_n_ranker/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/utils", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/utils", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/common", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/first_n_ranker/FirstNRanker.scala
package com.twitter.follow_recommendations.common.rankers.first_n_ranker import com.google.inject.Inject import com.google.inject.Singleton import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.Ranker import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasQualityFactor import com.twitter.follow_recommendations.common.rankers.utils.Utils import com.twitter.product_mixer.core.model.common.identifier.CandidateSourceIdentifier import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams /** * This class is meant to filter candidates between stages of our ranker by taking the first N * candidates, merging any candidate source information for candidates with multiple entries. * To allow us to chain this truncation operation any number of times sequentially within the main * ranking builder, we abstract the truncation as a separate Ranker */ @Singleton class FirstNRanker[Target <: HasClientContext with HasParams with HasQualityFactor] @Inject() ( stats: StatsReceiver) extends Ranker[Target, CandidateUser] { val name: String = this.getClass.getSimpleName private val baseStats = stats.scope("first_n_ranker") val scaledDownByQualityFactorCounter = baseStats.counter("scaled_down_by_quality_factor") private val mergeStat = baseStats.scope("merged_candidates") private val mergeStat2 = mergeStat.counter("2") private val mergeStat3 = mergeStat.counter("3") private val mergeStat4 = mergeStat.counter("4+") private val candidateSizeStats = baseStats.scope("candidate_size") private case class CandidateSourceScore( candidateId: Long, sourceId: CandidateSourceIdentifier, score: Option[Double]) /** * Adds the rank of each candidate based on the primary candidate source's score. * In the event where the provided ordering of candidates do not align with the score, * we will respect the score, since the ordering might have been mixed up due to other previous * steps like the shuffleFn in the `WeightedCandidateSourceRanker`. * @param candidates ordered list of candidates * @return same ordered list of candidates, but with the rank information appended */ def addRank(candidates: Seq[CandidateUser]): Seq[CandidateUser] = { val candidateSourceRanks = for { (sourceIdOpt, sourceCandidates) <- candidates.groupBy(_.getPrimaryCandidateSource) (candidate, rank) <- sourceCandidates.sortBy(-_.score.getOrElse(0.0)).zipWithIndex } yield { (candidate, sourceIdOpt) -> rank } candidates.map { c => c.getPrimaryCandidateSource .map { sourceId => val sourceRank = candidateSourceRanks((c, c.getPrimaryCandidateSource)) c.addCandidateSourceRanksMap(Map(sourceId -> sourceRank)) }.getOrElse(c) } } override def rank(target: Target, candidates: Seq[CandidateUser]): Stitch[Seq[CandidateUser]] = { val scaleDownFactor = Math.max( target.qualityFactor.getOrElse(1.0d), target.params(FirstNRankerParams.MinNumCandidatesScoredScaleDownFactor) ) if (scaleDownFactor < 1.0d) scaledDownByQualityFactorCounter.incr() val n = (target.params(FirstNRankerParams.CandidatesToRank) * scaleDownFactor).toInt val scribeRankingInfo: Boolean = target.params(FirstNRankerParams.ScribeRankingInfoInFirstNRanker) candidateSizeStats.counter(s"n$n").incr() val candidatesWithRank = addRank(candidates) if (target.params(FirstNRankerParams.GroupDuplicateCandidates)) { val groupedCandidates: Map[Long, Seq[CandidateUser]] = candidatesWithRank.groupBy(_.id) val topN = candidates .map { c => merge(groupedCandidates(c.id)) }.distinct.take(n) Stitch.value(if (scribeRankingInfo) Utils.addRankingInfo(topN, name) else topN) } else { Stitch.value( if (scribeRankingInfo) Utils.addRankingInfo(candidatesWithRank, name).take(n) else candidatesWithRank.take(n)) } // for efficiency, if don't need to deduplicate } /** * we use the primary candidate source of the first entry, and aggregate all of the other entries' * candidate source scores into the first entry's candidateSourceScores * @param candidates list of candidates with the same id * @return a single merged candidate */ private[first_n_ranker] def merge(candidates: Seq[CandidateUser]): CandidateUser = { if (candidates.size == 1) { candidates.head } else { candidates.size match { case 2 => mergeStat2.incr() case 3 => mergeStat3.incr() case i if i >= 4 => mergeStat4.incr() case _ => } val allSources = candidates.flatMap(_.getCandidateSources).toMap val allRanks = candidates.flatMap(_.getCandidateRanks).toMap candidates.head.addCandidateSourceScoresMap(allSources).addCandidateSourceRanksMap(allRanks) } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/first_n_ranker/FirstNRankerFSConfig.scala
package com.twitter.follow_recommendations.common.rankers.first_n_ranker import javax.inject.Inject import javax.inject.Singleton import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.FSParam @Singleton class FirstNRankerFSConfig @Inject() extends FeatureSwitchConfig { override val booleanFSParams: Seq[FSParam[Boolean]] = Seq(FirstNRankerParams.ScribeRankingInfoInFirstNRanker) override val intFSParams: Seq[FSBoundedParam[Int]] = Seq( FirstNRankerParams.CandidatesToRank ) override val doubleFSParams: Seq[FSBoundedParam[Double]] = Seq( FirstNRankerParams.MinNumCandidatesScoredScaleDownFactor ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/first_n_ranker/FirstNRankerFeatureSwitchKeys.scala
package com.twitter.follow_recommendations.common.rankers.first_n_ranker object FirstNRankerFeatureSwitchKeys { val CandidatePoolSize = "first_n_ranker_candidate_pool_size" val ScribeRankingInfo = "first_n_ranker_scribe_ranking_info" val MinNumCandidatesScoredScaleDownFactor = "first_n_ranker_min_scale_down_factor" }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/first_n_ranker/FirstNRankerParams.scala
package com.twitter.follow_recommendations.common.rankers.first_n_ranker import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.FSParam import com.twitter.timelines.configapi.Param object FirstNRankerParams { case object CandidatesToRank extends FSBoundedParam[Int]( FirstNRankerFeatureSwitchKeys.CandidatePoolSize, default = 100, min = 50, max = 600) case object GroupDuplicateCandidates extends Param[Boolean](true) case object ScribeRankingInfoInFirstNRanker extends FSParam[Boolean](FirstNRankerFeatureSwitchKeys.ScribeRankingInfo, true) // the minimum of candidates to score in each request. object MinNumCandidatesScoredScaleDownFactor extends FSBoundedParam[Double]( name = FirstNRankerFeatureSwitchKeys.MinNumCandidatesScoredScaleDownFactor, default = 0.3, min = 0.1, max = 1.0) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/interleave_ranker/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/ranking", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/utils", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/utils", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/common", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/interleave_ranker/InterleaveRanker.scala
package com.twitter.follow_recommendations.common.rankers.interleave_ranker import com.google.common.annotations.VisibleForTesting import com.google.inject.Inject import com.google.inject.Singleton import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.Ranker import com.twitter.follow_recommendations.common.base.StatsUtil import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.rankers.common.RankerId import com.twitter.follow_recommendations.common.rankers.utils.Utils import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams @Singleton class InterleaveRanker[Target <: HasParams] @Inject() ( statsReceiver: StatsReceiver) extends Ranker[Target, CandidateUser] { val name: String = this.getClass.getSimpleName private val stats = statsReceiver.scope("interleave_ranker") private val inputStats = stats.scope("input") private val interleavingStats = stats.scope("interleave") override def rank( target: Target, candidates: Seq[CandidateUser] ): Stitch[Seq[CandidateUser]] = { StatsUtil.profileStitch( Stitch.value(rankCandidates(target, candidates)), stats.scope("rank") ) } private def rankCandidates( target: Target, candidates: Seq[CandidateUser] ): Seq[CandidateUser] = { /** * By this stage, all valid candidates should have: * 1. Their Scores field populated. * 2. Their selectedRankerId set. * 3. Have a score associated to their selectedRankerId. * If there is any candidate that doesn't meet the conditions above, there is a problem in one * of the previous rankers. Since no new scoring is done in this ranker, we simply remove them. */ val validCandidates = candidates.filter { c => c.scores.isDefined && c.scores.exists(_.selectedRankerId.isDefined) && getCandidateScoreByRankerId(c, c.scores.flatMap(_.selectedRankerId)).isDefined } // To monitor the percentage of valid candidates, as defined above, we track the following: inputStats.counter("candidates_with_no_scores").incr(candidates.count(_.scores.isEmpty)) inputStats .counter("candidates_with_no_selected_ranker").incr(candidates.count { c => c.scores.isEmpty || c.scores.exists(_.selectedRankerId.isEmpty) }) inputStats .counter("candidates_with_no_score_for_selected_ranker").incr(candidates.count { c => c.scores.isEmpty || c.scores.exists(_.selectedRankerId.isEmpty) || getCandidateScoreByRankerId(c, c.scores.flatMap(_.selectedRankerId)).isEmpty }) inputStats.counter("total_num_candidates").incr(candidates.length) inputStats.counter("total_valid_candidates").incr(validCandidates.length) // We only count rankerIds from those candidates who are valid to exclude those candidates with // a valid selectedRankerId that don't have an associated score for it. val rankerIds = validCandidates.flatMap(_.scores.flatMap(_.selectedRankerId)).sorted.distinct rankerIds.foreach { rankerId => inputStats .counter(s"valid_scores_for_${rankerId.toString}").incr( candidates.count(getCandidateScoreByRankerId(_, Some(rankerId)).isDefined)) inputStats.counter(s"total_candidates_for_${rankerId.toString}").incr(candidates.length) } inputStats.counter(s"num_ranker_ids=${rankerIds.length}").incr() val scribeRankingInfo: Boolean = target.params(InterleaveRankerParams.ScribeRankingInfoInInterleaveRanker) if (rankerIds.length <= 1) // In the case of "Number of RankerIds = 0", we pass on the candidates even though there is // a problem in a previous ranker that provided the scores. if (scribeRankingInfo) Utils.addRankingInfo(candidates, name) else candidates else if (scribeRankingInfo) Utils.addRankingInfo(interleaveCandidates(validCandidates, rankerIds), name) else interleaveCandidates(validCandidates, rankerIds) } @VisibleForTesting private[interleave_ranker] def interleaveCandidates( candidates: Seq[CandidateUser], rankerIds: Seq[RankerId.RankerId] ): Seq[CandidateUser] = { val candidatesWithRank = rankerIds .flatMap { ranker => candidates // We first sort all candidates using this ranker. .sortBy(-getCandidateScoreByRankerId(_, Some(ranker)).getOrElse(Double.MinValue)) .zipWithIndex.filter( // but only hold those candidates whose selected ranker is this ranker. // These ranks will be forced in the final ordering. _._1.scores.flatMap(_.selectedRankerId).contains(ranker)) } // Only candidates who have isInProducerScoringExperiment set to true will have their position enforced. We // separate candidates into two groups: (1) Production and (2) Experiment. val (expCandidates, prodCandidates) = candidatesWithRank.partition(_._1.scores.exists(_.isInProducerScoringExperiment)) // We resolve (potential) conflicts between the enforced ranks of experimental models. val expCandidatesFinalPos = resolveConflicts(expCandidates) // Retrieve non-occupied positions and assign them to candidates who use production ranker. val occupiedPos = expCandidatesFinalPos.map(_._2).toSet val prodCandidatesFinalPos = prodCandidates .map(_._1).zip( candidates.indices.filterNot(occupiedPos.contains).sorted.take(prodCandidates.length)) // Merge the two groups and sort them by their corresponding positions. val finalCandidates = (prodCandidatesFinalPos ++ expCandidatesFinalPos).sortBy(_._2).map(_._1) // We count the presence of each ranker in the top-3 final positions. finalCandidates.zip(0 until 3).foreach { case (c, r) => // We only do so for candidates that are in a producer-side experiment. if (c.scores.exists(_.isInProducerScoringExperiment)) c.scores.flatMap(_.selectedRankerId).map(_.toString).foreach { rankerName => interleavingStats .counter(s"num_final_position_${r}_$rankerName") .incr() } } finalCandidates } @VisibleForTesting private[interleave_ranker] def resolveConflicts( candidatesWithRank: Seq[(CandidateUser, Int)] ): Seq[(CandidateUser, Int)] = { // The following two metrics will allow us to calculate the rate of conflicts occurring. // Example: If overall there are 10 producers in different bucketing experiments, and 3 of them // are assigned to the same position. The rate would be 3/10, 30%. val numCandidatesWithConflicts = interleavingStats.counter("candidates_with_conflict") val numCandidatesNoConflicts = interleavingStats.counter("candidates_without_conflict") val candidatesGroupedByRank = candidatesWithRank.groupBy(_._2).toSeq.sortBy(_._1).map { case (rank, candidatesWithRank) => (rank, candidatesWithRank.map(_._1)) } candidatesGroupedByRank.foldLeft(Seq[(CandidateUser, Int)]()) { (upToHere, nextGroup) => val (rank, candidates) = nextGroup if (candidates.length > 1) numCandidatesWithConflicts.incr(candidates.length) else numCandidatesNoConflicts.incr() // We use the position after the last-assigned candidate as a starting point, or 0 otherwise. // If candidates' position is after this "starting point", we enforce that position instead. val minAvailableIndex = scala.math.max(upToHere.lastOption.map(_._2).getOrElse(-1) + 1, rank) val enforcedPos = (minAvailableIndex until minAvailableIndex + candidates.length).toList val shuffledEnforcedPos = if (candidates.length > 1) scala.util.Random.shuffle(enforcedPos) else enforcedPos if (shuffledEnforcedPos.length > 1) { candidates.zip(shuffledEnforcedPos).sortBy(_._2).map(_._1).zipWithIndex.foreach { case (c, r) => c.scores.flatMap(_.selectedRankerId).map(_.toString).foreach { rankerName => // For each ranker, we count the total number of times it has been in a conflict. interleavingStats .counter(s"num_${shuffledEnforcedPos.length}-way_conflicts_$rankerName") .incr() // We also count the positions each of the rankers have fallen randomly into. In any // experiment this should converge to uniform distribution given enough occurrences. // Note that the position here is relative to the other candidates in the conflict and // not the overall position of each candidate. interleavingStats .counter( s"num_position_${r}_after_${shuffledEnforcedPos.length}-way_conflict_$rankerName") .incr() } } } upToHere ++ candidates.zip(shuffledEnforcedPos).sortBy(_._2) } } @VisibleForTesting private[interleave_ranker] def getCandidateScoreByRankerId( candidate: CandidateUser, rankerIdOpt: Option[RankerId.RankerId] ): Option[Double] = { rankerIdOpt match { case None => None case Some(rankerId) => candidate.scores.flatMap { _.scores.find(_.rankerId.contains(rankerId)).map(_.value) } } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/interleave_ranker/InterleaveRankerFSConfig.scala
package com.twitter.follow_recommendations.common.rankers.interleave_ranker import javax.inject.Inject import javax.inject.Singleton import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig import com.twitter.timelines.configapi.FSParam @Singleton class InterleaveRankerFSConfig @Inject() extends FeatureSwitchConfig { override val booleanFSParams: Seq[FSParam[Boolean]] = Seq(InterleaveRankerParams.ScribeRankingInfoInInterleaveRanker) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/interleave_ranker/InterleaveRankerParams.scala
package com.twitter.follow_recommendations.common.rankers.interleave_ranker import com.twitter.timelines.configapi.FSParam object InterleaveRankerParams { case object ScribeRankingInfoInInterleaveRanker extends FSParam[Boolean]("interleave_ranker_scribe_ranking_info", true) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/ranking/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/deepbirdv2", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/scoring", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/utils", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/utils", "src/java/com/twitter/ml/api:api-base", "util/util-slf4j-api/src/main/scala", ], ) # This is to import only the params from MlRanker, for instance to get request-level heavy ranker. scala_library( name = "ml_ranker_params", sources = [ "MlRankerParams.scala", ], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common", "timelines/src/main/scala/com/twitter/timelines/config/configapi", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/ranking/HydrateFeaturesTransform.scala
package com.twitter.follow_recommendations.common.rankers.ml_ranker.ranking import com.google.inject.Inject import com.google.inject.Singleton import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.GatedTransform import com.twitter.follow_recommendations.common.base.StatsUtil.profileStitchMapResults import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.feature_hydration.sources.UserScoringFeatureSource import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDebugOptions import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.follow_recommendations.common.models.RichDataRecord import com.twitter.ml.api.DataRecord import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import com.twitter.util.logging.Logging /** * Hydrate features given target and candidates lists. * This is a required step before MlRanker. * If a feature is not hydrated before MlRanker is triggered, a runtime exception will be thrown */ @Singleton class HydrateFeaturesTransform[ Target <: HasClientContext with HasParams with HasDebugOptions with HasPreFetchedFeature with HasSimilarToContext with HasDisplayLocation] @Inject() ( userScoringFeatureSource: UserScoringFeatureSource, stats: StatsReceiver) extends GatedTransform[Target, CandidateUser] with Logging { private val hydrateFeaturesStats = stats.scope("hydrate_features") def transform(target: Target, candidates: Seq[CandidateUser]): Stitch[Seq[CandidateUser]] = { // get features val featureMapStitch: Stitch[Map[CandidateUser, DataRecord]] = profileStitchMapResults( userScoringFeatureSource.hydrateFeatures(target, candidates), hydrateFeaturesStats) featureMapStitch.map { featureMap => candidates .map { candidate => val dataRecord = featureMap(candidate) // add debugRecord only when the request parameter is set val debugDataRecord = if (target.debugOptions.exists(_.fetchDebugInfo)) { Some(candidate.toDebugDataRecord(dataRecord, userScoringFeatureSource.featureContext)) } else None candidate.copy( dataRecord = Some(RichDataRecord(Some(dataRecord), debugDataRecord)) ) } } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/ranking/MlRanker.scala
package com.twitter.follow_recommendations.common.rankers.ml_ranker.ranking import com.google.common.annotations.VisibleForTesting import com.google.inject.Inject import com.google.inject.Singleton import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.Ranker import com.twitter.follow_recommendations.common.base.StatsUtil import com.twitter.follow_recommendations.common.base.StatsUtil.profileSeqResults import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasDebugOptions import com.twitter.follow_recommendations.common.models.Scores import com.twitter.follow_recommendations.common.rankers.common.RankerId import com.twitter.follow_recommendations.common.rankers.common.RankerId.RankerId import com.twitter.follow_recommendations.common.rankers.utils.Utils import com.twitter.follow_recommendations.common.rankers.ml_ranker.scoring.AdhocScorer import com.twitter.follow_recommendations.common.rankers.ml_ranker.scoring.Scorer import com.twitter.follow_recommendations.common.rankers.ml_ranker.scoring.ScorerFactory import com.twitter.follow_recommendations.common.utils.CollectionUtil import com.twitter.ml.api.DataRecord import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import com.twitter.timelines.configapi.Params import com.twitter.util.logging.Logging /** * This class has a rank function that will perform 4 steps: * - choose which scorer to use for each candidate * - score candidates given their respective features * - add scoring information to the candidate * - sort candidates by their respective scores * The feature source and scorer will depend on the request's params */ @Singleton class MlRanker[ Target <: HasClientContext with HasParams with HasDisplayLocation with HasDebugOptions] @Inject() ( scorerFactory: ScorerFactory, statsReceiver: StatsReceiver) extends Ranker[Target, CandidateUser] with Logging { private val stats: StatsReceiver = statsReceiver.scope("ml_ranker") private val inputStat = stats.scope("1_input") private val selectScorerStat = stats.scope("2_select_scorer") private val scoreStat = stats.scope("3_score") override def rank( target: Target, candidates: Seq[CandidateUser] ): Stitch[Seq[CandidateUser]] = { profileSeqResults(candidates, inputStat) val requestRankerId = target.params(MlRankerParams.RequestScorerIdParam) val rankerIds = chooseRankerByCandidate(candidates, requestRankerId) val scoreStitch = score(candidates, rankerIds, requestRankerId).map { scoredCandidates => { // sort the candidates by score val sortedCandidates = sort(target, scoredCandidates) // add scribe field to candidates (if applicable) and return candidates scribeCandidates(target, sortedCandidates) } } StatsUtil.profileStitch(scoreStitch, stats.scope("rank")) } /** * @param target: The WTF request for a given consumer. * @param candidates A list of candidates considered for recommendation. * @return A map from each candidate to a tuple that includes: * (1) The selected scorer that should be used to rank this candidate * (2) a flag determining whether the candidate is in a producer-side experiment. */ private[ranking] def chooseRankerByCandidate( candidates: Seq[CandidateUser], requestRankerId: RankerId ): Map[CandidateUser, RankerId] = { candidates.map { candidate => val selectedCandidateRankerId = if (candidate.params == Params.Invalid || candidate.params == Params.Empty) { selectScorerStat.counter("candidate_params_empty").incr() requestRankerId } else { val candidateRankerId = candidate.params(MlRankerParams.CandidateScorerIdParam) if (candidateRankerId == RankerId.None) { // This candidate is a not part of any producer-side experiment. selectScorerStat.counter("default_to_request_ranker").incr() requestRankerId } else { // This candidate is in a treatment bucket of a producer-side experiment. selectScorerStat.counter("use_candidate_ranker").incr() candidateRankerId } } selectScorerStat.scope("selected").counter(selectedCandidateRankerId.toString).incr() candidate -> selectedCandidateRankerId }.toMap } @VisibleForTesting private[ranking] def score( candidates: Seq[CandidateUser], rankerIds: Map[CandidateUser, RankerId], requestRankerId: RankerId ): Stitch[Seq[CandidateUser]] = { val features = candidates.map(_.dataRecord.flatMap(_.dataRecord)) require(features.forall(_.nonEmpty), "features are not hydrated for all the candidates") val scorers = scorerFactory.getScorers(rankerIds.values.toSeq.sorted.distinct) // Scorers are split into ML-based and Adhoc (defined as a scorer that does not need to call an // ML prediction service and scores candidates using locally-available data). val (adhocScorers, mlScorers) = scorers.partition { case _: AdhocScorer => true case _ => false } // score candidates val scoresStitch = score(features.map(_.get), mlScorers) val candidatesWithMlScoresStitch = scoresStitch.map { scoresSeq => candidates .zip(scoresSeq).map { // copy datarecord and score into candidate object case (candidate, scores) => val selectedRankerId = rankerIds(candidate) val useRequestRanker = candidate.params == Params.Invalid || candidate.params == Params.Empty || candidate.params(MlRankerParams.CandidateScorerIdParam) == RankerId.None candidate.copy( score = scores.scores.find(_.rankerId.contains(requestRankerId)).map(_.value), scores = if (scores.scores.nonEmpty) { Some( scores.copy( scores = scores.scores, selectedRankerId = Some(selectedRankerId), isInProducerScoringExperiment = !useRequestRanker )) } else None ) } } candidatesWithMlScoresStitch.map { candidates => // The basis for adhoc scores are the "request-level" ML ranker. We add the base score here // while adhoc scorers are applied in [[AdhocRanker]]. addMlBaseScoresForAdhocScorers(candidates, requestRankerId, adhocScorers) } } @VisibleForTesting private[ranking] def addMlBaseScoresForAdhocScorers( candidates: Seq[CandidateUser], requestRankerId: RankerId, adhocScorers: Seq[Scorer] ): Seq[CandidateUser] = { candidates.map { candidate => candidate.scores match { case Some(oldScores) => // 1. We fetch the ML score that is the basis of adhoc scores: val baseMlScoreOpt = Utils.getCandidateScoreByRankerId(candidate, requestRankerId) // 2. For each adhoc scorer, we copy the ML score object, changing only the ID and type. val newScores = adhocScorers flatMap { adhocScorer => baseMlScoreOpt.map( _.copy(rankerId = Some(adhocScorer.id), scoreType = adhocScorer.scoreType)) } // 3. We add the new adhoc score entries to the candidate. candidate.copy(scores = Some(oldScores.copy(scores = oldScores.scores ++ newScores))) case _ => // Since there is no base ML score, there should be no adhoc score modification as well. candidate } } } private[this] def score( dataRecords: Seq[DataRecord], scorers: Seq[Scorer] ): Stitch[Seq[Scores]] = { val scoredResponse = scorers.map { scorer => StatsUtil.profileStitch(scorer.score(dataRecords), scoreStat.scope(scorer.id.toString)) } // If we could score a candidate with too many rankers, it is likely to blow up the whole system. // and fail back to default production model StatsUtil.profileStitch(Stitch.collect(scoredResponse), scoreStat).map { scoresByScorerId => CollectionUtil.transposeLazy(scoresByScorerId).map { scoresPerCandidate => Scores(scoresPerCandidate) } } } // sort candidates using score in descending order private[this] def sort( target: Target, candidates: Seq[CandidateUser] ): Seq[CandidateUser] = { candidates.sortBy(c => -c.score.getOrElse(MlRanker.DefaultScore)) } private[this] def scribeCandidates( target: Target, candidates: Seq[CandidateUser] ): Seq[CandidateUser] = { val scribeRankingInfo: Boolean = target.params(MlRankerParams.ScribeRankingInfoInMlRanker) scribeRankingInfo match { case true => Utils.addRankingInfo(candidates, "MlRanker") case false => candidates } } } object MlRanker { // this is to ensure candidates with absent scores are ranked the last val DefaultScore: Double = Double.MinValue }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/ranking/MlRankerFSConfig.scala
package com.twitter.follow_recommendations.common.rankers.ml_ranker.ranking import javax.inject.Inject import javax.inject.Singleton import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig import com.twitter.timelines.configapi.FSParam @Singleton class MlRankerFSConfig @Inject() extends FeatureSwitchConfig { override val booleanFSParams: Seq[FSParam[Boolean]] = Seq(MlRankerParams.ScribeRankingInfoInMlRanker) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/ranking/MlRankerParams.scala
package com.twitter.follow_recommendations.common.rankers.ml_ranker.ranking import com.twitter.follow_recommendations.common.rankers.common.RankerId import com.twitter.timelines.configapi.FSEnumParam import com.twitter.timelines.configapi.FSParam /** * When adding Producer side experiments, make sure to register the FS Key in [[ProducerFeatureFilter]] * in [[FeatureSwitchesModule]], otherwise, the FS will not work. */ object MlRankerParams { // which ranker to use by default for the given request case object RequestScorerIdParam extends FSEnumParam[RankerId.type]( name = "post_nux_ml_flow_ml_ranker_id", default = RankerId.PostNuxProdRanker, enum = RankerId ) // which ranker to use for the given candidate case object CandidateScorerIdParam extends FSEnumParam[RankerId.type]( name = "post_nux_ml_flow_candidate_user_scorer_id", default = RankerId.None, enum = RankerId ) case object ScribeRankingInfoInMlRanker extends FSParam[Boolean]("post_nux_ml_flow_scribe_ranking_info_in_ml_ranker", true) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/scoring/AdhocScorer.scala
package com.twitter.follow_recommendations.common.rankers.ml_ranker.scoring import com.twitter.follow_recommendations.common.rankers.common.AdhocScoreModificationType.AdhocScoreModificationType import com.twitter.follow_recommendations.common.models.Score import com.twitter.ml.api.DataRecord import com.twitter.stitch.Stitch trait AdhocScorer extends Scorer { /** * NOTE: For instances of [[AdhocScorer]] this function SHOULD NOT be used. * Please use: * [[score(target: HasClientContext with HasParams, candidates: Seq[CandidateUser])]] * instead. */ @Deprecated override def score(records: Seq[DataRecord]): Stitch[Seq[Score]] = throw new UnsupportedOperationException( "For instances of AdhocScorer this operation is not defined. Please use " + "`def score(target: HasClientContext with HasParams, candidates: Seq[CandidateUser])` " + "instead.") /** * This helps us manage the extend of adhoc modification on candidates' score. There is a hard * limit of applying ONLY ONE scorer of each type to a score. */ val scoreModificationType: AdhocScoreModificationType }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/scoring/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/deepbirdv2", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/ranking:ml_ranker_params", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/utils", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/common", "src/java/com/twitter/ml/api:api-base", "src/scala/com/twitter/pluck/source/core_workflows/user_model:condensed_user_state-scala", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/scoring/DeepbirdScorer.scala
package com.twitter.follow_recommendations.common.rankers.ml_ranker.scoring import com.twitter.cortex.deepbird.thriftjava.DeepbirdPredictionService import com.twitter.cortex.deepbird.thriftjava.ModelSelector import com.twitter.finagle.stats.Stat import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDebugOptions import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.Score import com.twitter.ml.api.DataRecord import com.twitter.ml.api.Feature import com.twitter.ml.api.RichDataRecord import com.twitter.ml.prediction_service.{BatchPredictionRequest => JBatchPredictionRequest} import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import com.twitter.util.Future import com.twitter.util.TimeoutException import scala.collection.JavaConversions._ import scala.collection.JavaConverters._ /** * Generic trait that implements the scoring given a deepbirdClient * To test out a new model, create a scorer extending this trait, override the modelName and inject the scorer */ trait DeepbirdScorer extends Scorer { def modelName: String def predictionFeature: Feature.Continuous // Set a default batchSize of 100 when making model prediction calls to the Deepbird V2 prediction server def batchSize: Int = 100 def deepbirdClient: DeepbirdPredictionService.ServiceToClient def baseStats: StatsReceiver def modelSelector: ModelSelector = new ModelSelector().setId(modelName) def stats: StatsReceiver = baseStats.scope(this.getClass.getSimpleName).scope(modelName) private def requestCount = stats.counter("requests") private def emptyRequestCount = stats.counter("empty_requests") private def successCount = stats.counter("success") private def failureCount = stats.counter("failures") private def inputRecordsStat = stats.stat("input_records") private def outputRecordsStat = stats.stat("output_records") // Counters for tracking batch-prediction statistics when making DBv2 prediction calls // // numBatchRequests tracks the number of batch prediction requests made to DBv2 prediction servers private def numBatchRequests = stats.counter("batches") // numEmptyBatchRequests tracks the number of batch prediction requests made to DBv2 prediction servers // that had an empty input DataRecord private def numEmptyBatchRequests = stats.counter("empty_batches") // numTimedOutBatchRequests tracks the number of batch prediction requests made to DBv2 prediction servers // that had timed-out private def numTimedOutBatchRequests = stats.counter("timeout_batches") private def batchPredictionLatency = stats.stat("batch_prediction_latency") private def predictionLatency = stats.stat("prediction_latency") private def numEmptyModelPredictions = stats.counter("empty_model_predictions") private def numNonEmptyModelPredictions = stats.counter("non_empty_model_predictions") private val DefaultPredictionScore = 0.0 /** * NOTE: For instances of [[DeepbirdScorer]] this function SHOULD NOT be used. * Please use [[score(records: Seq[DataRecord])]] instead. */ @Deprecated def score( target: HasClientContext with HasParams with HasDisplayLocation with HasDebugOptions, candidates: Seq[CandidateUser] ): Seq[Option[Score]] = throw new UnsupportedOperationException( "For instances of DeepbirdScorer this operation is not defined. Please use " + "`def score(records: Seq[DataRecord]): Stitch[Seq[Score]]` " + "instead.") override def score(records: Seq[DataRecord]): Stitch[Seq[Score]] = { requestCount.incr() if (records.isEmpty) { emptyRequestCount.incr() Stitch.Nil } else { inputRecordsStat.add(records.size) Stitch.callFuture( batchPredict(records, batchSize) .map { recordList => val scores = recordList.map { record => Score( value = record.getOrElse(DefaultPredictionScore), rankerId = Some(id), scoreType = scoreType) } outputRecordsStat.add(scores.size) scores }.onSuccess(_ => successCount.incr()) .onFailure(_ => failureCount.incr())) } } def batchPredict( dataRecords: Seq[DataRecord], batchSize: Int ): Future[Seq[Option[Double]]] = { Stat .timeFuture(predictionLatency) { val batchedDataRecords = dataRecords.grouped(batchSize).toSeq numBatchRequests.incr(batchedDataRecords.size) Future .collect(batchedDataRecords.map(batch => predict(batch))) .map(res => res.reduce(_ ++ _)) } } def predict(dataRecords: Seq[DataRecord]): Future[Seq[Option[Double]]] = { Stat .timeFuture(batchPredictionLatency) { if (dataRecords.isEmpty) { numEmptyBatchRequests.incr() Future.Nil } else { deepbirdClient .batchPredictFromModel(new JBatchPredictionRequest(dataRecords.asJava), modelSelector) .map { response => response.predictions.toSeq.map { prediction => val predictionFeatureOption = Option( new RichDataRecord(prediction).getFeatureValue(predictionFeature) ) predictionFeatureOption match { case Some(predictionValue) => numNonEmptyModelPredictions.incr() Option(predictionValue.toDouble) case None => numEmptyModelPredictions.incr() Option(DefaultPredictionScore) } } } .rescue { case e: TimeoutException => // DBv2 prediction calls that timed out numTimedOutBatchRequests.incr() stats.counter(e.getClass.getSimpleName).incr() Future.value(dataRecords.map(_ => Option(DefaultPredictionScore))) case e: Exception => // other generic DBv2 prediction call failures stats.counter(e.getClass.getSimpleName).incr() Future.value(dataRecords.map(_ => Option(DefaultPredictionScore))) } } } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/scoring/PostnuxDeepbirdProdScorer.scala
package com.twitter.follow_recommendations.common.rankers.ml_ranker.scoring import com.twitter.cortex.deepbird.thriftjava.DeepbirdPredictionService import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.constants.GuiceNamedConstants import com.twitter.follow_recommendations.common.rankers.common.RankerId import com.twitter.ml.api.Feature import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton // This is a standard DeepbirdV2 ML Ranker scoring config that should be extended by all ML scorers // // Only modify this trait when adding new fields to DeepbirdV2 scorers which trait DeepbirdProdScorer extends DeepbirdScorer { override val batchSize = 20 } // Feature.Continuous("prediction") is specific to ClemNet architecture, we can change it to be more informative in the next iteration trait PostNuxV1DeepbirdProdScorer extends DeepbirdProdScorer { override val predictionFeature: Feature.Continuous = new Feature.Continuous("prediction") } // The current, primary PostNUX DeepbirdV2 scorer used in production @Singleton class PostnuxDeepbirdProdScorer @Inject() ( @Named(GuiceNamedConstants.WTF_PROD_DEEPBIRDV2_CLIENT) override val deepbirdClient: DeepbirdPredictionService.ServiceToClient, override val baseStats: StatsReceiver) extends PostNuxV1DeepbirdProdScorer { override val id = RankerId.PostNuxProdRanker override val modelName = "PostNUX14531GafClemNetWarmStart" }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/scoring/RandomScorer.scala
package com.twitter.follow_recommendations.common.rankers.ml_ranker.scoring import com.twitter.cortex.deepbird.thriftjava.DeepbirdPredictionService import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.constants.GuiceNamedConstants import com.twitter.follow_recommendations.common.rankers.common.RankerId import com.twitter.ml.api.DataRecord import com.twitter.ml.api.Feature import com.twitter.util.Future import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton /** * This scorer assigns random values between 0 and 1 to each candidate as scores. */ @Singleton class RandomScorer @Inject() ( @Named(GuiceNamedConstants.WTF_PROD_DEEPBIRDV2_CLIENT) override val deepbirdClient: DeepbirdPredictionService.ServiceToClient, override val baseStats: StatsReceiver) extends DeepbirdScorer { override val id = RankerId.RandomRanker private val rnd = new scala.util.Random(System.currentTimeMillis()) override def predict(dataRecords: Seq[DataRecord]): Future[Seq[Option[Double]]] = { if (dataRecords.isEmpty) { Future.Nil } else { // All candidates are assigned a random value between 0 and 1 as score. Future.value(dataRecords.map(_ => Option(rnd.nextDouble()))) } } override val modelName = "PostNuxRandomRanker" // This is not needed since we are overriding the `predict` function, but we have to override // `predictionFeature` anyway. override val predictionFeature: Feature.Continuous = new Feature.Continuous("prediction.pfollow_pengagement") }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/scoring/Scorer.scala
package com.twitter.follow_recommendations.common.rankers.ml_ranker.scoring import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasDebugOptions import com.twitter.follow_recommendations.common.models.Score import com.twitter.follow_recommendations.common.models.ScoreType import com.twitter.follow_recommendations.common.rankers.common.RankerId import com.twitter.ml.api.DataRecord import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams trait Scorer { // unique id of the scorer def id: RankerId.Value // type of the output scores def scoreType: Option[ScoreType] = None // Scoring when an ML model is used. def score(records: Seq[DataRecord]): Stitch[Seq[Score]] /** * Scoring when a non-ML method is applied. E.g: Boosting, randomized reordering, etc. * This method assumes that candidates' scores are already retrieved from heavy-ranker models and * are available for use. */ def score( target: HasClientContext with HasParams with HasDisplayLocation with HasDebugOptions, candidates: Seq[CandidateUser] ): Seq[Option[Score]] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/scoring/ScorerFactory.scala
package com.twitter.follow_recommendations.common.rankers.ml_ranker.scoring import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.rankers.common.RankerId import com.twitter.follow_recommendations.common.rankers.common.RankerId.RankerId import javax.inject.Inject import javax.inject.Singleton @Singleton class ScorerFactory @Inject() ( postnuxProdScorer: PostnuxDeepbirdProdScorer, randomScorer: RandomScorer, stats: StatsReceiver) { private val scorerFactoryStats = stats.scope("scorer_factory") private val scorerStat = scorerFactoryStats.scope("scorer") def getScorers( rankerIds: Seq[RankerId] ): Seq[Scorer] = { rankerIds.map { scorerId => val scorer: Scorer = getScorerById(scorerId) // count # of times a ranker has been requested scorerStat.counter(scorer.id.toString).incr() scorer } } def getScorerById(scorerId: RankerId): Scorer = scorerId match { case RankerId.PostNuxProdRanker => postnuxProdScorer case RankerId.RandomRanker => randomScorer case _ => scorerStat.counter("invalid_scorer_type").incr() throw new IllegalArgumentException("unknown_scorer_type") } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/utils/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/utils/Utils.scala
package com.twitter.follow_recommendations.common.rankers.utils import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.Score import com.twitter.follow_recommendations.common.rankers.common.RankerId.RankerId object Utils { /** * Add the ranking and scoring info for a list of candidates on a given ranking stage. * @param candidates A list of CandidateUser * @param rankingStage Should use `Ranker.name` as the ranking stage. * @return The list of CandidateUser with ranking/scoring info added. */ def addRankingInfo(candidates: Seq[CandidateUser], rankingStage: String): Seq[CandidateUser] = { candidates.zipWithIndex.map { case (candidate, rank) => // 1-based ranking for better readability candidate.addInfoPerRankingStage(rankingStage, candidate.scores, rank + 1) } } def getCandidateScoreByRankerId(candidate: CandidateUser, rankerId: RankerId): Option[Score] = candidate.scores.flatMap { ss => ss.scores.find(_.rankerId.contains(rankerId)) } def getAllRankerIds(candidates: Seq[CandidateUser]): Seq[RankerId] = candidates.flatMap(_.scores.map(_.scores.flatMap(_.rankerId))).flatten.distinct }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/weighted_candidate_source_ranker/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/utils", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/utils", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/common", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/weighted_candidate_source_ranker/CandidateShuffle.scala
package com.twitter.follow_recommendations.common.rankers.weighted_candidate_source_ranker import com.twitter.follow_recommendations.common.utils.RandomUtil import scala.util.Random sealed trait CandidateShuffler[T] { def shuffle(seed: Option[Long])(input: Seq[T]): Seq[T] } class NoShuffle[T]() extends CandidateShuffler[T] { def shuffle(seed: Option[Long])(input: Seq[T]): Seq[T] = input } class RandomShuffler[T]() extends CandidateShuffler[T] { def shuffle(seed: Option[Long])(input: Seq[T]): Seq[T] = { seed.map(new Random(_)).getOrElse(Random).shuffle(input) } } trait RankWeightedRandomShuffler[T] extends CandidateShuffler[T] { def rankToWeight(rank: Int): Double def shuffle(seed: Option[Long])(input: Seq[T]): Seq[T] = { val candWeights = input.zipWithIndex.map { case (candidate, rank) => (candidate, rankToWeight(rank)) } RandomUtil.weightedRandomShuffle(candWeights, seed.map(new Random(_))).unzip._1 } } class ExponentialShuffler[T]() extends RankWeightedRandomShuffler[T] { def rankToWeight(rank: Int): Double = { 1 / math .pow(rank.toDouble, 2.0) // this function was proved to be effective in previous DDGs } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/weighted_candidate_source_ranker/WeightMethod.scala
package com.twitter.follow_recommendations.common.rankers.weighted_candidate_source_ranker object WeightMethod extends Enumeration { type WeightMethod = Value val WeightedRandomSampling, WeightedRoundRobin = Value }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/weighted_candidate_source_ranker/WeightedCandidateSourceBaseRanker.scala
package com.twitter.follow_recommendations.common.rankers.weighted_candidate_source_ranker import com.twitter.follow_recommendations.common.utils.RandomUtil import com.twitter.follow_recommendations.common.utils.MergeUtil import com.twitter.follow_recommendations.common.utils.Weighted import com.twitter.follow_recommendations.common.rankers.weighted_candidate_source_ranker.WeightMethod._ import scala.util.Random /** * This ranker selects the next candidate source to select a candidate from. It supports * two kinds of algorithm, WeightedRandomSampling or WeightedRoundRobin. WeightedRandomSampling * pick the next candidate source randomly, WeightedRoundRobin picked the next candidate source * sequentially based on the weight of the candidate source. It is default to WeightedRandomSampling * if no weight method is provided. * * Example usage of this class: * * When use WeightedRandomSampling: * Input candidate sources and their weights are: {{CS1: 3}, {CS2: 2}, {CS3: 5}} * Ranked candidates sequence is not determined because of random sampling. * One possible output candidate sequence is: (CS1_candidate1, CS2_candidate1, CS2_candidate2, * CS3_candidate1, CS3_candidates2, CS3_candidate3, CS1_candidate2, CS1_candidate3, * CS3_candidate4, CS3_candidate5, CS1_candidate4, CS1_candidate5, CS2_candidate6, CS2_candidate3,...) * * When use WeightedRoundRobin: * Input candidate sources and their weights are: {{CS1: 3}, {CS2: 2}, {CS3: 5}} * Output candidate sequence is: (CS1_candidate1, CS1_candidate2, CS1_candidate3, * CS2_candidate1, CS2_candidates2, CS3_candidate1, CS3_candidate2, CS3_candidate3, * CS3_candidate4, CS3_candidate5, CS1_candidate4, CS1_candidate5, CS1_candidate6, CS2_candidate3,...) * * Note: CS1_candidate1 means the first candidate in CS1 candidate source. * * @tparam A candidate source type * @tparam Rec Recommendation type * @param candidateSourceWeights relative weights for different candidate sources */ class WeightedCandidateSourceBaseRanker[A, Rec]( candidateSourceWeights: Map[A, Double], weightMethod: WeightMethod = WeightedRandomSampling, randomSeed: Option[Long]) { /** * Creates a iterator over algorithms and calls next to return a Stream of candidates * * * @param candidateSources the set of candidate sources that are being sampled * @param candidateSourceWeights map of candidate source to weight * @param candidates the map of candidate source to the iterator of its results * @param weightMethod a enum to indict which weight method to use. Two values are supported * currently. When WeightedRandomSampling is set, the next candidate is picked from a candidate * source that is randomly chosen. When WeightedRoundRobin is set, the next candidate is picked * from current candidate source until the number of candidates reaches to the assigned weight of * the candidate source. The next call of this function will return a candidate from the next * candidate source which is after previous candidate source based on the order input * candidate source sequence. * @return stream of candidates */ def stream( candidateSources: Set[A], candidateSourceWeights: Map[A, Double], candidates: Map[A, Iterator[Rec]], weightMethod: WeightMethod = WeightedRandomSampling, random: Option[Random] = None ): Stream[Rec] = { val weightedCandidateSource: Weighted[A] = new Weighted[A] { override def apply(a: A): Double = candidateSourceWeights.getOrElse(a, 0) } /** * Generates a stream of candidates. * * @param candidateSourceIter an iterator over candidate sources returned by the sampling procedure * @return stream of candidates */ def next(candidateSourceIter: Iterator[A]): Stream[Rec] = { val source = candidateSourceIter.next() val it = candidates(source) if (it.hasNext) { val currCand = it.next() currCand #:: next(candidateSourceIter) } else { assert(candidateSources.contains(source), "Selected source is not in candidate sources") // Remove the depleted candidate source and re-sample stream(candidateSources - source, candidateSourceWeights, candidates, weightMethod, random) } } if (candidateSources.isEmpty) Stream.empty else { val candidateSourceSeq = candidateSources.toSeq val candidateSourceIter = if (weightMethod == WeightMethod.WeightedRoundRobin) { MergeUtil.weightedRoundRobin(candidateSourceSeq)(weightedCandidateSource).iterator } else { //default to weighted random sampling if no other weight method is provided RandomUtil .weightedRandomSamplingWithReplacement( candidateSourceSeq, random )(weightedCandidateSource).iterator } next(candidateSourceIter) } } def apply(input: Map[A, TraversableOnce[Rec]]): Stream[Rec] = { stream( input.keySet, candidateSourceWeights, input.map { case (k, v) => k -> v.toIterator }, // cannot do mapValues here, as that only returns a view weightMethod, randomSeed.map(new Random(_)) ) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/weighted_candidate_source_ranker/WeightedCandidateSourceRanker.scala
package com.twitter.follow_recommendations.common.rankers.weighted_candidate_source_ranker import com.twitter.follow_recommendations.common.base.Ranker import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.rankers.common.DedupCandidates import com.twitter.follow_recommendations.common.rankers.utils.Utils import com.twitter.product_mixer.core.model.common.identifier.CandidateSourceIdentifier import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams /** * Candidate Ranker that mixes and ranks multiple candidate lists from different candidate sources with the * following steps: * 1) generate a ranked candidate list of each candidate source by sorting and shuffling the candidate list * of the algorithm. * 2) merge the ranked lists generated in 1) into a single list using weighted randomly sampling. * 3) If dedup is required, dedup the output from 2) by candidate id. * * @param basedRanker base ranker * @param shuffleFn the shuffle function that will be used to shuffle each algorithm's sorted candidate list. * @param dedup whether to remove duplicated candidates from the final output. */ class WeightedCandidateSourceRanker[Target <: HasParams]( basedRanker: WeightedCandidateSourceBaseRanker[ CandidateSourceIdentifier, CandidateUser ], shuffleFn: Seq[CandidateUser] => Seq[CandidateUser], dedup: Boolean) extends Ranker[Target, CandidateUser] { val name: String = this.getClass.getSimpleName override def rank(target: Target, candidates: Seq[CandidateUser]): Stitch[Seq[CandidateUser]] = { val scribeRankingInfo: Boolean = target.params(WeightedCandidateSourceRankerParams.ScribeRankingInfoInWeightedRanker) val rankedCands = rankCandidates(group(candidates)) Stitch.value(if (scribeRankingInfo) Utils.addRankingInfo(rankedCands, name) else rankedCands) } private def group( candidates: Seq[CandidateUser] ): Map[CandidateSourceIdentifier, Seq[CandidateUser]] = { val flattened = for { candidate <- candidates identifier <- candidate.getPrimaryCandidateSource } yield (identifier, candidate) flattened.groupBy(_._1).mapValues(_.map(_._2)) } private def rankCandidates( input: Map[CandidateSourceIdentifier, Seq[CandidateUser]] ): Seq[CandidateUser] = { // Sort and shuffle candidates per candidate source. // Note 1: Using map instead mapValue here since mapValue somehow caused infinite loop when used as part of Stream. val sortAndShuffledCandidates = input.map { case (source, candidates) => // Note 2: toList is required here since candidates is a view, and it will result in infinit loop when used as part of Stream. // Note 3: there is no real sorting logic here, it assumes the input is already sorted by candidate sources val sortedCandidates = candidates.toList source -> shuffleFn(sortedCandidates).iterator } val rankedCandidates = basedRanker(sortAndShuffledCandidates) if (dedup) DedupCandidates(rankedCandidates) else rankedCandidates } } object WeightedCandidateSourceRanker { def build[Target <: HasParams]( candidateSourceWeight: Map[CandidateSourceIdentifier, Double], shuffleFn: Seq[CandidateUser] => Seq[CandidateUser] = identity, dedup: Boolean = false, randomSeed: Option[Long] = None ): WeightedCandidateSourceRanker[Target] = { new WeightedCandidateSourceRanker( new WeightedCandidateSourceBaseRanker( candidateSourceWeight, WeightMethod.WeightedRandomSampling, randomSeed = randomSeed), shuffleFn, dedup ) } } object WeightedCandidateSourceRankerWithoutRandomSampling { def build[Target <: HasParams]( candidateSourceWeight: Map[CandidateSourceIdentifier, Double] ): WeightedCandidateSourceRanker[Target] = { new WeightedCandidateSourceRanker( new WeightedCandidateSourceBaseRanker( candidateSourceWeight, WeightMethod.WeightedRoundRobin, randomSeed = None), identity, false, ) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/weighted_candidate_source_ranker/WeightedCandidateSourceRankerFSConfig.scala
package com.twitter.follow_recommendations.common.rankers.weighted_candidate_source_ranker import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig import com.twitter.timelines.configapi.FSParam import javax.inject.Inject import javax.inject.Singleton @Singleton class WeightedCandidateSourceRankerFSConfig @Inject() extends FeatureSwitchConfig { override val booleanFSParams: Seq[FSParam[Boolean]] = Seq(WeightedCandidateSourceRankerParams.ScribeRankingInfoInWeightedRanker) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/weighted_candidate_source_ranker/WeightedCandidateSourceRankerParams.scala
package com.twitter.follow_recommendations.common.rankers.weighted_candidate_source_ranker import com.twitter.timelines.configapi.FSParam object WeightedCandidateSourceRankerParams { case object ScribeRankingInfoInWeightedRanker extends FSParam[Boolean]("weighted_ranker_scribe_ranking_info", false) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/stores/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/socialgraph", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/strato", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "strato/config/columns/onboarding/userrecs:userrecs-strato-client", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/stores/LowTweepCredFollowStore.scala
package com.twitter.follow_recommendations.common.stores import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasRecentFollowedUserIds import com.twitter.stitch.Stitch import com.twitter.strato.generated.client.onboarding.userrecs.TweepCredOnUserClientColumn import javax.inject.Inject import javax.inject.Singleton // Not a candidate source since it's a intermediary. @Singleton class LowTweepCredFollowStore @Inject() (tweepCredOnUserClientColumn: TweepCredOnUserClientColumn) { def getLowTweepCredUsers(target: HasRecentFollowedUserIds): Stitch[Seq[CandidateUser]] = { val newFollowings = target.recentFollowedUserIds.getOrElse(Nil).take(LowTweepCredFollowStore.NumFlockToRetrieve) val validTweepScoreUserIdsStitch: Stitch[Seq[Long]] = Stitch .traverse(newFollowings) { newFollowingUserId => val tweepCredScoreOptStitch = tweepCredOnUserClientColumn.fetcher .fetch(newFollowingUserId) .map(_.v) tweepCredScoreOptStitch.map(_.flatMap(tweepCred => if (tweepCred < LowTweepCredFollowStore.TweepCredThreshold) { Some(newFollowingUserId) } else { None })) }.map(_.flatten) validTweepScoreUserIdsStitch .map(_.map(CandidateUser(_, Some(CandidateUser.DefaultCandidateScore)))) } } object LowTweepCredFollowStore { val NumFlockToRetrieve = 500 val TweepCredThreshold = 40 }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/transforms/dedup/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/transforms/dedup/DedupTransform.scala
package com.twitter.follow_recommendations.common.transforms.dedup import com.twitter.follow_recommendations.common.base.Transform import com.twitter.product_mixer.core.model.common.UniversalNoun import com.twitter.stitch.Stitch import scala.collection.mutable class DedupTransform[Request, Candidate <: UniversalNoun[Long]]() extends Transform[Request, Candidate] { override def transform(target: Request, candidates: Seq[Candidate]): Stitch[Seq[Candidate]] = { val seen = mutable.HashSet[Long]() Stitch.value(candidates.filter(candidate => seen.add(candidate.id))) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/transforms/modify_social_proof/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "configapi/configapi-core", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/graph_feature_service", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/socialgraph", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/utils", "follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/deciders", "snowflake/src/main/scala/com/twitter/snowflake/id", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/transforms/modify_social_proof/ModifySocialProofTransform.scala
package com.twitter.follow_recommendations.common.transforms.modify_social_proof import com.twitter.conversions.DurationOps._ import com.twitter.decider.Decider import com.twitter.decider.RandomRecipient import com.twitter.finagle.stats.StatsReceiver import com.twitter.finagle.util.DefaultTimer import com.twitter.follow_recommendations.common.base.GatedTransform import com.twitter.follow_recommendations.common.clients.graph_feature_service.GraphFeatureServiceClient import com.twitter.follow_recommendations.common.clients.socialgraph.SocialGraphClient import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.FollowProof import com.twitter.follow_recommendations.configapi.deciders.DeciderKey import com.twitter.graph_feature_service.thriftscala.EdgeType import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.snowflake.id.SnowflakeId import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import com.twitter.util.logging.Logging import com.twitter.util.Duration import com.twitter.util.Time import javax.inject.Inject import javax.inject.Singleton object ModifySocialProof { val GfsLagDuration: Duration = 14.days val GfsIntersectionIds: Int = 3 val SgsIntersectionIds: Int = 10 val LeftEdgeTypes: Set[EdgeType] = Set(EdgeType.Following) val RightEdgeTypes: Set[EdgeType] = Set(EdgeType.FollowedBy) /** * Given the intersection ID's for a particular candidate, update the candidate's social proof * @param candidate candidate object * @param followProof follow proof to be added (includes id's and count) * @param stats stats for tracking * @return updated candidate object */ def addIntersectionIdsToCandidate( candidate: CandidateUser, followProof: FollowProof, stats: StatsReceiver ): CandidateUser = { // create updated set of social proof val updatedFollowedByOpt = candidate.followedBy match { case Some(existingFollowedBy) => Some((followProof.followedBy ++ existingFollowedBy).distinct) case None if followProof.followedBy.nonEmpty => Some(followProof.followedBy.distinct) case _ => None } val updatedFollowProof = updatedFollowedByOpt.map { updatedFollowedBy => val updatedCount = followProof.numIds.max(updatedFollowedBy.size) // track stats val numSocialProofAdded = updatedFollowedBy.size - candidate.followedBy.size addCandidatesWithSocialContextCountStat(stats, numSocialProofAdded) FollowProof(updatedFollowedBy, updatedCount) } candidate.setFollowProof(updatedFollowProof) } private def addCandidatesWithSocialContextCountStat( statsReceiver: StatsReceiver, count: Int ): Unit = { if (count > 3) { statsReceiver.counter("4_and_more").incr() } else { statsReceiver.counter(count.toString).incr() } } } /** * This class makes a request to gfs/sgs for hydrating additional social proof on each of the * provided candidates. */ @Singleton class ModifySocialProof @Inject() ( gfsClient: GraphFeatureServiceClient, socialGraphClient: SocialGraphClient, statsReceiver: StatsReceiver, decider: Decider = Decider.True) extends Logging { import ModifySocialProof._ private val stats = statsReceiver.scope(this.getClass.getSimpleName) private val addedStats = stats.scope("num_social_proof_added_per_candidate") private val gfsStats = stats.scope("graph_feature_service") private val sgsStats = stats.scope("social_graph_service") private val previousProofEmptyCounter = stats.counter("previous_proof_empty") private val emptyFollowProofCounter = stats.counter("empty_followed_proof") /** * For each candidate provided, we get the intersectionIds between the user and the candidate, * appending the unique results to the social proof (followedBy field) if not already previously * seen we query GFS for all users, except for cases specified via the mustCallSgs field or for * very new users, who would not have any data in GFS, due to the lag duration of the service's * processing. this is determined by GfsLagDuration * @param userId id of the target user whom we provide recommendations for * @param candidates list of candidates * @param intersectionIdsNum if provided, determines the maximum number of accounts we want to be hydrated for social proof * @param mustCallSgs Determines if we should query SGS regardless of user age or not. * @return list of candidates updated with additional social proof */ def hydrateSocialProof( userId: Long, candidates: Seq[CandidateUser], intersectionIdsNum: Option[Int] = None, mustCallSgs: Boolean = false, callSgsCachedColumn: Boolean = false, gfsLagDuration: Duration = GfsLagDuration, gfsIntersectionIds: Int = GfsIntersectionIds, sgsIntersectionIds: Int = SgsIntersectionIds, ): Stitch[Seq[CandidateUser]] = { addCandidatesWithSocialContextCountStat( stats.scope("social_context_count_before_hydration"), candidates.count(_.followedBy.isDefined) ) val candidateIds = candidates.map(_.id) val userAgeOpt = SnowflakeId.timeFromIdOpt(userId).map(Time.now - _) // this decider gate is used to determine what % of requests is allowed to call // Graph Feature Service. this is useful for ramping down requests to Graph Feature Service // when necessary val deciderKey: String = DeciderKey.EnableGraphFeatureServiceRequests.toString val enableGfsRequests: Boolean = decider.isAvailable(deciderKey, Some(RandomRecipient)) // if new query sgs val (candidateToIntersectionIdsMapFut, isGfs) = if (!enableGfsRequests || mustCallSgs || userAgeOpt.exists(_ < gfsLagDuration)) { ( if (callSgsCachedColumn) socialGraphClient.getIntersectionsFromCachedColumn( userId, candidateIds, intersectionIdsNum.getOrElse(sgsIntersectionIds) ) else socialGraphClient.getIntersections( userId, candidateIds, intersectionIdsNum.getOrElse(sgsIntersectionIds)), false) } else { ( gfsClient.getIntersections( userId, candidateIds, intersectionIdsNum.getOrElse(gfsIntersectionIds)), true) } val finalCandidates = candidateToIntersectionIdsMapFut .map { candidateToIntersectionIdsMap => { previousProofEmptyCounter.incr(candidates.count(_.followedBy.exists(_.isEmpty))) candidates.map { candidate => addIntersectionIdsToCandidate( candidate, candidateToIntersectionIdsMap.getOrElse(candidate.id, FollowProof(Seq.empty, 0)), addedStats) } } } .within(250.milliseconds)(DefaultTimer) .rescue { case e: Exception => error(e.getMessage) if (isGfs) { gfsStats.scope("rescued").counter(e.getClass.getSimpleName).incr() } else { sgsStats.scope("rescued").counter(e.getClass.getSimpleName).incr() } Stitch.value(candidates) } finalCandidates.onSuccess { candidatesSeq => emptyFollowProofCounter.incr(candidatesSeq.count(_.followedBy.exists(_.isEmpty))) addCandidatesWithSocialContextCountStat( stats.scope("social_context_count_after_hydration"), candidatesSeq.count(_.followedBy.isDefined) ) } } } /** * This transform uses ModifySocialProof (which makes a request to gfs/sgs) for hydrating additional * social proof on each of the provided candidates. */ @Singleton class ModifySocialProofTransform @Inject() (modifySocialProof: ModifySocialProof) extends GatedTransform[HasClientContext with HasParams, CandidateUser] with Logging { override def transform( target: HasClientContext with HasParams, candidates: Seq[CandidateUser] ): Stitch[Seq[CandidateUser]] = target.getOptionalUserId .map(modifySocialProof.hydrateSocialProof(_, candidates)).getOrElse(Stitch.value(candidates)) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/transforms/modify_social_proof/RemoveAccountProofTransform.scala
package com.twitter.follow_recommendations.common.transforms.modify_social_proof import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.GatedTransform import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import javax.inject.Inject import javax.inject.Singleton @Singleton class RemoveAccountProofTransform @Inject() (statsReceiver: StatsReceiver) extends GatedTransform[HasClientContext with HasParams, CandidateUser] { private val stats = statsReceiver.scope(this.getClass.getSimpleName) private val removedProofsCounter = stats.counter("num_removed_proofs") override def transform( target: HasClientContext with HasParams, items: Seq[CandidateUser] ): Stitch[Seq[CandidateUser]] = Stitch.value(items.map { candidate => removedProofsCounter.incr() candidate.copy(reason = None) }) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/transforms/ranker_id/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/com/google/inject/extensions:guice-assistedinject", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "finatra/inject/inject-core/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/base", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/utils", "hermit/hermit-core/src/main/scala/com/twitter/hermit/constants", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/transforms/ranker_id/RandomRankerIdTransform.scala
package com.twitter.follow_recommendations.common.transforms.ranker_id import com.google.inject.Inject import com.google.inject.Singleton import com.twitter.follow_recommendations.common.base.GatedTransform import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.Score import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams /** * This class appends each candidate's rankerIds with the RandomRankerId. * This is primarily for determining if a candidate was generated via random shuffling. */ @Singleton class RandomRankerIdTransform @Inject() () extends GatedTransform[HasParams, CandidateUser] { override def transform( target: HasParams, candidates: Seq[CandidateUser] ): Stitch[Seq[CandidateUser]] = { Stitch.value(candidates.map(_.addScore(Score.RandomScore))) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/transforms/recommendation_flow_identifier/AddRecommendationFlowIdentifierTransform.scala
package com.twitter.follow_recommendations.common.transforms.recommendation_flow_identifier import com.google.inject.Inject import com.twitter.follow_recommendations.common.base.Transform import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasRecommendationFlowIdentifier import com.twitter.stitch.Stitch class AddRecommendationFlowIdentifierTransform @Inject() extends Transform[HasRecommendationFlowIdentifier, CandidateUser] { override def transform( target: HasRecommendationFlowIdentifier, items: Seq[CandidateUser] ): Stitch[Seq[CandidateUser]] = { Stitch.value(items.map { candidateUser => candidateUser.copy(recommendationFlowIdentifier = target.recommendationFlowIdentifier) }) } }