path stringlengths 26 218 | content stringlengths 0 231k |
|---|---|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/models/Request.scala | package com.twitter.follow_recommendations.models
import com.twitter.follow_recommendations.common.models.DisplayLocation
import com.twitter.product_mixer.core.model.marshalling.request
import com.twitter.product_mixer.core.model.marshalling.request.ClientContext
import com.twitter.product_mixer.core.model.marshalling.request.ProductContext
import com.twitter.product_mixer.core.model.marshalling.request.{Request => ProductMixerRequest}
case class Request(
override val maxResults: Option[Int],
override val debugParams: Option[request.DebugParams],
override val productContext: Option[ProductContext],
override val product: request.Product,
override val clientContext: ClientContext,
override val serializedRequestCursor: Option[String],
override val frsDebugParams: Option[DebugParams],
displayLocation: DisplayLocation,
excludedIds: Option[Seq[Long]],
fetchPromotedContent: Option[Boolean],
userLocationState: Option[String] = None)
extends ProductMixerRequest
with HasFrsDebugParams {}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/models/ScoringUserRequest.scala | package com.twitter.follow_recommendations.models
import com.twitter.follow_recommendations.common.feature_hydration.common.HasPreFetchedFeature
import com.twitter.follow_recommendations.common.models._
import com.twitter.follow_recommendations.logging.{thriftscala => offline}
import com.twitter.product_mixer.core.model.marshalling.request.ClientContext
import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext
import com.twitter.timelines.configapi.HasParams
import com.twitter.timelines.configapi.Params
case class ScoringUserRequest(
override val clientContext: ClientContext,
override val displayLocation: DisplayLocation,
override val params: Params,
override val debugOptions: Option[DebugOptions] = None,
override val recentFollowedUserIds: Option[Seq[Long]],
override val recentFollowedByUserIds: Option[Seq[Long]],
override val wtfImpressions: Option[Seq[WtfImpression]],
override val similarToUserIds: Seq[Long],
candidates: Seq[CandidateUser],
debugParams: Option[DebugParams] = None,
isSoftUser: Boolean = false)
extends HasClientContext
with HasDisplayLocation
with HasParams
with HasDebugOptions
with HasPreFetchedFeature
with HasSimilarToContext {
def toOfflineThrift: offline.OfflineScoringUserRequest = offline.OfflineScoringUserRequest(
ClientContextConverter.toFRSOfflineClientContextThrift(clientContext),
displayLocation.toOfflineThrift,
candidates.map(_.toOfflineUserThrift)
)
def toRecommendationRequest: RecommendationRequest = RecommendationRequest(
clientContext = clientContext,
displayLocation = displayLocation,
displayContext = None,
maxResults = None,
cursor = None,
excludedIds = None,
fetchPromotedContent = None,
debugParams = debugParams,
isSoftUser = isSoftUser
)
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/models/ScoringUserResponse.scala | package com.twitter.follow_recommendations.models
import com.twitter.follow_recommendations.common.models.CandidateUser
import com.twitter.follow_recommendations.logging.{thriftscala => offline}
import com.twitter.follow_recommendations.{thriftscala => t}
case class ScoringUserResponse(candidates: Seq[CandidateUser]) {
lazy val toThrift: t.ScoringUserResponse =
t.ScoringUserResponse(candidates.map(_.toUserThrift))
lazy val toRecommendationResponse: RecommendationResponse = RecommendationResponse(candidates)
lazy val toOfflineThrift: offline.OfflineScoringUserResponse =
offline.OfflineScoringUserResponse(candidates.map(_.toOfflineUserThrift))
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/models/failures/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/pipeline/pipeline_failure",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/models/failures/TimeoutPipelineFailure.scala | package com.twitter.follow_recommendations.models.failures
import com.twitter.product_mixer.core.pipeline.pipeline_failure.CandidateSourceTimeout
import com.twitter.product_mixer.core.pipeline.pipeline_failure.PipelineFailure
object TimeoutPipelineFailure {
def apply(candidateSourceName: String): PipelineFailure = {
PipelineFailure(
CandidateSourceTimeout,
s"Candidate Source $candidateSourceName timed out before returning candidates")
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/modules/ABDeciderModule.scala | package com.twitter.follow_recommendations.modules
import com.google.inject.Provides
import com.google.inject.name.Named
import com.twitter.abdecider.ABDeciderFactory
import com.twitter.abdecider.LoggingABDecider
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.follow_recommendations.common.constants.GuiceNamedConstants
import com.twitter.inject.TwitterModule
import com.twitter.logging.LoggerFactory
import javax.inject.Singleton
object ABDeciderModule extends TwitterModule {
@Provides
@Singleton
def provideABDecider(
stats: StatsReceiver,
@Named(GuiceNamedConstants.CLIENT_EVENT_LOGGER) factory: LoggerFactory
): LoggingABDecider = {
val ymlPath = "/usr/local/config/abdecider/abdecider.yml"
val abDeciderFactory = ABDeciderFactory(
abDeciderYmlPath = ymlPath,
scribeLogger = Some(factory()),
environment = Some("production")
)
abDeciderFactory.buildWithLogging()
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/modules/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/javax/inject:javax.inject",
"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",
"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/transforms/modify_social_proof",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products",
"follow-recommendations-service/thrift/src/main/thrift:thrift-scala",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/product/guice",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/product/registry",
"twml/runtime/src/main/scala/com/twitter/deepbird/runtime/prediction_engine",
"util/util-slf4j-api/src/main/scala",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/modules/ConfigApiModule.scala | package com.twitter.follow_recommendations.modules
import com.google.inject.Provides
import com.twitter.decider.Decider
import com.twitter.follow_recommendations.configapi.ConfigBuilder
import com.twitter.inject.TwitterModule
import com.twitter.servo.decider.DeciderGateBuilder
import com.twitter.timelines.configapi.Config
import javax.inject.Singleton
object ConfigApiModule extends TwitterModule {
@Provides
@Singleton
def providesDeciderGateBuilder(decider: Decider): DeciderGateBuilder =
new DeciderGateBuilder(decider)
@Provides
@Singleton
def providesConfig(configBuilder: ConfigBuilder): Config = configBuilder.build()
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/modules/DiffyModule.scala | package com.twitter.follow_recommendations.modules
import com.google.inject.Provides
import com.google.inject.Singleton
import com.twitter.inject.annotations.Flag
import com.twitter.decider.RandomRecipient
import com.twitter.finagle.ThriftMux
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.mtls.client.MtlsStackClient.MtlsThriftMuxClientSyntax
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.finagle.thrift.ClientId
import com.twitter.finatra.annotations.DarkTrafficService
import com.twitter.follow_recommendations.configapi.deciders.DeciderKey
import com.twitter.follow_recommendations.thriftscala.FollowRecommendationsThriftService
import com.twitter.inject.TwitterModule
import com.twitter.inject.thrift.filters.DarkTrafficFilter
import com.twitter.servo.decider.DeciderGateBuilder
object DiffyModule extends TwitterModule {
// diffy.dest is defined in the Follow Recommendations Service aurora file
// and points to the Dark Traffic Proxy server
private val destFlag =
flag[String]("diffy.dest", "/$/nil", "Resolvable name of diffy-service or proxy")
@Provides
@Singleton
@DarkTrafficService
def provideDarkTrafficService(
serviceIdentifier: ServiceIdentifier
): FollowRecommendationsThriftService.ReqRepServicePerEndpoint = {
ThriftMux.client
.withClientId(ClientId("follow_recos_service_darktraffic_proxy_client"))
.withMutualTls(serviceIdentifier)
.servicePerEndpoint[FollowRecommendationsThriftService.ReqRepServicePerEndpoint](
dest = destFlag(),
label = "darktrafficproxy"
)
}
@Provides
@Singleton
def provideDarkTrafficFilter(
@DarkTrafficService darkService: FollowRecommendationsThriftService.ReqRepServicePerEndpoint,
deciderGateBuilder: DeciderGateBuilder,
statsReceiver: StatsReceiver,
@Flag("environment") env: String
): DarkTrafficFilter[FollowRecommendationsThriftService.ReqRepServicePerEndpoint] = {
// sampleFunction is used to determine which requests should get replicated
// to the dark traffic proxy server
val sampleFunction: Any => Boolean = { _ =>
// check whether the current FRS instance is deployed in production
env match {
case "prod" =>
statsReceiver.scope("provideDarkTrafficFilter").counter("prod").incr()
destFlag.isDefined && deciderGateBuilder
.keyToFeature(DeciderKey.EnableTrafficDarkReading).isAvailable(RandomRecipient)
case _ =>
statsReceiver.scope("provideDarkTrafficFilter").counter("devel").incr()
// replicate zero requests if in non-production environment
false
}
}
new DarkTrafficFilter[FollowRecommendationsThriftService.ReqRepServicePerEndpoint](
darkService,
sampleFunction,
forwardAfterService = true,
statsReceiver.scope("DarkTrafficFilter"),
lookupByMethod = true
)
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/modules/FeatureSwitchesModule.scala | package com.twitter.follow_recommendations.modules
import com.google.inject.Provides
import com.twitter.abdecider.LoggingABDecider
import com.twitter.featureswitches.v2.Feature
import com.twitter.featureswitches.v2.FeatureFilter
import com.twitter.featureswitches.v2.FeatureSwitches
import com.twitter.featureswitches.v2.builder.FeatureSwitchesBuilder
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.follow_recommendations.common.constants.GuiceNamedConstants.PRODUCER_SIDE_FEATURE_SWITCHES
import com.twitter.inject.TwitterModule
import javax.inject.Named
import javax.inject.Singleton
object FeaturesSwitchesModule extends TwitterModule {
private val DefaultConfigRepoPath = "/usr/local/config"
private val FeaturesPath = "/features/onboarding/follow-recommendations-service/main"
val isLocal = flag("configrepo.local", false, "Is the server running locally or in a DC")
val localConfigRepoPath = flag(
"local.configrepo",
System.getProperty("user.home") + "/workspace/config",
"Path to your local config repo"
)
@Provides
@Singleton
def providesFeatureSwitches(
abDecider: LoggingABDecider,
statsReceiver: StatsReceiver
): FeatureSwitches = {
val configRepoPath = if (isLocal()) {
localConfigRepoPath()
} else {
DefaultConfigRepoPath
}
FeatureSwitchesBuilder
.createDefault(FeaturesPath, abDecider, Some(statsReceiver))
.configRepoAbsPath(configRepoPath)
.serviceDetailsFromAurora()
.build()
}
@Provides
@Singleton
@Named(PRODUCER_SIDE_FEATURE_SWITCHES)
def providesProducerFeatureSwitches(
abDecider: LoggingABDecider,
statsReceiver: StatsReceiver
): FeatureSwitches = {
val configRepoPath = if (isLocal()) {
localConfigRepoPath()
} else {
DefaultConfigRepoPath
}
/**
* Feature Switches evaluate all tied FS Keys on Params construction time, which is very inefficient
* for producer/candidate side holdbacks because we have 100s of candidates, and 100s of FS which result
* in 10,000 FS evaluations when we want 1 per candidate (100 total), so we create a new FS Client
* which has a [[ProducerFeatureFilter]] set for feature filter to reduce the FS Keys we evaluate.
*/
FeatureSwitchesBuilder
.createDefault(FeaturesPath, abDecider, Some(statsReceiver.scope("producer_side_fs")))
.configRepoAbsPath(configRepoPath)
.serviceDetailsFromAurora()
.addFeatureFilter(ProducerFeatureFilter)
.build()
}
}
case object ProducerFeatureFilter extends FeatureFilter {
private val AllowedKeys = Set(
"post_nux_ml_flow_candidate_user_scorer_id",
"frs_receiver_holdback_keep_social_user_candidate",
"frs_receiver_holdback_keep_user_candidate")
override def filter(feature: Feature): Option[Feature] = {
if (AllowedKeys.exists(feature.parameters.contains)) {
Some(feature)
} else {
None
}
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/modules/FlagsModule.scala | package com.twitter.follow_recommendations.modules
import com.twitter.inject.TwitterModule
object FlagsModule extends TwitterModule {
flag[Boolean](
name = "fetch_prod_promoted_accounts",
help = "Whether or not to fetch production promoted accounts (true / false)"
)
flag[Boolean](
name = "interests_opt_out_prod_enabled",
help = "Whether to fetch intersts opt out data from the prod strato column or not"
)
flag[Boolean](
name = "log_results",
default = false,
help = "Whether to log results such that we use them for scoring or metrics"
)
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/modules/ProductRegistryModule.scala | package com.twitter.follow_recommendations.modules
import com.twitter.follow_recommendations.products.ProdProductRegistry
import com.twitter.follow_recommendations.products.common.ProductRegistry
import com.twitter.inject.TwitterModule
import javax.inject.Singleton
object ProductRegistryModule extends TwitterModule {
override protected def configure(): Unit = {
bind[ProductRegistry].to[ProdProductRegistry].in[Singleton]
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/modules/ScorerModule.scala | package com.twitter.follow_recommendations.modules
import com.google.inject.Provides
import com.google.inject.Singleton
import com.twitter.inject.TwitterModule
import com.twitter.relevance.ep_model.common.CommonConstants
import com.twitter.relevance.ep_model.scorer.EPScorer
import com.twitter.relevance.ep_model.scorer.EPScorerBuilder
import java.io.File
import java.io.FileOutputStream
import scala.language.postfixOps
object ScorerModule extends TwitterModule {
private val STPScorerPath = "/quality/stp_models/20141223"
private def fileFromResource(resource: String): File = {
val inputStream = getClass.getResourceAsStream(resource)
val file = File.createTempFile(resource, "temp")
val fos = new FileOutputStream(file)
Iterator
.continually(inputStream.read)
.takeWhile(-1 !=)
.foreach(fos.write)
file
}
@Provides
@Singleton
def provideEpScorer: EPScorer = {
val modelPath =
fileFromResource(STPScorerPath + "/" + CommonConstants.EP_MODEL_FILE_NAME).getAbsolutePath
val trainingConfigPath =
fileFromResource(STPScorerPath + "/" + CommonConstants.TRAINING_CONFIG).getAbsolutePath
val epScorer = new EPScorerBuilder
epScorer
.withModelPath(modelPath)
.withTrainingConfig(trainingConfigPath)
.build()
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/modules/ScribeModule.scala | package com.twitter.follow_recommendations.modules
import com.google.inject.Provides
import com.google.inject.Singleton
import com.google.inject.name.Named
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.follow_recommendations.common.constants.GuiceNamedConstants
import com.twitter.inject.TwitterModule
import com.twitter.logging.BareFormatter
import com.twitter.logging.HandlerFactory
import com.twitter.logging.Level
import com.twitter.logging.LoggerFactory
import com.twitter.logging.NullHandler
import com.twitter.logging.QueueingHandler
import com.twitter.logging.ScribeHandler
object ScribeModule extends TwitterModule {
val useProdLogger = flag(
name = "scribe.use_prod_loggers",
default = false,
help = "whether to use production logging for service"
)
@Provides
@Singleton
@Named(GuiceNamedConstants.CLIENT_EVENT_LOGGER)
def provideClientEventsLoggerFactory(stats: StatsReceiver): LoggerFactory = {
val loggerCategory = "client_event"
val clientEventsHandler: HandlerFactory = if (useProdLogger()) {
QueueingHandler(
maxQueueSize = 10000,
handler = ScribeHandler(
category = loggerCategory,
formatter = BareFormatter,
level = Some(Level.INFO),
statsReceiver = stats.scope("client_event_scribe")
)
)
} else { () => NullHandler }
LoggerFactory(
node = "abdecider",
level = Some(Level.INFO),
useParents = false,
handlers = clientEventsHandler :: Nil
)
}
@Provides
@Singleton
@Named(GuiceNamedConstants.REQUEST_LOGGER)
def provideFollowRecommendationsLoggerFactory(stats: StatsReceiver): LoggerFactory = {
val loggerCategory = "follow_recommendations_logs"
val handlerFactory: HandlerFactory = if (useProdLogger()) {
QueueingHandler(
maxQueueSize = 10000,
handler = ScribeHandler(
category = loggerCategory,
formatter = BareFormatter,
level = Some(Level.INFO),
statsReceiver = stats.scope("follow_recommendations_logs_scribe")
)
)
} else { () => NullHandler }
LoggerFactory(
node = loggerCategory,
level = Some(Level.INFO),
useParents = false,
handlers = handlerFactory :: Nil
)
}
@Provides
@Singleton
@Named(GuiceNamedConstants.FLOW_LOGGER)
def provideFrsRecommendationFlowLoggerFactory(stats: StatsReceiver): LoggerFactory = {
val loggerCategory = "frs_recommendation_flow_logs"
val handlerFactory: HandlerFactory = if (useProdLogger()) {
QueueingHandler(
maxQueueSize = 10000,
handler = ScribeHandler(
category = loggerCategory,
formatter = BareFormatter,
level = Some(Level.INFO),
statsReceiver = stats.scope("frs_recommendation_flow_logs_scribe")
)
)
} else { () => NullHandler }
LoggerFactory(
node = loggerCategory,
level = Some(Level.INFO),
useParents = false,
handlers = handlerFactory :: Nil
)
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/modules/TimerModule.scala | package com.twitter.follow_recommendations.modules
import com.google.inject.Provides
import com.google.inject.Singleton
import com.twitter.finagle.memcached.ZookeeperStateMonitor.DefaultTimer
import com.twitter.inject.TwitterModule
import com.twitter.util.Timer
object TimerModule extends TwitterModule {
@Provides
@Singleton
def providesTimer: Timer = DefaultTimer
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"3rdparty/jvm/org/slf4j:slf4j-api",
"finatra/inject/inject-app/src/main/scala",
"finatra/inject/inject-core/src/main/scala",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/common",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/explore_tab",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline_tweet_recs",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/sidebar",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/product/guice",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/ProdProductRegistry.scala | package com.twitter.follow_recommendations.products
import com.twitter.follow_recommendations.common.models.DisplayLocation
import com.twitter.follow_recommendations.products.common.ProductRegistry
import com.twitter.follow_recommendations.products.explore_tab.ExploreTabProduct
import com.twitter.follow_recommendations.products.home_timeline.HomeTimelineProduct
import com.twitter.follow_recommendations.products.home_timeline_tweet_recs.HomeTimelineTweetRecsProduct
import com.twitter.follow_recommendations.products.sidebar.SidebarProduct
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ProdProductRegistry @Inject() (
exploreTabProduct: ExploreTabProduct,
homeTimelineProduct: HomeTimelineProduct,
homeTimelineTweetRecsProduct: HomeTimelineTweetRecsProduct,
sidebarProduct: SidebarProduct,
) extends ProductRegistry {
override val products: Seq[common.Product] =
Seq(
exploreTabProduct,
homeTimelineProduct,
homeTimelineTweetRecsProduct,
sidebarProduct
)
override val displayLocationProductMap: Map[DisplayLocation, common.Product] =
products.groupBy(_.displayLocation).flatMap {
case (loc, products) =>
assert(products.size == 1, s"Found more than 1 Product for ${loc}")
products.headOption.map { product => loc -> product }
}
override def getProductByDisplayLocation(displayLocation: DisplayLocation): common.Product = {
displayLocationProductMap.getOrElse(
displayLocation,
throw new MissingProductException(displayLocation))
}
}
class MissingProductException(displayLocation: DisplayLocation)
extends Exception(s"No Product found for ${displayLocation}")
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/common/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"configapi/configapi-core",
"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/models",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/models",
"follow-recommendations-service/thrift/src/main/thrift:thrift-scala",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/common/Exceptions.scala | package com.twitter.follow_recommendations.products.common
abstract class ProductException(message: String) extends Exception(message)
class MissingFieldException(productRequest: ProductRequest, fieldName: String)
extends ProductException(
s"Missing ${fieldName} field for ${productRequest.recommendationRequest.displayLocation} request")
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/common/Product.scala | package com.twitter.follow_recommendations.products.common
import com.twitter.follow_recommendations.assembler.models.Layout
import com.twitter.follow_recommendations.common.base.BaseRecommendationFlow
import com.twitter.follow_recommendations.common.base.Transform
import com.twitter.follow_recommendations.common.models.DisplayLocation
import com.twitter.follow_recommendations.common.models.Recommendation
import com.twitter.follow_recommendations.models.RecommendationRequest
import com.twitter.product_mixer.core.model.marshalling.request.{Product => ProductMixerProduct}
import com.twitter.stitch.Stitch
import com.twitter.timelines.configapi.Params
trait Product {
/** Each product also requires a human-readable name.
* You can change this at any time
*/
def name: String
/**
* Every product needs a machine-friendly identifier for internal use.
* You should use the same name as the product package name.
* Except dashes are better than underscore
*
* Avoid changing this once it's in production.
*/
def identifier: String
def displayLocation: DisplayLocation
def selectWorkflows(
request: ProductRequest
): Stitch[Seq[BaseRecommendationFlow[ProductRequest, _ <: Recommendation]]]
/**
* Blender is responsible for blending together the candidates generated by different flows used
* in a product. For example, if a product uses two flows, it is blender's responsibility to
* interleave their generated candidates together and make a unified sequence of candidates.
*/
def blender: Transform[ProductRequest, Recommendation]
/**
* It is resultsTransformer job to do any final transformations needed on the final list of
* candidates generated by a product. For example, if a final quality check on candidates needed,
* resultsTransformer will handle it.
*/
def resultsTransformer(request: ProductRequest): Stitch[Transform[ProductRequest, Recommendation]]
def enabled(request: ProductRequest): Stitch[Boolean]
def layout: Option[Layout] = None
def productMixerProduct: Option[ProductMixerProduct] = None
}
case class ProductRequest(recommendationRequest: RecommendationRequest, params: Params)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/common/ProductRegistry.scala | package com.twitter.follow_recommendations.products.common
import com.twitter.follow_recommendations.common.models.DisplayLocation
trait ProductRegistry {
def products: Seq[Product]
def displayLocationProductMap: Map[DisplayLocation, Product]
def getProductByDisplayLocation(displayLocation: DisplayLocation): Product
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/explore_tab/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"finatra/inject/inject-app/src/main/scala",
"finatra/inject/inject-core/src/main/scala",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/blenders",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/flows/ads",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/flows/post_nux_ml",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/common",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/explore_tab/configapi",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/explore_tab/ExploreTabProduct.scala | package com.twitter.follow_recommendations.products.explore_tab
import com.twitter.follow_recommendations.common.base.BaseRecommendationFlow
import com.twitter.follow_recommendations.common.base.IdentityTransform
import com.twitter.follow_recommendations.common.base.Transform
import com.twitter.follow_recommendations.common.models.DisplayLocation
import com.twitter.follow_recommendations.common.models.Recommendation
import com.twitter.follow_recommendations.flows.post_nux_ml.PostNuxMlFlow
import com.twitter.follow_recommendations.flows.post_nux_ml.PostNuxMlRequestBuilder
import com.twitter.follow_recommendations.products.common.Product
import com.twitter.follow_recommendations.products.common.ProductRequest
import com.twitter.follow_recommendations.products.explore_tab.configapi.ExploreTabParams
import com.twitter.stitch.Stitch
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ExploreTabProduct @Inject() (
postNuxMlFlow: PostNuxMlFlow,
postNuxMlRequestBuilder: PostNuxMlRequestBuilder)
extends Product {
override val name: String = "Explore Tab"
override val identifier: String = "explore-tab"
override val displayLocation: DisplayLocation = DisplayLocation.ExploreTab
override def selectWorkflows(
request: ProductRequest
): Stitch[Seq[BaseRecommendationFlow[ProductRequest, _ <: Recommendation]]] = {
postNuxMlRequestBuilder.build(request).map { postNuxMlRequest =>
Seq(postNuxMlFlow.mapKey({ _: ProductRequest => postNuxMlRequest }))
}
}
override val blender: Transform[ProductRequest, Recommendation] =
new IdentityTransform[ProductRequest, Recommendation]
override def resultsTransformer(
request: ProductRequest
): Stitch[Transform[ProductRequest, Recommendation]] =
Stitch.value(new IdentityTransform[ProductRequest, Recommendation])
override def enabled(request: ProductRequest): Stitch[Boolean] = {
// Ideally we should hook up is_soft_user as custom FS field and disable the product through FS
val enabledForUserType = !request.recommendationRequest.isSoftUser || request.params(
ExploreTabParams.EnableProductForSoftUser)
Stitch.value(request.params(ExploreTabParams.EnableProduct) && enabledForUserType)
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/explore_tab/configapi/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"configapi/configapi-core",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/common",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/explore_tab/configapi/ExploreTabFSConfig.scala | package com.twitter.follow_recommendations.products.explore_tab.configapi
import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig
import com.twitter.follow_recommendations.products.explore_tab.configapi.ExploreTabParams._
import com.twitter.timelines.configapi.FSName
import com.twitter.timelines.configapi.Param
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ExploreTabFSConfig @Inject() () extends FeatureSwitchConfig {
override val booleanFSParams: Seq[Param[Boolean] with FSName] =
Seq(EnableProductForSoftUser)
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/explore_tab/configapi/ExploreTabParams.scala | package com.twitter.follow_recommendations.products.explore_tab.configapi
import com.twitter.timelines.configapi.Param
import com.twitter.timelines.configapi.FSParam
object ExploreTabParams {
object EnableProduct extends Param[Boolean](false)
object EnableProductForSoftUser
extends FSParam[Boolean]("explore_tab_enable_product_for_soft_user", false)
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"finatra/inject/inject-app/src/main/scala",
"finatra/inject/inject-core/src/main/scala",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/blenders",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/flows/ads",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/flows/post_nux_ml",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/common",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline/configapi",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline/HTLProductMixer.scala | package com.twitter.follow_recommendations.products.home_timeline
import com.twitter.product_mixer.core.model.common.identifier.ProductIdentifier
import com.twitter.product_mixer.core.model.marshalling.request.Product
case object HTLProductMixer extends Product {
override val identifier: ProductIdentifier = ProductIdentifier("HomeTimeline")
override val stringCenterProject: Option[String] = Some("people-discovery")
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline/HomeTimelineProduct.scala | package com.twitter.follow_recommendations.products.home_timeline
import com.twitter.follow_recommendations.assembler.models.ActionConfig
import com.twitter.follow_recommendations.assembler.models.FollowedByUsersProof
import com.twitter.follow_recommendations.assembler.models.FooterConfig
import com.twitter.follow_recommendations.assembler.models.GeoContextProof
import com.twitter.follow_recommendations.assembler.models.HeaderConfig
import com.twitter.follow_recommendations.assembler.models.Layout
import com.twitter.follow_recommendations.assembler.models.TitleConfig
import com.twitter.follow_recommendations.assembler.models.UserListLayout
import com.twitter.follow_recommendations.assembler.models.UserListOptions
import com.twitter.follow_recommendations.common.base.BaseRecommendationFlow
import com.twitter.follow_recommendations.common.base.IdentityTransform
import com.twitter.follow_recommendations.common.base.Transform
import com.twitter.follow_recommendations.flows.ads.PromotedAccountsFlow
import com.twitter.follow_recommendations.flows.ads.PromotedAccountsFlowRequest
import com.twitter.follow_recommendations.blenders.PromotedAccountsBlender
import com.twitter.follow_recommendations.common.models.DisplayLocation
import com.twitter.follow_recommendations.common.models.Recommendation
import com.twitter.follow_recommendations.flows.post_nux_ml.PostNuxMlFlow
import com.twitter.follow_recommendations.flows.post_nux_ml.PostNuxMlRequestBuilder
import com.twitter.follow_recommendations.products.common.Product
import com.twitter.follow_recommendations.products.common.ProductRequest
import com.twitter.follow_recommendations.products.home_timeline.configapi.HomeTimelineParams._
import com.twitter.inject.Injector
import com.twitter.product_mixer.core.model.marshalling.request
import com.twitter.product_mixer.core.product.guice.ProductScope
import com.twitter.stitch.Stitch
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class HomeTimelineProduct @Inject() (
postNuxMlFlow: PostNuxMlFlow,
postNuxMlRequestBuilder: PostNuxMlRequestBuilder,
promotedAccountsFlow: PromotedAccountsFlow,
promotedAccountsBlender: PromotedAccountsBlender,
productScope: ProductScope,
injector: Injector,
) extends Product {
override val name: String = "Home Timeline"
override val identifier: String = "home-timeline"
override val displayLocation: DisplayLocation = DisplayLocation.HomeTimeline
override def selectWorkflows(
request: ProductRequest
): Stitch[Seq[BaseRecommendationFlow[ProductRequest, _ <: Recommendation]]] = {
postNuxMlRequestBuilder.build(request).map { postNuxMlRequest =>
Seq(
postNuxMlFlow.mapKey({ request: ProductRequest => postNuxMlRequest }),
promotedAccountsFlow.mapKey(mkPromotedAccountsRequest))
}
}
override val blender: Transform[ProductRequest, Recommendation] = {
promotedAccountsBlender.mapTarget[ProductRequest](getMaxResults)
}
private val identityTransform = new IdentityTransform[ProductRequest, Recommendation]
override def resultsTransformer(
request: ProductRequest
): Stitch[Transform[ProductRequest, Recommendation]] = Stitch.value(identityTransform)
override def enabled(request: ProductRequest): Stitch[Boolean] =
Stitch.value(request.params(EnableProduct))
override def layout: Option[Layout] = {
productMixerProduct.map { product =>
val homeTimelineStrings = productScope.let(product) {
injector.instance[HomeTimelineStrings]
}
UserListLayout(
header = Some(HeaderConfig(TitleConfig(homeTimelineStrings.whoToFollowModuleTitle))),
userListOptions = UserListOptions(userBioEnabled = true, userBioTruncated = true, None),
socialProofs = Some(
Seq(
FollowedByUsersProof(
homeTimelineStrings.whoToFollowFollowedByManyUserSingleString,
homeTimelineStrings.whoToFollowFollowedByManyUserDoubleString,
homeTimelineStrings.whoToFollowFollowedByManyUserMultipleString
),
GeoContextProof(homeTimelineStrings.whoToFollowPopularInCountryKey)
)),
footer = Some(
FooterConfig(
Some(ActionConfig(homeTimelineStrings.whoToFollowModuleFooter, "http://twitter.com"))))
)
}
}
override def productMixerProduct: Option[request.Product] = Some(HTLProductMixer)
private[home_timeline] def mkPromotedAccountsRequest(
req: ProductRequest
): PromotedAccountsFlowRequest = {
PromotedAccountsFlowRequest(
req.recommendationRequest.clientContext,
req.params,
req.recommendationRequest.displayLocation,
None,
req.recommendationRequest.excludedIds.getOrElse(Nil)
)
}
private[home_timeline] def getMaxResults(req: ProductRequest): Int = {
req.recommendationRequest.maxResults.getOrElse(
req.params(DefaultMaxResults)
)
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline/HomeTimelineStrings.scala | package com.twitter.follow_recommendations.products.home_timeline
import com.twitter.product_mixer.core.product.guice.scope.ProductScoped
import com.twitter.stringcenter.client.ExternalStringRegistry
import com.twitter.stringcenter.client.core.ExternalString
import javax.inject.Inject
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
class HomeTimelineStrings @Inject() (
@ProductScoped externalStringRegistryProvider: Provider[ExternalStringRegistry]) {
private val externalStringRegistry = externalStringRegistryProvider.get()
val whoToFollowFollowedByManyUserSingleString: ExternalString =
externalStringRegistry.createProdString("WtfRecommendationContext.followedByManyUserSingle")
val whoToFollowFollowedByManyUserDoubleString: ExternalString =
externalStringRegistry.createProdString("WtfRecommendationContext.followedByManyUserDouble")
val whoToFollowFollowedByManyUserMultipleString: ExternalString =
externalStringRegistry.createProdString("WtfRecommendationContext.followedByManyUserMultiple")
val whoToFollowPopularInCountryKey: ExternalString =
externalStringRegistry.createProdString("WtfRecommendationContext.popularInCountry")
val whoToFollowModuleTitle: ExternalString =
externalStringRegistry.createProdString("WhoToFollowModule.title")
val whoToFollowModuleFooter: ExternalString =
externalStringRegistry.createProdString("WhoToFollowModule.pivot")
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline/configapi/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"configapi/configapi-core",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/common",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline/configapi/HomeTimelineFSConfig.scala | package com.twitter.follow_recommendations.products.home_timeline.configapi
import com.twitter.follow_recommendations.configapi.common.FeatureSwitchConfig
import com.twitter.follow_recommendations.products.home_timeline.configapi.HomeTimelineParams._
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 HomeTimelineFSConfig @Inject() () extends FeatureSwitchConfig {
override val booleanFSParams: Seq[Param[Boolean] with FSName] =
Seq(EnableWritingServingHistory)
override val durationFSParams: Seq[FSBoundedParam[Duration] with HasDurationConversion] = Seq(
DurationGuardrailToForceSuggest,
SuggestBasedFatigueDuration
)
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline/configapi/HomeTimelineParams.scala | package com.twitter.follow_recommendations.products.home_timeline.configapi
import com.twitter.conversions.DurationOps._
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.timelines.configapi.Param
import com.twitter.util.Duration
object HomeTimelineParams {
object EnableProduct extends Param[Boolean](false)
object DefaultMaxResults extends Param[Int](20)
object EnableWritingServingHistory
extends FSParam[Boolean]("home_timeline_enable_writing_serving_history", false)
object DurationGuardrailToForceSuggest
extends FSBoundedParam[Duration](
name = "home_timeline_duration_guardrail_to_force_suggest_in_hours",
default = 0.hours,
min = 0.hours,
max = 1000.hours)
with HasDurationConversion {
override val durationConversion: DurationConversion = DurationConversion.FromHours
}
object SuggestBasedFatigueDuration
extends FSBoundedParam[Duration](
name = "home_timeline_suggest_based_fatigue_duration_in_hours",
default = 0.hours,
min = 0.hours,
max = 1000.hours)
with HasDurationConversion {
override val durationConversion: DurationConversion = DurationConversion.FromHours
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline_tweet_recs/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"finatra/inject/inject-app/src/main/scala",
"finatra/inject/inject-core/src/main/scala",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/blenders",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/flows/content_recommender_flow",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/common",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline_tweet_recs/configapi",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline_tweet_recs/HomeTimelineTweetRecsProduct.scala | package com.twitter.follow_recommendations.products.home_timeline_tweet_recs
import com.twitter.follow_recommendations.common.base.BaseRecommendationFlow
import com.twitter.follow_recommendations.common.base.IdentityTransform
import com.twitter.follow_recommendations.common.base.Transform
import com.twitter.follow_recommendations.common.models.DisplayLocation
import com.twitter.follow_recommendations.common.models.Recommendation
import com.twitter.follow_recommendations.flows.content_recommender_flow.ContentRecommenderFlow
import com.twitter.follow_recommendations.flows.content_recommender_flow.ContentRecommenderRequestBuilder
import com.twitter.follow_recommendations.products.common.Product
import com.twitter.follow_recommendations.products.common.ProductRequest
import com.twitter.follow_recommendations.products.home_timeline_tweet_recs.configapi.HomeTimelineTweetRecsParams._
import com.twitter.stitch.Stitch
import javax.inject.Inject
import javax.inject.Singleton
/*
* This "DisplayLocation" is used to generate user recommendations using the ContentRecommenderFlow. These recommendations are later used downstream
* to generate recommended tweets on Home Timeline.
*/
@Singleton
class HomeTimelineTweetRecsProduct @Inject() (
contentRecommenderFlow: ContentRecommenderFlow,
contentRecommenderRequestBuilder: ContentRecommenderRequestBuilder)
extends Product {
override val name: String = "Home Timeline Tweet Recs"
override val identifier: String = "home-timeline-tweet-recs"
override val displayLocation: DisplayLocation = DisplayLocation.HomeTimelineTweetRecs
override def selectWorkflows(
request: ProductRequest
): Stitch[Seq[BaseRecommendationFlow[ProductRequest, _ <: Recommendation]]] = {
contentRecommenderRequestBuilder.build(request).map { contentRecommenderRequest =>
Seq(contentRecommenderFlow.mapKey({ request: ProductRequest => contentRecommenderRequest }))
}
}
override val blender: Transform[ProductRequest, Recommendation] =
new IdentityTransform[ProductRequest, Recommendation]
override def resultsTransformer(
request: ProductRequest
): Stitch[Transform[ProductRequest, Recommendation]] =
Stitch.value(new IdentityTransform[ProductRequest, Recommendation])
override def enabled(request: ProductRequest): Stitch[Boolean] =
Stitch.value(request.params(EnableProduct))
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline_tweet_recs/configapi/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"configapi/configapi-core",
"configapi/configapi-decider",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/common",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/home_timeline_tweet_recs/configapi/HomeTimelineTweetRecsParams.scala | package com.twitter.follow_recommendations.products.home_timeline_tweet_recs.configapi
import com.twitter.timelines.configapi.Param
object HomeTimelineTweetRecsParams {
object EnableProduct extends Param[Boolean](false)
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/sidebar/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"finatra/inject/inject-app/src/main/scala",
"finatra/inject/inject-core/src/main/scala",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/blenders",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/flows/ads",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/flows/post_nux_ml",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/common",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/sidebar/configapi",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/sidebar/SidebarProduct.scala | package com.twitter.follow_recommendations.products.sidebar
import com.twitter.follow_recommendations.common.base.BaseRecommendationFlow
import com.twitter.follow_recommendations.common.base.IdentityTransform
import com.twitter.follow_recommendations.common.base.Transform
import com.twitter.follow_recommendations.flows.ads.PromotedAccountsFlow
import com.twitter.follow_recommendations.flows.ads.PromotedAccountsFlowRequest
import com.twitter.follow_recommendations.blenders.PromotedAccountsBlender
import com.twitter.follow_recommendations.common.models.DisplayLocation
import com.twitter.follow_recommendations.common.models.Recommendation
import com.twitter.follow_recommendations.flows.post_nux_ml.PostNuxMlFlow
import com.twitter.follow_recommendations.flows.post_nux_ml.PostNuxMlRequestBuilder
import com.twitter.follow_recommendations.products.common.Product
import com.twitter.follow_recommendations.products.common.ProductRequest
import com.twitter.follow_recommendations.products.sidebar.configapi.SidebarParams
import com.twitter.stitch.Stitch
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SidebarProduct @Inject() (
postNuxMlFlow: PostNuxMlFlow,
postNuxMlRequestBuilder: PostNuxMlRequestBuilder,
promotedAccountsFlow: PromotedAccountsFlow,
promotedAccountsBlender: PromotedAccountsBlender)
extends Product {
override val name: String = "Sidebar"
override val identifier: String = "sidebar"
override val displayLocation: DisplayLocation = DisplayLocation.Sidebar
override def selectWorkflows(
request: ProductRequest
): Stitch[Seq[BaseRecommendationFlow[ProductRequest, _ <: Recommendation]]] = {
postNuxMlRequestBuilder.build(request).map { postNuxMlRequest =>
Seq(
postNuxMlFlow.mapKey({ _: ProductRequest => postNuxMlRequest }),
promotedAccountsFlow.mapKey(mkPromotedAccountsRequest)
)
}
}
override val blender: Transform[ProductRequest, Recommendation] = {
promotedAccountsBlender.mapTarget[ProductRequest](getMaxResults)
}
private[sidebar] def mkPromotedAccountsRequest(
req: ProductRequest
): PromotedAccountsFlowRequest = {
PromotedAccountsFlowRequest(
req.recommendationRequest.clientContext,
req.params,
req.recommendationRequest.displayLocation,
None,
req.recommendationRequest.excludedIds.getOrElse(Nil)
)
}
private[sidebar] def getMaxResults(req: ProductRequest): Int = {
req.recommendationRequest.maxResults.getOrElse(
req.params(SidebarParams.DefaultMaxResults)
)
}
override def resultsTransformer(
request: ProductRequest
): Stitch[Transform[ProductRequest, Recommendation]] =
Stitch.value(new IdentityTransform[ProductRequest, Recommendation])
override def enabled(request: ProductRequest): Stitch[Boolean] =
Stitch.value(request.params(SidebarParams.EnableProduct))
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/sidebar/configapi/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"configapi/configapi-core",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products/sidebar/configapi/SidebarParams.scala | package com.twitter.follow_recommendations.products.sidebar.configapi
import com.twitter.timelines.configapi.Param
object SidebarParams {
object EnableProduct extends Param[Boolean](false)
object DefaultMaxResults extends Param[Int](20)
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/services/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
tags = ["bazel-compatible"],
dependencies = [
"finatra/inject/inject-app/src/main/scala",
"finatra/inject/inject-core/src/main/scala",
"finatra/inject/inject-server/src/main/scala",
"finatra/inject/inject-thrift-client",
"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/candidate_sources/crowd_search_accounts",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/real_graph",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/recent_engagement",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/sims",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/stp",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/top_organic_follows_accounts",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/clients/impression_store",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/predicates/sgs",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/ranking",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/rankers/ml_ranker/scoring",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/utils",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/assembler/models",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/deciders",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/logging",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/products",
"follow-recommendations-service/thrift/src/main/thrift:thrift-scala",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/pipeline/product",
"product-mixer/core/src/main/scala/com/twitter/product_mixer/core/product/registry",
"twitter-server/server/src/main/scala",
"util/util-app/src/main/scala",
"util/util-core:scala",
"util/util-slf4j-api/src/main/scala",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/services/FollowRecommendationsServiceWarmupHandler.scala | package com.twitter.follow_recommendations.services
import com.twitter.finagle.thrift.ClientId
import com.twitter.finatra.thrift.routing.ThriftWarmup
import com.twitter.follow_recommendations.thriftscala.FollowRecommendationsThriftService.GetRecommendations
import com.twitter.follow_recommendations.thriftscala.ClientContext
import com.twitter.follow_recommendations.thriftscala.DebugParams
import com.twitter.follow_recommendations.thriftscala.DisplayContext
import com.twitter.follow_recommendations.thriftscala.DisplayLocation
import com.twitter.follow_recommendations.thriftscala.Profile
import com.twitter.follow_recommendations.thriftscala.RecommendationRequest
import com.twitter.inject.Logging
import com.twitter.inject.utils.Handler
import com.twitter.scrooge.Request
import com.twitter.scrooge.Response
import com.twitter.util.Return
import com.twitter.util.Throw
import com.twitter.util.Try
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class FollowRecommendationsServiceWarmupHandler @Inject() (warmup: ThriftWarmup)
extends Handler
with Logging {
private val clientId = ClientId("thrift-warmup-client")
override def handle(): Unit = {
val testIds = Seq(1L)
def warmupQuery(userId: Long, displayLocation: DisplayLocation): RecommendationRequest = {
val clientContext = ClientContext(
userId = Some(userId),
guestId = None,
appId = Some(258901L),
ipAddress = Some("0.0.0.0"),
userAgent = Some("FAKE_USER_AGENT_FOR_WARMUPS"),
countryCode = Some("US"),
languageCode = Some("en"),
isTwoffice = None,
userRoles = None,
deviceId = Some("FAKE_DEVICE_ID_FOR_WARMUPS")
)
RecommendationRequest(
clientContext = clientContext,
displayLocation = displayLocation,
displayContext = None,
maxResults = Some(3),
fetchPromotedContent = Some(false),
debugParams = Some(DebugParams(doNotLog = Some(true)))
)
}
// Add FRS display locations here if they should be targeted for warm-up
// when FRS is starting from a fresh state after a deploy
val displayLocationsToWarmUp: Seq[DisplayLocation] = Seq(
DisplayLocation.HomeTimeline,
DisplayLocation.HomeTimelineReverseChron,
DisplayLocation.ProfileSidebar,
DisplayLocation.NuxInterests,
DisplayLocation.NuxPymk
)
try {
clientId.asCurrent {
// Iterate over each user ID created for testing
testIds foreach { id =>
// Iterate over each display location targeted for warm-up
displayLocationsToWarmUp foreach { displayLocation =>
val warmupReq = warmupQuery(id, displayLocation)
info(s"Sending warm-up request to service with query: $warmupReq")
warmup.sendRequest(
method = GetRecommendations,
req = Request(GetRecommendations.Args(warmupReq)))(assertWarmupResponse)
// send the request one more time so that it goes through cache hits
warmup.sendRequest(
method = GetRecommendations,
req = Request(GetRecommendations.Args(warmupReq)))(assertWarmupResponse)
}
}
}
} catch {
case e: Throwable =>
// we don't want a warmup failure to prevent start-up
error(e.getMessage, e)
}
info("Warm-up done.")
}
/* Private */
private def assertWarmupResponse(result: Try[Response[GetRecommendations.SuccessType]]): Unit = {
// we collect and log any exceptions from the result.
result match {
case Return(_) => // ok
case Throw(exception) =>
warn()
error(s"Error performing warm-up request: ${exception.getMessage}", exception)
}
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/services/ProductMixerRecommendationService.scala | package com.twitter.follow_recommendations.services
import com.twitter.finagle.stats.StatsReceiver
import javax.inject.Inject
import javax.inject.Singleton
import com.twitter.timelines.configapi.Params
import com.twitter.follow_recommendations.common.utils.DisplayLocationProductConverterUtil
import com.twitter.follow_recommendations.configapi.deciders.DeciderParams
import com.twitter.follow_recommendations.logging.FrsLogger
import com.twitter.follow_recommendations.models.{DebugParams => FrsDebugParams}
import com.twitter.follow_recommendations.models.RecommendationRequest
import com.twitter.follow_recommendations.models.RecommendationResponse
import com.twitter.follow_recommendations.models.Request
import com.twitter.product_mixer.core.model.marshalling.request.{
DebugParams => ProductMixerDebugParams
}
import com.twitter.product_mixer.core.product.registry.ProductPipelineRegistry
import com.twitter.product_mixer.core.pipeline.product.ProductPipelineRequest
import com.twitter.stitch.Stitch
@Singleton
class ProductMixerRecommendationService @Inject() (
productPipelineRegistry: ProductPipelineRegistry,
resultLogger: FrsLogger,
baseStats: StatsReceiver) {
private val stats = baseStats.scope("product_mixer_recos_service_stats")
private val loggingStats = stats.scope("logged")
def get(request: RecommendationRequest, params: Params): Stitch[RecommendationResponse] = {
if (params(DeciderParams.EnableRecommendations)) {
val productMixerRequest = convertToProductMixerRequest(request)
productPipelineRegistry
.getProductPipeline[Request, RecommendationResponse](productMixerRequest.product)
.process(ProductPipelineRequest(productMixerRequest, params)).onSuccess { response =>
if (resultLogger.shouldLog(request.debugParams)) {
loggingStats.counter().incr()
resultLogger.logRecommendationResult(request, response)
}
}
} else {
Stitch.value(RecommendationResponse(Nil))
}
}
def convertToProductMixerRequest(frsRequest: RecommendationRequest): Request = {
Request(
maxResults = frsRequest.maxResults,
debugParams = convertToProductMixerDebugParams(frsRequest.debugParams),
productContext = None,
product =
DisplayLocationProductConverterUtil.displayLocationToProduct(frsRequest.displayLocation),
clientContext = frsRequest.clientContext,
serializedRequestCursor = frsRequest.cursor,
frsDebugParams = frsRequest.debugParams,
displayLocation = frsRequest.displayLocation,
excludedIds = frsRequest.excludedIds,
fetchPromotedContent = frsRequest.fetchPromotedContent,
userLocationState = frsRequest.userLocationState
)
}
private def convertToProductMixerDebugParams(
frsDebugParams: Option[FrsDebugParams]
): Option[ProductMixerDebugParams] = {
frsDebugParams.map { debugParams =>
ProductMixerDebugParams(debugParams.featureOverrides, None)
}
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/services/ProductPipelineSelector.scala | package com.twitter.follow_recommendations.services
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.follow_recommendations.common.base.StatsUtil
import com.twitter.follow_recommendations.common.models.CandidateUser
import com.twitter.follow_recommendations.common.models.DebugOptions
import com.twitter.follow_recommendations.models.DebugParams
import com.twitter.follow_recommendations.models.RecommendationRequest
import com.twitter.follow_recommendations.models.RecommendationResponse
import com.twitter.stitch.Stitch
import com.twitter.timelines.configapi.Params
import javax.inject.Inject
import javax.inject.Singleton
import scala.util.Random
@Singleton
class ProductPipelineSelector @Inject() (
recommendationsService: RecommendationsService,
productMixerRecommendationService: ProductMixerRecommendationService,
productPipelineSelectorConfig: ProductPipelineSelectorConfig,
baseStats: StatsReceiver) {
private val frsStats = baseStats.scope("follow_recommendations_service")
private val stats = frsStats.scope("product_pipeline_selector_parity")
private val readFromProductMixerCounter = stats.counter("select_product_mixer")
private val readFromOldFRSCounter = stats.counter("select_old_frs")
def selectPipeline(
request: RecommendationRequest,
params: Params
): Stitch[RecommendationResponse] = {
productPipelineSelectorConfig
.getDarkReadAndExpParams(request.displayLocation).map { darkReadAndExpParam =>
if (params(darkReadAndExpParam.expParam)) {
readFromProductMixerPipeline(request, params)
} else if (params(darkReadAndExpParam.darkReadParam)) {
darkReadAndReturnResult(request, params)
} else {
readFromOldFrsPipeline(request, params)
}
}.getOrElse(readFromOldFrsPipeline(request, params))
}
private def readFromProductMixerPipeline(
request: RecommendationRequest,
params: Params
): Stitch[RecommendationResponse] = {
readFromProductMixerCounter.incr()
productMixerRecommendationService.get(request, params)
}
private def readFromOldFrsPipeline(
request: RecommendationRequest,
params: Params
): Stitch[RecommendationResponse] = {
readFromOldFRSCounter.incr()
recommendationsService.get(request, params)
}
private def darkReadAndReturnResult(
request: RecommendationRequest,
params: Params
): Stitch[RecommendationResponse] = {
val darkReadStats = stats.scope("select_dark_read", request.displayLocation.toFsName)
darkReadStats.counter("count").incr()
// If no seed is set, create a random one that both requests will use to remove differences
// in randomness for the WeightedCandidateSourceRanker
val randomizationSeed = new Random().nextLong()
val oldFRSPiplelineRequest = request.copy(
debugParams = Some(
request.debugParams.getOrElse(
DebugParams(None, Some(DebugOptions(randomizationSeed = Some(randomizationSeed))))))
)
val productMixerPipelineRequest = request.copy(
debugParams = Some(
request.debugParams.getOrElse(
DebugParams(
None,
Some(DebugOptions(doNotLog = true, randomizationSeed = Some(randomizationSeed))))))
)
StatsUtil
.profileStitch(
readFromOldFrsPipeline(oldFRSPiplelineRequest, params),
darkReadStats.scope("frs_timing")).applyEffect { frsOldPipelineResponse =>
Stitch.async(
StatsUtil
.profileStitch(
readFromProductMixerPipeline(productMixerPipelineRequest, params),
darkReadStats.scope("product_mixer_timing")).liftToOption().map {
case Some(frsProductMixerResponse) =>
darkReadStats.counter("product_mixer_pipeline_success").incr()
compare(request, frsOldPipelineResponse, frsProductMixerResponse)
case None =>
darkReadStats.counter("product_mixer_pipeline_failure").incr()
}
)
}
}
def compare(
request: RecommendationRequest,
frsOldPipelineResponse: RecommendationResponse,
frsProductMixerResponse: RecommendationResponse
): Unit = {
val compareStats = stats.scope("pipeline_comparison", request.displayLocation.toFsName)
compareStats.counter("total-comparisons").incr()
val oldFrsMap = frsOldPipelineResponse.recommendations.map { user => user.id -> user }.toMap
val productMixerMap = frsProductMixerResponse.recommendations.map { user =>
user.id -> user
}.toMap
compareTopNResults(3, frsOldPipelineResponse, frsProductMixerResponse, compareStats)
compareTopNResults(5, frsOldPipelineResponse, frsProductMixerResponse, compareStats)
compareTopNResults(25, frsOldPipelineResponse, frsProductMixerResponse, compareStats)
compareTopNResults(50, frsOldPipelineResponse, frsProductMixerResponse, compareStats)
compareTopNResults(75, frsOldPipelineResponse, frsProductMixerResponse, compareStats)
// Compare individual matching candidates
oldFrsMap.keys.foreach(userId => {
if (productMixerMap.contains(userId)) {
(oldFrsMap(userId), productMixerMap(userId)) match {
case (oldFrsUser: CandidateUser, productMixerUser: CandidateUser) =>
compareStats.counter("matching-user-count").incr()
compareUser(oldFrsUser, productMixerUser, compareStats)
case _ =>
compareStats.counter("unknown-user-type-count").incr()
}
} else {
compareStats.counter("missing-user-count").incr()
}
})
}
private def compareTopNResults(
n: Int,
frsOldPipelineResponse: RecommendationResponse,
frsProductMixerResponse: RecommendationResponse,
compareStats: StatsReceiver
): Unit = {
if (frsOldPipelineResponse.recommendations.size >= n && frsProductMixerResponse.recommendations.size >= n) {
val oldFrsPipelineFirstN = frsOldPipelineResponse.recommendations.take(n).map(_.id)
val productMixerPipelineFirstN = frsProductMixerResponse.recommendations.take(n).map(_.id)
if (oldFrsPipelineFirstN.sorted == productMixerPipelineFirstN.sorted)
compareStats.counter(s"first-$n-sorted-equal-ids").incr()
if (oldFrsPipelineFirstN == productMixerPipelineFirstN)
compareStats.counter(s"first-$n-unsorted-ids-equal").incr()
else
compareStats.counter(s"first-$n-unsorted-ids-unequal").incr()
}
}
private def compareUser(
oldFrsUser: CandidateUser,
productMixerUser: CandidateUser,
stats: StatsReceiver
): Unit = {
val userStats = stats.scope("matching-user")
if (oldFrsUser.score != productMixerUser.score)
userStats.counter("mismatch-score").incr()
if (oldFrsUser.reason != productMixerUser.reason)
userStats.counter("mismatch-reason").incr()
if (oldFrsUser.userCandidateSourceDetails != productMixerUser.userCandidateSourceDetails)
userStats.counter("mismatch-userCandidateSourceDetails").incr()
if (oldFrsUser.adMetadata != productMixerUser.adMetadata)
userStats.counter("mismatch-adMetadata").incr()
if (oldFrsUser.trackingToken != productMixerUser.trackingToken)
userStats.counter("mismatch-trackingToken").incr()
if (oldFrsUser.dataRecord != productMixerUser.dataRecord)
userStats.counter("mismatch-dataRecord").incr()
if (oldFrsUser.scores != productMixerUser.scores)
userStats.counter("mismatch-scores").incr()
if (oldFrsUser.infoPerRankingStage != productMixerUser.infoPerRankingStage)
userStats.counter("mismatch-infoPerRankingStage").incr()
if (oldFrsUser.params != productMixerUser.params)
userStats.counter("mismatch-params").incr()
if (oldFrsUser.engagements != productMixerUser.engagements)
userStats.counter("mismatch-engagements").incr()
if (oldFrsUser.recommendationFlowIdentifier != productMixerUser.recommendationFlowIdentifier)
userStats.counter("mismatch-recommendationFlowIdentifier").incr()
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/services/ProductPipelineSelectorConfig.scala | package com.twitter.follow_recommendations.services
import com.twitter.follow_recommendations.common.models.DisplayLocation
import com.twitter.timelines.configapi.FSParam
import com.twitter.timelines.configapi.Param
import javax.inject.Singleton
@Singleton
class ProductPipelineSelectorConfig {
private val paramsMap: Map[DisplayLocation, DarkReadAndExpParams] = Map.empty
def getDarkReadAndExpParams(
displayLocation: DisplayLocation
): Option[DarkReadAndExpParams] = {
paramsMap.get(displayLocation)
}
}
case class DarkReadAndExpParams(darkReadParam: Param[Boolean], expParam: FSParam[Boolean])
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/services/ProductRecommenderService.scala | package com.twitter.follow_recommendations.services
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.follow_recommendations.common.base.StatsUtil
import com.twitter.follow_recommendations.common.models.Recommendation
import com.twitter.follow_recommendations.models.RecommendationRequest
import com.twitter.follow_recommendations.products.common.ProductRegistry
import com.twitter.follow_recommendations.products.common.ProductRequest
import com.twitter.stitch.Stitch
import com.twitter.follow_recommendations.configapi.params.GlobalParams.EnableWhoToFollowProducts
import com.twitter.timelines.configapi.Params
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ProductRecommenderService @Inject() (
productRegistry: ProductRegistry,
statsReceiver: StatsReceiver) {
private val stats = statsReceiver.scope("ProductRecommenderService")
def getRecommendations(
request: RecommendationRequest,
params: Params
): Stitch[Seq[Recommendation]] = {
val displayLocation = request.displayLocation
val displayLocationStatName = displayLocation.toString
val locationStats = stats.scope(displayLocationStatName)
val loggedInOrOutStats = if (request.clientContext.userId.isDefined) {
stats.scope("logged_in").scope(displayLocationStatName)
} else {
stats.scope("logged_out").scope(displayLocationStatName)
}
loggedInOrOutStats.counter("requests").incr()
val product = productRegistry.getProductByDisplayLocation(displayLocation)
val productRequest = ProductRequest(request, params)
val productEnabledStitch =
StatsUtil.profileStitch(product.enabled(productRequest), locationStats.scope("enabled"))
productEnabledStitch.flatMap { productEnabled =>
if (productEnabled && params(EnableWhoToFollowProducts)) {
loggedInOrOutStats.counter("enabled").incr()
val stitch = for {
workflows <- StatsUtil.profileStitch(
product.selectWorkflows(productRequest),
locationStats.scope("select_workflows"))
workflowRecos <- StatsUtil.profileStitch(
Stitch.collect(
workflows.map(_.process(productRequest).map(_.result.getOrElse(Seq.empty)))),
locationStats.scope("execute_workflows")
)
blendedCandidates <- StatsUtil.profileStitch(
product.blender.transform(productRequest, workflowRecos.flatten),
locationStats.scope("blend_results"))
resultsTransformer <- StatsUtil.profileStitch(
product.resultsTransformer(productRequest),
locationStats.scope("results_transformer"))
transformedCandidates <- StatsUtil.profileStitch(
resultsTransformer.transform(productRequest, blendedCandidates),
locationStats.scope("execute_results_transformer"))
} yield {
transformedCandidates
}
StatsUtil.profileStitchResults[Seq[Recommendation]](stitch, locationStats, _.size)
} else {
loggedInOrOutStats.counter("disabled").incr()
locationStats.counter("disabled_product").incr()
Stitch.Nil
}
}
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/services/RecommendationsService.scala | package com.twitter.follow_recommendations.services
import com.twitter.follow_recommendations.configapi.deciders.DeciderParams
import com.twitter.follow_recommendations.logging.FrsLogger
import com.twitter.follow_recommendations.models.RecommendationRequest
import com.twitter.follow_recommendations.models.RecommendationResponse
import com.twitter.stitch.Stitch
import com.twitter.timelines.configapi.Params
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class RecommendationsService @Inject() (
productRecommenderService: ProductRecommenderService,
resultLogger: FrsLogger) {
def get(request: RecommendationRequest, params: Params): Stitch[RecommendationResponse] = {
if (params(DeciderParams.EnableRecommendations)) {
productRecommenderService
.getRecommendations(request, params).map(RecommendationResponse).onSuccess { response =>
if (resultLogger.shouldLog(request.debugParams)) {
resultLogger.logRecommendationResult(request, response)
}
}
} else {
Stitch.value(RecommendationResponse(Nil))
}
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/services/UserScoringService.scala | package com.twitter.follow_recommendations.services
import com.twitter.finagle.stats.Counter
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.follow_recommendations.common.base.StatsUtil.profileStitchSeqResults
import com.twitter.follow_recommendations.common.clients.impression_store.WtfImpressionStore
import com.twitter.follow_recommendations.common.clients.socialgraph.SocialGraphClient
import com.twitter.follow_recommendations.common.rankers.ml_ranker.ranking.HydrateFeaturesTransform
import com.twitter.follow_recommendations.common.rankers.ml_ranker.ranking.MlRanker
import com.twitter.follow_recommendations.common.utils.RescueWithStatsUtils.rescueWithStats
import com.twitter.follow_recommendations.configapi.deciders.DeciderParams
import com.twitter.follow_recommendations.logging.FrsLogger
import com.twitter.follow_recommendations.models.ScoringUserRequest
import com.twitter.follow_recommendations.models.ScoringUserResponse
import com.twitter.stitch.Stitch
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class UserScoringService @Inject() (
socialGraph: SocialGraphClient,
wtfImpressionStore: WtfImpressionStore,
hydrateFeaturesTransform: HydrateFeaturesTransform[ScoringUserRequest],
mlRanker: MlRanker[ScoringUserRequest],
resultLogger: FrsLogger,
stats: StatsReceiver) {
private val scopedStats: StatsReceiver = stats.scope(this.getClass.getSimpleName)
private val disabledCounter: Counter = scopedStats.counter("disabled")
def get(request: ScoringUserRequest): Stitch[ScoringUserResponse] = {
if (request.params(DeciderParams.EnableScoreUserCandidates)) {
val hydratedRequest = hydrate(request)
val candidatesStitch = hydratedRequest.flatMap { req =>
hydrateFeaturesTransform.transform(req, request.candidates).flatMap {
candidateWithFeatures =>
mlRanker.rank(req, candidateWithFeatures)
}
}
profileStitchSeqResults(candidatesStitch, scopedStats)
.map(ScoringUserResponse)
.onSuccess { response =>
if (resultLogger.shouldLog(request.debugParams)) {
resultLogger.logScoringResult(request, response)
}
}
} else {
disabledCounter.incr()
Stitch.value(ScoringUserResponse(Nil))
}
}
private def hydrate(request: ScoringUserRequest): Stitch[ScoringUserRequest] = {
val allStitches = Stitch.collect(request.clientContext.userId.map { userId =>
val recentFollowedUserIdsStitch =
rescueWithStats(
socialGraph.getRecentFollowedUserIds(userId),
stats,
"recentFollowedUserIds")
val recentFollowedByUserIdsStitch =
rescueWithStats(
socialGraph.getRecentFollowedByUserIds(userId),
stats,
"recentFollowedByUserIds")
val wtfImpressionsStitch =
rescueWithStats(
wtfImpressionStore.get(userId, request.displayLocation),
stats,
"wtfImpressions")
Stitch.join(recentFollowedUserIdsStitch, recentFollowedByUserIdsStitch, wtfImpressionsStitch)
})
allStitches.map {
case Some((recentFollowedUserIds, recentFollowedByUserIds, wtfImpressions)) =>
request.copy(
recentFollowedUserIds =
if (recentFollowedUserIds.isEmpty) None else Some(recentFollowedUserIds),
recentFollowedByUserIds =
if (recentFollowedByUserIds.isEmpty) None else Some(recentFollowedByUserIds),
wtfImpressions = if (wtfImpressions.isEmpty) None else Some(wtfImpressions)
)
case _ => request
}
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/services/exceptions/BUILD | scala_library(
sources = ["*.scala"],
compiler_option_sets = ["fatal_warnings"],
tags = ["bazel-compatible"],
dependencies = [
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift",
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift:controller",
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift/exceptions",
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift/filters",
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift/modules",
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift/response",
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift/routing",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/services/exceptions/UnknownExceptionMapper.scala | package com.twitter.follow_recommendations.service.exceptions
import com.twitter.finatra.thrift.exceptions.ExceptionMapper
import com.twitter.inject.Logging
import com.twitter.util.Future
import javax.inject.Singleton
@Singleton
class UnknownLoggingExceptionMapper extends ExceptionMapper[Exception, Throwable] with Logging {
def handleException(throwable: Exception): Future[Throwable] = {
error(
s"Unmapped Exception: ${throwable.getMessage} - ${throwable.getStackTrace.mkString(", \n\t")}",
throwable
)
Future.exception(throwable)
}
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/utils/BUILD | scala_library(
compiler_option_sets = ["fatal_warnings"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"finatra/inject/inject-app/src/main/scala",
"finatra/inject/inject-core/src/main/scala",
"finatra/inject/inject-server/src/main/scala",
"finatra/inject/inject-thrift-client",
"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/candidate_sources/addressbook",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/geo",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/ppmi_locale_follow",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/recent_engagement",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/sims",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/sims_expansion",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/socialgraph",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/stp",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/triangular_loops",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/candidate_sources/two_hop_random_walk",
"follow-recommendations-service/common/src/main/scala/com/twitter/follow_recommendations/common/feature_hydration/sources",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/configapi/params",
"follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/models",
"twitter-server/server/src/main/scala",
"util/util-app/src/main/scala",
"util/util-core:scala",
"util/util-slf4j-api/src/main/scala",
],
)
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/utils/CandidateSourceHoldbackUtil.scala | package com.twitter.follow_recommendations.utils
import com.twitter.follow_recommendations.common.candidate_sources.addressbook._
import com.twitter.follow_recommendations.common.candidate_sources.geo.PopCountrySource
import com.twitter.follow_recommendations.common.candidate_sources.geo.PopCountryBackFillSource
import com.twitter.follow_recommendations.common.candidate_sources.geo.PopGeoSource
import com.twitter.follow_recommendations.common.candidate_sources.geo.PopGeohashSource
import com.twitter.follow_recommendations.common.candidate_sources.ppmi_locale_follow.PPMILocaleFollowSource
import com.twitter.follow_recommendations.common.candidate_sources.recent_engagement.RecentEngagementNonDirectFollowSource
import com.twitter.follow_recommendations.common.candidate_sources.sims.SwitchingSimsSource
import com.twitter.follow_recommendations.common.candidate_sources.sims_expansion.RecentEngagementSimilarUsersSource
import com.twitter.follow_recommendations.common.candidate_sources.sims_expansion.RecentFollowingSimilarUsersSource
import com.twitter.follow_recommendations.common.candidate_sources.sims_expansion.RecentStrongEngagementDirectFollowSimilarUsersSource
import com.twitter.follow_recommendations.common.candidate_sources.socialgraph.RecentFollowingRecentFollowingExpansionSource
import com.twitter.follow_recommendations.common.candidate_sources.stp.MutualFollowStrongTiePredictionSource
import com.twitter.follow_recommendations.common.candidate_sources.stp.OfflineStrongTiePredictionSource
import com.twitter.follow_recommendations.common.candidate_sources.stp.BaseOnlineSTPSource
import com.twitter.follow_recommendations.common.candidate_sources.stp.SocialProofEnforcedOfflineStrongTiePredictionSource
import com.twitter.follow_recommendations.common.candidate_sources.triangular_loops.TriangularLoopsSource
import com.twitter.follow_recommendations.common.candidate_sources.two_hop_random_walk.TwoHopRandomWalkSource
import com.twitter.follow_recommendations.common.models.CandidateUser
import com.twitter.follow_recommendations.configapi.params.GlobalParams
import com.twitter.follow_recommendations.models.CandidateSourceType
import com.twitter.product_mixer.core.functional_component.candidate_source.CandidateSource
import com.twitter.product_mixer.core.model.common.identifier.CandidateSourceIdentifier
import com.twitter.timelines.configapi.HasParams
trait CandidateSourceHoldbackUtil {
import CandidateSourceHoldbackUtil._
def filterCandidateSources[T <: HasParams](
request: T,
sources: Seq[CandidateSource[T, CandidateUser]]
): Seq[CandidateSource[T, CandidateUser]] = {
val typeToFilter = request.params(GlobalParams.CandidateSourcesToFilter)
val sourcesToFilter = CandidateSourceTypeToMap.get(typeToFilter).getOrElse(Set.empty)
sources.filterNot { source => sourcesToFilter.contains(source.identifier) }
}
}
object CandidateSourceHoldbackUtil {
final val ContextualActivityCandidateSourceIds: Set[CandidateSourceIdentifier] =
Set(
RecentFollowingSimilarUsersSource.Identifier,
RecentEngagementNonDirectFollowSource.Identifier,
RecentEngagementSimilarUsersSource.Identifier,
RecentStrongEngagementDirectFollowSimilarUsersSource.Identifier,
SwitchingSimsSource.Identifier,
)
final val SocialCandidateSourceIds: Set[CandidateSourceIdentifier] =
Set(
ForwardEmailBookSource.Identifier,
ForwardPhoneBookSource.Identifier,
ReverseEmailBookSource.Identifier,
ReversePhoneBookSource.Identifier,
RecentFollowingRecentFollowingExpansionSource.Identifier,
BaseOnlineSTPSource.Identifier,
MutualFollowStrongTiePredictionSource.Identifier,
OfflineStrongTiePredictionSource.Identifier,
SocialProofEnforcedOfflineStrongTiePredictionSource.Identifier,
TriangularLoopsSource.Identifier,
TwoHopRandomWalkSource.Identifier
)
final val GeoCandidateSourceIds: Set[CandidateSourceIdentifier] =
Set(
PPMILocaleFollowSource.Identifier,
PopCountrySource.Identifier,
PopGeohashSource.Identifier,
PopCountryBackFillSource.Identifier,
PopGeoSource.Identifier,
)
final val CandidateSourceTypeToMap: Map[CandidateSourceType.Value, Set[
CandidateSourceIdentifier
]] =
Map(
CandidateSourceType.Social -> SocialCandidateSourceIds,
CandidateSourceType.ActivityContextual -> ContextualActivityCandidateSourceIds,
CandidateSourceType.GeoAndInterests -> GeoCandidateSourceIds
)
}
|
the-algorithm-main/follow-recommendations-service/server/src/main/scala/com/twitter/follow_recommendations/utils/RecommendationFlowBaseSideEffectsUtil.scala | package com.twitter.follow_recommendations.utils
import com.twitter.follow_recommendations.common.base.RecommendationFlow
import com.twitter.follow_recommendations.common.base.SideEffectsUtil
import com.twitter.follow_recommendations.common.models.CandidateUser
import com.twitter.product_mixer.core.functional_component.candidate_source.CandidateSource
import com.twitter.product_mixer.core.model.common.identifier.CandidateSourceIdentifier
import com.twitter.product_mixer.core.model.marshalling.request.HasClientContext
import com.twitter.snowflake.id.SnowflakeId
import com.twitter.stitch.Stitch
trait RecommendationFlowBaseSideEffectsUtil[Target <: HasClientContext, Candidate <: CandidateUser]
extends SideEffectsUtil[Target, Candidate] {
recommendationFlow: RecommendationFlow[Target, Candidate] =>
override def applySideEffects(
target: Target,
candidateSources: Seq[CandidateSource[Target, Candidate]],
candidatesFromCandidateSources: Seq[Candidate],
mergedCandidates: Seq[Candidate],
filteredCandidates: Seq[Candidate],
rankedCandidates: Seq[Candidate],
transformedCandidates: Seq[Candidate],
truncatedCandidates: Seq[Candidate],
results: Seq[Candidate]
): Stitch[Unit] = {
Stitch.async(
Stitch.collect(
Seq(
applySideEffectsCandidateSourceCandidates(
target,
candidateSources,
candidatesFromCandidateSources),
applySideEffectsMergedCandidates(target, mergedCandidates),
applySideEffectsFilteredCandidates(target, filteredCandidates),
applySideEffectsRankedCandidates(target, rankedCandidates),
applySideEffectsTransformedCandidates(target, transformedCandidates),
applySideEffectsTruncatedCandidates(target, truncatedCandidates),
applySideEffectsResults(target, results)
)
))
}
/*
In subclasses, override functions below to apply custom side effects at each step in pipeline.
Call super.applySideEffectsXYZ to scribe basic scribes implemented in this parent class
*/
def applySideEffectsCandidateSourceCandidates(
target: Target,
candidateSources: Seq[CandidateSource[Target, Candidate]],
candidatesFromCandidateSources: Seq[Candidate]
): Stitch[Unit] = {
val candidatesGroupedByCandidateSources =
candidatesFromCandidateSources.groupBy(
_.getPrimaryCandidateSource.getOrElse(CandidateSourceIdentifier("NoCandidateSource")))
target.getOptionalUserId match {
case Some(userId) =>
val userAgeOpt = SnowflakeId.timeFromIdOpt(userId).map(_.untilNow.inDays)
userAgeOpt match {
case Some(userAge) if userAge <= 30 =>
candidateSources.map { candidateSource =>
{
val candidateSourceStats = statsReceiver.scope(candidateSource.identifier.name)
val isEmpty =
!candidatesGroupedByCandidateSources.keySet.contains(candidateSource.identifier)
if (userAge <= 1)
candidateSourceStats
.scope("user_age", "1", "empty").counter(isEmpty.toString).incr()
if (userAge <= 7)
candidateSourceStats
.scope("user_age", "7", "empty").counter(isEmpty.toString).incr()
if (userAge <= 30)
candidateSourceStats
.scope("user_age", "30", "empty").counter(isEmpty.toString).incr()
}
}
case _ => Nil
}
case None => Nil
}
Stitch.Unit
}
def applySideEffectsBaseCandidates(
target: Target,
candidates: Seq[Candidate]
): Stitch[Unit] = Stitch.Unit
def applySideEffectsMergedCandidates(
target: Target,
candidates: Seq[Candidate]
): Stitch[Unit] = applySideEffectsBaseCandidates(target, candidates)
def applySideEffectsFilteredCandidates(
target: Target,
candidates: Seq[Candidate]
): Stitch[Unit] = applySideEffectsBaseCandidates(target, candidates)
def applySideEffectsRankedCandidates(
target: Target,
candidates: Seq[Candidate]
): Stitch[Unit] = applySideEffectsBaseCandidates(target, candidates)
def applySideEffectsTransformedCandidates(
target: Target,
candidates: Seq[Candidate]
): Stitch[Unit] = applySideEffectsBaseCandidates(target, candidates)
def applySideEffectsTruncatedCandidates(
target: Target,
candidates: Seq[Candidate]
): Stitch[Unit] = applySideEffectsBaseCandidates(target, candidates)
def applySideEffectsResults(
target: Target,
candidates: Seq[Candidate]
): Stitch[Unit] = applySideEffectsBaseCandidates(target, candidates)
}
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/BUILD | create_thrift_libraries(
base_name = "thrift",
sources = ["*.thrift"],
platform = "java8",
tags = ["bazel-compatible"],
dependency_roots = [
"finatra-internal/thrift/src/main/thrift",
"follow-recommendations-service/thrift/src/main/thrift/logging:thrift",
"product-mixer/core/src/main/thrift/com/twitter/product_mixer/core:thrift",
"src/thrift/com/twitter/ads/adserver:adserver_common",
"src/thrift/com/twitter/ml/api:data",
"src/thrift/com/twitter/suggests/controller_data",
],
generate_languages = [
"java",
"scala",
"strato",
],
provides_java_name = "follow-recommendations-java",
provides_scala_name = "follow-recommendations-scala",
)
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/assembler.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
struct Header {
1: required Title title
}
struct Title {
1: required string text
}
struct Footer {
1: optional Action action
}
struct Action {
1: required string text
2: required string actionURL
}
struct UserList {
1: required bool userBioEnabled
2: required bool userBioTruncated
3: optional i64 userBioMaxLines
4: optional FeedbackAction feedbackAction
}
struct Carousel {
1: optional FeedbackAction feedbackAction
}
union WTFPresentation {
1: UserList userBioList
2: Carousel carousel
}
struct DismissUserId {}
union FeedbackAction {
1: DismissUserId dismissUserId
}
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/client_context.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
// Caller/Client level specific context (e.g, user id/guest id/app id).
struct ClientContext {
1: optional i64 userId(personalDataType='UserId')
2: optional i64 guestId(personalDataType='GuestId')
3: optional i64 appId(personalDataType='AppId')
4: optional string ipAddress(personalDataType='IpAddress')
5: optional string userAgent(personalDataType='UserAgent')
6: optional string countryCode(personalDataType='InferredCountry')
7: optional string languageCode(personalDataType='InferredLanguage')
9: optional bool isTwoffice(personalDataType='InferredLocation')
10: optional set<string> userRoles
11: optional string deviceId(personalDataType='DeviceId')
12: optional i64 guestIdAds(personalDataType='GuestId')
13: optional i64 guestIdMarketing(personalDataType='GuestId')
}(hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/debug.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendation
// These are broken into their own union
// because we can have features that are
// complex flavors of these (such as Seq)
union PrimitiveFeatureValue {
1: i32 intValue
2: i64 longValue
3: string strValue
4: bool boolValue
}
union FeatureValue {
1: PrimitiveFeatureValue primitiveValue
}
struct DebugParams {
1: optional map<string, FeatureValue> featureOverrides
2: optional i64 randomizationSeed
3: optional bool includeDebugInfoInResults
4: optional bool doNotLog
}
enum DebugCandidateSourceIdentifier {
UTT_INTERESTS_RELATED_USERS_SOURCE = 0
UTT_PRODUCER_EXPANSION_SOURCE = 1
UTT_SEED_ACCOUNT_SOURCE = 2
BYF_USER_FOLLOW_CLUSTER_SIMS_SOURCE = 3
BYF_USER_FOLLOW_CLUSTER_SOURCE = 4
USER_FOLLOW_CLUSTER_SOURCE = 5
RECENT_SEARCH_BASED_SOURCE = 6
PEOPLE_ACTIVITY_RECENT_ENGAGEMENT_SOURCE = 7
PEOPLE_ACTIVITY_RECENT_ENGAGEMENT_SIMS_SOURCE = 8,
REVERSE_PHONE_BOOK_SOURCE = 9,
REVERSE_EMAIL_BOOK_SOURCE = 10,
SIMS_DEBUG_STORE = 11,
UTT_PRODUCER_ONLINE_MBCG_SOURCE = 12,
BONUS_FOLLOW_CONDITIONAL_ENGAGEMENT_STORE = 13,
// 14 (BONUS_FOLLOW_PMI_STORE) was deleted as it's not used anymore
FOLLOW2VEC_NEAREST_NEIGHBORS_STORE = 15,
OFFLINE_STP = 16,
OFFLINE_STP_BIG = 17,
OFFLINE_MUTUAL_FOLLOW_EXPANSION = 18,
REPEATED_PROFILE_VISITS = 19,
TIME_DECAY_FOLLOW2VEC_NEAREST_NEIGHBORS_STORE = 20,
LINEAR_REGRESSION_FOLLOW2VEC_NEAREST_NEIGHBORS_STORE = 21,
REAL_GRAPH_EXPANSION_SOURCE = 22,
RELATABLE_ACCOUNTS_BY_INTEREST = 23,
EMAIL_TWEET_CLICK = 24,
GOOD_TWEET_CLICK_ENGAGEMENTS = 25,
ENGAGED_FOLLOWER_RATIO = 26,
TWEET_SHARE_ENGAGEMENTS = 27,
BULK_FRIEND_FOLLOWS = 28,
REAL_GRAPH_OON_V2_SOURCE = 30,
CROWD_SEARCH_ACCOUNTS = 31,
POP_GEOHASH = 32,
POP_COUNTRY = 33,
POP_COUNTRY_BACKFILL = 34,
TWEET_SHARER_TO_SHARE_RECIPIENT_ENGAGEMENTS = 35,
TWEET_AUTHOR_TO_SHARE_RECIPIENT_ENGAGEMENTS = 36,
BULK_FRIEND_FOLLOWS_NEW_USER = 37,
ONLINE_STP_EPSCORER = 38,
ORGANIC_FOLLOW_ACCOUNTS = 39,
NUX_LO_HISTORY = 40,
TRAFFIC_ATTRIBUTION_ACCOUNTS = 41,
ONLINE_STP_RAW_ADDRESS_BOOK = 42,
POP_GEOHASH_QUALITY_FOLLOW = 43,
NOTIFICATION_ENGAGEMENT = 44,
EFR_BY_WORLDWIDE_PICTURE_PRODUCER = 45,
POP_GEOHASH_REAL_GRAPH = 46,
}
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/display_context.thrift | include "flows.thrift"
include "recently_engaged_user_id.thrift"
namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
struct Profile {
1: required i64 profileId(personalDataType='UserId')
}(hasPersonalData='true')
struct Search {
1: required string searchQuery(personalDataType='SearchQuery')
}(hasPersonalData='true')
struct Rux {
1: required i64 focalAuthorId(personalDataType='UserId')
}(hasPersonalData='true')
struct Topic {
1: required i64 topicId(personalDataType = 'TopicFollow')
}(hasPersonalData='true')
struct ReactiveFollow {
1: required list<i64> followedUserIds(personalDataType='UserId')
}(hasPersonalData='true')
struct NuxInterests {
1: optional flows.FlowContext flowContext // set for recommendation inside an interactive flow
2: optional list<i64> uttInterestIds // if provided, we use these interestIds for generating candidates instead of for example fetching user selected interests
}(hasPersonalData='true')
struct AdCampaignTarget {
1: required list<i64> similarToUserIds(personalDataType='UserId')
}(hasPersonalData='true')
struct ConnectTab {
1: required list<i64> byfSeedUserIds(personalDataType='UserId')
2: required list<i64> similarToUserIds(personalDataType='UserId')
3: required list<recently_engaged_user_id.RecentlyEngagedUserId> recentlyEngagedUserIds
}(hasPersonalData='true')
struct SimilarToUser {
1: required i64 similarToUserId(personalDataType='UserId')
}(hasPersonalData='true')
struct PostNuxFollowTask {
1: optional flows.FlowContext flowContext // set for recommendation inside an interactive flow
}(hasPersonalData='true')
union DisplayContext {
1: Profile profile
2: Search search
3: Rux rux
4: Topic topic
5: ReactiveFollow reactiveFollow
6: NuxInterests nuxInterests
7: AdCampaignTarget adCampaignTarget
8: ConnectTab connectTab
9: SimilarToUser similarToUser
10: PostNuxFollowTask postNuxFollowTask
}(hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/display_location.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
enum DisplayLocation {
SIDEBAR = 0
PROFILE_SIDEBAR = 2
CLUSTER_FOLLOW = 7
NEW_USER_SARUS_BACKFILL = 12
PROFILE_DEVICE_FOLLOW = 23
RECOS_BACKFILL = 32
HOME_TIMELINE = 39 # HOME_TIMELINE_WTF in Hermit
PROFILE_TOP_FOLLOWING = 42
PROFILE_TOP_FOLLOWERS = 43
PEOPLE_PLUS_PLUS = 47
EXPLORE_TAB = 57
MagicRecs = 59 # Account recommendation in notification
AB_UPLOAD_INJECTION = 60
/**
* To prevent setting 2 display locations with the same index in FRS.
*
* The display location should be added to the following files:
* - 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
*/
CAMPAIGN_FORM = 61
RUX_LANDING_PAGE = 62
PROFILE_BONUS_FOLLOW = 63
ELECTION_EXPLORE_WTF = 64
HTL_BONUS_FOLLOW = 65
TOPIC_LANDING_PAGE_HEADER = 66
NUX_PYMK = 67
NUX_INTERESTS = 68
REACTIVE_FOLLOW = 69
RUX_PYMK = 70
INDIA_COVID19_CURATED_ACCOUNTS_WTF = 71
NUX_TOPIC_BONUS_FOLLOW = 72
TWEET_NOTIFICATION_RECS = 73
HTL_SPACE_HOSTS = 74
POST_NUX_FOLLOW_TASK = 75
TOPIC_LANDING_PAGE = 76
USER_TYPEAHEAD_PREFETCH = 77
HOME_TIMELINE_RELATABLE_ACCOUNTS = 78
NUX_GEO_CATEGORY = 79
NUX_INTERESTS_CATEGORY = 80
NUX_PYMK_CATEGORY = 81
TOP_ARTICLES = 82
HOME_TIMELINE_TWEET_RECS = 83
HTL_BULK_FRIEND_FOLLOWS = 84
NUX_AUTO_FOLLOW = 85
SEARCH_BONUS_FOLLOW = 86
CONTENT_RECOMMENDER = 87
HOME_TIMELINE_REVERSE_CHRON = 88
}
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/engagementType.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
enum EngagementType {
Click = 0
Like = 1
Mention = 2
Retweet = 3
ProfileView = 4
}
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/flows.thrift | /*
* This file defines additional thrift objects that should be specified in FRS request for context of recommendation, specifically the previous recommendations / new interactions in an interactive flow (series of follow steps). These typically are sent from OCF
*/
namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
struct FlowRecommendation {
1: required i64 userId(personalDataType='UserId')
}(hasPersonalData='true')
struct RecommendationStep {
1: required list<FlowRecommendation> recommendations
2: required set<i64> followedUserIds(personalDataType='UserId')
}(hasPersonalData='true')
struct FlowContext {
1: required list<RecommendationStep> steps
}(hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/follow-recommendations-service.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
include "assembler.thrift"
include "client_context.thrift"
include "debug.thrift"
include "display_context.thrift"
include "display_location.thrift"
include "recommendations.thrift"
include "recently_engaged_user_id.thrift"
include "finatra-thrift/finatra_thrift_exceptions.thrift"
include "com/twitter/product_mixer/core/pipeline_execution_result.thrift"
struct RecommendationRequest {
1: required client_context.ClientContext clientContext
2: required display_location.DisplayLocation displayLocation
3: optional display_context.DisplayContext displayContext
// Max results to return
4: optional i32 maxResults
// Cursor to continue returning results if any
5: optional string cursor
// IDs of Content to exclude from recommendations
6: optional list<i64> excludedIds(personalDataType='UserId')
// Whether to also get promoted content
7: optional bool fetchPromotedContent
8: optional debug.DebugParams debugParams
9: optional string userLocationState(personalDataType='InferredLocation')
}(hasPersonalData='true')
struct RecommendationResponse {
1: required list<recommendations.Recommendation> recommendations
}(hasPersonalData='true')
// for scoring a list of candidates, while logging hydrated features
struct ScoringUserRequest {
1: required client_context.ClientContext clientContext
2: required display_location.DisplayLocation displayLocation
3: required list<recommendations.UserRecommendation> candidates
4: optional debug.DebugParams debugParams
}(hasPersonalData='true')
struct ScoringUserResponse {
1: required list<recommendations.UserRecommendation> candidates // empty for now
}(hasPersonalData='true')
// for getting the list of candidates generated by a single candidate source
struct DebugCandidateSourceRequest {
1: required client_context.ClientContext clientContext
2: required debug.DebugCandidateSourceIdentifier candidateSource
3: optional list<i64> uttInterestIds
4: optional debug.DebugParams debugParams
5: optional list<i64> recentlyFollowedUserIds
6: optional list<recently_engaged_user_id.RecentlyEngagedUserId> recentlyEngagedUserIds
7: optional list<i64> byfSeedUserIds
8: optional list<i64> similarToUserIds
9: required bool applySgsPredicate
10: optional i32 maxResults
}(hasPersonalData='true')
service FollowRecommendationsThriftService {
RecommendationResponse getRecommendations(1: RecommendationRequest request) throws (
1: finatra_thrift_exceptions.ServerError serverError,
2: finatra_thrift_exceptions.UnknownClientIdError unknownClientIdError,
3: finatra_thrift_exceptions.NoClientIdError noClientIdError
)
RecommendationDisplayResponse getRecommendationDisplayResponse(1: RecommendationRequest request) throws (
1: finatra_thrift_exceptions.ServerError serverError,
2: finatra_thrift_exceptions.UnknownClientIdError unknownClientIdError,
3: finatra_thrift_exceptions.NoClientIdError noClientIdError
)
// temporary endpoint for feature hydration and logging for data collection.
ScoringUserResponse scoreUserCandidates(1: ScoringUserRequest request) throws (
1: finatra_thrift_exceptions.ServerError serverError,
2: finatra_thrift_exceptions.UnknownClientIdError unknownClientIdError,
3: finatra_thrift_exceptions.NoClientIdError noClientIdError
)
// Debug endpoint for getting recommendations of a single candidate source. We can remove this endpoint when ProMix provide this functionality and we integrate with it.
RecommendationResponse debugCandidateSource(1: DebugCandidateSourceRequest request) throws (
1: finatra_thrift_exceptions.ServerError serverError,
2: finatra_thrift_exceptions.UnknownClientIdError unknownClientIdError,
3: finatra_thrift_exceptions.NoClientIdError noClientIdError
)
// Get the full execution log for a pipeline (used by our debugging tools)
pipeline_execution_result.PipelineExecutionResult executePipeline(1: RecommendationRequest request) throws (
1: finatra_thrift_exceptions.ServerError serverError,
2: finatra_thrift_exceptions.UnknownClientIdError unknownClientIdError,
3: finatra_thrift_exceptions.NoClientIdError noClientIdError
)
}
struct RecommendationDisplayResponse {
1: required list<recommendations.HydratedRecommendation> hydratedRecommendation
2: optional assembler.Header header
3: optional assembler.Footer footer
4: optional assembler.WTFPresentation wtfPresentation
}(hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/follow_recommendations_serving_history.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
// struct used for storing the history of computing and serving of recommendations to a user
struct FollowRecommendationsServingHistory {
1: required i64 lastComputationTimeMs (personalDataType = 'PrivateTimestamp')
2: required i64 lastServingTimeMs (personalDataType = 'PrivateTimestamp')
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/BUILD | create_thrift_libraries(
base_name = "thrift",
sources = ["*.thrift"],
platform = "java8",
tags = ["bazel-compatible"],
dependency_roots = [
"src/thrift/com/twitter/ads/adserver:adserver_common",
"src/thrift/com/twitter/ml/api:data",
"src/thrift/com/twitter/suggests/controller_data",
],
generate_languages = [
"java",
"scala",
"strato",
],
provides_java_name = "follow-recommendations-logging-java",
provides_scala_name = "follow-recommendations-logging-scala",
)
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/client_context.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
// Offline equal of ClientContext
struct OfflineClientContext {
1: optional i64 userId(personalDataType='UserId')
2: optional i64 guestId(personalDataType='GuestId')
3: optional i64 appId(personalDataType='AppId')
4: optional string countryCode(personalDataType='InferredCountry')
5: optional string languageCode(personalDataType='InferredLanguage')
6: optional i64 guestIdAds(personalDataType='GuestId')
7: optional i64 guestIdMarketing(personalDataType='GuestId')
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/debug.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendation.logging
// subset of DebugParams
struct OfflineDebugParams {
1: optional i64 randomizationSeed // track if the request was randomly ranked or not
}(persisted='true', hasPersonalData='false')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/display_context.thrift | include "logging/flows.thrift"
include "logging/recently_engaged_user_id.thrift"
namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
// Offline equal of Profile DisplayContext
struct OfflineProfile {
1: required i64 profileId(personalDataType='UserId')
}(persisted='true', hasPersonalData='true')
// Offline equal of Search DisplayContext
struct OfflineSearch {
1: required string searchQuery(personalDataType='SearchQuery')
}(persisted='true', hasPersonalData='true')
// Offline equal of Rux Landing Page DisplayContext
struct OfflineRux {
1: required i64 focalAuthorId(personalDataType="UserId")
}(persisted='true', hasPersonalData='true')
// Offline equal of Topic DisplayContext
struct OfflineTopic {
1: required i64 topicId(personalDataType = 'TopicFollow')
}(persisted='true', hasPersonalData='true')
struct OfflineReactiveFollow {
1: required list<i64> followedUserIds(personalDataType='UserId')
}(persisted='true', hasPersonalData='true')
struct OfflineNuxInterests {
1: optional flows.OfflineFlowContext flowContext // set for recommendation inside an interactive flow
}(persisted='true', hasPersonalData='true')
struct OfflineAdCampaignTarget {
1: required list<i64> similarToUserIds(personalDataType='UserId')
}(persisted='true', hasPersonalData='true')
struct OfflineConnectTab {
1: required list<i64> byfSeedUserIds(personalDataType='UserId')
2: required list<i64> similarToUserIds(personalDataType='UserId')
3: required list<recently_engaged_user_id.RecentlyEngagedUserId> recentlyEngagedUserIds
}(persisted='true', hasPersonalData='true')
struct OfflineSimilarToUser {
1: required i64 similarToUserId(personalDataType='UserId')
}(persisted='true', hasPersonalData='true')
struct OfflinePostNuxFollowTask {
1: optional flows.OfflineFlowContext flowContext // set for recommendation inside an interactive flow
}(persisted='true', hasPersonalData='true')
// Offline equal of DisplayContext
union OfflineDisplayContext {
1: OfflineProfile profile
2: OfflineSearch search
3: OfflineRux rux
4: OfflineTopic topic
5: OfflineReactiveFollow reactiveFollow
6: OfflineNuxInterests nuxInterests
7: OfflineAdCampaignTarget adCampaignTarget
8: OfflineConnectTab connectTab
9: OfflineSimilarToUser similarToUser
10: OfflinePostNuxFollowTask postNuxFollowTask
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/display_location.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
/**
* 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
*/
// Offline equal of DisplayLocation
enum OfflineDisplayLocation {
SIDEBAR = 0
PROFILE_SIDEBAR = 2
CLUSTER_FOLLOW = 7
NEW_USER_SARUS_BACKFILL = 12
PROFILE_DEVICE_FOLLOW = 23
RECOS_BACKFILL = 32
HOME_TIMELINE = 39
PROFILE_TOP_FOLLOWING = 42
PROFILE_TOP_FOLLOWERS = 43
PEOPLE_PLUS_PLUS = 47
EXPLORE_TAB = 57
MagicRecs = 59
AB_UPLOAD_INJECTION = 60
CAMPAIGN_FORM = 61
RUX_LANDING_PAGE = 62
PROFILE_BONUS_FOLLOW = 63
ELECTION_EXPLORE_WTF = 64
HTL_BONUS_FOLLOW = 65
TOPIC_LANDING_PAGE_HEADER = 66
NUX_PYMK = 67
NUX_INTERESTS = 68
REACTIVE_FOLLOW = 69
RUX_PYMK = 70
INDIA_COVID19_CURATED_ACCOUNTS_WTF=71
NUX_TOPIC_BONUS_FOLLOW = 72
TWEET_NOTIFICATION_RECS = 73
HTL_SPACE_HOSTS = 74
POST_NUX_FOLLOW_TASK = 75
TOPIC_LANDING_PAGE = 76
USER_TYPEAHEAD_PREFETCH = 77
HOME_TIMELINE_RELATABLE_ACCOUNTS = 78
NUX_GEO_CATEGORY = 79
NUX_INTERESTS_CATEGORY = 80
NUX_PYMK_CATEGORY = 81
TOP_ARTICLES = 82
HOME_TIMELINE_TWEET_RECS = 83
HTL_BULK_FRIEND_FOLLOWS = 84
NUX_AUTO_FOLLOW = 85
SEARCH_BONUS_FOLLOW = 86
CONTENT_RECOMMENDER = 87
HOME_TIMELINE_REVERSE_CHRON = 88
}(persisted='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/engagementType.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
enum EngagementType {
Click = 0
Like = 1
Mention = 2
Retweet = 3
ProfileView = 4
}
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/flows.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
struct OfflineFlowRecommendation {
1: required i64 userId(personalDataType='UserId')
}(persisted='true', hasPersonalData='true')
struct OfflineRecommendationStep {
1: required list<OfflineFlowRecommendation> recommendations
2: required set<i64> followedUserIds(personalDataType='UserId')
}(persisted='true', hasPersonalData='true')
struct OfflineFlowContext {
1: required list<OfflineRecommendationStep> steps
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/logs.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
include "client_context.thrift"
include "debug.thrift"
include "display_context.thrift"
include "display_location.thrift"
include "recommendations.thrift"
struct OfflineRecommendationRequest {
1: required client_context.OfflineClientContext clientContext
2: required display_location.OfflineDisplayLocation displayLocation
3: optional display_context.OfflineDisplayContext displayContext
4: optional i32 maxResults
5: optional string cursor
6: optional list<i64> excludedIds(personalDataType='UserId')
7: optional bool fetchPromotedContent
8: optional debug.OfflineDebugParams debugParams
}(persisted='true', hasPersonalData='true')
struct OfflineRecommendationResponse {
1: required list<recommendations.OfflineRecommendation> recommendations
}(persisted='true', hasPersonalData='true')
struct RecommendationLog {
1: required OfflineRecommendationRequest request
2: required OfflineRecommendationResponse response
3: required i64 timestampMs
}(persisted='true', hasPersonalData='true')
struct OfflineScoringUserRequest {
1: required client_context.OfflineClientContext clientContext
2: required display_location.OfflineDisplayLocation displayLocation
3: required list<recommendations.OfflineUserRecommendation> candidates
}(persisted='true', hasPersonalData='true')
struct OfflineScoringUserResponse {
1: required list<recommendations.OfflineUserRecommendation> candidates
}(persisted='true', hasPersonalData='true')
struct ScoredUsersLog {
1: required OfflineScoringUserRequest request
2: required OfflineScoringUserResponse response
3: required i64 timestampMs
}(persisted='true', hasPersonalData='true')
struct OfflineRecommendationFlowUserMetadata {
1: optional i32 userSignupAge(personalDataType = 'AgeOfAccount')
2: optional string userState(personalDataType = 'UserState')
}(persisted='true', hasPersonalData='true')
struct OfflineRecommendationFlowSignals {
1: optional string countryCode(personalDataType='InferredCountry')
}(persisted='true', hasPersonalData='true')
struct OfflineRecommendationFlowCandidateSourceCandidates {
1: required string candidateSourceName
2: required list<i64> candidateUserIds(personalDataType='UserId')
3: optional list<double> candidateUserScores
}(persisted='true', hasPersonalData='true')
struct RecommendationFlowLog {
1: required client_context.OfflineClientContext clientContext
2: optional OfflineRecommendationFlowUserMetadata userMetadata
3: optional OfflineRecommendationFlowSignals signals
4: required i64 timestampMs
5: required string recommendationFlowIdentifier
6: optional list<OfflineRecommendationFlowCandidateSourceCandidates> filteredCandidates
7: optional list<OfflineRecommendationFlowCandidateSourceCandidates> rankedCandidates
8: optional list<OfflineRecommendationFlowCandidateSourceCandidates> truncatedCandidates
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/reasons.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
// Proof based on Follow relationship
struct FollowProof {
1: required list<i64> userIds(personalDataType='UserId')
2: required i32 numIds(personalDataType='CountOfFollowersAndFollowees')
}(persisted='true', hasPersonalData='true')
// Similar to userIds in the context (e.g. profileId)
struct SimilarToProof {
1: required list<i64> userIds(personalDataType='UserId')
}(persisted='true', hasPersonalData='true')
// Proof based on geo location
struct PopularInGeoProof {
1: required string location(personalDataType='InferredLocation')
}(persisted='true', hasPersonalData='true')
// Proof based on ttt interest
struct TttInterestProof {
1: required i64 interestId(personalDataType='ProvidedInterests')
2: required string interestDisplayName(personalDataType='ProvidedInterests')
}(persisted='true', hasPersonalData='true')
// Proof based on topics
struct TopicProof {
1: required i64 topicId(personalDataType='ProvidedInterests')
}(persisted='true', hasPersonalData='true')
// Proof based on custom interest / search queries
struct CustomInterestProof {
1: required string customerInterest(personalDataType='SearchQuery')
}(persisted='true', hasPersonalData='true')
// Proof based on tweet authors
struct TweetsAuthorProof {
1: required list<i64> tweetIds(personalDataType='TweetId')
}(persisted='true', hasPersonalData='true')
// Proof candidate is of device follow type
struct DeviceFollowProof {
1: required bool isDeviceFollow(personalDataType='OtherDeviceInfo')
}(persisted='true', hasPersonalData='true')
// Account level proof that should be attached to each candidate
struct AccountProof {
1: optional FollowProof followProof
2: optional SimilarToProof similarToProof
3: optional PopularInGeoProof popularInGeoProof
4: optional TttInterestProof tttInterestProof
5: optional TopicProof topicProof
6: optional CustomInterestProof customInterestProof
7: optional TweetsAuthorProof tweetsAuthorProof
8: optional DeviceFollowProof deviceFollowProof
}(persisted='true', hasPersonalData='true')
struct Reason {
1: optional AccountProof accountProof
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/recently_engaged_user_id.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
include "engagementType.thrift"
struct RecentlyEngagedUserId {
1: required i64 id(personalDataType='UserId')
2: required engagementType.EngagementType engagementType
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/recommendations.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
include "com/twitter/ads/adserver/adserver_common.thrift"
include "reasons.thrift"
include "tracking.thrift"
include "scoring.thrift"
// Offline equal of UserRecommendation
struct OfflineUserRecommendation {
1: required i64 userId(personalDataType='UserId')
// reason for this suggestions, eg: social context
2: optional reasons.Reason reason
// present if it is a promoted account
3: optional adserver_common.AdImpression adImpression
// tracking token (unserialized) for attribution
4: optional tracking.TrackingToken trackingToken
// scoring details
5: optional scoring.ScoringDetails scoringDetails
}(persisted='true', hasPersonalData='true')
// Offline equal of Recommendation
union OfflineRecommendation {
1: OfflineUserRecommendation user
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/scoring.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
include "com/twitter/ml/api/data.thrift"
struct CandidateSourceDetails {
1: optional map<string, double> candidateSourceScores
2: optional i32 primarySource
}(persisted='true', hasPersonalData='false')
struct Score {
1: required double value
2: optional string rankerId
3: optional string scoreType
}(persisted='true', hasPersonalData='false') // scoring and ranking info per ranking stage
// Contains (1) the ML-based heavy ranker and score (2) scores and rankers in producer experiment framework
struct Scores {
1: required list<Score> scores
2: optional string selectedRankerId
3: required bool isInProducerScoringExperiment
}(persisted='true', hasPersonalData='false')
struct RankingInfo {
1: optional Scores scores
2: optional i32 rank
}(persisted='true', hasPersonalData='false')
// this encapsulates all information related to the ranking process from generation to scoring
struct ScoringDetails {
1: optional CandidateSourceDetails candidateSourceDetails
2: optional double score // The ML-based heavy ranker score
3: optional data.DataRecord dataRecord
4: optional list<string> rankerIds // all ranker ids, including (1) ML-based heavy ranker (2) non-ML adhoc rankers
5: optional map<string, RankingInfo> infoPerRankingStage // scoring and ranking info per ranking stage
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/logging/tracking.thrift | namespace java com.twitter.follow_recommendations.logging.thriftjava
#@namespace scala com.twitter.follow_recommendations.logging.thriftscala
#@namespace strato com.twitter.follow_recommendations.logging
include "com/twitter/suggests/controller_data/controller_data.thrift"
include "display_location.thrift"
struct TrackingToken {
// trace-id of the request
1: required i64 sessionId (personalDataType='SessionId')
2: optional display_location.OfflineDisplayLocation displayLocation
// 64-bit encoded binary attributes of our recommendation
3: optional controller_data.ControllerData controllerData
// WTF Algorithm Id (backward compatibility)
4: optional i32 algoId
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/reasons.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
// Proof based on Follow relationship
struct FollowProof {
1: required list<i64> userIds(personalDataType='UserId')
2: required i32 numIds(personalDataType='CountOfFollowersAndFollowees')
}(hasPersonalData='true')
// Similar to userIds in the context (e.g. profileId)
struct SimilarToProof {
1: required list<i64> userIds(personalDataType='UserId')
}(hasPersonalData='true')
// Proof based on geo location
struct PopularInGeoProof {
1: required string location(personalDataType='InferredLocation')
}(hasPersonalData='true')
// Proof based on ttt interest
struct TttInterestProof {
1: required i64 interestId(personalDataType='ProvidedInterests')
2: required string interestDisplayName(personalDataType='ProvidedInterests')
}(hasPersonalData='true')
// Proof based on topics
struct TopicProof {
1: required i64 topicId(personalDataType='ProvidedInterests')
}(hasPersonalData='true')
// Proof based on custom interest / search queries
struct CustomInterestProof {
1: required string query(personalDataType='SearchQuery')
}(hasPersonalData='true')
// Proof based on tweet authors
struct TweetsAuthorProof {
1: required list<i64> tweetIds(personalDataType='TweetId')
}(hasPersonalData='true')
// Proof candidate is of device follow type
struct DeviceFollowProof {
1: required bool isDeviceFollow(personalDataType='OtherDeviceInfo')
}(hasPersonalData='true')
// Account level proof that should be attached to each candidate
struct AccountProof {
1: optional FollowProof followProof
2: optional SimilarToProof similarToProof
3: optional PopularInGeoProof popularInGeoProof
4: optional TttInterestProof tttInterestProof
5: optional TopicProof topicProof
6: optional CustomInterestProof customInterestProof
7: optional TweetsAuthorProof tweetsAuthorProof
8: optional DeviceFollowProof deviceFollowProof
}(hasPersonalData='true')
struct Reason {
1: optional AccountProof accountProof
}(hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/recently_engaged_user_id.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
include "engagementType.thrift"
struct RecentlyEngagedUserId {
1: required i64 id(personalDataType='UserId')
2: required engagementType.EngagementType engagementType
}(persisted='true', hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/recommendations.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
include "com/twitter/ads/adserver/adserver_common.thrift"
include "debug.thrift"
include "reasons.thrift"
include "scoring.thrift"
struct UserRecommendation {
1: required i64 userId(personalDataType='UserId')
// reason for this suggestions, eg: social context
2: optional reasons.Reason reason
// present if it is a promoted account
3: optional adserver_common.AdImpression adImpression
// tracking token for attribution
4: optional string trackingInfo
// scoring details
5: optional scoring.ScoringDetails scoringDetails
6: optional string recommendationFlowIdentifier
// FeatureSwitch overrides for candidates:
7: optional map<string, debug.FeatureValue> featureOverrides
}(hasPersonalData='true')
union Recommendation {
1: UserRecommendation user
}(hasPersonalData='true')
struct HydratedUserRecommendation {
1: required i64 userId(personalDataType='UserId')
2: optional string socialProof
// present if it is a promoted account, used by clients for determining ad impression
3: optional adserver_common.AdImpression adImpression
// tracking token for attribution
4: optional string trackingInfo
}(hasPersonalData='true')
union HydratedRecommendation {
1: HydratedUserRecommendation hydratedUserRecommendation
}
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/scoring.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
include "com/twitter/ml/api/data.thrift"
struct CandidateSourceDetails {
1: optional map<string, double> candidateSourceScores
2: optional i32 primarySource
3: optional map<string, i32> candidateSourceRanks
}(hasPersonalData='false')
struct Score {
1: required double value
2: optional string rankerId
3: optional string scoreType
}(hasPersonalData='false')
// Contains (1) the ML-based heavy ranker and score (2) scores and rankers in producer experiment framework
struct Scores {
1: required list<Score> scores
2: optional string selectedRankerId
3: required bool isInProducerScoringExperiment
}(hasPersonalData='false')
struct RankingInfo {
1: optional Scores scores
2: optional i32 rank
}(hasPersonalData='false')
// this encapsulates all information related to the ranking process from generation to scoring
struct ScoringDetails {
1: optional CandidateSourceDetails candidateSourceDetails
2: optional double score
3: optional data.DataRecord dataRecord
4: optional list<string> rankerIds
5: optional DebugDataRecord debugDataRecord // this field is not logged as it's only used for debugging
6: optional map<string, RankingInfo> infoPerRankingStage // scoring and ranking info per ranking stage
}(hasPersonalData='true')
// exactly the same as a data record, except that we store the feature name instead of the id
struct DebugDataRecord {
1: optional set<string> binaryFeatures; // stores BINARY features
2: optional map<string, double> continuousFeatures; // stores CONTINUOUS features
3: optional map<string, i64> discreteFeatures; // stores DISCRETE features
4: optional map<string, string> stringFeatures; // stores STRING features
5: optional map<string, set<string>> sparseBinaryFeatures; // stores sparse BINARY features
6: optional map<string, map<string, double>> sparseContinuousFeatures; // sparse CONTINUOUS features
}(hasPersonalData='true')
|
the-algorithm-main/follow-recommendations-service/thrift/src/main/thrift/tracking.thrift | namespace java com.twitter.follow_recommendations.thriftjava
#@namespace scala com.twitter.follow_recommendations.thriftscala
#@namespace strato com.twitter.follow_recommendations
include "com/twitter/suggests/controller_data/controller_data.thrift"
include "display_location.thrift"
// struct used for tracking/attribution purposes in our offline pipelines
struct TrackingToken {
// trace-id of the request
1: required i64 sessionId (personalDataType='SessionId')
2: optional display_location.DisplayLocation displayLocation
// 64-bit encoded binary attributes of our recommendation
3: optional controller_data.ControllerData controllerData
// WTF Algorithm Id (backward compatibility)
4: optional i32 algoId
}(hasPersonalData='true')
|
the-algorithm-main/graph-feature-service/BUILD.bazel | alias(
name = "graph_feature_service-server",
target = ":graph_feature_service-server_lib",
)
target(
name = "graph_feature_service-server_lib",
dependencies = [
"graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server",
],
)
alias(
name = "graph_feature_service-worker",
target = ":graph_feature_service-worker_lib",
)
target(
name = "graph_feature_service-worker_lib",
dependencies = [
"graph-feature-service/src/main/scala/com/twitter/graph_feature_service/worker",
],
)
jvm_binary(
name = "server-bin",
basename = "graph_feature_service-server",
main = "com.twitter.graph_feature_service.server.Main",
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
":graph_feature_service-server",
"3rdparty/jvm/ch/qos/logback:logback-classic",
"finagle/finagle-zipkin-scribe/src/main/scala",
"loglens/loglens-logback/src/main/scala/com/twitter/loglens/logback",
"twitter-server/logback-classic/src/main/scala",
],
)
jvm_binary(
name = "worker-bin",
basename = "graph_feature_service-worker",
main = "com.twitter.graph_feature_service.worker.Main",
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
":graph_feature_service-worker",
"3rdparty/jvm/ch/qos/logback:logback-classic",
"finagle/finagle-zipkin-scribe/src/main/scala",
"loglens/loglens-logback/src/main/scala/com/twitter/loglens/logback",
"twitter-server/logback-classic/src/main/scala",
],
)
jvm_app(
name = "server-bundle",
basename = "graph_feature_service-server-dist",
binary = ":server-bin",
tags = ["bazel-compatible"],
)
jvm_app(
name = "worker-bundle",
basename = "graph_feature_service-worker-dist",
binary = ":worker-bin",
tags = ["bazel-compatible"],
)
|
the-algorithm-main/graph-feature-service/README.md | # Graph Feature Service
Graph Feature Service (GFS) is a distributed system that can provide various graph features for given pairs of users. For instance, given source user A and candidate user C, GFS can answer questions like “how many of A’s followings have favorited C”, “how many of A’s followings are following C”, and “how much C is similar to the users that A has favorited“. |
the-algorithm-main/graph-feature-service/doc/common.md | # Common thrift types
GFS uses several thrift datastructures which are common to multiple queries. They are listed below.
## EdgeType
`EdgeType` is a thrift enum which specifies which edge types to query for the graph.
```thrift
enum EdgeType {
FOLLOWING,
FOLLOWED_BY,
FAVORITE,
FAVORITED_BY,
RETWEET,
RETWEETED_BY,
REPLY,
REPLYED_BY,
MENTION,
MENTIONED_BY,
MUTUAL_FOLLOW,
SIMILAR_TO, // more edge types (like block, report, etc.) can be supported later.
RESERVED_12,
RESERVED_13,
RESERVED_14,
RESERVED_15,
RESERVED_16,
RESERVED_17,
RESERVED_18,
RESERVED_19,
RESERVED_20
}
```
For an example of how this is used, consider the `GetNeighbors` query. If we set the `edgeType` field
of the `GfsNeighborsRequest`, the response will contain all the users that the specified user follows.
If, on the other hand, we set `edgeType` to be `FollowedBy` it will return all the users who are
followed by the specified user.
## FeatureType
`FeatureType` is a thrift struct which is used in queries which require two edge types.
```thrift
struct FeatureType {
1: required EdgeType leftEdgeType // edge type from source user
2: required EdgeType rightEdgeType // edge type from candidate user
}(persisted="true")
```
## UserWithScore
The candidate generation queries return lists of candidates together with a computed score for the
relevant feature. `UserWithScore` is a thrift struct which bundles together a candidate's ID with
the score.
```thrift
struct UserWithScore {
1: required i64 userId
2: required double score
}
```
|
the-algorithm-main/graph-feature-service/doc/getintersection.md | # GetIntersection
## Request and response syntax
A `GetIntersection` call takes as input a `GfsIntersectionRequest` thrift struct.
```thrift
struct GfsIntersectionRequest {
1: required i64 userId
2: required list<i64> candidateUserIds
3: required list<FeatureType> featureTypes
}
```
The response is returned in a `GfsIntersectionResponse` thrift struct.
```thrift
struct GfsIntersectionResponse {
1: required i64 userId
2: required list<GfsIntersectionResult> results
}
struct GfsIntersectionResult {
1: required i64 candidateUserId
2: required list<IntersectionValue> intersectionValues
}
struct IntersectionValue {
1: required FeatureType featureType
2: optional i32 count
3: optional list<i64> intersectionIds
4: optional i32 leftNodeDegree
5: optional i32 rightNodeDegree
}(persisted="true")
```
## Behavior
The `GfsIntersectionResponse` contains in its `results` field a `GfsIntersectionResult` for every candidate in `candidateIds` which contains an `IntersectionValue` for every `FeatureType` in the request's `featureTypes` field.
The `IntersectionValue` contains the size of the intersection between the `leftEdgeType` edges from `userId` and the `rightEdgeType` edges from `candidateId` in the `count` field, as well as their respective degrees in the graphs in `leftNodeDegree` and `rightNodeDegree` respectively.
**Note:** the `intersectionIds` field currently only contains `Nil`.
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/common/BUILD.bazel | scala_library(
platform = "java8",
tags = [
"bazel-compatible",
"bazel-only",
],
dependencies = ["src/scala/com/twitter/storehaus_internal/util"],
)
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/common/Configs.scala | package com.twitter.graph_feature_service.common
import com.twitter.conversions.DurationOps._
import com.twitter.util.Duration
import com.twitter.util.Time
import java.nio.ByteBuffer
import scala.util.hashing.MurmurHash3
object Configs {
// NOTE: notify #recos-platform slack room, if you want to change this.
// This SHOULD be updated together with NUM_SHARDS in worker.aurora
final val NumGraphShards: Int = 40
final val TopKRealGraph: Int = 512
final val BaseHdfsPath: String = "/user/cassowary/processed/gfs/constant_db/"
// whether or not to write in_value and out_value graphs. Used in the scalding job.
final val EnableValueGraphs: Boolean = true
// whether or not to write in_key and out_key graphs. Used in the scalding job.
final val EnableKeyGraphs: Boolean = false
final val FollowOutValPath: String = "follow_out_val/"
final val FollowOutKeyPath: String = "follow_out_key/"
final val FollowInValPath: String = "follow_in_val/"
final val FollowInKeyPath: String = "follow_in_key/"
final val MutualFollowValPath: String = "mutual_follow_val/"
final val MutualFollowKeyPath: String = "mutual_follow_key/"
final val FavoriteOutValPath: String = "favorite_out_val/"
final val FavoriteInValPath: String = "favorite_in_val/"
final val FavoriteOutKeyPath: String = "favorite_out_key/"
final val FavoriteInKeyPath: String = "favorite_in_key/"
final val RetweetOutValPath: String = "retweet_out_val/"
final val RetweetInValPath: String = "retweet_in_val/"
final val RetweetOutKeyPath: String = "retweet_out_key/"
final val RetweetInKeyPath: String = "retweet_in_key/"
final val MentionOutValPath: String = "mention_out_val/"
final val MentionInValPath: String = "mention_in_val/"
final val MentionOutKeyPath: String = "mention_out_key/"
final val MentionInKeyPath: String = "mention_in_key/"
final val MemCacheTTL: Duration = 8.hours
final val RandomSeed: Int = 39582942
def getTimedHdfsShardPath(shardId: Int, path: String, time: Time): String = {
val timeStr = time.format("yyyy/MM/dd")
s"$path/$timeStr/shard_$shardId"
}
def getHdfsPath(path: String, overrideBaseHdfsPath: Option[String] = None): String = {
val basePath = overrideBaseHdfsPath.getOrElse(BaseHdfsPath)
s"$basePath$path"
}
private def hash(kArr: Array[Byte], seed: Int): Int = {
MurmurHash3.bytesHash(kArr, seed) & 0x7fffffff // keep positive
}
private def hashLong(l: Long, seed: Int): Int = {
hash(ByteBuffer.allocate(8).putLong(l).array(), seed)
}
def shardForUser(userId: Long): Int = {
hashLong(userId, RandomSeed) % NumGraphShards
}
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/BUILD.bazel | scala_library(
sources = ["**/*.scala"],
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"3rdparty/jvm/com/google/inject:guice",
"3rdparty/jvm/com/twitter/storehaus:core",
"3rdparty/jvm/javax/inject:javax.inject",
"3rdparty/jvm/net/codingwell:scala-guice",
"3rdparty/jvm/org/lz4:lz4-java",
"3rdparty/jvm/org/slf4j:slf4j-api",
"discovery-common/src/main/scala/com/twitter/discovery/common/stats",
"finagle/finagle-http/src/main/scala",
"finatra-internal/decider/src/main/scala",
"finatra-internal/mtls-thriftmux/src/main/scala",
"finatra/inject/inject-app/src/main/scala",
"finatra/inject/inject-core/src/main/scala",
"finatra/inject/inject-server/src/main/scala",
"finatra/inject/inject-thrift-client/src/main/scala",
"finatra/inject/inject-utils/src/main/scala",
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift",
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift:controller",
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift/filters",
"finatra/thrift/src/main/scala/com/twitter/finatra/thrift/routing",
"graph-feature-service/src/main/resources",
"graph-feature-service/src/main/scala/com/twitter/graph_feature_service/common",
"graph-feature-service/src/main/scala/com/twitter/graph_feature_service/util",
"graph-feature-service/src/main/thrift/com/twitter/graph_feature_service:graph_feature_service_thrift-scala",
"hermit/hermit-core/src/main/scala/com/twitter/hermit/store/common",
"servo/request/src/main/scala",
"src/scala/com/twitter/storehaus_internal/memcache",
"util/util-app/src/main/scala",
"util/util-slf4j-api/src/main/scala",
],
)
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/Main.scala | package com.twitter.graph_feature_service.server
import com.google.inject.Module
import com.twitter.finatra.decider.modules.DeciderModule
import com.twitter.finatra.mtls.thriftmux.Mtls
import com.twitter.finatra.thrift.ThriftServer
import com.twitter.finatra.thrift.filters.{
AccessLoggingFilter,
LoggingMDCFilter,
StatsFilter,
ThriftMDCFilter,
TraceIdMDCFilter
}
import com.twitter.finatra.mtls.thriftmux.modules.MtlsThriftWebFormsModule
import com.twitter.finatra.thrift.routing.ThriftRouter
import com.twitter.graph_feature_service.server.controllers.ServerController
import com.twitter.graph_feature_service.server.handlers.ServerWarmupHandler
import com.twitter.graph_feature_service.server.modules.{
GetIntersectionStoreModule,
GraphFeatureServiceWorkerClientsModule,
ServerFlagsModule
}
import com.twitter.graph_feature_service.thriftscala
import com.twitter.inject.thrift.modules.ThriftClientIdModule
object Main extends ServerMain
class ServerMain extends ThriftServer with Mtls {
override val name = "graph_feature_service-server"
override val modules: Seq[Module] = {
Seq(
ServerFlagsModule,
DeciderModule,
ThriftClientIdModule,
GraphFeatureServiceWorkerClientsModule,
GetIntersectionStoreModule,
new MtlsThriftWebFormsModule[thriftscala.Server.MethodPerEndpoint](this)
)
}
override def configureThrift(router: ThriftRouter): Unit = {
router
.filter[LoggingMDCFilter]
.filter[TraceIdMDCFilter]
.filter[ThriftMDCFilter]
.filter[AccessLoggingFilter]
.filter[StatsFilter]
.add[ServerController]
}
override protected def warmup(): Unit = {
handle[ServerWarmupHandler]()
}
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/controllers/ServerController.scala | package com.twitter.graph_feature_service.server.controllers
import com.twitter.discovery.common.stats.DiscoveryStatsFilter
import com.twitter.finagle.Service
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.finatra.thrift.Controller
import com.twitter.graph_feature_service.server.handlers.ServerGetIntersectionHandler.GetIntersectionRequest
import com.twitter.graph_feature_service.server.handlers.ServerGetIntersectionHandler
import com.twitter.graph_feature_service.thriftscala
import com.twitter.graph_feature_service.thriftscala.Server.GetIntersection
import com.twitter.graph_feature_service.thriftscala.Server.GetPresetIntersection
import com.twitter.graph_feature_service.thriftscala._
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ServerController @Inject() (
serverGetIntersectionHandler: ServerGetIntersectionHandler
)(
implicit statsReceiver: StatsReceiver)
extends Controller(thriftscala.Server) {
private val getIntersectionService: Service[GetIntersectionRequest, GfsIntersectionResponse] =
new DiscoveryStatsFilter(statsReceiver.scope("srv").scope("get_intersection"))
.andThen(Service.mk(serverGetIntersectionHandler))
val getIntersection: Service[GetIntersection.Args, GfsIntersectionResponse] = { args =>
// TODO: Disable updateCache after HTL switch to use PresetIntersection endpoint.
getIntersectionService(
GetIntersectionRequest.fromGfsIntersectionRequest(args.request, cacheable = true))
}
handle(GetIntersection) { getIntersection }
def getPresetIntersection: Service[
GetPresetIntersection.Args,
GfsIntersectionResponse
] = { args =>
// TODO: Refactor after HTL switch to PresetIntersection
val cacheable = args.request.presetFeatureTypes == PresetFeatureTypes.HtlTwoHop
getIntersectionService(
GetIntersectionRequest.fromGfsPresetIntersectionRequest(args.request, cacheable))
}
handle(GetPresetIntersection) { getPresetIntersection }
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/handlers/ServerGetIntersectionHandler.scala | package com.twitter.graph_feature_service.server.handlers
import com.twitter.finagle.stats.Stat
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.graph_feature_service.server.handlers.ServerGetIntersectionHandler.GetIntersectionRequest
import com.twitter.graph_feature_service.server.stores.FeatureTypesEncoder
import com.twitter.graph_feature_service.server.stores.GetIntersectionStore.GetIntersectionQuery
import com.twitter.graph_feature_service.thriftscala.PresetFeatureTypes
import com.twitter.graph_feature_service.thriftscala._
import com.twitter.graph_feature_service.util.FeatureTypesCalculator
import com.twitter.servo.request.RequestHandler
import com.twitter.storehaus.ReadableStore
import com.twitter.util.Future
import com.twitter.util.Memoize
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
@Singleton
class ServerGetIntersectionHandler @Inject() (
@Named("ReadThroughGetIntersectionStore")
readThroughStore: ReadableStore[GetIntersectionQuery, CachedIntersectionResult],
@Named("BypassCacheGetIntersectionStore")
readOnlyStore: ReadableStore[GetIntersectionQuery, CachedIntersectionResult]
)(
implicit statsReceiver: StatsReceiver)
extends RequestHandler[GetIntersectionRequest, GfsIntersectionResponse] {
import ServerGetIntersectionHandler._
// TODO: Track all the stats based on PresetFeatureType and update the dashboard
private val stats: StatsReceiver = statsReceiver.scope("srv").scope("get_intersection")
private val numCandidatesCount = stats.counter("total_num_candidates")
private val numCandidatesStat = stats.stat("num_candidates")
private val numFeaturesStat = stats.stat("num_features")
private val userEmptyCount = stats.counter("user_empty_count")
private val candidateEmptyRateStat = stats.stat("candidate_empty_rate")
private val candidateNumEmptyStat = stats.stat("candidate_num_empty")
private val missedRateStat = stats.stat("miss_rate")
private val numMissedStat = stats.stat("num_missed")
// Assume the order from HTL doesn't change. Only log the HTL query now.
private val featureStatMap = FeatureTypesCalculator.presetFeatureTypes.map { feature =>
val featureString = s"${feature.leftEdgeType.name}_${feature.rightEdgeType.name}"
feature -> Array(
stats.counter(s"feature_type_${featureString}_total"),
stats.counter(s"feature_type_${featureString}_count_zero"),
stats.counter(s"feature_type_${featureString}_left_zero"),
stats.counter(s"feature_type_${featureString}_right_zero")
)
}.toMap
private val sourceCandidateNumStats = Memoize[PresetFeatureTypes, Stat] { presetFeature =>
stats.stat(s"source_candidate_num_${presetFeature.name}")
}
override def apply(request: GetIntersectionRequest): Future[GfsIntersectionResponse] = {
val featureTypes = request.calculatedFeatureTypes
val numCandidates = request.candidateUserIds.length
val numFeatures = featureTypes.length
numCandidatesCount.incr(numCandidates)
numCandidatesStat.add(numCandidates)
numFeaturesStat.add(numFeatures)
sourceCandidateNumStats(request.presetFeatureTypes).add(numCandidates)
// Note: do not change the orders of features and candidates.
val candidateIds = request.candidateUserIds
if (featureTypes.isEmpty || candidateIds.isEmpty) {
Future.value(DefaultGfsIntersectionResponse)
} else {
Future
.collect {
val getIntersectionStore = if (request.cacheable) readThroughStore else readOnlyStore
getIntersectionStore.multiGet(GetIntersectionQuery.buildQueries(request))
}.map { responses =>
val results = responses.collect {
case (query, Some(result)) =>
query.candidateId -> GfsIntersectionResult(
query.candidateId,
query.calculatedFeatureTypes.zip(result.values).map {
case (featureType, value) =>
IntersectionValue(
featureType,
Some(value.count),
if (value.intersectionIds.isEmpty) None else Some(value.intersectionIds),
Some(value.leftNodeDegree),
Some(value.rightNodeDegree)
)
}
)
}
// Keep the response order same as input
val processedResults = candidateIds.map { candidateId =>
results.getOrElse(candidateId, GfsIntersectionResult(candidateId, List.empty))
}
val candidateEmptyNum =
processedResults.count(
_.intersectionValues.exists(value => isZero(value.rightNodeDegree)))
val numMissed = processedResults.count(_.intersectionValues.size != numFeatures)
if (processedResults.exists(
_.intersectionValues.forall(value => isZero(value.leftNodeDegree)))) {
userEmptyCount.incr()
}
candidateNumEmptyStat.add(candidateEmptyNum)
candidateEmptyRateStat.add(candidateEmptyNum.toFloat / numCandidates)
numMissedStat.add(numMissed)
missedRateStat.add(numMissed.toFloat / numCandidates)
processedResults.foreach { result =>
result.intersectionValues.zip(featureTypes).foreach {
case (value, featureType) =>
featureStatMap.get(featureType).foreach { statsArray =>
statsArray(TotalIndex).incr()
if (isZero(value.count)) {
statsArray(CountIndex).incr()
}
if (isZero(value.leftNodeDegree)) {
statsArray(LeftIndex).incr()
}
if (isZero(value.rightNodeDegree)) {
statsArray(RightIndex).incr()
}
}
}
}
GfsIntersectionResponse(processedResults)
}
}
}
}
private[graph_feature_service] object ServerGetIntersectionHandler {
case class GetIntersectionRequest(
userId: Long,
candidateUserIds: Seq[Long],
featureTypes: Seq[FeatureType],
presetFeatureTypes: PresetFeatureTypes,
intersectionIdLimit: Option[Int],
cacheable: Boolean) {
lazy val calculatedFeatureTypes: Seq[FeatureType] =
FeatureTypesCalculator.getFeatureTypes(presetFeatureTypes, featureTypes)
lazy val calculatedFeatureTypesString: String =
FeatureTypesEncoder(calculatedFeatureTypes)
}
object GetIntersectionRequest {
def fromGfsIntersectionRequest(
request: GfsIntersectionRequest,
cacheable: Boolean
): GetIntersectionRequest = {
GetIntersectionRequest(
request.userId,
request.candidateUserIds,
request.featureTypes,
PresetFeatureTypes.Empty,
request.intersectionIdLimit,
cacheable)
}
def fromGfsPresetIntersectionRequest(
request: GfsPresetIntersectionRequest,
cacheable: Boolean
): GetIntersectionRequest = {
GetIntersectionRequest(
request.userId,
request.candidateUserIds,
List.empty,
request.presetFeatureTypes,
request.intersectionIdLimit,
cacheable)
}
}
private val DefaultGfsIntersectionResponse = GfsIntersectionResponse()
private val TotalIndex = 0
private val CountIndex = 1
private val LeftIndex = 2
private val RightIndex = 3
def isZero(opt: Option[Int]): Boolean = {
!opt.exists(_ != 0)
}
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/handlers/ServerWarmupHandler.scala | package com.twitter.graph_feature_service.server.handlers
import com.twitter.finatra.thrift.routing.ThriftWarmup
import com.twitter.graph_feature_service.thriftscala.EdgeType.FavoritedBy
import com.twitter.graph_feature_service.thriftscala.EdgeType.FollowedBy
import com.twitter.graph_feature_service.thriftscala.EdgeType.Following
import com.twitter.graph_feature_service.thriftscala.Server.GetIntersection
import com.twitter.graph_feature_service.thriftscala.FeatureType
import com.twitter.graph_feature_service.thriftscala.GfsIntersectionRequest
import com.twitter.inject.utils.Handler
import com.twitter.scrooge.Request
import com.twitter.util.logging.Logger
import javax.inject.Inject
import javax.inject.Singleton
import scala.util.Random
@Singleton
class ServerWarmupHandler @Inject() (warmup: ThriftWarmup) extends Handler {
val logger: Logger = Logger("WarmupHandler")
// TODO: Add the testing accounts to warm-up the service.
private val testingAccounts: Array[Long] = Seq.empty.toArray
private def getRandomRequest: GfsIntersectionRequest = {
GfsIntersectionRequest(
testingAccounts(Random.nextInt(testingAccounts.length)),
testingAccounts,
Seq(FeatureType(Following, FollowedBy), FeatureType(Following, FavoritedBy))
)
}
override def handle(): Unit = {
warmup.sendRequest(
GetIntersection,
Request(
GetIntersection.Args(
getRandomRequest
)),
10
)()
logger.info("Warmup Done!")
}
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/modules/GetIntersectionStoreModule.scala | package com.twitter.graph_feature_service.server.modules
import com.google.inject.Provides
import com.twitter.bijection.scrooge.CompactScalaCodec
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.stats.StatsReceiver
import com.twitter.graph_feature_service.common.Configs._
import com.twitter.graph_feature_service.server.stores.GetIntersectionStore
import com.twitter.graph_feature_service.server.stores.GetIntersectionStore.GetIntersectionQuery
import com.twitter.graph_feature_service.thriftscala.CachedIntersectionResult
import com.twitter.hermit.store.common.ObservedMemcachedReadableStore
import com.twitter.inject.TwitterModule
import com.twitter.inject.annotations.Flag
import com.twitter.storehaus.ReadableStore
import com.twitter.storehaus_internal.memcache.MemcacheStore
import com.twitter.storehaus_internal.util.{ClientName, ZkEndPoint}
import com.twitter.util.Duration
import javax.inject.{Named, Singleton}
/**
* Initialize the MemCache based GetIntersectionStore.
* The Key of MemCache is UserId~CandidateId~FeatureTypes~IntersectionIdLimit.
*/
object GetIntersectionStoreModule extends TwitterModule {
private[this] val requestTimeout: Duration = 25.millis
private[this] val retries: Int = 0
@Provides
@Named("ReadThroughGetIntersectionStore")
@Singleton
def provideReadThroughGetIntersectionStore(
graphFeatureServiceWorkerClients: GraphFeatureServiceWorkerClients,
serviceIdentifier: ServiceIdentifier,
@Flag(ServerFlagNames.MemCacheClientName) memCacheName: String,
@Flag(ServerFlagNames.MemCachePath) memCachePath: String
)(
implicit statsReceiver: StatsReceiver
): ReadableStore[GetIntersectionQuery, CachedIntersectionResult] = {
buildMemcacheStore(
graphFeatureServiceWorkerClients,
memCacheName,
memCachePath,
serviceIdentifier)
}
@Provides
@Named("BypassCacheGetIntersectionStore")
@Singleton
def provideReadOnlyGetIntersectionStore(
graphFeatureServiceWorkerClients: GraphFeatureServiceWorkerClients,
)(
implicit statsReceiver: StatsReceiver
): ReadableStore[GetIntersectionQuery, CachedIntersectionResult] = {
// Bypass the Memcache.
GetIntersectionStore(graphFeatureServiceWorkerClients, statsReceiver)
}
private[this] def buildMemcacheStore(
graphFeatureServiceWorkerClients: GraphFeatureServiceWorkerClients,
memCacheName: String,
memCachePath: String,
serviceIdentifier: ServiceIdentifier,
)(
implicit statsReceiver: StatsReceiver
): ReadableStore[GetIntersectionQuery, CachedIntersectionResult] = {
val backingStore = GetIntersectionStore(graphFeatureServiceWorkerClients, statsReceiver)
val cacheClient = MemcacheStore.memcachedClient(
name = ClientName(memCacheName),
dest = ZkEndPoint(memCachePath),
timeout = requestTimeout,
retries = retries,
serviceIdentifier = serviceIdentifier,
statsReceiver = statsReceiver
)
ObservedMemcachedReadableStore.fromCacheClient[GetIntersectionQuery, CachedIntersectionResult](
backingStore = backingStore,
cacheClient = cacheClient,
ttl = MemCacheTTL
)(
valueInjection = LZ4Injection.compose(CompactScalaCodec(CachedIntersectionResult)),
statsReceiver = statsReceiver.scope("mem_cache"),
keyToString = { key =>
s"L~${key.userId}~${key.candidateId}~${key.featureTypesString}~${key.intersectionIdLimit}"
}
)
}
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/modules/GraphFeatureServiceWorkerClientsModule.scala | package com.twitter.graph_feature_service.server.modules
import com.google.inject.Provides
import com.twitter.conversions.DurationOps._
import com.twitter.finagle.mtls.authentication.ServiceIdentifier
import com.twitter.finagle.mtls.client.MtlsStackClient._
import com.twitter.finagle.ThriftMux
import com.twitter.finagle.service.RetryBudget
import com.twitter.graph_feature_service.thriftscala
import com.twitter.inject.TwitterModule
import com.twitter.inject.annotations.Flag
import com.twitter.util.{Await, Duration}
import javax.inject.Singleton
case class GraphFeatureServiceWorkerClients(
workers: Seq[thriftscala.Worker.MethodPerEndpoint])
object GraphFeatureServiceWorkerClientsModule extends TwitterModule {
private[this] val closeableGracePeriod: Duration = 1.second
private[this] val requestTimeout: Duration = 25.millis
@Provides
@Singleton
def provideGraphFeatureServiceWorkerClient(
@Flag(ServerFlagNames.NumWorkers) numWorkers: Int,
@Flag(ServerFlagNames.ServiceRole) serviceRole: String,
@Flag(ServerFlagNames.ServiceEnv) serviceEnv: String,
serviceIdentifier: ServiceIdentifier
): GraphFeatureServiceWorkerClients = {
val workers: Seq[thriftscala.Worker.MethodPerEndpoint] =
(0 until numWorkers).map { id =>
val dest = s"/srv#/$serviceEnv/local/$serviceRole/graph_feature_service-worker-$id"
val client = ThriftMux.client
.withRequestTimeout(requestTimeout)
.withRetryBudget(RetryBudget.Empty)
.withMutualTls(serviceIdentifier)
.build[thriftscala.Worker.MethodPerEndpoint](dest, s"worker-$id")
onExit {
val closeable = client.asClosable
Await.result(closeable.close(closeableGracePeriod), closeableGracePeriod)
}
client
}
GraphFeatureServiceWorkerClients(workers)
}
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/modules/LZ4Injection.scala | package com.twitter.graph_feature_service.server.modules
import com.twitter.bijection.Injection
import scala.util.Try
import net.jpountz.lz4.{LZ4CompressorWithLength, LZ4DecompressorWithLength, LZ4Factory}
object LZ4Injection extends Injection[Array[Byte], Array[Byte]] {
private val lz4Factory = LZ4Factory.fastestInstance()
private val fastCompressor = new LZ4CompressorWithLength(lz4Factory.fastCompressor())
private val decompressor = new LZ4DecompressorWithLength(lz4Factory.fastDecompressor())
override def apply(a: Array[Byte]): Array[Byte] = LZ4Injection.fastCompressor.compress(a)
override def invert(b: Array[Byte]): Try[Array[Byte]] = Try {
LZ4Injection.decompressor.decompress(b)
}
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/modules/ServerFlagModule.scala | package com.twitter.graph_feature_service.server.modules
import com.twitter.inject.TwitterModule
object ServerFlagNames {
final val NumWorkers = "service.num_workers"
final val ServiceRole = "service.role"
final val ServiceEnv = "service.env"
final val MemCacheClientName = "service.mem_cache_client_name"
final val MemCachePath = "service.mem_cache_path"
}
/**
* Initializes references to the flag values defined in the aurora.deploy file.
* To check what the flag values are initialized in runtime, search FlagsModule in stdout
*/
object ServerFlagsModule extends TwitterModule {
import ServerFlagNames._
flag[Int](NumWorkers, "Num of workers")
flag[String](ServiceRole, "Service Role")
flag[String](ServiceEnv, "Service Env")
flag[String](MemCacheClientName, "MemCache Client Name")
flag[String](MemCachePath, "MemCache Path")
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/stores/FeatureTypesEncoder.scala | package com.twitter.graph_feature_service.server.stores
import com.twitter.graph_feature_service.common.Configs.RandomSeed
import com.twitter.graph_feature_service.thriftscala.FeatureType
import scala.util.hashing.MurmurHash3
object FeatureTypesEncoder {
def apply(featureTypes: Seq[FeatureType]): String = {
val byteArray = featureTypes.flatMap { featureType =>
Array(featureType.leftEdgeType.getValue.toByte, featureType.rightEdgeType.getValue.toByte)
}.toArray
(MurmurHash3.bytesHash(byteArray, RandomSeed) & 0x7fffffff).toString // keep positive
}
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/server/stores/GetIntersectionStore.scala | package com.twitter.graph_feature_service.server.stores
import com.twitter.finagle.RequestTimeoutException
import com.twitter.finagle.stats.{Stat, StatsReceiver}
import com.twitter.graph_feature_service.server.handlers.ServerGetIntersectionHandler.GetIntersectionRequest
import com.twitter.graph_feature_service.server.modules.GraphFeatureServiceWorkerClients
import com.twitter.graph_feature_service.server.stores.GetIntersectionStore.GetIntersectionQuery
import com.twitter.graph_feature_service.thriftscala._
import com.twitter.inject.Logging
import com.twitter.storehaus.ReadableStore
import com.twitter.util.Future
import javax.inject.Singleton
import scala.collection.mutable.ArrayBuffer
@Singleton
case class GetIntersectionStore(
graphFeatureServiceWorkerClients: GraphFeatureServiceWorkerClients,
statsReceiver: StatsReceiver)
extends ReadableStore[GetIntersectionQuery, CachedIntersectionResult]
with Logging {
import GetIntersectionStore._
private val stats = statsReceiver.scope("get_intersection_store")
private val requestCount = stats.counter(name = "request_count")
private val aggregatorLatency = stats.stat("aggregator_latency")
private val timeOutCounter = stats.counter("worker_timeouts")
private val unknownErrorCounter = stats.counter("unknown_errors")
override def multiGet[K1 <: GetIntersectionQuery](
ks: Set[K1]
): Map[K1, Future[Option[CachedIntersectionResult]]] = {
if (ks.isEmpty) {
Map.empty
} else {
requestCount.incr()
val head = ks.head
// We assume all the GetIntersectionQuery use the same userId and featureTypes
val userId = head.userId
val featureTypes = head.featureTypes
val presetFeatureTypes = head.presetFeatureTypes
val calculatedFeatureTypes = head.calculatedFeatureTypes
val intersectionIdLimit = head.intersectionIdLimit
val request = WorkerIntersectionRequest(
userId,
ks.map(_.candidateId).toArray,
featureTypes,
presetFeatureTypes,
intersectionIdLimit
)
val resultFuture = Future
.collect(
graphFeatureServiceWorkerClients.workers.map { worker =>
worker
.getIntersection(request)
.rescue {
case _: RequestTimeoutException =>
timeOutCounter.incr()
Future.value(DefaultWorkerIntersectionResponse)
case e =>
unknownErrorCounter.incr()
logger.error("Failure to load result.", e)
Future.value(DefaultWorkerIntersectionResponse)
}
}
).map { responses =>
Stat.time(aggregatorLatency) {
gfsIntersectionResponseAggregator(
responses,
calculatedFeatureTypes,
request.candidateUserIds,
intersectionIdLimit
)
}
}
ks.map { query =>
query -> resultFuture.map(_.get(query.candidateId))
}.toMap
}
}
/**
* Function to merge GfsIntersectionResponse from workers into one result.
*/
private def gfsIntersectionResponseAggregator(
responseList: Seq[WorkerIntersectionResponse],
features: Seq[FeatureType],
candidates: Seq[Long],
intersectionIdLimit: Int
): Map[Long, CachedIntersectionResult] = {
// Map of (candidate -> features -> type -> value)
val cube = Array.fill[Int](candidates.length, features.length, 3)(0)
// Map of (candidate -> features -> intersectionIds)
val ids = Array.fill[Option[ArrayBuffer[Long]]](candidates.length, features.length)(None)
val notZero = intersectionIdLimit != 0
for {
response <- responseList
(features, candidateIndex) <- response.results.zipWithIndex
(workerValue, featureIndex) <- features.zipWithIndex
} {
cube(candidateIndex)(featureIndex)(CountIndex) += workerValue.count
cube(candidateIndex)(featureIndex)(LeftDegreeIndex) += workerValue.leftNodeDegree
cube(candidateIndex)(featureIndex)(RightDegreeIndex) += workerValue.rightNodeDegree
if (notZero && workerValue.intersectionIds.nonEmpty) {
val arrayBuffer = ids(candidateIndex)(featureIndex) match {
case Some(buffer) => buffer
case None =>
val buffer = ArrayBuffer[Long]()
ids(candidateIndex)(featureIndex) = Some(buffer)
buffer
}
val intersectionIds = workerValue.intersectionIds
// Scan the intersectionId based on the Shard. The response order is consistent.
if (arrayBuffer.size < intersectionIdLimit) {
if (intersectionIds.size > intersectionIdLimit - arrayBuffer.size) {
arrayBuffer ++= intersectionIds.slice(0, intersectionIdLimit - arrayBuffer.size)
} else {
arrayBuffer ++= intersectionIds
}
}
}
}
candidates.zipWithIndex.map {
case (candidate, candidateIndex) =>
candidate -> CachedIntersectionResult(features.indices.map { featureIndex =>
WorkerIntersectionValue(
cube(candidateIndex)(featureIndex)(CountIndex),
cube(candidateIndex)(featureIndex)(LeftDegreeIndex),
cube(candidateIndex)(featureIndex)(RightDegreeIndex),
ids(candidateIndex)(featureIndex).getOrElse(Nil)
)
})
}.toMap
}
}
object GetIntersectionStore {
private[graph_feature_service] case class GetIntersectionQuery(
userId: Long,
candidateId: Long,
featureTypes: Seq[FeatureType],
presetFeatureTypes: PresetFeatureTypes,
featureTypesString: String,
calculatedFeatureTypes: Seq[FeatureType],
intersectionIdLimit: Int)
private[graph_feature_service] object GetIntersectionQuery {
def buildQueries(request: GetIntersectionRequest): Set[GetIntersectionQuery] = {
request.candidateUserIds.toSet.map { candidateId: Long =>
GetIntersectionQuery(
request.userId,
candidateId,
request.featureTypes,
request.presetFeatureTypes,
request.calculatedFeatureTypesString,
request.calculatedFeatureTypes,
request.intersectionIdLimit.getOrElse(DefaultIntersectionIdLimit)
)
}
}
}
// Don't return the intersectionId for better performance
private val DefaultIntersectionIdLimit = 0
private val DefaultWorkerIntersectionResponse = WorkerIntersectionResponse()
private val CountIndex = 0
private val LeftDegreeIndex = 1
private val RightDegreeIndex = 2
}
|
the-algorithm-main/graph-feature-service/src/main/scala/com/twitter/graph_feature_service/util/BUILD | scala_library(
platform = "java8",
tags = ["bazel-compatible"],
dependencies = [
"graph-feature-service/src/main/thrift/com/twitter/graph_feature_service:graph_feature_service_thrift-scala",
],
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.