path
stringlengths
26
218
content
stringlengths
0
231k
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/email_storage_service/BUILD
scala_library( sources = ["*.scala"], compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "emailstorage/server/src/main/thrift/com/twitter/emailstorage/api:email-storage-service-scala", "finatra-internal/mtls-thriftmux/src/main/scala", "finatra/inject/inject-thrift-client", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "stitch/stitch-core", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/email_storage_service/EmailStorageServiceClient.scala
package com.twitter.follow_recommendations.common.clients.email_storage_service import com.twitter.cds.contact_consent_state.thriftscala.PurposeOfProcessing import com.twitter.emailstorage.api.thriftscala.EmailStorageService import com.twitter.emailstorage.api.thriftscala.GetUsersEmailsRequest import com.twitter.stitch.Stitch import javax.inject.Inject import javax.inject.Singleton @Singleton class EmailStorageServiceClient @Inject() ( val emailStorageService: EmailStorageService.MethodPerEndpoint) { def getVerifiedEmail( userId: Long, purposeOfProcessing: PurposeOfProcessing ): Stitch[Option[String]] = { val req = GetUsersEmailsRequest( userIds = Seq(userId), clientIdentifier = Some("follow-recommendations-service"), purposesOfProcessing = Some(Seq(purposeOfProcessing)) ) Stitch.callFuture(emailStorageService.getUsersEmails(req)) map { _.usersEmails.map(_.confirmedEmail.map(_.email)).head } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/email_storage_service/EmailStorageServiceModule.scala
package com.twitter.follow_recommendations.common.clients.email_storage_service import com.twitter.emailstorage.api.thriftscala.EmailStorageService import com.twitter.finatra.mtls.thriftmux.modules.MtlsClient import com.twitter.follow_recommendations.common.clients.common.BaseClientModule object EmailStorageServiceModule extends BaseClientModule[EmailStorageService.MethodPerEndpoint] with MtlsClient { override val label = "email-storage-service" override val dest = "/s/email-server/email-server" }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/geoduck/BUILD
scala_library( sources = ["*.scala"], compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/github/nscala_time", "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-internal/mtls-thriftmux/src/main/scala", "finatra/inject/inject-core/src/main/scala", "finatra/inject/inject-thrift-client/src/main/scala", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "src/thrift/com/twitter/geoduck:geoduck-scala", "src/thrift/com/twitter/geoduck:geoduckpartnerplaces-thrift-scala", "stitch/stitch-core", "util/util-core:scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/geoduck/LocationServiceClient.scala
package com.twitter.follow_recommendations.common.clients.geoduck import com.twitter.follow_recommendations.common.models.GeohashAndCountryCode import com.twitter.geoduck.common.thriftscala.LocationSource import com.twitter.geoduck.common.thriftscala.PlaceQuery import com.twitter.geoduck.common.thriftscala.TransactionLocation import com.twitter.geoduck.common.thriftscala.UserLocationRequest import com.twitter.geoduck.thriftscala.LocationService import com.twitter.stitch.Stitch import javax.inject.Inject import javax.inject.Singleton @Singleton class LocationServiceClient @Inject() (locationService: LocationService.MethodPerEndpoint) { def getGeohashAndCountryCode(userId: Long): Stitch[GeohashAndCountryCode] = { Stitch .callFuture { locationService .userLocation( UserLocationRequest( Seq(userId), Some(PlaceQuery(allPlaceTypes = Some(true))), simpleReverseGeocode = true)) .map(_.found.get(userId)).map { transactionLocationOpt => val geohashOpt = transactionLocationOpt.flatMap(getGeohashFromTransactionLocation) val countryCodeOpt = transactionLocationOpt.flatMap(_.simpleRgcResult.flatMap(_.countryCodeAlpha2)) GeohashAndCountryCode(geohashOpt, countryCodeOpt) } } } private[this] def getGeohashFromTransactionLocation( transactionLocation: TransactionLocation ): Option[String] = { transactionLocation.geohash.flatMap { geohash => val geohashPrefixLength = transactionLocation.locationSource match { // if location source is logical, keep the first 4 chars in geohash case Some(LocationSource.Logical) => Some(4) // if location source is physical, keep the prefix according to accuracy // accuracy is the accuracy of GPS readings in the unit of meter case Some(LocationSource.Physical) => transactionLocation.coordinate.flatMap { coordinate => coordinate.accuracy match { case Some(accuracy) if (accuracy < 50) => Some(7) case Some(accuracy) if (accuracy < 200) => Some(6) case Some(accuracy) if (accuracy < 1000) => Some(5) case Some(accuracy) if (accuracy < 50000) => Some(4) case Some(accuracy) if (accuracy < 100000) => Some(3) case _ => None } } case Some(LocationSource.Model) => Some(4) case _ => None } geohashPrefixLength match { case Some(l: Int) => geohash.stringGeohash.map(_.take(l)) case _ => None } } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/geoduck/LocationServiceModule.scala
package com.twitter.follow_recommendations.common.clients.geoduck import com.twitter.finatra.mtls.thriftmux.modules.MtlsClient import com.twitter.follow_recommendations.common.clients.common.BaseClientModule import com.twitter.geoduck.thriftscala.LocationService object LocationServiceModule extends BaseClientModule[LocationService.MethodPerEndpoint] with MtlsClient { override val label = "geoduck_locationservice" override val dest = "/s/geo/geoduck_locationservice" }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/geoduck/ReverseGeocodeClient.scala
package com.twitter.follow_recommendations.common.clients.geoduck import com.twitter.follow_recommendations.common.models.GeohashAndCountryCode import com.twitter.geoduck.common.thriftscala.Location import com.twitter.geoduck.common.thriftscala.PlaceQuery import com.twitter.geoduck.common.thriftscala.ReverseGeocodeIPRequest import com.twitter.geoduck.service.thriftscala.GeoContext import com.twitter.geoduck.thriftscala.ReverseGeocoder import com.twitter.stitch.Stitch import javax.inject.Inject import javax.inject.Singleton @Singleton class ReverseGeocodeClient @Inject() (rgcService: ReverseGeocoder.MethodPerEndpoint) { def getGeohashAndCountryCode(ipAddress: String): Stitch[GeohashAndCountryCode] = { Stitch .callFuture { rgcService .reverseGeocodeIp( ReverseGeocodeIPRequest( Seq(ipAddress), PlaceQuery(None), simpleReverseGeocode = true ) // note: simpleReverseGeocode means that country code will be included in response ).map { response => response.found.get(ipAddress) match { case Some(location) => getGeohashAndCountryCodeFromLocation(location) case _ => GeohashAndCountryCode(None, None) } } } } private def getGeohashAndCountryCodeFromLocation(location: Location): GeohashAndCountryCode = { val countryCode: Option[String] = location.simpleRgcResult.flatMap { _.countryCodeAlpha2 } val geohashString: Option[String] = location.geohash.flatMap { hash => hash.stringGeohash.flatMap { hashString => Some(ReverseGeocodeClient.truncate(hashString)) } } GeohashAndCountryCode(geohashString, countryCode) } } object ReverseGeocodeClient { val DefaultGeoduckIPRequestContext: GeoContext = GeoContext(allPlaceTypes = true, includeGeohash = true, includeCountryCode = true) // All these geohashes are guessed by IP (Logical Location Source). // So take the four letters to make sure it is consistent with LocationServiceClient val GeohashLengthAfterTruncation = 4 def truncate(geohash: String): String = geohash.take(GeohashLengthAfterTruncation) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/geoduck/UserLocationFetcher.scala
package com.twitter.follow_recommendations.common.clients.geoduck import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.models.GeohashAndCountryCode import com.twitter.stitch.Stitch import javax.inject.Inject import javax.inject.Singleton @Singleton class UserLocationFetcher @Inject() ( locationServiceClient: LocationServiceClient, reverseGeocodeClient: ReverseGeocodeClient, statsReceiver: StatsReceiver) { private val stats: StatsReceiver = statsReceiver.scope("user_location_fetcher") private val totalRequestsCounter = stats.counter("requests") private val emptyResponsesCounter = stats.counter("empty") private val locationServiceExceptionCounter = stats.counter("location_service_exception") private val reverseGeocodeExceptionCounter = stats.counter("reverse_geocode_exception") def getGeohashAndCountryCode( userId: Option[Long], ipAddress: Option[String] ): Stitch[Option[GeohashAndCountryCode]] = { totalRequestsCounter.incr() val lscLocationStitch = Stitch .collect { userId.map(locationServiceClient.getGeohashAndCountryCode) }.rescue { case _: Exception => locationServiceExceptionCounter.incr() Stitch.None } val ipLocationStitch = Stitch .collect { ipAddress.map(reverseGeocodeClient.getGeohashAndCountryCode) }.rescue { case _: Exception => reverseGeocodeExceptionCounter.incr() Stitch.None } Stitch.join(lscLocationStitch, ipLocationStitch).map { case (lscLocation, ipLocation) => { val geohash = lscLocation.flatMap(_.geohash).orElse(ipLocation.flatMap(_.geohash)) val countryCode = lscLocation.flatMap(_.countryCode).orElse(ipLocation.flatMap(_.countryCode)) (geohash, countryCode) match { case (None, None) => emptyResponsesCounter.incr() None case _ => Some(GeohashAndCountryCode(geohash, countryCode)) } } } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/gizmoduck/BUILD
scala_library( sources = ["*.scala"], compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/github/nscala_time", "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-internal/mtls-thriftmux/src/main/scala", "finatra/inject/inject-core/src/main/scala", "finatra/inject/inject-thrift-client/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/common", "src/thrift/com/twitter/gizmoduck:thrift-scala", "stitch/stitch-gizmoduck", "util/util-core:scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/gizmoduck/GizmoduckClient.scala
package com.twitter.follow_recommendations.common.clients.gizmoduck import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.StatsUtil import com.twitter.gizmoduck.thriftscala.LookupContext import com.twitter.gizmoduck.thriftscala.PerspectiveEdge import com.twitter.gizmoduck.thriftscala.QueryFields import com.twitter.stitch.Stitch import com.twitter.stitch.gizmoduck.Gizmoduck import javax.inject.Inject import javax.inject.Singleton @Singleton class GizmoduckClient @Inject() (gizmoduckStitchClient: Gizmoduck, statsReceiver: StatsReceiver) { val stats = statsReceiver.scope("gizmoduck_client") val getByIdStats = stats.scope("get_by_id") val getUserById = stats.scope("get_user_by_id") def isProtected(userId: Long): Stitch[Boolean] = { // get latency metrics with StatsUtil.profileStitch when calling .getById val response = StatsUtil.profileStitch( gizmoduckStitchClient.getById(userId, Set(QueryFields.Safety)), getByIdStats ) response.map { result => result.user.flatMap(_.safety).map(_.isProtected).getOrElse(true) } } def getUserName(userId: Long, forUserId: Long): Stitch[Option[String]] = { val queryFields = GizmoduckClient.GetUserByIdUserNameQueryFields val lookupContext = LookupContext( forUserId = Some(forUserId), perspectiveEdges = Some(GizmoduckClient.DefaultPerspectiveEdges) ) // get latency metrics with StatsUtil.profileStitch when calling .getUserById val response = StatsUtil.profileStitch( gizmoduckStitchClient.getUserById(userId, queryFields, lookupContext), getUserById ) response.map(_.profile.map(_.name)) } } object GizmoduckClient { // Similar to GizmoduckUserRepository.DefaultPerspectiveEdges val DefaultPerspectiveEdges: Set[PerspectiveEdge] = Set( PerspectiveEdge.Blocking, PerspectiveEdge.BlockedBy, PerspectiveEdge.DeviceFollowing, PerspectiveEdge.FollowRequestSent, PerspectiveEdge.Following, PerspectiveEdge.FollowedBy, PerspectiveEdge.LifelineFollowing, PerspectiveEdge.LifelineFollowedBy, PerspectiveEdge.Muting, PerspectiveEdge.NoRetweetsFrom ) // From GizmoduckUserRepository.DefaultQueryFields val GetUserByIdQueryFields: Set[QueryFields] = Set( QueryFields.Account, QueryFields.Counts, QueryFields.ExtendedProfile, QueryFields.Perspective, QueryFields.Profile, QueryFields.ProfileDesign, QueryFields.ProfileLocation, QueryFields.Safety, QueryFields.Roles, QueryFields.Takedowns, QueryFields.UrlEntities, QueryFields.DirectMessageView, QueryFields.MediaView ) val GetUserByIdUserNameQueryFields: Set[QueryFields] = Set( QueryFields.Profile ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/gizmoduck/GizmoduckModule.scala
package com.twitter.follow_recommendations.common.clients.gizmoduck import com.google.inject.Provides import com.twitter.finatra.mtls.thriftmux.modules.MtlsClient import com.twitter.follow_recommendations.common.clients.common.BaseClientModule import com.twitter.gizmoduck.thriftscala.QueryFields import com.twitter.gizmoduck.thriftscala.UserService import com.twitter.stitch.gizmoduck.Gizmoduck import javax.inject.Singleton object GizmoduckModule extends BaseClientModule[UserService.MethodPerEndpoint] with MtlsClient { override val label = "gizmoduck" override val dest = "/s/gizmoduck/gizmoduck" @Provides @Singleton def provideExtraGizmoduckQueryFields: Set[QueryFields] = Set.empty @Provides @Singleton def providesStitchClient(futureIface: UserService.MethodPerEndpoint): Gizmoduck = { Gizmoduck(futureIface) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/graph_feature_service/BUILD
scala_library( sources = ["*.scala"], compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "finatra-internal/mtls-thriftmux/src/main/scala", "finatra/inject/inject-thrift-client", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "graph-feature-service/src/main/thrift/com/twitter/graph_feature_service:graph_feature_service_thrift-scala", "stitch/stitch-core", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/graph_feature_service/GraphFeatureServiceClient.scala
package com.twitter.follow_recommendations.common.clients.graph_feature_service import com.twitter.follow_recommendations.common.models.FollowProof import com.twitter.graph_feature_service.thriftscala.PresetFeatureTypes.WtfTwoHop import com.twitter.graph_feature_service.thriftscala.EdgeType import com.twitter.graph_feature_service.thriftscala.GfsIntersectionResponse import com.twitter.graph_feature_service.thriftscala.GfsPresetIntersectionRequest import com.twitter.graph_feature_service.thriftscala.{Server => GraphFeatureService} import com.twitter.stitch.Stitch import javax.inject.{Inject, Singleton} @Singleton class GraphFeatureServiceClient @Inject() ( graphFeatureService: GraphFeatureService.MethodPerEndpoint) { import GraphFeatureServiceClient._ def getIntersections( userId: Long, candidateIds: Seq[Long], numIntersectionIds: Int ): Stitch[Map[Long, FollowProof]] = { Stitch .callFuture( graphFeatureService.getPresetIntersection( GfsPresetIntersectionRequest(userId, candidateIds, WtfTwoHop, Some(numIntersectionIds)) ) ).map { case GfsIntersectionResponse(gfsIntersectionResults) => (for { candidateId <- candidateIds gfsIntersectionResultForCandidate = gfsIntersectionResults.filter(_.candidateUserId == candidateId) followProof <- for { result <- gfsIntersectionResultForCandidate intersection <- result.intersectionValues if leftEdgeTypes.contains(intersection.featureType.leftEdgeType) if rightEdgeTypes.contains(intersection.featureType.rightEdgeType) intersectionIds <- intersection.intersectionIds.toSeq } yield FollowProof(intersectionIds, intersection.count.getOrElse(0)) } yield { candidateId -> followProof }).toMap } } } object GraphFeatureServiceClient { val leftEdgeTypes: Set[EdgeType] = Set(EdgeType.Following) val rightEdgeTypes: Set[EdgeType] = Set(EdgeType.FollowedBy) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/graph_feature_service/GraphFeatureStoreModule.scala
package com.twitter.follow_recommendations.common.clients.graph_feature_service import com.twitter.finatra.mtls.thriftmux.modules.MtlsClient import com.twitter.follow_recommendations.common.clients.common.BaseClientModule import com.twitter.graph_feature_service.thriftscala.{Server => GraphFeatureService} object GraphFeatureStoreModule extends BaseClientModule[GraphFeatureService.MethodPerEndpoint] with MtlsClient { override val label = "graph_feature_service" override val dest = "/s/cassowary/graph_feature_service-server" }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/impression_store/BUILD
scala_library( sources = ["*.scala"], compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/github/nscala_time", "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", "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/models", "follow-recommendations-service/thrift/src/main/thrift:thrift-scala", "stitch/stitch-socialgraph", "util/util-core:scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/impression_store/ImpressionStoreModule.scala
package com.twitter.follow_recommendations.common.clients.impression_store import com.google.inject.Provides import com.google.inject.Singleton import com.twitter.follow_recommendations.thriftscala.DisplayLocation import com.twitter.inject.TwitterModule import com.twitter.strato.catalog.Scan.Slice import com.twitter.strato.client.Client import com.twitter.strato.thrift.ScroogeConvImplicits._ object ImpressionStoreModule extends TwitterModule { val columnPath: String = "onboarding/userrecs/wtfImpressionCountsStore" type PKey = (Long, DisplayLocation) type LKey = Long type Value = (Long, Int) @Provides @Singleton def providesImpressionStore(stratoClient: Client): WtfImpressionStore = { new WtfImpressionStore( stratoClient.scanner[ (PKey, Slice[LKey]), Unit, (PKey, LKey), Value ](columnPath) ) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/impression_store/WtfImpressionStore.scala
package com.twitter.follow_recommendations.common.clients.impression_store import com.twitter.follow_recommendations.common.models.DisplayLocation import com.twitter.follow_recommendations.common.models.WtfImpression import com.twitter.follow_recommendations.thriftscala.{DisplayLocation => TDisplayLocation} import com.twitter.stitch.Stitch import com.twitter.strato.catalog.Scan.Slice import com.twitter.strato.client.Scanner import com.twitter.util.Time import com.twitter.util.logging.Logging import javax.inject.Inject import javax.inject.Singleton @Singleton class WtfImpressionStore @Inject() ( scanner: Scanner[ ((Long, TDisplayLocation), Slice[Long]), Unit, ((Long, TDisplayLocation), Long), (Long, Int) ]) extends Logging { def get(userId: Long, dl: DisplayLocation): Stitch[Seq[WtfImpression]] = { val thriftDl = dl.toThrift scanner.scan(((userId, thriftDl), Slice.all[Long])).map { impressionsPerDl => val wtfImpressions = for { (((_, _), candidateId), (latestTs, counts)) <- impressionsPerDl } yield WtfImpression( candidateId = candidateId, displayLocation = dl, latestTime = Time.fromMilliseconds(latestTs), counts = counts ) wtfImpressions } rescue { // fail open so that the request can still go through case ex: Throwable => logger.warn(s"$dl WtfImpressionsStore warn: " + ex.getMessage) Stitch.Nil } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/interests_service/BUILD
scala_library( name = "interests_service", sources = ["InterestServiceClient.scala"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "frigate/frigate-common/src/main/scala/com/twitter/frigate/common/store/interests", "interests-service/thrift/src/main/thrift:thrift-scala", "strato/src/main/scala/com/twitter/strato/catalog", "strato/src/main/scala/com/twitter/strato/client", "strato/src/main/scala/com/twitter/strato/data", "strato/src/main/scala/com/twitter/strato/thrift", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/interests_service/InterestServiceClient.scala
package com.twitter.follow_recommendations.common.clients.interests_service import com.google.inject.Inject import com.google.inject.Singleton import com.twitter.finagle.stats.NullStatsReceiver import com.twitter.finagle.stats.StatsReceiver import com.twitter.frigate.common.store.InterestedInInterestsFetchKey import com.twitter.inject.Logging import com.twitter.interests.thriftscala.InterestId import com.twitter.interests.thriftscala.InterestRelationship import com.twitter.interests.thriftscala.InterestedInInterestModel import com.twitter.interests.thriftscala.UserInterest import com.twitter.interests.thriftscala.UserInterestData import com.twitter.interests.thriftscala.UserInterestsResponse import com.twitter.stitch.Stitch import com.twitter.strato.client.Client import com.twitter.strato.thrift.ScroogeConvImplicits._ @Singleton class InterestServiceClient @Inject() ( stratoClient: Client, statsReceiver: StatsReceiver = NullStatsReceiver) extends Logging { val interestsServiceStratoColumnPath = "interests/interestedInInterests" val stats = statsReceiver.scope("interest_service_client") val errorCounter = stats.counter("error") private val interestsFetcher = stratoClient.fetcher[InterestedInInterestsFetchKey, UserInterestsResponse]( interestsServiceStratoColumnPath, checkTypes = true ) def fetchUttInterestIds( userId: Long ): Stitch[Seq[Long]] = { fetchInterestRelationships(userId) .map(_.toSeq.flatten.flatMap(extractUttInterest)) } def extractUttInterest( interestRelationShip: InterestRelationship ): Option[Long] = { interestRelationShip match { case InterestRelationship.V1(relationshipV1) => relationshipV1.interestId match { case InterestId.SemanticCore(semanticCoreInterest) => Some(semanticCoreInterest.id) case _ => None } case _ => None } } def fetchCustomInterests( userId: Long ): Stitch[Seq[String]] = { fetchInterestRelationships(userId) .map(_.toSeq.flatten.flatMap(extractCustomInterest)) } def extractCustomInterest( interestRelationShip: InterestRelationship ): Option[String] = { interestRelationShip match { case InterestRelationship.V1(relationshipV1) => relationshipV1.interestId match { case InterestId.FreeForm(freeFormInterest) => Some(freeFormInterest.interest) case _ => None } case _ => None } } def fetchInterestRelationships( userId: Long ): Stitch[Option[Seq[InterestRelationship]]] = { interestsFetcher .fetch( InterestedInInterestsFetchKey( userId = userId, labels = None, None )) .map(_.v) .map { case Some(response) => response.interests.interests.map { interests => interests.collect { case UserInterest(_, Some(interestData)) => getInterestRelationship(interestData) }.flatten } case _ => None } .rescue { case e: Throwable => // we are swallowing all errors logger.warn(s"interests could not be retrieved for user $userId due to ${e.getCause}") errorCounter.incr Stitch.None } } private def getInterestRelationship( interestData: UserInterestData ): Seq[InterestRelationship] = { interestData match { case UserInterestData.InterestedIn(interestModels) => interestModels.collect { case InterestedInInterestModel.ExplicitModel(model) => model } case _ => Nil } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/phone_storage_service/BUILD
scala_library( sources = ["*.scala"], compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "finatra-internal/mtls-thriftmux/src/main/scala", "finatra/inject/inject-thrift-client", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "phonestorage/server/src/main/thrift/com/twitter/phonestorage/api:phone-storage-service-scala", "stitch/stitch-core", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/phone_storage_service/PhoneStorageServiceClient.scala
package com.twitter.follow_recommendations.common.clients.phone_storage_service import com.twitter.cds.contact_consent_state.thriftscala.PurposeOfProcessing import com.twitter.phonestorage.api.thriftscala.GetUserPhonesByUsersRequest import com.twitter.phonestorage.api.thriftscala.PhoneStorageService import com.twitter.stitch.Stitch import javax.inject.Inject import javax.inject.Singleton @Singleton class PhoneStorageServiceClient @Inject() ( val phoneStorageService: PhoneStorageService.MethodPerEndpoint) { /** * PSS can potentially return multiple phone records. * The current implementation of getUserPhonesByUsers returns only a single phone for a single user_id but * we can trivially support handling multiple in case that changes in the future. */ def getPhoneNumbers( userId: Long, purposeOfProcessing: PurposeOfProcessing, forceCarrierLookup: Option[Boolean] = None ): Stitch[Seq[String]] = { val req = GetUserPhonesByUsersRequest( userIds = Seq(userId), forceCarrierLookup = forceCarrierLookup, purposesOfProcessing = Some(Seq(purposeOfProcessing)) ) Stitch.callFuture(phoneStorageService.getUserPhonesByUsers(req)) map { _.userPhones.map(_.phoneNumber) } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/phone_storage_service/PhoneStorageServiceModule.scala
package com.twitter.follow_recommendations.common.clients.phone_storage_service import com.twitter.finatra.mtls.thriftmux.modules.MtlsClient import com.twitter.follow_recommendations.common.clients.common.BaseClientModule import com.twitter.phonestorage.api.thriftscala.PhoneStorageService object PhoneStorageServiceModule extends BaseClientModule[PhoneStorageService.MethodPerEndpoint] with MtlsClient { override val label = "phone-storage-service" override val dest = "/s/ibis-ds-api/ibis-ds-api:thrift2" }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/real_time_real_graph/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/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/ml/featureStore:featureStore-strato-client", "strato/config/columns/onboarding/userrecs:userrecs-strato-client", "strato/src/main/scala/com/twitter/strato/client", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/real_time_real_graph/Engagement.scala
package com.twitter.follow_recommendations.common.clients.real_time_real_graph sealed trait EngagementType // We do not include SoftFollow since it's deprecated object EngagementType { object Click extends EngagementType object Like extends EngagementType object Mention extends EngagementType object Retweet extends EngagementType object ProfileView extends EngagementType } case class Engagement(engagementType: EngagementType, timestamp: Long)
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/real_time_real_graph/EngagementScorer.scala
package com.twitter.follow_recommendations.common.clients.real_time_real_graph import com.twitter.conversions.DurationOps._ import com.twitter.util.Time object EngagementScorer { private[real_time_real_graph] val MemoryDecayHalfLife = 24.hour private val ScoringFunctionBase = 0.5 def apply( engagements: Map[Long, Seq[Engagement]], engagementScoreMap: Map[EngagementType, Double], minScore: Double = 0.0 ): Seq[(Long, Double, Seq[EngagementType])] = { val now = Time.now engagements .mapValues { engags => val totalScore = engags.map { engagement => score(engagement, now, engagementScoreMap) }.sum val engagementProof = getEngagementProof(engags, engagementScoreMap) (totalScore, engagementProof) } .collect { case (uid, (score, proof)) if score > minScore => (uid, score, proof) } .toSeq .sortBy(-_._2) } /** * The engagement score is the base score decayed via timestamp, loosely model the human memory forgetting * curve, see https://en.wikipedia.org/wiki/Forgetting_curve */ private[real_time_real_graph] def score( engagement: Engagement, now: Time, engagementScoreMap: Map[EngagementType, Double] ): Double = { val timeLapse = math.max(now.inMillis - engagement.timestamp, 0) val engagementScore = engagementScoreMap.getOrElse(engagement.engagementType, 0.0) engagementScore * math.pow( ScoringFunctionBase, timeLapse.toDouble / MemoryDecayHalfLife.inMillis) } private def getEngagementProof( engagements: Seq[Engagement], engagementScoreMap: Map[EngagementType, Double] ): Seq[EngagementType] = { val filteredEngagement = engagements .collectFirst { case engagement if engagement.engagementType != EngagementType.Click && engagementScoreMap.get(engagement.engagementType).exists(_ > 0.0) => engagement.engagementType } Seq(filteredEngagement.getOrElse(EngagementType.Click)) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/real_time_real_graph/RealTimeRealGraphClient.scala
package com.twitter.follow_recommendations.common.clients.real_time_real_graph import com.google.inject.Inject import com.google.inject.Singleton import com.twitter.conversions.DurationOps._ import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.snowflake.id.SnowflakeId import com.twitter.stitch.Stitch import com.twitter.strato.generated.client.ml.featureStore.TimelinesUserVertexOnUserClientColumn import com.twitter.strato.generated.client.onboarding.userrecs.RealGraphScoresMhOnUserClientColumn import com.twitter.util.Duration import com.twitter.util.Time import com.twitter.wtf.real_time_interaction_graph.thriftscala._ @Singleton class RealTimeRealGraphClient @Inject() ( timelinesUserVertexOnUserClientColumn: TimelinesUserVertexOnUserClientColumn, realGraphScoresMhOnUserClientColumn: RealGraphScoresMhOnUserClientColumn) { def mapUserVertexToEngagementAndFilter(userVertex: UserVertex): Map[Long, Seq[Engagement]] = { val minTimestamp = (Time.now - RealTimeRealGraphClient.MaxEngagementAge).inMillis userVertex.outgoingInteractionMap.mapValues { interactions => interactions .flatMap { interaction => RealTimeRealGraphClient.toEngagement(interaction) }.filter( _.timestamp >= minTimestamp) }.toMap } def getRecentProfileViewEngagements(userId: Long): Stitch[Map[Long, Seq[Engagement]]] = { timelinesUserVertexOnUserClientColumn.fetcher .fetch(userId).map(_.v).map { input => input .map { userVertex => val targetToEngagements = mapUserVertexToEngagementAndFilter(userVertex) targetToEngagements.mapValues { engagements => engagements.filter(engagement => engagement.engagementType == EngagementType.ProfileView) } }.getOrElse(Map.empty) } } def getUsersRecentlyEngagedWith( userId: Long, engagementScoreMap: Map[EngagementType, Double], includeDirectFollowCandidates: Boolean, includeNonDirectFollowCandidates: Boolean ): Stitch[Seq[CandidateUser]] = { val isNewUser = SnowflakeId.timeFromIdOpt(userId).exists { signupTime => (Time.now - signupTime) < RealTimeRealGraphClient.MaxNewUserAge } val updatedEngagementScoreMap = if (isNewUser) engagementScoreMap + (EngagementType.ProfileView -> RealTimeRealGraphClient.ProfileViewScore) else engagementScoreMap Stitch .join( timelinesUserVertexOnUserClientColumn.fetcher.fetch(userId).map(_.v), realGraphScoresMhOnUserClientColumn.fetcher.fetch(userId).map(_.v)).map { case (Some(userVertex), Some(neighbors)) => val engagements = mapUserVertexToEngagementAndFilter(userVertex) val candidatesAndScores: Seq[(Long, Double, Seq[EngagementType])] = EngagementScorer.apply(engagements, engagementScoreMap = updatedEngagementScoreMap) val directNeighbors = neighbors.candidates.map(_._1).toSet val (directFollows, nonDirectFollows) = candidatesAndScores .partition { case (id, _, _) => directNeighbors.contains(id) } val candidates = (if (includeNonDirectFollowCandidates) nonDirectFollows else Seq.empty) ++ (if (includeDirectFollowCandidates) directFollows.take(RealTimeRealGraphClient.MaxNumDirectFollow) else Seq.empty) candidates.map { case (id, score, proof) => CandidateUser(id, Some(score)) } case _ => Nil } } def getRealGraphWeights(userId: Long): Stitch[Map[Long, Double]] = realGraphScoresMhOnUserClientColumn.fetcher .fetch(userId) .map( _.v .map(_.candidates.map(candidate => (candidate.userId, candidate.score)).toMap) .getOrElse(Map.empty[Long, Double])) } object RealTimeRealGraphClient { private def toEngagement(interaction: Interaction): Option[Engagement] = { // We do not include SoftFollow since it's deprecated interaction match { case Interaction.Retweet(Retweet(timestamp)) => Some(Engagement(EngagementType.Retweet, timestamp)) case Interaction.Favorite(Favorite(timestamp)) => Some(Engagement(EngagementType.Like, timestamp)) case Interaction.Click(Click(timestamp)) => Some(Engagement(EngagementType.Click, timestamp)) case Interaction.Mention(Mention(timestamp)) => Some(Engagement(EngagementType.Mention, timestamp)) case Interaction.ProfileView(ProfileView(timestamp)) => Some(Engagement(EngagementType.ProfileView, timestamp)) case _ => None } } val MaxNumDirectFollow = 50 val MaxEngagementAge: Duration = 14.days val MaxNewUserAge: Duration = 30.days val ProfileViewScore = 0.4 val EngagementScoreMap = Map( EngagementType.Like -> 1.0, EngagementType.Retweet -> 1.0, EngagementType.Mention -> 1.0 ) val StrongEngagementScoreMap = Map( EngagementType.Like -> 1.0, EngagementType.Retweet -> 1.0, ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/socialgraph/BUILD
scala_library( sources = ["*.scala"], compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/github/nscala_time", "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-internal/mtls-thriftmux/src/main/scala", "finatra/inject/inject-core/src/main/scala", "finatra/inject/inject-thrift-client/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/common", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models", "socialgraph/server/src/main/scala/com/twitter/socialgraph/util", "src/thrift/com/twitter/socialgraph:thrift-scala", "stitch/stitch-socialgraph", "strato/config/columns/onboarding/socialGraphService:socialGraphService-strato-client", "strato/src/main/scala/com/twitter/strato/client", "util/util-core:scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/socialgraph/SocialGraphClient.scala
package com.twitter.follow_recommendations.common.clients.socialgraph import com.twitter.escherbird.util.stitchcache.StitchCache import com.twitter.finagle.stats.NullStatsReceiver import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.base.StatsUtil import com.twitter.follow_recommendations.common.models.FollowProof import com.twitter.follow_recommendations.common.models.UserIdWithTimestamp import com.twitter.inject.Logging import com.twitter.socialgraph.thriftscala.EdgesRequest import com.twitter.socialgraph.thriftscala.IdsRequest import com.twitter.socialgraph.thriftscala.IdsResult import com.twitter.socialgraph.thriftscala.LookupContext import com.twitter.socialgraph.thriftscala.OverCapacity import com.twitter.socialgraph.thriftscala.PageRequest import com.twitter.socialgraph.thriftscala.RelationshipType import com.twitter.socialgraph.thriftscala.SrcRelationship import com.twitter.socialgraph.util.ByteBufferUtil import com.twitter.stitch.Stitch import com.twitter.stitch.socialgraph.SocialGraph import com.twitter.strato.client.Fetcher import com.twitter.strato.generated.client.onboarding.socialGraphService.IdsClientColumn import com.twitter.util.Duration import com.twitter.util.Time import java.nio.ByteBuffer import javax.inject.Inject import javax.inject.Singleton case class RecentEdgesQuery( userId: Long, relations: Seq[RelationshipType], // prefer to default value to better utilize the caching function of stitch count: Option[Int] = Some(SocialGraphClient.MaxQuerySize), performUnion: Boolean = true, recentEdgesWindowOpt: Option[Duration] = None, targets: Option[Seq[Long]] = None) case class EdgeRequestQuery( userId: Long, relation: RelationshipType, count: Option[Int] = Some(SocialGraphClient.MaxQuerySize), performUnion: Boolean = true, recentEdgesWindowOpt: Option[Duration] = None, targets: Option[Seq[Long]] = None) @Singleton class SocialGraphClient @Inject() ( socialGraph: SocialGraph, idsClientColumn: IdsClientColumn, statsReceiver: StatsReceiver = NullStatsReceiver) extends Logging { private val stats = statsReceiver.scope(this.getClass.getSimpleName) private val cacheStats = stats.scope("cache") private val getIntersectionsStats = stats.scope("getIntersections") private val getIntersectionsFromCachedColumnStats = stats.scope("getIntersectionsFromCachedColumn") private val getRecentEdgesStats = stats.scope("getRecentEdges") private val getRecentEdgesCachedStats = stats.scope("getRecentEdgesCached") private val getRecentEdgesFromCachedColumnStats = stats.scope("getRecentEdgesFromCachedColumn") private val getRecentEdgesCachedInternalStats = stats.scope("getRecentEdgesCachedInternal") private val getRecentEdgesWithTimeStats = stats.scope("getRecentEdgesWithTime") val sgsIdsFetcher: Fetcher[IdsRequest, Unit, IdsResult] = idsClientColumn.fetcher private val recentEdgesCache = StitchCache[RecentEdgesQuery, Seq[Long]]( maxCacheSize = SocialGraphClient.MaxCacheSize, ttl = SocialGraphClient.CacheTTL, statsReceiver = cacheStats, underlyingCall = getRecentEdges ) def getRecentEdgesCached( rq: RecentEdgesQuery, useCachedStratoColumn: Boolean = true ): Stitch[Seq[Long]] = { getRecentEdgesCachedStats.counter("requests").incr() if (useCachedStratoColumn) { getRecentEdgesFromCachedColumn(rq) } else { StatsUtil.profileStitch( getRecentEdgesCachedInternal(rq), getRecentEdgesCachedInternalStats ) } } def getRecentEdgesCachedInternal(rq: RecentEdgesQuery): Stitch[Seq[Long]] = { recentEdgesCache.readThrough(rq) } def getRecentEdgesFromCachedColumn(rq: RecentEdgesQuery): Stitch[Seq[Long]] = { val pageRequest = rq.recentEdgesWindowOpt match { case Some(recentEdgesWindow) => PageRequest( count = rq.count, cursor = Some(getEdgeCursor(recentEdgesWindow)), selectAll = Some(true) ) case _ => PageRequest(count = rq.count) } val idsRequest = IdsRequest( rq.relations.map { relationshipType => SrcRelationship( source = rq.userId, relationshipType = relationshipType, targets = rq.targets ) }, pageRequest = Some(pageRequest), context = Some(LookupContext(performUnion = Some(rq.performUnion))) ) val socialGraphStitch = sgsIdsFetcher .fetch(idsRequest, Unit) .map(_.v) .map { result => result .map { idResult => val userIds: Seq[Long] = idResult.ids getRecentEdgesFromCachedColumnStats.stat("num_edges").add(userIds.size) userIds }.getOrElse(Seq.empty) } .rescue { case e: Exception => stats.counter(e.getClass.getSimpleName).incr() Stitch.Nil } StatsUtil.profileStitch( socialGraphStitch, getRecentEdgesFromCachedColumnStats ) } def getRecentEdges(rq: RecentEdgesQuery): Stitch[Seq[Long]] = { val pageRequest = rq.recentEdgesWindowOpt match { case Some(recentEdgesWindow) => PageRequest( count = rq.count, cursor = Some(getEdgeCursor(recentEdgesWindow)), selectAll = Some(true) ) case _ => PageRequest(count = rq.count) } val socialGraphStitch = socialGraph .ids( IdsRequest( rq.relations.map { relationshipType => SrcRelationship( source = rq.userId, relationshipType = relationshipType, targets = rq.targets ) }, pageRequest = Some(pageRequest), context = Some(LookupContext(performUnion = Some(rq.performUnion))) ) ) .map { idsResult => val userIds: Seq[Long] = idsResult.ids getRecentEdgesStats.stat("num_edges").add(userIds.size) userIds } .rescue { case e: OverCapacity => stats.counter(e.getClass.getSimpleName).incr() logger.warn("SGS Over Capacity", e) Stitch.Nil } StatsUtil.profileStitch( socialGraphStitch, getRecentEdgesStats ) } // This method return recent edges of (userId, timeInMs) def getRecentEdgesWithTime(rq: EdgeRequestQuery): Stitch[Seq[UserIdWithTimestamp]] = { val pageRequest = rq.recentEdgesWindowOpt match { case Some(recentEdgesWindow) => PageRequest( count = rq.count, cursor = Some(getEdgeCursor(recentEdgesWindow)), selectAll = Some(true) ) case _ => PageRequest(count = rq.count) } val socialGraphStitch = socialGraph .edges( EdgesRequest( SrcRelationship( source = rq.userId, relationshipType = rq.relation, targets = rq.targets ), pageRequest = Some(pageRequest), context = Some(LookupContext(performUnion = Some(rq.performUnion))) ) ) .map { edgesResult => val userIds = edgesResult.edges.map { socialEdge => UserIdWithTimestamp(socialEdge.target, socialEdge.updatedAt) } getRecentEdgesWithTimeStats.stat("num_edges").add(userIds.size) userIds } .rescue { case e: OverCapacity => stats.counter(e.getClass.getSimpleName).incr() logger.warn("SGS Over Capacity", e) Stitch.Nil } StatsUtil.profileStitch( socialGraphStitch, getRecentEdgesWithTimeStats ) } // This method returns the cursor for a time duration, such that all the edges returned by SGS will be created // in the range (now-window, now) def getEdgeCursor(window: Duration): ByteBuffer = { val cursorInLong = (-(Time.now - window).inMilliseconds) << 20 ByteBufferUtil.fromLong(cursorInLong) } // notice that this is more expensive but more realtime than the GFS one def getIntersections( userId: Long, candidateIds: Seq[Long], numIntersectionIds: Int ): Stitch[Map[Long, FollowProof]] = { val socialGraphStitch: Stitch[Map[Long, FollowProof]] = Stitch .collect(candidateIds.map { candidateId => socialGraph .ids( IdsRequest( Seq( SrcRelationship(userId, RelationshipType.Following), SrcRelationship(candidateId, RelationshipType.FollowedBy) ), pageRequest = Some(PageRequest(count = Some(numIntersectionIds))) ) ).map { idsResult => getIntersectionsStats.stat("num_edges").add(idsResult.ids.size) (candidateId -> FollowProof(idsResult.ids, idsResult.ids.size)) } }).map(_.toMap) .rescue { case e: OverCapacity => stats.counter(e.getClass.getSimpleName).incr() logger.warn("social graph over capacity in hydrating social proof", e) Stitch.value(Map.empty) } StatsUtil.profileStitch( socialGraphStitch, getIntersectionsStats ) } def getIntersectionsFromCachedColumn( userId: Long, candidateIds: Seq[Long], numIntersectionIds: Int ): Stitch[Map[Long, FollowProof]] = { val socialGraphStitch: Stitch[Map[Long, FollowProof]] = Stitch .collect(candidateIds.map { candidateId => val idsRequest = IdsRequest( Seq( SrcRelationship(userId, RelationshipType.Following), SrcRelationship(candidateId, RelationshipType.FollowedBy) ), pageRequest = Some(PageRequest(count = Some(numIntersectionIds))) ) sgsIdsFetcher .fetch(idsRequest, Unit) .map(_.v) .map { resultOpt => resultOpt.map { idsResult => getIntersectionsFromCachedColumnStats.stat("num_edges").add(idsResult.ids.size) candidateId -> FollowProof(idsResult.ids, idsResult.ids.size) } } }).map(_.flatten.toMap) .rescue { case e: Exception => stats.counter(e.getClass.getSimpleName).incr() Stitch.value(Map.empty) } StatsUtil.profileStitch( socialGraphStitch, getIntersectionsFromCachedColumnStats ) } def getInvalidRelationshipUserIds( userId: Long, maxNumRelationship: Int = SocialGraphClient.MaxNumInvalidRelationship ): Stitch[Seq[Long]] = { getRecentEdges( RecentEdgesQuery( userId, SocialGraphClient.InvalidRelationshipTypes, Some(maxNumRelationship) ) ) } def getInvalidRelationshipUserIdsFromCachedColumn( userId: Long, maxNumRelationship: Int = SocialGraphClient.MaxNumInvalidRelationship ): Stitch[Seq[Long]] = { getRecentEdgesFromCachedColumn( RecentEdgesQuery( userId, SocialGraphClient.InvalidRelationshipTypes, Some(maxNumRelationship) ) ) } def getRecentFollowedUserIds(userId: Long): Stitch[Seq[Long]] = { getRecentEdges( RecentEdgesQuery( userId, Seq(RelationshipType.Following) ) ) } def getRecentFollowedUserIdsFromCachedColumn(userId: Long): Stitch[Seq[Long]] = { getRecentEdgesFromCachedColumn( RecentEdgesQuery( userId, Seq(RelationshipType.Following) ) ) } def getRecentFollowedUserIdsWithTime(userId: Long): Stitch[Seq[UserIdWithTimestamp]] = { getRecentEdgesWithTime( EdgeRequestQuery( userId, RelationshipType.Following ) ) } def getRecentFollowedByUserIds(userId: Long): Stitch[Seq[Long]] = { getRecentEdges( RecentEdgesQuery( userId, Seq(RelationshipType.FollowedBy) ) ) } def getRecentFollowedByUserIdsFromCachedColumn(userId: Long): Stitch[Seq[Long]] = { getRecentEdgesFromCachedColumn( RecentEdgesQuery( userId, Seq(RelationshipType.FollowedBy) ) ) } def getRecentFollowedUserIdsWithTimeWindow( userId: Long, timeWindow: Duration ): Stitch[Seq[Long]] = { getRecentEdges( RecentEdgesQuery( userId, Seq(RelationshipType.Following), recentEdgesWindowOpt = Some(timeWindow) ) ) } } object SocialGraphClient { val MaxQuerySize: Int = 500 val MaxCacheSize: Int = 5000000 // Ref: src/thrift/com/twitter/socialgraph/social_graph_service.thrift val MaxNumInvalidRelationship: Int = 5000 val CacheTTL: Duration = Duration.fromHours(24) val InvalidRelationshipTypes: Seq[RelationshipType] = Seq( RelationshipType.HideRecommendations, RelationshipType.Blocking, RelationshipType.BlockedBy, RelationshipType.Muting, RelationshipType.MutedBy, RelationshipType.ReportedAsSpam, RelationshipType.ReportedAsSpamBy, RelationshipType.ReportedAsAbuse, RelationshipType.ReportedAsAbuseBy, RelationshipType.FollowRequestOutgoing, RelationshipType.Following, RelationshipType.UsedToFollow, ) /** * * Whether to call SGS to validate each candidate based on the number of invalid relationship users * prefetched during request building step. This aims to not omit any invalid candidates that are * not filtered out in previous steps. * If the number is 0, this might be a fail-opened SGS call. * If the number is larger or equal to 5000, this could hit SGS page size limit. * Both cases account for a small percentage of the total traffic (<5%). * * @param numInvalidRelationshipUsers number of invalid relationship users fetched from getInvalidRelationshipUserIds * @return whether to enable post-ranker SGS predicate */ def enablePostRankerSgsPredicate(numInvalidRelationshipUsers: Int): Boolean = { numInvalidRelationshipUsers == 0 || numInvalidRelationshipUsers >= MaxNumInvalidRelationship } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/socialgraph/SocialGraphModule.scala
package com.twitter.follow_recommendations.common.clients.socialgraph import com.google.inject.Provides import com.twitter.finagle.ThriftMux import com.twitter.finatra.mtls.thriftmux.modules.MtlsClient import com.twitter.follow_recommendations.common.clients.common.BaseClientModule import com.twitter.socialgraph.thriftscala.SocialGraphService import com.twitter.stitch.socialgraph.SocialGraph import javax.inject.Singleton object SocialGraphModule extends BaseClientModule[SocialGraphService.MethodPerEndpoint] with MtlsClient { override val label = "social-graph-service" override val dest = "/s/socialgraph/socialgraph" override def configureThriftMuxClient(client: ThriftMux.Client): ThriftMux.Client = client.withSessionQualifier.noFailFast @Provides @Singleton def providesStitchClient(futureIface: SocialGraphService.MethodPerEndpoint): SocialGraph = { SocialGraph(futureIface) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/strato/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", "src/scala/com/twitter/onboarding/relevance/candidate_generation/utt/models", "src/thrift/com/twitter/core_workflows/user_model:user_model-scala", "src/thrift/com/twitter/frigate/data_pipeline:frigate-user-history-thrift-scala", "src/thrift/com/twitter/hermit/candidate:hermit-candidate-scala", "src/thrift/com/twitter/hermit/pop_geo:hermit-pop-geo-scala", "src/thrift/com/twitter/onboarding/relevance/relatable_accounts:relatable_accounts-scala", "src/thrift/com/twitter/onboarding/relevance/store:store-scala", "src/thrift/com/twitter/recos/user_user_graph:user_user_graph-scala", "src/thrift/com/twitter/search/account_search/extended_network:extended_network_users-scala", "src/thrift/com/twitter/service/metastore/gen:thrift-scala", "src/thrift/com/twitter/wtf/candidate:wtf-candidate-scala", "src/thrift/com/twitter/wtf/ml:wtf-ml-output-thrift-scala", "src/thrift/com/twitter/wtf/real_time_interaction_graph:wtf-real_time_interaction_graph-thrift-scala", "src/thrift/com/twitter/wtf/triangular_loop:triangular_loop-scala", "strato/src/main/scala/com/twitter/strato/client", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/strato/StratoClientModule.scala
package com.twitter.follow_recommendations.common.clients.strato import com.google.inject.name.Named import com.google.inject.Provides import com.google.inject.Singleton import com.twitter.conversions.DurationOps._ import com.twitter.core_workflows.user_model.thriftscala.CondensedUserState import com.twitter.search.account_search.extended_network.thriftscala.ExtendedNetworkUserKey import com.twitter.search.account_search.extended_network.thriftscala.ExtendedNetworkUserVal import com.twitter.finagle.ThriftMux import com.twitter.finagle.mtls.authentication.ServiceIdentifier import com.twitter.finagle.thrift.Protocols import com.twitter.follow_recommendations.common.constants.GuiceNamedConstants import com.twitter.follow_recommendations.common.constants.ServiceConstants._ import com.twitter.frigate.data_pipeline.candidate_generation.thriftscala.LatestEvents import com.twitter.hermit.candidate.thriftscala.{Candidates => HermitCandidates} import com.twitter.hermit.pop_geo.thriftscala.PopUsersInPlace import com.twitter.onboarding.relevance.relatable_accounts.thriftscala.RelatableAccounts import com.twitter.inject.TwitterModule import com.twitter.onboarding.relevance.candidates.thriftscala.InterestBasedUserRecommendations import com.twitter.onboarding.relevance.candidates.thriftscala.UTTInterest import com.twitter.onboarding.relevance.store.thriftscala.WhoToFollowDismissEventDetails import com.twitter.recos.user_user_graph.thriftscala.RecommendUserRequest import com.twitter.recos.user_user_graph.thriftscala.RecommendUserResponse import com.twitter.service.metastore.gen.thriftscala.UserRecommendabilityFeatures import com.twitter.strato.catalog.Scan.Slice import com.twitter.strato.client.Strato.{Client => StratoClient} import com.twitter.strato.client.Client import com.twitter.strato.client.Fetcher import com.twitter.strato.client.Scanner import com.twitter.strato.thrift.ScroogeConvImplicits._ import com.twitter.wtf.candidate.thriftscala.CandidateSeq import com.twitter.wtf.ml.thriftscala.CandidateFeatures import com.twitter.wtf.real_time_interaction_graph.thriftscala.Interaction import com.twitter.wtf.triangular_loop.thriftscala.{Candidates => TriangularLoopCandidates} import com.twitter.strato.opcontext.Attribution._ object StratoClientModule extends TwitterModule { // column paths val CosineFollowPath = "recommendations/similarity/similarUsersByFollowGraph.User" val CosineListPath = "recommendations/similarity/similarUsersByListGraph.User" val CuratedCandidatesPath = "onboarding/curatedAccounts" val CuratedFilteredAccountsPath = "onboarding/filteredAccountsFromRecommendations" val PopUsersInPlacePath = "onboarding/userrecs/popUsersInPlace" val ProfileSidebarBlacklistPath = "recommendations/hermit/profile-sidebar-blacklist" val RealTimeInteractionsPath = "hmli/realTimeInteractions" val SimsPath = "recommendations/similarity/similarUsersBySims.User" val DBV2SimsPath = "onboarding/userrecs/newSims.User" val TriangularLoopsPath = "onboarding/userrecs/triangularLoops.User" val TwoHopRandomWalkPath = "onboarding/userrecs/twoHopRandomWalk.User" val UserRecommendabilityPath = "onboarding/userRecommendabilityWithLongKeys.User" val UTTAccountRecommendationsPath = "onboarding/userrecs/utt_account_recommendations" val UttSeedAccountsRecommendationPath = "onboarding/userrecs/utt_seed_accounts" val UserStatePath = "onboarding/userState.User" val WTFPostNuxFeaturesPath = "ml/featureStore/onboarding/wtfPostNuxFeatures.User" val ElectionCandidatesPath = "onboarding/electionAccounts" val UserUserGraphPath = "recommendations/userUserGraph" val WtfDissmissEventsPath = "onboarding/wtfDismissEvents" val RelatableAccountsPath = "onboarding/userrecs/relatableAccounts" val ExtendedNetworkCandidatesPath = "search/account_search/extendedNetworkCandidatesMH" val LabeledNotificationPath = "frigate/magicrecs/labeledPushRecsAggregated.User" @Provides @Singleton def stratoClient(serviceIdentifier: ServiceIdentifier): Client = { val timeoutBudget = 500.milliseconds StratoClient( ThriftMux.client .withRequestTimeout(timeoutBudget) .withProtocolFactory(Protocols.binaryFactory( stringLengthLimit = StringLengthLimit, containerLengthLimit = ContainerLengthLimit))) .withMutualTls(serviceIdentifier) .build() } // add strato putters, fetchers, scanners below: @Provides @Singleton @Named(GuiceNamedConstants.COSINE_FOLLOW_FETCHER) def cosineFollowFetcher(stratoClient: Client): Fetcher[Long, Unit, HermitCandidates] = stratoClient.fetcher[Long, Unit, HermitCandidates](CosineFollowPath) @Provides @Singleton @Named(GuiceNamedConstants.COSINE_LIST_FETCHER) def cosineListFetcher(stratoClient: Client): Fetcher[Long, Unit, HermitCandidates] = stratoClient.fetcher[Long, Unit, HermitCandidates](CosineListPath) @Provides @Singleton @Named(GuiceNamedConstants.CURATED_COMPETITOR_ACCOUNTS_FETCHER) def curatedBlacklistedAccountsFetcher(stratoClient: Client): Fetcher[String, Unit, Seq[Long]] = stratoClient.fetcher[String, Unit, Seq[Long]](CuratedFilteredAccountsPath) @Provides @Singleton @Named(GuiceNamedConstants.CURATED_CANDIDATES_FETCHER) def curatedCandidatesFetcher(stratoClient: Client): Fetcher[String, Unit, Seq[Long]] = stratoClient.fetcher[String, Unit, Seq[Long]](CuratedCandidatesPath) @Provides @Singleton @Named(GuiceNamedConstants.POP_USERS_IN_PLACE_FETCHER) def popUsersInPlaceFetcher(stratoClient: Client): Fetcher[String, Unit, PopUsersInPlace] = stratoClient.fetcher[String, Unit, PopUsersInPlace](PopUsersInPlacePath) @Provides @Singleton @Named(GuiceNamedConstants.RELATABLE_ACCOUNTS_FETCHER) def relatableAccountsFetcher(stratoClient: Client): Fetcher[String, Unit, RelatableAccounts] = stratoClient.fetcher[String, Unit, RelatableAccounts](RelatableAccountsPath) @Provides @Singleton @Named(GuiceNamedConstants.PROFILE_SIDEBAR_BLACKLIST_SCANNER) def profileSidebarBlacklistScanner( stratoClient: Client ): Scanner[(Long, Slice[Long]), Unit, (Long, Long), Unit] = stratoClient.scanner[(Long, Slice[Long]), Unit, (Long, Long), Unit](ProfileSidebarBlacklistPath) @Provides @Singleton @Named(GuiceNamedConstants.REAL_TIME_INTERACTIONS_FETCHER) def realTimeInteractionsFetcher( stratoClient: Client ): Fetcher[(Long, Long), Unit, Seq[Interaction]] = stratoClient.fetcher[(Long, Long), Unit, Seq[Interaction]](RealTimeInteractionsPath) @Provides @Singleton @Named(GuiceNamedConstants.SIMS_FETCHER) def simsFetcher(stratoClient: Client): Fetcher[Long, Unit, HermitCandidates] = stratoClient.fetcher[Long, Unit, HermitCandidates](SimsPath) @Provides @Singleton @Named(GuiceNamedConstants.DBV2_SIMS_FETCHER) def dbv2SimsFetcher(stratoClient: Client): Fetcher[Long, Unit, HermitCandidates] = stratoClient.fetcher[Long, Unit, HermitCandidates](DBV2SimsPath) @Provides @Singleton @Named(GuiceNamedConstants.TRIANGULAR_LOOPS_FETCHER) def triangularLoopsFetcher(stratoClient: Client): Fetcher[Long, Unit, TriangularLoopCandidates] = stratoClient.fetcher[Long, Unit, TriangularLoopCandidates](TriangularLoopsPath) @Provides @Singleton @Named(GuiceNamedConstants.TWO_HOP_RANDOM_WALK_FETCHER) def twoHopRandomWalkFetcher(stratoClient: Client): Fetcher[Long, Unit, CandidateSeq] = stratoClient.fetcher[Long, Unit, CandidateSeq](TwoHopRandomWalkPath) @Provides @Singleton @Named(GuiceNamedConstants.USER_RECOMMENDABILITY_FETCHER) def userRecommendabilityFetcher( stratoClient: Client ): Fetcher[Long, Unit, UserRecommendabilityFeatures] = stratoClient.fetcher[Long, Unit, UserRecommendabilityFeatures](UserRecommendabilityPath) @Provides @Singleton @Named(GuiceNamedConstants.USER_STATE_FETCHER) def userStateFetcher(stratoClient: Client): Fetcher[Long, Unit, CondensedUserState] = stratoClient.fetcher[Long, Unit, CondensedUserState](UserStatePath) @Provides @Singleton @Named(GuiceNamedConstants.UTT_ACCOUNT_RECOMMENDATIONS_FETCHER) def uttAccountRecommendationsFetcher( stratoClient: Client ): Fetcher[UTTInterest, Unit, InterestBasedUserRecommendations] = stratoClient.fetcher[UTTInterest, Unit, InterestBasedUserRecommendations]( UTTAccountRecommendationsPath) @Provides @Singleton @Named(GuiceNamedConstants.UTT_SEED_ACCOUNTS_FETCHER) def uttSeedAccountRecommendationsFetcher( stratoClient: Client ): Fetcher[UTTInterest, Unit, InterestBasedUserRecommendations] = stratoClient.fetcher[UTTInterest, Unit, InterestBasedUserRecommendations]( UttSeedAccountsRecommendationPath) @Provides @Singleton @Named(GuiceNamedConstants.ELECTION_CANDIDATES_FETCHER) def electionCandidatesFetcher(stratoClient: Client): Fetcher[String, Unit, Seq[Long]] = stratoClient.fetcher[String, Unit, Seq[Long]](ElectionCandidatesPath) @Provides @Singleton @Named(GuiceNamedConstants.USER_USER_GRAPH_FETCHER) def userUserGraphFetcher( stratoClient: Client ): Fetcher[RecommendUserRequest, Unit, RecommendUserResponse] = stratoClient.fetcher[RecommendUserRequest, Unit, RecommendUserResponse](UserUserGraphPath) @Provides @Singleton @Named(GuiceNamedConstants.POST_NUX_WTF_FEATURES_FETCHER) def wtfPostNuxFeaturesFetcher(stratoClient: Client): Fetcher[Long, Unit, CandidateFeatures] = { val attribution = ManhattanAppId("starbuck", "wtf_starbuck") stratoClient .fetcher[Long, Unit, CandidateFeatures](WTFPostNuxFeaturesPath) .withAttribution(attribution) } @Provides @Singleton @Named(GuiceNamedConstants.EXTENDED_NETWORK) def extendedNetworkFetcher( stratoClient: Client ): Fetcher[ExtendedNetworkUserKey, Unit, ExtendedNetworkUserVal] = { stratoClient .fetcher[ExtendedNetworkUserKey, Unit, ExtendedNetworkUserVal](ExtendedNetworkCandidatesPath) } @Provides @Singleton @Named(GuiceNamedConstants.DISMISS_STORE_SCANNER) def dismissStoreScanner( stratoClient: Client ): Scanner[ (Long, Slice[(Long, Long)]), Unit, (Long, (Long, Long)), WhoToFollowDismissEventDetails ] = stratoClient.scanner[ (Long, Slice[(Long, Long)]), // PKEY: userId, LKEY: (-ts, candidateId) Unit, (Long, (Long, Long)), WhoToFollowDismissEventDetails ](WtfDissmissEventsPath) @Provides @Singleton @Named(GuiceNamedConstants.LABELED_NOTIFICATION_FETCHER) def labeledNotificationFetcher( stratoClient: Client ): Fetcher[Long, Unit, LatestEvents] = { stratoClient .fetcher[Long, Unit, LatestEvents](LabeledNotificationPath) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/user_state/BUILD
scala_library( sources = ["*.scala"], compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/com/google/inject:guice", "3rdparty/jvm/net/codingwell:scala-guice", "3rdparty/jvm/org/slf4j:slf4j-api", "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/server/src/main/scala/com/twitter/follow_recommendations/configapi/deciders", "stitch/stitch-core", "strato/src/main/scala/com/twitter/strato/client", "user-signal-service/thrift/src/main/thrift:thrift-scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/user_state/UserStateClient.scala
package com.twitter.follow_recommendations.common.clients.user_state import com.google.inject.name.Named import com.twitter.conversions.DurationOps._ import com.twitter.core_workflows.user_model.thriftscala.CondensedUserState 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.finagle.util.DefaultTimer 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.constants.GuiceNamedConstants import com.twitter.follow_recommendations.configapi.deciders.DeciderKey import com.twitter.stitch.Stitch import com.twitter.strato.client.Fetcher import com.twitter.util.Duration import javax.inject.Inject import javax.inject.Singleton import java.lang.{Long => JLong} @Singleton class UserStateClient @Inject() ( @Named(GuiceNamedConstants.USER_STATE_FETCHER) userStateFetcher: Fetcher[ Long, Unit, CondensedUserState ], client: Client, statsReceiver: StatsReceiver, decider: Decider = Decider.False) { private val stats: StatsReceiver = statsReceiver.scope("user_state_client") // 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 = UserStateClient.CacheTTL, statsReceiver = stats.scope("twemcache") ) def getUserState(userId: Long): Stitch[Option[UserState]] = { val deciderKey: String = DeciderKey.EnableDistributedCaching.toString val enableDistributedCaching: Boolean = decider.isAvailable(deciderKey, Some(RandomRecipient)) val userStateStitch: Stitch[Option[UserState]] = enableDistributedCaching match { // read from memcache case true => memcacheClient.readThrough( // add a key prefix to address cache key collisions key = "UserStateClient" + userId.toString, underlyingCall = () => fetchUserState(userId) ) case false => fetchUserState(userId) } val userStateStitchWithTimeout: Stitch[Option[UserState]] = userStateStitch // set a 150ms timeout limit for user state fetches .within(150.milliseconds)(DefaultTimer) .rescue { case e: Exception => stats.scope("rescued").counter(e.getClass.getSimpleName).incr() Stitch(None) } // profile the latency of stitch call and return the result StatsUtil.profileStitch( userStateStitchWithTimeout, stats.scope("getUserState") ) } def fetchUserState(userId: JLong): Stitch[Option[UserState]] = { userStateFetcher.fetch(userId).map(_.v.flatMap(_.userState)) } } object UserStateClient { val CacheTTL: Duration = Duration.fromHours(6) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants/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", "util/util-core/src/main/scala/com/twitter/conversions", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants/CandidateAlgorithmTypeConstants.scala
package com.twitter.follow_recommendations.common.constants import com.twitter.hermit.constants.AlgorithmFeedbackTokens.AlgorithmToFeedbackTokenMap import com.twitter.hermit.model.Algorithm._ import com.twitter.follow_recommendations.common.models.AlgorithmType object CandidateAlgorithmTypeConstants { /** * Each algorithm is based on one, or more, of the 4 types of information we have on users, * described in [[AlgorithmType]]. Assignment of algorithms to these categories are based on */ private val AlgorithmIdToType: Map[String, Set[AlgorithmType.Value]] = Map( // Activity Algorithms: AlgorithmToFeedbackTokenMap(NewFollowingSimilarUser).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(Sims).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(NewFollowingSimilarUserSalsa).toString -> Set( AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(RecentEngagementNonDirectFollow).toString -> Set( AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(RecentEngagementSimilarUser).toString -> Set( AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(RecentEngagementSarusOcCur).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(RecentSearchBasedRec).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(TwistlyTweetAuthors).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(Follow2VecNearestNeighbors).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(EmailTweetClick).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(RepeatedProfileVisits).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(GoodTweetClickEngagements).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(TweetShareEngagements).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(TweetSharerToShareRecipientEngagements).toString -> Set( AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(TweetAuthorToShareRecipientEngagements).toString -> Set( AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(LinearRegressionFollow2VecNearestNeighbors).toString -> Set( AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(NUXLOHistory).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(TrafficAttributionAccounts).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(RealGraphOonV2).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(MagicRecsRecentEngagements).toString -> Set(AlgorithmType.Activity), AlgorithmToFeedbackTokenMap(NotificationEngagement).toString -> Set(AlgorithmType.Activity), // Social Algorithms: AlgorithmToFeedbackTokenMap(TwoHopRandomWalk).toString -> Set(AlgorithmType.Social), AlgorithmToFeedbackTokenMap(RealTimeMutualFollow).toString -> Set(AlgorithmType.Social), AlgorithmToFeedbackTokenMap(ForwardPhoneBook).toString -> Set(AlgorithmType.Social), AlgorithmToFeedbackTokenMap(ForwardEmailBook).toString -> Set(AlgorithmType.Social), AlgorithmToFeedbackTokenMap(NewFollowingNewFollowingExpansion).toString -> Set( AlgorithmType.Social), AlgorithmToFeedbackTokenMap(NewFollowingSarusCoOccurSocialProof).toString -> Set( AlgorithmType.Social), AlgorithmToFeedbackTokenMap(ReverseEmailBookIbis).toString -> Set(AlgorithmType.Social), AlgorithmToFeedbackTokenMap(ReversePhoneBook).toString -> Set(AlgorithmType.Social), AlgorithmToFeedbackTokenMap(StrongTiePredictionRec).toString -> Set(AlgorithmType.Social), AlgorithmToFeedbackTokenMap(StrongTiePredictionRecWithSocialProof).toString -> Set( AlgorithmType.Social), AlgorithmToFeedbackTokenMap(OnlineStrongTiePredictionRec).toString -> Set(AlgorithmType.Social), AlgorithmToFeedbackTokenMap(OnlineStrongTiePredictionRecNoCaching).toString -> Set( AlgorithmType.Social), AlgorithmToFeedbackTokenMap(TriangularLoop).toString -> Set(AlgorithmType.Social), AlgorithmToFeedbackTokenMap(StrongTiePredictionPmi).toString -> Set(AlgorithmType.Social), AlgorithmToFeedbackTokenMap(OnlineStrongTiePredictionRAB).toString -> Set(AlgorithmType.Social), // Geo Algorithms: AlgorithmToFeedbackTokenMap(PopCountryBackFill).toString -> Set(AlgorithmType.Geo), AlgorithmToFeedbackTokenMap(PopCountry).toString -> Set(AlgorithmType.Geo), AlgorithmToFeedbackTokenMap(PopGeohash).toString -> Set(AlgorithmType.Geo), // AlgorithmToFeedbackTokenMap(PopGeohashRealGraph).toString -> Set(AlgorithmType.Geo), AlgorithmToFeedbackTokenMap(EngagedFollowerRatio).toString -> Set(AlgorithmType.Geo), AlgorithmToFeedbackTokenMap(CrowdSearchAccounts).toString -> Set(AlgorithmType.Geo), AlgorithmToFeedbackTokenMap(OrganicFollowAccounts).toString -> Set(AlgorithmType.Geo), AlgorithmToFeedbackTokenMap(PopGeohashQualityFollow).toString -> Set(AlgorithmType.Geo), AlgorithmToFeedbackTokenMap(PPMILocaleFollow).toString -> Set(AlgorithmType.Geo), // Interest Algorithms: AlgorithmToFeedbackTokenMap(TttInterest).toString -> Set(AlgorithmType.Interest), AlgorithmToFeedbackTokenMap(UttInterestRelatedUsers).toString -> Set(AlgorithmType.Interest), AlgorithmToFeedbackTokenMap(UttSeedAccounts).toString -> Set(AlgorithmType.Interest), AlgorithmToFeedbackTokenMap(UttProducerExpansion).toString -> Set(AlgorithmType.Interest), // Hybrid (more than one type) Algorithms: AlgorithmToFeedbackTokenMap(UttProducerOfflineMbcgV1).toString -> Set( AlgorithmType.Interest, AlgorithmType.Geo), AlgorithmToFeedbackTokenMap(CuratedAccounts).toString -> Set( AlgorithmType.Interest, AlgorithmType.Geo), AlgorithmToFeedbackTokenMap(UserUserGraph).toString -> Set( AlgorithmType.Social, AlgorithmType.Activity), ) def getAlgorithmTypes(algoId: String): Set[String] = { AlgorithmIdToType.get(algoId).map(_.map(_.toString)).getOrElse(Set.empty) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants/GuiceNamedConstants.scala
package com.twitter.follow_recommendations.common.constants object GuiceNamedConstants { final val PRODUCER_SIDE_FEATURE_SWITCHES = "PRODUCER_SIDE_FEATURE_SWITCHES" final val CLIENT_EVENT_LOGGER = "CLIENT_EVENT_LOGGER" final val COSINE_FOLLOW_FETCHER = "cosine_follow_fetcher" final val COSINE_LIST_FETCHER = "cosine_list_fetcher" final val CURATED_CANDIDATES_FETCHER = "curated_candidates_fetcher" final val CURATED_COMPETITOR_ACCOUNTS_FETCHER = "curated_competitor_accounts_fetcher" final val POP_USERS_IN_PLACE_FETCHER = "pop_users_in_place_fetcher" final val PROFILE_SIDEBAR_BLACKLIST_SCANNER = "profile_sidebar_blacklist_scanner" final val REQUEST_LOGGER = "REQUEST_LOGGER" final val FLOW_LOGGER = "FLOW_LOGGER" final val REAL_TIME_INTERACTIONS_FETCHER = "real_time_interactions_fetcher" final val SIMS_FETCHER = "sims_fetcher" final val DBV2_SIMS_FETCHER = "dbv2_sims_fetcher" final val TRIANGULAR_LOOPS_FETCHER = "triangular_loops_fetcher" final val TWO_HOP_RANDOM_WALK_FETCHER = "two_hop_random_walk_fetcher" final val USER_RECOMMENDABILITY_FETCHER = "user_recommendability_fetcher" final val USER_STATE_FETCHER = "user_state_fetcher" final val UTT_ACCOUNT_RECOMMENDATIONS_FETCHER = "utt_account_recomendations_fetcher" final val UTT_SEED_ACCOUNTS_FETCHER = "utt_seed_accounts_fetcher" final val ELECTION_CANDIDATES_FETCHER = "election_candidates_fetcher" final val POST_NUX_WTF_FEATURES_FETCHER = "post_nux_wtf_features_fetcher" final val USER_USER_GRAPH_FETCHER = "user_user_graph_fetcher" final val DISMISS_STORE_SCANNER = "dismiss_store_scanner" final val LABELED_NOTIFICATION_FETCHER = "labeled_notification_scanner" final val STP_EP_SCORER = "stp_ep_scorer" final val STP_DBV2_SCORER = "stp_dbv2_scorer" final val STP_RAB_DBV2_SCORER = "stp_rab_dbv2_scorer" final val EXTENDED_NETWORK = "extended_network_candidates" // scoring client constants final val WTF_PROD_DEEPBIRDV2_CLIENT = "wtf_prod_deepbirdv2_client" // ann clients final val RELATABLE_ACCOUNTS_FETCHER = "relatable_accounts_fetcher" }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/constants/ServiceConstants.scala
package com.twitter.follow_recommendations.common.constants import com.twitter.conversions.StorageUnitOps._ object ServiceConstants { /** thrift client response size limits * these were estimated using monitoring dashboard * 3MB network usage per second / 25 rps ~ 120KB/req << 1MB * we give some buffer here in case some requests require more data than others */ val StringLengthLimit: Long = 10.megabyte.inBytes val ContainerLengthLimit: Long = 1.megabyte.inBytes }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/adapters/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ ":candidate-algorithm-adapter", ":client-context-adapter", ":post-nux-algorithm-adapter", ":pre-fetched-feature-adapter", ], ) target( name = "common", tags = ["bazel-compatible"], dependencies = [ "3rdparty/jvm/org/slf4j:slf4j-api", "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/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/common", "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", "src/java/com/twitter/ml/api:api-base", "src/scala/com/twitter/ml/api/util", "src/scala/com/twitter/onboarding/relevance/util/metadata", "util/util-slf4j-api/src/main/scala", ], ) scala_library( name = "candidate-algorithm-adapter", sources = [ "CandidateAlgorithmAdapter.scala", ], compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ ":common", "hermit/hermit-core/src/main/scala/com/twitter/hermit/constants", ], ) scala_library( name = "client-context-adapter", sources = [ "ClientContextAdapter.scala", ], compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ ":common", "snowflake/src/main/scala/com/twitter/snowflake/id", ], ) scala_library( name = "post-nux-algorithm-adapter", sources = [ "PostNuxAlgorithmAdapter.scala", ], platform = "java8", tags = ["bazel-compatible"], dependencies = [ ":common", "src/scala/com/twitter/ml/featurestore/catalog/features/customer_journey:post-nux-algorithm-aggregate", ], ) scala_library( name = "pre-fetched-feature-adapter", sources = [ "PreFetchedFeatureAdapter.scala", ], platform = "java8", tags = ["bazel-compatible"], dependencies = [ ":common", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/adapters/CandidateAlgorithmAdapter.scala
package com.twitter.follow_recommendations.common.feature_hydration.adapters import com.twitter.follow_recommendations.common.models.UserCandidateSourceDetails import com.twitter.hermit.constants.AlgorithmFeedbackTokens.AlgorithmToFeedbackTokenMap import com.twitter.hermit.model.Algorithm import com.twitter.hermit.model.Algorithm.Algorithm import com.twitter.hermit.model.Algorithm.UttProducerOfflineMbcgV1 import com.twitter.hermit.model.Algorithm.UttProducerOnlineMbcgV1 import com.twitter.ml.api.DataRecord import com.twitter.ml.api.Feature.SparseBinary import com.twitter.ml.api.Feature.SparseContinuous import com.twitter.ml.api.FeatureContext import com.twitter.ml.api.IRecordOneToOneAdapter import com.twitter.ml.api.util.FDsl._ object CandidateAlgorithmAdapter extends IRecordOneToOneAdapter[Option[UserCandidateSourceDetails]] { val CANDIDATE_ALGORITHMS: SparseBinary = new SparseBinary("candidate.source.algorithm_ids") val CANDIDATE_SOURCE_SCORES: SparseContinuous = new SparseContinuous("candidate.source.scores") val CANDIDATE_SOURCE_RANKS: SparseContinuous = new SparseContinuous("candidate.source.ranks") override val getFeatureContext: FeatureContext = new FeatureContext( CANDIDATE_ALGORITHMS, CANDIDATE_SOURCE_SCORES, CANDIDATE_SOURCE_RANKS ) /** list of candidate source remaps to avoid creating different features for experimental sources. * the LHS should contain the experimental source, and the RHS should contain the prod source. */ def remapCandidateSource(a: Algorithm): Algorithm = a match { case UttProducerOnlineMbcgV1 => UttProducerOfflineMbcgV1 case _ => a } // add the list of algorithm feedback tokens (integers) as a sparse binary feature override def adaptToDataRecord( userCandidateSourceDetailsOpt: Option[UserCandidateSourceDetails] ): DataRecord = { val dr = new DataRecord() userCandidateSourceDetailsOpt.foreach { userCandidateSourceDetails => val scoreMap = for { (source, scoreOpt) <- userCandidateSourceDetails.candidateSourceScores score <- scoreOpt algo <- Algorithm.withNameOpt(source.name) algoId <- AlgorithmToFeedbackTokenMap.get(remapCandidateSource(algo)) } yield algoId.toString -> score val rankMap = for { (source, rank) <- userCandidateSourceDetails.candidateSourceRanks algo <- Algorithm.withNameOpt(source.name) algoId <- AlgorithmToFeedbackTokenMap.get(remapCandidateSource(algo)) } yield algoId.toString -> rank.toDouble val algoIds = scoreMap.keys.toSet ++ rankMap.keys.toSet // hydrate if not empty if (rankMap.nonEmpty) { dr.setFeatureValue(CANDIDATE_SOURCE_RANKS, rankMap) } if (scoreMap.nonEmpty) { dr.setFeatureValue(CANDIDATE_SOURCE_SCORES, scoreMap) } if (algoIds.nonEmpty) { dr.setFeatureValue(CANDIDATE_ALGORITHMS, algoIds) } } dr } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/adapters/ClientContextAdapter.scala
package com.twitter.follow_recommendations.common.feature_hydration.adapters import com.twitter.follow_recommendations.common.models.DisplayLocation import com.twitter.ml.api.Feature.Binary import com.twitter.ml.api.Feature.Continuous import com.twitter.ml.api.Feature.Discrete import com.twitter.ml.api.Feature.Text import com.twitter.ml.api.util.FDsl._ import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.ml.api.IRecordOneToOneAdapter import com.twitter.onboarding.relevance.util.metadata.LanguageUtil import com.twitter.product_mixer.core.model.marshalling.request.ClientContext import com.twitter.snowflake.id.SnowflakeId object ClientContextAdapter extends IRecordOneToOneAdapter[(ClientContext, DisplayLocation)] { // we name features with `user.account` for relatively static user-related features val USER_COUNTRY: Text = new Text("user.account.country") val USER_LANGUAGE: Text = new Text("user.account.language") // we name features with `user.context` for more dynamic user-related features val USER_LANGUAGE_PREFIX: Text = new Text("user.context.language_prefix") val USER_CLIENT: Discrete = new Discrete("user.context.client") val USER_AGE: Continuous = new Continuous("user.context.age") val USER_IS_RECENT: Binary = new Binary("user.is.recent") // we name features with `meta` for meta info about the WTF recommendation request val META_DISPLAY_LOCATION: Text = new Text("meta.display_location") val META_POSITION: Discrete = new Discrete("meta.position") // This indicates whether a data point is from a random serving policy val META_IS_RANDOM: Binary = new Binary("prediction.engine.is_random") val RECENT_WIN_IN_DAYS: Int = 30 val GOAL_META_POSITION: Long = 1L val GOAL_META_IS_RANDOM: Boolean = true override val getFeatureContext: FeatureContext = new FeatureContext( USER_COUNTRY, USER_LANGUAGE, USER_AGE, USER_LANGUAGE_PREFIX, USER_CLIENT, USER_IS_RECENT, META_DISPLAY_LOCATION, META_POSITION, META_IS_RANDOM ) /** * we only want to set the relevant fields iff they exist to eliminate redundant information * we do some simple normalization on the language code * we set META_POSITION to 1 always * we set META_IS_RANDOM to true always to simulate a random serving distribution * @param record ClientContext and DisplayLocation from the request */ override def adaptToDataRecord(target: (ClientContext, DisplayLocation)): DataRecord = { val dr = new DataRecord() val cc = target._1 val dl = target._2 cc.countryCode.foreach(countryCode => dr.setFeatureValue(USER_COUNTRY, countryCode)) cc.languageCode.foreach(rawLanguageCode => { val userLanguage = LanguageUtil.simplifyLanguage(rawLanguageCode) val userLanguagePrefix = userLanguage.take(2) dr.setFeatureValue(USER_LANGUAGE, userLanguage) dr.setFeatureValue(USER_LANGUAGE_PREFIX, userLanguagePrefix) }) cc.appId.foreach(appId => dr.setFeatureValue(USER_CLIENT, appId)) cc.userId.foreach(id => SnowflakeId.timeFromIdOpt(id).map { signupTime => val userAge = signupTime.untilNow.inMillis.toDouble dr.setFeatureValue(USER_AGE, userAge) dr.setFeatureValue(USER_IS_RECENT, signupTime.untilNow.inDays <= RECENT_WIN_IN_DAYS) signupTime.untilNow.inDays }) dr.setFeatureValue(META_DISPLAY_LOCATION, dl.toFsName) dr.setFeatureValue(META_POSITION, GOAL_META_POSITION) dr.setFeatureValue(META_IS_RANDOM, GOAL_META_IS_RANDOM) dr } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/adapters/PostNuxAlgorithmAdapter.scala
package com.twitter.follow_recommendations.common.feature_hydration.adapters import com.twitter.ml.api.DataRecord import com.twitter.ml.api.Feature import com.twitter.ml.api.Feature.Continuous import com.twitter.ml.api.FeatureContext import com.twitter.ml.api.IRecordOneToOneAdapter import com.twitter.ml.api.util.FDsl._ import com.twitter.ml.featurestore.catalog.features.customer_journey.PostNuxAlgorithmFeatures import com.twitter.ml.featurestore.catalog.features.customer_journey.PostNuxAlgorithmIdAggregateFeatureGroup import com.twitter.ml.featurestore.catalog.features.customer_journey.PostNuxAlgorithmTypeAggregateFeatureGroup import scala.collection.JavaConverters._ object PostNuxAlgorithmIdAdapter extends PostNuxAlgorithmAdapter { override val PostNuxAlgorithmFeatureGroup: PostNuxAlgorithmFeatures = PostNuxAlgorithmIdAggregateFeatureGroup // To keep the length of feature names reasonable, we remove the prefix added by FeatureStore. override val FeatureStorePrefix: String = "wtf_algorithm_id.customer_journey.post_nux_algorithm_id_aggregate_feature_group." } object PostNuxAlgorithmTypeAdapter extends PostNuxAlgorithmAdapter { override val PostNuxAlgorithmFeatureGroup: PostNuxAlgorithmFeatures = PostNuxAlgorithmTypeAggregateFeatureGroup // To keep the length of feature names reasonable, we remove the prefix added by FeatureStore. override val FeatureStorePrefix: String = "wtf_algorithm_type.customer_journey.post_nux_algorithm_type_aggregate_feature_group." } trait PostNuxAlgorithmAdapter extends IRecordOneToOneAdapter[DataRecord] { val PostNuxAlgorithmFeatureGroup: PostNuxAlgorithmFeatures // The string that is attached to the feature name when it is fetched from feature store. val FeatureStorePrefix: String /** * * This stores transformed aggregate features for PostNux algorithm aggregate features. The * transformation here is log-ratio, where ratio is the raw value divided by # of impressions. */ case class TransformedAlgorithmFeatures( ratioLog: Continuous) { def getFeatures: Seq[Continuous] = Seq(ratioLog) } private def applyFeatureStorePrefix(feature: Continuous) = new Continuous( s"$FeatureStorePrefix${feature.getFeatureName}") // The list of input features WITH the prefix assigned to them by FeatureStore. lazy val allInputFeatures: Seq[Seq[Continuous]] = Seq( PostNuxAlgorithmFeatureGroup.Aggregate7DayFeatures.map(applyFeatureStorePrefix), PostNuxAlgorithmFeatureGroup.Aggregate30DayFeatures.map(applyFeatureStorePrefix) ) // This is a list of the features WITHOUT the prefix assigned to them by FeatureStore. lazy val outputBaseFeatureNames: Seq[Seq[Continuous]] = Seq( PostNuxAlgorithmFeatureGroup.Aggregate7DayFeatures, PostNuxAlgorithmFeatureGroup.Aggregate30DayFeatures ) // We use backend impression to calculate ratio values. lazy val ratioDenominators: Seq[Continuous] = Seq( applyFeatureStorePrefix(PostNuxAlgorithmFeatureGroup.BackendImpressions7Days), applyFeatureStorePrefix(PostNuxAlgorithmFeatureGroup.BackendImpressions30Days) ) /** * A mapping from an original feature's ID to the corresponding set of transformed features. * This is used to compute the transformed features for each of the original ones. */ private lazy val TransformedFeaturesMap: Map[Continuous, TransformedAlgorithmFeatures] = outputBaseFeatureNames.flatten.map { feature => ( // The input feature would have the FeatureStore prefix attached to it. new Continuous(s"$FeatureStorePrefix${feature.getFeatureName}"), // We don't keep the FeatureStore prefix to keep the length of feature names reasonable. TransformedAlgorithmFeatures( new Continuous(s"${feature.getFeatureName}-ratio-log") )) }.toMap /** * Given a denominator, number of impressions, this function returns another function that adds * transformed features (log1p and ratio) of an input feature to a DataRecord. */ private def addTransformedFeaturesToDataRecordFunc( originalDr: DataRecord, numImpressions: Double, ): (DataRecord, Continuous) => DataRecord = { (record: DataRecord, feature: Continuous) => { Option(originalDr.getFeatureValue(feature)) foreach { featureValue => TransformedFeaturesMap.get(feature).foreach { transformedFeatures => record.setFeatureValue( transformedFeatures.ratioLog, // We don't use log1p here since the values are ratios and adding 1 to the _ratio_ would // lead to logarithm of values between 1 and 2, essentially making all values the same. math.log((featureValue + 1) / numImpressions) ) } } record } } /** * @param record: The input record whose PostNuxAlgorithm aggregates are to be transformed. * @return the input [[DataRecord]] with transformed aggregates added. */ override def adaptToDataRecord(record: DataRecord): DataRecord = { if (record.continuousFeatures == null) { // There are no base features available, and hence no transformations. record } else { /** * The `foldLeft` below goes through pairs of (1) Feature groups, such as those calculated over * 7 days or 30 days, and (2) the number of impressions for each of these groups, which is the * denominator when ratio is calculated. */ ratioDenominators .zip(allInputFeatures).foldLeft( /* initial empty DataRecord */ record)( ( /* DataRecord with transformed features up to here */ transformedRecord, /* A tuple with the denominator (#impressions) and features to be transformed */ numImpressionsAndFeatures ) => { val (numImpressionsFeature, features) = numImpressionsAndFeatures Option(record.getFeatureValue(numImpressionsFeature)) match { case Some(numImpressions) if numImpressions > 0.0 => /** * With the number of impressions fixed, we generate a function that adds log-ratio * for each feature in the current [[DataRecord]]. The `foldLeft` goes through all * such features and applies that function while updating the kept DataRecord. */ features.foldLeft(transformedRecord)( addTransformedFeaturesToDataRecordFunc(record, numImpressions)) case _ => transformedRecord } }) } } def getFeatures: Seq[Feature[_]] = TransformedFeaturesMap.values.flatMap(_.getFeatures).toSeq override def getFeatureContext: FeatureContext = new FeatureContext() .addFeatures(this.getFeatures.asJava) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/adapters/PreFetchedFeatureAdapter.scala
package com.twitter.follow_recommendations.common.feature_hydration.adapters import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.ml.api.Feature.Continuous import com.twitter.ml.api.util.FDsl._ import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.ml.api.IRecordOneToOneAdapter import com.twitter.util.Time /** * This adapter mimics UserRecentWTFImpressionsAndFollowsAdapter (for user) and * RecentWTFImpressionsFeatureAdapter (for candidate) for extracting recent impression * and follow features. This adapter extracts user, candidate, and pair-wise features. */ object PreFetchedFeatureAdapter extends IRecordOneToOneAdapter[ (HasPreFetchedFeature, CandidateUser) ] { // impression features val USER_NUM_RECENT_IMPRESSIONS: Continuous = new Continuous( "user.prefetch.num_recent_impressions" ) val USER_LAST_IMPRESSION_DURATION: Continuous = new Continuous( "user.prefetch.last_impression_duration" ) val CANDIDATE_NUM_RECENT_IMPRESSIONS: Continuous = new Continuous( "user-candidate.prefetch.num_recent_impressions" ) val CANDIDATE_LAST_IMPRESSION_DURATION: Continuous = new Continuous( "user-candidate.prefetch.last_impression_duration" ) // follow features val USER_NUM_RECENT_FOLLOWERS: Continuous = new Continuous( "user.prefetch.num_recent_followers" ) val USER_NUM_RECENT_FOLLOWED_BY: Continuous = new Continuous( "user.prefetch.num_recent_followed_by" ) val USER_NUM_RECENT_MUTUAL_FOLLOWS: Continuous = new Continuous( "user.prefetch.num_recent_mutual_follows" ) // impression + follow features val USER_NUM_RECENT_FOLLOWED_IMPRESSIONS: Continuous = new Continuous( "user.prefetch.num_recent_followed_impression" ) val USER_LAST_FOLLOWED_IMPRESSION_DURATION: Continuous = new Continuous( "user.prefetch.last_followed_impression_duration" ) override def adaptToDataRecord( record: (HasPreFetchedFeature, CandidateUser) ): DataRecord = { val (target, candidate) = record val dr = new DataRecord() val t = Time.now // set impression features for user, optionally for candidate dr.setFeatureValue(USER_NUM_RECENT_IMPRESSIONS, target.numWtfImpressions.toDouble) dr.setFeatureValue( USER_LAST_IMPRESSION_DURATION, (t - target.latestImpressionTime).inMillis.toDouble) target.getCandidateImpressionCounts(candidate.id).foreach { counts => dr.setFeatureValue(CANDIDATE_NUM_RECENT_IMPRESSIONS, counts.toDouble) } target.getCandidateLatestTime(candidate.id).foreach { latestTime: Time => dr.setFeatureValue(CANDIDATE_LAST_IMPRESSION_DURATION, (t - latestTime).inMillis.toDouble) } // set recent follow features for user dr.setFeatureValue(USER_NUM_RECENT_FOLLOWERS, target.numRecentFollowedUserIds.toDouble) dr.setFeatureValue(USER_NUM_RECENT_FOLLOWED_BY, target.numRecentFollowedByUserIds.toDouble) dr.setFeatureValue(USER_NUM_RECENT_MUTUAL_FOLLOWS, target.numRecentMutualFollows.toDouble) dr.setFeatureValue(USER_NUM_RECENT_FOLLOWED_IMPRESSIONS, target.numFollowedImpressions.toDouble) dr.setFeatureValue( USER_LAST_FOLLOWED_IMPRESSION_DURATION, target.lastFollowedImpressionDurationMs.getOrElse(Long.MaxValue).toDouble) dr } override def getFeatureContext: FeatureContext = new FeatureContext( USER_NUM_RECENT_IMPRESSIONS, USER_LAST_IMPRESSION_DURATION, CANDIDATE_NUM_RECENT_IMPRESSIONS, CANDIDATE_LAST_IMPRESSION_DURATION, USER_NUM_RECENT_FOLLOWERS, USER_NUM_RECENT_FOLLOWED_BY, USER_NUM_RECENT_MUTUAL_FOLLOWS, USER_NUM_RECENT_FOLLOWED_IMPRESSIONS, USER_LAST_FOLLOWED_IMPRESSION_DURATION, ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/common/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/utils", "src/java/com/twitter/ml/api:api-base", "util/util-slf4j-api/src/main/scala", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/common/FeatureSource.scala
package com.twitter.follow_recommendations.common.feature_hydration.common import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams trait FeatureSource { def id: FeatureSourceId def featureContext: FeatureContext def hydrateFeatures( target: HasClientContext with HasPreFetchedFeature with HasParams with HasSimilarToContext with HasDisplayLocation, candidates: Seq[CandidateUser] ): Stitch[Map[CandidateUser, DataRecord]] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/common/FeatureSourceId.scala
package com.twitter.follow_recommendations.common.feature_hydration.common sealed trait FeatureSourceId object FeatureSourceId { object CandidateAlgorithmSourceId extends FeatureSourceId object ClientContextSourceId extends FeatureSourceId object FeatureStoreSourceId extends FeatureSourceId object FeatureStoreTimelinesAuthorSourceId extends FeatureSourceId object FeatureStoreGizmoduckSourceId extends FeatureSourceId object FeatureStoreUserMetricCountsSourceId extends FeatureSourceId object FeatureStoreNotificationSourceId extends FeatureSourceId object FeatureStorePrecomputedNotificationSourceId extends FeatureSourceId object FeatureStorePostNuxAlgorithmSourceId extends FeatureSourceId @deprecated object StratoFeatureHydrationSourceId extends FeatureSourceId object PreFetchedFeatureSourceId extends FeatureSourceId object UserScoringFeatureSourceId extends FeatureSourceId }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/common/HasPreFetchedFeature.scala
package com.twitter.follow_recommendations.common.feature_hydration.common import com.twitter.follow_recommendations.common.models.HasMutualFollowedUserIds import com.twitter.follow_recommendations.common.models.HasWtfImpressions import com.twitter.follow_recommendations.common.models.WtfImpression import com.twitter.util.Time trait HasPreFetchedFeature extends HasMutualFollowedUserIds with HasWtfImpressions { lazy val followedImpressions: Seq[WtfImpression] = { for { wtfImprList <- wtfImpressions.toSeq wtfImpr <- wtfImprList if recentFollowedUserIds.exists(_.contains(wtfImpr.candidateId)) } yield wtfImpr } lazy val numFollowedImpressions: Int = followedImpressions.size lazy val lastFollowedImpressionDurationMs: Option[Long] = { if (followedImpressions.nonEmpty) { Some((Time.now - followedImpressions.map(_.latestTime).max).inMillis) } else None } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/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/constants", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/adapters", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/common", "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/common", "hermit/hermit-core/src/main/scala/com/twitter/hermit/constants", "src/java/com/twitter/ml/api:api-base", "src/scala/com/twitter/ml/featurestore/catalog/datasets/core:socialgraph", "src/scala/com/twitter/ml/featurestore/catalog/datasets/core:usersource", "src/scala/com/twitter/ml/featurestore/catalog/datasets/onboarding:mc-user-counting", "src/scala/com/twitter/ml/featurestore/catalog/datasets/onboarding:user-wtf-algorithm-aggregate", "src/scala/com/twitter/ml/featurestore/catalog/datasets/onboarding:wtf-impression", "src/scala/com/twitter/ml/featurestore/catalog/datasets/onboarding:wtf-post-nux", "src/scala/com/twitter/ml/featurestore/catalog/datasets/onboarding:wtf-user-algorithm-aggregate", "src/scala/com/twitter/ml/featurestore/catalog/datasets/timelines:timelines-author-features", "src/scala/com/twitter/ml/featurestore/catalog/entities/core", "src/scala/com/twitter/ml/featurestore/catalog/entities/onboarding", "src/scala/com/twitter/ml/featurestore/catalog/features/core:socialgraph", "src/scala/com/twitter/ml/featurestore/catalog/features/core:user", "src/scala/com/twitter/ml/featurestore/catalog/features/interests_discovery:user-topic-relationships", "src/scala/com/twitter/ml/featurestore/catalog/features/magicrecs:non-mr-notif-summmaries", "src/scala/com/twitter/ml/featurestore/catalog/features/magicrecs:non-mr-notif-summmary-aggregates", "src/scala/com/twitter/ml/featurestore/catalog/features/magicrecs:nonmr-ntab-summaries", "src/scala/com/twitter/ml/featurestore/catalog/features/onboarding:mc-user-counting", "src/scala/com/twitter/ml/featurestore/catalog/features/onboarding:post-nux-offline", "src/scala/com/twitter/ml/featurestore/catalog/features/onboarding:post-nux-offline-edge", "src/scala/com/twitter/ml/featurestore/catalog/features/onboarding:ratio", "src/scala/com/twitter/ml/featurestore/catalog/features/onboarding:simcluster-user-interested-in-candidate-known-for", "src/scala/com/twitter/ml/featurestore/catalog/features/onboarding:user-wtf-algorithm-aggregate", "src/scala/com/twitter/ml/featurestore/catalog/features/onboarding:wtf-impression", "src/scala/com/twitter/ml/featurestore/catalog/features/onboarding:wtf-user-algorithm-aggregate", "src/scala/com/twitter/ml/featurestore/catalog/features/rux:user-resurrection", "src/scala/com/twitter/ml/featurestore/catalog/features/timelines:aggregate", "src/scala/com/twitter/ml/featurestore/lib", "src/scala/com/twitter/ml/featurestore/lib/dynamic", "src/scala/com/twitter/ml/featurestore/lib/embedding", "src/scala/com/twitter/ml/featurestore/lib/feature", "src/scala/com/twitter/ml/featurestore/lib/online", "src/scala/com/twitter/ml/featurestore/lib/params", "src/scala/com/twitter/onboarding/relevance/adapters/features/featurestore", "strato/config/columns/ml/featureStore:featureStore-strato-client", "strato/config/columns/ml/featureStore/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/feature_hydration/sources/CandidateAlgorithmSource.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.google.inject.Inject import com.google.inject.Provides import com.google.inject.Singleton import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.feature_hydration.adapters.CandidateAlgorithmAdapter import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSource import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSourceId import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams /** * This source only takes features from the candidate's source, * which is all the information we have about the candidate pre-feature-hydration */ @Provides @Singleton class CandidateAlgorithmSource @Inject() (stats: StatsReceiver) extends FeatureSource { override val id: FeatureSourceId = FeatureSourceId.CandidateAlgorithmSourceId override val featureContext: FeatureContext = CandidateAlgorithmAdapter.getFeatureContext override def hydrateFeatures( t: HasClientContext with HasPreFetchedFeature with HasParams with HasSimilarToContext with HasDisplayLocation, // we don't use the target here candidates: Seq[CandidateUser] ): Stitch[Map[CandidateUser, DataRecord]] = { val featureHydrationStats = stats.scope("candidate_alg_source") val hasSourceDetailsStat = featureHydrationStats.counter("has_source_details") val noSourceDetailsStat = featureHydrationStats.counter("no_source_details") val noSourceRankStat = featureHydrationStats.counter("no_source_rank") val hasSourceRankStat = featureHydrationStats.counter("has_source_rank") val noSourceScoreStat = featureHydrationStats.counter("no_source_score") val hasSourceScoreStat = featureHydrationStats.counter("has_source_score") val candidatesToAlgoMap = for { candidate <- candidates } yield { if (candidate.userCandidateSourceDetails.nonEmpty) { hasSourceDetailsStat.incr() candidate.userCandidateSourceDetails.foreach { details => if (details.candidateSourceRanks.isEmpty) { noSourceRankStat.incr() } else { hasSourceRankStat.incr() } if (details.candidateSourceScores.isEmpty) { noSourceScoreStat.incr() } else { hasSourceScoreStat.incr() } } } else { noSourceDetailsStat.incr() } candidate -> CandidateAlgorithmAdapter.adaptToDataRecord(candidate.userCandidateSourceDetails) } Stitch.value(candidatesToAlgoMap.toMap) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/ClientContextSource.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.google.inject.Provides import com.google.inject.Singleton import com.twitter.follow_recommendations.common.feature_hydration.adapters.ClientContextAdapter import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSource import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSourceId import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams /** * This source only takes features from the request (e.g. client context, WTF display location) * No external calls are made. */ @Provides @Singleton class ClientContextSource() extends FeatureSource { override val id: FeatureSourceId = FeatureSourceId.ClientContextSourceId override val featureContext: FeatureContext = ClientContextAdapter.getFeatureContext override def hydrateFeatures( t: HasClientContext with HasPreFetchedFeature with HasParams with HasSimilarToContext with HasDisplayLocation, candidates: Seq[CandidateUser] ): Stitch[Map[CandidateUser, DataRecord]] = { Stitch.value( candidates .map(_ -> ((t.clientContext, t.displayLocation))).toMap.mapValues( ClientContextAdapter.adaptToDataRecord)) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/FeatureHydrationSourcesFSConfig.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.FSName import com.twitter.timelines.configapi.HasDurationConversion import com.twitter.timelines.configapi.Param import com.twitter.util.Duration import javax.inject.Inject import javax.inject.Singleton @Singleton class FeatureHydrationSourcesFSConfig @Inject() () extends FeatureSwitchConfig { override val booleanFSParams: Seq[Param[Boolean] with FSName] = Seq( FeatureStoreSourceParams.EnableAlgorithmAggregateFeatures, FeatureStoreSourceParams.EnableAuthorTopicAggregateFeatures, FeatureStoreSourceParams.EnableCandidateClientFeatures, FeatureStoreSourceParams.EnableCandidatePrecomputedNotificationFeatures, FeatureStoreSourceParams.EnableCandidateUserAuthorRealTimeAggregateFeatures, FeatureStoreSourceParams.EnableCandidateUserFeatures, FeatureStoreSourceParams.EnableCandidateUserResurrectionFeatures, FeatureStoreSourceParams.EnableCandidateUserTimelinesAuthorAggregateFeatures, FeatureStoreSourceParams.EnableSeparateClientForTimelinesAuthors, FeatureStoreSourceParams.EnableSeparateClientForGizmoduck, FeatureStoreSourceParams.EnableSeparateClientForMetricCenterUserCounting, FeatureStoreSourceParams.EnableSeparateClientForNotifications, FeatureStoreSourceParams.EnableSimilarToUserFeatures, FeatureStoreSourceParams.EnableTargetUserFeatures, FeatureStoreSourceParams.EnableTargetUserResurrectionFeatures, FeatureStoreSourceParams.EnableTargetUserWtfImpressionFeatures, FeatureStoreSourceParams.EnableTopicAggregateFeatures, FeatureStoreSourceParams.EnableUserCandidateEdgeFeatures, FeatureStoreSourceParams.EnableUserCandidateWtfImpressionCandidateFeatures, FeatureStoreSourceParams.EnableUserClientFeatures, FeatureStoreSourceParams.EnableUserTopicFeatures, FeatureStoreSourceParams.EnableUserWtfAlgEdgeFeatures, ) override val durationFSParams: Seq[FSBoundedParam[Duration] with HasDurationConversion] = Seq( FeatureStoreSourceParams.GlobalFetchTimeout ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/FeatureHydrationSourcesFeatureSwitchKeys.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources object FeatureHydrationSourcesFeatureSwitchKeys { val EnableAlgorithmAggregateFeatures = "feature_store_source_enable_algorithm_aggregate_features" val EnableAuthorTopicAggregateFeatures = "feature_store_source_enable_author_topic_aggregate_features" val EnableCandidateClientFeatures = "feature_store_source_enable_candidate_client_features" val EnableCandidateNotificationFeatures = "feature_store_source_enable_candidate_notification_features" val EnableCandidatePrecomputedNotificationFeatures = "feature_store_source_enable_candidate_precomputed_notification_features" val EnableCandidateUserFeatures = "feature_store_source_enable_candidate_user_features" val EnableCandidateUserAuthorRealTimeAggregateFeatures = "feature_store_source_enable_candidate_user_author_rta_features" val EnableCandidateUserResurrectionFeatures = "feature_store_source_enable_candidate_user_resurrection_features" val EnableCandidateUserTimelinesAuthorAggregateFeatures = "feature_store_source_enable_candidate_user_timelines_author_aggregate_features" val EnableSimilarToUserFeatures = "feature_store_source_enable_similar_to_user_features" val EnableTargetUserFeatures = "feature_store_source_enable_target_user_features" val EnableTargetUserUserAuthorUserStateRealTimeAggregatesFeature = "feature_store_source_enable_target_user_user_author_user_state_rta_features" val EnableTargetUserResurrectionFeatures = "feature_store_source_enable_target_user_resurrection_features" val EnableTargetUserWtfImpressionFeatures = "feature_store_source_enable_target_user_wtf_impression_features" val EnableTopicAggregateFeatures = "feature_store_source_enable_topic_aggregate_features" val EnableUserCandidateEdgeFeatures = "feature_store_source_enable_user_candidate_edge_features" val EnableUserCandidateWtfImpressionCandidateFeatures = "feature_store_source_enable_user_candidate_wtf_impression_features" val EnableUserClientFeatures = "feature_store_source_enable_user_client_features" val EnableUserNotificationFeatures = "feature_store_source_enable_user_notification_features" val EnableUserTopicFeatures = "feature_store_source_enable_user_topic_features" val EnableUserWtfAlgEdgeFeatures = "feature_store_source_enable_user_wtf_alg_edge_features" val FeatureHydrationTimeout = "feature_store_source_hydration_timeout_in_millis" val UseSeparateClientForTimelinesAuthor = "feature_store_source_separate_client_for_timelines_author_data" val UseSeparateClientMetricCenterUserCounting = "feature_store_source_separate_client_for_mc_user_counting_data" val UseSeparateClientForNotifications = "feature_store_source_separate_client_for_notifications" val UseSeparateClientForGizmoduck = "feature_store_source_separate_client_for_gizmoduck" }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/FeatureStoreFeatures.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.ml.featurestore.catalog.entities.core.{Author => AuthorEntity} import com.twitter.ml.featurestore.catalog.entities.core.{AuthorTopic => AuthorTopicEntity} import com.twitter.ml.featurestore.catalog.entities.core.{CandidateUser => CandidateUserEntity} import com.twitter.ml.featurestore.catalog.entities.core.{Topic => TopicEntity} import com.twitter.ml.featurestore.catalog.entities.core.{User => UserEntity} import com.twitter.ml.featurestore.catalog.entities.core.{UserCandidate => UserCandidateEntity} import com.twitter.ml.featurestore.catalog.entities.onboarding.UserWtfAlgorithmEntity import com.twitter.ml.featurestore.catalog.entities.onboarding.{ WtfAlgorithm => WtfAlgorithmIdEntity } import com.twitter.ml.featurestore.catalog.entities.onboarding.{ WtfAlgorithmType => WtfAlgorithmTypeEntity } import com.twitter.ml.featurestore.catalog.features.core.UserClients.FullPrimaryClientVersion import com.twitter.ml.featurestore.catalog.features.core.UserClients.NumClients import com.twitter.ml.featurestore.catalog.features.core.UserClients.PrimaryClient import com.twitter.ml.featurestore.catalog.features.core.UserClients.PrimaryClientVersion import com.twitter.ml.featurestore.catalog.features.core.UserClients.PrimaryDeviceManufacturer import com.twitter.ml.featurestore.catalog.features.core.UserClients.PrimaryMobileSdkVersion import com.twitter.ml.featurestore.catalog.features.core.UserClients.SecondaryClient import com.twitter.ml.featurestore.catalog.features.core.UserCounts.Favorites import com.twitter.ml.featurestore.catalog.features.core.UserCounts.Followers import com.twitter.ml.featurestore.catalog.features.core.UserCounts.Following import com.twitter.ml.featurestore.catalog.features.core.UserCounts.Tweets import com.twitter.ml.featurestore.catalog.features.customer_journey.PostNuxAlgorithmIdAggregateFeatureGroup import com.twitter.ml.featurestore.catalog.features.customer_journey.PostNuxAlgorithmTypeAggregateFeatureGroup import com.twitter.ml.featurestore.catalog.features.customer_journey.{Utils => FeatureGroupUtils} import com.twitter.ml.featurestore.catalog.features.interests_discovery.UserTopicRelationships.FollowedTopics import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumFavorites import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumFavoritesReceived import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumFollowBacks import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumFollows import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumFollowsReceived import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumLoginDays import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumLoginTweetImpressions import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumMuteBacks import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumMuted import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumOriginalTweets import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumQualityFollowReceived import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumQuoteRetweets import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumQuoteRetweetsReceived import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumReplies import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumRepliesReceived import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumRetweets import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumRetweetsReceived import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumSpamBlocked import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumSpamBlockedBacks import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumTweetImpressions import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumTweets import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumUnfollowBacks import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumUnfollows import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumUserActiveMinutes import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumWasMutualFollowed import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumWasMutualUnfollowed import com.twitter.ml.featurestore.catalog.features.onboarding.MetricCenterUserCounts.NumWasUnfollowed import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOffline.Country import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOffline.FollowersOverFollowingRatio import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOffline.Language import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOffline.MutualFollowsOverFollowersRatio import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOffline.MutualFollowsOverFollowingRatio import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOffline.NumFollowers import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOffline.NumFollowings import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOffline.NumMutualFollows import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOffline.TweepCred import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOffline.UserState import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOfflineEdge.HaveSameCountry import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOfflineEdge.HaveSameLanguage import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOfflineEdge.HaveSameUserState import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOfflineEdge.NumFollowersGap import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOfflineEdge.NumFollowingsGap import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOfflineEdge.NumMutualFollowsGap import com.twitter.ml.featurestore.catalog.features.onboarding.PostNuxOfflineEdge.TweepCredGap import com.twitter.ml.featurestore.catalog.features.onboarding.Ratio.FollowersFollowings import com.twitter.ml.featurestore.catalog.features.onboarding.Ratio.MutualFollowsFollowing import com.twitter.ml.featurestore.catalog.features.onboarding.SimclusterUserInterestedInCandidateKnownFor.HasIntersection import com.twitter.ml.featurestore.catalog.features.onboarding.SimclusterUserInterestedInCandidateKnownFor.IntersectionCandidateKnownForScore import com.twitter.ml.featurestore.catalog.features.onboarding.SimclusterUserInterestedInCandidateKnownFor.IntersectionClusterIds import com.twitter.ml.featurestore.catalog.features.onboarding.SimclusterUserInterestedInCandidateKnownFor.IntersectionUserFavCandidateKnownForScore import com.twitter.ml.featurestore.catalog.features.onboarding.SimclusterUserInterestedInCandidateKnownFor.IntersectionUserFavScore import com.twitter.ml.featurestore.catalog.features.onboarding.SimclusterUserInterestedInCandidateKnownFor.IntersectionUserFollowCandidateKnownForScore import com.twitter.ml.featurestore.catalog.features.onboarding.SimclusterUserInterestedInCandidateKnownFor.IntersectionUserFollowScore import com.twitter.ml.featurestore.catalog.features.onboarding.UserWtfAlgorithmAggregate import com.twitter.ml.featurestore.catalog.features.onboarding.WhoToFollowImpression.HomeTimelineWtfCandidateCounts import com.twitter.ml.featurestore.catalog.features.onboarding.WhoToFollowImpression.HomeTimelineWtfCandidateImpressionCounts import com.twitter.ml.featurestore.catalog.features.onboarding.WhoToFollowImpression.HomeTimelineWtfCandidateImpressionLatestTimestamp import com.twitter.ml.featurestore.catalog.features.onboarding.WhoToFollowImpression.HomeTimelineWtfLatestTimestamp import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.FollowRate import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.Follows import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.FollowsTweetFavRate import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.FollowsTweetReplies import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.FollowsTweetReplyRate import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.FollowsTweetRetweetRate import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.FollowsTweetRetweets import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.FollowsWithTweetFavs import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.FollowsWithTweetImpressions import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.HasAnyEngagements import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.HasForwardEngagements import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.HasReverseEngagements import com.twitter.ml.featurestore.catalog.features.onboarding.WtfUserAlgorithmAggregate.Impressions import com.twitter.ml.featurestore.catalog.features.rux.UserResurrection.DaysSinceRecentResurrection import com.twitter.ml.featurestore.catalog.features.timelines.AuthorTopicAggregates import com.twitter.ml.featurestore.catalog.features.timelines.EngagementsReceivedByAuthorRealTimeAggregates import com.twitter.ml.featurestore.catalog.features.timelines.NegativeEngagementsReceivedByAuthorRealTimeAggregates import com.twitter.ml.featurestore.catalog.features.timelines.OriginalAuthorAggregates import com.twitter.ml.featurestore.catalog.features.timelines.TopicEngagementRealTimeAggregates import com.twitter.ml.featurestore.catalog.features.timelines.TopicEngagementUserStateRealTimeAggregates import com.twitter.ml.featurestore.catalog.features.timelines.TopicNegativeEngagementUserStateRealTimeAggregates import com.twitter.ml.featurestore.catalog.features.timelines.UserEngagementAuthorUserStateRealTimeAggregates import com.twitter.ml.featurestore.catalog.features.timelines.UserNegativeEngagementAuthorUserStateRealTimeAggregates import com.twitter.ml.featurestore.lib.EntityId import com.twitter.ml.featurestore.lib.UserId import com.twitter.ml.featurestore.lib.feature.BoundFeature import com.twitter.ml.featurestore.lib.feature.Feature object FeatureStoreFeatures { import FeatureStoreRawFeatures._ ///////////////////////////// Target user features //////////////////////// val targetUserFeatures: Set[BoundFeature[_ <: EntityId, _]] = (userKeyedFeatures ++ userAlgorithmAggregateFeatures).map(_.bind(UserEntity)) val targetUserResurrectionFeatures: Set[BoundFeature[_ <: EntityId, _]] = userResurrectionFeatures.map(_.bind(UserEntity)) val targetUserWtfImpressionFeatures: Set[BoundFeature[_ <: EntityId, _]] = wtfImpressionUserFeatures.map(_.bind(UserEntity)) val targetUserUserAuthorUserStateRealTimeAggregatesFeature: Set[BoundFeature[_ <: EntityId, _]] = userAuthorUserStateRealTimeAggregatesFeature.map(_.bind(UserEntity)) val targetUserStatusFeatures: Set[BoundFeature[_ <: EntityId, _]] = userStatusFeatures.map(_.bind(UserEntity).logarithm1p) val targetUserMetricCountFeatures: Set[BoundFeature[_ <: EntityId, _]] = mcFeatures.map(_.bind(UserEntity).logarithm1p) val targetUserClientFeatures: Set[BoundFeature[_ <: EntityId, _]] = clientFeatures.map(_.bind(UserEntity)) ///////////////////////////// Candidate user features //////////////////////// val candidateUserFeatures: Set[BoundFeature[_ <: EntityId, _]] = userKeyedFeatures.map(_.bind(CandidateUserEntity)) val candidateUserAuthorRealTimeAggregateFeatures: Set[BoundFeature[_ <: EntityId, _]] = authorAggregateFeatures.map(_.bind(CandidateUserEntity)) val candidateUserResurrectionFeatures: Set[BoundFeature[_ <: EntityId, _]] = userResurrectionFeatures.map(_.bind(CandidateUserEntity)) val candidateUserStatusFeatures: Set[BoundFeature[_ <: EntityId, _]] = userStatusFeatures.map(_.bind(CandidateUserEntity).logarithm1p) val candidateUserTimelinesAuthorAggregateFeatures: Set[BoundFeature[_ <: EntityId, _]] = Set(timelinesAuthorAggregateFeatures.bind(CandidateUserEntity)) val candidateUserMetricCountFeatures: Set[BoundFeature[_ <: EntityId, _]] = mcFeatures.map(_.bind(CandidateUserEntity).logarithm1p) val candidateUserClientFeatures: Set[BoundFeature[_ <: EntityId, _]] = clientFeatures.map(_.bind(CandidateUserEntity)) val similarToUserFeatures: Set[BoundFeature[_ <: EntityId, _]] = (userKeyedFeatures ++ authorAggregateFeatures).map(_.bind(AuthorEntity)) val similarToUserStatusFeatures: Set[BoundFeature[_ <: EntityId, _]] = userStatusFeatures.map(_.bind(AuthorEntity).logarithm1p) val similarToUserTimelinesAuthorAggregateFeatures: Set[BoundFeature[_ <: EntityId, _]] = Set(timelinesAuthorAggregateFeatures.bind(AuthorEntity)) val similarToUserMetricCountFeatures: Set[BoundFeature[_ <: EntityId, _]] = mcFeatures.map(_.bind(AuthorEntity).logarithm1p) val userCandidateEdgeFeatures: Set[BoundFeature[_ <: EntityId, _]] = (simclusterUVIntersectionFeatures ++ userCandidatePostNuxEdgeFeatures).map( _.bind(UserCandidateEntity)) val userCandidateWtfImpressionCandidateFeatures: Set[BoundFeature[_ <: EntityId, _]] = wtfImpressionCandidateFeatures.map(_.bind(UserCandidateEntity)) /** * Aggregate features based on candidate source algorithms. */ val postNuxAlgorithmIdAggregateFeatures: Set[BoundFeature[_ <: EntityId, _]] = Set(PostNuxAlgorithmIdAggregateFeatureGroup.FeaturesAsDataRecord) .map(_.bind(WtfAlgorithmIdEntity)) /** * Aggregate features based on candidate source algorithm types. There are 4 at the moment: * Geo, Social, Activity and Interest. */ val postNuxAlgorithmTypeAggregateFeatures: Set[BoundFeature[_ <: EntityId, _]] = Set(PostNuxAlgorithmTypeAggregateFeatureGroup.FeaturesAsDataRecord) .map(_.bind(WtfAlgorithmTypeEntity)) // user wtf-Algorithm features val userWtfAlgorithmEdgeFeatures: Set[BoundFeature[_ <: EntityId, _]] = FeatureGroupUtils.getTimelinesAggregationFrameworkCombinedFeatures( UserWtfAlgorithmAggregate, UserWtfAlgorithmEntity, FeatureGroupUtils.getMaxSumAvgAggregate(UserWtfAlgorithmAggregate) ) /** * We have to add the max/sum/avg-aggregated features to the set of all features so that we can * register them using FRS's [[FrsFeatureJsonExporter]]. * * Any additional such aggregated features that are included in [[FeatureStoreSource]] client * should be registered here as well. */ val maxSumAvgAggregatedFeatureContext: FeatureContext = new FeatureContext() .addFeatures( UserWtfAlgorithmAggregate.getSecondaryAggregatedFeatureContext ) // topic features val topicAggregateFeatures: Set[BoundFeature[_ <: EntityId, _]] = Set( TopicEngagementRealTimeAggregates.FeaturesAsDataRecord, TopicNegativeEngagementUserStateRealTimeAggregates.FeaturesAsDataRecord, TopicEngagementUserStateRealTimeAggregates.FeaturesAsDataRecord ).map(_.bind(TopicEntity)) val userTopicFeatures: Set[BoundFeature[_ <: EntityId, _]] = Set(FollowedTopics.bind(UserEntity)) val authorTopicFeatures: Set[BoundFeature[_ <: EntityId, _]] = Set( AuthorTopicAggregates.FeaturesAsDataRecord.bind(AuthorTopicEntity)) val topicFeatures = topicAggregateFeatures ++ userTopicFeatures ++ authorTopicFeatures } object FeatureStoreRawFeatures { val mcFeatures = Set( NumTweets, NumRetweets, NumOriginalTweets, NumRetweetsReceived, NumFavoritesReceived, NumRepliesReceived, NumQuoteRetweetsReceived, NumFollowsReceived, NumFollowBacks, NumFollows, NumUnfollows, NumUnfollowBacks, NumQualityFollowReceived, NumQuoteRetweets, NumFavorites, NumReplies, NumLoginTweetImpressions, NumTweetImpressions, NumLoginDays, NumUserActiveMinutes, NumMuted, NumSpamBlocked, NumMuteBacks, NumSpamBlockedBacks, NumWasMutualFollowed, NumWasMutualUnfollowed, NumWasUnfollowed ) // based off usersource, and each feature represents the cumulative 'sent' counts val userStatusFeatures = Set( Favorites, Followers, Following, Tweets ) // ratio features created from combining other features val userRatioFeatures = Set(MutualFollowsFollowing, FollowersFollowings) // features related to user login history val userResurrectionFeatures: Set[Feature[UserId, Int]] = Set( DaysSinceRecentResurrection ) // real-time aggregate features borrowed from timelines val authorAggregateFeatures = Set( EngagementsReceivedByAuthorRealTimeAggregates.FeaturesAsDataRecord, NegativeEngagementsReceivedByAuthorRealTimeAggregates.FeaturesAsDataRecord, ) val timelinesAuthorAggregateFeatures = OriginalAuthorAggregates.FeaturesAsDataRecord val userAuthorUserStateRealTimeAggregatesFeature: Set[Feature[UserId, DataRecord]] = Set( UserEngagementAuthorUserStateRealTimeAggregates.FeaturesAsDataRecord, UserNegativeEngagementAuthorUserStateRealTimeAggregates.FeaturesAsDataRecord ) // post nux per-user offline features val userOfflineFeatures = Set( NumFollowings, NumFollowers, NumMutualFollows, TweepCred, UserState, Language, Country, MutualFollowsOverFollowingRatio, MutualFollowsOverFollowersRatio, FollowersOverFollowingRatio, ) // matched post nux offline features between user and candidate val userCandidatePostNuxEdgeFeatures = Set( HaveSameUserState, HaveSameLanguage, HaveSameCountry, NumFollowingsGap, NumFollowersGap, NumMutualFollowsGap, TweepCredGap, ) // user algorithm aggregate features val userAlgorithmAggregateFeatures = Set( Impressions, Follows, FollowRate, FollowsWithTweetImpressions, FollowsWithTweetFavs, FollowsTweetFavRate, FollowsTweetReplies, FollowsTweetReplyRate, FollowsTweetRetweets, FollowsTweetRetweetRate, HasForwardEngagements, HasReverseEngagements, HasAnyEngagements, ) val userKeyedFeatures = userRatioFeatures ++ userOfflineFeatures val wtfImpressionUserFeatures = Set(HomeTimelineWtfCandidateCounts, HomeTimelineWtfLatestTimestamp) val wtfImpressionCandidateFeatures = Set(HomeTimelineWtfCandidateImpressionCounts, HomeTimelineWtfCandidateImpressionLatestTimestamp) val simclusterUVIntersectionFeatures = Set( IntersectionClusterIds, HasIntersection, IntersectionUserFollowScore, IntersectionUserFavScore, IntersectionCandidateKnownForScore, IntersectionUserFollowCandidateKnownForScore, IntersectionUserFavCandidateKnownForScore ) // Client features val clientFeatures = Set( NumClients, PrimaryClient, PrimaryClientVersion, FullPrimaryClientVersion, PrimaryDeviceManufacturer, PrimaryMobileSdkVersion, SecondaryClient ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/FeatureStoreGizmoduckSource.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.github.benmanes.caffeine.cache.Caffeine import com.google.inject.Inject import com.twitter.finagle.TimeoutException import com.twitter.finagle.mtls.authentication.ServiceIdentifier import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSource import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSourceId import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.feature_hydration.sources.Utils.adaptAdditionalFeaturesToDataRecord import com.twitter.follow_recommendations.common.feature_hydration.sources.Utils.randomizedTTL import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.ml.api.IRecordOneToOneAdapter import com.twitter.ml.featurestore.catalog.datasets.core.UsersourceEntityDataset import com.twitter.ml.featurestore.catalog.entities.core.{Author => AuthorEntity} import com.twitter.ml.featurestore.catalog.entities.core.{AuthorTopic => AuthorTopicEntity} import com.twitter.ml.featurestore.catalog.entities.core.{CandidateUser => CandidateUserEntity} import com.twitter.ml.featurestore.catalog.entities.core.{User => UserEntity} import com.twitter.ml.featurestore.lib.EdgeEntityId import com.twitter.ml.featurestore.lib.EntityId import com.twitter.ml.featurestore.lib.TopicId import com.twitter.ml.featurestore.lib.UserId import com.twitter.ml.featurestore.lib.data.PredictionRecord import com.twitter.ml.featurestore.lib.data.PredictionRecordAdapter import com.twitter.ml.featurestore.lib.dataset.DatasetId import com.twitter.ml.featurestore.lib.dataset.online.Hydrator.HydrationResponse import com.twitter.ml.featurestore.lib.dataset.online.OnlineAccessDataset import com.twitter.ml.featurestore.lib.dynamic.ClientConfig import com.twitter.ml.featurestore.lib.dynamic.DynamicFeatureStoreClient import com.twitter.ml.featurestore.lib.dynamic.DynamicHydrationConfig import com.twitter.ml.featurestore.lib.dynamic.FeatureStoreParamsConfig import com.twitter.ml.featurestore.lib.dynamic.GatedFeatures import com.twitter.ml.featurestore.lib.feature.BoundFeature import com.twitter.ml.featurestore.lib.feature.BoundFeatureSet import com.twitter.ml.featurestore.lib.online.DatasetValuesCache import com.twitter.ml.featurestore.lib.online.FeatureStoreRequest import com.twitter.ml.featurestore.lib.online.OnlineFeatureGenerationStats import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import java.util.concurrent.TimeUnit import com.twitter.conversions.DurationOps._ import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext class FeatureStoreGizmoduckSource @Inject() ( serviceIdentifier: ServiceIdentifier, stats: StatsReceiver) extends FeatureSource { import FeatureStoreGizmoduckSource._ val backupSourceStats = stats.scope("feature_store_hydration_gizmoduck") val adapterStats = backupSourceStats.scope("adapters") override def id: FeatureSourceId = FeatureSourceId.FeatureStoreGizmoduckSourceId override def featureContext: FeatureContext = getFeatureContext val clientConfig: ClientConfig[HasParams] = ClientConfig( dynamicHydrationConfig = dynamicHydrationConfig, featureStoreParamsConfig = FeatureStoreParamsConfig(FeatureStoreParameters.featureStoreParams, Map.empty), /** * The smaller one between `timeoutProvider` and `FeatureStoreSourceParams.GlobalFetchTimeout` * used below takes effect. */ timeoutProvider = Function.const(800.millis), serviceIdentifier = serviceIdentifier ) private val datasetsToCache = Set( UsersourceEntityDataset ).asInstanceOf[Set[OnlineAccessDataset[_ <: EntityId, _]]] private val datasetValuesCache: DatasetValuesCache = DatasetValuesCache( Caffeine .newBuilder() .expireAfterWrite(randomizedTTL(12.hours.inSeconds), TimeUnit.SECONDS) .maximumSize(DefaultCacheMaxKeys) .build[(_ <: EntityId, DatasetId), Stitch[HydrationResponse[_]]] .asMap, datasetsToCache, DatasetCacheScope ) private val dynamicFeatureStoreClient = DynamicFeatureStoreClient( clientConfig, backupSourceStats, Set(datasetValuesCache) ) private val adapter: IRecordOneToOneAdapter[PredictionRecord] = PredictionRecordAdapter.oneToOne( BoundFeatureSet(allFeatures), OnlineFeatureGenerationStats(backupSourceStats) ) override def hydrateFeatures( target: HasClientContext with HasPreFetchedFeature with HasParams with HasSimilarToContext with HasDisplayLocation, candidates: Seq[CandidateUser] ): Stitch[Map[CandidateUser, DataRecord]] = { target.getOptionalUserId .map { targetUserId => val featureRequests = candidates.map { candidate => val userEntityId = UserEntity.withId(UserId(targetUserId)) val candidateEntityId = CandidateUserEntity.withId(UserId(candidate.id)) val similarToUserId = target.similarToUserIds.map(id => AuthorEntity.withId(UserId(id))) val topicProof = candidate.reason.flatMap(_.accountProof.flatMap(_.topicProof)) val authorTopicEntity = if (topicProof.isDefined) { backupSourceStats.counter("candidates_with_topic_proof").incr() Set( AuthorTopicEntity.withId( EdgeEntityId(UserId(candidate.id), TopicId(topicProof.get.topicId)))) } else Nil val entities = Seq(userEntityId, candidateEntityId) ++ similarToUserId ++ authorTopicEntity FeatureStoreRequest(entities) } val predictionRecordsFut = dynamicFeatureStoreClient(featureRequests, target) val candidateFeatureMap = predictionRecordsFut.map { predictionRecords => // we can zip predictionRecords with candidates as the order is preserved in the client candidates .zip(predictionRecords).map { case (candidate, predictionRecord) => candidate -> adaptAdditionalFeaturesToDataRecord( adapter.adaptToDataRecord(predictionRecord), adapterStats, FeatureStoreSource.featureAdapters) }.toMap } Stitch .callFuture(candidateFeatureMap) .within(target.params(FeatureStoreSourceParams.GlobalFetchTimeout))( com.twitter.finagle.util.DefaultTimer) .rescue { case _: TimeoutException => Stitch.value(Map.empty[CandidateUser, DataRecord]) } }.getOrElse(Stitch.value(Map.empty[CandidateUser, DataRecord])) } } object FeatureStoreGizmoduckSource { private val DatasetCacheScope = "feature_store_local_cache_gizmoduck" private val DefaultCacheMaxKeys = 20000 val allFeatures: Set[BoundFeature[_ <: EntityId, _]] = FeatureStoreFeatures.candidateUserStatusFeatures ++ FeatureStoreFeatures.similarToUserStatusFeatures ++ FeatureStoreFeatures.targetUserStatusFeatures val getFeatureContext: FeatureContext = BoundFeatureSet(allFeatures).toFeatureContext val dynamicHydrationConfig: DynamicHydrationConfig[HasParams] = DynamicHydrationConfig( Set( GatedFeatures( boundFeatureSet = BoundFeatureSet(FeatureStoreFeatures.targetUserStatusFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForGizmoduck) & HasParams.paramGate(FeatureStoreSourceParams.EnableTargetUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(FeatureStoreFeatures.candidateUserStatusFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForGizmoduck) & HasParams.paramGate(FeatureStoreSourceParams.EnableCandidateUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(FeatureStoreFeatures.similarToUserStatusFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForGizmoduck) & HasParams.paramGate(FeatureStoreSourceParams.EnableSimilarToUserFeatures) ), )) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/FeatureStoreParameters.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.twitter.conversions.DurationOps._ import com.twitter.ml.featurestore.catalog.datasets.core.UserMobileSdkDataset import com.twitter.ml.featurestore.catalog.datasets.core.UsersourceEntityDataset import com.twitter.ml.featurestore.catalog.datasets.customer_journey.PostNuxAlgorithmIdAggregateDataset import com.twitter.ml.featurestore.catalog.datasets.customer_journey.PostNuxAlgorithmTypeAggregateDataset import com.twitter.ml.featurestore.catalog.datasets.magicrecs.NotificationSummariesEntityDataset import com.twitter.ml.featurestore.catalog.datasets.onboarding.MetricCenterUserCountingFeaturesDataset import com.twitter.ml.featurestore.catalog.datasets.onboarding.UserWtfAlgorithmAggregateFeaturesDataset import com.twitter.ml.featurestore.catalog.datasets.onboarding.WhoToFollowPostNuxFeaturesDataset import com.twitter.ml.featurestore.catalog.datasets.rux.UserRecentReactivationTimeDataset import com.twitter.ml.featurestore.catalog.datasets.timelines.AuthorFeaturesEntityDataset import com.twitter.ml.featurestore.lib.dataset.DatasetParams import com.twitter.ml.featurestore.lib.dataset.online.BatchingPolicy import com.twitter.ml.featurestore.lib.params.FeatureStoreParams import com.twitter.strato.opcontext.Attribution.ManhattanAppId import com.twitter.strato.opcontext.ServeWithin object FeatureStoreParameters { private val FeatureServiceBatchSize = 100 val featureStoreParams = FeatureStoreParams( global = DatasetParams( serveWithin = Some(ServeWithin(duration = 240.millis, roundTripAllowance = None)), attributions = Seq( ManhattanAppId("omega", "wtf_impression_store"), ManhattanAppId("athena", "wtf_athena"), ManhattanAppId("starbuck", "wtf_starbuck"), ManhattanAppId("apollo", "wtf_apollo") ), batchingPolicy = Some(BatchingPolicy.Isolated(FeatureServiceBatchSize)) ), perDataset = Map( MetricCenterUserCountingFeaturesDataset.id -> DatasetParams( stratoSuffix = Some("onboarding"), batchingPolicy = Some(BatchingPolicy.Isolated(200)) ), UsersourceEntityDataset.id -> DatasetParams( stratoSuffix = Some("onboarding") ), WhoToFollowPostNuxFeaturesDataset.id -> DatasetParams( stratoSuffix = Some("onboarding"), batchingPolicy = Some(BatchingPolicy.Isolated(200)) ), AuthorFeaturesEntityDataset.id -> DatasetParams( stratoSuffix = Some("onboarding"), batchingPolicy = Some(BatchingPolicy.Isolated(10)) ), UserRecentReactivationTimeDataset.id -> DatasetParams( stratoSuffix = None // removed due to low hit rate. we should use a negative cache in the future ), UserWtfAlgorithmAggregateFeaturesDataset.id -> DatasetParams( stratoSuffix = None ), NotificationSummariesEntityDataset.id -> DatasetParams( stratoSuffix = Some("onboarding"), serveWithin = Some(ServeWithin(duration = 45.millis, roundTripAllowance = None)), batchingPolicy = Some(BatchingPolicy.Isolated(10)) ), UserMobileSdkDataset.id -> DatasetParams( stratoSuffix = Some("onboarding") ), PostNuxAlgorithmIdAggregateDataset.id -> DatasetParams( stratoSuffix = Some("onboarding") ), PostNuxAlgorithmTypeAggregateDataset.id -> DatasetParams( stratoSuffix = Some("onboarding") ), ), enableFeatureGenerationStats = true ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/FeatureStorePostNuxAlgorithmSource.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.github.benmanes.caffeine.cache.Caffeine import com.google.inject.Inject import com.twitter.conversions.DurationOps._ import com.twitter.finagle.TimeoutException import com.twitter.finagle.mtls.authentication.ServiceIdentifier import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.constants.CandidateAlgorithmTypeConstants import com.twitter.follow_recommendations.common.feature_hydration.adapters.CandidateAlgorithmAdapter.remapCandidateSource import com.twitter.follow_recommendations.common.feature_hydration.adapters.PostNuxAlgorithmIdAdapter import com.twitter.follow_recommendations.common.feature_hydration.adapters.PostNuxAlgorithmTypeAdapter import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSource import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSourceId import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.feature_hydration.sources.Utils.adaptAdditionalFeaturesToDataRecord import com.twitter.follow_recommendations.common.feature_hydration.sources.Utils.randomizedTTL import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.hermit.constants.AlgorithmFeedbackTokens.AlgorithmToFeedbackTokenMap import com.twitter.ml.api.DataRecord import com.twitter.ml.api.DataRecordMerger import com.twitter.ml.api.FeatureContext import com.twitter.ml.api.IRecordOneToOneAdapter import com.twitter.ml.featurestore.catalog.datasets.customer_journey.PostNuxAlgorithmIdAggregateDataset import com.twitter.ml.featurestore.catalog.datasets.customer_journey.PostNuxAlgorithmTypeAggregateDataset import com.twitter.ml.featurestore.catalog.entities.onboarding.{WtfAlgorithm => OnboardingWtfAlgoId} import com.twitter.ml.featurestore.catalog.entities.onboarding.{ WtfAlgorithmType => OnboardingWtfAlgoType } import com.twitter.ml.featurestore.catalog.features.customer_journey.CombineAllFeaturesPolicy import com.twitter.ml.featurestore.lib.EntityId import com.twitter.ml.featurestore.lib.WtfAlgorithmId import com.twitter.ml.featurestore.lib.WtfAlgorithmType import com.twitter.ml.featurestore.lib.data.PredictionRecord import com.twitter.ml.featurestore.lib.data.PredictionRecordAdapter import com.twitter.ml.featurestore.lib.dataset.DatasetId import com.twitter.ml.featurestore.lib.dataset.online.Hydrator.HydrationResponse import com.twitter.ml.featurestore.lib.dataset.online.OnlineAccessDataset import com.twitter.ml.featurestore.lib.dynamic.ClientConfig import com.twitter.ml.featurestore.lib.dynamic.DynamicFeatureStoreClient import com.twitter.ml.featurestore.lib.dynamic.DynamicHydrationConfig import com.twitter.ml.featurestore.lib.dynamic.FeatureStoreParamsConfig import com.twitter.ml.featurestore.lib.dynamic.GatedFeatures import com.twitter.ml.featurestore.lib.entity.EntityWithId import com.twitter.ml.featurestore.lib.feature.BoundFeature import com.twitter.ml.featurestore.lib.feature.BoundFeatureSet import com.twitter.ml.featurestore.lib.online.DatasetValuesCache import com.twitter.ml.featurestore.lib.online.FeatureStoreRequest import com.twitter.ml.featurestore.lib.online.OnlineFeatureGenerationStats import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import java.util.concurrent.TimeUnit import scala.collection.JavaConverters._ class FeatureStorePostNuxAlgorithmSource @Inject() ( serviceIdentifier: ServiceIdentifier, stats: StatsReceiver) extends FeatureSource { import FeatureStorePostNuxAlgorithmSource._ val backupSourceStats = stats.scope("feature_store_hydration_post_nux_algorithm") val adapterStats = backupSourceStats.scope("adapters") override def id: FeatureSourceId = FeatureSourceId.FeatureStorePostNuxAlgorithmSourceId override def featureContext: FeatureContext = getFeatureContext private val dataRecordMerger = new DataRecordMerger val clientConfig: ClientConfig[HasParams] = ClientConfig( dynamicHydrationConfig = dynamicHydrationConfig, featureStoreParamsConfig = FeatureStoreParamsConfig(FeatureStoreParameters.featureStoreParams, Map.empty), /** * The smaller one between `timeoutProvider` and `FeatureStoreSourceParams.GlobalFetchTimeout` * used below takes effect. */ timeoutProvider = Function.const(800.millis), serviceIdentifier = serviceIdentifier ) private val datasetsToCache = Set( PostNuxAlgorithmIdAggregateDataset, PostNuxAlgorithmTypeAggregateDataset, ).asInstanceOf[Set[OnlineAccessDataset[_ <: EntityId, _]]] private val datasetValuesCache: DatasetValuesCache = DatasetValuesCache( Caffeine .newBuilder() .expireAfterWrite(randomizedTTL(12.hours.inSeconds), TimeUnit.SECONDS) .maximumSize(DefaultCacheMaxKeys) .build[(_ <: EntityId, DatasetId), Stitch[HydrationResponse[_]]] .asMap, datasetsToCache, DatasetCacheScope ) private val dynamicFeatureStoreClient = DynamicFeatureStoreClient( clientConfig, backupSourceStats, Set(datasetValuesCache) ) private val adapterToDataRecord: IRecordOneToOneAdapter[PredictionRecord] = PredictionRecordAdapter.oneToOne( BoundFeatureSet(allFeatures), OnlineFeatureGenerationStats(backupSourceStats) ) // These two calculate the rate for each feature by dividing it by the number of impressions, then // apply a log transformation. private val transformAdapters = Seq(PostNuxAlgorithmIdAdapter, PostNuxAlgorithmTypeAdapter) override def hydrateFeatures( target: HasClientContext with HasPreFetchedFeature with HasParams with HasSimilarToContext with HasDisplayLocation, candidates: Seq[CandidateUser] ): Stitch[Map[CandidateUser, DataRecord]] = { target.getOptionalUserId .map { _: Long => val candidateAlgoIdEntities = candidates.map { candidate => candidate.id -> candidate.getAllAlgorithms .flatMap { algo => AlgorithmToFeedbackTokenMap.get(remapCandidateSource(algo)) }.map(algoId => OnboardingWtfAlgoId.withId(WtfAlgorithmId(algoId))) }.toMap val candidateAlgoTypeEntities = candidateAlgoIdEntities.map { case (candidateId, algoIdEntities) => candidateId -> algoIdEntities .map(_.id.algoId) .flatMap(algoId => CandidateAlgorithmTypeConstants.getAlgorithmTypes(algoId.toString)) .distinct .map(algoType => OnboardingWtfAlgoType.withId(WtfAlgorithmType(algoType))) } val entities = { candidateAlgoIdEntities.values.flatten ++ candidateAlgoTypeEntities.values.flatten }.toSeq.distinct val requests = entities.map(entity => FeatureStoreRequest(Seq(entity))) val predictionRecordsFut = dynamicFeatureStoreClient(requests, target) val candidateFeatureMap = predictionRecordsFut.map { predictionRecords: Seq[PredictionRecord] => val entityFeatureMap: Map[EntityWithId[_], DataRecord] = entities .zip(predictionRecords).map { case (entity, predictionRecord) => entity -> adaptAdditionalFeaturesToDataRecord( adapterToDataRecord.adaptToDataRecord(predictionRecord), adapterStats, transformAdapters) }.toMap // In case we have more than one algorithm ID, or type, for a candidate, we merge the // resulting DataRecords using the two merging policies below. val algoIdMergeFn = CombineAllFeaturesPolicy(PostNuxAlgorithmIdAdapter.getFeatures).getMergeFn val algoTypeMergeFn = CombineAllFeaturesPolicy(PostNuxAlgorithmTypeAdapter.getFeatures).getMergeFn val candidateAlgoIdFeaturesMap = candidateAlgoIdEntities.mapValues { entities => val features = entities.flatMap(e => Option(entityFeatureMap.getOrElse(e, null))) algoIdMergeFn(features) } val candidateAlgoTypeFeaturesMap = candidateAlgoTypeEntities.mapValues { entities => val features = entities.flatMap(e => Option(entityFeatureMap.getOrElse(e, null))) algoTypeMergeFn(features) } candidates.map { candidate => val idDrOpt = candidateAlgoIdFeaturesMap.getOrElse(candidate.id, None) val typeDrOpt = candidateAlgoTypeFeaturesMap.getOrElse(candidate.id, None) val featureDr = (idDrOpt, typeDrOpt) match { case (None, Some(typeDataRecord)) => typeDataRecord case (Some(idDataRecord), None) => idDataRecord case (None, None) => new DataRecord() case (Some(idDataRecord), Some(typeDataRecord)) => dataRecordMerger.merge(idDataRecord, typeDataRecord) idDataRecord } candidate -> featureDr }.toMap } Stitch .callFuture(candidateFeatureMap) .within(target.params(FeatureStoreSourceParams.GlobalFetchTimeout))( com.twitter.finagle.util.DefaultTimer) .rescue { case _: TimeoutException => Stitch.value(Map.empty[CandidateUser, DataRecord]) } }.getOrElse(Stitch.value(Map.empty[CandidateUser, DataRecord])) } } object FeatureStorePostNuxAlgorithmSource { private val DatasetCacheScope = "feature_store_local_cache_post_nux_algorithm" private val DefaultCacheMaxKeys = 1000 // Both of these datasets have <50 keys total. val allFeatures: Set[BoundFeature[_ <: EntityId, _]] = FeatureStoreFeatures.postNuxAlgorithmIdAggregateFeatures ++ FeatureStoreFeatures.postNuxAlgorithmTypeAggregateFeatures val algoIdFinalFeatures = CombineAllFeaturesPolicy( PostNuxAlgorithmIdAdapter.getFeatures).outputFeaturesPostMerge.toSeq val algoTypeFinalFeatures = CombineAllFeaturesPolicy( PostNuxAlgorithmTypeAdapter.getFeatures).outputFeaturesPostMerge.toSeq val getFeatureContext: FeatureContext = new FeatureContext().addFeatures((algoIdFinalFeatures ++ algoTypeFinalFeatures).asJava) val dynamicHydrationConfig: DynamicHydrationConfig[HasParams] = DynamicHydrationConfig( Set( GatedFeatures( boundFeatureSet = BoundFeatureSet(FeatureStoreFeatures.postNuxAlgorithmIdAggregateFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableAlgorithmAggregateFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(FeatureStoreFeatures.postNuxAlgorithmTypeAggregateFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableAlgorithmAggregateFeatures) ), )) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/FeatureStoreSource.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.github.benmanes.caffeine.cache.Caffeine import com.google.inject.Inject import com.google.inject.Singleton import com.twitter.conversions.DurationOps._ import com.twitter.finagle.TimeoutException import com.twitter.finagle.mtls.authentication.ServiceIdentifier import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.feature_hydration.adapters.CandidateAlgorithmAdapter.remapCandidateSource import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSource import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSourceId import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.feature_hydration.sources.Utils.adaptAdditionalFeaturesToDataRecord import com.twitter.follow_recommendations.common.feature_hydration.sources.Utils.randomizedTTL import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.hermit.constants.AlgorithmFeedbackTokens.AlgorithmToFeedbackTokenMap import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.ml.api.IRecordOneToOneAdapter import com.twitter.ml.featurestore.catalog.datasets.core.UsersourceEntityDataset import com.twitter.ml.featurestore.catalog.datasets.magicrecs.NotificationSummariesEntityDataset import com.twitter.ml.featurestore.catalog.datasets.onboarding.MetricCenterUserCountingFeaturesDataset import com.twitter.ml.featurestore.catalog.datasets.timelines.AuthorFeaturesEntityDataset import com.twitter.ml.featurestore.catalog.entities.core.{Author => AuthorEntity} import com.twitter.ml.featurestore.catalog.entities.core.{AuthorTopic => AuthorTopicEntity} import com.twitter.ml.featurestore.catalog.entities.core.{CandidateUser => CandidateUserEntity} import com.twitter.ml.featurestore.catalog.entities.core.{Topic => TopicEntity} import com.twitter.ml.featurestore.catalog.entities.core.{User => UserEntity} import com.twitter.ml.featurestore.catalog.entities.core.{UserCandidate => UserCandidateEntity} import com.twitter.ml.featurestore.catalog.entities.onboarding.UserWtfAlgorithmEntity import com.twitter.ml.featurestore.lib.data.PredictionRecord import com.twitter.ml.featurestore.lib.data.PredictionRecordAdapter import com.twitter.ml.featurestore.lib.dataset.online.Hydrator.HydrationResponse import com.twitter.ml.featurestore.lib.dataset.online.OnlineAccessDataset import com.twitter.ml.featurestore.lib.dataset.DatasetId import com.twitter.ml.featurestore.lib.dynamic._ import com.twitter.ml.featurestore.lib.feature._ import com.twitter.ml.featurestore.lib.online.DatasetValuesCache import com.twitter.ml.featurestore.lib.online.FeatureStoreRequest import com.twitter.ml.featurestore.lib.online.OnlineFeatureGenerationStats import com.twitter.ml.featurestore.lib.EdgeEntityId import com.twitter.ml.featurestore.lib.EntityId import com.twitter.ml.featurestore.lib.TopicId import com.twitter.ml.featurestore.lib.UserId import com.twitter.ml.featurestore.lib.WtfAlgorithmId import com.twitter.onboarding.relevance.adapters.features.featurestore.CandidateAuthorTopicAggregatesAdapter import com.twitter.onboarding.relevance.adapters.features.featurestore.CandidateTopicEngagementRealTimeAggregatesAdapter import com.twitter.onboarding.relevance.adapters.features.featurestore.CandidateTopicEngagementUserStateRealTimeAggregatesAdapter import com.twitter.onboarding.relevance.adapters.features.featurestore.CandidateTopicNegativeEngagementUserStateRealTimeAggregatesAdapter import com.twitter.onboarding.relevance.adapters.features.featurestore.FeatureStoreAdapter import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import java.util.concurrent.TimeUnit @Singleton class FeatureStoreSource @Inject() ( serviceIdentifier: ServiceIdentifier, stats: StatsReceiver) extends FeatureSource { import FeatureStoreSource._ override val id: FeatureSourceId = FeatureSourceId.FeatureStoreSourceId override val featureContext: FeatureContext = FeatureStoreSource.getFeatureContext val hydrateFeaturesStats = stats.scope("hydrate_features") val adapterStats = stats.scope("adapters") val featureSet: BoundFeatureSet = BoundFeatureSet(FeatureStoreSource.allFeatures) val clientConfig: ClientConfig[HasParams] = ClientConfig( dynamicHydrationConfig = FeatureStoreSource.dynamicHydrationConfig, featureStoreParamsConfig = FeatureStoreParamsConfig(FeatureStoreParameters.featureStoreParams, Map.empty), /** * The smaller one between `timeoutProvider` and `FeatureStoreSourceParams.GlobalFetchTimeout` * used below takes effect. */ timeoutProvider = Function.const(800.millis), serviceIdentifier = serviceIdentifier ) private val datasetsToCache = Set( MetricCenterUserCountingFeaturesDataset, UsersourceEntityDataset, AuthorFeaturesEntityDataset, NotificationSummariesEntityDataset ).asInstanceOf[Set[OnlineAccessDataset[_ <: EntityId, _]]] private val datasetValuesCache: DatasetValuesCache = DatasetValuesCache( Caffeine .newBuilder() .expireAfterWrite(randomizedTTL(12.hours.inSeconds), TimeUnit.SECONDS) .maximumSize(DefaultCacheMaxKeys) .build[(_ <: EntityId, DatasetId), Stitch[HydrationResponse[_]]] .asMap, datasetsToCache, DatasetCacheScope ) private val dynamicFeatureStoreClient = DynamicFeatureStoreClient( clientConfig, stats, Set(datasetValuesCache) ) private val adapter: IRecordOneToOneAdapter[PredictionRecord] = PredictionRecordAdapter.oneToOne( BoundFeatureSet(allFeatures), OnlineFeatureGenerationStats(stats) ) override def hydrateFeatures( target: HasClientContext with HasPreFetchedFeature with HasParams with HasSimilarToContext with HasDisplayLocation, candidates: Seq[CandidateUser] ): Stitch[Map[CandidateUser, DataRecord]] = { target.getOptionalUserId .map { targetUserId => val featureRequests = candidates.map { candidate => val userId = UserId(targetUserId) val userEntityId = UserEntity.withId(userId) val candidateEntityId = CandidateUserEntity.withId(UserId(candidate.id)) val userCandidateEdgeEntityId = UserCandidateEntity.withId(EdgeEntityId(userId, UserId(candidate.id))) val similarToUserId = target.similarToUserIds.map(id => AuthorEntity.withId(UserId(id))) val topicProof = candidate.reason.flatMap(_.accountProof.flatMap(_.topicProof)) val topicEntities = if (topicProof.isDefined) { hydrateFeaturesStats.counter("candidates_with_topic_proof").incr() val topicId = topicProof.get.topicId val topicEntityId = TopicEntity.withId(TopicId(topicId)) val authorTopicEntityId = AuthorTopicEntity.withId(EdgeEntityId(UserId(candidate.id), TopicId(topicId))) Seq(topicEntityId, authorTopicEntityId) } else Nil val candidateAlgorithmsWithScores = candidate.getAllAlgorithms val userWtfAlgEdgeEntities = candidateAlgorithmsWithScores.flatMap(algo => { val algoId = AlgorithmToFeedbackTokenMap.get(remapCandidateSource(algo)) algoId.map(id => UserWtfAlgorithmEntity.withId(EdgeEntityId(userId, WtfAlgorithmId(id)))) }) val entities = Seq( userEntityId, candidateEntityId, userCandidateEdgeEntityId) ++ similarToUserId ++ topicEntities ++ userWtfAlgEdgeEntities FeatureStoreRequest(entities) } val predictionRecordsFut = dynamicFeatureStoreClient(featureRequests, target) val candidateFeatureMap = predictionRecordsFut.map { predictionRecords => // we can zip predictionRecords with candidates as the order is preserved in the client candidates .zip(predictionRecords).map { case (candidate, predictionRecord) => candidate -> adaptAdditionalFeaturesToDataRecord( adapter.adaptToDataRecord(predictionRecord), adapterStats, FeatureStoreSource.featureAdapters) }.toMap } Stitch .callFuture(candidateFeatureMap) .within(target.params(FeatureStoreSourceParams.GlobalFetchTimeout))( com.twitter.finagle.util.DefaultTimer) .rescue { case _: TimeoutException => Stitch.value(Map.empty[CandidateUser, DataRecord]) } }.getOrElse(Stitch.value(Map.empty[CandidateUser, DataRecord])) } } // list of features that we will be fetching, even if we are only scribing but not scoring with them object FeatureStoreSource { private val DatasetCacheScope = "feature_store_local_cache" private val DefaultCacheMaxKeys = 70000 import FeatureStoreFeatures._ ///////////////////// ALL hydrated features ///////////////////// val allFeatures: Set[BoundFeature[_ <: EntityId, _]] = //target user targetUserFeatures ++ targetUserUserAuthorUserStateRealTimeAggregatesFeature ++ targetUserResurrectionFeatures ++ targetUserWtfImpressionFeatures ++ targetUserStatusFeatures ++ targetUserMetricCountFeatures ++ //candidate user candidateUserFeatures ++ candidateUserResurrectionFeatures ++ candidateUserAuthorRealTimeAggregateFeatures ++ candidateUserStatusFeatures ++ candidateUserMetricCountFeatures ++ candidateUserTimelinesAuthorAggregateFeatures ++ candidateUserClientFeatures ++ //similar to user similarToUserFeatures ++ similarToUserStatusFeatures ++ similarToUserMetricCountFeatures ++ similarToUserTimelinesAuthorAggregateFeatures ++ //other userCandidateEdgeFeatures ++ userCandidateWtfImpressionCandidateFeatures ++ topicFeatures ++ userWtfAlgorithmEdgeFeatures ++ targetUserClientFeatures val dynamicHydrationConfig: DynamicHydrationConfig[HasParams] = DynamicHydrationConfig( Set( GatedFeatures( boundFeatureSet = BoundFeatureSet(topicAggregateFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableTopicAggregateFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(authorTopicFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForTimelinesAuthors).unary_! & HasParams.paramGate(FeatureStoreSourceParams.EnableAuthorTopicAggregateFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(userTopicFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableUserTopicFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(targetUserFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableTargetUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(targetUserUserAuthorUserStateRealTimeAggregatesFeature), gate = HasParams.paramGate( FeatureStoreSourceParams.EnableTargetUserUserAuthorUserStateRealTimeAggregatesFeature) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(targetUserResurrectionFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableTargetUserResurrectionFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(targetUserWtfImpressionFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableTargetUserWtfImpressionFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(targetUserStatusFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableSeparateClientForGizmoduck).unary_! & HasParams.paramGate(FeatureStoreSourceParams.EnableTargetUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(targetUserMetricCountFeatures), gate = HasParams .paramGate( FeatureStoreSourceParams.EnableSeparateClientForMetricCenterUserCounting).unary_! & HasParams.paramGate(FeatureStoreSourceParams.EnableTargetUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(candidateUserFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableCandidateUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(candidateUserAuthorRealTimeAggregateFeatures), gate = HasParams.paramGate( FeatureStoreSourceParams.EnableCandidateUserAuthorRealTimeAggregateFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(candidateUserResurrectionFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableCandidateUserResurrectionFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(candidateUserStatusFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableSeparateClientForGizmoduck).unary_! & HasParams.paramGate(FeatureStoreSourceParams.EnableCandidateUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(candidateUserTimelinesAuthorAggregateFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForTimelinesAuthors).unary_! & HasParams.paramGate( FeatureStoreSourceParams.EnableCandidateUserTimelinesAuthorAggregateFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(candidateUserMetricCountFeatures), gate = HasParams .paramGate( FeatureStoreSourceParams.EnableSeparateClientForMetricCenterUserCounting).unary_! & HasParams.paramGate(FeatureStoreSourceParams.EnableCandidateUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(userCandidateEdgeFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableUserCandidateEdgeFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(userCandidateWtfImpressionCandidateFeatures), gate = HasParams.paramGate( FeatureStoreSourceParams.EnableUserCandidateWtfImpressionCandidateFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(userWtfAlgorithmEdgeFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableUserWtfAlgEdgeFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(similarToUserFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableSimilarToUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(similarToUserStatusFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableSeparateClientForGizmoduck).unary_! & HasParams.paramGate(FeatureStoreSourceParams.EnableSimilarToUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(similarToUserTimelinesAuthorAggregateFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForTimelinesAuthors).unary_! & HasParams.paramGate(FeatureStoreSourceParams.EnableSimilarToUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(similarToUserMetricCountFeatures), gate = HasParams .paramGate( FeatureStoreSourceParams.EnableSeparateClientForMetricCenterUserCounting).unary_! & HasParams.paramGate(FeatureStoreSourceParams.EnableSimilarToUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(candidateUserClientFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableCandidateClientFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(targetUserClientFeatures), gate = HasParams.paramGate(FeatureStoreSourceParams.EnableUserClientFeatures) ), ) ) // for calibrating features, e.g. add log transformed topic features val featureAdapters: Seq[FeatureStoreAdapter] = Seq( CandidateTopicEngagementRealTimeAggregatesAdapter, CandidateTopicNegativeEngagementUserStateRealTimeAggregatesAdapter, CandidateTopicEngagementUserStateRealTimeAggregatesAdapter, CandidateAuthorTopicAggregatesAdapter ) val additionalFeatureContext: FeatureContext = FeatureContext.merge( featureAdapters .foldRight(new FeatureContext())((adapter, context) => context .addFeatures(adapter.getFeatureContext)) ) val getFeatureContext: FeatureContext = BoundFeatureSet(allFeatures).toFeatureContext .addFeatures(additionalFeatureContext) // The below are aggregated features that are aggregated for a second time over multiple keys. .addFeatures(maxSumAvgAggregatedFeatureContext) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/FeatureStoreSourceParams.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.twitter.timelines.configapi.DurationConversion import com.twitter.timelines.configapi.FSBoundedParam import com.twitter.timelines.configapi.FSParam import com.twitter.timelines.configapi.HasDurationConversion import com.twitter.util.Duration import com.twitter.conversions.DurationOps._ object FeatureStoreSourceParams { case object EnableTopicAggregateFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableTopicAggregateFeatures, default = true ) case object EnableAlgorithmAggregateFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableAlgorithmAggregateFeatures, default = false ) case object EnableAuthorTopicAggregateFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableAuthorTopicAggregateFeatures, default = true ) case object EnableUserTopicFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableUserTopicFeatures, default = false ) case object EnableTargetUserFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableTargetUserFeatures, default = true ) case object EnableTargetUserUserAuthorUserStateRealTimeAggregatesFeature extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableTargetUserUserAuthorUserStateRealTimeAggregatesFeature, default = true ) case object EnableTargetUserResurrectionFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableTargetUserResurrectionFeatures, default = true ) case object EnableTargetUserWtfImpressionFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableTargetUserWtfImpressionFeatures, default = true ) case object EnableCandidateUserFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableCandidateUserFeatures, default = true ) case object EnableCandidateUserAuthorRealTimeAggregateFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableCandidateUserAuthorRealTimeAggregateFeatures, default = true ) case object EnableCandidateUserResurrectionFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableCandidateUserResurrectionFeatures, default = true ) case object EnableCandidateUserTimelinesAuthorAggregateFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableCandidateUserTimelinesAuthorAggregateFeatures, default = true ) case object EnableUserCandidateEdgeFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableUserCandidateEdgeFeatures, default = true ) case object EnableUserCandidateWtfImpressionCandidateFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableUserCandidateWtfImpressionCandidateFeatures, default = true ) case object EnableUserWtfAlgEdgeFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableUserWtfAlgEdgeFeatures, default = false ) case object EnableSimilarToUserFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableSimilarToUserFeatures, default = true ) case object EnableCandidatePrecomputedNotificationFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableCandidatePrecomputedNotificationFeatures, default = false ) case object EnableCandidateClientFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableCandidateClientFeatures, default = false ) case object EnableUserClientFeatures extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.EnableUserClientFeatures, default = false ) case object EnableSeparateClientForTimelinesAuthors extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.UseSeparateClientForTimelinesAuthor, default = false ) case object EnableSeparateClientForMetricCenterUserCounting extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.UseSeparateClientMetricCenterUserCounting, default = false ) case object EnableSeparateClientForNotifications extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.UseSeparateClientForNotifications, default = false ) case object EnableSeparateClientForGizmoduck extends FSParam[Boolean]( name = FeatureHydrationSourcesFeatureSwitchKeys.UseSeparateClientForGizmoduck, default = false ) case object GlobalFetchTimeout extends FSBoundedParam[Duration]( name = FeatureHydrationSourcesFeatureSwitchKeys.FeatureHydrationTimeout, default = 240.millisecond, min = 100.millisecond, max = 400.millisecond) with HasDurationConversion { override def durationConversion: DurationConversion = DurationConversion.FromMillis } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/FeatureStoreTimelinesAuthorSource.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.github.benmanes.caffeine.cache.Caffeine import com.google.inject.Inject import com.twitter.finagle.TimeoutException import com.twitter.finagle.mtls.authentication.ServiceIdentifier import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSource import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSourceId import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.feature_hydration.sources.Utils.adaptAdditionalFeaturesToDataRecord import com.twitter.follow_recommendations.common.feature_hydration.sources.Utils.randomizedTTL import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.ml.api.IRecordOneToOneAdapter import com.twitter.ml.featurestore.catalog.datasets.timelines.AuthorFeaturesEntityDataset import com.twitter.ml.featurestore.catalog.entities.core.{Author => AuthorEntity} import com.twitter.ml.featurestore.catalog.entities.core.{AuthorTopic => AuthorTopicEntity} import com.twitter.ml.featurestore.catalog.entities.core.{CandidateUser => CandidateUserEntity} import com.twitter.ml.featurestore.catalog.entities.core.{User => UserEntity} import com.twitter.ml.featurestore.lib.EdgeEntityId import com.twitter.ml.featurestore.lib.EntityId import com.twitter.ml.featurestore.lib.TopicId import com.twitter.ml.featurestore.lib.UserId import com.twitter.ml.featurestore.lib.data.PredictionRecord import com.twitter.ml.featurestore.lib.data.PredictionRecordAdapter import com.twitter.ml.featurestore.lib.dataset.DatasetId import com.twitter.ml.featurestore.lib.dataset.online.Hydrator.HydrationResponse import com.twitter.ml.featurestore.lib.dataset.online.OnlineAccessDataset import com.twitter.ml.featurestore.lib.dynamic.ClientConfig import com.twitter.ml.featurestore.lib.dynamic.DynamicFeatureStoreClient import com.twitter.ml.featurestore.lib.dynamic.DynamicHydrationConfig import com.twitter.ml.featurestore.lib.dynamic.FeatureStoreParamsConfig import com.twitter.ml.featurestore.lib.dynamic.GatedFeatures import com.twitter.ml.featurestore.lib.feature.BoundFeature import com.twitter.ml.featurestore.lib.feature.BoundFeatureSet import com.twitter.ml.featurestore.lib.online.DatasetValuesCache import com.twitter.ml.featurestore.lib.online.FeatureStoreRequest import com.twitter.ml.featurestore.lib.online.OnlineFeatureGenerationStats import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import java.util.concurrent.TimeUnit import com.twitter.conversions.DurationOps._ import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext class FeatureStoreTimelinesAuthorSource @Inject() ( serviceIdentifier: ServiceIdentifier, stats: StatsReceiver) extends FeatureSource { import FeatureStoreTimelinesAuthorSource._ val backupSourceStats = stats.scope("feature_store_hydration_timelines_author") val adapterStats = backupSourceStats.scope("adapters") override def id: FeatureSourceId = FeatureSourceId.FeatureStoreTimelinesAuthorSourceId override def featureContext: FeatureContext = getFeatureContext val clientConfig: ClientConfig[HasParams] = ClientConfig( dynamicHydrationConfig = dynamicHydrationConfig, featureStoreParamsConfig = FeatureStoreParamsConfig(FeatureStoreParameters.featureStoreParams, Map.empty), /** * The smaller one between `timeoutProvider` and `FeatureStoreSourceParams.GlobalFetchTimeout` * used below takes effect. */ timeoutProvider = Function.const(800.millis), serviceIdentifier = serviceIdentifier ) private val datasetsToCache = Set( AuthorFeaturesEntityDataset ).asInstanceOf[Set[OnlineAccessDataset[_ <: EntityId, _]]] private val datasetValuesCache: DatasetValuesCache = DatasetValuesCache( Caffeine .newBuilder() .expireAfterWrite(randomizedTTL(12.hours.inSeconds), TimeUnit.SECONDS) .maximumSize(DefaultCacheMaxKeys) .build[(_ <: EntityId, DatasetId), Stitch[HydrationResponse[_]]] .asMap, datasetsToCache, DatasetCacheScope ) private val dynamicFeatureStoreClient = DynamicFeatureStoreClient( clientConfig, backupSourceStats, Set(datasetValuesCache) ) private val adapter: IRecordOneToOneAdapter[PredictionRecord] = PredictionRecordAdapter.oneToOne( BoundFeatureSet(allFeatures), OnlineFeatureGenerationStats(backupSourceStats) ) override def hydrateFeatures( target: HasClientContext with HasPreFetchedFeature with HasParams with HasSimilarToContext with HasDisplayLocation, candidates: Seq[CandidateUser] ): Stitch[Map[CandidateUser, DataRecord]] = { target.getOptionalUserId .map { targetUserId => val featureRequests = candidates.map { candidate => val userEntityId = UserEntity.withId(UserId(targetUserId)) val candidateEntityId = CandidateUserEntity.withId(UserId(candidate.id)) val similarToUserId = target.similarToUserIds.map(id => AuthorEntity.withId(UserId(id))) val topicProof = candidate.reason.flatMap(_.accountProof.flatMap(_.topicProof)) val authorTopicEntity = if (topicProof.isDefined) { backupSourceStats.counter("candidates_with_topic_proof").incr() Set( AuthorTopicEntity.withId( EdgeEntityId(UserId(candidate.id), TopicId(topicProof.get.topicId)))) } else Nil val entities = Seq(userEntityId, candidateEntityId) ++ similarToUserId ++ authorTopicEntity FeatureStoreRequest(entities) } val predictionRecordsFut = dynamicFeatureStoreClient(featureRequests, target) val candidateFeatureMap = predictionRecordsFut.map { predictionRecords => // we can zip predictionRecords with candidates as the order is preserved in the client candidates .zip(predictionRecords).map { case (candidate, predictionRecord) => candidate -> adaptAdditionalFeaturesToDataRecord( adapter.adaptToDataRecord(predictionRecord), adapterStats, FeatureStoreSource.featureAdapters) }.toMap } Stitch .callFuture(candidateFeatureMap) .within(target.params(FeatureStoreSourceParams.GlobalFetchTimeout))( com.twitter.finagle.util.DefaultTimer) .rescue { case _: TimeoutException => Stitch.value(Map.empty[CandidateUser, DataRecord]) } }.getOrElse(Stitch.value(Map.empty[CandidateUser, DataRecord])) } } object FeatureStoreTimelinesAuthorSource { private val DatasetCacheScope = "feature_store_local_cache_timelines_author" private val DefaultCacheMaxKeys = 20000 import FeatureStoreFeatures._ val allFeatures: Set[BoundFeature[_ <: EntityId, _]] = similarToUserTimelinesAuthorAggregateFeatures ++ candidateUserTimelinesAuthorAggregateFeatures ++ authorTopicFeatures val getFeatureContext: FeatureContext = BoundFeatureSet(allFeatures).toFeatureContext val dynamicHydrationConfig: DynamicHydrationConfig[HasParams] = DynamicHydrationConfig( Set( GatedFeatures( boundFeatureSet = BoundFeatureSet(authorTopicFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForTimelinesAuthors) & HasParams.paramGate(FeatureStoreSourceParams.EnableAuthorTopicAggregateFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(similarToUserTimelinesAuthorAggregateFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForTimelinesAuthors) & HasParams.paramGate(FeatureStoreSourceParams.EnableSimilarToUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(candidateUserTimelinesAuthorAggregateFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForTimelinesAuthors) & HasParams.paramGate( FeatureStoreSourceParams.EnableCandidateUserTimelinesAuthorAggregateFeatures) ), )) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/FeatureStoreUserMetricCountsSource.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.github.benmanes.caffeine.cache.Caffeine import com.google.inject.Inject import com.twitter.finagle.TimeoutException import com.twitter.finagle.mtls.authentication.ServiceIdentifier import com.twitter.finagle.stats.StatsReceiver import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSource import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSourceId import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.feature_hydration.sources.Utils.adaptAdditionalFeaturesToDataRecord import com.twitter.follow_recommendations.common.feature_hydration.sources.Utils.randomizedTTL import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.ml.api.IRecordOneToOneAdapter import com.twitter.ml.featurestore.catalog.datasets.onboarding.MetricCenterUserCountingFeaturesDataset import com.twitter.ml.featurestore.catalog.entities.core.{Author => AuthorEntity} import com.twitter.ml.featurestore.catalog.entities.core.{AuthorTopic => AuthorTopicEntity} import com.twitter.ml.featurestore.catalog.entities.core.{CandidateUser => CandidateUserEntity} import com.twitter.ml.featurestore.catalog.entities.core.{User => UserEntity} import com.twitter.ml.featurestore.lib.EdgeEntityId import com.twitter.ml.featurestore.lib.EntityId import com.twitter.ml.featurestore.lib.TopicId import com.twitter.ml.featurestore.lib.UserId import com.twitter.ml.featurestore.lib.data.PredictionRecord import com.twitter.ml.featurestore.lib.data.PredictionRecordAdapter import com.twitter.ml.featurestore.lib.dataset.DatasetId import com.twitter.ml.featurestore.lib.dataset.online.Hydrator.HydrationResponse import com.twitter.ml.featurestore.lib.dataset.online.OnlineAccessDataset import com.twitter.ml.featurestore.lib.dynamic.ClientConfig import com.twitter.ml.featurestore.lib.dynamic.DynamicFeatureStoreClient import com.twitter.ml.featurestore.lib.dynamic.DynamicHydrationConfig import com.twitter.ml.featurestore.lib.dynamic.FeatureStoreParamsConfig import com.twitter.ml.featurestore.lib.dynamic.GatedFeatures import com.twitter.ml.featurestore.lib.feature.BoundFeature import com.twitter.ml.featurestore.lib.feature.BoundFeatureSet import com.twitter.ml.featurestore.lib.online.DatasetValuesCache import com.twitter.ml.featurestore.lib.online.FeatureStoreRequest import com.twitter.ml.featurestore.lib.online.OnlineFeatureGenerationStats import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams import java.util.concurrent.TimeUnit import com.twitter.conversions.DurationOps._ import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext class FeatureStoreUserMetricCountsSource @Inject() ( serviceIdentifier: ServiceIdentifier, stats: StatsReceiver) extends FeatureSource { import FeatureStoreUserMetricCountsSource._ val backupSourceStats = stats.scope("feature_store_hydration_mc_counting") val adapterStats = backupSourceStats.scope("adapters") override def id: FeatureSourceId = FeatureSourceId.FeatureStoreUserMetricCountsSourceId override def featureContext: FeatureContext = getFeatureContext val clientConfig: ClientConfig[HasParams] = ClientConfig( dynamicHydrationConfig = dynamicHydrationConfig, featureStoreParamsConfig = FeatureStoreParamsConfig(FeatureStoreParameters.featureStoreParams, Map.empty), /** * The smaller one between `timeoutProvider` and `FeatureStoreSourceParams.GlobalFetchTimeout` * used below takes effect. */ timeoutProvider = Function.const(800.millis), serviceIdentifier = serviceIdentifier ) private val datasetsToCache = Set( MetricCenterUserCountingFeaturesDataset ).asInstanceOf[Set[OnlineAccessDataset[_ <: EntityId, _]]] private val datasetValuesCache: DatasetValuesCache = DatasetValuesCache( Caffeine .newBuilder() .expireAfterWrite(randomizedTTL(12.hours.inSeconds), TimeUnit.SECONDS) .maximumSize(DefaultCacheMaxKeys) .build[(_ <: EntityId, DatasetId), Stitch[HydrationResponse[_]]] .asMap, datasetsToCache, DatasetCacheScope ) private val dynamicFeatureStoreClient = DynamicFeatureStoreClient( clientConfig, backupSourceStats, Set(datasetValuesCache) ) private val adapter: IRecordOneToOneAdapter[PredictionRecord] = PredictionRecordAdapter.oneToOne( BoundFeatureSet(allFeatures), OnlineFeatureGenerationStats(backupSourceStats) ) override def hydrateFeatures( target: HasClientContext with HasPreFetchedFeature with HasParams with HasSimilarToContext with HasDisplayLocation, candidates: Seq[CandidateUser] ): Stitch[Map[CandidateUser, DataRecord]] = { target.getOptionalUserId .map { targetUserId => val featureRequests = candidates.map { candidate => val userEntityId = UserEntity.withId(UserId(targetUserId)) val candidateEntityId = CandidateUserEntity.withId(UserId(candidate.id)) val similarToUserId = target.similarToUserIds.map(id => AuthorEntity.withId(UserId(id))) val topicProof = candidate.reason.flatMap(_.accountProof.flatMap(_.topicProof)) val authorTopicEntity = if (topicProof.isDefined) { backupSourceStats.counter("candidates_with_topic_proof").incr() Set( AuthorTopicEntity.withId( EdgeEntityId(UserId(candidate.id), TopicId(topicProof.get.topicId)))) } else Nil val entities = Seq(userEntityId, candidateEntityId) ++ similarToUserId ++ authorTopicEntity FeatureStoreRequest(entities) } val predictionRecordsFut = dynamicFeatureStoreClient(featureRequests, target) val candidateFeatureMap = predictionRecordsFut.map { predictionRecords => // we can zip predictionRecords with candidates as the order is preserved in the client candidates .zip(predictionRecords).map { case (candidate, predictionRecord) => candidate -> adaptAdditionalFeaturesToDataRecord( adapter.adaptToDataRecord(predictionRecord), adapterStats, FeatureStoreSource.featureAdapters) }.toMap } Stitch .callFuture(candidateFeatureMap) .within(target.params(FeatureStoreSourceParams.GlobalFetchTimeout))( com.twitter.finagle.util.DefaultTimer) .rescue { case _: TimeoutException => Stitch.value(Map.empty[CandidateUser, DataRecord]) } }.getOrElse(Stitch.value(Map.empty[CandidateUser, DataRecord])) } } object FeatureStoreUserMetricCountsSource { private val DatasetCacheScope = "feature_store_local_cache_mc_user_counting" private val DefaultCacheMaxKeys = 20000 val allFeatures: Set[BoundFeature[_ <: EntityId, _]] = FeatureStoreFeatures.candidateUserMetricCountFeatures ++ FeatureStoreFeatures.similarToUserMetricCountFeatures ++ FeatureStoreFeatures.targetUserMetricCountFeatures val getFeatureContext: FeatureContext = BoundFeatureSet(allFeatures).toFeatureContext val dynamicHydrationConfig: DynamicHydrationConfig[HasParams] = DynamicHydrationConfig( Set( GatedFeatures( boundFeatureSet = BoundFeatureSet(FeatureStoreFeatures.targetUserMetricCountFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForMetricCenterUserCounting) & HasParams.paramGate(FeatureStoreSourceParams.EnableTargetUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(FeatureStoreFeatures.candidateUserMetricCountFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForMetricCenterUserCounting) & HasParams.paramGate(FeatureStoreSourceParams.EnableCandidateUserFeatures) ), GatedFeatures( boundFeatureSet = BoundFeatureSet(FeatureStoreFeatures.similarToUserMetricCountFeatures), gate = HasParams .paramGate(FeatureStoreSourceParams.EnableSeparateClientForMetricCenterUserCounting) & HasParams.paramGate(FeatureStoreSourceParams.EnableSimilarToUserFeatures) ), )) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/HydrationSourcesModule.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.google.inject.Provides import com.google.inject.Singleton import com.twitter.escherbird.util.stitchcache.StitchCache import com.twitter.finagle.mtls.authentication.ServiceIdentifier import com.twitter.finagle.stats.StatsReceiver import com.twitter.inject.TwitterModule import com.twitter.stitch.Stitch import com.twitter.storage.client.manhattan.bijections.Bijections.BinaryCompactScalaInjection import com.twitter.storage.client.manhattan.bijections.Bijections.LongInjection import com.twitter.storage.client.manhattan.kv.Guarantee import com.twitter.storage.client.manhattan.kv.ManhattanKVClient import com.twitter.storage.client.manhattan.kv.ManhattanKVClientMtlsParams import com.twitter.storage.client.manhattan.kv.ManhattanKVEndpoint import com.twitter.storage.client.manhattan.kv.ManhattanKVEndpointBuilder import com.twitter.storage.client.manhattan.kv.impl.Component import com.twitter.storage.client.manhattan.kv.impl.Component0 import com.twitter.storage.client.manhattan.kv.impl.KeyDescriptor import com.twitter.storage.client.manhattan.kv.impl.ValueDescriptor import com.twitter.strato.generated.client.ml.featureStore.McUserCountingOnUserClientColumn import com.twitter.strato.generated.client.ml.featureStore.onboarding.TimelinesAuthorFeaturesOnUserClientColumn import com.twitter.timelines.author_features.v1.thriftscala.AuthorFeatures import com.twitter.conversions.DurationOps._ import com.twitter.onboarding.relevance.features.thriftscala.MCUserCountingFeatures import java.lang.{Long => JLong} import scala.util.Random object HydrationSourcesModule extends TwitterModule { val readFromManhattan = flag( "feature_hydration_enable_reading_from_manhattan", false, "Whether to read the data from Manhattan or Strato") val manhattanAppId = flag("frs_readonly.appId", "ml_features_athena", "RO App Id used by the RO FRS service") val manhattanDestName = flag( "frs_readonly.destName", "/s/manhattan/athena.native-thrift", "manhattan Dest Name used by the RO FRS service") @Provides @Singleton def providesAthenaManhattanClient( serviceIdentifier: ServiceIdentifier ): ManhattanKVEndpoint = { val client = ManhattanKVClient( manhattanAppId(), manhattanDestName(), ManhattanKVClientMtlsParams(serviceIdentifier) ) ManhattanKVEndpointBuilder(client) .defaultGuarantee(Guarantee.Weak) .build() } val manhattanAuthorDataset = "timelines_author_features" private val defaultCacheMaxKeys = 60000 private val cacheTTL = 12.hours private val earlyExpiration = 0.2 val authorKeyDesc = KeyDescriptor(Component(LongInjection), Component0) val authorDatasetKey = authorKeyDesc.withDataset(manhattanAuthorDataset) val authorValDesc = ValueDescriptor(BinaryCompactScalaInjection(AuthorFeatures)) @Provides @Singleton def timelinesAuthorStitchCache( manhattanReadOnlyEndpoint: ManhattanKVEndpoint, timelinesAuthorFeaturesColumn: TimelinesAuthorFeaturesOnUserClientColumn, stats: StatsReceiver ): StitchCache[JLong, Option[AuthorFeatures]] = { val stitchCacheStats = stats .scope("direct_ds_source_feature_hydration_module").scope("timelines_author") val stStat = stitchCacheStats.counter("readFromStrato-each") val mhtStat = stitchCacheStats.counter("readFromManhattan-each") val timelinesAuthorUnderlyingCall = if (readFromManhattan()) { stitchCacheStats.counter("readFromManhattan").incr() val authorCacheUnderlyingManhattanCall: JLong => Stitch[Option[AuthorFeatures]] = id => { mhtStat.incr() val key = authorDatasetKey.withPkey(id) manhattanReadOnlyEndpoint .get(key = key, valueDesc = authorValDesc).map(_.map(value => clearUnsedFieldsForAuthorFeature(value.contents))) } authorCacheUnderlyingManhattanCall } else { stitchCacheStats.counter("readFromStrato").incr() val authorCacheUnderlyingStratoCall: JLong => Stitch[Option[AuthorFeatures]] = id => { stStat.incr() val timelinesAuthorFeaturesFetcher = timelinesAuthorFeaturesColumn.fetcher timelinesAuthorFeaturesFetcher .fetch(id).map(result => result.v.map(clearUnsedFieldsForAuthorFeature)) } authorCacheUnderlyingStratoCall } StitchCache[JLong, Option[AuthorFeatures]]( underlyingCall = timelinesAuthorUnderlyingCall, maxCacheSize = defaultCacheMaxKeys, ttl = randomizedTTL(cacheTTL.inSeconds).seconds, statsReceiver = stitchCacheStats ) } // Not adding manhattan since it didn't seem useful for Author Data, we can add in another phab // if deemed helpful @Provides @Singleton def metricCenterUserCountingStitchCache( mcUserCountingFeaturesColumn: McUserCountingOnUserClientColumn, stats: StatsReceiver ): StitchCache[JLong, Option[MCUserCountingFeatures]] = { val stitchCacheStats = stats .scope("direct_ds_source_feature_hydration_module").scope("mc_user_counting") val stStat = stitchCacheStats.counter("readFromStrato-each") stitchCacheStats.counter("readFromStrato").incr() val mcUserCountingCacheUnderlyingCall: JLong => Stitch[Option[MCUserCountingFeatures]] = id => { stStat.incr() val mcUserCountingFeaturesFetcher = mcUserCountingFeaturesColumn.fetcher mcUserCountingFeaturesFetcher.fetch(id).map(_.v) } StitchCache[JLong, Option[MCUserCountingFeatures]]( underlyingCall = mcUserCountingCacheUnderlyingCall, maxCacheSize = defaultCacheMaxKeys, ttl = randomizedTTL(cacheTTL.inSeconds).seconds, statsReceiver = stitchCacheStats ) } // clear out fields we don't need to save cache space private def clearUnsedFieldsForAuthorFeature(entry: AuthorFeatures): AuthorFeatures = { entry.unsetUserTopics.unsetUserHealth.unsetAuthorCountryCodeAggregates.unsetOriginalAuthorCountryCodeAggregates } // To avoid a cache stampede. See https://en.wikipedia.org/wiki/Cache_stampede private def randomizedTTL(ttl: Long): Long = { (ttl - ttl * earlyExpiration * Random.nextDouble()).toLong } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/PreFetchedFeatureSource.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.google.inject.Inject import com.google.inject.Provides import com.google.inject.Singleton import com.twitter.follow_recommendations.common.feature_hydration.adapters.PreFetchedFeatureAdapter import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSource import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSourceId import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams @Provides @Singleton class PreFetchedFeatureSource @Inject() () extends FeatureSource { override def id: FeatureSourceId = FeatureSourceId.PreFetchedFeatureSourceId override def featureContext: FeatureContext = PreFetchedFeatureAdapter.getFeatureContext override def hydrateFeatures( target: HasClientContext with HasPreFetchedFeature with HasParams with HasSimilarToContext with HasDisplayLocation, candidates: Seq[CandidateUser] ): Stitch[Map[CandidateUser, DataRecord]] = { Stitch.value(candidates.map { candidate => candidate -> PreFetchedFeatureAdapter.adaptToDataRecord((target, candidate)) }.toMap) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/UserScoringFeatureSource.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.google.inject.Inject import com.google.inject.Provides import com.google.inject.Singleton import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSource import com.twitter.follow_recommendations.common.feature_hydration.common.FeatureSourceId import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature import com.twitter.follow_recommendations.common.models.CandidateUser import com.twitter.follow_recommendations.common.models.HasDisplayLocation import com.twitter.follow_recommendations.common.models.HasSimilarToContext import com.twitter.ml.api.DataRecord import com.twitter.ml.api.DataRecordMerger import com.twitter.ml.api.FeatureContext import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext import com.twitter.stitch.Stitch import com.twitter.timelines.configapi.HasParams /** * This source wraps around the separate sources that we hydrate features from * @param featureStoreSource gets features that require a RPC call to feature store * @param stratoFeatureHydrationSource gets features that require a RPC call to strato columns * @param clientContextSource gets features that are already present in the request context * @param candidateAlgorithmSource gets features that are already present from candidate generation * @param preFetchedFeatureSource gets features that were prehydrated (shared in request lifecycle) */ @Provides @Singleton class UserScoringFeatureSource @Inject() ( featureStoreSource: FeatureStoreSource, featureStoreGizmoduckSource: FeatureStoreGizmoduckSource, featureStorePostNuxAlgorithmSource: FeatureStorePostNuxAlgorithmSource, featureStoreTimelinesAuthorSource: FeatureStoreTimelinesAuthorSource, featureStoreUserMetricCountsSource: FeatureStoreUserMetricCountsSource, clientContextSource: ClientContextSource, candidateAlgorithmSource: CandidateAlgorithmSource, preFetchedFeatureSource: PreFetchedFeatureSource) extends FeatureSource { override val id: FeatureSourceId = FeatureSourceId.UserScoringFeatureSourceId override val featureContext: FeatureContext = FeatureContext.merge( featureStoreSource.featureContext, featureStoreGizmoduckSource.featureContext, featureStorePostNuxAlgorithmSource.featureContext, featureStoreTimelinesAuthorSource.featureContext, featureStoreUserMetricCountsSource.featureContext, clientContextSource.featureContext, candidateAlgorithmSource.featureContext, preFetchedFeatureSource.featureContext, ) val sources = Seq( featureStoreSource, featureStorePostNuxAlgorithmSource, featureStoreTimelinesAuthorSource, featureStoreUserMetricCountsSource, featureStoreGizmoduckSource, clientContextSource, candidateAlgorithmSource, preFetchedFeatureSource ) val dataRecordMerger = new DataRecordMerger def hydrateFeatures( target: HasClientContext with HasPreFetchedFeature with HasParams with HasSimilarToContext with HasDisplayLocation, candidates: Seq[CandidateUser] ): Stitch[Map[CandidateUser, DataRecord]] = { Stitch.collect(sources.map(_.hydrateFeatures(target, candidates))).map { featureMaps => (for { candidate <- candidates } yield { val combinedDataRecord = new DataRecord featureMaps .flatMap(_.get(candidate).toSeq).foreach(dataRecordMerger.merge(combinedDataRecord, _)) candidate -> combinedDataRecord }).toMap } } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources/Utils.scala
package com.twitter.follow_recommendations.common.feature_hydration.sources import com.twitter.finagle.stats.StatsReceiver import com.twitter.ml.api.DataRecord import com.twitter.ml.api.IRecordOneToOneAdapter import scala.util.Random /** * Helper functions for FeatureStoreSource operations in FRS are available here. */ object Utils { private val EarlyExpiration = 0.2 private[common] def adaptAdditionalFeaturesToDataRecord( record: DataRecord, adapterStats: StatsReceiver, featureAdapters: Seq[IRecordOneToOneAdapter[DataRecord]] ): DataRecord = { featureAdapters.foldRight(record) { (adapter, record) => adapterStats.counter(adapter.getClass.getSimpleName).incr() adapter.adaptToDataRecord(record) } } // To avoid a cache stampede. See https://en.wikipedia.org/wiki/Cache_stampede private[common] def randomizedTTL(ttl: Long): Long = { (ttl - ttl * EarlyExpiration * Random.nextDouble()).toLong } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/features/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", "product-mixer/core/src/main/scala/com/twitter/product_mixer/core/pipeline", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/features/LocationFeature.scala
package com.twitter.follow_recommendations.common.features import com.twitter.follow_recommendations.common.models.GeohashAndCountryCode import com.twitter.product_mixer.core.feature.FeatureWithDefaultOnFailure import com.twitter.product_mixer.core.pipeline.PipelineQuery case object LocationFeature extends FeatureWithDefaultOnFailure[PipelineQuery, Option[GeohashAndCountryCode]] { override val defaultValue: Option[GeohashAndCountryCode] = None }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/features/TrackingTokenFeature.scala
package com.twitter.follow_recommendations.common.features import com.twitter.product_mixer.core.feature.FeatureWithDefaultOnFailure import com.twitter.product_mixer.core.pipeline.PipelineQuery case object TrackingTokenFeature extends FeatureWithDefaultOnFailure[PipelineQuery, Option[Int]] { override val defaultValue: Option[Int] = None }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/features/UserStateFeature.scala
package com.twitter.follow_recommendations.common.features import com.twitter.core_workflows.user_model.thriftscala.UserState import com.twitter.product_mixer.core.feature.Feature import com.twitter.product_mixer.core.pipeline.PipelineQuery case object UserStateFeature extends Feature[PipelineQuery, Option[UserState]] {}
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/AddressBookMetadata.scala
package com.twitter.follow_recommendations.common.models import com.twitter.hermit.model.Algorithm import com.twitter.product_mixer.core.model.common.identifier.CandidateSourceIdentifier /** * contains information if a candidate is from a candidate source generated using the following signals. */ case class AddressBookMetadata( inForwardPhoneBook: Boolean, inReversePhoneBook: Boolean, inForwardEmailBook: Boolean, inReverseEmailBook: Boolean) object AddressBookMetadata { val ForwardPhoneBookCandidateSource = CandidateSourceIdentifier( Algorithm.ForwardPhoneBook.toString) val ReversePhoneBookCandidateSource = CandidateSourceIdentifier( Algorithm.ReversePhoneBook.toString) val ForwardEmailBookCandidateSource = CandidateSourceIdentifier( Algorithm.ForwardEmailBook.toString) val ReverseEmailBookCandidateSource = CandidateSourceIdentifier( Algorithm.ReverseEmailBookIbis.toString) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/AlgorithmType.scala
package com.twitter.follow_recommendations.common.models /** * Each candidate source algorithm could be based on one, or more, of the 4 general type of * information we have on a user: * 1. Social: the user's connections in Twitter's social graph. * 2. Geo: the user's geographical information. * 3. Interest: information on the user's chosen interests. * 4. Activity: information on the user's past activity. * * Note that an algorithm can fall under more than one of these categories. */ object AlgorithmType extends Enumeration { type AlgorithmType = Value val Social: Value = Value("social") val Geo: Value = Value("geo") val Activity: Value = Value("activity") val Interest: Value = Value("interest") }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/BUILD
scala_library( compiler_option_sets = ["fatal_warnings"], platform = "java8", tags = ["bazel-compatible"], dependencies = [ "configapi/configapi-core/src/main/scala/com/twitter/timelines/configapi", "follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/common", "follow-recommendations-service/thrift/src/main/thrift:thrift-scala", "hermit/hermit-core/src/main/scala/com/twitter/hermit/constants", "hermit/hermit-core/src/main/scala/com/twitter/hermit/model", "hermit/hermit-ml/src/main/scala/com/twitter/hermit/ml/models", "product-mixer/core/src/main/scala/com/twitter/product_mixer/core/functional_component/candidate_source", "product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/common", "product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/common/identifier", "product-mixer/core/src/main/scala/com/twitter/product_mixer/core/model/marshalling/request", "product-mixer/core/src/main/thrift/com/twitter/product_mixer/core:thrift-scala", "scrooge/scrooge-serializer/src/main/scala", "src/java/com/twitter/ml/api:api-base", "src/scala/com/twitter/ml/api/util", "src/scala/com/twitter/wtf/scalding/jobs/strong_tie_prediction", "src/thrift/com/twitter/ads/adserver:adserver_rpc-scala", "src/thrift/com/twitter/timelines/author_features/user_health:thrift-scala", "user-signal-service/thrift/src/main/thrift:thrift-scala", "util/util-slf4j-api/src/main/scala/com/twitter/util/logging", ], exports = [ "util/util-slf4j-api/src/main/scala/com/twitter/util/logging", ], )
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/CandidateUser.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.ml.api.thriftscala.{DataRecord => TDataRecord} import com.twitter.ml.api.util.ScalaToJavaDataRecordConversions import com.twitter.timelines.configapi.HasParams import com.twitter.timelines.configapi.Params import com.twitter.product_mixer.core.model.common.UniversalNoun import com.twitter.product_mixer.core.model.common.identifier.CandidateSourceIdentifier trait FollowableEntity extends UniversalNoun[Long] trait Recommendation extends FollowableEntity with HasReason with HasAdMetadata with HasTrackingToken { val score: Option[Double] def toThrift: t.Recommendation def toOfflineThrift: offline.OfflineRecommendation } case class CandidateUser( override val id: Long, override val score: Option[Double] = None, override val reason: Option[Reason] = None, override val userCandidateSourceDetails: Option[UserCandidateSourceDetails] = None, override val adMetadata: Option[AdMetadata] = None, override val trackingToken: Option[TrackingToken] = None, override val dataRecord: Option[RichDataRecord] = None, override val scores: Option[Scores] = None, override val infoPerRankingStage: Option[scala.collection.Map[String, RankingInfo]] = None, override val params: Params = Params.Invalid, override val engagements: Seq[EngagementType] = Nil, override val recommendationFlowIdentifier: Option[String] = None) extends Recommendation with HasUserCandidateSourceDetails with HasDataRecord with HasScores with HasParams with HasEngagements with HasRecommendationFlowIdentifier with HasInfoPerRankingStage { val rankerIdsStr: Option[Seq[String]] = { val strs = scores.map(_.scores.flatMap(_.rankerId.map(_.toString))) if (strs.exists(_.nonEmpty)) strs else None } val thriftDataRecord: Option[TDataRecord] = for { richDataRecord <- dataRecord dr <- richDataRecord.dataRecord } yield { ScalaToJavaDataRecordConversions.javaDataRecord2ScalaDataRecord(dr) } val toOfflineUserThrift: offline.OfflineUserRecommendation = { val scoringDetails = if (userCandidateSourceDetails.isEmpty && score.isEmpty && thriftDataRecord.isEmpty) { None } else { Some( offline.ScoringDetails( candidateSourceDetails = userCandidateSourceDetails.map(_.toOfflineThrift), score = score, dataRecord = thriftDataRecord, rankerIds = rankerIdsStr, infoPerRankingStage = infoPerRankingStage.map(_.mapValues(_.toOfflineThrift)) ) ) } offline .OfflineUserRecommendation( id, reason.map(_.toOfflineThrift), adMetadata.map(_.adImpression), trackingToken.map(_.toOfflineThrift), scoringDetails = scoringDetails ) } override val toOfflineThrift: offline.OfflineRecommendation = offline.OfflineRecommendation.User(toOfflineUserThrift) val toUserThrift: t.UserRecommendation = { val scoringDetails = if (userCandidateSourceDetails.isEmpty && score.isEmpty && thriftDataRecord.isEmpty && scores.isEmpty) { None } else { Some( t.ScoringDetails( candidateSourceDetails = userCandidateSourceDetails.map(_.toThrift), score = score, dataRecord = thriftDataRecord, rankerIds = rankerIdsStr, debugDataRecord = dataRecord.flatMap(_.debugDataRecord), infoPerRankingStage = infoPerRankingStage.map(_.mapValues(_.toThrift)) ) ) } t.UserRecommendation( userId = id, reason = reason.map(_.toThrift), adImpression = adMetadata.map(_.adImpression), trackingInfo = trackingToken.map(TrackingToken.serialize), scoringDetails = scoringDetails, recommendationFlowIdentifier = recommendationFlowIdentifier ) } override val toThrift: t.Recommendation = t.Recommendation.User(toUserThrift) def setFollowProof(followProofOpt: Option[FollowProof]): CandidateUser = { this.copy( reason = reason .map { reason => reason.copy( accountProof = reason.accountProof .map { accountProof => accountProof.copy(followProof = followProofOpt) }.orElse(Some(AccountProof(followProof = followProofOpt))) ) }.orElse(Some(Reason(Some(AccountProof(followProof = followProofOpt))))) ) } def addScore(score: Score): CandidateUser = { val newScores = scores match { case Some(existingScores) => existingScores.copy(scores = existingScores.scores :+ score) case None => Scores(Seq(score)) } this.copy(scores = Some(newScores)) } } object CandidateUser { val DefaultCandidateScore = 1.0 // for converting candidate in ScoringUserRequest def fromUserRecommendation(candidate: t.UserRecommendation): CandidateUser = { // we only use the primary candidate source for now val userCandidateSourceDetails = for { scoringDetails <- candidate.scoringDetails candidateSourceDetails <- scoringDetails.candidateSourceDetails } yield UserCandidateSourceDetails( primaryCandidateSource = candidateSourceDetails.primarySource .flatMap(AlgorithmFeedbackTokens.TokenToAlgorithmMap.get).map { algo => CandidateSourceIdentifier(algo.toString) }, candidateSourceScores = fromThriftScoreMap(candidateSourceDetails.candidateSourceScores), candidateSourceRanks = fromThriftRankMap(candidateSourceDetails.candidateSourceRanks), addressBookMetadata = None ) CandidateUser( id = candidate.userId, score = candidate.scoringDetails.flatMap(_.score), reason = candidate.reason.map(Reason.fromThrift), userCandidateSourceDetails = userCandidateSourceDetails, trackingToken = candidate.trackingInfo.map(TrackingToken.deserialize), recommendationFlowIdentifier = candidate.recommendationFlowIdentifier, infoPerRankingStage = candidate.scoringDetails.flatMap( _.infoPerRankingStage.map(_.mapValues(RankingInfo.fromThrift))) ) } def fromThriftScoreMap( thriftMapOpt: Option[scala.collection.Map[String, Double]] ): Map[CandidateSourceIdentifier, Option[Double]] = { (for { thriftMap <- thriftMapOpt.toSeq (algoName, score) <- thriftMap.toSeq } yield { CandidateSourceIdentifier(algoName) -> Some(score) }).toMap } def fromThriftRankMap( thriftMapOpt: Option[scala.collection.Map[String, Int]] ): Map[CandidateSourceIdentifier, Int] = { (for { thriftMap <- thriftMapOpt.toSeq (algoName, rank) <- thriftMap.toSeq } yield { CandidateSourceIdentifier(algoName) -> rank }).toMap } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/ClientContextConverter.scala
package com.twitter.follow_recommendations.common.models import com.twitter.follow_recommendations.logging.{thriftscala => offline} import com.twitter.follow_recommendations.{thriftscala => frs} import com.twitter.product_mixer.core.model.marshalling.request.ClientContext object ClientContextConverter { def toFRSOfflineClientContextThrift( productMixerClientContext: ClientContext ): offline.OfflineClientContext = offline.OfflineClientContext( productMixerClientContext.userId, productMixerClientContext.guestId, productMixerClientContext.appId, productMixerClientContext.countryCode, productMixerClientContext.languageCode, productMixerClientContext.guestIdAds, productMixerClientContext.guestIdMarketing ) def fromThrift(clientContext: frs.ClientContext): ClientContext = ClientContext( userId = clientContext.userId, guestId = clientContext.guestId, appId = clientContext.appId, ipAddress = clientContext.ipAddress, userAgent = clientContext.userAgent, countryCode = clientContext.countryCode, languageCode = clientContext.languageCode, isTwoffice = clientContext.isTwoffice, userRoles = clientContext.userRoles.map(_.toSet), deviceId = clientContext.deviceId, guestIdAds = clientContext.guestIdAds, guestIdMarketing = clientContext.guestIdMarketing, mobileDeviceId = None, mobileDeviceAdId = None, limitAdTracking = None ) def toThrift(clientContext: ClientContext): frs.ClientContext = frs.ClientContext( userId = clientContext.userId, guestId = clientContext.guestIdAds, appId = clientContext.appId, ipAddress = clientContext.ipAddress, userAgent = clientContext.userAgent, countryCode = clientContext.countryCode, languageCode = clientContext.languageCode, isTwoffice = clientContext.isTwoffice, userRoles = clientContext.userRoles, deviceId = clientContext.deviceId, guestIdAds = clientContext.guestIdAds, guestIdMarketing = clientContext.guestIdMarketing ) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/DisplayLocation.scala
package com.twitter.follow_recommendations.common.models import com.twitter.adserver.thriftscala.{DisplayLocation => AdDisplayLocation} import com.twitter.follow_recommendations.logging.thriftscala.{ OfflineDisplayLocation => TOfflineDisplayLocation } import com.twitter.follow_recommendations.thriftscala.{DisplayLocation => TDisplayLocation} sealed trait DisplayLocation { def toThrift: TDisplayLocation def toOfflineThrift: TOfflineDisplayLocation def toFsName: String // corresponding display location in adserver if available // make sure to be consistent with the definition here def toAdDisplayLocation: Option[AdDisplayLocation] = None } /** * Make sure you add the new DL to the following files and redeploy our attribution jobs * - follow-recommendations-service/thrift/src/main/thrift/display_location.thrift * - follow-recommendations-service/thrift/src/main/thrift/logging/display_location.thrift * - follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/DisplayLocation.scala */ object DisplayLocation { case object ProfileSidebar extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.ProfileSidebar override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.ProfileSidebar override val toFsName: String = "ProfileSidebar" override val toAdDisplayLocation: Option[AdDisplayLocation] = Some( AdDisplayLocation.ProfileAccountsSidebar ) } case object HomeTimeline extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.HomeTimeline override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.HomeTimeline override val toFsName: String = "HomeTimeline" override val toAdDisplayLocation: Option[AdDisplayLocation] = Some( // it is based on the logic that HTL DL should correspond to Sidebar: AdDisplayLocation.WtfSidebar ) } case object ReactiveFollow extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.ReactiveFollow override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.ReactiveFollow override val toFsName: String = "ReactiveFollow" } case object ExploreTab extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.ExploreTab override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.ExploreTab override val toFsName: String = "ExploreTab" } case object MagicRecs extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.MagicRecs override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.MagicRecs override val toFsName: String = "MagicRecs" } case object AbUploadInjection extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.AbUploadInjection override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.AbUploadInjection override val toFsName: String = "AbUploadInjection" } case object RuxLandingPage extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.RuxLandingPage override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.RuxLandingPage override val toFsName: String = "RuxLandingPage" } case object ProfileBonusFollow extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.ProfileBonusFollow override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.ProfileBonusFollow override val toFsName: String = "ProfileBonusFollow" } case object ElectionExploreWtf extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.ElectionExploreWtf override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.ElectionExploreWtf override val toFsName: String = "ElectionExploreWtf" } case object ClusterFollow extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.ClusterFollow override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.ClusterFollow override val toFsName: String = "ClusterFollow" override val toAdDisplayLocation: Option[AdDisplayLocation] = Some( AdDisplayLocation.ClusterFollow ) } case object HtlBonusFollow extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.HtlBonusFollow override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.HtlBonusFollow override val toFsName: String = "HtlBonusFollow" } case object TopicLandingPageHeader extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.TopicLandingPageHeader override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.TopicLandingPageHeader override val toFsName: String = "TopicLandingPageHeader" } case object NewUserSarusBackfill extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.NewUserSarusBackfill override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.NewUserSarusBackfill override val toFsName: String = "NewUserSarusBackfill" } case object NuxPymk extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.NuxPymk override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.NuxPymk override val toFsName: String = "NuxPymk" } case object NuxInterests extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.NuxInterests override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.NuxInterests override val toFsName: String = "NuxInterests" } case object NuxTopicBonusFollow extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.NuxTopicBonusFollow override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.NuxTopicBonusFollow override val toFsName: String = "NuxTopicBonusFollow" } case object Sidebar extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.Sidebar override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.Sidebar override val toFsName: String = "Sidebar" override val toAdDisplayLocation: Option[AdDisplayLocation] = Some( AdDisplayLocation.WtfSidebar ) } case object CampaignForm extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.CampaignForm override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.CampaignForm override val toFsName: String = "CampaignForm" } case object ProfileTopFollowers extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.ProfileTopFollowers override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.ProfileTopFollowers override val toFsName: String = "ProfileTopFollowers" } case object ProfileTopFollowing extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.ProfileTopFollowing override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.ProfileTopFollowing override val toFsName: String = "ProfileTopFollowing" } case object RuxPymk extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.RuxPymk override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.RuxPymk override val toFsName: String = "RuxPymk" } case object IndiaCovid19CuratedAccountsWtf extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.IndiaCovid19CuratedAccountsWtf override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.IndiaCovid19CuratedAccountsWtf override val toFsName: String = "IndiaCovid19CuratedAccountsWtf" } case object PeoplePlusPlus extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.PeoplePlusPlus override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.PeoplePlusPlus override val toFsName: String = "PeoplePlusPlus" } case object TweetNotificationRecs extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.TweetNotificationRecs override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.TweetNotificationRecs override val toFsName: String = "TweetNotificationRecs" } case object ProfileDeviceFollow extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.ProfileDeviceFollow override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.ProfileDeviceFollow override val toFsName: String = "ProfileDeviceFollow" } case object RecosBackfill extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.RecosBackfill override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.RecosBackfill override val toFsName: String = "RecosBackfill" } case object HtlSpaceHosts extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.HtlSpaceHosts override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.HtlSpaceHosts override val toFsName: String = "HtlSpaceHosts" } case object PostNuxFollowTask extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.PostNuxFollowTask override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.PostNuxFollowTask override val toFsName: String = "PostNuxFollowTask" } case object TopicLandingPage extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.TopicLandingPage override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.TopicLandingPage override val toFsName: String = "TopicLandingPage" } case object UserTypeaheadPrefetch extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.UserTypeaheadPrefetch override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.UserTypeaheadPrefetch override val toFsName: String = "UserTypeaheadPrefetch" } case object HomeTimelineRelatableAccounts extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.HomeTimelineRelatableAccounts override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.HomeTimelineRelatableAccounts override val toFsName: String = "HomeTimelineRelatableAccounts" } case object NuxGeoCategory extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.NuxGeoCategory override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.NuxGeoCategory override val toFsName: String = "NuxGeoCategory" } case object NuxInterestsCategory extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.NuxInterestsCategory override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.NuxInterestsCategory override val toFsName: String = "NuxInterestsCategory" } case object TopArticles extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.TopArticles override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.TopArticles override val toFsName: String = "TopArticles" } case object NuxPymkCategory extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.NuxPymkCategory override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.NuxPymkCategory override val toFsName: String = "NuxPymkCategory" } case object HomeTimelineTweetRecs extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.HomeTimelineTweetRecs override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.HomeTimelineTweetRecs override val toFsName: String = "HomeTimelineTweetRecs" } case object HtlBulkFriendFollows extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.HtlBulkFriendFollows override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.HtlBulkFriendFollows override val toFsName: String = "HtlBulkFriendFollows" } case object NuxAutoFollow extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.NuxAutoFollow override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.NuxAutoFollow override val toFsName: String = "NuxAutoFollow" } case object SearchBonusFollow extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.SearchBonusFollow override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.SearchBonusFollow override val toFsName: String = "SearchBonusFollow" } case object ContentRecommender extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.ContentRecommender override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.ContentRecommender override val toFsName: String = "ContentRecommender" } case object HomeTimelineReverseChron extends DisplayLocation { override val toThrift: TDisplayLocation = TDisplayLocation.HomeTimelineReverseChron override val toOfflineThrift: TOfflineDisplayLocation = TOfflineDisplayLocation.HomeTimelineReverseChron override val toFsName: String = "HomeTimelineReverseChron" } def fromThrift(displayLocation: TDisplayLocation): DisplayLocation = displayLocation match { case TDisplayLocation.ProfileSidebar => ProfileSidebar case TDisplayLocation.HomeTimeline => HomeTimeline case TDisplayLocation.MagicRecs => MagicRecs case TDisplayLocation.AbUploadInjection => AbUploadInjection case TDisplayLocation.RuxLandingPage => RuxLandingPage case TDisplayLocation.ProfileBonusFollow => ProfileBonusFollow case TDisplayLocation.ElectionExploreWtf => ElectionExploreWtf case TDisplayLocation.ClusterFollow => ClusterFollow case TDisplayLocation.HtlBonusFollow => HtlBonusFollow case TDisplayLocation.ReactiveFollow => ReactiveFollow case TDisplayLocation.TopicLandingPageHeader => TopicLandingPageHeader case TDisplayLocation.NewUserSarusBackfill => NewUserSarusBackfill case TDisplayLocation.NuxPymk => NuxPymk case TDisplayLocation.NuxInterests => NuxInterests case TDisplayLocation.NuxTopicBonusFollow => NuxTopicBonusFollow case TDisplayLocation.ExploreTab => ExploreTab case TDisplayLocation.Sidebar => Sidebar case TDisplayLocation.CampaignForm => CampaignForm case TDisplayLocation.ProfileTopFollowers => ProfileTopFollowers case TDisplayLocation.ProfileTopFollowing => ProfileTopFollowing case TDisplayLocation.RuxPymk => RuxPymk case TDisplayLocation.IndiaCovid19CuratedAccountsWtf => IndiaCovid19CuratedAccountsWtf case TDisplayLocation.PeoplePlusPlus => PeoplePlusPlus case TDisplayLocation.TweetNotificationRecs => TweetNotificationRecs case TDisplayLocation.ProfileDeviceFollow => ProfileDeviceFollow case TDisplayLocation.RecosBackfill => RecosBackfill case TDisplayLocation.HtlSpaceHosts => HtlSpaceHosts case TDisplayLocation.PostNuxFollowTask => PostNuxFollowTask case TDisplayLocation.TopicLandingPage => TopicLandingPage case TDisplayLocation.UserTypeaheadPrefetch => UserTypeaheadPrefetch case TDisplayLocation.HomeTimelineRelatableAccounts => HomeTimelineRelatableAccounts case TDisplayLocation.NuxGeoCategory => NuxGeoCategory case TDisplayLocation.NuxInterestsCategory => NuxInterestsCategory case TDisplayLocation.TopArticles => TopArticles case TDisplayLocation.NuxPymkCategory => NuxPymkCategory case TDisplayLocation.HomeTimelineTweetRecs => HomeTimelineTweetRecs case TDisplayLocation.HtlBulkFriendFollows => HtlBulkFriendFollows case TDisplayLocation.NuxAutoFollow => NuxAutoFollow case TDisplayLocation.SearchBonusFollow => SearchBonusFollow case TDisplayLocation.ContentRecommender => ContentRecommender case TDisplayLocation.HomeTimelineReverseChron => HomeTimelineReverseChron case TDisplayLocation.EnumUnknownDisplayLocation(i) => throw new UnknownDisplayLocationException( s"Unknown display location thrift enum with value: ${i}") } def fromOfflineThrift(displayLocation: TOfflineDisplayLocation): DisplayLocation = displayLocation match { case TOfflineDisplayLocation.ProfileSidebar => ProfileSidebar case TOfflineDisplayLocation.HomeTimeline => HomeTimeline case TOfflineDisplayLocation.MagicRecs => MagicRecs case TOfflineDisplayLocation.AbUploadInjection => AbUploadInjection case TOfflineDisplayLocation.RuxLandingPage => RuxLandingPage case TOfflineDisplayLocation.ProfileBonusFollow => ProfileBonusFollow case TOfflineDisplayLocation.ElectionExploreWtf => ElectionExploreWtf case TOfflineDisplayLocation.ClusterFollow => ClusterFollow case TOfflineDisplayLocation.HtlBonusFollow => HtlBonusFollow case TOfflineDisplayLocation.TopicLandingPageHeader => TopicLandingPageHeader case TOfflineDisplayLocation.NewUserSarusBackfill => NewUserSarusBackfill case TOfflineDisplayLocation.NuxPymk => NuxPymk case TOfflineDisplayLocation.NuxInterests => NuxInterests case TOfflineDisplayLocation.NuxTopicBonusFollow => NuxTopicBonusFollow case TOfflineDisplayLocation.ExploreTab => ExploreTab case TOfflineDisplayLocation.ReactiveFollow => ReactiveFollow case TOfflineDisplayLocation.Sidebar => Sidebar case TOfflineDisplayLocation.CampaignForm => CampaignForm case TOfflineDisplayLocation.ProfileTopFollowers => ProfileTopFollowers case TOfflineDisplayLocation.ProfileTopFollowing => ProfileTopFollowing case TOfflineDisplayLocation.RuxPymk => RuxPymk case TOfflineDisplayLocation.IndiaCovid19CuratedAccountsWtf => IndiaCovid19CuratedAccountsWtf case TOfflineDisplayLocation.PeoplePlusPlus => PeoplePlusPlus case TOfflineDisplayLocation.TweetNotificationRecs => TweetNotificationRecs case TOfflineDisplayLocation.ProfileDeviceFollow => ProfileDeviceFollow case TOfflineDisplayLocation.RecosBackfill => RecosBackfill case TOfflineDisplayLocation.HtlSpaceHosts => HtlSpaceHosts case TOfflineDisplayLocation.PostNuxFollowTask => PostNuxFollowTask case TOfflineDisplayLocation.TopicLandingPage => TopicLandingPage case TOfflineDisplayLocation.UserTypeaheadPrefetch => UserTypeaheadPrefetch case TOfflineDisplayLocation.HomeTimelineRelatableAccounts => HomeTimelineRelatableAccounts case TOfflineDisplayLocation.NuxGeoCategory => NuxGeoCategory case TOfflineDisplayLocation.NuxInterestsCategory => NuxInterestsCategory case TOfflineDisplayLocation.TopArticles => TopArticles case TOfflineDisplayLocation.NuxPymkCategory => NuxPymkCategory case TOfflineDisplayLocation.HomeTimelineTweetRecs => HomeTimelineTweetRecs case TOfflineDisplayLocation.HtlBulkFriendFollows => HtlBulkFriendFollows case TOfflineDisplayLocation.NuxAutoFollow => NuxAutoFollow case TOfflineDisplayLocation.SearchBonusFollow => SearchBonusFollow case TOfflineDisplayLocation.ContentRecommender => ContentRecommender case TOfflineDisplayLocation.HomeTimelineReverseChron => HomeTimelineReverseChron case TOfflineDisplayLocation.EnumUnknownOfflineDisplayLocation(i) => throw new UnknownDisplayLocationException( s"Unknown offline display location thrift enum with value: ${i}") } } class UnknownDisplayLocationException(message: String) extends Exception(message)
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/EngagementType.scala
package com.twitter.follow_recommendations.common.models import com.twitter.follow_recommendations.thriftscala.{EngagementType => TEngagementType} import com.twitter.follow_recommendations.logging.thriftscala.{ EngagementType => OfflineEngagementType } sealed trait EngagementType { def toThrift: TEngagementType def toOfflineThrift: OfflineEngagementType } object EngagementType { object Click extends EngagementType { override val toThrift: TEngagementType = TEngagementType.Click override val toOfflineThrift: OfflineEngagementType = OfflineEngagementType.Click } object Like extends EngagementType { override val toThrift: TEngagementType = TEngagementType.Like override val toOfflineThrift: OfflineEngagementType = OfflineEngagementType.Like } object Mention extends EngagementType { override val toThrift: TEngagementType = TEngagementType.Mention override val toOfflineThrift: OfflineEngagementType = OfflineEngagementType.Mention } object Retweet extends EngagementType { override val toThrift: TEngagementType = TEngagementType.Retweet override val toOfflineThrift: OfflineEngagementType = OfflineEngagementType.Retweet } object ProfileView extends EngagementType { override val toThrift: TEngagementType = TEngagementType.ProfileView override val toOfflineThrift: OfflineEngagementType = OfflineEngagementType.ProfileView } def fromThrift(engagementType: TEngagementType): EngagementType = engagementType match { case TEngagementType.Click => Click case TEngagementType.Like => Like case TEngagementType.Mention => Mention case TEngagementType.Retweet => Retweet case TEngagementType.ProfileView => ProfileView case TEngagementType.EnumUnknownEngagementType(i) => throw new UnknownEngagementTypeException( s"Unknown engagement type thrift enum with value: ${i}") } def fromOfflineThrift(engagementType: OfflineEngagementType): EngagementType = engagementType match { case OfflineEngagementType.Click => Click case OfflineEngagementType.Like => Like case OfflineEngagementType.Mention => Mention case OfflineEngagementType.Retweet => Retweet case OfflineEngagementType.ProfileView => ProfileView case OfflineEngagementType.EnumUnknownEngagementType(i) => throw new UnknownEngagementTypeException( s"Unknown engagement type offline thrift enum with value: ${i}") } } class UnknownEngagementTypeException(message: String) extends Exception(message)
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/FilterReason.scala
package com.twitter.follow_recommendations.common.models sealed trait FilterReason { def reason: String } object FilterReason { case object NoReason extends FilterReason { override val reason: String = "no_reason" } case class ParamReason(paramName: String) extends FilterReason { override val reason: String = s"param_$paramName" } case object ExcludedId extends FilterReason { override val reason: String = "excluded_id_from_request" } case object ProfileSidebarBlacklist extends FilterReason { override val reason: String = "profile_sidebar_blacklisted_id" } case object CuratedAccountsCompetitorList extends FilterReason { override val reason: String = "curated_blacklisted_id" } case class InvalidRelationshipTypes(relationshipTypes: String) extends FilterReason { override val reason: String = s"invalid_relationship_types $relationshipTypes" } case object ProfileId extends FilterReason { override val reason: String = "candidate_has_same_id_as_profile" } case object DismissedId extends FilterReason { override val reason: String = s"dismissed_candidate" } case object OptedOutId extends FilterReason { override val reason: String = s"candidate_opted_out_from_criteria_in_request" } // gizmoduck predicates case object NoUser extends FilterReason { override val reason: String = "no_user_result_from_gizmoduck" } case object AddressBookUndiscoverable extends FilterReason { override val reason: String = "not_discoverable_via_address_book" } case object PhoneBookUndiscoverable extends FilterReason { override val reason: String = "not_discoverable_via_phone_book" } case object Deactivated extends FilterReason { override val reason: String = "deactivated" } case object Suspended extends FilterReason { override val reason: String = "suspended" } case object Restricted extends FilterReason { override val reason: String = "restricted" } case object NsfwUser extends FilterReason { override val reason: String = "nsfwUser" } case object NsfwAdmin extends FilterReason { override val reason: String = "nsfwAdmin" } case object HssSignal extends FilterReason { override val reason: String = "hssSignal" } case object IsProtected extends FilterReason { override val reason: String = "isProtected" } case class CountryTakedown(countryCode: String) extends FilterReason { override val reason: String = s"takedown_in_$countryCode" } case object Blink extends FilterReason { override val reason: String = "blink" } case object AlreadyFollowed extends FilterReason { override val reason: String = "already_followed" } case object InvalidRelationship extends FilterReason { override val reason: String = "invalid_relationship" } case object NotFollowingTargetUser extends FilterReason { override val reason: String = "not_following_target_user" } case object CandidateSideHoldback extends FilterReason { override val reason: String = "candidate_side_holdback" } case object Inactive extends FilterReason { override val reason: String = "inactive" } case object MissingRecommendabilityData extends FilterReason { override val reason: String = "missing_recommendability_data" } case object HighTweetVelocity extends FilterReason { override val reason: String = "high_tweet_velocity" } case object AlreadyRecommended extends FilterReason { override val reason: String = "already_recommended" } case object MinStateNotMet extends FilterReason { override val reason: String = "min_state_user_not_met" } case object FailOpen extends FilterReason { override val reason: String = "fail_open" } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/FlowContext.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 FlowContext(steps: Seq[RecommendationStep]) { def toThrift: t.FlowContext = t.FlowContext(steps = steps.map(_.toThrift)) def toOfflineThrift: offline.OfflineFlowContext = offline.OfflineFlowContext(steps = steps.map(_.toOfflineThrift)) } object FlowContext { def fromThrift(flowContext: t.FlowContext): FlowContext = { FlowContext(steps = flowContext.steps.map(RecommendationStep.fromThrift)) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/FlowRecommendation.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 FlowRecommendation(userId: Long) { def toThrift: t.FlowRecommendation = t.FlowRecommendation(userId = userId) def toOfflineThrift: offline.OfflineFlowRecommendation = offline.OfflineFlowRecommendation(userId = userId) } object FlowRecommendation { def fromThrift(flowRecommendation: t.FlowRecommendation): FlowRecommendation = { FlowRecommendation( userId = flowRecommendation.userId ) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/GeohashAndCountryCode.scala
package com.twitter.follow_recommendations.common.models case class GeohashAndCountryCode(geohash: Option[String], countryCode: Option[String])
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasAdMetadata.scala
package com.twitter.follow_recommendations.common.models import com.twitter.adserver.{thriftscala => t} case class AdMetadata( insertPosition: Int, // use original ad impression info to avoid losing data in domain model translations adImpression: t.AdImpression) trait HasAdMetadata { def adMetadata: Option[AdMetadata] def adImpression: Option[t.AdImpression] = { adMetadata.map(_.adImpression) } def insertPosition: Option[Int] = { adMetadata.map(_.insertPosition) } def isPromotedAccount: Boolean = adMetadata.isDefined }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasByfSeedUserIds.scala
package com.twitter.follow_recommendations.common.models trait HasByfSeedUserIds { def byfSeedUserIds: Option[Seq[Long]] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasDataRecord.scala
package com.twitter.follow_recommendations.common.models import com.twitter.follow_recommendations.thriftscala.DebugDataRecord import com.twitter.ml.api.DataRecord import com.twitter.ml.api.FeatureContext import com.twitter.util.Try import com.twitter.util.logging.Logging import scala.collection.convert.ImplicitConversions._ // contains the standard dataRecord struct, and the debug version if required case class RichDataRecord( dataRecord: Option[DataRecord] = None, debugDataRecord: Option[DebugDataRecord] = None, ) trait HasDataRecord extends Logging { def dataRecord: Option[RichDataRecord] def toDebugDataRecord(dr: DataRecord, featureContext: FeatureContext): DebugDataRecord = { val binaryFeatures: Option[Set[String]] = if (dr.isSetBinaryFeatures) { Some(dr.getBinaryFeatures.flatMap { id => Try(featureContext.getFeature(id).getFeatureName).toOption }.toSet) } else None val continuousFeatures: Option[Map[String, Double]] = if (dr.isSetContinuousFeatures) { Some(dr.getContinuousFeatures.flatMap { case (id, value) => Try(featureContext.getFeature(id).getFeatureName).toOption.map { id => id -> value.toDouble } }.toMap) } else None val discreteFeatures: Option[Map[String, Long]] = if (dr.isSetDiscreteFeatures) { Some(dr.getDiscreteFeatures.flatMap { case (id, value) => Try(featureContext.getFeature(id).getFeatureName).toOption.map { id => id -> value.toLong } }.toMap) } else None val stringFeatures: Option[Map[String, String]] = if (dr.isSetStringFeatures) { Some(dr.getStringFeatures.flatMap { case (id, value) => Try(featureContext.getFeature(id).getFeatureName).toOption.map { id => id -> value } }.toMap) } else None val sparseBinaryFeatures: Option[Map[String, Set[String]]] = if (dr.isSetSparseBinaryFeatures) { Some(dr.getSparseBinaryFeatures.flatMap { case (id, values) => Try(featureContext.getFeature(id).getFeatureName).toOption.map { id => id -> values.toSet } }.toMap) } else None val sparseContinuousFeatures: Option[Map[String, Map[String, Double]]] = if (dr.isSetSparseContinuousFeatures) { Some(dr.getSparseContinuousFeatures.flatMap { case (id, values) => Try(featureContext.getFeature(id).getFeatureName).toOption.map { id => id -> values.map { case (str, value) => str -> value.toDouble }.toMap } }.toMap) } else None DebugDataRecord( binaryFeatures = binaryFeatures, continuousFeatures = continuousFeatures, discreteFeatures = discreteFeatures, stringFeatures = stringFeatures, sparseBinaryFeatures = sparseBinaryFeatures, sparseContinuousFeatures = sparseContinuousFeatures, ) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasDebugOptions.scala
package com.twitter.follow_recommendations.common.models import com.twitter.follow_recommendations.thriftscala.DebugParams case class DebugOptions( randomizationSeed: Option[Long] = None, fetchDebugInfo: Boolean = false, doNotLog: Boolean = false) object DebugOptions { def fromDebugParamsThrift(debugParams: DebugParams): DebugOptions = { DebugOptions( debugParams.randomizationSeed, debugParams.includeDebugInfoInResults.getOrElse(false), debugParams.doNotLog.getOrElse(false) ) } } trait HasDebugOptions { def debugOptions: Option[DebugOptions] def getRandomizationSeed: Option[Long] = debugOptions.flatMap(_.randomizationSeed) def fetchDebugInfo: Option[Boolean] = debugOptions.map(_.fetchDebugInfo) } trait HasFrsDebugOptions { def frsDebugOptions: Option[DebugOptions] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasDismissedUserIds.scala
package com.twitter.follow_recommendations.common.models trait HasDismissedUserIds { // user ids that are recently followed by the target user def dismissedUserIds: Option[Seq[Long]] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasDisplayLocation.scala
package com.twitter.follow_recommendations.common.models trait HasDisplayLocation { def displayLocation: DisplayLocation }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasEngagements.scala
package com.twitter.follow_recommendations.common.models trait HasEngagements { def engagements: Seq[EngagementType] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasExcludedUserIds.scala
package com.twitter.follow_recommendations.common.models trait HasExcludedUserIds { // user ids that are going to be excluded from recommendations def excludedUserIds: Seq[Long] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasGeohashAndCountryCode.scala
package com.twitter.follow_recommendations.common.models trait HasGeohashAndCountryCode { def geohashAndCountryCode: Option[GeohashAndCountryCode] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasInfoPerRankingStage.scala
package com.twitter.follow_recommendations.common.models trait HasInfoPerRankingStage { def infoPerRankingStage: Option[scala.collection.Map[String, RankingInfo]] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasInterestIds.scala
package com.twitter.follow_recommendations.common.models trait HasCustomInterests { def customInterests: Option[Seq[String]] } trait HasUttInterests { def uttInterestIds: Option[Seq[Long]] } trait HasInterestIds extends HasCustomInterests with HasUttInterests {}
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasInvalidRelationshipUserIds.scala
package com.twitter.follow_recommendations.common.models trait HasInvalidRelationshipUserIds { // user ids that have invalid relationship with the target user def invalidRelationshipUserIds: Option[Set[Long]] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasIsSoftUser.scala
package com.twitter.follow_recommendations.common.models trait HasIsSoftUser { def isSoftUser: Boolean }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasMutualFollowedUserIds.scala
package com.twitter.follow_recommendations.common.models // intersection of recent followers and followed by trait HasMutualFollowedUserIds extends HasRecentFollowedUserIds with HasRecentFollowedByUserIds { lazy val recentMutualFollows: Seq[Long] = recentFollowedUserIds.getOrElse(Nil).intersect(recentFollowedByUserIds.getOrElse(Nil)) lazy val numRecentMutualFollows: Int = recentMutualFollows.size }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasPreviousRecommendationsContext.scala
package com.twitter.follow_recommendations.common.models trait HasPreviousRecommendationsContext { def previouslyRecommendedUserIDs: Set[Long] def previouslyFollowedUserIds: Set[Long] def skippedFollows: Set[Long] = { previouslyRecommendedUserIDs.diff(previouslyFollowedUserIds) } }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasProfileId.scala
package com.twitter.follow_recommendations.common.models trait HasProfileId { def profileId: Long }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasQualityFactor.scala
package com.twitter.follow_recommendations.common.models trait HasQualityFactor { def qualityFactor: Option[Double] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasRecentFollowedByUserIds.scala
package com.twitter.follow_recommendations.common.models trait HasRecentFollowedByUserIds { // user ids that have recently followed the target user; target user has been "followed by" them. def recentFollowedByUserIds: Option[Seq[Long]] lazy val numRecentFollowedByUserIds: Int = recentFollowedByUserIds.map(_.size).getOrElse(0) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasRecentFollowedUserIds.scala
package com.twitter.follow_recommendations.common.models trait HasRecentFollowedUserIds { // user ids that are recently followed by the target user def recentFollowedUserIds: Option[Seq[Long]] // user ids that are recently followed by the target user in set data-structure lazy val recentFollowedUserIdsSet: Option[Set[Long]] = recentFollowedUserIds match { case Some(users) => Some(users.toSet) case None => Some(Set.empty) } lazy val numRecentFollowedUserIds: Int = recentFollowedUserIds.map(_.size).getOrElse(0) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasRecentFollowedUserIdsWithTime.scala
package com.twitter.follow_recommendations.common.models trait HasRecentFollowedUserIdsWithTime { // user ids that are recently followed by the target user def recentFollowedUserIdsWithTime: Option[Seq[UserIdWithTimestamp]] lazy val numRecentFollowedUserIdsWithTime: Int = recentFollowedUserIdsWithTime.map(_.size).getOrElse(0) }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasRecentlyEngagedUserIds.scala
package com.twitter.follow_recommendations.common.models trait HasRecentlyEngagedUserIds { val recentlyEngagedUserIds: Option[Seq[RecentlyEngagedUserId]] }
the-algorithm-main/follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/models/HasRecommendationFlowIdentifier.scala
package com.twitter.follow_recommendations.common.models trait HasRecommendationFlowIdentifier { def recommendationFlowIdentifier: Option[String] }