Repository navigation
Expand file tree
/
Copy pathInteractionGraphNegativeJob.scala
More file actions
155 lines (140 loc) · 6.45 KB
/
Copy pathInteractionGraphNegativeJob.scala
File metadata and controls
155 lines (140 loc) · 6.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
package com.twitter.interaction_graph.scio.agg_negative
import com.google.api.services.bigquery.model.TimePartitioning
import com.spotify.scio.ScioContext
import com.spotify.scio.values.SCollection
import com.twitter.algebird.mutable.PriorityQueueMonoid
import com.twitter.beam.io.dal.DAL
import com.twitter.beam.io.fs.multiformat.PathLayout
import com.twitter.beam.io.fs.multiformat.WriteOptions
import com.twitter.conversions.DurationOps._
import com.twitter.dal.client.dataset.SnapshotDALDataset
import com.twitter.interaction_graph.scio.common.ConversionUtil.hasNegativeFeatures
import com.twitter.interaction_graph.scio.common.ConversionUtil.toRealGraphEdgeFeatures
import com.twitter.interaction_graph.scio.common.FeatureGeneratorUtil.getEdgeFeature
import com.twitter.interaction_graph.scio.common.GraphUtil
import com.twitter.interaction_graph.scio.common.InteractionGraphRawInput
import com.twitter.interaction_graph.thriftscala.Edge
import com.twitter.interaction_graph.thriftscala.FeatureName
import com.twitter.scalding_internal.multiformat.format.keyval.KeyVal
import com.twitter.scio_internal.job.ScioBeamJob
import com.twitter.scrooge.ThriftStruct
import com.twitter.socialgraph.hadoop.SocialgraphUnfollowsScalaDataset
import com.twitter.tcdc.bqblaster.beam.syntax._
import com.twitter.tcdc.bqblaster.core.avro.TypedProjection
import com.twitter.tcdc.bqblaster.core.transform.RootTransform
import com.twitter.timelines.real_graph.thriftscala.RealGraphFeaturesTest
import com.twitter.timelines.real_graph.v1.thriftscala.{RealGraphFeatures => RealGraphFeaturesV1}
import com.twitter.user_session_store.thriftscala.UserSession
import flockdb_tools.datasets.flock.FlockBlocksEdgesScalaDataset
import flockdb_tools.datasets.flock.FlockMutesEdgesScalaDataset
import flockdb_tools.datasets.flock.FlockReportAsAbuseEdgesScalaDataset
import flockdb_tools.datasets.flock.FlockReportAsSpamEdgesScalaDataset
import java.time.Instant
import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO
object InteractionGraphNegativeJob extends ScioBeamJob[InteractionGraphNegativeOption] {
val maxDestinationIds = 500 // p99 is about 500
def getFeatureCounts(e: Edge): Int = e.features.size
val negativeEdgeOrdering = Ordering.by[Edge, Int](getFeatureCounts)
val negativeEdgeReverseOrdering = negativeEdgeOrdering.reverse
implicit val pqMonoid: PriorityQueueMonoid[Edge] =
new PriorityQueueMonoid[Edge](maxDestinationIds)(negativeEdgeOrdering)
override protected def configurePipeline(
sc: ScioContext,
opts: InteractionGraphNegativeOption
): Unit = {
val endTs = opts.interval.getEndMillis
// read input datasets
val blocks: SCollection[InteractionGraphRawInput] =
GraphUtil.getFlockFeatures(
readSnapshot(FlockBlocksEdgesScalaDataset, sc),
FeatureName.NumBlocks,
endTs)
val mutes: SCollection[InteractionGraphRawInput] =
GraphUtil.getFlockFeatures(
readSnapshot(FlockMutesEdgesScalaDataset, sc),
FeatureName.NumMutes,
endTs)
val abuseReports: SCollection[InteractionGraphRawInput] =
GraphUtil.getFlockFeatures(
readSnapshot(FlockReportAsAbuseEdgesScalaDataset, sc),
FeatureName.NumReportAsAbuses,
endTs)
val spamReports: SCollection[InteractionGraphRawInput] =
GraphUtil.getFlockFeatures(
readSnapshot(FlockReportAsSpamEdgesScalaDataset, sc),
FeatureName.NumReportAsSpams,
endTs)
// we only keep unfollows in the past 90 days due to the huge size of this dataset,
// and to prevent permanent "shadow-banning" in the event of accidental unfollows.
// we treat unfollows as less critical than above 4 negative signals, since it deals more with
// interest than health typically, which might change over time.
val unfollows: SCollection[InteractionGraphRawInput] =
GraphUtil
.getSocialGraphFeatures(
readSnapshot(SocialgraphUnfollowsScalaDataset, sc),
FeatureName.NumUnfollows,
endTs)
.filter(_.age < 90)
// group all features by (src, dest)
val allEdgeFeatures: SCollection[Edge] =
getEdgeFeature(SCollection.unionAll(Seq(blocks, mutes, abuseReports, spamReports, unfollows)))
val negativeFeatures: SCollection[KeyVal[Long, UserSession]] =
allEdgeFeatures
.keyBy(_.sourceId)
.topByKey(maxDestinationIds)(Ordering.by(_.features.size))
.map {
case (srcId, pqEdges) =>
val topKNeg =
pqEdges.toSeq.flatMap(toRealGraphEdgeFeatures(hasNegativeFeatures))
KeyVal(
srcId,
UserSession(
userId = Some(srcId),
realGraphFeaturesTest =
Some(RealGraphFeaturesTest.V1(RealGraphFeaturesV1(topKNeg)))))
}
// save to GCS (via DAL)
negativeFeatures.saveAsCustomOutput(
"Write Negative Edge Label",
DAL.writeVersionedKeyVal(
dataset = RealGraphNegativeFeaturesScalaDataset,
pathLayout = PathLayout.VersionedPath(opts.getOutputPath),
instant = Instant.ofEpochMilli(opts.interval.getEndMillis),
writeOption = WriteOptions(numOfShards = Some(3000))
)
)
// save to BQ
val ingestionDate = opts.getDate().value.getStart.toDate
val bqDataset = opts.getBqDataset
val bqFieldsTransform = RootTransform
.Builder()
.withPrependedFields("dateHour" -> TypedProjection.fromConstant(ingestionDate))
val timePartitioning = new TimePartitioning()
.setType("DAY").setField("dateHour").setExpirationMs(21.days.inMilliseconds)
val bqWriter = BigQueryIO
.write[Edge]
.to(s"${bqDataset}.interaction_graph_agg_negative_edge_snapshot")
.withExtendedErrorInfo()
.withTimePartitioning(timePartitioning)
.withLoadJobProjectId("twttr-recos-ml-prod")
.withThriftSupport(bqFieldsTransform.build(), AvroConverter.Legacy)
.withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED)
.withWriteDisposition(
BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE
) // we only want the latest snapshot
allEdgeFeatures
.saveAsCustomOutput(
s"Save Recommendations to BQ interaction_graph_agg_negative_edge_snapshot",
bqWriter
)
}
def readSnapshot[T <: ThriftStruct](
dataset: SnapshotDALDataset[T],
sc: ScioContext
): SCollection[T] = {
sc.customInput(
s"Reading most recent snaphost ${dataset.role.name}.${dataset.logicalName}",
DAL.readMostRecentSnapshotNoOlderThan[T](dataset, 7.days)
)
}
}